idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
232,500 | def predict_log_proba ( self , X ) : Xt , _ , _ = self . _transform ( X ) return self . _final_estimator . predict_log_proba ( Xt ) | Apply transforms and predict_log_proba of the final estimator |
232,501 | def base_features ( ) : features = { 'mean' : mean , 'median' : median , 'abs_energy' : abs_energy , 'std' : std , 'var' : var , 'min' : minimum , 'max' : maximum , 'skew' : skew , 'kurt' : kurt , 'mse' : mse , 'mnx' : mean_crossings } return features | Returns dictionary of some basic features that can be calculated for segmented time series data |
232,502 | def all_features ( ) : features = { 'mean' : mean , 'median' : median , 'gmean' : gmean , 'hmean' : hmean , 'vec_sum' : vec_sum , 'abs_sum' : abs_sum , 'abs_energy' : abs_energy , 'std' : std , 'var' : var , 'variation' : variation , 'min' : minimum , 'max' : maximum , 'skew' : skew , 'kurt' : kurt , 'mean_diff' : mean... | Returns dictionary of all features in the module |
232,503 | def emg_features ( threshold = 0 ) : return { 'mean_abs_value' : mean_abs , 'zero_crossings' : zero_crossing ( threshold ) , 'slope_sign_changes' : slope_sign_changes ( threshold ) , 'waveform_length' : waveform_length , 'integrated_emg' : abs_sum , 'emg_var' : emg_var , 'simple square integral' : abs_energy , 'root_me... | Return a dictionary of popular features used for EMG time series classification . |
232,504 | def means_abs_diff ( X ) : return np . mean ( np . abs ( np . diff ( X , axis = 1 ) ) , axis = 1 ) | mean absolute temporal derivative |
232,505 | def mse ( X ) : return np . mean ( np . square ( np . abs ( np . fft . fft ( X , axis = 1 ) ) ) , axis = 1 ) | computes mean spectral energy for each variable in a segmented time series |
232,506 | def mean_crossings ( X ) : X = np . atleast_3d ( X ) N = X . shape [ 0 ] D = X . shape [ 2 ] mnx = np . zeros ( ( N , D ) ) for i in range ( D ) : pos = X [ : , : , i ] > 0 npos = ~ pos c = ( pos [ : , : - 1 ] & npos [ : , 1 : ] ) | ( npos [ : , : - 1 ] & pos [ : , 1 : ] ) mnx [ : , i ] = np . count_nonzero ( c , axis ... | Computes number of mean crossings for each variable in a segmented time series |
232,507 | def corr2 ( X ) : X = np . atleast_3d ( X ) N = X . shape [ 0 ] D = X . shape [ 2 ] if D == 1 : return np . zeros ( N , dtype = np . float ) trii = np . triu_indices ( D , k = 1 ) DD = len ( trii [ 0 ] ) r = np . zeros ( ( N , DD ) ) for i in np . arange ( N ) : rmat = np . corrcoef ( X [ i ] ) r [ i ] = rmat [ trii ] ... | computes correlations between all variable pairs in a segmented time series |
232,508 | def waveform_length ( X ) : return np . sum ( np . abs ( np . diff ( X , axis = 1 ) ) , axis = 1 ) | cumulative length of the waveform over a segment for each variable in the segmented time series |
232,509 | def root_mean_square ( X ) : segment_width = X . shape [ 1 ] return np . sqrt ( np . sum ( X * X , axis = 1 ) / segment_width ) | root mean square for each variable in the segmented time series |
232,510 | def split ( self , X , y ) : check_ts_data ( X , y ) Xt , Xc = get_ts_data_parts ( X ) Ns = len ( Xt ) Xt_new , y_new = self . _ts_slice ( Xt , y ) if Xc is not None : Xc_new = np . concatenate ( [ Xc ] * self . n_splits ) X_new = TS_Data ( Xt_new , Xc_new ) else : X_new = np . array ( Xt_new ) cv = self . _make_indice... | Splits time series data and target arrays and generates splitting indices |
232,511 | def _ts_slice ( self , Xt , y ) : Ns = len ( Xt ) Xt_new = [ ] for i in range ( self . n_splits ) : for j in range ( Ns ) : Njs = int ( len ( Xt [ j ] ) / self . n_splits ) Xt_new . append ( Xt [ j ] [ ( Njs * i ) : ( Njs * ( i + 1 ) ) ] ) Xt_new = np . array ( Xt_new ) if len ( np . atleast_1d ( y [ 0 ] ) ) == len ( X... | takes time series data and splits each series into temporal folds |
232,512 | def _make_indices ( self , Ns ) : N_new = int ( Ns * self . n_splits ) test = [ np . full ( N_new , False ) for i in range ( self . n_splits ) ] for i in range ( self . n_splits ) : test [ i ] [ np . arange ( Ns * i , Ns * ( i + 1 ) ) ] = True train = [ np . logical_not ( test [ i ] ) for i in range ( self . n_splits )... | makes indices for cross validation |
232,513 | def transform ( self , X , y , sample_weight = None ) : check_ts_data_with_ts_target ( X , y ) Xt , Xc = get_ts_data_parts ( X ) N = len ( Xt ) yt = [ ] Xtt = [ ] swt = sample_weight Nt = [ ] for i in range ( N ) : Xi , yi = self . _transform ( Xt [ i ] , y [ i ] ) yt += yi Xtt += Xi Nt . append ( len ( yi ) ) if Xc is... | Transforms the time series data with run length encoding of the target variable Note this transformation changes the number of samples in the data If sample_weight is provided it is transformed to align to the new target encoding |
232,514 | def _rle ( self , a ) : ia = np . asarray ( a ) n = len ( ia ) y = np . array ( ia [ 1 : ] != ia [ : - 1 ] ) i = np . append ( np . where ( y ) , n - 1 ) z = np . diff ( np . append ( - 1 , i ) ) p = np . cumsum ( np . append ( 0 , z ) ) [ : - 1 ] return ( z , p , ia [ i ] ) | rle implementation credit to Thomas Browne from his SOF post Sept 2015 |
232,515 | def _transform ( self , X , y ) : z , p , y_rle = self . _rle ( y ) p = np . append ( p , len ( y ) ) big_enough = p [ 1 : ] - p [ : - 1 ] >= self . min_length Xt = [ ] for i in range ( len ( y_rle ) ) : if ( big_enough [ i ] ) : Xt . append ( X [ p [ i ] : p [ i + 1 ] ] ) yt = y_rle [ big_enough ] . tolist ( ) return ... | Transforms single series |
232,516 | def get_ts_data_parts ( X ) : if not isinstance ( X , TS_Data ) : return X , None return X . ts_data , X . context_data | Separates time series data object into time series variables and contextual variables |
232,517 | def check_ts_data_with_ts_target ( X , y = None ) : if y is not None : Nx = len ( X ) Ny = len ( y ) if Nx != Ny : raise ValueError ( "Number of time series different in X (%d) and y (%d)" % ( Nx , Ny ) ) Xt , _ = get_ts_data_parts ( X ) Ntx = np . array ( [ len ( Xt [ i ] ) for i in np . arange ( Nx ) ] ) Nty = np . a... | Checks time series data with time series target is good . If not raises value error . |
232,518 | def ts_stats ( Xt , y , fs = 1.0 , class_labels = None ) : check_ts_data ( Xt ) Xt , Xs = get_ts_data_parts ( Xt ) if Xs is not None : S = len ( np . atleast_1d ( Xs [ 0 ] ) ) else : S = 0 C = np . max ( y ) + 1 if class_labels is None : class_labels = np . arange ( C ) N = len ( Xt ) if Xt [ 0 ] . ndim > 1 : D = Xt [ ... | Generates some helpful statistics about the data X |
232,519 | def load_watch ( ) : module_path = dirname ( __file__ ) data = np . load ( module_path + "/data/watch_dataset.npy" ) . item ( ) return data | Loads some of the 6 - axis inertial sensor data from my smartwatch project . The sensor data was recorded as study subjects performed sets of 20 shoulder exercise repetitions while wearing a smartwatch . It is a multivariate time series . |
232,520 | def shuffle_data ( X , y = None , sample_weight = None ) : if len ( X ) > 1 : ind = np . arange ( len ( X ) , dtype = np . int ) np . random . shuffle ( ind ) Xt = X [ ind ] yt = y swt = sample_weight if yt is not None : yt = yt [ ind ] if swt is not None : swt = swt [ ind ] return Xt , yt , swt else : return X , y , s... | Shuffles indices X y and sample_weight together |
232,521 | def expand_variables_to_segments ( v , Nt ) : N_v = len ( np . atleast_1d ( v [ 0 ] ) ) return np . concatenate ( [ np . full ( ( Nt [ i ] , N_v ) , v [ i ] ) for i in np . arange ( len ( v ) ) ] ) | expands contextual variables v by repeating each instance as specified in Nt |
232,522 | def sliding_window ( time_series , width , step , order = 'F' ) : w = np . hstack ( [ time_series [ i : 1 + i - width or None : step ] for i in range ( 0 , width ) ] ) result = w . reshape ( ( int ( len ( w ) / width ) , width ) , order = 'F' ) if order == 'F' : return result else : return np . ascontiguousarray ( resu... | Segments univariate time series with sliding window |
232,523 | def sliding_tensor ( mv_time_series , width , step , order = 'F' ) : D = mv_time_series . shape [ 1 ] data = [ sliding_window ( mv_time_series [ : , j ] , width , step , order ) for j in range ( D ) ] return np . stack ( data , axis = 2 ) | segments multivariate time series with sliding window |
232,524 | def transform ( self , X , y = None , sample_weight = None ) : check_ts_data ( X , y ) Xt , Xc = get_ts_data_parts ( X ) yt = y N = len ( Xt ) if Xt [ 0 ] . ndim > 1 : Xt = np . array ( [ sliding_tensor ( Xt [ i ] , self . width , self . _step , self . order ) for i in np . arange ( N ) ] ) else : Xt = np . array ( [ s... | Transforms the time series data into segments Note this transformation changes the number of samples in the data If y is provided it is segmented and transformed to align to the new samples as per y_func Currently sample weights always returned as None |
232,525 | def transform ( self , X , y = None , sample_weight = None ) : check_ts_data ( X , y ) Xt , Xc = get_ts_data_parts ( X ) yt = y swt = sample_weight Xt = self . _mv_resize ( Xt ) if Xc is not None : Xt = TS_Data ( Xt , Xc ) if yt is not None and len ( np . atleast_1d ( yt [ 0 ] ) ) > 1 : yt = self . _mv_resize ( yt ) sw... | Transforms the time series data into fixed length segments using padding and or truncation If y is a time series and passed it will be transformed as well |
232,526 | def _check_data ( self , X ) : if len ( X ) > 1 : sval = np . unique ( X [ 0 ] [ : , 1 ] ) if np . all ( [ np . all ( np . unique ( X [ i ] [ : , 1 ] ) == sval ) for i in range ( 1 , len ( X ) ) ] ) : pass else : raise ValueError ( "Unique identifier var_types not consistent between time series" ) | Checks that unique identifiers vaf_types are consistent between time series . |
232,527 | def _check_features ( self , features , Xti ) : N = Xti . shape [ 0 ] N_fts = len ( features ) fshapes = np . zeros ( ( N_fts , 2 ) , dtype = np . int ) keys = [ key for key in features ] for i in np . arange ( N_fts ) : fshapes [ i ] = np . row_stack ( features [ keys [ i ] ] ( Xti ) ) . shape if not np . all ( fshape... | tests output of each feature against a segmented time series X |
232,528 | def _generate_feature_labels ( self , X ) : Xt , Xc = get_ts_data_parts ( X ) ftr_sizes = self . _check_features ( self . features , Xt [ 0 : 3 ] ) f_labels = [ ] for key in ftr_sizes : for i in range ( ftr_sizes [ key ] ) : f_labels += [ key + '_' + str ( i ) ] if Xc is not None : Ns = len ( np . atleast_1d ( Xc [ 0 ]... | Generates string feature labels |
232,529 | def _retrieve_indices ( cols ) : if isinstance ( cols , int ) : return [ cols ] elif isinstance ( cols , slice ) : start = cols . start if cols . start else 0 stop = cols . stop step = cols . step if cols . step else 1 return list ( range ( start , stop , step ) ) elif isinstance ( cols , list ) and cols : if isinstanc... | Retrieve a list of indices corresponding to the provided column specification . |
232,530 | def _validate ( self ) : if self . f_labels is None : raise NotFittedError ( 'FeatureRepMix' ) if not self . transformers : return names , transformers , _ = zip ( * self . transformers ) self . _validate_names ( names ) for trans in transformers : if not isinstance ( trans , FeatureRep ) : raise TypeError ( "All trans... | Internal function to validate the transformer before applying all internal transformers . |
232,531 | def transform ( self , X ) : if self . func is None : return X else : Xt , Xc = get_ts_data_parts ( X ) n_samples = len ( Xt ) Xt = self . func ( Xt , ** self . func_kwargs ) if len ( Xt ) != n_samples : raise ValueError ( "FunctionTransformer changes sample number (not supported)." ) if Xc is not None : Xt = TS_Data (... | Transforms the time series data based on the provided function . Note this transformation must not change the number of samples in the data . |
232,532 | def build_payload ( self , payload ) : remaining_size = self . MAX_SEGMENT_PAYLOAD_SIZE for part in self . parts : part_payload = part . pack ( remaining_size ) payload . write ( part_payload ) remaining_size -= len ( part_payload ) | Build payload of all parts and write them into the payload buffer |
232,533 | def escape ( value ) : if isinstance ( value , ( tuple , list ) ) : return "(" + ", " . join ( [ escape ( arg ) for arg in value ] ) + ")" else : typ = by_python_type . get ( value . __class__ ) if typ is None : raise InterfaceError ( "Unsupported python input: %s (%s)" % ( value , value . __class__ ) ) return typ . to... | Escape a single value . |
232,534 | def escape_values ( values ) : if isinstance ( values , ( tuple , list ) ) : return tuple ( [ escape ( value ) for value in values ] ) elif isinstance ( values , dict ) : return dict ( [ ( key , escape ( value ) ) for ( key , value ) in values . items ( ) ] ) else : raise InterfaceError ( "escape_values expects list, t... | Escape multiple values from a list tuple or dict . |
232,535 | def prepare ( cls , value ) : pfield = struct . pack ( 'b' , cls . type_code ) if isinstance ( value , string_types ) : value = datetime . datetime . strptime ( value , "%Y-%m-%d" ) year = value . year | 0x8000 month = value . month - 1 pfield += cls . _struct . pack ( year , month , value . day ) return pfield | Pack datetime value into proper binary format |
232,536 | def prepare ( cls , value ) : pfield = struct . pack ( 'b' , cls . type_code ) if isinstance ( value , string_types ) : if "." in value : value = datetime . datetime . strptime ( value , "%H:%M:%S.%f" ) else : value = datetime . datetime . strptime ( value , "%H:%M:%S" ) millisecond = value . second * 1000 + value . mi... | Pack time value into proper binary format |
232,537 | def prepare ( cls , value , length = 0 , position = 0 , is_last_data = True ) : hstruct = WriteLobHeader . header_struct lob_option_dataincluded = WriteLobHeader . LOB_OPTION_DATAINCLUDED if length > 0 else 0 lob_option_lastdata = WriteLobHeader . LOB_OPTION_LASTDATA if is_last_data else 0 options = lob_option_dataincl... | Prepare Lob header . Note that the actual lob data is NOT written here but appended after the parameter block for each row! |
232,538 | def seek ( self , offset , whence = SEEK_SET ) : self . data . seek ( offset , whence ) new_pos = self . data . tell ( ) missing_bytes_to_read = new_pos - self . _current_lob_length if missing_bytes_to_read > 0 : self . data . seek ( 0 , SEEK_END ) self . read ( missing_bytes_to_read + self . EXTRA_NUM_ITEMS_TO_READ_AF... | Seek pointer in lob data buffer to requested position . Might trigger further loading of data from the database if the pointer is beyond currently read data . |
232,539 | def _read_missing_lob_data_from_db ( self , readoffset , readlength ) : logger . debug ( 'Reading missing lob data from db. Offset: %d, readlength: %d' % ( readoffset , readlength ) ) lob_data = self . _make_read_lob_request ( readoffset , readlength ) enc_lob_data = self . _decode_lob_data ( lob_data ) assert readleng... | Read LOB request part from database |
232,540 | def _init_io_container ( self , init_value ) : if isinstance ( init_value , CLOB_STRING_IO_CLASSES ) : v = init_value else : if PY3 : init_value . encode ( 'ascii' ) v = CLOB_STRING_IO ( init_value ) return v | Initialize container to hold lob data . Here either a cStringIO or a io . StringIO class is used depending on the Python version . For CLobs ensure that an initial unicode value only contains valid ascii chars . |
232,541 | def _handle_upsert ( self , parts , unwritten_lobs = ( ) ) : self . description = None self . _received_last_resultset_part = True for part in parts : if part . kind == part_kinds . ROWSAFFECTED : self . rowcount = part . values [ 0 ] elif part . kind in ( part_kinds . TRANSACTIONFLAGS , part_kinds . STATEMENTCONTEXT ,... | Handle reply messages from INSERT or UPDATE statements |
232,542 | def _handle_select ( self , parts , result_metadata = None ) : self . rowcount = - 1 if result_metadata is not None : self . description , self . _column_types = self . _handle_result_metadata ( result_metadata ) for part in parts : if part . kind == part_kinds . RESULTSETID : self . _resultset_id = part . value elif p... | Handle reply messages from SELECT statements |
232,543 | def _handle_dbproc_call ( self , parts , parameters_metadata ) : for part in parts : if part . kind == part_kinds . ROWSAFFECTED : self . rowcount = part . values [ 0 ] elif part . kind == part_kinds . TRANSACTIONFLAGS : pass elif part . kind == part_kinds . STATEMENTCONTEXT : pass elif part . kind == part_kinds . OUTP... | Handle reply messages from STORED PROCEDURE statements |
232,544 | def allhexlify ( data ) : hx = binascii . hexlify ( data ) return b'' . join ( [ b'\\x' + o for o in re . findall ( b'..' , hx ) ] ) | Hexlify given data into a string representation with hex values for all chars Input like ab \ x04ce becomes \ x61 \ x62 \ x04 \ x63 \ x65 |
232,545 | def pack ( self , remaining_size ) : arguments_count , payload = self . pack_data ( remaining_size - self . header_size ) payload_length = len ( payload ) if payload_length % 8 != 0 : payload += b"\x00" * ( 8 - payload_length % 8 ) self . header = PartHeader ( self . kind , self . attribute , arguments_count , self . b... | Pack data of part into binary format |
232,546 | def unpack_from ( cls , payload , expected_parts ) : for num_part in iter_range ( expected_parts ) : hdr = payload . read ( cls . header_size ) try : part_header = PartHeader ( * cls . header_struct . unpack ( hdr ) ) except struct . error : raise InterfaceError ( "No valid part header" ) if part_header . payload_size ... | Unpack parts from payload |
232,547 | def pack_data ( self , remaining_size ) : payload = self . part_struct . pack ( self . locator_id , self . readoffset + 1 , self . readlength , b' ' ) return 4 , payload | Pack data . readoffset has to be increased by one seems like HANA starts from 1 not zero . |
232,548 | def build_payload ( self , payload ) : for segment in self . segments : segment . pack ( payload , commit = self . autocommit ) | Build payload of message . |
232,549 | def pack ( self ) : payload = io . BytesIO ( ) payload . seek ( self . header_size , io . SEEK_CUR ) self . build_payload ( payload ) packet_length = len ( payload . getvalue ( ) ) - self . header_size self . header = MessageHeader ( self . session_id , self . packet_count , packet_length , constants . MAX_SEGMENT_SIZE... | Pack message to binary stream . |
232,550 | def check_specs ( specs , renamings , types ) : from pythran . types . tog import unify , clone , tr from pythran . types . tog import Function , TypeVariable , InferenceError functions = { renamings . get ( k , k ) : v for k , v in specs . functions . items ( ) } for fname , signatures in functions . items ( ) : ftype... | Does nothing but raising PythranSyntaxError if specs are incompatible with the actual code |
232,551 | def check_exports ( mod , specs , renamings ) : functions = { renamings . get ( k , k ) : v for k , v in specs . functions . items ( ) } mod_functions = { node . name : node for node in mod . body if isinstance ( node , ast . FunctionDef ) } for fname , signatures in functions . items ( ) : try : fnode = mod_functions ... | Does nothing but raising PythranSyntaxError if specs references an undefined global |
232,552 | def visit_Import ( self , node ) : for alias in node . names : current_module = MODULES for path in alias . name . split ( '.' ) : if path not in current_module : raise PythranSyntaxError ( "Module '{0}' unknown." . format ( alias . name ) , node ) else : current_module = current_module [ path ] | Check if imported module exists in MODULES . |
232,553 | def visit_ImportFrom ( self , node ) : if node . level : raise PythranSyntaxError ( "Relative import not supported" , node ) if not node . module : raise PythranSyntaxError ( "import from without module" , node ) module = node . module current_module = MODULES for path in module . split ( '.' ) : if path not in current... | Check validity of imported functions . |
232,554 | def uncamel ( name ) : s1 = re . sub ( '(.)([A-Z][a-z]+)' , r'\1_\2' , name ) return re . sub ( '([a-z0-9])([A-Z])' , r'\1_\2' , s1 ) . lower ( ) | Transform CamelCase naming convention into C - ish convention . |
232,555 | def verify_dependencies ( self ) : for i in range ( 1 , len ( self . deps ) ) : assert ( not ( isinstance ( self . deps [ i ] , Transformation ) and isinstance ( self . deps [ i - 1 ] , Analysis ) ) ) , "invalid dep order for %s" % self | Checks no analysis are called before a transformation as the transformation could invalidate the analysis . |
232,556 | def prepare ( self , node ) : if isinstance ( node , ast . Module ) : self . ctx . module = node elif isinstance ( node , ast . FunctionDef ) : self . ctx . function = node for D in self . deps : d = D ( ) d . attach ( self . passmanager , self . ctx ) result = d . run ( node ) setattr ( self , uncamel ( D . __name__ )... | Gather analysis result required by this analysis |
232,557 | def run ( self , node ) : n = super ( Transformation , self ) . run ( node ) if self . update : ast . fix_missing_locations ( n ) self . passmanager . _cache . clear ( ) return n | Apply transformation and dependencies and fix new node location . |
232,558 | def apply ( self , node ) : new_node = self . run ( node ) return self . update , new_node | Apply transformation and return if an update happened . |
232,559 | def gather ( self , analysis , node ) : "High-level function to call an `analysis' on a `node'" assert issubclass ( analysis , Analysis ) a = analysis ( ) a . attach ( self ) return a . run ( node ) | High - level function to call an analysis on a node |
232,560 | def dump ( self , backend , node ) : assert issubclass ( backend , Backend ) b = backend ( ) b . attach ( self ) return b . run ( node ) | High - level function to call a backend on a node to generate code for module module_name . |
232,561 | def apply ( self , transformation , node ) : assert issubclass ( transformation , ( Transformation , Analysis ) ) a = transformation ( ) a . attach ( self ) res = a . apply ( node ) if a . update : self . _cache . clear ( ) return res | High - level function to call a transformation on a node . If the transformation is an analysis the result of the analysis is displayed . |
232,562 | def pytype_to_ctype ( t ) : if isinstance ( t , List ) : return 'pythonic::types::list<{0}>' . format ( pytype_to_ctype ( t . __args__ [ 0 ] ) ) elif isinstance ( t , Set ) : return 'pythonic::types::set<{0}>' . format ( pytype_to_ctype ( t . __args__ [ 0 ] ) ) elif isinstance ( t , Dict ) : tkey , tvalue = t . __args_... | Python - > pythonic type binding . |
232,563 | def pytype_to_pretty_type ( t ) : if isinstance ( t , List ) : return '{0} list' . format ( pytype_to_pretty_type ( t . __args__ [ 0 ] ) ) elif isinstance ( t , Set ) : return '{0} set' . format ( pytype_to_pretty_type ( t . __args__ [ 0 ] ) ) elif isinstance ( t , Dict ) : tkey , tvalue = t . __args__ return '{0}:{1} ... | Python - > docstring type . |
232,564 | def get_type ( name , env , non_generic ) : if name in env : if isinstance ( env [ name ] , MultiType ) : return clone ( env [ name ] ) return fresh ( env [ name ] , non_generic ) else : print ( "W: Undefined symbol {0}" . format ( name ) ) return TypeVariable ( ) | Get the type of identifier name from the type environment env . |
232,565 | def fresh ( t , non_generic ) : mappings = { } def freshrec ( tp ) : p = prune ( tp ) if isinstance ( p , TypeVariable ) : if is_generic ( p , non_generic ) : if p not in mappings : mappings [ p ] = TypeVariable ( ) return mappings [ p ] else : return p elif isinstance ( p , dict ) : return p elif isinstance ( p , Coll... | Makes a copy of a type expression . |
232,566 | def prune ( t ) : if isinstance ( t , TypeVariable ) : if t . instance is not None : t . instance = prune ( t . instance ) return t . instance return t | Returns the currently defining instance of t . |
232,567 | def occurs_in_type ( v , type2 ) : pruned_type2 = prune ( type2 ) if pruned_type2 == v : return True elif isinstance ( pruned_type2 , TypeOperator ) : return occurs_in ( v , pruned_type2 . types ) return False | Checks whether a type variable occurs in a type expression . |
232,568 | def visit_Module ( self , node ) : node . body = [ k for k in ( self . visit ( n ) for n in node . body ) if k ] imports = [ ast . Import ( [ ast . alias ( i , mangle ( i ) ) ] ) for i in self . imports ] node . body = imports + node . body ast . fix_missing_locations ( node ) return node | Visit the whole module and add all import at the top level . |
232,569 | def visit_Name ( self , node ) : if node . id in self . symbols : symbol = path_to_node ( self . symbols [ node . id ] ) if not getattr ( symbol , 'isliteral' , lambda : False ) ( ) : parent = self . ancestors [ node ] [ - 1 ] blacklist = ( ast . Tuple , ast . List , ast . Set , ast . Return ) if isinstance ( parent , ... | Replace name with full expanded name . |
232,570 | def save_function_effect ( module ) : for intr in module . values ( ) : if isinstance ( intr , dict ) : save_function_effect ( intr ) else : fe = FunctionEffects ( intr ) IntrinsicArgumentEffects [ intr ] = fe if isinstance ( intr , intrinsic . Class ) : save_function_effect ( intr . fields ) | Recursively save function effect for pythonic functions . |
232,571 | def prepare ( self , node ) : super ( ArgumentEffects , self ) . prepare ( node ) for n in self . global_declarations . values ( ) : fe = FunctionEffects ( n ) self . node_to_functioneffect [ n ] = fe self . result . add_node ( fe ) | Initialise arguments effects as this analyse is inter - procedural . |
232,572 | def process_locals ( self , node , node_visited , * skipped ) : local_vars = self . scope [ node ] . difference ( skipped ) local_vars = local_vars . difference ( self . openmp_deps ) if not local_vars : return node_visited locals_visited = [ ] for varname in local_vars : vartype = self . typeof ( varname ) decl = Stat... | Declare variable local to node and insert declaration before . |
232,573 | def process_omp_attachements ( self , node , stmt , index = None ) : omp_directives = metadata . get ( node , OMPDirective ) if omp_directives : directives = list ( ) for directive in omp_directives : directive . deps = [ self . visit ( dep ) for dep in directive . deps ] directives . append ( directive ) if index is N... | Add OpenMP pragma on the correct stmt in the correct order . |
232,574 | def visit_Assign ( self , node ) : if not all ( isinstance ( n , ( ast . Name , ast . Subscript ) ) for n in node . targets ) : raise PythranSyntaxError ( "Must assign to an identifier or a subscript" , node ) value = self . visit ( node . value ) targets = [ self . visit ( t ) for t in node . targets ] alltargets = "=... | Create Assign node for final Cxx representation . |
232,575 | def gen_for ( self , node , target , local_iter , local_iter_decl , loop_body ) : local_target = "__target{0}" . format ( id ( node ) ) local_target_decl = self . types . builder . IteratorOfType ( local_iter_decl ) if node . target . id in self . scope [ node ] and not hasattr ( self , 'yields' ) : local_type = "auto&... | Create For representation on iterator for Cxx generation . |
232,576 | def handle_real_loop_comparison ( self , args , target , upper_bound ) : if len ( args ) <= 2 : order = 1 elif isinstance ( args [ 2 ] , ast . Num ) : order = - 1 + 2 * ( int ( args [ 2 ] . n ) > 0 ) elif isinstance ( args [ 1 ] , ast . Num ) and isinstance ( args [ 0 ] , ast . Num ) : order = - 1 + 2 * ( int ( args [ ... | Handle comparison for real loops . |
232,577 | def gen_c_for ( self , node , local_iter , loop_body ) : args = node . iter . args step = "1L" if len ( args ) <= 2 else self . visit ( args [ 2 ] ) if len ( args ) == 1 : lower_bound = "0L" upper_arg = 0 else : lower_bound = self . visit ( args [ 0 ] ) upper_arg = 1 upper_type = iter_type = "long " upper_value = self ... | Create C For representation for Cxx generation . |
232,578 | def handle_omp_for ( self , node , local_iter ) : for directive in metadata . get ( node , OMPDirective ) : if any ( key in directive . s for key in ( ' parallel ' , ' task ' ) ) : directive . s += ' shared({})' directive . deps . append ( ast . Name ( local_iter , ast . Load ( ) , None ) ) directive . shared_deps . ap... | Fix OpenMP directives on For loops . |
232,579 | def can_use_autofor ( self , node ) : auto_for = ( isinstance ( node . target , ast . Name ) and node . target . id in self . scope [ node ] and node . target . id not in self . openmp_deps ) auto_for &= not metadata . get ( node , OMPDirective ) auto_for &= node . target . id not in self . openmp_deps return auto_for | Check if given for Node can use autoFor syntax . |
232,580 | def can_use_c_for ( self , node ) : assert isinstance ( node . target , ast . Name ) if sys . version_info . major == 3 : range_name = 'range' else : range_name = 'xrange' pattern_range = ast . Call ( func = ast . Attribute ( value = ast . Name ( id = '__builtin__' , ctx = ast . Load ( ) , annotation = None ) , attr = ... | Check if a for loop can use classic C syntax . |
232,581 | def visit_For ( self , node ) : if not isinstance ( node . target , ast . Name ) : raise PythranSyntaxError ( "Using something other than an identifier as loop target" , node . target ) target = self . visit ( node . target ) loop_body = Block ( [ self . visit ( stmt ) for stmt in node . body ] ) loop_body = self . pro... | Create For representation for Cxx generation . |
232,582 | def visit_While ( self , node ) : test = self . visit ( node . test ) body = [ self . visit ( n ) for n in node . body ] stmt = While ( test , Block ( body ) ) return self . process_omp_attachements ( node , stmt ) | Create While node for Cxx generation . |
232,583 | def visit_Break ( self , _ ) : if self . break_handlers and self . break_handlers [ - 1 ] : return Statement ( "goto {0}" . format ( self . break_handlers [ - 1 ] ) ) else : return Statement ( "break" ) | Generate break statement in most case and goto for orelse clause . |
232,584 | def visit_Module ( self , node ) : deps = sorted ( self . dependencies ) headers = [ Include ( os . path . join ( "pythonic" , "include" , * t ) + ".hpp" ) for t in deps ] headers += [ Include ( os . path . join ( "pythonic" , * t ) + ".hpp" ) for t in deps ] decls_n_defns = [ self . visit ( stmt ) for stmt in node . b... | Build a compilation unit . |
232,585 | def refine ( pm , node , optimizations ) : pm . apply ( ExpandGlobals , node ) pm . apply ( ExpandImportAll , node ) pm . apply ( NormalizeTuples , node ) pm . apply ( ExpandBuiltins , node ) pm . apply ( ExpandImports , node ) pm . apply ( NormalizeMethodCalls , node ) pm . apply ( NormalizeIsNone , node ) pm . apply ... | Refine node in place until it matches pythran s expectations . |
232,586 | def prepare ( self , node ) : super ( GlobalEffects , self ) . prepare ( node ) def register_node ( module ) : for v in module . values ( ) : if isinstance ( v , dict ) : register_node ( v ) else : fe = GlobalEffects . FunctionEffect ( v ) self . node_to_functioneffect [ v ] = fe self . result . add_node ( fe ) if isin... | Initialise globals effects as this analyse is inter - procedural . |
232,587 | def prepare ( self , node ) : def register ( name , module ) : for fname , function in module . items ( ) : if isinstance ( function , dict ) : register ( name + "::" + fname , function ) else : tname = 'pythonic::{0}::functor::{1}' . format ( name , fname ) self . result [ function ] = self . builder . NamedType ( tna... | Initialise values to prepare typing computation . |
232,588 | def register ( self , ptype ) : if len ( self . typedefs ) < cfg . getint ( 'typing' , 'max_combiner' ) : self . typedefs . append ( ptype ) return True return False | register ptype as a local typedef |
232,589 | def isargument ( self , node ) : try : node_id , _ = self . node_to_id ( node ) return ( node_id in self . name_to_nodes and any ( [ isinstance ( n , ast . Name ) and isinstance ( n . ctx , ast . Param ) for n in self . name_to_nodes [ node_id ] ] ) ) except UnboundableRValue : return False | checks whether node aliases to a parameter . |
232,590 | def combine ( self , node , othernode , op = None , unary_op = None , register = False , aliasing_type = False ) : if self . result [ othernode ] is self . builder . UnknownType : if node not in self . result : self . result [ node ] = self . builder . UnknownType return if aliasing_type : self . combine_ ( node , othe... | Change node typing with combination of node and othernode . |
232,591 | def visit_Return ( self , node ) : self . generic_visit ( node ) if not self . yield_points : assert node . value , "Values were added in each return statement." self . combine ( self . current , node . value ) | Compute return type and merges with others possible return type . |
232,592 | def visit_Yield ( self , node ) : self . generic_visit ( node ) self . combine ( self . current , node . value ) | Compute yield type and merges it with others yield type . |
232,593 | def visit_BoolOp ( self , node ) : self . generic_visit ( node ) [ self . combine ( node , value ) for value in node . values ] | Merge BoolOp operand type . |
232,594 | def visit_Num ( self , node ) : ty = type ( node . n ) sty = pytype_to_ctype ( ty ) if node in self . immediates : sty = "std::integral_constant<%s, %s>" % ( sty , node . n ) self . result [ node ] = self . builder . NamedType ( sty ) | Set type for number . |
232,595 | def visit_Str ( self , node ) : self . result [ node ] = self . builder . NamedType ( pytype_to_ctype ( str ) ) | Set the pythonic string type . |
232,596 | def visit_Attribute ( self , node ) : obj , path = attr_to_path ( node ) if obj . isliteral ( ) : typename = pytype_to_ctype ( obj . signature ) self . result [ node ] = self . builder . NamedType ( typename ) else : self . result [ node ] = self . builder . DeclType ( '::' . join ( path ) + '{}' ) | Compute typing for an attribute node . |
232,597 | def visit_Slice ( self , node ) : self . generic_visit ( node ) if node . step is None or ( isinstance ( node . step , ast . Num ) and node . step . n == 1 ) : self . result [ node ] = self . builder . NamedType ( 'pythonic::types::contiguous_slice' ) else : self . result [ node ] = self . builder . NamedType ( 'python... | Set slicing type using continuous information if provided . |
232,598 | def init_not_msvc ( self ) : paths = os . environ . get ( 'LD_LIBRARY_PATH' , '' ) . split ( ':' ) for gomp in ( 'libgomp.so' , 'libgomp.dylib' ) : if cxx is None : continue cmd = [ cxx , '-print-file-name=' + gomp ] try : path = os . path . dirname ( check_output ( cmd ) . strip ( ) ) if path : paths . append ( path )... | Find OpenMP library and try to load if using ctype interface . |
232,599 | def visit_FunctionDef ( self , node ) : if ( len ( node . body ) == 1 and isinstance ( node . body [ 0 ] , ( ast . Call , ast . Return ) ) ) : ids = self . gather ( Identifiers , node . body [ 0 ] ) if node . name not in ids : self . result [ node . name ] = copy . deepcopy ( node ) | Determine this function definition can be inlined . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.