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 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
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",
":",
"return",
"request_inf... | 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 | train |
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 | train |
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 | train |
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",
":",
"return",
"request_i... | 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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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",
",",
"value",
... | 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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"result",
"=",
"[",
"]",
"for",
"val",
"in",
"value",
":",
"resul... | 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 | train |
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 | train |
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",
"=",
"[",
"]",
"lstr",
"=",
"str",
"for",
"row",
"in",
"self",
".",
"_table",
":",
"result",
".",
"append",
"(",
"'%s\\n'",
"%",
"self",
".",
"separator",
".",
"join",
"(",
"lstr",
"(",
"v",
")... | 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 | train |
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 | train |
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 | train |
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",
")",
":",
"try",
":",
"return",
"self",
".",
"header",
".",
"index",
"(",
"name",
")",
"except",
"ValueError",
":",
"raise",
"TableError",
"(",
"'Unknown index name %s.'",
"%",
"name",
")"
] | 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 | train |
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",
")",
":",
"fsm",
"=",
"textfsm",
".",
"TextFSM",
"(",
"template_file",
")",
"if",
"not",
"self",
".",
"_keys",
":",
"self",
".",
"_keys",
"=",
"set",
"(",
"fsm",
... | 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 | train |
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",
")",
":",
"r",
"word",
"=",
"str",
"(",
"match",
".",
"group",
"(",
")",
")",
"[",
"2",
":",
"-",
"2",
"]",
"return",
"'('",
"+",
"(",
"'('",
")",
".",
"join",
"(",
"word",
")",
"+",
"')?'",
... | 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 | train |
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 | train |
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 | train |
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",
")",
":",
"_",
"=",
"[",
"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 | train |
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",
")",
":",
"if",
"name",
"in",
"[",
"option",
".",
"name",
"for",
"option",
"in",
"self",
".",
"options",
"]",
":",
"raise",
"TextFSMTemplateError",
"(",
"'Duplicate option \"%s\"'",
"%",
"name",
")",
"try",
... | 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 | train |
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",
")",
":",
"self",
".",
"_cur_state",
"=",
"self",
".",
"states",
"[",
"'Start'",
"]",
"self",
".",
"_cur_state_name",
"=",
"'Start'",
"self",
".",
"_result",
"=",
"[",
"]",
"self",
".",
"_ClearAllRecord",
"(",
")"
] | 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 | train |
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 | train |
google/textfsm | textfsm/parser.py | TextFSM._GetValue | def _GetValue(self, name):
"""Returns the TextFSMValue object natching the requested name."""
for value in self.values:
if value.name == name:
return value | python | def _GetValue(self, name):
"""Returns the TextFSMValue object natching the requested name."""
for value in self.values:
if value.name == name:
return value | [
"def",
"_GetValue",
"(",
"self",
",",
"name",
")",
":",
"for",
"value",
"in",
"self",
".",
"values",
":",
"if",
"value",
".",
"name",
"==",
"name",
":",
"return",
"value"
] | Returns the TextFSMValue object natching the requested name. | [
"Returns",
"the",
"TextFSMValue",
"object",
"natching",
"the",
"requested",
"name",
"."
] | 63a2aaece33e07947aa80963dca99b893964633b | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L622-L626 | train |
google/textfsm | textfsm/parser.py | TextFSM._AppendRecord | def _AppendRecord(self):
"""Adds current record to result if well formed."""
# If no Values then don't output.
if not self.values:
return
cur_record = []
for value in self.values:
try:
value.OnSaveRecord()
except SkipRecord:
self._ClearRecord()
return
... | python | def _AppendRecord(self):
"""Adds current record to result if well formed."""
# If no Values then don't output.
if not self.values:
return
cur_record = []
for value in self.values:
try:
value.OnSaveRecord()
except SkipRecord:
self._ClearRecord()
return
... | [
"def",
"_AppendRecord",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"values",
":",
"return",
"cur_record",
"=",
"[",
"]",
"for",
"value",
"in",
"self",
".",
"values",
":",
"try",
":",
"value",
".",
"OnSaveRecord",
"(",
")",
"except",
"SkipRecord",... | Adds current record to result if well formed. | [
"Adds",
"current",
"record",
"to",
"result",
"if",
"well",
"formed",
"."
] | 63a2aaece33e07947aa80963dca99b893964633b | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L628-L657 | train |
google/textfsm | textfsm/parser.py | TextFSM._Parse | def _Parse(self, template):
"""Parses template file for FSM structure.
Args:
template: Valid template file.
Raises:
TextFSMTemplateError: If template file syntax is invalid.
"""
if not template:
raise TextFSMTemplateError('Null template.')
# Parse header with Variables.
... | python | def _Parse(self, template):
"""Parses template file for FSM structure.
Args:
template: Valid template file.
Raises:
TextFSMTemplateError: If template file syntax is invalid.
"""
if not template:
raise TextFSMTemplateError('Null template.')
# Parse header with Variables.
... | [
"def",
"_Parse",
"(",
"self",
",",
"template",
")",
":",
"if",
"not",
"template",
":",
"raise",
"TextFSMTemplateError",
"(",
"'Null template.'",
")",
"self",
".",
"_ParseFSMVariables",
"(",
"template",
")",
"while",
"self",
".",
"_ParseFSMState",
"(",
"templat... | Parses template file for FSM structure.
Args:
template: Valid template file.
Raises:
TextFSMTemplateError: If template file syntax is invalid. | [
"Parses",
"template",
"file",
"for",
"FSM",
"structure",
"."
] | 63a2aaece33e07947aa80963dca99b893964633b | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L659-L680 | train |
google/textfsm | textfsm/parser.py | TextFSM._ParseFSMVariables | def _ParseFSMVariables(self, template):
"""Extracts Variables from start of template file.
Values are expected as a contiguous block at the head of the file.
These will be line separated from the State definitions that follow.
Args:
template: Valid template file, with Value definitions at the to... | python | def _ParseFSMVariables(self, template):
"""Extracts Variables from start of template file.
Values are expected as a contiguous block at the head of the file.
These will be line separated from the State definitions that follow.
Args:
template: Valid template file, with Value definitions at the to... | [
"def",
"_ParseFSMVariables",
"(",
"self",
",",
"template",
")",
":",
"self",
".",
"values",
"=",
"[",
"]",
"for",
"line",
"in",
"template",
":",
"self",
".",
"_line_num",
"+=",
"1",
"line",
"=",
"line",
".",
"rstrip",
"(",
")",
"if",
"not",
"line",
... | Extracts Variables from start of template file.
Values are expected as a contiguous block at the head of the file.
These will be line separated from the State definitions that follow.
Args:
template: Valid template file, with Value definitions at the top.
Raises:
TextFSMTemplateError: If ... | [
"Extracts",
"Variables",
"from",
"start",
"of",
"template",
"file",
"."
] | 63a2aaece33e07947aa80963dca99b893964633b | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L682-L736 | train |
google/textfsm | textfsm/parser.py | TextFSM._ParseFSMState | def _ParseFSMState(self, template):
"""Extracts State and associated Rules from body of template file.
After the Value definitions the remainder of the template is
state definitions. The routine is expected to be called iteratively
until no more states remain - indicated by returning None.
The rou... | python | def _ParseFSMState(self, template):
"""Extracts State and associated Rules from body of template file.
After the Value definitions the remainder of the template is
state definitions. The routine is expected to be called iteratively
until no more states remain - indicated by returning None.
The rou... | [
"def",
"_ParseFSMState",
"(",
"self",
",",
"template",
")",
":",
"if",
"not",
"template",
":",
"return",
"state_name",
"=",
"''",
"for",
"line",
"in",
"template",
":",
"self",
".",
"_line_num",
"+=",
"1",
"line",
"=",
"line",
".",
"rstrip",
"(",
")",
... | Extracts State and associated Rules from body of template file.
After the Value definitions the remainder of the template is
state definitions. The routine is expected to be called iteratively
until no more states remain - indicated by returning None.
The routine checks that the state names are a well... | [
"Extracts",
"State",
"and",
"associated",
"Rules",
"from",
"body",
"of",
"template",
"file",
"."
] | 63a2aaece33e07947aa80963dca99b893964633b | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L743-L812 | train |
google/textfsm | textfsm/parser.py | TextFSM._ValidateFSM | def _ValidateFSM(self):
"""Checks state names and destinations for validity.
Each destination state must exist, be a valid name and
not be a reserved name.
There must be a 'Start' state and if 'EOF' or 'End' states are specified,
they must be empty.
Returns:
True if FSM is valid.
Ra... | python | def _ValidateFSM(self):
"""Checks state names and destinations for validity.
Each destination state must exist, be a valid name and
not be a reserved name.
There must be a 'Start' state and if 'EOF' or 'End' states are specified,
they must be empty.
Returns:
True if FSM is valid.
Ra... | [
"def",
"_ValidateFSM",
"(",
"self",
")",
":",
"if",
"'Start'",
"not",
"in",
"self",
".",
"states",
":",
"raise",
"TextFSMTemplateError",
"(",
"\"Missing state 'Start'.\"",
")",
"if",
"self",
".",
"states",
".",
"get",
"(",
"'End'",
")",
":",
"raise",
"Text... | Checks state names and destinations for validity.
Each destination state must exist, be a valid name and
not be a reserved name.
There must be a 'Start' state and if 'EOF' or 'End' states are specified,
they must be empty.
Returns:
True if FSM is valid.
Raises:
TextFSMTemplateErro... | [
"Checks",
"state",
"names",
"and",
"destinations",
"for",
"validity",
"."
] | 63a2aaece33e07947aa80963dca99b893964633b | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L814-L859 | train |
google/textfsm | textfsm/parser.py | TextFSM.ParseText | def ParseText(self, text, eof=True):
"""Passes CLI output through FSM and returns list of tuples.
First tuple is the header, every subsequent tuple is a row.
Args:
text: (str), Text to parse with embedded newlines.
eof: (boolean), Set to False if we are parsing only part of the file.
... | python | def ParseText(self, text, eof=True):
"""Passes CLI output through FSM and returns list of tuples.
First tuple is the header, every subsequent tuple is a row.
Args:
text: (str), Text to parse with embedded newlines.
eof: (boolean), Set to False if we are parsing only part of the file.
... | [
"def",
"ParseText",
"(",
"self",
",",
"text",
",",
"eof",
"=",
"True",
")",
":",
"lines",
"=",
"[",
"]",
"if",
"text",
":",
"lines",
"=",
"text",
".",
"splitlines",
"(",
")",
"for",
"line",
"in",
"lines",
":",
"self",
".",
"_CheckLine",
"(",
"lin... | Passes CLI output through FSM and returns list of tuples.
First tuple is the header, every subsequent tuple is a row.
Args:
text: (str), Text to parse with embedded newlines.
eof: (boolean), Set to False if we are parsing only part of the file.
Suppresses triggering EOF state.
Rai... | [
"Passes",
"CLI",
"output",
"through",
"FSM",
"and",
"returns",
"list",
"of",
"tuples",
"."
] | 63a2aaece33e07947aa80963dca99b893964633b | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L861-L892 | train |
google/textfsm | textfsm/parser.py | TextFSM.ParseTextToDicts | def ParseTextToDicts(self, *args, **kwargs):
"""Calls ParseText and turns the result into list of dicts.
List items are dicts of rows, dict key is column header and value is column
value.
Args:
text: (str), Text to parse with embedded newlines.
eof: (boolean), Set to False if we are parsin... | python | def ParseTextToDicts(self, *args, **kwargs):
"""Calls ParseText and turns the result into list of dicts.
List items are dicts of rows, dict key is column header and value is column
value.
Args:
text: (str), Text to parse with embedded newlines.
eof: (boolean), Set to False if we are parsin... | [
"def",
"ParseTextToDicts",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"result_lists",
"=",
"self",
".",
"ParseText",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"result_dicts",
"=",
"[",
"]",
"for",
"row",
"in",
"result_lists",
":",
... | Calls ParseText and turns the result into list of dicts.
List items are dicts of rows, dict key is column header and value is column
value.
Args:
text: (str), Text to parse with embedded newlines.
eof: (boolean), Set to False if we are parsing only part of the file.
Suppresses trig... | [
"Calls",
"ParseText",
"and",
"turns",
"the",
"result",
"into",
"list",
"of",
"dicts",
"."
] | 63a2aaece33e07947aa80963dca99b893964633b | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L894-L918 | train |
google/textfsm | textfsm/parser.py | TextFSM._AssignVar | def _AssignVar(self, matched, value):
"""Assigns variable into current record from a matched rule.
If a record entry is a list then append, otherwise values are replaced.
Args:
matched: (regexp.match) Named group for each matched value.
value: (str) The matched value.
"""
_value = self... | python | def _AssignVar(self, matched, value):
"""Assigns variable into current record from a matched rule.
If a record entry is a list then append, otherwise values are replaced.
Args:
matched: (regexp.match) Named group for each matched value.
value: (str) The matched value.
"""
_value = self... | [
"def",
"_AssignVar",
"(",
"self",
",",
"matched",
",",
"value",
")",
":",
"_value",
"=",
"self",
".",
"_GetValue",
"(",
"value",
")",
"if",
"_value",
"is",
"not",
"None",
":",
"_value",
".",
"AssignVar",
"(",
"matched",
".",
"group",
"(",
"value",
")... | Assigns variable into current record from a matched rule.
If a record entry is a list then append, otherwise values are replaced.
Args:
matched: (regexp.match) Named group for each matched value.
value: (str) The matched value. | [
"Assigns",
"variable",
"into",
"current",
"record",
"from",
"a",
"matched",
"rule",
"."
] | 63a2aaece33e07947aa80963dca99b893964633b | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L955-L966 | train |
google/textfsm | textfsm/parser.py | TextFSM._Operations | def _Operations(self, rule, line):
"""Operators on the data record.
Operators come in two parts and are a '.' separated pair:
Operators that effect the input line or the current state (line_op).
'Next' Get next input line and restart parsing (default).
'Continue' Keep current input... | python | def _Operations(self, rule, line):
"""Operators on the data record.
Operators come in two parts and are a '.' separated pair:
Operators that effect the input line or the current state (line_op).
'Next' Get next input line and restart parsing (default).
'Continue' Keep current input... | [
"def",
"_Operations",
"(",
"self",
",",
"rule",
",",
"line",
")",
":",
"if",
"rule",
".",
"record_op",
"==",
"'Record'",
":",
"self",
".",
"_AppendRecord",
"(",
")",
"elif",
"rule",
".",
"record_op",
"==",
"'Clear'",
":",
"self",
".",
"_ClearRecord",
"... | Operators on the data record.
Operators come in two parts and are a '.' separated pair:
Operators that effect the input line or the current state (line_op).
'Next' Get next input line and restart parsing (default).
'Continue' Keep current input line and continue resume parsing.
... | [
"Operators",
"on",
"the",
"data",
"record",
"."
] | 63a2aaece33e07947aa80963dca99b893964633b | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L968-L1020 | train |
google/textfsm | textfsm/parser.py | TextFSM.GetValuesByAttrib | def GetValuesByAttrib(self, attribute):
"""Returns the list of values that have a particular attribute."""
if attribute not in self._options_cls.ValidOptions():
raise ValueError("'%s': Not a valid attribute." % attribute)
result = []
for value in self.values:
if attribute in value.OptionNa... | python | def GetValuesByAttrib(self, attribute):
"""Returns the list of values that have a particular attribute."""
if attribute not in self._options_cls.ValidOptions():
raise ValueError("'%s': Not a valid attribute." % attribute)
result = []
for value in self.values:
if attribute in value.OptionNa... | [
"def",
"GetValuesByAttrib",
"(",
"self",
",",
"attribute",
")",
":",
"if",
"attribute",
"not",
"in",
"self",
".",
"_options_cls",
".",
"ValidOptions",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"'%s': Not a valid attribute.\"",
"%",
"attribute",
")",
"result",... | Returns the list of values that have a particular attribute. | [
"Returns",
"the",
"list",
"of",
"values",
"that",
"have",
"a",
"particular",
"attribute",
"."
] | 63a2aaece33e07947aa80963dca99b893964633b | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L1030-L1041 | train |
google/textfsm | textfsm/terminal.py | _AnsiCmd | def _AnsiCmd(command_list):
"""Takes a list of SGR values and formats them as an ANSI escape sequence.
Args:
command_list: List of strings, each string represents an SGR value.
e.g. 'fg_blue', 'bg_yellow'
Returns:
The ANSI escape sequence.
Raises:
ValueError: if a member of command_list d... | python | def _AnsiCmd(command_list):
"""Takes a list of SGR values and formats them as an ANSI escape sequence.
Args:
command_list: List of strings, each string represents an SGR value.
e.g. 'fg_blue', 'bg_yellow'
Returns:
The ANSI escape sequence.
Raises:
ValueError: if a member of command_list d... | [
"def",
"_AnsiCmd",
"(",
"command_list",
")",
":",
"if",
"not",
"isinstance",
"(",
"command_list",
",",
"list",
")",
":",
"raise",
"ValueError",
"(",
"'Invalid list: %s'",
"%",
"command_list",
")",
"for",
"sgr",
"in",
"command_list",
":",
"if",
"sgr",
".",
... | Takes a list of SGR values and formats them as an ANSI escape sequence.
Args:
command_list: List of strings, each string represents an SGR value.
e.g. 'fg_blue', 'bg_yellow'
Returns:
The ANSI escape sequence.
Raises:
ValueError: if a member of command_list does not map to a valid SGR value. | [
"Takes",
"a",
"list",
"of",
"SGR",
"values",
"and",
"formats",
"them",
"as",
"an",
"ANSI",
"escape",
"sequence",
"."
] | 63a2aaece33e07947aa80963dca99b893964633b | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/terminal.py#L115-L138 | train |
google/textfsm | textfsm/terminal.py | TerminalSize | def TerminalSize():
"""Returns terminal length and width as a tuple."""
try:
with open(os.ctermid(), 'r') as tty_instance:
length_width = struct.unpack(
'hh', fcntl.ioctl(tty_instance.fileno(), termios.TIOCGWINSZ, '1234'))
except (IOError, OSError):
try:
length_width = (int(os.enviro... | python | def TerminalSize():
"""Returns terminal length and width as a tuple."""
try:
with open(os.ctermid(), 'r') as tty_instance:
length_width = struct.unpack(
'hh', fcntl.ioctl(tty_instance.fileno(), termios.TIOCGWINSZ, '1234'))
except (IOError, OSError):
try:
length_width = (int(os.enviro... | [
"def",
"TerminalSize",
"(",
")",
":",
"try",
":",
"with",
"open",
"(",
"os",
".",
"ctermid",
"(",
")",
",",
"'r'",
")",
"as",
"tty_instance",
":",
"length_width",
"=",
"struct",
".",
"unpack",
"(",
"'hh'",
",",
"fcntl",
".",
"ioctl",
"(",
"tty_instan... | Returns terminal length and width as a tuple. | [
"Returns",
"terminal",
"length",
"and",
"width",
"as",
"a",
"tuple",
"."
] | 63a2aaece33e07947aa80963dca99b893964633b | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/terminal.py#L170-L182 | train |
google/textfsm | textfsm/terminal.py | main | def main(argv=None):
"""Routine to page text or determine window size via command line."""
if argv is None:
argv = sys.argv
try:
opts, args = getopt.getopt(argv[1:], 'dhs', ['nodelay', 'help', 'size'])
except getopt.error as msg:
raise Usage(msg)
# Print usage and return, regardless of presence... | python | def main(argv=None):
"""Routine to page text or determine window size via command line."""
if argv is None:
argv = sys.argv
try:
opts, args = getopt.getopt(argv[1:], 'dhs', ['nodelay', 'help', 'size'])
except getopt.error as msg:
raise Usage(msg)
# Print usage and return, regardless of presence... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"if",
"argv",
"is",
"None",
":",
"argv",
"=",
"sys",
".",
"argv",
"try",
":",
"opts",
",",
"args",
"=",
"getopt",
".",
"getopt",
"(",
"argv",
"[",
"1",
":",
"]",
",",
"'dhs'",
",",
"[",
"'nod... | Routine to page text or determine window size via command line. | [
"Routine",
"to",
"page",
"text",
"or",
"determine",
"window",
"size",
"via",
"command",
"line",
"."
] | 63a2aaece33e07947aa80963dca99b893964633b | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/terminal.py#L447-L484 | train |
google/textfsm | textfsm/terminal.py | Pager.Reset | def Reset(self):
"""Reset the pager to the top of the text."""
self._displayed = 0
self._currentpagelines = 0
self._lastscroll = 1
self._lines_to_show = self._cli_lines | python | def Reset(self):
"""Reset the pager to the top of the text."""
self._displayed = 0
self._currentpagelines = 0
self._lastscroll = 1
self._lines_to_show = self._cli_lines | [
"def",
"Reset",
"(",
"self",
")",
":",
"self",
".",
"_displayed",
"=",
"0",
"self",
".",
"_currentpagelines",
"=",
"0",
"self",
".",
"_lastscroll",
"=",
"1",
"self",
".",
"_lines_to_show",
"=",
"self",
".",
"_cli_lines"
] | Reset the pager to the top of the text. | [
"Reset",
"the",
"pager",
"to",
"the",
"top",
"of",
"the",
"text",
"."
] | 63a2aaece33e07947aa80963dca99b893964633b | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/terminal.py#L302-L307 | train |
google/textfsm | textfsm/terminal.py | Pager.SetLines | def SetLines(self, lines):
"""Set number of screen lines.
Args:
lines: An int, number of lines. If None, use terminal dimensions.
Raises:
ValueError, TypeError: Not a valid integer representation.
"""
(self._cli_lines, self._cli_cols) = TerminalSize()
if lines:
self._cli_li... | python | def SetLines(self, lines):
"""Set number of screen lines.
Args:
lines: An int, number of lines. If None, use terminal dimensions.
Raises:
ValueError, TypeError: Not a valid integer representation.
"""
(self._cli_lines, self._cli_cols) = TerminalSize()
if lines:
self._cli_li... | [
"def",
"SetLines",
"(",
"self",
",",
"lines",
")",
":",
"(",
"self",
".",
"_cli_lines",
",",
"self",
".",
"_cli_cols",
")",
"=",
"TerminalSize",
"(",
")",
"if",
"lines",
":",
"self",
".",
"_cli_lines",
"=",
"int",
"(",
"lines",
")"
] | Set number of screen lines.
Args:
lines: An int, number of lines. If None, use terminal dimensions.
Raises:
ValueError, TypeError: Not a valid integer representation. | [
"Set",
"number",
"of",
"screen",
"lines",
"."
] | 63a2aaece33e07947aa80963dca99b893964633b | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/terminal.py#L309-L322 | train |
google/textfsm | textfsm/terminal.py | Pager.Page | def Page(self, text=None, show_percent=None):
"""Page text.
Continues to page through any text supplied in the constructor. Also, any
text supplied to this method will be appended to the total text to be
displayed. The method returns when all available text has been displayed to
the user, or the us... | python | def Page(self, text=None, show_percent=None):
"""Page text.
Continues to page through any text supplied in the constructor. Also, any
text supplied to this method will be appended to the total text to be
displayed. The method returns when all available text has been displayed to
the user, or the us... | [
"def",
"Page",
"(",
"self",
",",
"text",
"=",
"None",
",",
"show_percent",
"=",
"None",
")",
":",
"if",
"text",
"is",
"not",
"None",
":",
"self",
".",
"_text",
"+=",
"text",
"if",
"show_percent",
"is",
"None",
":",
"show_percent",
"=",
"text",
"is",
... | Page text.
Continues to page through any text supplied in the constructor. Also, any
text supplied to this method will be appended to the total text to be
displayed. The method returns when all available text has been displayed to
the user, or the user quits the pager.
Args:
text: A string, ... | [
"Page",
"text",
"."
] | 63a2aaece33e07947aa80963dca99b893964633b | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/terminal.py#L329-L383 | train |
google/textfsm | textfsm/terminal.py | Pager._Scroll | def _Scroll(self, lines=None):
"""Set attributes to scroll the buffer correctly.
Args:
lines: An int, number of lines to scroll. If None, scrolls
by the terminal length.
"""
if lines is None:
lines = self._cli_lines
if lines < 0:
self._displayed -= self._cli_lines
s... | python | def _Scroll(self, lines=None):
"""Set attributes to scroll the buffer correctly.
Args:
lines: An int, number of lines to scroll. If None, scrolls
by the terminal length.
"""
if lines is None:
lines = self._cli_lines
if lines < 0:
self._displayed -= self._cli_lines
s... | [
"def",
"_Scroll",
"(",
"self",
",",
"lines",
"=",
"None",
")",
":",
"if",
"lines",
"is",
"None",
":",
"lines",
"=",
"self",
".",
"_cli_lines",
"if",
"lines",
"<",
"0",
":",
"self",
".",
"_displayed",
"-=",
"self",
".",
"_cli_lines",
"self",
".",
"_... | Set attributes to scroll the buffer correctly.
Args:
lines: An int, number of lines to scroll. If None, scrolls
by the terminal length. | [
"Set",
"attributes",
"to",
"scroll",
"the",
"buffer",
"correctly",
"."
] | 63a2aaece33e07947aa80963dca99b893964633b | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/terminal.py#L385-L404 | train |
google/textfsm | textfsm/terminal.py | Pager._AskUser | def _AskUser(self):
"""Prompt the user for the next action.
Returns:
A string, the character entered by the user.
"""
if self._show_percent:
progress = int(self._displayed*100 / (len(self._text.splitlines())))
progress_text = ' (%d%%)' % progress
else:
progress_text = ''
... | python | def _AskUser(self):
"""Prompt the user for the next action.
Returns:
A string, the character entered by the user.
"""
if self._show_percent:
progress = int(self._displayed*100 / (len(self._text.splitlines())))
progress_text = ' (%d%%)' % progress
else:
progress_text = ''
... | [
"def",
"_AskUser",
"(",
"self",
")",
":",
"if",
"self",
".",
"_show_percent",
":",
"progress",
"=",
"int",
"(",
"self",
".",
"_displayed",
"*",
"100",
"/",
"(",
"len",
"(",
"self",
".",
"_text",
".",
"splitlines",
"(",
")",
")",
")",
")",
"progress... | Prompt the user for the next action.
Returns:
A string, the character entered by the user. | [
"Prompt",
"the",
"user",
"for",
"the",
"next",
"action",
"."
] | 63a2aaece33e07947aa80963dca99b893964633b | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/terminal.py#L406-L426 | train |
google/textfsm | textfsm/terminal.py | Pager._GetCh | def _GetCh(self):
"""Read a single character from the user.
Returns:
A string, the character read.
"""
fd = self._tty.fileno()
old = termios.tcgetattr(fd)
try:
tty.setraw(fd)
ch = self._tty.read(1)
# Also support arrow key shortcuts (escape + 2 chars)
if ord(ch) ==... | python | def _GetCh(self):
"""Read a single character from the user.
Returns:
A string, the character read.
"""
fd = self._tty.fileno()
old = termios.tcgetattr(fd)
try:
tty.setraw(fd)
ch = self._tty.read(1)
# Also support arrow key shortcuts (escape + 2 chars)
if ord(ch) ==... | [
"def",
"_GetCh",
"(",
"self",
")",
":",
"fd",
"=",
"self",
".",
"_tty",
".",
"fileno",
"(",
")",
"old",
"=",
"termios",
".",
"tcgetattr",
"(",
"fd",
")",
"try",
":",
"tty",
".",
"setraw",
"(",
"fd",
")",
"ch",
"=",
"self",
".",
"_tty",
".",
"... | Read a single character from the user.
Returns:
A string, the character read. | [
"Read",
"a",
"single",
"character",
"from",
"the",
"user",
"."
] | 63a2aaece33e07947aa80963dca99b893964633b | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/terminal.py#L428-L444 | train |
skyfielders/python-skyfield | skyfield/relativity.py | add_deflection | def add_deflection(position, observer, ephemeris, t,
include_earth_deflection, count=3):
"""Update `position` for how solar system masses will deflect its light.
Given the ICRS `position` [x,y,z] of an object (au) that is being
viewed from the `observer` also expressed as [x,y,z], and gi... | python | def add_deflection(position, observer, ephemeris, t,
include_earth_deflection, count=3):
"""Update `position` for how solar system masses will deflect its light.
Given the ICRS `position` [x,y,z] of an object (au) that is being
viewed from the `observer` also expressed as [x,y,z], and gi... | [
"def",
"add_deflection",
"(",
"position",
",",
"observer",
",",
"ephemeris",
",",
"t",
",",
"include_earth_deflection",
",",
"count",
"=",
"3",
")",
":",
"tlt",
"=",
"length_of",
"(",
"position",
")",
"/",
"C_AUDAY",
"jd_tdb",
"=",
"t",
".",
"tdb",
"ts",... | Update `position` for how solar system masses will deflect its light.
Given the ICRS `position` [x,y,z] of an object (au) that is being
viewed from the `observer` also expressed as [x,y,z], and given an
ephemeris that can be used to determine solar system body positions,
and given the time `t` and Bool... | [
"Update",
"position",
"for",
"how",
"solar",
"system",
"masses",
"will",
"deflect",
"its",
"light",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/relativity.py#L23-L97 | train |
skyfielders/python-skyfield | skyfield/relativity.py | _add_deflection | def _add_deflection(position, observer, deflector, rmass):
"""Correct a position vector for how one particular mass deflects light.
Given the ICRS `position` [x,y,z] of an object (AU) together with
the positions of an `observer` and a `deflector` of reciprocal mass
`rmass`, this function updates `posit... | python | def _add_deflection(position, observer, deflector, rmass):
"""Correct a position vector for how one particular mass deflects light.
Given the ICRS `position` [x,y,z] of an object (AU) together with
the positions of an `observer` and a `deflector` of reciprocal mass
`rmass`, this function updates `posit... | [
"def",
"_add_deflection",
"(",
"position",
",",
"observer",
",",
"deflector",
",",
"rmass",
")",
":",
"pq",
"=",
"observer",
"+",
"position",
"-",
"deflector",
"pe",
"=",
"observer",
"-",
"deflector",
"pmag",
"=",
"length_of",
"(",
"position",
")",
"qmag",... | Correct a position vector for how one particular mass deflects light.
Given the ICRS `position` [x,y,z] of an object (AU) together with
the positions of an `observer` and a `deflector` of reciprocal mass
`rmass`, this function updates `position` in-place to show how much
the presence of the deflector w... | [
"Correct",
"a",
"position",
"vector",
"for",
"how",
"one",
"particular",
"mass",
"deflects",
"light",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/relativity.py#L121-L166 | train |
skyfielders/python-skyfield | skyfield/relativity.py | add_aberration | def add_aberration(position, velocity, light_time):
"""Correct a relative position vector for aberration of light.
Given the relative `position` [x,y,z] of an object (AU) from a
particular observer, the `velocity` [dx,dy,dz] at which the observer
is traveling (AU/day), and the light propagation delay `... | python | def add_aberration(position, velocity, light_time):
"""Correct a relative position vector for aberration of light.
Given the relative `position` [x,y,z] of an object (AU) from a
particular observer, the `velocity` [dx,dy,dz] at which the observer
is traveling (AU/day), and the light propagation delay `... | [
"def",
"add_aberration",
"(",
"position",
",",
"velocity",
",",
"light_time",
")",
":",
"p1mag",
"=",
"light_time",
"*",
"C_AUDAY",
"vemag",
"=",
"length_of",
"(",
"velocity",
")",
"beta",
"=",
"vemag",
"/",
"C_AUDAY",
"dot",
"=",
"dots",
"(",
"position",
... | Correct a relative position vector for aberration of light.
Given the relative `position` [x,y,z] of an object (AU) from a
particular observer, the `velocity` [dx,dy,dz] at which the observer
is traveling (AU/day), and the light propagation delay `light_time`
to the object (days), this function updates... | [
"Correct",
"a",
"relative",
"position",
"vector",
"for",
"aberration",
"of",
"light",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/relativity.py#L170-L193 | train |
skyfielders/python-skyfield | skyfield/jpllib.py | _center | def _center(code, segment_dict):
"""Starting with `code`, follow segments from target to center."""
while code in segment_dict:
segment = segment_dict[code]
yield segment
code = segment.center | python | def _center(code, segment_dict):
"""Starting with `code`, follow segments from target to center."""
while code in segment_dict:
segment = segment_dict[code]
yield segment
code = segment.center | [
"def",
"_center",
"(",
"code",
",",
"segment_dict",
")",
":",
"while",
"code",
"in",
"segment_dict",
":",
"segment",
"=",
"segment_dict",
"[",
"code",
"]",
"yield",
"segment",
"code",
"=",
"segment",
".",
"center"
] | Starting with `code`, follow segments from target to center. | [
"Starting",
"with",
"code",
"follow",
"segments",
"from",
"target",
"to",
"center",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/jpllib.py#L217-L222 | train |
skyfielders/python-skyfield | skyfield/jpllib.py | SpiceKernel.names | def names(self):
"""Return all target names that are valid with this kernel.
>>> pprint(planets.names())
{0: ['SOLAR_SYSTEM_BARYCENTER', 'SSB', 'SOLAR SYSTEM BARYCENTER'],
1: ['MERCURY_BARYCENTER', 'MERCURY BARYCENTER'],
2: ['VENUS_BARYCENTER', 'VENUS BARYCENTER'],
3:... | python | def names(self):
"""Return all target names that are valid with this kernel.
>>> pprint(planets.names())
{0: ['SOLAR_SYSTEM_BARYCENTER', 'SSB', 'SOLAR SYSTEM BARYCENTER'],
1: ['MERCURY_BARYCENTER', 'MERCURY BARYCENTER'],
2: ['VENUS_BARYCENTER', 'VENUS BARYCENTER'],
3:... | [
"def",
"names",
"(",
"self",
")",
":",
"d",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"code",
",",
"name",
"in",
"target_name_pairs",
":",
"if",
"code",
"in",
"self",
".",
"codes",
":",
"d",
"[",
"code",
"]",
".",
"append",
"(",
"name",
")",
"... | Return all target names that are valid with this kernel.
>>> pprint(planets.names())
{0: ['SOLAR_SYSTEM_BARYCENTER', 'SSB', 'SOLAR SYSTEM BARYCENTER'],
1: ['MERCURY_BARYCENTER', 'MERCURY BARYCENTER'],
2: ['VENUS_BARYCENTER', 'VENUS BARYCENTER'],
3: ['EARTH_BARYCENTER',
... | [
"Return",
"all",
"target",
"names",
"that",
"are",
"valid",
"with",
"this",
"kernel",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/jpllib.py#L106-L126 | train |
skyfielders/python-skyfield | skyfield/jpllib.py | SpiceKernel.decode | def decode(self, name):
"""Translate a target name into its integer code.
>>> planets.decode('Venus')
299
Raises ``ValueError`` if you supply an unknown name, or
``KeyError`` if the target is missing from this kernel. You can
supply an integer code if you already have ... | python | def decode(self, name):
"""Translate a target name into its integer code.
>>> planets.decode('Venus')
299
Raises ``ValueError`` if you supply an unknown name, or
``KeyError`` if the target is missing from this kernel. You can
supply an integer code if you already have ... | [
"def",
"decode",
"(",
"self",
",",
"name",
")",
":",
"if",
"isinstance",
"(",
"name",
",",
"int",
")",
":",
"code",
"=",
"name",
"else",
":",
"name",
"=",
"name",
".",
"upper",
"(",
")",
"code",
"=",
"_targets",
".",
"get",
"(",
"name",
")",
"i... | Translate a target name into its integer code.
>>> planets.decode('Venus')
299
Raises ``ValueError`` if you supply an unknown name, or
``KeyError`` if the target is missing from this kernel. You can
supply an integer code if you already have one and just want to
check ... | [
"Translate",
"a",
"target",
"name",
"into",
"its",
"integer",
"code",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/jpllib.py#L128-L152 | train |
skyfielders/python-skyfield | skyfield/iokit.py | _search | def _search(mapping, filename):
"""Search a Loader data structure for a filename."""
result = mapping.get(filename)
if result is not None:
return result
name, ext = os.path.splitext(filename)
result = mapping.get(ext)
if result is not None:
for pattern, result2 in result:
... | python | def _search(mapping, filename):
"""Search a Loader data structure for a filename."""
result = mapping.get(filename)
if result is not None:
return result
name, ext = os.path.splitext(filename)
result = mapping.get(ext)
if result is not None:
for pattern, result2 in result:
... | [
"def",
"_search",
"(",
"mapping",
",",
"filename",
")",
":",
"result",
"=",
"mapping",
".",
"get",
"(",
"filename",
")",
"if",
"result",
"is",
"not",
"None",
":",
"return",
"result",
"name",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
... | Search a Loader data structure for a filename. | [
"Search",
"a",
"Loader",
"data",
"structure",
"for",
"a",
"filename",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/iokit.py#L288-L299 | train |
skyfielders/python-skyfield | skyfield/iokit.py | load_file | def load_file(path):
"""Open a file on your local drive, using its extension to guess its type.
This routine only works on ``.bsp`` ephemeris files right now, but
will gain support for additional file types in the future. ::
from skyfield.api import load_file
planets = load_file('~/Downloa... | python | def load_file(path):
"""Open a file on your local drive, using its extension to guess its type.
This routine only works on ``.bsp`` ephemeris files right now, but
will gain support for additional file types in the future. ::
from skyfield.api import load_file
planets = load_file('~/Downloa... | [
"def",
"load_file",
"(",
"path",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
"base",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"path",
")",
"if",
"ext",
"==",
"'.bsp'",
":",
"return",
"SpiceKernel"... | Open a file on your local drive, using its extension to guess its type.
This routine only works on ``.bsp`` ephemeris files right now, but
will gain support for additional file types in the future. ::
from skyfield.api import load_file
planets = load_file('~/Downloads/de421.bsp') | [
"Open",
"a",
"file",
"on",
"your",
"local",
"drive",
"using",
"its",
"extension",
"to",
"guess",
"its",
"type",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/iokit.py#L302-L316 | train |
skyfielders/python-skyfield | skyfield/iokit.py | parse_deltat_data | def parse_deltat_data(fileobj):
"""Parse the United States Naval Observatory ``deltat.data`` file.
Each line file gives the date and the value of Delta T::
2016 2 1 68.1577
This function returns a 2xN array of raw Julian dates and matching
Delta T values.
"""
array = np.loadtxt(fileob... | python | def parse_deltat_data(fileobj):
"""Parse the United States Naval Observatory ``deltat.data`` file.
Each line file gives the date and the value of Delta T::
2016 2 1 68.1577
This function returns a 2xN array of raw Julian dates and matching
Delta T values.
"""
array = np.loadtxt(fileob... | [
"def",
"parse_deltat_data",
"(",
"fileobj",
")",
":",
"array",
"=",
"np",
".",
"loadtxt",
"(",
"fileobj",
")",
"year",
",",
"month",
",",
"day",
"=",
"array",
"[",
"-",
"1",
",",
":",
"3",
"]",
".",
"astype",
"(",
"int",
")",
"expiration_date",
"="... | Parse the United States Naval Observatory ``deltat.data`` file.
Each line file gives the date and the value of Delta T::
2016 2 1 68.1577
This function returns a 2xN array of raw Julian dates and matching
Delta T values. | [
"Parse",
"the",
"United",
"States",
"Naval",
"Observatory",
"deltat",
".",
"data",
"file",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/iokit.py#L319-L335 | train |
skyfielders/python-skyfield | skyfield/iokit.py | parse_deltat_preds | def parse_deltat_preds(fileobj):
"""Parse the United States Naval Observatory ``deltat.preds`` file.
The old format supplies a floating point year, the value of Delta T,
and one or two other fields::
2015.75 67.97 0.210 0.02
The new format adds a modified Julian day as ... | python | def parse_deltat_preds(fileobj):
"""Parse the United States Naval Observatory ``deltat.preds`` file.
The old format supplies a floating point year, the value of Delta T,
and one or two other fields::
2015.75 67.97 0.210 0.02
The new format adds a modified Julian day as ... | [
"def",
"parse_deltat_preds",
"(",
"fileobj",
")",
":",
"lines",
"=",
"iter",
"(",
"fileobj",
")",
"header",
"=",
"next",
"(",
"lines",
")",
"if",
"header",
".",
"startswith",
"(",
"b'YEAR'",
")",
":",
"next",
"(",
"lines",
")",
"year_float",
",",
"delt... | Parse the United States Naval Observatory ``deltat.preds`` file.
The old format supplies a floating point year, the value of Delta T,
and one or two other fields::
2015.75 67.97 0.210 0.02
The new format adds a modified Julian day as the first field:
58484.000 2019.00... | [
"Parse",
"the",
"United",
"States",
"Naval",
"Observatory",
"deltat",
".",
"preds",
"file",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/iokit.py#L338-L369 | train |
skyfielders/python-skyfield | skyfield/iokit.py | parse_leap_seconds | def parse_leap_seconds(fileobj):
"""Parse the IERS file ``Leap_Second.dat``.
The leap dates array can be searched with::
index = np.searchsorted(leap_dates, jd, 'right')
The resulting index allows (TAI - UTC) to be fetched with::
offset = leap_offsets[index]
"""
lines = iter(fil... | python | def parse_leap_seconds(fileobj):
"""Parse the IERS file ``Leap_Second.dat``.
The leap dates array can be searched with::
index = np.searchsorted(leap_dates, jd, 'right')
The resulting index allows (TAI - UTC) to be fetched with::
offset = leap_offsets[index]
"""
lines = iter(fil... | [
"def",
"parse_leap_seconds",
"(",
"fileobj",
")",
":",
"lines",
"=",
"iter",
"(",
"fileobj",
")",
"for",
"line",
"in",
"lines",
":",
"if",
"line",
".",
"startswith",
"(",
"b'# File expires on'",
")",
":",
"break",
"else",
":",
"raise",
"ValueError",
"(",
... | Parse the IERS file ``Leap_Second.dat``.
The leap dates array can be searched with::
index = np.searchsorted(leap_dates, jd, 'right')
The resulting index allows (TAI - UTC) to be fetched with::
offset = leap_offsets[index] | [
"Parse",
"the",
"IERS",
"file",
"Leap_Second",
".",
"dat",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/iokit.py#L371-L412 | train |
skyfielders/python-skyfield | skyfield/iokit.py | parse_tle | def parse_tle(fileobj):
"""Parse a file of TLE satellite element sets.
Builds an Earth satellite from each pair of adjacent lines in the
file that start with "1 " and "2 " and have 69 or more characters
each. If the preceding line is exactly 24 characters long, then it
is parsed as the satellite's... | python | def parse_tle(fileobj):
"""Parse a file of TLE satellite element sets.
Builds an Earth satellite from each pair of adjacent lines in the
file that start with "1 " and "2 " and have 69 or more characters
each. If the preceding line is exactly 24 characters long, then it
is parsed as the satellite's... | [
"def",
"parse_tle",
"(",
"fileobj",
")",
":",
"b0",
"=",
"b1",
"=",
"b''",
"for",
"b2",
"in",
"fileobj",
":",
"if",
"(",
"b1",
".",
"startswith",
"(",
"b'1 '",
")",
"and",
"len",
"(",
"b1",
")",
">=",
"69",
"and",
"b2",
".",
"startswith",
"(",
... | Parse a file of TLE satellite element sets.
Builds an Earth satellite from each pair of adjacent lines in the
file that start with "1 " and "2 " and have 69 or more characters
each. If the preceding line is exactly 24 characters long, then it
is parsed as the satellite's name. For each satellite foun... | [
"Parse",
"a",
"file",
"of",
"TLE",
"satellite",
"element",
"sets",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/iokit.py#L415-L461 | train |
skyfielders/python-skyfield | skyfield/iokit.py | download | def download(url, path, verbose=None, blocksize=128*1024):
"""Download a file from a URL, possibly displaying a progress bar.
Saves the output to the file named by `path`. If the URL cannot be
downloaded or the file cannot be written, an IOError is raised.
Normally, if the standard error output is a ... | python | def download(url, path, verbose=None, blocksize=128*1024):
"""Download a file from a URL, possibly displaying a progress bar.
Saves the output to the file named by `path`. If the URL cannot be
downloaded or the file cannot be written, an IOError is raised.
Normally, if the standard error output is a ... | [
"def",
"download",
"(",
"url",
",",
"path",
",",
"verbose",
"=",
"None",
",",
"blocksize",
"=",
"128",
"*",
"1024",
")",
":",
"tempname",
"=",
"path",
"+",
"'.download'",
"try",
":",
"connection",
"=",
"urlopen",
"(",
"url",
")",
"except",
"Exception",... | Download a file from a URL, possibly displaying a progress bar.
Saves the output to the file named by `path`. If the URL cannot be
downloaded or the file cannot be written, an IOError is raised.
Normally, if the standard error output is a terminal, then a
progress bar is displayed to keep the user en... | [
"Download",
"a",
"file",
"from",
"a",
"URL",
"possibly",
"displaying",
"a",
"progress",
"bar",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/iokit.py#L464-L536 | train |
skyfielders/python-skyfield | skyfield/iokit.py | Loader.tle | def tle(self, url, reload=False, filename=None):
"""Load and parse a satellite TLE file.
Given a URL or a local path, this loads a file of three-line records in
the common Celestrak file format, or two-line records like those from
space-track.org. For a three-line element set, each firs... | python | def tle(self, url, reload=False, filename=None):
"""Load and parse a satellite TLE file.
Given a URL or a local path, this loads a file of three-line records in
the common Celestrak file format, or two-line records like those from
space-track.org. For a three-line element set, each firs... | [
"def",
"tle",
"(",
"self",
",",
"url",
",",
"reload",
"=",
"False",
",",
"filename",
"=",
"None",
")",
":",
"d",
"=",
"{",
"}",
"with",
"self",
".",
"open",
"(",
"url",
",",
"reload",
"=",
"reload",
",",
"filename",
"=",
"filename",
")",
"as",
... | Load and parse a satellite TLE file.
Given a URL or a local path, this loads a file of three-line records in
the common Celestrak file format, or two-line records like those from
space-track.org. For a three-line element set, each first line gives
the name of a satellite and the followi... | [
"Load",
"and",
"parse",
"a",
"satellite",
"TLE",
"file",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/iokit.py#L199-L224 | train |
skyfielders/python-skyfield | skyfield/iokit.py | Loader.open | def open(self, url, mode='rb', reload=False, filename=None):
"""Open a file, downloading it first if it does not yet exist.
Unlike when you call a loader directly like ``my_loader()``,
this ``my_loader.open()`` method does not attempt to parse or
interpret the file; it simply returns an... | python | def open(self, url, mode='rb', reload=False, filename=None):
"""Open a file, downloading it first if it does not yet exist.
Unlike when you call a loader directly like ``my_loader()``,
this ``my_loader.open()`` method does not attempt to parse or
interpret the file; it simply returns an... | [
"def",
"open",
"(",
"self",
",",
"url",
",",
"mode",
"=",
"'rb'",
",",
"reload",
"=",
"False",
",",
"filename",
"=",
"None",
")",
":",
"if",
"'://'",
"not",
"in",
"url",
":",
"path_that_might_be_relative",
"=",
"url",
"path",
"=",
"os",
".",
"path",
... | Open a file, downloading it first if it does not yet exist.
Unlike when you call a loader directly like ``my_loader()``,
this ``my_loader.open()`` method does not attempt to parse or
interpret the file; it simply returns an open file object.
The ``url`` can be either an external URL, o... | [
"Open",
"a",
"file",
"downloading",
"it",
"first",
"if",
"it",
"does",
"not",
"yet",
"exist",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/iokit.py#L226-L256 | train |
skyfielders/python-skyfield | skyfield/iokit.py | Loader.timescale | def timescale(self, delta_t=None):
"""Open or download three time scale files, returning a `Timescale`.
This method is how most Skyfield users build a `Timescale`
object, which is necessary for building specific `Time` objects
that name specific moments.
This will open or downl... | python | def timescale(self, delta_t=None):
"""Open or download three time scale files, returning a `Timescale`.
This method is how most Skyfield users build a `Timescale`
object, which is necessary for building specific `Time` objects
that name specific moments.
This will open or downl... | [
"def",
"timescale",
"(",
"self",
",",
"delta_t",
"=",
"None",
")",
":",
"if",
"delta_t",
"is",
"not",
"None",
":",
"delta_t_recent",
"=",
"np",
".",
"array",
"(",
"(",
"(",
"-",
"1e99",
",",
"1e99",
")",
",",
"(",
"delta_t",
",",
"delta_t",
")",
... | Open or download three time scale files, returning a `Timescale`.
This method is how most Skyfield users build a `Timescale`
object, which is necessary for building specific `Time` objects
that name specific moments.
This will open or download the three files that Skyfield needs
... | [
"Open",
"or",
"download",
"three",
"time",
"scale",
"files",
"returning",
"a",
"Timescale",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/iokit.py#L258-L281 | train |
skyfielders/python-skyfield | skyfield/contrib/iosurvey.py | get_summary | def get_summary(url, spk=True):
''' simple function to retrieve the header of a BSP file and return SPK object'''
# connect to file at URL
bspurl = urllib2.urlopen(url)
# retrieve the "tip" of a file at URL
bsptip = bspurl.read(10**5) # first 100kB
# save data in fake file object (in-memory)
... | python | def get_summary(url, spk=True):
''' simple function to retrieve the header of a BSP file and return SPK object'''
# connect to file at URL
bspurl = urllib2.urlopen(url)
# retrieve the "tip" of a file at URL
bsptip = bspurl.read(10**5) # first 100kB
# save data in fake file object (in-memory)
... | [
"def",
"get_summary",
"(",
"url",
",",
"spk",
"=",
"True",
")",
":",
"bspurl",
"=",
"urllib2",
".",
"urlopen",
"(",
"url",
")",
"bsptip",
"=",
"bspurl",
".",
"read",
"(",
"10",
"**",
"5",
")",
"bspstr",
"=",
"StringIO",
"(",
"bsptip",
")",
"daf",
... | simple function to retrieve the header of a BSP file and return SPK object | [
"simple",
"function",
"to",
"retrieve",
"the",
"header",
"of",
"a",
"BSP",
"file",
"and",
"return",
"SPK",
"object"
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/contrib/iosurvey.py#L11-L29 | train |
skyfielders/python-skyfield | skyfield/vectorlib.py | _correct_for_light_travel_time | def _correct_for_light_travel_time(observer, target):
"""Return a light-time corrected astrometric position and velocity.
Given an `observer` that is a `Barycentric` position somewhere in
the solar system, compute where in the sky they will see the body
`target`, by computing the light-time between the... | python | def _correct_for_light_travel_time(observer, target):
"""Return a light-time corrected astrometric position and velocity.
Given an `observer` that is a `Barycentric` position somewhere in
the solar system, compute where in the sky they will see the body
`target`, by computing the light-time between the... | [
"def",
"_correct_for_light_travel_time",
"(",
"observer",
",",
"target",
")",
":",
"t",
"=",
"observer",
".",
"t",
"ts",
"=",
"t",
".",
"ts",
"cposition",
"=",
"observer",
".",
"position",
".",
"au",
"cvelocity",
"=",
"observer",
".",
"velocity",
".",
"a... | Return a light-time corrected astrometric position and velocity.
Given an `observer` that is a `Barycentric` position somewhere in
the solar system, compute where in the sky they will see the body
`target`, by computing the light-time between them and figuring out
where `target` was back when the light... | [
"Return",
"a",
"light",
"-",
"time",
"corrected",
"astrometric",
"position",
"and",
"velocity",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/vectorlib.py#L201-L230 | train |
skyfielders/python-skyfield | skyfield/vectorlib.py | VectorFunction.at | def at(self, t):
"""At time ``t``, compute the target's position relative to the center.
If ``t`` is an array of times, then the returned position object
will specify as many positions as there were times. The kind of
position returned depends on the value of the ``center``
att... | python | def at(self, t):
"""At time ``t``, compute the target's position relative to the center.
If ``t`` is an array of times, then the returned position object
will specify as many positions as there were times. The kind of
position returned depends on the value of the ``center``
att... | [
"def",
"at",
"(",
"self",
",",
"t",
")",
":",
"if",
"not",
"isinstance",
"(",
"t",
",",
"Time",
")",
":",
"raise",
"ValueError",
"(",
"'please provide the at() method with a Time'",
"' instance as its argument, instead of the'",
"' value {0!r}'",
".",
"format",
"(",... | At time ``t``, compute the target's position relative to the center.
If ``t`` is an array of times, then the returned position object
will specify as many positions as there were times. The kind of
position returned depends on the value of the ``center``
attribute:
* Solar Sys... | [
"At",
"time",
"t",
"compute",
"the",
"target",
"s",
"position",
"relative",
"to",
"the",
"center",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/vectorlib.py#L54-L82 | train |
skyfielders/python-skyfield | skyfield/timelib.py | _to_array | def _to_array(value):
"""When `value` is a plain Python sequence, return it as a NumPy array."""
if hasattr(value, 'shape'):
return value
elif hasattr(value, '__len__'):
return array(value)
else:
return float_(value) | python | def _to_array(value):
"""When `value` is a plain Python sequence, return it as a NumPy array."""
if hasattr(value, 'shape'):
return value
elif hasattr(value, '__len__'):
return array(value)
else:
return float_(value) | [
"def",
"_to_array",
"(",
"value",
")",
":",
"if",
"hasattr",
"(",
"value",
",",
"'shape'",
")",
":",
"return",
"value",
"elif",
"hasattr",
"(",
"value",
",",
"'__len__'",
")",
":",
"return",
"array",
"(",
"value",
")",
"else",
":",
"return",
"float_",
... | When `value` is a plain Python sequence, return it as a NumPy array. | [
"When",
"value",
"is",
"a",
"plain",
"Python",
"sequence",
"return",
"it",
"as",
"a",
"NumPy",
"array",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L40-L47 | train |
skyfielders/python-skyfield | skyfield/timelib.py | julian_day | def julian_day(year, month=1, day=1):
"""Given a proleptic Gregorian calendar date, return a Julian day int."""
janfeb = month < 3
return (day
+ 1461 * (year + 4800 - janfeb) // 4
+ 367 * (month - 2 + janfeb * 12) // 12
- 3 * ((year + 4900 - janfeb) // 100) // 4
... | python | def julian_day(year, month=1, day=1):
"""Given a proleptic Gregorian calendar date, return a Julian day int."""
janfeb = month < 3
return (day
+ 1461 * (year + 4800 - janfeb) // 4
+ 367 * (month - 2 + janfeb * 12) // 12
- 3 * ((year + 4900 - janfeb) // 100) // 4
... | [
"def",
"julian_day",
"(",
"year",
",",
"month",
"=",
"1",
",",
"day",
"=",
"1",
")",
":",
"janfeb",
"=",
"month",
"<",
"3",
"return",
"(",
"day",
"+",
"1461",
"*",
"(",
"year",
"+",
"4800",
"-",
"janfeb",
")",
"//",
"4",
"+",
"367",
"*",
"(",... | Given a proleptic Gregorian calendar date, return a Julian day int. | [
"Given",
"a",
"proleptic",
"Gregorian",
"calendar",
"date",
"return",
"a",
"Julian",
"day",
"int",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L700-L707 | train |
skyfielders/python-skyfield | skyfield/timelib.py | julian_date | def julian_date(year, month=1, day=1, hour=0, minute=0, second=0.0):
"""Given a proleptic Gregorian calendar date, return a Julian date float."""
return julian_day(year, month, day) - 0.5 + (
second + minute * 60.0 + hour * 3600.0) / DAY_S | python | def julian_date(year, month=1, day=1, hour=0, minute=0, second=0.0):
"""Given a proleptic Gregorian calendar date, return a Julian date float."""
return julian_day(year, month, day) - 0.5 + (
second + minute * 60.0 + hour * 3600.0) / DAY_S | [
"def",
"julian_date",
"(",
"year",
",",
"month",
"=",
"1",
",",
"day",
"=",
"1",
",",
"hour",
"=",
"0",
",",
"minute",
"=",
"0",
",",
"second",
"=",
"0.0",
")",
":",
"return",
"julian_day",
"(",
"year",
",",
"month",
",",
"day",
")",
"-",
"0.5"... | Given a proleptic Gregorian calendar date, return a Julian date float. | [
"Given",
"a",
"proleptic",
"Gregorian",
"calendar",
"date",
"return",
"a",
"Julian",
"date",
"float",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L709-L712 | train |
skyfielders/python-skyfield | skyfield/timelib.py | tdb_minus_tt | def tdb_minus_tt(jd_tdb):
"""Computes how far TDB is in advance of TT, given TDB.
Given that the two time scales never diverge by more than 2ms, TT
can also be given as the argument to perform the conversion in the
other direction.
"""
t = (jd_tdb - T0) / 36525.0
# USNO Circular 179, eq. ... | python | def tdb_minus_tt(jd_tdb):
"""Computes how far TDB is in advance of TT, given TDB.
Given that the two time scales never diverge by more than 2ms, TT
can also be given as the argument to perform the conversion in the
other direction.
"""
t = (jd_tdb - T0) / 36525.0
# USNO Circular 179, eq. ... | [
"def",
"tdb_minus_tt",
"(",
"jd_tdb",
")",
":",
"t",
"=",
"(",
"jd_tdb",
"-",
"T0",
")",
"/",
"36525.0",
"return",
"(",
"0.001657",
"*",
"sin",
"(",
"628.3076",
"*",
"t",
"+",
"6.2401",
")",
"+",
"0.000022",
"*",
"sin",
"(",
"575.3385",
"*",
"t",
... | Computes how far TDB is in advance of TT, given TDB.
Given that the two time scales never diverge by more than 2ms, TT
can also be given as the argument to perform the conversion in the
other direction. | [
"Computes",
"how",
"far",
"TDB",
"is",
"in",
"advance",
"of",
"TT",
"given",
"TDB",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L752-L769 | train |
skyfielders/python-skyfield | skyfield/timelib.py | interpolate_delta_t | def interpolate_delta_t(delta_t_table, tt):
"""Return interpolated Delta T values for the times in `tt`.
The 2xN table should provide TT values as element 0 and
corresponding Delta T values for element 1. For times outside the
range of the table, a long-term formula is used instead.
"""
tt_ar... | python | def interpolate_delta_t(delta_t_table, tt):
"""Return interpolated Delta T values for the times in `tt`.
The 2xN table should provide TT values as element 0 and
corresponding Delta T values for element 1. For times outside the
range of the table, a long-term formula is used instead.
"""
tt_ar... | [
"def",
"interpolate_delta_t",
"(",
"delta_t_table",
",",
"tt",
")",
":",
"tt_array",
",",
"delta_t_array",
"=",
"delta_t_table",
"delta_t",
"=",
"_to_array",
"(",
"interp",
"(",
"tt",
",",
"tt_array",
",",
"delta_t_array",
",",
"nan",
",",
"nan",
")",
")",
... | Return interpolated Delta T values for the times in `tt`.
The 2xN table should provide TT values as element 0 and
corresponding Delta T values for element 1. For times outside the
range of the table, a long-term formula is used instead. | [
"Return",
"interpolated",
"Delta",
"T",
"values",
"for",
"the",
"times",
"in",
"tt",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L771-L790 | train |
skyfielders/python-skyfield | skyfield/timelib.py | build_delta_t_table | def build_delta_t_table(delta_t_recent):
"""Build a table for interpolating Delta T.
Given a 2xN array of recent Delta T values, whose element 0 is a
sorted array of TT Julian dates and element 1 is Delta T values,
this routine returns a more complete table by prepending two
built-in data sources t... | python | def build_delta_t_table(delta_t_recent):
"""Build a table for interpolating Delta T.
Given a 2xN array of recent Delta T values, whose element 0 is a
sorted array of TT Julian dates and element 1 is Delta T values,
this routine returns a more complete table by prepending two
built-in data sources t... | [
"def",
"build_delta_t_table",
"(",
"delta_t_recent",
")",
":",
"ancient",
"=",
"load_bundled_npy",
"(",
"'morrison_stephenson_deltat.npy'",
")",
"historic",
"=",
"load_bundled_npy",
"(",
"'historic_deltat.npy'",
")",
"historic_start_time",
"=",
"historic",
"[",
"0",
","... | Build a table for interpolating Delta T.
Given a 2xN array of recent Delta T values, whose element 0 is a
sorted array of TT Julian dates and element 1 is Delta T values,
this routine returns a more complete table by prepending two
built-in data sources that ship with Skyfield as pre-built arrays:
... | [
"Build",
"a",
"table",
"for",
"interpolating",
"Delta",
"T",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L803-L839 | train |
skyfielders/python-skyfield | skyfield/timelib.py | Timescale.utc | def utc(self, year, month=1, day=1, hour=0, minute=0, second=0.0):
"""Build a `Time` from a UTC calendar date.
You can either specify the date as separate components, or
provide a time zone aware Python datetime. The following two
calls are equivalent (the ``utc`` time zone object can ... | python | def utc(self, year, month=1, day=1, hour=0, minute=0, second=0.0):
"""Build a `Time` from a UTC calendar date.
You can either specify the date as separate components, or
provide a time zone aware Python datetime. The following two
calls are equivalent (the ``utc`` time zone object can ... | [
"def",
"utc",
"(",
"self",
",",
"year",
",",
"month",
"=",
"1",
",",
"day",
"=",
"1",
",",
"hour",
"=",
"0",
",",
"minute",
"=",
"0",
",",
"second",
"=",
"0.0",
")",
":",
"if",
"isinstance",
"(",
"year",
",",
"datetime",
")",
":",
"dt",
"=",
... | Build a `Time` from a UTC calendar date.
You can either specify the date as separate components, or
provide a time zone aware Python datetime. The following two
calls are equivalent (the ``utc`` time zone object can be
imported from the ``skyfield.api`` module, or from ``pytz`` if
... | [
"Build",
"a",
"Time",
"from",
"a",
"UTC",
"calendar",
"date",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L91-L127 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.