idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
35,800 | def confirm_redirect_uri ( self , client_id , code , redirect_uri , client , request , * args , ** kwargs ) : raise NotImplementedError ( 'Subclasses must implement this method.' ) | Ensure that the authorization process represented by this authorization code began with this redirect_uri . |
35,801 | def save_token ( self , token , request , * args , ** kwargs ) : return self . save_bearer_token ( token , request , * args , ** kwargs ) | Persist the token with a token type specific method . |
35,802 | def encode_params_utf8 ( params ) : encoded = [ ] for k , v in params : encoded . append ( ( k . encode ( 'utf-8' ) if isinstance ( k , unicode_type ) else k , v . encode ( 'utf-8' ) if isinstance ( v , unicode_type ) else v ) ) return encoded | Ensures that all parameters in a list of 2 - element tuples are encoded to bytestrings using UTF - 8 |
35,803 | def decode_params_utf8 ( params ) : decoded = [ ] for k , v in params : decoded . append ( ( k . decode ( 'utf-8' ) if isinstance ( k , bytes ) else k , v . decode ( 'utf-8' ) if isinstance ( v , bytes ) else v ) ) return decoded | Ensures that all parameters in a list of 2 - element tuples are decoded to unicode using UTF - 8 . |
35,804 | def urldecode ( query ) : if query and not set ( query ) <= urlencoded : error = ( "Error trying to decode a non urlencoded string. " "Found invalid characters: %s " "in the string: '%s'. " "Please ensure the request/response body is " "x-www-form-urlencoded." ) raise ValueError ( error % ( set ( query ) - urlencoded ,... | Decode a query string in x - www - form - urlencoded format into a sequence of two - element tuples . |
35,805 | def extract_params ( raw ) : if isinstance ( raw , ( bytes , unicode_type ) ) : try : params = urldecode ( raw ) except ValueError : params = None elif hasattr ( raw , '__iter__' ) : try : dict ( raw ) except ValueError : params = None except TypeError : params = None else : params = list ( raw . items ( ) if isinstanc... | Extract parameters and return them as a list of 2 - tuples . |
35,806 | def generate_token ( length = 30 , chars = UNICODE_ASCII_CHARACTER_SET ) : rand = SystemRandom ( ) return '' . join ( rand . choice ( chars ) for x in range ( length ) ) | Generates a non - guessable OAuth token |
35,807 | def add_params_to_qs ( query , params ) : if isinstance ( params , dict ) : params = params . items ( ) queryparams = urlparse . parse_qsl ( query , keep_blank_values = True ) queryparams . extend ( params ) return urlencode ( queryparams ) | Extend a query with a list of two - tuples . |
35,808 | def add_params_to_uri ( uri , params , fragment = False ) : sch , net , path , par , query , fra = urlparse . urlparse ( uri ) if fragment : fra = add_params_to_qs ( fra , params ) else : query = add_params_to_qs ( query , params ) return urlparse . urlunparse ( ( sch , net , path , par , query , fra ) ) | Add a list of two - tuples to the uri query components . |
35,809 | def to_unicode ( data , encoding = 'UTF-8' ) : if isinstance ( data , unicode_type ) : return data if isinstance ( data , bytes ) : return unicode_type ( data , encoding = encoding ) if hasattr ( data , '__iter__' ) : try : dict ( data ) except TypeError : pass except ValueError : return ( to_unicode ( i , encoding ) f... | Convert a number of different types of objects to unicode . |
35,810 | def _append_params ( oauth_params , params ) : merged = list ( params ) merged . extend ( oauth_params ) merged . sort ( key = lambda i : i [ 0 ] . startswith ( 'oauth_' ) ) return merged | Append OAuth params to an existing set of parameters . |
35,811 | def prepare_request_uri_query ( oauth_params , uri ) : sch , net , path , par , query , fra = urlparse ( uri ) query = urlencode ( _append_params ( oauth_params , extract_params ( query ) or [ ] ) ) return urlunparse ( ( sch , net , path , par , query , fra ) ) | Prepare the Request URI Query . |
35,812 | def validate_request_token_request ( self , request ) : self . _check_transport_security ( request ) self . _check_mandatory_parameters ( request ) if request . realm : request . realms = request . realm . split ( ' ' ) else : request . realms = self . request_validator . get_default_realms ( request . client_key , req... | Validate a request token request . |
35,813 | def validate_request ( self , uri , http_method = 'GET' , body = None , headers = None ) : try : request = self . _create_request ( uri , http_method , body , headers ) except errors . OAuth1Error as err : log . info ( 'Exception caught while validating request, %s.' % err ) return False , None try : self . _check_tran... | Validate a signed OAuth request . |
35,814 | def create_token ( self , request , refresh_token = False ) : if callable ( self . expires_in ) : expires_in = self . expires_in ( request ) else : expires_in = self . expires_in request . expires_in = expires_in return self . request_validator . get_jwt_bearer_token ( None , None , request ) | Create a JWT Token using requestvalidator method . |
35,815 | def get_oauth_signature ( self , request ) : if self . signature_method == SIGNATURE_PLAINTEXT : return signature . sign_plaintext ( self . client_secret , self . resource_owner_secret ) uri , headers , body = self . _render ( request ) collected_params = signature . collect_parameters ( uri_query = urlparse . urlparse... | Get an OAuth signature to be used in signing a request |
35,816 | def get_oauth_params ( self , request ) : nonce = ( generate_nonce ( ) if self . nonce is None else self . nonce ) timestamp = ( generate_timestamp ( ) if self . timestamp is None else self . timestamp ) params = [ ( 'oauth_nonce' , nonce ) , ( 'oauth_timestamp' , timestamp ) , ( 'oauth_version' , '1.0' ) , ( 'oauth_si... | Get the basic OAuth parameters to be used in generating a signature . |
35,817 | def _render ( self , request , formencode = False , realm = None ) : uri , headers , body = request . uri , request . headers , request . body if self . signature_type == SIGNATURE_TYPE_AUTH_HEADER : headers = parameters . prepare_headers ( request . oauth_params , request . headers , realm = realm ) elif self . signat... | Render a signed request according to signature type |
35,818 | def sign ( self , uri , http_method = 'GET' , body = None , headers = None , realm = None ) : request = Request ( uri , http_method , body , headers , encoding = self . encoding ) content_type = request . headers . get ( 'Content-Type' , None ) multipart = content_type and content_type . startswith ( 'multipart/' ) sho... | Sign a request |
35,819 | def _raise_on_invalid_client ( self , request ) : if self . request_validator . client_authentication_required ( request ) : if not self . request_validator . authenticate_client ( request ) : log . debug ( 'Client authentication failed, %r.' , request ) raise InvalidClientError ( request = request ) elif not self . re... | Raise on failed client authentication . |
35,820 | def _raise_on_unsupported_token ( self , request ) : if ( request . token_type_hint and request . token_type_hint in self . valid_token_types and request . token_type_hint not in self . supported_token_types ) : raise UnsupportedTokenTypeError ( request = request ) | Raise on unsupported tokens . |
35,821 | def create_revocation_response ( self , uri , http_method = 'POST' , body = None , headers = None ) : resp_headers = { 'Content-Type' : 'application/json' , 'Cache-Control' : 'no-store' , 'Pragma' : 'no-cache' , } request = Request ( uri , http_method = http_method , body = body , headers = headers ) try : self . valid... | Revoke supplied access or refresh token . |
35,822 | def prepare_authorization_response ( self , request , token , headers , body , status ) : request . response_mode = request . response_mode or self . default_response_mode if request . response_mode not in ( 'query' , 'fragment' ) : log . debug ( 'Overriding invalid response mode %s with %s' , request . response_mode ,... | Place token according to response mode . |
35,823 | def prepare_mac_header ( token , uri , key , http_method , nonce = None , headers = None , body = None , ext = '' , hash_algorithm = 'hmac-sha-1' , issue_time = None , draft = 0 ) : http_method = http_method . upper ( ) host , port = utils . host_from_uri ( uri ) if hash_algorithm . lower ( ) == 'hmac-sha-1' : h = hash... | Add an MAC Access Authentication _ signature to headers . |
35,824 | def get_token_from_header ( request ) : token = None if 'Authorization' in request . headers : split_header = request . headers . get ( 'Authorization' ) . split ( ) if len ( split_header ) == 2 and split_header [ 0 ] == 'Bearer' : token = split_header [ 1 ] else : token = request . access_token return token | Helper function to extract a token from the request header . |
35,825 | def create_token ( self , request , refresh_token = False , ** kwargs ) : if "save_token" in kwargs : warnings . warn ( "`save_token` has been deprecated, it was not called internally." "If you do, call `request_validator.save_token()` instead." , DeprecationWarning ) if callable ( self . expires_in ) : expires_in = se... | Create a BearerToken by default without refresh token . |
35,826 | def list_to_scope ( scope ) : if isinstance ( scope , unicode_type ) or scope is None : return scope elif isinstance ( scope , ( set , tuple , list ) ) : return " " . join ( [ unicode_type ( s ) for s in scope ] ) else : raise ValueError ( "Invalid scope (%s), must be string, tuple, set, or list." % scope ) | Convert a list of scopes to a space separated string . |
35,827 | def scope_to_list ( scope ) : if isinstance ( scope , ( tuple , list , set ) ) : return [ unicode_type ( s ) for s in scope ] elif scope is None : return None else : return scope . strip ( ) . split ( " " ) | Convert a space separated string to a list of scopes . |
35,828 | def host_from_uri ( uri ) : default_ports = { 'HTTP' : '80' , 'HTTPS' : '443' , } sch , netloc , path , par , query , fra = urlparse ( uri ) if ':' in netloc : netloc , port = netloc . split ( ':' , 1 ) else : port = default_ports . get ( sch . upper ( ) ) return netloc , port | Extract hostname and port from URI . |
35,829 | def escape ( u ) : if not isinstance ( u , unicode_type ) : raise ValueError ( 'Only unicode objects are escapable.' ) return quote ( u . encode ( 'utf-8' ) , safe = b'~' ) | Escape a string in an OAuth - compatible fashion . |
35,830 | def generate_age ( issue_time ) : td = datetime . datetime . now ( ) - issue_time age = ( td . microseconds + ( td . seconds + td . days * 24 * 3600 ) * 10 ** 6 ) / 10 ** 6 return unicode_type ( age ) | Generate a age parameter for MAC authentication draft 00 . |
35,831 | def create_token_response ( self , request , token_handler ) : try : self . validate_token_request ( request ) except errors . FatalClientError as e : log . debug ( 'Fatal client error during validation of %r. %r.' , request , e ) raise except errors . OAuth2Error as e : log . debug ( 'Client error during validation of... | Return token or error embedded in the URI fragment . |
35,832 | def validate_token_request ( self , request ) : for param in ( 'client_id' , 'response_type' , 'redirect_uri' , 'scope' , 'state' ) : try : duplicate_params = request . duplicate_params except ValueError : raise errors . InvalidRequestFatalError ( description = 'Unable to parse query string' , request = request ) if pa... | Check the token request for normal and fatal errors . |
35,833 | def validate_authorization_request ( self , request ) : if request . prompt == 'none' : raise OIDCNoPrompt ( ) else : return self . proxy_target . validate_authorization_request ( request ) | Validates the OpenID Connect authorization request parameters . |
35,834 | def openid_authorization_validator ( self , request ) : if not request . scopes or 'openid' not in request . scopes : return { } prompt = request . prompt if request . prompt else [ ] if hasattr ( prompt , 'split' ) : prompt = prompt . strip ( ) . split ( ) prompt = set ( prompt ) if 'none' in prompt : if len ( prompt ... | Perform OpenID Connect specific authorization request validation . |
35,835 | def openid_authorization_validator ( self , request ) : request_info = super ( HybridGrant , self ) . openid_authorization_validator ( request ) if not request_info : return request_info if request . response_type in [ "code id_token" , "code id_token token" ] : if not request . nonce : raise InvalidRequestError ( requ... | Additional validation when following the Authorization Code flow . |
35,836 | def filter_oauth_params ( 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 ) ) | Removes all non oauth parameters from a dict or a list of params . |
35,837 | def parse_authorization_header ( authorization_header ) : auth_scheme = 'OAuth ' . lower ( ) if authorization_header [ : len ( auth_scheme ) ] . lower ( ) . startswith ( auth_scheme ) : items = parse_http_list ( authorization_header [ len ( auth_scheme ) : ] ) try : return list ( parse_keqv_list ( items ) . items ( ) )... | Parse an OAuth authorization header into a list of 2 - tuples |
35,838 | def openid_authorization_validator ( self , request ) : request_info = super ( ImplicitGrant , self ) . openid_authorization_validator ( request ) if not request_info : return request_info if not request . nonce : raise InvalidRequestError ( request = request , description = 'Request is missing mandatory nonce paramete... | Additional validation when following the implicit flow . |
35,839 | def create_access_token ( self , request , credentials ) : request . realms = self . request_validator . get_realms ( request . resource_owner_key , request ) token = { 'oauth_token' : self . token_generator ( ) , 'oauth_token_secret' : self . token_generator ( ) , 'oauth_authorized_realms' : ' ' . join ( request . rea... | Create and save a new access token . |
35,840 | def create_access_token_response ( self , uri , http_method = 'GET' , body = None , headers = None , credentials = None ) : resp_headers = { 'Content-Type' : 'application/x-www-form-urlencoded' } try : request = self . _create_request ( uri , http_method , body , headers ) valid , processed_request = self . validate_ac... | Create an access token response with a new request token if valid . |
35,841 | def validate_access_token_request ( self , request ) : self . _check_transport_security ( request ) self . _check_mandatory_parameters ( request ) if not request . resource_owner_key : raise errors . InvalidRequestError ( description = 'Missing resource owner.' ) if not self . request_validator . check_request_token ( ... | Validate an access token request . |
35,842 | def verify_request ( self , uri , http_method = 'GET' , body = None , headers = None , scopes = None ) : request = Request ( uri , http_method , body , headers ) request . token_type = self . find_token_type ( request ) request . scopes = scopes token_type_handler = self . tokens . get ( request . token_type , self . d... | Validate client code etc return body + headers |
35,843 | def find_token_type ( self , request ) : estimates = sorted ( ( ( t . estimate_type ( request ) , n ) for n , t in self . tokens . items ( ) ) , reverse = True ) return estimates [ 0 ] [ 1 ] if len ( estimates ) else None | Token type identification . |
35,844 | 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 f : json_data = json . load ( f ) tf_state = Tfstate ( json_data ) tf_state . tfstate_file = file_path return tf_state log . debug ( '{0} is not exist' . format ( fi... | Read the tfstate file and load its contents parses then as JSON and put the result into the object |
35,845 | def generate_cmd_string ( self , cmd , * args , ** kwargs ) : cmds = cmd . split ( ) cmds = [ self . terraform_bin_path ] + cmds for option , value in kwargs . items ( ) : if '_' in option : option = option . replace ( '_' , '-' ) if type ( value ) is list : for sub_v in value : cmds += [ '-{k}={v}' . format ( k = opti... | for any generate_cmd_string doesn t written as public method of terraform |
35,846 | 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 : encrypted_data = encrypted_id_data_nodes [ 0 ] key = self . __settings . get_sp_key ( ) nameid = OneLogin_Saml2_Utils . d... | Gets the NameID Data provided by the SAML Response from the IdP |
35,847 | 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 = '{%s}Assertion' % OneLogin_Saml2_Constants . NS_SAML if ( response_tag in signed_elements and signed_elements . count ( response_tag... | Verifies that the document has the expected signed nodes . |
35,848 | def __decrypt_assertion ( self , dom ) : key = self . __settings . get_sp_key ( ) debug = self . __settings . is_debug_active ( ) if not key : raise OneLogin_Saml2_Error ( 'No private key available to decrypt the assertion, check settings' , OneLogin_Saml2_Error . PRIVATE_KEY_NOT_FOUND ) encrypted_assertion_nodes = One... | Decrypts the Assertion |
35,849 | def get_metadata ( url , validate_cert = True ) : valid = False if validate_cert : response = urllib2 . urlopen ( url ) else : ctx = ssl . create_default_context ( ) ctx . check_hostname = False ctx . verify_mode = ssl . CERT_NONE response = urllib2 . urlopen ( url , context = ctx ) xml = response . read ( ) if xml : t... | Gets the metadata XML from the provided URL |
35,850 | def print_xmlsec_errors ( filename , line , func , error_object , error_subject , reason , msg ) : info = [ ] if error_object != "unknown" : info . append ( "obj=" + error_object ) if error_subject != "unknown" : info . append ( "subject=" + error_subject ) if msg . strip ( ) : info . append ( "msg=" + msg ) if reason ... | Auxiliary method . It overrides the default xmlsec debug message . |
35,851 | 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 [ 'server_name' ] else : raise Exception ( 'No hostname defined' ) if ':' in current_host : current_host_data = current_host . split ( ':' ) ... | Returns the current host . |
35,852 | def parse_duration ( duration , timestamp = None ) : assert isinstance ( duration , basestring ) assert timestamp is None or isinstance ( timestamp , int ) timedelta = duration_parser ( duration ) if timestamp is None : data = datetime . utcnow ( ) + timedelta else : data = datetime . utcfromtimestamp ( timestamp ) + t... | Interprets a ISO8601 duration value relative to a given timestamp . |
35,853 | def get_status ( dom ) : status = { } status_entry = OneLogin_Saml2_Utils . query ( dom , '/samlp:Response/samlp:Status' ) if len ( status_entry ) != 1 : raise OneLogin_Saml2_ValidationError ( 'Missing Status on response' , OneLogin_Saml2_ValidationError . MISSING_STATUS ) code_entry = OneLogin_Saml2_Utils . query ( do... | Gets Status from a Response . |
35,854 | 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 . |
35,855 | def __add_default_values ( self ) : self . __sp . setdefault ( 'assertionConsumerService' , { } ) self . __sp [ 'assertionConsumerService' ] . setdefault ( 'binding' , OneLogin_Saml2_Constants . BINDING_HTTP_POST ) self . __sp . setdefault ( 'attributeConsumingService' , { } ) self . __sp . setdefault ( 'singleLogoutSe... | Add default values if the settings info is not complete |
35,856 | 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_Request ( self . __settings , force_authn , is_passive , set_nameid_policy , name_id_value_req ) self . __last_request = authn_request . get_xml (... | Initiates the SSO process . |
35,857 | def logout ( self , return_to = None , name_id = None , session_index = None , nq = None , name_id_format = None ) : slo_url = self . get_slo_url ( ) if slo_url is None : raise OneLogin_Saml2_Error ( 'The IdP does not support Single Log Out' , OneLogin_Saml2_Error . SAML_SINGLE_LOGOUT_NOT_SUPPORTED ) if name_id is None... | Initiates the SLO process . |
35,858 | 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 [ 'singleLogoutService' ] : url = idp_data [ 'singleLogoutService' ] [ 'url' ] return url | Gets the SLO URL . |
35,859 | def add_pyspark_path ( ) : 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' , 'lib' , 'py4j-*-src.zip' ) ) if len ( py4j_src_zip ) == 0 : raise ValueError ( 'py4j source archive not found in... | Add PySpark to the library path based on the value of SPARK_HOME . |
35,860 | def datetime_to_nanos ( dt ) : if isinstance ( dt , pd . Timestamp ) : return dt . value elif isinstance ( dt , str ) : return pd . Timestamp ( dt ) . value elif isinstance ( dt , long ) : return dt elif isinstance ( dt , datetime ) : return long ( dt . strftime ( "%s%f" ) ) * 1000 raise ValueError | Accepts a string Pandas Timestamp or long and returns nanos since the epoch . |
35,861 | def uniform ( start , end = None , periods = None , freq = None , sc = None ) : dtmodule = sc . _jvm . com . cloudera . sparkts . __getattr__ ( 'DateTimeIndex$' ) . __getattr__ ( 'MODULE$' ) if freq is None : raise ValueError ( "Missing frequency" ) elif end is None and periods == None : raise ValueError ( "Need an end... | Instantiates a uniform DateTimeIndex . |
35,862 | def _zdt_to_nanos ( self , zdt ) : instant = zdt . toInstant ( ) return instant . getNano ( ) + instant . getEpochSecond ( ) * 1000000000 | Extracts nanoseconds from a ZonedDateTime |
35,863 | 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 . |
35,864 | 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 . |
35,865 | def fit_model ( y , x , yMaxLag , xMaxLag , includesOriginalX = True , noIntercept = False , sc = None ) : assert sc != None , "Missing SparkContext" jvm = sc . _jvm jmodel = jvm . com . cloudera . sparkts . models . AutoregressionX . fitModel ( _nparray2breezevector ( sc , y . toArray ( ) ) , _nparray2breezematrix ( s... | 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 of an AR model... |
35,866 | def time_series_rdd_from_pandas_series_rdd ( series_rdd ) : first = series_rdd . first ( ) dt_index = irregular ( first [ 1 ] . index , series_rdd . ctx ) return TimeSeriesRDD ( dt_index , series_rdd . mapValues ( lambda x : x . values ) ) | Instantiates a TimeSeriesRDD from an RDD of Pandas Series objects . |
35,867 | 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 . java . JavaTimeSeriesRDDFactory . timeSeriesRDDFromObservations ( dt_index . _jdt_index , df . _jdf , ts_col , key_col , val_col ) return TimeSeriesRDD ( None , No... | Instantiates a TimeSeriesRDD from a DataFrame of observations . |
35,868 | 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 . |
35,869 | def to_instants ( self ) : jrdd = self . _jtsrdd . toInstants ( - 1 ) . map ( self . ctx . _jvm . com . cloudera . sparkts . InstantToBytes ( ) ) return RDD ( jrdd , self . ctx , _InstantDeserializer ( ) ) | Returns an RDD of instants each a horizontal slice of this TimeSeriesRDD at a time . |
35,870 | def to_instants_dataframe ( self , sql_ctx ) : ssql_ctx = sql_ctx . _ssql_ctx jdf = self . _jtsrdd . toInstantsDataFrame ( ssql_ctx , - 1 ) return DataFrame ( jdf , sql_ctx ) | Returns a DataFrame of instants each a horizontal slice of this TimeSeriesRDD at a time . |
35,871 | 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 . toObservationsDataFrame ( ssql_ctx , ts_col , key_col , val_col ) return DataFrame ( jdf , sql_ctx ) | Returns a DataFrame of observations each containing a timestamp a key and a value . |
35,872 | def to_pandas_series_rdd ( self ) : pd_index = self . index ( ) . to_pandas_index ( ) return self . map ( lambda x : ( x [ 0 ] , pd . Series ( x [ 1 ] , pd_index ) ) ) | Returns an RDD of Pandas Series objects indexed with Pandas DatetimeIndexes |
35,873 | def to_pandas_dataframe ( self ) : pd_index = self . index ( ) . to_pandas_index ( ) return pd . DataFrame . from_items ( self . collect ( ) ) . set_index ( pd_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 . |
35,874 | def _SetHeader ( self , values ) : 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 = list ( values ) self . _BuildIndex ( ) | Set the row s header from a list . |
35,875 | def _SetValues ( self , values ) : def _ToStr ( value ) : if isinstance ( value , ( list , tuple ) ) : result = [ ] for val in value : result . append ( str ( val ) ) return result else : return str ( value ) if isinstance ( values , Row ) : if self . _keys != values . header : raise TypeError ( 'Attempt to append row ... | Set values from supplied dictionary or list . |
35,876 | def Filter ( self , function = None ) : flat = lambda x : x if isinstance ( x , str ) else '' . join ( [ flat ( y ) for y in x ] ) if function is None : function = lambda row : bool ( flat ( row . values ) ) new_table = self . __class__ ( ) new_table . _table = [ self . header ] for row in self : if function ( row ) is... | Construct Textable from the rows of which the function returns true . |
35,877 | def _GetTable ( self ) : result = [ ] lstr = str for row in self . _table : result . append ( '%s\n' % self . separator . join ( lstr ( v ) for v in row ) ) return '' . join ( result ) | Returns table with column headers and separators . |
35,878 | def _SetTable ( self , table ) : if not isinstance ( table , TextTable ) : raise TypeError ( 'Not an instance of TextTable.' ) self . Reset ( ) self . _table = copy . deepcopy ( table . _table ) for row in self : row . table = self | Sets table with column headers and separators . |
35,879 | def _TextJustify ( self , text , col_size ) : result = [ ] if '\n' in text : for paragraph in text . split ( '\n' ) : result . extend ( self . _TextJustify ( paragraph , col_size ) ) return result wrapper = textwrap . TextWrapper ( width = col_size - 2 , break_long_words = False , expand_tabs = False ) try : text_list ... | Formats text within column with white space padding . |
35,880 | 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 . |
35,881 | def _ParseCmdItem ( self , cmd_input , template_file = None ) : fsm = textfsm . TextFSM ( template_file ) if not self . _keys : self . _keys = set ( fsm . GetValuesByAttrib ( 'Key' ) ) table = texttable . TextTable ( ) table . header = fsm . header for record in fsm . ParseText ( cmd_input ) : table . Append ( record )... | Creates Texttable with output of command . |
35,882 | def _Completion ( self , match ) : r word = str ( match . group ( ) ) [ 2 : - 2 ] return '(' + ( '(' ) . join ( word ) + ')?' * len ( word ) | r Replaces double square brackets with variable length completion . |
35,883 | def main ( argv = None ) : 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 ( __doc__ ) print ( help_msg ) return 0 if not args or len ( args ) > 4 : ... | Validate text parsed with FSM or validate an FSM via command line . |
35,884 | def ValidOptions ( cls ) : 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 | Returns a list of valid option names . |
35,885 | def Header ( self ) : _ = [ option . OnGetValue ( ) for option in self . options ] return self . name | Fetch the header name of this Value . |
35,886 | def _AddOption ( self , name ) : if name in [ option . name for option in self . options ] : raise TextFSMTemplateError ( 'Duplicate option "%s"' % name ) try : option = self . _options_cls . GetOption ( name ) ( self ) except AttributeError : raise TextFSMTemplateError ( 'Unknown option "%s"' % name ) self . options .... | Add an option to this Value . |
35,887 | 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 . |
35,888 | def _GetHeader ( self ) : header = [ ] for value in self . values : try : header . append ( value . Header ( ) ) except SkipValue : continue return header | Returns header . |
35,889 | def _GetValue ( self , name ) : for value in self . values : if value . name == name : return value | Returns the TextFSMValue object natching the requested name . |
35,890 | def _AppendRecord ( self ) : if not self . values : return cur_record = [ ] for value in self . values : try : value . OnSaveRecord ( ) except SkipRecord : self . _ClearRecord ( ) return except SkipValue : continue cur_record . append ( value . value ) if len ( cur_record ) == ( cur_record . count ( None ) + cur_record... | Adds current record to result if well formed . |
35,891 | def _Parse ( self , template ) : if not template : raise TextFSMTemplateError ( 'Null template.' ) self . _ParseFSMVariables ( template ) while self . _ParseFSMState ( template ) : pass self . _ValidateFSM ( ) | Parses template file for FSM structure . |
35,892 | def _ParseFSMVariables ( self , template ) : self . values = [ ] for line in template : self . _line_num += 1 line = line . rstrip ( ) if not line : return if self . comment_regex . match ( line ) : continue if line . startswith ( 'Value ' ) : try : value = TextFSMValue ( fsm = self , max_name_len = self . MAX_NAME_LEN... | Extracts Variables from start of template file . |
35,893 | def _ParseFSMState ( self , template ) : if not template : return state_name = '' for line in template : self . _line_num += 1 line = line . rstrip ( ) if line and not self . comment_regex . match ( line ) : if ( not self . state_name_re . match ( line ) or len ( line ) > self . MAX_NAME_LEN or line in TextFSMRule . LI... | Extracts State and associated Rules from body of template file . |
35,894 | def _ValidateFSM ( self ) : if 'Start' not in self . states : raise TextFSMTemplateError ( "Missing state 'Start'." ) if self . states . get ( 'End' ) : raise TextFSMTemplateError ( "Non-Empty 'End' state." ) if self . states . get ( 'EOF' ) : raise TextFSMTemplateError ( "Non-Empty 'EOF' state." ) if 'End' in self . s... | Checks state names and destinations for validity . |
35,895 | def ParseText ( self , text , eof = True ) : lines = [ ] if text : lines = text . splitlines ( ) for line in lines : self . _CheckLine ( line ) if self . _cur_state_name in ( 'End' , 'EOF' ) : break if self . _cur_state_name != 'End' and 'EOF' not in self . states and eof : self . _AppendRecord ( ) return self . _resul... | Passes CLI output through FSM and returns list of tuples . |
35,896 | def ParseTextToDicts ( self , * args , ** kwargs ) : result_lists = self . ParseText ( * args , ** kwargs ) result_dicts = [ ] for row in result_lists : result_dicts . append ( dict ( zip ( self . header , row ) ) ) return result_dicts | Calls ParseText and turns the result into list of dicts . |
35,897 | 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 . |
35,898 | def _Operations ( self , rule , line ) : if rule . record_op == 'Record' : self . _AppendRecord ( ) elif rule . record_op == 'Clear' : self . _ClearRecord ( ) elif rule . record_op == 'Clearall' : self . _ClearAllRecord ( ) if rule . line_op == 'Error' : if rule . new_state : raise TextFSMError ( 'Error: %s. Rule Line:... | Operators on the data record . |
35,899 | def GetValuesByAttrib ( self , 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 . OptionNames ( ) : result . append ( value . name ) return result | Returns the list of values that have a particular attribute . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.