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
229,800
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/request_validator.py
RequestValidator.check_verifier
def check_verifier(self, verifier): """Checks that the verifier contains only safe characters and is no shorter than lower and no longer than upper. """ lower, upper = self.verifier_length return (set(verifier) <= self.safe_characters and lower <= len(verifier) <=...
python
def check_verifier(self, verifier): """Checks that the verifier contains only safe characters and is no shorter than lower and no longer than upper. """ lower, upper = self.verifier_length return (set(verifier) <= self.safe_characters and lower <= len(verifier) <=...
[ "def", "check_verifier", "(", "self", ",", "verifier", ")", ":", "lower", ",", "upper", "=", "self", ".", "verifier_length", "return", "(", "set", "(", "verifier", ")", "<=", "self", ".", "safe_characters", "and", "lower", "<=", "len", "(", "verifier", "...
Checks that the verifier contains only safe characters and is no shorter than lower and no longer than upper.
[ "Checks", "that", "the", "verifier", "contains", "only", "safe", "characters", "and", "is", "no", "shorter", "than", "lower", "and", "no", "longer", "than", "upper", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/request_validator.py#L190-L196
229,801
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/request_validator.py
RequestValidator.validate_timestamp_and_nonce
def validate_timestamp_and_nonce(self, client_key, timestamp, nonce, request, request_token=None, access_token=None): """Validates that the nonce has not been used before. :param client_key: The client/consumer key. :param timestamp: The ``oauth_timestamp`` ...
python
def validate_timestamp_and_nonce(self, client_key, timestamp, nonce, request, request_token=None, access_token=None): """Validates that the nonce has not been used before. :param client_key: The client/consumer key. :param timestamp: The ``oauth_timestamp`` ...
[ "def", "validate_timestamp_and_nonce", "(", "self", ",", "client_key", ",", "timestamp", ",", "nonce", ",", "request", ",", "request_token", "=", "None", ",", "access_token", "=", "None", ")", ":", "raise", "self", ".", "_subclass_must_implement", "(", "\"valida...
Validates that the nonce has not been used before. :param client_key: The client/consumer key. :param timestamp: The ``oauth_timestamp`` parameter. :param nonce: The ``oauth_nonce`` parameter. :param request_token: Request token string, if any. :param access_token: Access token ...
[ "Validates", "that", "the", "nonce", "has", "not", "been", "used", "before", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/request_validator.py#L576-L625
229,802
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/parameters.py
prepare_grant_uri
def prepare_grant_uri(uri, client_id, response_type, redirect_uri=None, scope=None, state=None, **kwargs): """Prepare the authorization grant request URI. The client constructs the request URI by adding the following parameters to the query component of the authorization endpoint URI ...
python
def prepare_grant_uri(uri, client_id, response_type, redirect_uri=None, scope=None, state=None, **kwargs): """Prepare the authorization grant request URI. The client constructs the request URI by adding the following parameters to the query component of the authorization endpoint URI ...
[ "def", "prepare_grant_uri", "(", "uri", ",", "client_id", ",", "response_type", ",", "redirect_uri", "=", "None", ",", "scope", "=", "None", ",", "state", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "is_secure_transport", "(", "uri", ")"...
Prepare the authorization grant request URI. The client constructs the request URI by adding the following parameters to the query component of the authorization endpoint URI using the ``application/x-www-form-urlencoded`` format as defined by [`W3C.REC-html401-19991224`_]: :param uri: :param ...
[ "Prepare", "the", "authorization", "grant", "request", "URI", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/parameters.py#L31-L87
229,803
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/parameters.py
prepare_token_request
def prepare_token_request(grant_type, body='', include_client_id=True, **kwargs): """Prepare the access token request. The client makes a request to the token endpoint by adding the following parameters using the ``application/x-www-form-urlencoded`` format in the HTTP request entity-body: :param ...
python
def prepare_token_request(grant_type, body='', include_client_id=True, **kwargs): """Prepare the access token request. The client makes a request to the token endpoint by adding the following parameters using the ``application/x-www-form-urlencoded`` format in the HTTP request entity-body: :param ...
[ "def", "prepare_token_request", "(", "grant_type", ",", "body", "=", "''", ",", "include_client_id", "=", "True", ",", "*", "*", "kwargs", ")", ":", "params", "=", "[", "(", "'grant_type'", ",", "grant_type", ")", "]", "if", "'scope'", "in", "kwargs", ":...
Prepare the access token request. The client makes a request to the token endpoint by adding the following parameters using the ``application/x-www-form-urlencoded`` format in the HTTP request entity-body: :param grant_type: To indicate grant type being used, i.e. "password", "a...
[ "Prepare", "the", "access", "token", "request", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/parameters.py#L90-L162
229,804
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/parameters.py
parse_authorization_code_response
def parse_authorization_code_response(uri, state=None): """Parse authorization grant response URI into a dict. If the resource owner grants the access request, the authorization server issues an authorization code and delivers it to the client by adding the following parameters to the query component o...
python
def parse_authorization_code_response(uri, state=None): """Parse authorization grant response URI into a dict. If the resource owner grants the access request, the authorization server issues an authorization code and delivers it to the client by adding the following parameters to the query component o...
[ "def", "parse_authorization_code_response", "(", "uri", ",", "state", "=", "None", ")", ":", "if", "not", "is_secure_transport", "(", "uri", ")", ":", "raise", "InsecureTransportError", "(", ")", "query", "=", "urlparse", ".", "urlparse", "(", "uri", ")", "....
Parse authorization grant response URI into a dict. If the resource owner grants the access request, the authorization server issues an authorization code and delivers it to the client by adding the following parameters to the query component of the redirection URI using the ``application/x-www-form-ur...
[ "Parse", "authorization", "grant", "response", "URI", "into", "a", "dict", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/parameters.py#L223-L273
229,805
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/parameters.py
parse_implicit_response
def parse_implicit_response(uri, state=None, scope=None): """Parse the implicit token response URI into a dict. If the resource owner grants the access request, the authorization server issues an access token and delivers it to the client by adding the following parameters to the fragment component of ...
python
def parse_implicit_response(uri, state=None, scope=None): """Parse the implicit token response URI into a dict. If the resource owner grants the access request, the authorization server issues an access token and delivers it to the client by adding the following parameters to the fragment component of ...
[ "def", "parse_implicit_response", "(", "uri", ",", "state", "=", "None", ",", "scope", "=", "None", ")", ":", "if", "not", "is_secure_transport", "(", "uri", ")", ":", "raise", "InsecureTransportError", "(", ")", "fragment", "=", "urlparse", ".", "urlparse",...
Parse the implicit token response URI into a dict. If the resource owner grants the access request, the authorization server issues an access token and delivers it to the client by adding the following parameters to the fragment component of the redirection URI using the ``application/x-www-form-urlenc...
[ "Parse", "the", "implicit", "token", "response", "URI", "into", "a", "dict", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/parameters.py#L276-L342
229,806
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/parameters.py
parse_token_response
def parse_token_response(body, scope=None): """Parse the JSON token response body into a dict. The authorization server issues an access token and optional refresh token, and constructs the response by adding the following parameters to the entity body of the HTTP response with a 200 (OK) status code: ...
python
def parse_token_response(body, scope=None): """Parse the JSON token response body into a dict. The authorization server issues an access token and optional refresh token, and constructs the response by adding the following parameters to the entity body of the HTTP response with a 200 (OK) status code: ...
[ "def", "parse_token_response", "(", "body", ",", "scope", "=", "None", ")", ":", "try", ":", "params", "=", "json", ".", "loads", "(", "body", ")", "except", "ValueError", ":", "# Fall back to URL-encoded string, to support old implementations,", "# including (at time...
Parse the JSON token response body into a dict. The authorization server issues an access token and optional refresh token, and constructs the response by adding the following parameters to the entity body of the HTTP response with a 200 (OK) status code: access_token REQUIRED. The access...
[ "Parse", "the", "JSON", "token", "response", "body", "into", "a", "dict", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/parameters.py#L345-L426
229,807
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/parameters.py
validate_token_parameters
def validate_token_parameters(params): """Ensures token precence, token type, expiration and scope in params.""" if 'error' in params: raise_from_error(params.get('error'), params) if not 'access_token' in params: raise MissingTokenError(description="Missing access token parameter.") i...
python
def validate_token_parameters(params): """Ensures token precence, token type, expiration and scope in params.""" if 'error' in params: raise_from_error(params.get('error'), params) if not 'access_token' in params: raise MissingTokenError(description="Missing access token parameter.") i...
[ "def", "validate_token_parameters", "(", "params", ")", ":", "if", "'error'", "in", "params", ":", "raise_from_error", "(", "params", ".", "get", "(", "'error'", ")", ",", "params", ")", "if", "not", "'access_token'", "in", "params", ":", "raise", "MissingTo...
Ensures token precence, token type, expiration and scope in params.
[ "Ensures", "token", "precence", "token", "type", "expiration", "and", "scope", "in", "params", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/parameters.py#L429-L455
229,808
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/clients/legacy_application.py
LegacyApplicationClient.prepare_request_body
def prepare_request_body(self, username, password, body='', scope=None, include_client_id=False, **kwargs): """Add the resource owner password and username to the request body. The client makes a request to the token endpoint by adding the following parameters using...
python
def prepare_request_body(self, username, password, body='', scope=None, include_client_id=False, **kwargs): """Add the resource owner password and username to the request body. The client makes a request to the token endpoint by adding the following parameters using...
[ "def", "prepare_request_body", "(", "self", ",", "username", ",", "password", ",", "body", "=", "''", ",", "scope", "=", "None", ",", "include_client_id", "=", "False", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'client_id'", "]", "=", "self", ...
Add the resource owner password and username to the request body. The client makes a request to the token endpoint by adding the following parameters using the "application/x-www-form-urlencoded" format per `Appendix B`_ in the HTTP request entity-body: :param username: The resource...
[ "Add", "the", "resource", "owner", "password", "and", "username", "to", "the", "request", "body", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/clients/legacy_application.py#L43-L85
229,809
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/clients/mobile_application.py
MobileApplicationClient.prepare_request_uri
def prepare_request_uri(self, uri, redirect_uri=None, scope=None, state=None, **kwargs): """Prepare the implicit grant request URI. The client constructs the request URI by adding the following parameters to the query component of the authorization endpoint URI ...
python
def prepare_request_uri(self, uri, redirect_uri=None, scope=None, state=None, **kwargs): """Prepare the implicit grant request URI. The client constructs the request URI by adding the following parameters to the query component of the authorization endpoint URI ...
[ "def", "prepare_request_uri", "(", "self", ",", "uri", ",", "redirect_uri", "=", "None", ",", "scope", "=", "None", ",", "state", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "prepare_grant_uri", "(", "uri", ",", "self", ".", "client_id", ...
Prepare the implicit grant request URI. The client constructs the request URI by adding the following parameters to the query component of the authorization endpoint URI using the "application/x-www-form-urlencoded" format, per `Appendix B`_: :param redirect_uri: OPTIONAL. The redirec...
[ "Prepare", "the", "implicit", "grant", "request", "URI", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/clients/mobile_application.py#L51-L97
229,810
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/clients/mobile_application.py
MobileApplicationClient.parse_request_uri_response
def parse_request_uri_response(self, uri, state=None, scope=None): """Parse the response URI fragment. If the resource owner grants the access request, the authorization server issues an access token and delivers it to the client by adding the following parameters to the fragment compon...
python
def parse_request_uri_response(self, uri, state=None, scope=None): """Parse the response URI fragment. If the resource owner grants the access request, the authorization server issues an access token and delivers it to the client by adding the following parameters to the fragment compon...
[ "def", "parse_request_uri_response", "(", "self", ",", "uri", ",", "state", "=", "None", ",", "scope", "=", "None", ")", ":", "self", ".", "token", "=", "parse_implicit_response", "(", "uri", ",", "state", "=", "state", ",", "scope", "=", "scope", ")", ...
Parse the response URI fragment. If the resource owner grants the access request, the authorization server issues an access token and delivers it to the client by adding the following parameters to the fragment component of the redirection URI using the "application/x-www-form-urlencode...
[ "Parse", "the", "response", "URI", "fragment", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/clients/mobile_application.py#L99-L174
229,811
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/request_validator.py
RequestValidator.confirm_redirect_uri
def confirm_redirect_uri(self, client_id, code, redirect_uri, client, request, *args, **kwargs): """Ensure that the authorization process represented by this authorization code began with this 'redirect_uri'. If the client specifies a redirect_uri when obtaining cod...
python
def confirm_redirect_uri(self, client_id, code, redirect_uri, client, request, *args, **kwargs): """Ensure that the authorization process represented by this authorization code began with this 'redirect_uri'. If the client specifies a redirect_uri when obtaining cod...
[ "def", "confirm_redirect_uri", "(", "self", ",", "client_id", ",", "code", ",", "redirect_uri", ",", "client", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "raise", "NotImplementedError", "(", "'Subclasses must implement this method.'", "...
Ensure that the authorization process represented by this authorization code began with this 'redirect_uri'. If the client specifies a redirect_uri when obtaining code then that redirect URI must be bound to the code and verified equal in this method, according to RFC 6749 section 4.1.3...
[ "Ensure", "that", "the", "authorization", "process", "represented", "by", "this", "authorization", "code", "began", "with", "this", "redirect_uri", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/request_validator.py#L89-L111
229,812
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/request_validator.py
RequestValidator.save_token
def save_token(self, token, request, *args, **kwargs): """Persist the token with a token type specific method. Currently, only save_bearer_token is supported. :param token: A (Bearer) token dict. :param request: OAuthlib request. :type request: oauthlib.common.Request "...
python
def save_token(self, token, request, *args, **kwargs): """Persist the token with a token type specific method. Currently, only save_bearer_token is supported. :param token: A (Bearer) token dict. :param request: OAuthlib request. :type request: oauthlib.common.Request "...
[ "def", "save_token", "(", "self", ",", "token", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "save_bearer_token", "(", "token", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Persist the token with a token type specific method. Currently, only save_bearer_token is supported. :param token: A (Bearer) token dict. :param request: OAuthlib request. :type request: oauthlib.common.Request
[ "Persist", "the", "token", "with", "a", "token", "type", "specific", "method", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/request_validator.py#L294-L303
229,813
oauthlib/oauthlib
oauthlib/common.py
encode_params_utf8
def encode_params_utf8(params): """Ensures that all parameters in a list of 2-element tuples are encoded to bytestrings using UTF-8 """ encoded = [] for k, v in params: encoded.append(( k.encode('utf-8') if isinstance(k, unicode_type) else k, v.encode('utf-8') if isin...
python
def encode_params_utf8(params): """Ensures that all parameters in a list of 2-element tuples are encoded to bytestrings using UTF-8 """ encoded = [] for k, v in params: encoded.append(( k.encode('utf-8') if isinstance(k, unicode_type) else k, v.encode('utf-8') if isin...
[ "def", "encode_params_utf8", "(", "params", ")", ":", "encoded", "=", "[", "]", "for", "k", ",", "v", "in", "params", ":", "encoded", ".", "append", "(", "(", "k", ".", "encode", "(", "'utf-8'", ")", "if", "isinstance", "(", "k", ",", "unicode_type",...
Ensures that all parameters in a list of 2-element tuples are encoded to bytestrings using UTF-8
[ "Ensures", "that", "all", "parameters", "in", "a", "list", "of", "2", "-", "element", "tuples", "are", "encoded", "to", "bytestrings", "using", "UTF", "-", "8" ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/common.py#L92-L101
229,814
oauthlib/oauthlib
oauthlib/common.py
decode_params_utf8
def decode_params_utf8(params): """Ensures that all parameters in a list of 2-element tuples are decoded to unicode using UTF-8. """ decoded = [] for k, v in params: decoded.append(( k.decode('utf-8') if isinstance(k, bytes) else k, v.decode('utf-8') if isinstance(v, ...
python
def decode_params_utf8(params): """Ensures that all parameters in a list of 2-element tuples are decoded to unicode using UTF-8. """ decoded = [] for k, v in params: decoded.append(( k.decode('utf-8') if isinstance(k, bytes) else k, v.decode('utf-8') if isinstance(v, ...
[ "def", "decode_params_utf8", "(", "params", ")", ":", "decoded", "=", "[", "]", "for", "k", ",", "v", "in", "params", ":", "decoded", ".", "append", "(", "(", "k", ".", "decode", "(", "'utf-8'", ")", "if", "isinstance", "(", "k", ",", "bytes", ")",...
Ensures that all parameters in a list of 2-element tuples are decoded to unicode using UTF-8.
[ "Ensures", "that", "all", "parameters", "in", "a", "list", "of", "2", "-", "element", "tuples", "are", "decoded", "to", "unicode", "using", "UTF", "-", "8", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/common.py#L104-L113
229,815
oauthlib/oauthlib
oauthlib/common.py
urldecode
def urldecode(query): """Decode a query string in x-www-form-urlencoded format into a sequence of two-element tuples. Unlike urlparse.parse_qsl(..., strict_parsing=True) urldecode will enforce correct formatting of the query string by validation. If validation fails a ValueError will be raised. url...
python
def urldecode(query): """Decode a query string in x-www-form-urlencoded format into a sequence of two-element tuples. Unlike urlparse.parse_qsl(..., strict_parsing=True) urldecode will enforce correct formatting of the query string by validation. If validation fails a ValueError will be raised. url...
[ "def", "urldecode", "(", "query", ")", ":", "# Check if query contains invalid characters", "if", "query", "and", "not", "set", "(", "query", ")", "<=", "urlencoded", ":", "error", "=", "(", "\"Error trying to decode a non urlencoded string. \"", "\"Found invalid characte...
Decode a query string in x-www-form-urlencoded format into a sequence of two-element tuples. Unlike urlparse.parse_qsl(..., strict_parsing=True) urldecode will enforce correct formatting of the query string by validation. If validation fails a ValueError will be raised. urllib.parse_qsl will only raise...
[ "Decode", "a", "query", "string", "in", "x", "-", "www", "-", "form", "-", "urlencoded", "format", "into", "a", "sequence", "of", "two", "-", "element", "tuples", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/common.py#L119-L165
229,816
oauthlib/oauthlib
oauthlib/common.py
extract_params
def extract_params(raw): """Extract parameters and return them as a list of 2-tuples. Will successfully extract parameters from urlencoded query strings, dicts, or lists of 2-tuples. Empty strings/dicts/lists will return an empty list of parameters. Any other input will result in a return value of ...
python
def extract_params(raw): """Extract parameters and return them as a list of 2-tuples. Will successfully extract parameters from urlencoded query strings, dicts, or lists of 2-tuples. Empty strings/dicts/lists will return an empty list of parameters. Any other input will result in a return value of ...
[ "def", "extract_params", "(", "raw", ")", ":", "if", "isinstance", "(", "raw", ",", "(", "bytes", ",", "unicode_type", ")", ")", ":", "try", ":", "params", "=", "urldecode", "(", "raw", ")", "except", "ValueError", ":", "params", "=", "None", "elif", ...
Extract parameters and return them as a list of 2-tuples. Will successfully extract parameters from urlencoded query strings, dicts, or lists of 2-tuples. Empty strings/dicts/lists will return an empty list of parameters. Any other input will result in a return value of None.
[ "Extract", "parameters", "and", "return", "them", "as", "a", "list", "of", "2", "-", "tuples", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/common.py#L168-L194
229,817
oauthlib/oauthlib
oauthlib/common.py
generate_token
def generate_token(length=30, chars=UNICODE_ASCII_CHARACTER_SET): """Generates a non-guessable OAuth token OAuth (1 and 2) does not specify the format of tokens except that they should be strings of random characters. Tokens should not be guessable and entropy when generating the random characters is i...
python
def generate_token(length=30, chars=UNICODE_ASCII_CHARACTER_SET): """Generates a non-guessable OAuth token OAuth (1 and 2) does not specify the format of tokens except that they should be strings of random characters. Tokens should not be guessable and entropy when generating the random characters is i...
[ "def", "generate_token", "(", "length", "=", "30", ",", "chars", "=", "UNICODE_ASCII_CHARACTER_SET", ")", ":", "rand", "=", "SystemRandom", "(", ")", "return", "''", ".", "join", "(", "rand", ".", "choice", "(", "chars", ")", "for", "x", "in", "range", ...
Generates a non-guessable OAuth token OAuth (1 and 2) does not specify the format of tokens except that they should be strings of random characters. Tokens should not be guessable and entropy when generating the random characters is important. Which is why SystemRandom is used instead of the default ra...
[ "Generates", "a", "non", "-", "guessable", "OAuth", "token" ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/common.py#L224-L233
229,818
oauthlib/oauthlib
oauthlib/common.py
add_params_to_qs
def add_params_to_qs(query, params): """Extend a query with a list of two-tuples.""" if isinstance(params, dict): params = params.items() queryparams = urlparse.parse_qsl(query, keep_blank_values=True) queryparams.extend(params) return urlencode(queryparams)
python
def add_params_to_qs(query, params): """Extend a query with a list of two-tuples.""" if isinstance(params, dict): params = params.items() queryparams = urlparse.parse_qsl(query, keep_blank_values=True) queryparams.extend(params) return urlencode(queryparams)
[ "def", "add_params_to_qs", "(", "query", ",", "params", ")", ":", "if", "isinstance", "(", "params", ",", "dict", ")", ":", "params", "=", "params", ".", "items", "(", ")", "queryparams", "=", "urlparse", ".", "parse_qsl", "(", "query", ",", "keep_blank_...
Extend a query with a list of two-tuples.
[ "Extend", "a", "query", "with", "a", "list", "of", "two", "-", "tuples", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/common.py#L269-L275
229,819
oauthlib/oauthlib
oauthlib/common.py
add_params_to_uri
def add_params_to_uri(uri, params, fragment=False): """Add a list of two-tuples to the uri query components.""" sch, net, path, par, query, fra = urlparse.urlparse(uri) if fragment: fra = add_params_to_qs(fra, params) else: query = add_params_to_qs(query, params) return urlparse.urlu...
python
def add_params_to_uri(uri, params, fragment=False): """Add a list of two-tuples to the uri query components.""" sch, net, path, par, query, fra = urlparse.urlparse(uri) if fragment: fra = add_params_to_qs(fra, params) else: query = add_params_to_qs(query, params) return urlparse.urlu...
[ "def", "add_params_to_uri", "(", "uri", ",", "params", ",", "fragment", "=", "False", ")", ":", "sch", ",", "net", ",", "path", ",", "par", ",", "query", ",", "fra", "=", "urlparse", ".", "urlparse", "(", "uri", ")", "if", "fragment", ":", "fra", "...
Add a list of two-tuples to the uri query components.
[ "Add", "a", "list", "of", "two", "-", "tuples", "to", "the", "uri", "query", "components", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/common.py#L278-L285
229,820
oauthlib/oauthlib
oauthlib/common.py
to_unicode
def to_unicode(data, encoding='UTF-8'): """Convert a number of different types of objects to unicode.""" if isinstance(data, unicode_type): return data if isinstance(data, bytes): return unicode_type(data, encoding=encoding) if hasattr(data, '__iter__'): try: dict(d...
python
def to_unicode(data, encoding='UTF-8'): """Convert a number of different types of objects to unicode.""" if isinstance(data, unicode_type): return data if isinstance(data, bytes): return unicode_type(data, encoding=encoding) if hasattr(data, '__iter__'): try: dict(d...
[ "def", "to_unicode", "(", "data", ",", "encoding", "=", "'UTF-8'", ")", ":", "if", "isinstance", "(", "data", ",", "unicode_type", ")", ":", "return", "data", "if", "isinstance", "(", "data", ",", "bytes", ")", ":", "return", "unicode_type", "(", "data",...
Convert a number of different types of objects to unicode.
[ "Convert", "a", "number", "of", "different", "types", "of", "objects", "to", "unicode", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/common.py#L306-L328
229,821
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/parameters.py
_append_params
def _append_params(oauth_params, params): """Append OAuth params to an existing set of parameters. Both params and oauth_params is must be lists of 2-tuples. Per `section 3.5.2`_ and `3.5.3`_ of the spec. .. _`section 3.5.2`: https://tools.ietf.org/html/rfc5849#section-3.5.2 .. _`3.5.3`: https://...
python
def _append_params(oauth_params, params): """Append OAuth params to an existing set of parameters. Both params and oauth_params is must be lists of 2-tuples. Per `section 3.5.2`_ and `3.5.3`_ of the spec. .. _`section 3.5.2`: https://tools.ietf.org/html/rfc5849#section-3.5.2 .. _`3.5.3`: https://...
[ "def", "_append_params", "(", "oauth_params", ",", "params", ")", ":", "merged", "=", "list", "(", "params", ")", "merged", ".", "extend", "(", "oauth_params", ")", "# The request URI / entity-body MAY include other request-specific", "# parameters, in which case, the proto...
Append OAuth params to an existing set of parameters. Both params and oauth_params is must be lists of 2-tuples. Per `section 3.5.2`_ and `3.5.3`_ of the spec. .. _`section 3.5.2`: https://tools.ietf.org/html/rfc5849#section-3.5.2 .. _`3.5.3`: https://tools.ietf.org/html/rfc5849#section-3.5.3
[ "Append", "OAuth", "params", "to", "an", "existing", "set", "of", "parameters", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/parameters.py#L94-L112
229,822
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/parameters.py
prepare_request_uri_query
def prepare_request_uri_query(oauth_params, uri): """Prepare the Request URI Query. Per `section 3.5.3`_ of the spec. .. _`section 3.5.3`: https://tools.ietf.org/html/rfc5849#section-3.5.3 """ # append OAuth params to the existing set of query components sch, net, path, par, query, fra = urlp...
python
def prepare_request_uri_query(oauth_params, uri): """Prepare the Request URI Query. Per `section 3.5.3`_ of the spec. .. _`section 3.5.3`: https://tools.ietf.org/html/rfc5849#section-3.5.3 """ # append OAuth params to the existing set of query components sch, net, path, par, query, fra = urlp...
[ "def", "prepare_request_uri_query", "(", "oauth_params", ",", "uri", ")", ":", "# append OAuth params to the existing set of query components", "sch", ",", "net", ",", "path", ",", "par", ",", "query", ",", "fra", "=", "urlparse", "(", "uri", ")", "query", "=", ...
Prepare the Request URI Query. Per `section 3.5.3`_ of the spec. .. _`section 3.5.3`: https://tools.ietf.org/html/rfc5849#section-3.5.3
[ "Prepare", "the", "Request", "URI", "Query", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/parameters.py#L127-L139
229,823
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/endpoints/request_token.py
RequestTokenEndpoint.validate_request_token_request
def validate_request_token_request(self, request): """Validate a request token request. :param request: OAuthlib request. :type request: oauthlib.common.Request :raises: OAuth1Error if the request is invalid. :returns: A tuple of 2 elements. 1. The validation r...
python
def validate_request_token_request(self, request): """Validate a request token request. :param request: OAuthlib request. :type request: oauthlib.common.Request :raises: OAuth1Error if the request is invalid. :returns: A tuple of 2 elements. 1. The validation r...
[ "def", "validate_request_token_request", "(", "self", ",", "request", ")", ":", "self", ".", "_check_transport_security", "(", "request", ")", "self", ".", "_check_mandatory_parameters", "(", "request", ")", "if", "request", ".", "realm", ":", "request", ".", "r...
Validate a request token request. :param request: OAuthlib request. :type request: oauthlib.common.Request :raises: OAuth1Error if the request is invalid. :returns: A tuple of 2 elements. 1. The validation result (True or False). 2. The request object...
[ "Validate", "a", "request", "token", "request", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/endpoints/request_token.py#L112-L211
229,824
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/endpoints/signature_only.py
SignatureOnlyEndpoint.validate_request
def validate_request(self, uri, http_method='GET', body=None, headers=None): """Validate a signed OAuth request. :param uri: The full URI of the token request. :param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc. :param body: The request body a...
python
def validate_request(self, uri, http_method='GET', body=None, headers=None): """Validate a signed OAuth request. :param uri: The full URI of the token request. :param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc. :param body: The request body a...
[ "def", "validate_request", "(", "self", ",", "uri", ",", "http_method", "=", "'GET'", ",", "body", "=", "None", ",", "headers", "=", "None", ")", ":", "try", ":", "request", "=", "self", ".", "_create_request", "(", "uri", ",", "http_method", ",", "bod...
Validate a signed OAuth request. :param uri: The full URI of the token request. :param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc. :param body: The request body as a string. :param headers: The request headers as a dict. :returns: A tuple of 2 elements. ...
[ "Validate", "a", "signed", "OAuth", "request", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/endpoints/signature_only.py#L23-L84
229,825
oauthlib/oauthlib
oauthlib/openid/connect/core/tokens.py
JWTToken.create_token
def create_token(self, request, refresh_token=False): """Create a JWT Token, using requestvalidator method.""" if callable(self.expires_in): expires_in = self.expires_in(request) else: expires_in = self.expires_in request.expires_in = expires_in return ...
python
def create_token(self, request, refresh_token=False): """Create a JWT Token, using requestvalidator method.""" if callable(self.expires_in): expires_in = self.expires_in(request) else: expires_in = self.expires_in request.expires_in = expires_in return ...
[ "def", "create_token", "(", "self", ",", "request", ",", "refresh_token", "=", "False", ")", ":", "if", "callable", "(", "self", ".", "expires_in", ")", ":", "expires_in", "=", "self", ".", "expires_in", "(", "request", ")", "else", ":", "expires_in", "=...
Create a JWT Token, using requestvalidator method.
[ "Create", "a", "JWT", "Token", "using", "requestvalidator", "method", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/openid/connect/core/tokens.py#L28-L38
229,826
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/__init__.py
Client.get_oauth_signature
def get_oauth_signature(self, request): """Get an OAuth signature to be used in signing a request To satisfy `section 3.4.1.2`_ item 2, if the request argument's headers dict attribute contains a Host item, its value will replace any netloc part of the request argument's uri attribute ...
python
def get_oauth_signature(self, request): """Get an OAuth signature to be used in signing a request To satisfy `section 3.4.1.2`_ item 2, if the request argument's headers dict attribute contains a Host item, its value will replace any netloc part of the request argument's uri attribute ...
[ "def", "get_oauth_signature", "(", "self", ",", "request", ")", ":", "if", "self", ".", "signature_method", "==", "SIGNATURE_PLAINTEXT", ":", "# fast-path", "return", "signature", ".", "sign_plaintext", "(", "self", ".", "client_secret", ",", "self", ".", "resou...
Get an OAuth signature to be used in signing a request To satisfy `section 3.4.1.2`_ item 2, if the request argument's headers dict attribute contains a Host item, its value will replace any netloc part of the request argument's uri attribute value. .. _`section 3.4.1.2`: https...
[ "Get", "an", "OAuth", "signature", "to", "be", "used", "in", "signing", "a", "request" ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/__init__.py#L112-L151
229,827
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/__init__.py
Client.get_oauth_params
def get_oauth_params(self, request): """Get the basic OAuth parameters to be used in generating a signature. """ nonce = (generate_nonce() if self.nonce is None else self.nonce) timestamp = (generate_timestamp() if self.timestamp is None else self.ti...
python
def get_oauth_params(self, request): """Get the basic OAuth parameters to be used in generating a signature. """ nonce = (generate_nonce() if self.nonce is None else self.nonce) timestamp = (generate_timestamp() if self.timestamp is None else self.ti...
[ "def", "get_oauth_params", "(", "self", ",", "request", ")", ":", "nonce", "=", "(", "generate_nonce", "(", ")", "if", "self", ".", "nonce", "is", "None", "else", "self", ".", "nonce", ")", "timestamp", "=", "(", "generate_timestamp", "(", ")", "if", "...
Get the basic OAuth parameters to be used in generating a signature.
[ "Get", "the", "basic", "OAuth", "parameters", "to", "be", "used", "in", "generating", "a", "signature", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/__init__.py#L153-L186
229,828
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/__init__.py
Client._render
def _render(self, request, formencode=False, realm=None): """Render a signed request according to signature type Returns a 3-tuple containing the request URI, headers, and body. If the formencode argument is True and the body contains parameters, it is escaped and returned as a valid f...
python
def _render(self, request, formencode=False, realm=None): """Render a signed request according to signature type Returns a 3-tuple containing the request URI, headers, and body. If the formencode argument is True and the body contains parameters, it is escaped and returned as a valid f...
[ "def", "_render", "(", "self", ",", "request", ",", "formencode", "=", "False", ",", "realm", "=", "None", ")", ":", "# TODO what if there are body params on a header-type auth?", "# TODO what if there are query params on a body-type auth?", "uri", ",", "headers", ",", "b...
Render a signed request according to signature type Returns a 3-tuple containing the request URI, headers, and body. If the formencode argument is True and the body contains parameters, it is escaped and returned as a valid formencoded string.
[ "Render", "a", "signed", "request", "according", "to", "signature", "type" ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/__init__.py#L188-L223
229,829
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/__init__.py
Client.sign
def sign(self, uri, http_method='GET', body=None, headers=None, realm=None): """Sign a request Signs an HTTP request with the specified parts. Returns a 3-tuple of the signed request's URI, headers, and body. Note that http_method is not returned as it is unaffected by the OAuth ...
python
def sign(self, uri, http_method='GET', body=None, headers=None, realm=None): """Sign a request Signs an HTTP request with the specified parts. Returns a 3-tuple of the signed request's URI, headers, and body. Note that http_method is not returned as it is unaffected by the OAuth ...
[ "def", "sign", "(", "self", ",", "uri", ",", "http_method", "=", "'GET'", ",", "body", "=", "None", ",", "headers", "=", "None", ",", "realm", "=", "None", ")", ":", "# normalize request data", "request", "=", "Request", "(", "uri", ",", "http_method", ...
Sign a request Signs an HTTP request with the specified parts. Returns a 3-tuple of the signed request's URI, headers, and body. Note that http_method is not returned as it is unaffected by the OAuth signing process. Also worth noting is that duplicate parameters will be includ...
[ "Sign", "a", "request" ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/__init__.py#L225-L327
229,830
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/endpoints/base.py
BaseEndpoint._raise_on_invalid_client
def _raise_on_invalid_client(self, request): """Raise on failed client authentication.""" if self.request_validator.client_authentication_required(request): if not self.request_validator.authenticate_client(request): log.debug('Client authentication failed, %r.', request) ...
python
def _raise_on_invalid_client(self, request): """Raise on failed client authentication.""" if self.request_validator.client_authentication_required(request): if not self.request_validator.authenticate_client(request): log.debug('Client authentication failed, %r.', request) ...
[ "def", "_raise_on_invalid_client", "(", "self", ",", "request", ")", ":", "if", "self", ".", "request_validator", ".", "client_authentication_required", "(", "request", ")", ":", "if", "not", "self", ".", "request_validator", ".", "authenticate_client", "(", "requ...
Raise on failed client authentication.
[ "Raise", "on", "failed", "client", "authentication", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/endpoints/base.py#L48-L56
229,831
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/endpoints/base.py
BaseEndpoint._raise_on_unsupported_token
def _raise_on_unsupported_token(self, request): """Raise on unsupported tokens.""" if (request.token_type_hint and request.token_type_hint in self.valid_token_types and request.token_type_hint not in self.supported_token_types): raise UnsupportedTokenTypeError(request...
python
def _raise_on_unsupported_token(self, request): """Raise on unsupported tokens.""" if (request.token_type_hint and request.token_type_hint in self.valid_token_types and request.token_type_hint not in self.supported_token_types): raise UnsupportedTokenTypeError(request...
[ "def", "_raise_on_unsupported_token", "(", "self", ",", "request", ")", ":", "if", "(", "request", ".", "token_type_hint", "and", "request", ".", "token_type_hint", "in", "self", ".", "valid_token_types", "and", "request", ".", "token_type_hint", "not", "in", "s...
Raise on unsupported tokens.
[ "Raise", "on", "unsupported", "tokens", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/endpoints/base.py#L58-L63
229,832
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/endpoints/revocation.py
RevocationEndpoint.create_revocation_response
def create_revocation_response(self, uri, http_method='POST', body=None, headers=None): """Revoke supplied access or refresh token. The authorization server responds with HTTP status code 200 if the token has been revoked sucessfully or if the client submitte...
python
def create_revocation_response(self, uri, http_method='POST', body=None, headers=None): """Revoke supplied access or refresh token. The authorization server responds with HTTP status code 200 if the token has been revoked sucessfully or if the client submitte...
[ "def", "create_revocation_response", "(", "self", ",", "uri", ",", "http_method", "=", "'POST'", ",", "body", "=", "None", ",", "headers", "=", "None", ")", ":", "resp_headers", "=", "{", "'Content-Type'", ":", "'application/json'", ",", "'Cache-Control'", ":"...
Revoke supplied access or refresh token. The authorization server responds with HTTP status code 200 if the token has been revoked sucessfully or if the client submitted an invalid token. Note: invalid tokens do not cause an error response since the client cannot handle such a...
[ "Revoke", "supplied", "access", "or", "refresh", "token", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/endpoints/revocation.py#L41-L85
229,833
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/grant_types/base.py
GrantTypeBase.prepare_authorization_response
def prepare_authorization_response(self, request, token, headers, body, status): """Place token according to response mode. Base classes can define a default response mode for their authorization response by overriding the static `default_response_mode` member. :param request: OAuthlib...
python
def prepare_authorization_response(self, request, token, headers, body, status): """Place token according to response mode. Base classes can define a default response mode for their authorization response by overriding the static `default_response_mode` member. :param request: OAuthlib...
[ "def", "prepare_authorization_response", "(", "self", ",", "request", ",", "token", ",", "headers", ",", "body", ",", "status", ")", ":", "request", ".", "response_mode", "=", "request", ".", "response_mode", "or", "self", ".", "default_response_mode", "if", "...
Place token according to response mode. Base classes can define a default response mode for their authorization response by overriding the static `default_response_mode` member. :param request: OAuthlib request. :type request: oauthlib.common.Request :param token: :para...
[ "Place", "token", "according", "to", "response", "mode", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/grant_types/base.py#L180-L220
229,834
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/tokens.py
prepare_mac_header
def prepare_mac_header(token, uri, key, http_method, nonce=None, headers=None, body=None, ext='', hash_algorithm='hmac-sha-1', issue_time=None, draft=0): "...
python
def prepare_mac_header(token, uri, key, http_method, nonce=None, headers=None, body=None, ext='', hash_algorithm='hmac-sha-1', issue_time=None, draft=0): "...
[ "def", "prepare_mac_header", "(", "token", ",", "uri", ",", "key", ",", "http_method", ",", "nonce", "=", "None", ",", "headers", "=", "None", ",", "body", "=", "None", ",", "ext", "=", "''", ",", "hash_algorithm", "=", "'hmac-sha-1'", ",", "issue_time",...
Add an `MAC Access Authentication`_ signature to headers. Unlike OAuth 1, this HMAC signature does not require inclusion of the request payload/body, neither does it use a combination of client_secret and token_secret but rather a mac_key provided together with the access token. Currently two algo...
[ "Add", "an", "MAC", "Access", "Authentication", "_", "signature", "to", "headers", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/tokens.py#L73-L179
229,835
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/tokens.py
get_token_from_header
def get_token_from_header(request): """ Helper function to extract a token from the request header. :param request: OAuthlib request. :type request: oauthlib.common.Request :return: Return the token or None if the Authorization header is malformed. """ token = None if 'Authorization' i...
python
def get_token_from_header(request): """ Helper function to extract a token from the request header. :param request: OAuthlib request. :type request: oauthlib.common.Request :return: Return the token or None if the Authorization header is malformed. """ token = None if 'Authorization' i...
[ "def", "get_token_from_header", "(", "request", ")", ":", "token", "=", "None", "if", "'Authorization'", "in", "request", ".", "headers", ":", "split_header", "=", "request", ".", "headers", ".", "get", "(", "'Authorization'", ")", ".", "split", "(", ")", ...
Helper function to extract a token from the request header. :param request: OAuthlib request. :type request: oauthlib.common.Request :return: Return the token or None if the Authorization header is malformed.
[ "Helper", "function", "to", "extract", "a", "token", "from", "the", "request", "header", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/tokens.py#L245-L262
229,836
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/tokens.py
BearerToken.create_token
def create_token(self, request, refresh_token=False, **kwargs): """ Create a BearerToken, by default without refresh token. :param request: OAuthlib request. :type request: oauthlib.common.Request :param refresh_token: """ if "save_token" in kwargs: w...
python
def create_token(self, request, refresh_token=False, **kwargs): """ Create a BearerToken, by default without refresh token. :param request: OAuthlib request. :type request: oauthlib.common.Request :param refresh_token: """ if "save_token" in kwargs: w...
[ "def", "create_token", "(", "self", ",", "request", ",", "refresh_token", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "\"save_token\"", "in", "kwargs", ":", "warnings", ".", "warn", "(", "\"`save_token` has been deprecated, it was not called internally.\"...
Create a BearerToken, by default without refresh token. :param request: OAuthlib request. :type request: oauthlib.common.Request :param refresh_token:
[ "Create", "a", "BearerToken", "by", "default", "without", "refresh", "token", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/tokens.py#L300-L340
229,837
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/utils.py
list_to_scope
def list_to_scope(scope): """Convert a list of scopes to a space separated string.""" if isinstance(scope, unicode_type) or scope is None: return scope elif isinstance(scope, (set, tuple, list)): return " ".join([unicode_type(s) for s in scope]) else: raise ValueError("Invalid sc...
python
def list_to_scope(scope): """Convert a list of scopes to a space separated string.""" if isinstance(scope, unicode_type) or scope is None: return scope elif isinstance(scope, (set, tuple, list)): return " ".join([unicode_type(s) for s in scope]) else: raise ValueError("Invalid sc...
[ "def", "list_to_scope", "(", "scope", ")", ":", "if", "isinstance", "(", "scope", ",", "unicode_type", ")", "or", "scope", "is", "None", ":", "return", "scope", "elif", "isinstance", "(", "scope", ",", "(", "set", ",", "tuple", ",", "list", ")", ")", ...
Convert a list of scopes to a space separated string.
[ "Convert", "a", "list", "of", "scopes", "to", "a", "space", "separated", "string", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/utils.py#L25-L32
229,838
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/utils.py
scope_to_list
def scope_to_list(scope): """Convert a space separated string to a list of scopes.""" if isinstance(scope, (tuple, list, set)): return [unicode_type(s) for s in scope] elif scope is None: return None else: return scope.strip().split(" ")
python
def scope_to_list(scope): """Convert a space separated string to a list of scopes.""" if isinstance(scope, (tuple, list, set)): return [unicode_type(s) for s in scope] elif scope is None: return None else: return scope.strip().split(" ")
[ "def", "scope_to_list", "(", "scope", ")", ":", "if", "isinstance", "(", "scope", ",", "(", "tuple", ",", "list", ",", "set", ")", ")", ":", "return", "[", "unicode_type", "(", "s", ")", "for", "s", "in", "scope", "]", "elif", "scope", "is", "None"...
Convert a space separated string to a list of scopes.
[ "Convert", "a", "space", "separated", "string", "to", "a", "list", "of", "scopes", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/utils.py#L35-L42
229,839
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/utils.py
host_from_uri
def host_from_uri(uri): """Extract hostname and port from URI. Will use default port for HTTP and HTTPS if none is present in the URI. """ default_ports = { 'HTTP': '80', 'HTTPS': '443', } sch, netloc, path, par, query, fra = urlparse(uri) if ':' in netloc: netloc, ...
python
def host_from_uri(uri): """Extract hostname and port from URI. Will use default port for HTTP and HTTPS if none is present in the URI. """ default_ports = { 'HTTP': '80', 'HTTPS': '443', } sch, netloc, path, par, query, fra = urlparse(uri) if ':' in netloc: netloc, ...
[ "def", "host_from_uri", "(", "uri", ")", ":", "default_ports", "=", "{", "'HTTP'", ":", "'80'", ",", "'HTTPS'", ":", "'443'", ",", "}", "sch", ",", "netloc", ",", "path", ",", "par", ",", "query", ",", "fra", "=", "urlparse", "(", "uri", ")", "if",...
Extract hostname and port from URI. Will use default port for HTTP and HTTPS if none is present in the URI.
[ "Extract", "hostname", "and", "port", "from", "URI", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/utils.py#L52-L68
229,840
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/utils.py
escape
def escape(u): """Escape a string in an OAuth-compatible fashion. TODO: verify whether this can in fact be used for OAuth 2 """ if not isinstance(u, unicode_type): raise ValueError('Only unicode objects are escapable.') return quote(u.encode('utf-8'), safe=b'~')
python
def escape(u): """Escape a string in an OAuth-compatible fashion. TODO: verify whether this can in fact be used for OAuth 2 """ if not isinstance(u, unicode_type): raise ValueError('Only unicode objects are escapable.') return quote(u.encode('utf-8'), safe=b'~')
[ "def", "escape", "(", "u", ")", ":", "if", "not", "isinstance", "(", "u", ",", "unicode_type", ")", ":", "raise", "ValueError", "(", "'Only unicode objects are escapable.'", ")", "return", "quote", "(", "u", ".", "encode", "(", "'utf-8'", ")", ",", "safe",...
Escape a string in an OAuth-compatible fashion. TODO: verify whether this can in fact be used for OAuth 2
[ "Escape", "a", "string", "in", "an", "OAuth", "-", "compatible", "fashion", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/utils.py#L71-L79
229,841
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/utils.py
generate_age
def generate_age(issue_time): """Generate a age parameter for MAC authentication draft 00.""" td = datetime.datetime.now() - issue_time age = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6) / 10 ** 6 return unicode_type(age)
python
def generate_age(issue_time): """Generate a age parameter for MAC authentication draft 00.""" td = datetime.datetime.now() - issue_time age = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6) / 10 ** 6 return unicode_type(age)
[ "def", "generate_age", "(", "issue_time", ")", ":", "td", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "-", "issue_time", "age", "=", "(", "td", ".", "microseconds", "+", "(", "td", ".", "seconds", "+", "td", ".", "days", "*", "24", "*",...
Generate a age parameter for MAC authentication draft 00.
[ "Generate", "a", "age", "parameter", "for", "MAC", "authentication", "draft", "00", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/utils.py#L82-L87
229,842
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/grant_types/implicit.py
ImplicitGrant.create_token_response
def create_token_response(self, request, token_handler): """Return token or error embedded in the URI fragment. :param request: OAuthlib request. :type request: oauthlib.common.Request :param token_handler: A token handler instance, for example of type oaut...
python
def create_token_response(self, request, token_handler): """Return token or error embedded in the URI fragment. :param request: OAuthlib request. :type request: oauthlib.common.Request :param token_handler: A token handler instance, for example of type oaut...
[ "def", "create_token_response", "(", "self", ",", "request", ",", "token_handler", ")", ":", "try", ":", "self", ".", "validate_token_request", "(", "request", ")", "# If the request fails due to a missing, invalid, or mismatching", "# redirection URI, or if the client identifi...
Return token or error embedded in the URI fragment. :param request: OAuthlib request. :type request: oauthlib.common.Request :param token_handler: A token handler instance, for example of type oauthlib.oauth2.BearerToken. If the resource owner grants the a...
[ "Return", "token", "or", "error", "embedded", "in", "the", "URI", "fragment", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/grant_types/implicit.py#L168-L256
229,843
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/grant_types/implicit.py
ImplicitGrant.validate_token_request
def validate_token_request(self, request): """Check the token request for normal and fatal errors. :param request: OAuthlib request. :type request: oauthlib.common.Request This method is very similar to validate_authorization_request in the AuthorizationCodeGrant but differ in ...
python
def validate_token_request(self, request): """Check the token request for normal and fatal errors. :param request: OAuthlib request. :type request: oauthlib.common.Request This method is very similar to validate_authorization_request in the AuthorizationCodeGrant but differ in ...
[ "def", "validate_token_request", "(", "self", ",", "request", ")", ":", "# First check for fatal errors", "# If the request fails due to a missing, invalid, or mismatching", "# redirection URI, or if the client identifier is missing or invalid,", "# the authorization server SHOULD inform the r...
Check the token request for normal and fatal errors. :param request: OAuthlib request. :type request: oauthlib.common.Request This method is very similar to validate_authorization_request in the AuthorizationCodeGrant but differ in a few subtle areas. A normal error could be a...
[ "Check", "the", "token", "request", "for", "normal", "and", "fatal", "errors", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/grant_types/implicit.py#L265-L364
229,844
oauthlib/oauthlib
oauthlib/openid/connect/core/grant_types/base.py
GrantTypeBase.validate_authorization_request
def validate_authorization_request(self, request): """Validates the OpenID Connect authorization request parameters. :returns: (list of scopes, dict of request info) """ # If request.prompt is 'none' then no login/authorization form should # be presented to the user. Instead, a ...
python
def validate_authorization_request(self, request): """Validates the OpenID Connect authorization request parameters. :returns: (list of scopes, dict of request info) """ # If request.prompt is 'none' then no login/authorization form should # be presented to the user. Instead, a ...
[ "def", "validate_authorization_request", "(", "self", ",", "request", ")", ":", "# If request.prompt is 'none' then no login/authorization form should", "# be presented to the user. Instead, a silent login/authorization", "# should be performed.", "if", "request", ".", "prompt", "==", ...
Validates the OpenID Connect authorization request parameters. :returns: (list of scopes, dict of request info)
[ "Validates", "the", "OpenID", "Connect", "authorization", "request", "parameters", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/openid/connect/core/grant_types/base.py#L27-L38
229,845
oauthlib/oauthlib
oauthlib/openid/connect/core/grant_types/base.py
GrantTypeBase.openid_authorization_validator
def openid_authorization_validator(self, request): """Perform OpenID Connect specific authorization request validation. nonce OPTIONAL. String value used to associate a Client session with an ID Token, and to mitigate replay attacks. The value is passed t...
python
def openid_authorization_validator(self, request): """Perform OpenID Connect specific authorization request validation. nonce OPTIONAL. String value used to associate a Client session with an ID Token, and to mitigate replay attacks. The value is passed t...
[ "def", "openid_authorization_validator", "(", "self", ",", "request", ")", ":", "# Treat it as normal OAuth 2 auth code request if openid is not present", "if", "not", "request", ".", "scopes", "or", "'openid'", "not", "in", "request", ".", "scopes", ":", "return", "{",...
Perform OpenID Connect specific authorization request validation. nonce OPTIONAL. String value used to associate a Client session with an ID Token, and to mitigate replay attacks. The value is passed through unmodified from the Authentication Request to ...
[ "Perform", "OpenID", "Connect", "specific", "authorization", "request", "validation", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/openid/connect/core/grant_types/base.py#L71-L248
229,846
oauthlib/oauthlib
oauthlib/openid/connect/core/grant_types/hybrid.py
HybridGrant.openid_authorization_validator
def openid_authorization_validator(self, request): """Additional validation when following the Authorization Code flow. """ request_info = super(HybridGrant, self).openid_authorization_validator(request) if not request_info: # returns immediately if OAuth2.0 return request_i...
python
def openid_authorization_validator(self, request): """Additional validation when following the Authorization Code flow. """ request_info = super(HybridGrant, self).openid_authorization_validator(request) if not request_info: # returns immediately if OAuth2.0 return request_i...
[ "def", "openid_authorization_validator", "(", "self", ",", "request", ")", ":", "request_info", "=", "super", "(", "HybridGrant", ",", "self", ")", ".", "openid_authorization_validator", "(", "request", ")", "if", "not", "request_info", ":", "# returns immediately i...
Additional validation when following the Authorization Code flow.
[ "Additional", "validation", "when", "following", "the", "Authorization", "Code", "flow", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/openid/connect/core/grant_types/hybrid.py#L39-L61
229,847
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/utils.py
filter_oauth_params
def filter_oauth_params(params): """Removes all non oauth parameters from a dict or a list of params.""" is_oauth = lambda kv: kv[0].startswith("oauth_") if isinstance(params, dict): return list(filter(is_oauth, list(params.items()))) else: return list(filter(is_oauth, params))
python
def filter_oauth_params(params): """Removes all non oauth parameters from a dict or a list of params.""" is_oauth = lambda kv: kv[0].startswith("oauth_") if isinstance(params, dict): return list(filter(is_oauth, list(params.items()))) else: return list(filter(is_oauth, params))
[ "def", "filter_oauth_params", "(", "params", ")", ":", "is_oauth", "=", "lambda", "kv", ":", "kv", "[", "0", "]", ".", "startswith", "(", "\"oauth_\"", ")", "if", "isinstance", "(", "params", ",", "dict", ")", ":", "return", "list", "(", "filter", "(",...
Removes all non oauth parameters from a dict or a list of params.
[ "Removes", "all", "non", "oauth", "parameters", "from", "a", "dict", "or", "a", "list", "of", "params", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/utils.py#L38-L44
229,848
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/utils.py
parse_authorization_header
def parse_authorization_header(authorization_header): """Parse an OAuth authorization header into a list of 2-tuples""" auth_scheme = 'OAuth '.lower() if authorization_header[:len(auth_scheme)].lower().startswith(auth_scheme): items = parse_http_list(authorization_header[len(auth_scheme):]) ...
python
def parse_authorization_header(authorization_header): """Parse an OAuth authorization header into a list of 2-tuples""" auth_scheme = 'OAuth '.lower() if authorization_header[:len(auth_scheme)].lower().startswith(auth_scheme): items = parse_http_list(authorization_header[len(auth_scheme):]) ...
[ "def", "parse_authorization_header", "(", "authorization_header", ")", ":", "auth_scheme", "=", "'OAuth '", ".", "lower", "(", ")", "if", "authorization_header", "[", ":", "len", "(", "auth_scheme", ")", "]", ".", "lower", "(", ")", ".", "startswith", "(", "...
Parse an OAuth authorization header into a list of 2-tuples
[ "Parse", "an", "OAuth", "authorization", "header", "into", "a", "list", "of", "2", "-", "tuples" ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/utils.py#L81-L90
229,849
oauthlib/oauthlib
oauthlib/openid/connect/core/grant_types/implicit.py
ImplicitGrant.openid_authorization_validator
def openid_authorization_validator(self, request): """Additional validation when following the implicit flow. """ request_info = super(ImplicitGrant, self).openid_authorization_validator(request) if not request_info: # returns immediately if OAuth2.0 return request_info ...
python
def openid_authorization_validator(self, request): """Additional validation when following the implicit flow. """ request_info = super(ImplicitGrant, self).openid_authorization_validator(request) if not request_info: # returns immediately if OAuth2.0 return request_info ...
[ "def", "openid_authorization_validator", "(", "self", ",", "request", ")", ":", "request_info", "=", "super", "(", "ImplicitGrant", ",", "self", ")", ".", "openid_authorization_validator", "(", "request", ")", "if", "not", "request_info", ":", "# returns immediately...
Additional validation when following the implicit flow.
[ "Additional", "validation", "when", "following", "the", "implicit", "flow", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/openid/connect/core/grant_types/implicit.py#L34-L52
229,850
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/endpoints/access_token.py
AccessTokenEndpoint.create_access_token
def create_access_token(self, request, credentials): """Create and save a new access token. Similar to OAuth 2, indication of granted scopes will be included as a space separated list in ``oauth_authorized_realms``. :param request: OAuthlib request. :type request: oauthlib.comm...
python
def create_access_token(self, request, credentials): """Create and save a new access token. Similar to OAuth 2, indication of granted scopes will be included as a space separated list in ``oauth_authorized_realms``. :param request: OAuthlib request. :type request: oauthlib.comm...
[ "def", "create_access_token", "(", "self", ",", "request", ",", "credentials", ")", ":", "request", ".", "realms", "=", "self", ".", "request_validator", ".", "get_realms", "(", "request", ".", "resource_owner_key", ",", "request", ")", "token", "=", "{", "'...
Create and save a new access token. Similar to OAuth 2, indication of granted scopes will be included as a space separated list in ``oauth_authorized_realms``. :param request: OAuthlib request. :type request: oauthlib.common.Request :returns: The token as an urlencoded string.
[ "Create", "and", "save", "a", "new", "access", "token", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/endpoints/access_token.py#L34-L54
229,851
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/endpoints/access_token.py
AccessTokenEndpoint.create_access_token_response
def create_access_token_response(self, uri, http_method='GET', body=None, headers=None, credentials=None): """Create an access token response, with a new request token if valid. :param uri: The full URI of the token request. :param http_method: A valid HTTP ...
python
def create_access_token_response(self, uri, http_method='GET', body=None, headers=None, credentials=None): """Create an access token response, with a new request token if valid. :param uri: The full URI of the token request. :param http_method: A valid HTTP ...
[ "def", "create_access_token_response", "(", "self", ",", "uri", ",", "http_method", "=", "'GET'", ",", "body", "=", "None", ",", "headers", "=", "None", ",", "credentials", "=", "None", ")", ":", "resp_headers", "=", "{", "'Content-Type'", ":", "'application...
Create an access token response, with a new request token if valid. :param uri: The full URI of the token request. :param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc. :param body: The request body as a string. :param headers: The request headers as a dict. :pa...
[ "Create", "an", "access", "token", "response", "with", "a", "new", "request", "token", "if", "valid", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/endpoints/access_token.py#L56-L119
229,852
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/endpoints/access_token.py
AccessTokenEndpoint.validate_access_token_request
def validate_access_token_request(self, request): """Validate an access token request. :param request: OAuthlib request. :type request: oauthlib.common.Request :raises: OAuth1Error if the request is invalid. :returns: A tuple of 2 elements. 1. The validation re...
python
def validate_access_token_request(self, request): """Validate an access token request. :param request: OAuthlib request. :type request: oauthlib.common.Request :raises: OAuth1Error if the request is invalid. :returns: A tuple of 2 elements. 1. The validation re...
[ "def", "validate_access_token_request", "(", "self", ",", "request", ")", ":", "self", ".", "_check_transport_security", "(", "request", ")", "self", ".", "_check_mandatory_parameters", "(", "request", ")", "if", "not", "request", ".", "resource_owner_key", ":", "...
Validate an access token request. :param request: OAuthlib request. :type request: oauthlib.common.Request :raises: OAuth1Error if the request is invalid. :returns: A tuple of 2 elements. 1. The validation result (True or False). 2. The request object...
[ "Validate", "an", "access", "token", "request", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/endpoints/access_token.py#L121-L217
229,853
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/endpoints/resource.py
ResourceEndpoint.verify_request
def verify_request(self, uri, http_method='GET', body=None, headers=None, scopes=None): """Validate client, code etc, return body + headers""" request = Request(uri, http_method, body, headers) request.token_type = self.find_token_type(request) request.scopes = sco...
python
def verify_request(self, uri, http_method='GET', body=None, headers=None, scopes=None): """Validate client, code etc, return body + headers""" request = Request(uri, http_method, body, headers) request.token_type = self.find_token_type(request) request.scopes = sco...
[ "def", "verify_request", "(", "self", ",", "uri", ",", "http_method", "=", "'GET'", ",", "body", "=", "None", ",", "headers", "=", "None", ",", "scopes", "=", "None", ")", ":", "request", "=", "Request", "(", "uri", ",", "http_method", ",", "body", "...
Validate client, code etc, return body + headers
[ "Validate", "client", "code", "etc", "return", "body", "+", "headers" ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/endpoints/resource.py#L65-L75
229,854
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/endpoints/resource.py
ResourceEndpoint.find_token_type
def find_token_type(self, request): """Token type identification. RFC 6749 does not provide a method for easily differentiating between different token types during protected resource access. We estimate the most likely token type (if any) by asking each known token type to give...
python
def find_token_type(self, request): """Token type identification. RFC 6749 does not provide a method for easily differentiating between different token types during protected resource access. We estimate the most likely token type (if any) by asking each known token type to give...
[ "def", "find_token_type", "(", "self", ",", "request", ")", ":", "estimates", "=", "sorted", "(", "(", "(", "t", ".", "estimate_type", "(", "request", ")", ",", "n", ")", "for", "n", ",", "t", "in", "self", ".", "tokens", ".", "items", "(", ")", ...
Token type identification. RFC 6749 does not provide a method for easily differentiating between different token types during protected resource access. We estimate the most likely token type (if any) by asking each known token type to give an estimation based on the request.
[ "Token", "type", "identification", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/endpoints/resource.py#L77-L87
229,855
beelit94/python-terraform
python_terraform/tfstate.py
Tfstate.load_file
def load_file(file_path): """ Read the tfstate file and load its contents, parses then as JSON and put the result into the object """ log.debug('read data from {0}'.format(file_path)) if os.path.exists(file_path): with open(file_path) as f: json_data =...
python
def load_file(file_path): """ Read the tfstate file and load its contents, parses then as JSON and put the result into the object """ log.debug('read data from {0}'.format(file_path)) if os.path.exists(file_path): with open(file_path) as f: json_data =...
[ "def", "load_file", "(", "file_path", ")", ":", "log", ".", "debug", "(", "'read data from {0}'", ".", "format", "(", "file_path", ")", ")", "if", "os", ".", "path", ".", "exists", "(", "file_path", ")", ":", "with", "open", "(", "file_path", ")", "as"...
Read the tfstate file and load its contents, parses then as JSON and put the result into the object
[ "Read", "the", "tfstate", "file", "and", "load", "its", "contents", "parses", "then", "as", "JSON", "and", "put", "the", "result", "into", "the", "object" ]
99950cb03c37abadb0d7e136452e43f4f17dd4e1
https://github.com/beelit94/python-terraform/blob/99950cb03c37abadb0d7e136452e43f4f17dd4e1/python_terraform/tfstate.py#L19-L34
229,856
beelit94/python-terraform
python_terraform/__init__.py
Terraform.generate_cmd_string
def generate_cmd_string(self, cmd, *args, **kwargs): """ for any generate_cmd_string doesn't written as public method of terraform examples: 1. call import command, ref to https://www.terraform.io/docs/commands/import.html --> generate_cmd_string call: te...
python
def generate_cmd_string(self, cmd, *args, **kwargs): """ for any generate_cmd_string doesn't written as public method of terraform examples: 1. call import command, ref to https://www.terraform.io/docs/commands/import.html --> generate_cmd_string call: te...
[ "def", "generate_cmd_string", "(", "self", ",", "cmd", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "cmds", "=", "cmd", ".", "split", "(", ")", "cmds", "=", "[", "self", ".", "terraform_bin_path", "]", "+", "cmds", "for", "option", ",", "va...
for any generate_cmd_string doesn't written as public method of terraform examples: 1. call import command, ref to https://www.terraform.io/docs/commands/import.html --> generate_cmd_string call: terraform import -input=true aws_instance.foo i-abcd1234 --> python...
[ "for", "any", "generate_cmd_string", "doesn", "t", "written", "as", "public", "method", "of", "terraform" ]
99950cb03c37abadb0d7e136452e43f4f17dd4e1
https://github.com/beelit94/python-terraform/blob/99950cb03c37abadb0d7e136452e43f4f17dd4e1/python_terraform/__init__.py#L181-L244
229,857
onelogin/python-saml
src/onelogin/saml2/response.py
OneLogin_Saml2_Response.get_nameid_data
def get_nameid_data(self): """ Gets the NameID Data provided by the SAML Response from the IdP :returns: Name ID Data (Value, Format, NameQualifier, SPNameQualifier) :rtype: dict """ nameid = None nameid_data = {} encrypted_id_data_nodes = self.__query_a...
python
def get_nameid_data(self): """ Gets the NameID Data provided by the SAML Response from the IdP :returns: Name ID Data (Value, Format, NameQualifier, SPNameQualifier) :rtype: dict """ nameid = None nameid_data = {} encrypted_id_data_nodes = self.__query_a...
[ "def", "get_nameid_data", "(", "self", ")", ":", "nameid", "=", "None", "nameid_data", "=", "{", "}", "encrypted_id_data_nodes", "=", "self", ".", "__query_assertion", "(", "'/saml:Subject/saml:EncryptedID/xenc:EncryptedData'", ")", "if", "encrypted_id_data_nodes", ":",...
Gets the NameID Data provided by the SAML Response from the IdP :returns: Name ID Data (Value, Format, NameQualifier, SPNameQualifier) :rtype: dict
[ "Gets", "the", "NameID", "Data", "provided", "by", "the", "SAML", "Response", "from", "the", "IdP" ]
9fe7a72da5b4caa1529c1640b52d2649447ce49b
https://github.com/onelogin/python-saml/blob/9fe7a72da5b4caa1529c1640b52d2649447ce49b/src/onelogin/saml2/response.py#L438-L487
229,858
onelogin/python-saml
src/onelogin/saml2/response.py
OneLogin_Saml2_Response.validate_signed_elements
def validate_signed_elements(self, signed_elements): """ Verifies that the document has the expected signed nodes. :param signed_elements: The signed elements to be checked :type signed_elements: list :param raise_exceptions: Whether to return false on failure or raise an excep...
python
def validate_signed_elements(self, signed_elements): """ Verifies that the document has the expected signed nodes. :param signed_elements: The signed elements to be checked :type signed_elements: list :param raise_exceptions: Whether to return false on failure or raise an excep...
[ "def", "validate_signed_elements", "(", "self", ",", "signed_elements", ")", ":", "if", "len", "(", "signed_elements", ")", ">", "2", ":", "return", "False", "response_tag", "=", "'{%s}Response'", "%", "OneLogin_Saml2_Constants", ".", "NS_SAMLP", "assertion_tag", ...
Verifies that the document has the expected signed nodes. :param signed_elements: The signed elements to be checked :type signed_elements: list :param raise_exceptions: Whether to return false on failure or raise an exception :type raise_exceptions: Boolean
[ "Verifies", "that", "the", "document", "has", "the", "expected", "signed", "nodes", "." ]
9fe7a72da5b4caa1529c1640b52d2649447ce49b
https://github.com/onelogin/python-saml/blob/9fe7a72da5b4caa1529c1640b52d2649447ce49b/src/onelogin/saml2/response.py#L677-L716
229,859
onelogin/python-saml
src/onelogin/saml2/response.py
OneLogin_Saml2_Response.__decrypt_assertion
def __decrypt_assertion(self, dom): """ Decrypts the Assertion :raises: Exception if no private key available :param dom: Encrypted Assertion :type dom: Element :returns: Decrypted Assertion :rtype: Element """ key = self.__settings.get_sp_key()...
python
def __decrypt_assertion(self, dom): """ Decrypts the Assertion :raises: Exception if no private key available :param dom: Encrypted Assertion :type dom: Element :returns: Decrypted Assertion :rtype: Element """ key = self.__settings.get_sp_key()...
[ "def", "__decrypt_assertion", "(", "self", ",", "dom", ")", ":", "key", "=", "self", ".", "__settings", ".", "get_sp_key", "(", ")", "debug", "=", "self", ".", "__settings", ".", "is_debug_active", "(", ")", "if", "not", "key", ":", "raise", "OneLogin_Sa...
Decrypts the Assertion :raises: Exception if no private key available :param dom: Encrypted Assertion :type dom: Element :returns: Decrypted Assertion :rtype: Element
[ "Decrypts", "the", "Assertion" ]
9fe7a72da5b4caa1529c1640b52d2649447ce49b
https://github.com/onelogin/python-saml/blob/9fe7a72da5b4caa1529c1640b52d2649447ce49b/src/onelogin/saml2/response.py#L799-L856
229,860
onelogin/python-saml
src/onelogin/saml2/idp_metadata_parser.py
OneLogin_Saml2_IdPMetadataParser.get_metadata
def get_metadata(url, validate_cert=True): """ Gets the metadata XML from the provided URL :param url: Url where the XML of the Identity Provider Metadata is published. :type url: string :param validate_cert: If the url uses https schema, that flag enables or not the verificati...
python
def get_metadata(url, validate_cert=True): """ Gets the metadata XML from the provided URL :param url: Url where the XML of the Identity Provider Metadata is published. :type url: string :param validate_cert: If the url uses https schema, that flag enables or not the verificati...
[ "def", "get_metadata", "(", "url", ",", "validate_cert", "=", "True", ")", ":", "valid", "=", "False", "if", "validate_cert", ":", "response", "=", "urllib2", ".", "urlopen", "(", "url", ")", "else", ":", "ctx", "=", "ssl", ".", "create_default_context", ...
Gets the metadata XML from the provided URL :param url: Url where the XML of the Identity Provider Metadata is published. :type url: string :param validate_cert: If the url uses https schema, that flag enables or not the verification of the associated certificate. :type validate_cert: ...
[ "Gets", "the", "metadata", "XML", "from", "the", "provided", "URL" ]
9fe7a72da5b4caa1529c1640b52d2649447ce49b
https://github.com/onelogin/python-saml/blob/9fe7a72da5b4caa1529c1640b52d2649447ce49b/src/onelogin/saml2/idp_metadata_parser.py#L28-L63
229,861
onelogin/python-saml
src/onelogin/saml2/utils.py
print_xmlsec_errors
def print_xmlsec_errors(filename, line, func, error_object, error_subject, reason, msg): """ Auxiliary method. It overrides the default xmlsec debug message. """ info = [] if error_object != "unknown": info.append("obj=" + error_object) if error_subject != "unknown": info.append...
python
def print_xmlsec_errors(filename, line, func, error_object, error_subject, reason, msg): """ Auxiliary method. It overrides the default xmlsec debug message. """ info = [] if error_object != "unknown": info.append("obj=" + error_object) if error_subject != "unknown": info.append...
[ "def", "print_xmlsec_errors", "(", "filename", ",", "line", ",", "func", ",", "error_object", ",", "error_subject", ",", "reason", ",", "msg", ")", ":", "info", "=", "[", "]", "if", "error_object", "!=", "\"unknown\"", ":", "info", ".", "append", "(", "\...
Auxiliary method. It overrides the default xmlsec debug message.
[ "Auxiliary", "method", ".", "It", "overrides", "the", "default", "xmlsec", "debug", "message", "." ]
9fe7a72da5b4caa1529c1640b52d2649447ce49b
https://github.com/onelogin/python-saml/blob/9fe7a72da5b4caa1529c1640b52d2649447ce49b/src/onelogin/saml2/utils.py#L63-L78
229,862
onelogin/python-saml
src/onelogin/saml2/utils.py
OneLogin_Saml2_Utils.get_self_host
def get_self_host(request_data): """ Returns the current host. :param request_data: The request as a dict :type: dict :return: The current host :rtype: string """ if 'http_host' in request_data: current_host = request_data['http_host'] ...
python
def get_self_host(request_data): """ Returns the current host. :param request_data: The request as a dict :type: dict :return: The current host :rtype: string """ if 'http_host' in request_data: current_host = request_data['http_host'] ...
[ "def", "get_self_host", "(", "request_data", ")", ":", "if", "'http_host'", "in", "request_data", ":", "current_host", "=", "request_data", "[", "'http_host'", "]", "elif", "'server_name'", "in", "request_data", ":", "current_host", "=", "request_data", "[", "'ser...
Returns the current host. :param request_data: The request as a dict :type: dict :return: The current host :rtype: string
[ "Returns", "the", "current", "host", "." ]
9fe7a72da5b4caa1529c1640b52d2649447ce49b
https://github.com/onelogin/python-saml/blob/9fe7a72da5b4caa1529c1640b52d2649447ce49b/src/onelogin/saml2/utils.py#L315-L341
229,863
onelogin/python-saml
src/onelogin/saml2/utils.py
OneLogin_Saml2_Utils.parse_duration
def parse_duration(duration, timestamp=None): """ Interprets a ISO8601 duration value relative to a given timestamp. :param duration: The duration, as a string. :type: string :param timestamp: The unix timestamp we should apply the duration to. Optiona...
python
def parse_duration(duration, timestamp=None): """ Interprets a ISO8601 duration value relative to a given timestamp. :param duration: The duration, as a string. :type: string :param timestamp: The unix timestamp we should apply the duration to. Optiona...
[ "def", "parse_duration", "(", "duration", ",", "timestamp", "=", "None", ")", ":", "assert", "isinstance", "(", "duration", ",", "basestring", ")", "assert", "timestamp", "is", "None", "or", "isinstance", "(", "timestamp", ",", "int", ")", "timedelta", "=", ...
Interprets a ISO8601 duration value relative to a given timestamp. :param duration: The duration, as a string. :type: string :param timestamp: The unix timestamp we should apply the duration to. Optional, default to the current time. :type: string :re...
[ "Interprets", "a", "ISO8601", "duration", "value", "relative", "to", "a", "given", "timestamp", "." ]
9fe7a72da5b4caa1529c1640b52d2649447ce49b
https://github.com/onelogin/python-saml/blob/9fe7a72da5b4caa1529c1640b52d2649447ce49b/src/onelogin/saml2/utils.py#L477-L499
229,864
onelogin/python-saml
src/onelogin/saml2/utils.py
OneLogin_Saml2_Utils.get_status
def get_status(dom): """ Gets Status from a Response. :param dom: The Response as XML :type: Document :returns: The Status, an array with the code and a message. :rtype: dict """ status = {} status_entry = OneLogin_Saml2_Utils.query(dom, '/samlp...
python
def get_status(dom): """ Gets Status from a Response. :param dom: The Response as XML :type: Document :returns: The Status, an array with the code and a message. :rtype: dict """ status = {} status_entry = OneLogin_Saml2_Utils.query(dom, '/samlp...
[ "def", "get_status", "(", "dom", ")", ":", "status", "=", "{", "}", "status_entry", "=", "OneLogin_Saml2_Utils", ".", "query", "(", "dom", ",", "'/samlp:Response/samlp:Status'", ")", "if", "len", "(", "status_entry", ")", "!=", "1", ":", "raise", "OneLogin_S...
Gets Status from a Response. :param dom: The Response as XML :type: Document :returns: The Status, an array with the code and a message. :rtype: dict
[ "Gets", "Status", "from", "a", "Response", "." ]
9fe7a72da5b4caa1529c1640b52d2649447ce49b
https://github.com/onelogin/python-saml/blob/9fe7a72da5b4caa1529c1640b52d2649447ce49b/src/onelogin/saml2/utils.py#L734-L771
229,865
onelogin/python-saml
src/onelogin/saml2/utils.py
OneLogin_Saml2_Utils.write_temp_file
def write_temp_file(content): """ Writes some content into a temporary file and returns it. :param content: The file content :type: string :returns: The temporary file :rtype: file-like object """ f_temp = NamedTemporaryFile(delete=True) f_temp.f...
python
def write_temp_file(content): """ Writes some content into a temporary file and returns it. :param content: The file content :type: string :returns: The temporary file :rtype: file-like object """ f_temp = NamedTemporaryFile(delete=True) f_temp.f...
[ "def", "write_temp_file", "(", "content", ")", ":", "f_temp", "=", "NamedTemporaryFile", "(", "delete", "=", "True", ")", "f_temp", ".", "file", ".", "write", "(", "content", ")", "f_temp", ".", "file", ".", "flush", "(", ")", "return", "f_temp" ]
Writes some content into a temporary file and returns it. :param content: The file content :type: string :returns: The temporary file :rtype: file-like object
[ "Writes", "some", "content", "into", "a", "temporary", "file", "and", "returns", "it", "." ]
9fe7a72da5b4caa1529c1640b52d2649447ce49b
https://github.com/onelogin/python-saml/blob/9fe7a72da5b4caa1529c1640b52d2649447ce49b/src/onelogin/saml2/utils.py#L814-L827
229,866
onelogin/python-saml
src/onelogin/saml2/settings.py
OneLogin_Saml2_Settings.__add_default_values
def __add_default_values(self): """ Add default values if the settings info is not complete """ self.__sp.setdefault('assertionConsumerService', {}) self.__sp['assertionConsumerService'].setdefault('binding', OneLogin_Saml2_Constants.BINDING_HTTP_POST) self.__sp.setdefau...
python
def __add_default_values(self): """ Add default values if the settings info is not complete """ self.__sp.setdefault('assertionConsumerService', {}) self.__sp['assertionConsumerService'].setdefault('binding', OneLogin_Saml2_Constants.BINDING_HTTP_POST) self.__sp.setdefau...
[ "def", "__add_default_values", "(", "self", ")", ":", "self", ".", "__sp", ".", "setdefault", "(", "'assertionConsumerService'", ",", "{", "}", ")", "self", ".", "__sp", "[", "'assertionConsumerService'", "]", ".", "setdefault", "(", "'binding'", ",", "OneLogi...
Add default values if the settings info is not complete
[ "Add", "default", "values", "if", "the", "settings", "info", "is", "not", "complete" ]
9fe7a72da5b4caa1529c1640b52d2649447ce49b
https://github.com/onelogin/python-saml/blob/9fe7a72da5b4caa1529c1640b52d2649447ce49b/src/onelogin/saml2/settings.py#L250-L307
229,867
onelogin/python-saml
src/onelogin/saml2/auth.py
OneLogin_Saml2_Auth.login
def login(self, return_to=None, force_authn=False, is_passive=False, set_nameid_policy=True, name_id_value_req=None): """ Initiates the SSO process. :param return_to: Optional argument. The target URL the user should be redirected to after login. :type return_to: string :param ...
python
def login(self, return_to=None, force_authn=False, is_passive=False, set_nameid_policy=True, name_id_value_req=None): """ Initiates the SSO process. :param return_to: Optional argument. The target URL the user should be redirected to after login. :type return_to: string :param ...
[ "def", "login", "(", "self", ",", "return_to", "=", "None", ",", "force_authn", "=", "False", ",", "is_passive", "=", "False", ",", "set_nameid_policy", "=", "True", ",", "name_id_value_req", "=", "None", ")", ":", "authn_request", "=", "OneLogin_Saml2_Authn_R...
Initiates the SSO process. :param return_to: Optional argument. The target URL the user should be redirected to after login. :type return_to: string :param force_authn: Optional argument. When true the AuthNRequest will set the ForceAuthn='true'. :type force_authn: bool :param...
[ "Initiates", "the", "SSO", "process", "." ]
9fe7a72da5b4caa1529c1640b52d2649447ce49b
https://github.com/onelogin/python-saml/blob/9fe7a72da5b4caa1529c1640b52d2649447ce49b/src/onelogin/saml2/auth.py#L326-L363
229,868
onelogin/python-saml
src/onelogin/saml2/auth.py
OneLogin_Saml2_Auth.logout
def logout(self, return_to=None, name_id=None, session_index=None, nq=None, name_id_format=None): """ Initiates the SLO process. :param return_to: Optional argument. The target URL the user should be redirected to after logout. :type return_to: string :param name_id: The NameID...
python
def logout(self, return_to=None, name_id=None, session_index=None, nq=None, name_id_format=None): """ Initiates the SLO process. :param return_to: Optional argument. The target URL the user should be redirected to after logout. :type return_to: string :param name_id: The NameID...
[ "def", "logout", "(", "self", ",", "return_to", "=", "None", ",", "name_id", "=", "None", ",", "session_index", "=", "None", ",", "nq", "=", "None", ",", "name_id_format", "=", "None", ")", ":", "slo_url", "=", "self", ".", "get_slo_url", "(", ")", "...
Initiates the SLO process. :param return_to: Optional argument. The target URL the user should be redirected to after logout. :type return_to: string :param name_id: The NameID that will be set in the LogoutRequest. :type name_id: string :param session_index: SessionIndex that...
[ "Initiates", "the", "SLO", "process", "." ]
9fe7a72da5b4caa1529c1640b52d2649447ce49b
https://github.com/onelogin/python-saml/blob/9fe7a72da5b4caa1529c1640b52d2649447ce49b/src/onelogin/saml2/auth.py#L365-L419
229,869
onelogin/python-saml
src/onelogin/saml2/auth.py
OneLogin_Saml2_Auth.get_slo_url
def get_slo_url(self): """ Gets the SLO URL. :returns: An URL, the SLO endpoint of the IdP :rtype: string """ url = None idp_data = self.__settings.get_idp_data() if 'singleLogoutService' in idp_data.keys() and 'url' in idp_data['singleLogoutService']: ...
python
def get_slo_url(self): """ Gets the SLO URL. :returns: An URL, the SLO endpoint of the IdP :rtype: string """ url = None idp_data = self.__settings.get_idp_data() if 'singleLogoutService' in idp_data.keys() and 'url' in idp_data['singleLogoutService']: ...
[ "def", "get_slo_url", "(", "self", ")", ":", "url", "=", "None", "idp_data", "=", "self", ".", "__settings", ".", "get_idp_data", "(", ")", "if", "'singleLogoutService'", "in", "idp_data", ".", "keys", "(", ")", "and", "'url'", "in", "idp_data", "[", "'s...
Gets the SLO URL. :returns: An URL, the SLO endpoint of the IdP :rtype: string
[ "Gets", "the", "SLO", "URL", "." ]
9fe7a72da5b4caa1529c1640b52d2649447ce49b
https://github.com/onelogin/python-saml/blob/9fe7a72da5b4caa1529c1640b52d2649447ce49b/src/onelogin/saml2/auth.py#L431-L442
229,870
sryza/spark-timeseries
python/sparkts/utils.py
add_pyspark_path
def add_pyspark_path(): """Add PySpark to the library path based on the value of SPARK_HOME. """ try: spark_home = os.environ['SPARK_HOME'] sys.path.append(os.path.join(spark_home, 'python')) py4j_src_zip = glob(os.path.join(spark_home, 'python', ...
python
def add_pyspark_path(): """Add PySpark to the library path based on the value of SPARK_HOME. """ try: spark_home = os.environ['SPARK_HOME'] sys.path.append(os.path.join(spark_home, 'python')) py4j_src_zip = glob(os.path.join(spark_home, 'python', ...
[ "def", "add_pyspark_path", "(", ")", ":", "try", ":", "spark_home", "=", "os", ".", "environ", "[", "'SPARK_HOME'", "]", "sys", ".", "path", ".", "append", "(", "os", ".", "path", ".", "join", "(", "spark_home", ",", "'python'", ")", ")", "py4j_src_zip...
Add PySpark to the library path based on the value of SPARK_HOME.
[ "Add", "PySpark", "to", "the", "library", "path", "based", "on", "the", "value", "of", "SPARK_HOME", "." ]
280aa887dc08ab114411245268f230fdabb76eec
https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/utils.py#L9-L30
229,871
sryza/spark-timeseries
python/sparkts/utils.py
datetime_to_nanos
def datetime_to_nanos(dt): """ Accepts a string, Pandas Timestamp, or long, and returns nanos since the epoch. """ if isinstance(dt, pd.Timestamp): return dt.value elif isinstance(dt, str): return pd.Timestamp(dt).value elif isinstance(dt, long): return dt elif isinst...
python
def datetime_to_nanos(dt): """ Accepts a string, Pandas Timestamp, or long, and returns nanos since the epoch. """ if isinstance(dt, pd.Timestamp): return dt.value elif isinstance(dt, str): return pd.Timestamp(dt).value elif isinstance(dt, long): return dt elif isinst...
[ "def", "datetime_to_nanos", "(", "dt", ")", ":", "if", "isinstance", "(", "dt", ",", "pd", ".", "Timestamp", ")", ":", "return", "dt", ".", "value", "elif", "isinstance", "(", "dt", ",", "str", ")", ":", "return", "pd", ".", "Timestamp", "(", "dt", ...
Accepts a string, Pandas Timestamp, or long, and returns nanos since the epoch.
[ "Accepts", "a", "string", "Pandas", "Timestamp", "or", "long", "and", "returns", "nanos", "since", "the", "epoch", "." ]
280aa887dc08ab114411245268f230fdabb76eec
https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/utils.py#L37-L50
229,872
sryza/spark-timeseries
python/sparkts/datetimeindex.py
uniform
def uniform(start, end=None, periods=None, freq=None, sc=None): """ Instantiates a uniform DateTimeIndex. Either end or periods must be specified. Parameters ---------- start : string, long (nanos from epoch), or Pandas Timestamp end : string, long (nanos from epoch), or Pandas...
python
def uniform(start, end=None, periods=None, freq=None, sc=None): """ Instantiates a uniform DateTimeIndex. Either end or periods must be specified. Parameters ---------- start : string, long (nanos from epoch), or Pandas Timestamp end : string, long (nanos from epoch), or Pandas...
[ "def", "uniform", "(", "start", ",", "end", "=", "None", ",", "periods", "=", "None", ",", "freq", "=", "None", ",", "sc", "=", "None", ")", ":", "dtmodule", "=", "sc", ".", "_jvm", ".", "com", ".", "cloudera", ".", "sparkts", ".", "__getattr__", ...
Instantiates a uniform DateTimeIndex. Either end or periods must be specified. Parameters ---------- start : string, long (nanos from epoch), or Pandas Timestamp end : string, long (nanos from epoch), or Pandas Timestamp periods : int freq : a frequency object s...
[ "Instantiates", "a", "uniform", "DateTimeIndex", "." ]
280aa887dc08ab114411245268f230fdabb76eec
https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/datetimeindex.py#L129-L153
229,873
sryza/spark-timeseries
python/sparkts/datetimeindex.py
DateTimeIndex._zdt_to_nanos
def _zdt_to_nanos(self, zdt): """Extracts nanoseconds from a ZonedDateTime""" instant = zdt.toInstant() return instant.getNano() + instant.getEpochSecond() * 1000000000
python
def _zdt_to_nanos(self, zdt): """Extracts nanoseconds from a ZonedDateTime""" instant = zdt.toInstant() return instant.getNano() + instant.getEpochSecond() * 1000000000
[ "def", "_zdt_to_nanos", "(", "self", ",", "zdt", ")", ":", "instant", "=", "zdt", ".", "toInstant", "(", ")", "return", "instant", ".", "getNano", "(", ")", "+", "instant", ".", "getEpochSecond", "(", ")", "*", "1000000000" ]
Extracts nanoseconds from a ZonedDateTime
[ "Extracts", "nanoseconds", "from", "a", "ZonedDateTime" ]
280aa887dc08ab114411245268f230fdabb76eec
https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/datetimeindex.py#L24-L27
229,874
sryza/spark-timeseries
python/sparkts/datetimeindex.py
DateTimeIndex.datetime_at_loc
def datetime_at_loc(self, loc): """Returns the timestamp at the given integer location as a Pandas Timestamp.""" return pd.Timestamp(self._zdt_to_nanos(self._jdt_index.dateTimeAtLoc(loc)))
python
def datetime_at_loc(self, loc): """Returns the timestamp at the given integer location as a Pandas Timestamp.""" return pd.Timestamp(self._zdt_to_nanos(self._jdt_index.dateTimeAtLoc(loc)))
[ "def", "datetime_at_loc", "(", "self", ",", "loc", ")", ":", "return", "pd", ".", "Timestamp", "(", "self", ".", "_zdt_to_nanos", "(", "self", ".", "_jdt_index", ".", "dateTimeAtLoc", "(", "loc", ")", ")", ")" ]
Returns the timestamp at the given integer location as a Pandas Timestamp.
[ "Returns", "the", "timestamp", "at", "the", "given", "integer", "location", "as", "a", "Pandas", "Timestamp", "." ]
280aa887dc08ab114411245268f230fdabb76eec
https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/datetimeindex.py#L37-L39
229,875
sryza/spark-timeseries
python/sparkts/datetimeindex.py
DateTimeIndex.islice
def islice(self, start, end): """ Returns a new DateTimeIndex, containing a subslice of the timestamps in this index, as specified by the given integer start and end locations. Parameters ---------- start : int The location of the start of the range, inclusiv...
python
def islice(self, start, end): """ Returns a new DateTimeIndex, containing a subslice of the timestamps in this index, as specified by the given integer start and end locations. Parameters ---------- start : int The location of the start of the range, inclusiv...
[ "def", "islice", "(", "self", ",", "start", ",", "end", ")", ":", "jdt_index", "=", "self", ".", "_jdt_index", ".", "islice", "(", "start", ",", "end", ")", "return", "DateTimeIndex", "(", "jdt_index", "=", "jdt_index", ")" ]
Returns a new DateTimeIndex, containing a subslice of the timestamps in this index, as specified by the given integer start and end locations. Parameters ---------- start : int The location of the start of the range, inclusive. end : int The location of t...
[ "Returns", "a", "new", "DateTimeIndex", "containing", "a", "subslice", "of", "the", "timestamps", "in", "this", "index", "as", "specified", "by", "the", "given", "integer", "start", "and", "end", "locations", "." ]
280aa887dc08ab114411245268f230fdabb76eec
https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/datetimeindex.py#L51-L64
229,876
sryza/spark-timeseries
python/sparkts/models/AutoregressionX.py
fit_model
def fit_model(y, x, yMaxLag, xMaxLag, includesOriginalX=True, noIntercept=False, sc=None): """ Fit an autoregressive model with additional exogenous variables. The model predicts a value at time t of a dependent variable, Y, as a function of previous values of Y, and a combination of previous values of ...
python
def fit_model(y, x, yMaxLag, xMaxLag, includesOriginalX=True, noIntercept=False, sc=None): """ Fit an autoregressive model with additional exogenous variables. The model predicts a value at time t of a dependent variable, Y, as a function of previous values of Y, and a combination of previous values of ...
[ "def", "fit_model", "(", "y", ",", "x", ",", "yMaxLag", ",", "xMaxLag", ",", "includesOriginalX", "=", "True", ",", "noIntercept", "=", "False", ",", "sc", "=", "None", ")", ":", "assert", "sc", "!=", "None", ",", "\"Missing SparkContext\"", "jvm", "=", ...
Fit an autoregressive model with additional exogenous variables. The model predicts a value at time t of a dependent variable, Y, as a function of previous values of Y, and a combination of previous values of exogenous regressors X_i, and current values of exogenous regressors X_i. This is a generalization ...
[ "Fit", "an", "autoregressive", "model", "with", "additional", "exogenous", "variables", ".", "The", "model", "predicts", "a", "value", "at", "time", "t", "of", "a", "dependent", "variable", "Y", "as", "a", "function", "of", "previous", "values", "of", "Y", ...
280aa887dc08ab114411245268f230fdabb76eec
https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/models/AutoregressionX.py#L11-L45
229,877
sryza/spark-timeseries
python/sparkts/timeseriesrdd.py
time_series_rdd_from_pandas_series_rdd
def time_series_rdd_from_pandas_series_rdd(series_rdd): """ Instantiates a TimeSeriesRDD from an RDD of Pandas Series objects. The series in the RDD are all expected to have the same DatetimeIndex. Parameters ---------- series_rdd : RDD of (string, pandas.Series) tuples sc : SparkContext ...
python
def time_series_rdd_from_pandas_series_rdd(series_rdd): """ Instantiates a TimeSeriesRDD from an RDD of Pandas Series objects. The series in the RDD are all expected to have the same DatetimeIndex. Parameters ---------- series_rdd : RDD of (string, pandas.Series) tuples sc : SparkContext ...
[ "def", "time_series_rdd_from_pandas_series_rdd", "(", "series_rdd", ")", ":", "first", "=", "series_rdd", ".", "first", "(", ")", "dt_index", "=", "irregular", "(", "first", "[", "1", "]", ".", "index", ",", "series_rdd", ".", "ctx", ")", "return", "TimeSeri...
Instantiates a TimeSeriesRDD from an RDD of Pandas Series objects. The series in the RDD are all expected to have the same DatetimeIndex. Parameters ---------- series_rdd : RDD of (string, pandas.Series) tuples sc : SparkContext
[ "Instantiates", "a", "TimeSeriesRDD", "from", "an", "RDD", "of", "Pandas", "Series", "objects", "." ]
280aa887dc08ab114411245268f230fdabb76eec
https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/timeseriesrdd.py#L201-L214
229,878
sryza/spark-timeseries
python/sparkts/timeseriesrdd.py
time_series_rdd_from_observations
def time_series_rdd_from_observations(dt_index, df, ts_col, key_col, val_col): """ Instantiates a TimeSeriesRDD from a DataFrame of observations. An observation is a row containing a timestamp, a string key, and float value. Parameters ---------- dt_index : DateTimeIndex The index of t...
python
def time_series_rdd_from_observations(dt_index, df, ts_col, key_col, val_col): """ Instantiates a TimeSeriesRDD from a DataFrame of observations. An observation is a row containing a timestamp, a string key, and float value. Parameters ---------- dt_index : DateTimeIndex The index of t...
[ "def", "time_series_rdd_from_observations", "(", "dt_index", ",", "df", ",", "ts_col", ",", "key_col", ",", "val_col", ")", ":", "jvm", "=", "df", ".", "_sc", ".", "_jvm", "jtsrdd", "=", "jvm", ".", "com", ".", "cloudera", ".", "sparkts", ".", "api", "...
Instantiates a TimeSeriesRDD from a DataFrame of observations. An observation is a row containing a timestamp, a string key, and float value. Parameters ---------- dt_index : DateTimeIndex The index of the RDD to create. Observations not contained in this index will be ignored. df : DataFr...
[ "Instantiates", "a", "TimeSeriesRDD", "from", "a", "DataFrame", "of", "observations", "." ]
280aa887dc08ab114411245268f230fdabb76eec
https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/timeseriesrdd.py#L216-L237
229,879
sryza/spark-timeseries
python/sparkts/timeseriesrdd.py
TimeSeriesRDD.map_series
def map_series(self, fn, dt_index = None): """ Returns a TimeSeriesRDD, with a transformation applied to all the series in this RDD. Either the series produced by the given function should conform to this TimeSeriesRDD's index, or a new DateTimeIndex should be given that they conform to...
python
def map_series(self, fn, dt_index = None): """ Returns a TimeSeriesRDD, with a transformation applied to all the series in this RDD. Either the series produced by the given function should conform to this TimeSeriesRDD's index, or a new DateTimeIndex should be given that they conform to...
[ "def", "map_series", "(", "self", ",", "fn", ",", "dt_index", "=", "None", ")", ":", "if", "dt_index", "==", "None", ":", "dt_index", "=", "self", ".", "index", "(", ")", "return", "TimeSeriesRDD", "(", "dt_index", ",", "self", ".", "map", "(", "fn",...
Returns a TimeSeriesRDD, with a transformation applied to all the series in this RDD. Either the series produced by the given function should conform to this TimeSeriesRDD's index, or a new DateTimeIndex should be given that they conform to. Parameters ---------- fn : f...
[ "Returns", "a", "TimeSeriesRDD", "with", "a", "transformation", "applied", "to", "all", "the", "series", "in", "this", "RDD", "." ]
280aa887dc08ab114411245268f230fdabb76eec
https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/timeseriesrdd.py#L77-L93
229,880
sryza/spark-timeseries
python/sparkts/timeseriesrdd.py
TimeSeriesRDD.to_instants
def to_instants(self): """ Returns an RDD of instants, each a horizontal slice of this TimeSeriesRDD at a time. This essentially transposes the TimeSeriesRDD, producing an RDD of tuples of datetime and a numpy array containing all the observations that occurred at that time. """...
python
def to_instants(self): """ Returns an RDD of instants, each a horizontal slice of this TimeSeriesRDD at a time. This essentially transposes the TimeSeriesRDD, producing an RDD of tuples of datetime and a numpy array containing all the observations that occurred at that time. """...
[ "def", "to_instants", "(", "self", ")", ":", "jrdd", "=", "self", ".", "_jtsrdd", ".", "toInstants", "(", "-", "1", ")", ".", "map", "(", "self", ".", "ctx", ".", "_jvm", ".", "com", ".", "cloudera", ".", "sparkts", ".", "InstantToBytes", "(", ")",...
Returns an RDD of instants, each a horizontal slice of this TimeSeriesRDD at a time. This essentially transposes the TimeSeriesRDD, producing an RDD of tuples of datetime and a numpy array containing all the observations that occurred at that time.
[ "Returns", "an", "RDD", "of", "instants", "each", "a", "horizontal", "slice", "of", "this", "TimeSeriesRDD", "at", "a", "time", "." ]
280aa887dc08ab114411245268f230fdabb76eec
https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/timeseriesrdd.py#L95-L104
229,881
sryza/spark-timeseries
python/sparkts/timeseriesrdd.py
TimeSeriesRDD.to_instants_dataframe
def to_instants_dataframe(self, sql_ctx): """ Returns a DataFrame of instants, each a horizontal slice of this TimeSeriesRDD at a time. This essentially transposes the TimeSeriesRDD, producing a DataFrame where each column is a key form one of the rows in the TimeSeriesRDD. """ ...
python
def to_instants_dataframe(self, sql_ctx): """ Returns a DataFrame of instants, each a horizontal slice of this TimeSeriesRDD at a time. This essentially transposes the TimeSeriesRDD, producing a DataFrame where each column is a key form one of the rows in the TimeSeriesRDD. """ ...
[ "def", "to_instants_dataframe", "(", "self", ",", "sql_ctx", ")", ":", "ssql_ctx", "=", "sql_ctx", ".", "_ssql_ctx", "jdf", "=", "self", ".", "_jtsrdd", ".", "toInstantsDataFrame", "(", "ssql_ctx", ",", "-", "1", ")", "return", "DataFrame", "(", "jdf", ","...
Returns a DataFrame of instants, each a horizontal slice of this TimeSeriesRDD at a time. This essentially transposes the TimeSeriesRDD, producing a DataFrame where each column is a key form one of the rows in the TimeSeriesRDD.
[ "Returns", "a", "DataFrame", "of", "instants", "each", "a", "horizontal", "slice", "of", "this", "TimeSeriesRDD", "at", "a", "time", "." ]
280aa887dc08ab114411245268f230fdabb76eec
https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/timeseriesrdd.py#L106-L115
229,882
sryza/spark-timeseries
python/sparkts/timeseriesrdd.py
TimeSeriesRDD.to_observations_dataframe
def to_observations_dataframe(self, sql_ctx, ts_col='timestamp', key_col='key', val_col='value'): """ Returns a DataFrame of observations, each containing a timestamp, a key, and a value. Parameters ---------- sql_ctx : SQLContext ts_col : string The name for...
python
def to_observations_dataframe(self, sql_ctx, ts_col='timestamp', key_col='key', val_col='value'): """ Returns a DataFrame of observations, each containing a timestamp, a key, and a value. Parameters ---------- sql_ctx : SQLContext ts_col : string The name for...
[ "def", "to_observations_dataframe", "(", "self", ",", "sql_ctx", ",", "ts_col", "=", "'timestamp'", ",", "key_col", "=", "'key'", ",", "val_col", "=", "'value'", ")", ":", "ssql_ctx", "=", "sql_ctx", ".", "_ssql_ctx", "jdf", "=", "self", ".", "_jtsrdd", "....
Returns a DataFrame of observations, each containing a timestamp, a key, and a value. Parameters ---------- sql_ctx : SQLContext ts_col : string The name for the timestamp column. key_col : string The name for the key column. val_col : string ...
[ "Returns", "a", "DataFrame", "of", "observations", "each", "containing", "a", "timestamp", "a", "key", "and", "a", "value", "." ]
280aa887dc08ab114411245268f230fdabb76eec
https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/timeseriesrdd.py#L123-L139
229,883
sryza/spark-timeseries
python/sparkts/timeseriesrdd.py
TimeSeriesRDD.to_pandas_series_rdd
def to_pandas_series_rdd(self): """ Returns an RDD of Pandas Series objects indexed with Pandas DatetimeIndexes """ pd_index = self.index().to_pandas_index() return self.map(lambda x: (x[0], pd.Series(x[1], pd_index)))
python
def to_pandas_series_rdd(self): """ Returns an RDD of Pandas Series objects indexed with Pandas DatetimeIndexes """ pd_index = self.index().to_pandas_index() return self.map(lambda x: (x[0], pd.Series(x[1], pd_index)))
[ "def", "to_pandas_series_rdd", "(", "self", ")", ":", "pd_index", "=", "self", ".", "index", "(", ")", ".", "to_pandas_index", "(", ")", "return", "self", ".", "map", "(", "lambda", "x", ":", "(", "x", "[", "0", "]", ",", "pd", ".", "Series", "(", ...
Returns an RDD of Pandas Series objects indexed with Pandas DatetimeIndexes
[ "Returns", "an", "RDD", "of", "Pandas", "Series", "objects", "indexed", "with", "Pandas", "DatetimeIndexes" ]
280aa887dc08ab114411245268f230fdabb76eec
https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/timeseriesrdd.py#L141-L146
229,884
sryza/spark-timeseries
python/sparkts/timeseriesrdd.py
TimeSeriesRDD.to_pandas_dataframe
def to_pandas_dataframe(self): """ Pulls the contents of the RDD to the driver and places them in a Pandas DataFrame. Each record in the RDD becomes and column, and the DataFrame is indexed with a DatetimeIndex generated from this RDD's index. """ pd_index = self...
python
def to_pandas_dataframe(self): """ Pulls the contents of the RDD to the driver and places them in a Pandas DataFrame. Each record in the RDD becomes and column, and the DataFrame is indexed with a DatetimeIndex generated from this RDD's index. """ pd_index = self...
[ "def", "to_pandas_dataframe", "(", "self", ")", ":", "pd_index", "=", "self", ".", "index", "(", ")", ".", "to_pandas_index", "(", ")", "return", "pd", ".", "DataFrame", ".", "from_items", "(", "self", ".", "collect", "(", ")", ")", ".", "set_index", "...
Pulls the contents of the RDD to the driver and places them in a Pandas DataFrame. Each record in the RDD becomes and column, and the DataFrame is indexed with a DatetimeIndex generated from this RDD's index.
[ "Pulls", "the", "contents", "of", "the", "RDD", "to", "the", "driver", "and", "places", "them", "in", "a", "Pandas", "DataFrame", ".", "Each", "record", "in", "the", "RDD", "becomes", "and", "column", "and", "the", "DataFrame", "is", "indexed", "with", "...
280aa887dc08ab114411245268f230fdabb76eec
https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/timeseriesrdd.py#L148-L156
229,885
google/textfsm
textfsm/texttable.py
Row._SetHeader
def _SetHeader(self, values): """Set the row's header from a list.""" if self._values and len(values) != len(self._values): raise ValueError('Header values not equal to existing data width.') if not self._values: for _ in range(len(values)): self._values.append(None) self._keys = lis...
python
def _SetHeader(self, values): """Set the row's header from a list.""" if self._values and len(values) != len(self._values): raise ValueError('Header values not equal to existing data width.') if not self._values: for _ in range(len(values)): self._values.append(None) self._keys = lis...
[ "def", "_SetHeader", "(", "self", ",", "values", ")", ":", "if", "self", ".", "_values", "and", "len", "(", "values", ")", "!=", "len", "(", "self", ".", "_values", ")", ":", "raise", "ValueError", "(", "'Header values not equal to existing data width.'", ")...
Set the row's header from a list.
[ "Set", "the", "row", "s", "header", "from", "a", "list", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/texttable.py#L190-L198
229,886
google/textfsm
textfsm/texttable.py
Row._SetValues
def _SetValues(self, values): """Set values from supplied dictionary or list. Args: values: A Row, dict indexed by column name, or list. Raises: TypeError: Argument is not a list or dict, or list is not equal row length or dictionary keys don't match. """ def _ToStr(value): ...
python
def _SetValues(self, values): """Set values from supplied dictionary or list. Args: values: A Row, dict indexed by column name, or list. Raises: TypeError: Argument is not a list or dict, or list is not equal row length or dictionary keys don't match. """ def _ToStr(value): ...
[ "def", "_SetValues", "(", "self", ",", "values", ")", ":", "def", "_ToStr", "(", "value", ")", ":", "\"\"\"Convert individul list entries to string.\"\"\"", "if", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ":", "result", "=", "[", ...
Set values from supplied dictionary or list. Args: values: A Row, dict indexed by column name, or list. Raises: TypeError: Argument is not a list or dict, or list is not equal row length or dictionary keys don't match.
[ "Set", "values", "from", "supplied", "dictionary", "or", "list", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/texttable.py#L222-L264
229,887
google/textfsm
textfsm/texttable.py
TextTable.Filter
def Filter(self, function=None): """Construct Textable from the rows of which the function returns true. Args: function: A function applied to each row which returns a bool. If function is None, all rows with empty column values are removed. Returns: A new TextT...
python
def Filter(self, function=None): """Construct Textable from the rows of which the function returns true. Args: function: A function applied to each row which returns a bool. If function is None, all rows with empty column values are removed. Returns: A new TextT...
[ "def", "Filter", "(", "self", ",", "function", "=", "None", ")", ":", "flat", "=", "lambda", "x", ":", "x", "if", "isinstance", "(", "x", ",", "str", ")", "else", "''", ".", "join", "(", "[", "flat", "(", "y", ")", "for", "y", "in", "x", "]",...
Construct Textable from the rows of which the function returns true. Args: function: A function applied to each row which returns a bool. If function is None, all rows with empty column values are removed. Returns: A new TextTable() Raises: TableError: Wh...
[ "Construct", "Textable", "from", "the", "rows", "of", "which", "the", "function", "returns", "true", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/texttable.py#L378-L402
229,888
google/textfsm
textfsm/texttable.py
TextTable._GetTable
def _GetTable(self): """Returns table, with column headers and separators. Returns: The whole table including headers as a string. Each row is joined by a newline and each entry by self.separator. """ result = [] # Avoid the global lookup cost on each iteration. lstr = str for r...
python
def _GetTable(self): """Returns table, with column headers and separators. Returns: The whole table including headers as a string. Each row is joined by a newline and each entry by self.separator. """ result = [] # Avoid the global lookup cost on each iteration. lstr = str for r...
[ "def", "_GetTable", "(", "self", ")", ":", "result", "=", "[", "]", "# Avoid the global lookup cost on each iteration.", "lstr", "=", "str", "for", "row", "in", "self", ".", "_table", ":", "result", ".", "append", "(", "'%s\\n'", "%", "self", ".", "separator...
Returns table, with column headers and separators. Returns: The whole table including headers as a string. Each row is joined by a newline and each entry by self.separator.
[ "Returns", "table", "with", "column", "headers", "and", "separators", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/texttable.py#L595-L610
229,889
google/textfsm
textfsm/texttable.py
TextTable._SetTable
def _SetTable(self, table): """Sets table, with column headers and separators.""" if not isinstance(table, TextTable): raise TypeError('Not an instance of TextTable.') self.Reset() self._table = copy.deepcopy(table._table) # pylint: disable=W0212 # Point parent table of each row back ourselv...
python
def _SetTable(self, table): """Sets table, with column headers and separators.""" if not isinstance(table, TextTable): raise TypeError('Not an instance of TextTable.') self.Reset() self._table = copy.deepcopy(table._table) # pylint: disable=W0212 # Point parent table of each row back ourselv...
[ "def", "_SetTable", "(", "self", ",", "table", ")", ":", "if", "not", "isinstance", "(", "table", ",", "TextTable", ")", ":", "raise", "TypeError", "(", "'Not an instance of TextTable.'", ")", "self", ".", "Reset", "(", ")", "self", ".", "_table", "=", "...
Sets table, with column headers and separators.
[ "Sets", "table", "with", "column", "headers", "and", "separators", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/texttable.py#L612-L620
229,890
google/textfsm
textfsm/texttable.py
TextTable._TextJustify
def _TextJustify(self, text, col_size): """Formats text within column with white space padding. A single space is prefixed, and a number of spaces are added as a suffix such that the length of the resultant string equals the col_size. If the length of the text exceeds the column width available then i...
python
def _TextJustify(self, text, col_size): """Formats text within column with white space padding. A single space is prefixed, and a number of spaces are added as a suffix such that the length of the resultant string equals the col_size. If the length of the text exceeds the column width available then i...
[ "def", "_TextJustify", "(", "self", ",", "text", ",", "col_size", ")", ":", "result", "=", "[", "]", "if", "'\\n'", "in", "text", ":", "for", "paragraph", "in", "text", ".", "split", "(", "'\\n'", ")", ":", "result", ".", "extend", "(", "self", "."...
Formats text within column with white space padding. A single space is prefixed, and a number of spaces are added as a suffix such that the length of the resultant string equals the col_size. If the length of the text exceeds the column width available then it is split into words and returned as a lis...
[ "Formats", "text", "within", "column", "with", "white", "space", "padding", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/texttable.py#L639-L684
229,891
google/textfsm
textfsm/texttable.py
TextTable.index
def index(self, name=None): # pylint: disable=C6409 """Returns index number of supplied column name. Args: name: string of column name. Raises: TableError: If name not found. Returns: Index of the specified header entry. """ try: return self.header.index(name) exc...
python
def index(self, name=None): # pylint: disable=C6409 """Returns index number of supplied column name. Args: name: string of column name. Raises: TableError: If name not found. Returns: Index of the specified header entry. """ try: return self.header.index(name) exc...
[ "def", "index", "(", "self", ",", "name", "=", "None", ")", ":", "# pylint: disable=C6409", "try", ":", "return", "self", ".", "header", ".", "index", "(", "name", ")", "except", "ValueError", ":", "raise", "TableError", "(", "'Unknown index name %s.'", "%",...
Returns index number of supplied column name. Args: name: string of column name. Raises: TableError: If name not found. Returns: Index of the specified header entry.
[ "Returns", "index", "number", "of", "supplied", "column", "name", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/texttable.py#L1074-L1089
229,892
google/textfsm
textfsm/clitable.py
CliTable._ParseCmdItem
def _ParseCmdItem(self, cmd_input, template_file=None): """Creates Texttable with output of command. Args: cmd_input: String, Device response. template_file: File object, template to parse with. Returns: TextTable containing command output. Raises: CliTableError: A template wa...
python
def _ParseCmdItem(self, cmd_input, template_file=None): """Creates Texttable with output of command. Args: cmd_input: String, Device response. template_file: File object, template to parse with. Returns: TextTable containing command output. Raises: CliTableError: A template wa...
[ "def", "_ParseCmdItem", "(", "self", ",", "cmd_input", ",", "template_file", "=", "None", ")", ":", "# Build FSM machine from the template.", "fsm", "=", "textfsm", ".", "TextFSM", "(", "template_file", ")", "if", "not", "self", ".", "_keys", ":", "self", ".",...
Creates Texttable with output of command. Args: cmd_input: String, Device response. template_file: File object, template to parse with. Returns: TextTable containing command output. Raises: CliTableError: A template was not found for the given command.
[ "Creates", "Texttable", "with", "output", "of", "command", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/clitable.py#L288-L313
229,893
google/textfsm
textfsm/clitable.py
CliTable._Completion
def _Completion(self, match): # pylint: disable=C6114 r"""Replaces double square brackets with variable length completion. Completion cannot be mixed with regexp matching or '\' characters i.e. '[[(\n)]] would become (\(n)?)?.' Args: match: A regex Match() object. Returns: String ...
python
def _Completion(self, match): # pylint: disable=C6114 r"""Replaces double square brackets with variable length completion. Completion cannot be mixed with regexp matching or '\' characters i.e. '[[(\n)]] would become (\(n)?)?.' Args: match: A regex Match() object. Returns: String ...
[ "def", "_Completion", "(", "self", ",", "match", ")", ":", "# pylint: disable=C6114", "# Strip the outer '[[' & ']]' and replace with ()? regexp pattern.", "word", "=", "str", "(", "match", ".", "group", "(", ")", ")", "[", "2", ":", "-", "2", "]", "return", "'(...
r"""Replaces double square brackets with variable length completion. Completion cannot be mixed with regexp matching or '\' characters i.e. '[[(\n)]] would become (\(n)?)?.' Args: match: A regex Match() object. Returns: String of the format '(a(b(c(d)?)?)?)?'.
[ "r", "Replaces", "double", "square", "brackets", "with", "variable", "length", "completion", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/clitable.py#L329-L344
229,894
google/textfsm
textfsm/parser.py
main
def main(argv=None): """Validate text parsed with FSM or validate an FSM via command line.""" if argv is None: argv = sys.argv try: opts, args = getopt.getopt(argv[1:], 'h', ['help']) except getopt.error as msg: raise Usage(msg) for opt, _ in opts: if opt in ('-h', '--help'): print(__...
python
def main(argv=None): """Validate text parsed with FSM or validate an FSM via command line.""" if argv is None: argv = sys.argv try: opts, args = getopt.getopt(argv[1:], 'h', ['help']) except getopt.error as msg: raise Usage(msg) for opt, _ in opts: if opt in ('-h', '--help'): print(__...
[ "def", "main", "(", "argv", "=", "None", ")", ":", "if", "argv", "is", "None", ":", "argv", "=", "sys", ".", "argv", "try", ":", "opts", ",", "args", "=", "getopt", ".", "getopt", "(", "argv", "[", "1", ":", "]", ",", "'h'", ",", "[", "'help'...
Validate text parsed with FSM or validate an FSM via command line.
[ "Validate", "text", "parsed", "with", "FSM", "or", "validate", "an", "FSM", "via", "command", "line", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L1044-L1093
229,895
google/textfsm
textfsm/parser.py
TextFSMOptions.ValidOptions
def ValidOptions(cls): """Returns a list of valid option names.""" valid_options = [] for obj_name in dir(cls): obj = getattr(cls, obj_name) if inspect.isclass(obj) and issubclass(obj, cls.OptionBase): valid_options.append(obj_name) return valid_options
python
def ValidOptions(cls): """Returns a list of valid option names.""" valid_options = [] for obj_name in dir(cls): obj = getattr(cls, obj_name) if inspect.isclass(obj) and issubclass(obj, cls.OptionBase): valid_options.append(obj_name) return valid_options
[ "def", "ValidOptions", "(", "cls", ")", ":", "valid_options", "=", "[", "]", "for", "obj_name", "in", "dir", "(", "cls", ")", ":", "obj", "=", "getattr", "(", "cls", ",", "obj_name", ")", "if", "inspect", ".", "isclass", "(", "obj", ")", "and", "is...
Returns a list of valid option names.
[ "Returns", "a", "list", "of", "valid", "option", "names", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L114-L121
229,896
google/textfsm
textfsm/parser.py
TextFSMValue.Header
def Header(self): """Fetch the header name of this Value.""" # Call OnGetValue on options. _ = [option.OnGetValue() for option in self.options] return self.name
python
def Header(self): """Fetch the header name of this Value.""" # Call OnGetValue on options. _ = [option.OnGetValue() for option in self.options] return self.name
[ "def", "Header", "(", "self", ")", ":", "# Call OnGetValue on options.", "_", "=", "[", "option", ".", "OnGetValue", "(", ")", "for", "option", "in", "self", ".", "options", "]", "return", "self", ".", "name" ]
Fetch the header name of this Value.
[ "Fetch", "the", "header", "name", "of", "this", "Value", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L262-L266
229,897
google/textfsm
textfsm/parser.py
TextFSMValue._AddOption
def _AddOption(self, name): """Add an option to this Value. Args: name: (str), the name of the Option to add. Raises: TextFSMTemplateError: If option is already present or the option does not exist. """ # Check for duplicate option declaration if name in [option.name for o...
python
def _AddOption(self, name): """Add an option to this Value. Args: name: (str), the name of the Option to add. Raises: TextFSMTemplateError: If option is already present or the option does not exist. """ # Check for duplicate option declaration if name in [option.name for o...
[ "def", "_AddOption", "(", "self", ",", "name", ")", ":", "# Check for duplicate option declaration", "if", "name", "in", "[", "option", ".", "name", "for", "option", "in", "self", ".", "options", "]", ":", "raise", "TextFSMTemplateError", "(", "'Duplicate option...
Add an option to this Value. Args: name: (str), the name of the Option to add. Raises: TextFSMTemplateError: If option is already present or the option does not exist.
[ "Add", "an", "option", "to", "this", "Value", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L321-L342
229,898
google/textfsm
textfsm/parser.py
TextFSM.Reset
def Reset(self): """Preserves FSM but resets starting state and current record.""" # Current state is Start state. self._cur_state = self.states['Start'] self._cur_state_name = 'Start' # Clear table of results and current record. self._result = [] self._ClearAllRecord()
python
def Reset(self): """Preserves FSM but resets starting state and current record.""" # Current state is Start state. self._cur_state = self.states['Start'] self._cur_state_name = 'Start' # Clear table of results and current record. self._result = [] self._ClearAllRecord()
[ "def", "Reset", "(", "self", ")", ":", "# Current state is Start state.", "self", ".", "_cur_state", "=", "self", ".", "states", "[", "'Start'", "]", "self", ".", "_cur_state_name", "=", "'Start'", "# Clear table of results and current record.", "self", ".", "_resul...
Preserves FSM but resets starting state and current record.
[ "Preserves", "FSM", "but", "resets", "starting", "state", "and", "current", "record", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L596-L605
229,899
google/textfsm
textfsm/parser.py
TextFSM._GetHeader
def _GetHeader(self): """Returns header.""" header = [] for value in self.values: try: header.append(value.Header()) except SkipValue: continue return header
python
def _GetHeader(self): """Returns header.""" header = [] for value in self.values: try: header.append(value.Header()) except SkipValue: continue return header
[ "def", "_GetHeader", "(", "self", ")", ":", "header", "=", "[", "]", "for", "value", "in", "self", ".", "values", ":", "try", ":", "header", ".", "append", "(", "value", ".", "Header", "(", ")", ")", "except", "SkipValue", ":", "continue", "return", ...
Returns header.
[ "Returns", "header", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L612-L620