idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
38,400 | def write_translated ( self , name , value , event = None ) : data = { 'name' : name } if value is not None : data [ 'value' ] = self . _massage_write_value ( value ) if event is not None : data [ 'event' ] = self . _massage_write_value ( event ) message = self . streamer . serialize_for_stream ( data ) bytes_written = self . write_bytes ( message ) assert bytes_written == len ( message ) return bytes_written | Send a translated write request to the VI . |
38,401 | def write_raw ( self , message_id , data , bus = None , frame_format = None ) : if not isinstance ( message_id , numbers . Number ) : try : message_id = int ( message_id , 0 ) except ValueError : raise ValueError ( "ID must be numerical" ) data = { 'id' : message_id , 'data' : data } if bus is not None : data [ 'bus' ] = bus if frame_format is not None : data [ 'frame_format' ] = frame_format message = self . streamer . serialize_for_stream ( data ) bytes_written = self . write_bytes ( message ) assert bytes_written == len ( message ) return bytes_written | Send a raw write request to the VI . |
38,402 | def _massage_write_value ( cls , value ) : if not isinstance ( value , numbers . Number ) : if value == "true" : value = True elif value == "false" : value = False elif value [ 0 ] == '"' and value [ - 1 ] == '"' : value = value [ 1 : - 1 ] else : try : value = float ( value ) except ValueError : pass return value | Convert string values from command - line arguments into first - order Python boolean and float objects if applicable . |
38,403 | def _validate ( cls , message ) : valid = False if ( ( 'name' in message and 'value' in message ) or ( 'id' in message and 'data' in message ) ) : valid = True return valid | Confirm the validitiy of a given dict as an OpenXC message . |
38,404 | def value ( self , new_value ) : if self . unit != units . Undefined and new_value . unit != self . unit : raise AttributeError ( "%s must be in %s" % ( self . __class__ , self . unit ) ) self . _value = new_value | Set the value of this measurement . |
38,405 | def from_dict ( cls , data ) : args = [ ] if 'id' in data and 'data' in data : measurement_class = CanMessage args . append ( "Bus %s: 0x%x" % ( data . get ( 'bus' , '?' ) , data [ 'id' ] ) ) args . append ( data [ 'data' ] ) else : measurement_class = cls . _class_from_name ( data [ 'name' ] ) if measurement_class == Measurement : args . append ( data [ 'name' ] ) args . append ( data [ 'value' ] ) return measurement_class ( * args , event = data . get ( 'event' , None ) , override_unit = True ) | Create a new Measurement subclass instance using the given dict . |
38,406 | def name_from_class ( cls , measurement_class ) : if not getattr ( cls , '_measurements_initialized' , False ) : cls . _measurement_map = dict ( ( m . name , m ) for m in all_measurements ( ) ) cls . _measurements_initialized = True try : name = getattr ( measurement_class , 'name' ) except AttributeError : raise UnrecognizedMeasurementError ( "No 'name' attribute in %s" % measurement_class ) else : cls . _measurement_map [ name ] = measurement_class return name | For a given measurement class return its generic name . |
38,407 | def _store_timestamp ( self , timestamp ) : if getattr ( self , 'first_timestamp' , None ) is None : self . first_timestamp = timestamp LOG . debug ( "Storing %d as the first timestamp of the trace file %s" , self . first_timestamp , self . filename ) | If not already saved cache the first timestamp in the active trace file on the instance . |
38,408 | def read ( self ) : line = self . trace_file . readline ( ) if line == '' : if self . loop : self . _reopen_file ( ) else : self . trace_file . close ( ) self . trace_file = None raise DataSourceError ( ) message = JsonFormatter . deserialize ( line ) timestamp = message . get ( 'timestamp' , None ) if self . realtime and timestamp is not None : self . _store_timestamp ( timestamp ) self . _wait ( self . starting_time , self . first_timestamp , timestamp ) return line + "\x00" | Read a line of data from the input source at a time . |
38,409 | def _open_file ( filename ) : if filename is None : raise DataSourceError ( "Trace filename is not defined" ) try : trace_file = open ( filename , "r" ) except IOError as e : raise DataSourceError ( "Unable to open trace file %s" % filename , e ) else : LOG . debug ( "Opened trace file %s" , filename ) return trace_file | Attempt to open the the file at filename for reading . |
38,410 | def _wait ( starting_time , first_timestamp , timestamp ) : target_time = starting_time + ( timestamp - first_timestamp ) time . sleep ( max ( target_time - time . time ( ) , 0 ) ) | Given that the first timestamp in the trace file is first_timestamp and we started playing back the file at starting_time block until the current timestamp should occur . |
38,411 | def from_xml_node ( cls , node ) : return cls ( name = node . find ( "Name" ) . text , bit_position = int ( node . find ( "Bitposition" ) . text ) , bit_size = int ( node . find ( "Bitsize" ) . text ) , factor = float ( node . find ( "Factor" ) . text ) , offset = float ( node . find ( "Offset" ) . text ) , min_value = float ( node . find ( "Minimum" ) . text ) , max_value = float ( node . find ( "Maximum" ) . text ) ) | Construct a Signal instance from an XML node exported from a Vector CANoe . dbc file . |
38,412 | def run ( self ) : message_buffer = b"" while self . running : try : message_buffer += self . source . read_logs ( ) except DataSourceError as e : if self . running : LOG . warn ( "Can't read logs from data source -- stopping: %s" , e ) break except NotImplementedError as e : LOG . info ( "%s doesn't support logging" % self ) break while True : if "\x00" not in message_buffer : break record , _ , remainder = message_buffer . partition ( b"\x00" ) self . record ( record ) message_buffer = remainder | Continuously read data from the source and attempt to parse a valid message from the buffer of bytes . When a message is parsed passes it off to the callback if one is set . |
38,413 | def compute ( self , t , yerr = 1.123e-12 , check_sorted = True , A = None , U = None , V = None ) : t = np . atleast_1d ( t ) if check_sorted and np . any ( np . diff ( t ) < 0.0 ) : raise ValueError ( "the input coordinates must be sorted" ) if check_sorted and len ( t . shape ) > 1 : raise ValueError ( "dimension mismatch" ) self . _t = t self . _yerr = np . empty_like ( self . _t ) self . _yerr [ : ] = yerr ( alpha_real , beta_real , alpha_complex_real , alpha_complex_imag , beta_complex_real , beta_complex_imag ) = self . kernel . coefficients self . _A = np . empty ( 0 ) if A is None else A self . _U = np . empty ( ( 0 , 0 ) ) if U is None else U self . _V = np . empty ( ( 0 , 0 ) ) if V is None else V self . solver . compute ( self . kernel . jitter , alpha_real , beta_real , alpha_complex_real , alpha_complex_imag , beta_complex_real , beta_complex_imag , self . _A , self . _U , self . _V , t , self . _yerr ** 2 ) self . dirty = False | Compute the extended form of the covariance matrix and factorize |
38,414 | def log_likelihood ( self , y , _const = math . log ( 2.0 * math . pi ) , quiet = False ) : y = self . _process_input ( y ) resid = y - self . mean . get_value ( self . _t ) try : self . _recompute ( ) except solver . LinAlgError : if quiet : return - np . inf raise if len ( y . shape ) > 1 : raise ValueError ( "dimension mismatch" ) logdet = self . solver . log_determinant ( ) if not np . isfinite ( logdet ) : return - np . inf loglike = - 0.5 * ( self . solver . dot_solve ( resid ) + logdet + len ( y ) * _const ) if not np . isfinite ( loglike ) : return - np . inf return loglike | Compute the marginalized likelihood of the GP model |
38,415 | def grad_log_likelihood ( self , y , quiet = False ) : if not solver . has_autodiff ( ) : raise RuntimeError ( "celerite must be compiled with autodiff " "support to use the gradient methods" ) if not self . kernel . vector_size : return self . log_likelihood ( y , quiet = quiet ) , np . empty ( 0 ) y = self . _process_input ( y ) if len ( y . shape ) > 1 : raise ValueError ( "dimension mismatch" ) resid = y - self . mean . get_value ( self . _t ) ( alpha_real , beta_real , alpha_complex_real , alpha_complex_imag , beta_complex_real , beta_complex_imag ) = self . kernel . coefficients try : val , grad = self . solver . grad_log_likelihood ( self . kernel . jitter , alpha_real , beta_real , alpha_complex_real , alpha_complex_imag , beta_complex_real , beta_complex_imag , self . _A , self . _U , self . _V , self . _t , resid , self . _yerr ** 2 ) except solver . LinAlgError : if quiet : return - np . inf , np . zeros ( self . vector_size ) raise if self . kernel . _has_coeffs : coeffs_jac = self . kernel . get_coeffs_jacobian ( ) full_grad = np . dot ( coeffs_jac , grad [ 1 : ] ) else : full_grad = np . zeros ( self . kernel . vector_size ) if self . kernel . _has_jitter : jitter_jac = self . kernel . get_jitter_jacobian ( ) full_grad += jitter_jac * grad [ 0 ] if self . mean . vector_size : self . _recompute ( ) alpha = self . solver . solve ( resid ) g = self . mean . get_gradient ( self . _t ) full_grad = np . append ( full_grad , np . dot ( g , alpha ) ) return val , full_grad | Compute the gradient of the marginalized likelihood |
38,416 | def apply_inverse ( self , y ) : self . _recompute ( ) return self . solver . solve ( self . _process_input ( y ) ) | Apply the inverse of the covariance matrix to a vector or matrix |
38,417 | def dot ( self , y , t = None , A = None , U = None , V = None , kernel = None , check_sorted = True ) : if kernel is None : kernel = self . kernel if t is not None : t = np . atleast_1d ( t ) if check_sorted and np . any ( np . diff ( t ) < 0.0 ) : raise ValueError ( "the input coordinates must be sorted" ) if check_sorted and len ( t . shape ) > 1 : raise ValueError ( "dimension mismatch" ) A = np . empty ( 0 ) if A is None else A U = np . empty ( ( 0 , 0 ) ) if U is None else U V = np . empty ( ( 0 , 0 ) ) if V is None else V else : if not self . computed : raise RuntimeError ( "you must call 'compute' first" ) t = self . _t A = self . _A U = self . _U V = self . _V ( alpha_real , beta_real , alpha_complex_real , alpha_complex_imag , beta_complex_real , beta_complex_imag ) = kernel . coefficients return self . solver . dot ( kernel . jitter , alpha_real , beta_real , alpha_complex_real , alpha_complex_imag , beta_complex_real , beta_complex_imag , A , U , V , t , np . ascontiguousarray ( y , dtype = float ) ) | Dot the covariance matrix into a vector or matrix |
38,418 | def predict ( self , y , t = None , return_cov = True , return_var = False ) : y = self . _process_input ( y ) if len ( y . shape ) > 1 : raise ValueError ( "dimension mismatch" ) if t is None : xs = self . _t else : xs = np . ascontiguousarray ( t , dtype = float ) if len ( xs . shape ) > 1 : raise ValueError ( "dimension mismatch" ) self . _recompute ( ) resid = y - self . mean . get_value ( self . _t ) if t is None : alpha = self . solver . solve ( resid ) . flatten ( ) alpha = resid - ( self . _yerr ** 2 + self . kernel . jitter ) * alpha elif not len ( self . _A ) : alpha = self . solver . predict ( resid , xs ) else : Kxs = self . get_matrix ( xs , self . _t ) alpha = np . dot ( Kxs , alpha ) mu = self . mean . get_value ( xs ) + alpha if not ( return_var or return_cov ) : return mu Kxs = self . get_matrix ( xs , self . _t ) KxsT = np . ascontiguousarray ( Kxs . T , dtype = np . float64 ) if return_var : var = - np . sum ( KxsT * self . apply_inverse ( KxsT ) , axis = 0 ) var += self . kernel . get_value ( 0.0 ) return mu , var cov = self . kernel . get_value ( xs [ : , None ] - xs [ None , : ] ) cov -= np . dot ( Kxs , self . apply_inverse ( KxsT ) ) return mu , cov | Compute the conditional predictive distribution of the model |
38,419 | def get_matrix ( self , x1 = None , x2 = None , include_diagonal = None , include_general = None ) : if x1 is None and x2 is None : if self . _t is None or not self . computed : raise RuntimeError ( "you must call 'compute' first" ) K = self . kernel . get_value ( self . _t [ : , None ] - self . _t [ None , : ] ) if include_diagonal is None or include_diagonal : K [ np . diag_indices_from ( K ) ] += ( self . _yerr ** 2 + self . kernel . jitter ) if ( include_general is None or include_general ) and len ( self . _A ) : K [ np . diag_indices_from ( K ) ] += self . _A K += np . tril ( np . dot ( self . _U . T , self . _V ) , - 1 ) K += np . triu ( np . dot ( self . _V . T , self . _U ) , 1 ) return K incl = False x1 = np . ascontiguousarray ( x1 , dtype = float ) if x2 is None : x2 = x1 incl = include_diagonal is not None and include_diagonal K = self . kernel . get_value ( x1 [ : , None ] - x2 [ None , : ] ) if incl : K [ np . diag_indices_from ( K ) ] += self . kernel . jitter return K | Get the covariance matrix at given independent coordinates |
38,420 | def sample ( self , size = None ) : self . _recompute ( ) if size is None : n = np . random . randn ( len ( self . _t ) ) else : n = np . random . randn ( len ( self . _t ) , size ) n = self . solver . dot_L ( n ) if size is None : return self . mean . get_value ( self . _t ) + n [ : , 0 ] return self . mean . get_value ( self . _t ) [ None , : ] + n . T | Sample from the prior distribution over datasets |
38,421 | def get_value ( self , tau ) : tau = np . asarray ( tau ) ( alpha_real , beta_real , alpha_complex_real , alpha_complex_imag , beta_complex_real , beta_complex_imag ) = self . coefficients k = get_kernel_value ( alpha_real , beta_real , alpha_complex_real , alpha_complex_imag , beta_complex_real , beta_complex_imag , tau . flatten ( ) , ) return np . asarray ( k ) . reshape ( tau . shape ) | Compute the value of the term for an array of lags |
38,422 | def get_psd ( self , omega ) : w = np . asarray ( omega ) ( alpha_real , beta_real , alpha_complex_real , alpha_complex_imag , beta_complex_real , beta_complex_imag ) = self . coefficients p = get_psd_value ( alpha_real , beta_real , alpha_complex_real , alpha_complex_imag , beta_complex_real , beta_complex_imag , w . flatten ( ) , ) return p . reshape ( w . shape ) | Compute the PSD of the term for an array of angular frequencies |
38,423 | def coefficients ( self ) : vector = self . get_parameter_vector ( include_frozen = True ) pars = self . get_all_coefficients ( vector ) if len ( pars ) != 6 : raise ValueError ( "there must be 6 coefficient blocks" ) if any ( len ( p . shape ) != 1 for p in pars ) : raise ValueError ( "coefficient blocks must be 1D" ) if len ( pars [ 0 ] ) != len ( pars [ 1 ] ) : raise ValueError ( "coefficient blocks must have the same shape" ) if any ( len ( pars [ 2 ] ) != len ( p ) for p in pars [ 3 : ] ) : raise ValueError ( "coefficient blocks must have the same shape" ) return pars | All of the coefficient arrays |
38,424 | def _determine_current_dimension_size ( self , dim_name , max_size ) : if self . dimensions [ dim_name ] is not None : return max_size def _find_dim ( h5group , dim ) : if dim not in h5group : return _find_dim ( h5group . parent , dim ) return h5group [ dim ] dim_variable = _find_dim ( self . _h5group , dim_name ) if "REFERENCE_LIST" not in dim_variable . attrs : return max_size root = self . _h5group [ "/" ] for ref , _ in dim_variable . attrs [ "REFERENCE_LIST" ] : var = root [ ref ] for i , var_d in enumerate ( var . dims ) : name = _name_from_dimension ( var_d ) if name == dim_name : max_size = max ( var . shape [ i ] , max_size ) return max_size | Helper method to determine the current size of a dimension . |
38,425 | def _create_dim_scales ( self ) : dim_order = self . _dim_order . maps [ 0 ] for dim in sorted ( dim_order , key = lambda d : dim_order [ d ] ) : if dim not in self . _h5group : size = self . _current_dim_sizes [ dim ] kwargs = { } if self . _dim_sizes [ dim ] is None : kwargs [ "maxshape" ] = ( None , ) self . _h5group . create_dataset ( name = dim , shape = ( size , ) , dtype = 'S1' , ** kwargs ) h5ds = self . _h5group [ dim ] h5ds . attrs [ '_Netcdf4Dimid' ] = dim_order [ dim ] if len ( h5ds . shape ) > 1 : dims = self . _variables [ dim ] . dimensions coord_ids = np . array ( [ dim_order [ d ] for d in dims ] , 'int32' ) h5ds . attrs [ '_Netcdf4Coordinates' ] = coord_ids scale_name = dim if dim in self . variables else NOT_A_VARIABLE h5ds . dims . create_scale ( h5ds , scale_name ) for subgroup in self . groups . values ( ) : subgroup . _create_dim_scales ( ) | Create all necessary HDF5 dimension scale . |
38,426 | def _attach_dim_scales ( self ) : for name , var in self . variables . items ( ) : if name not in self . dimensions : for n , dim in enumerate ( var . dimensions ) : var . _h5ds . dims [ n ] . attach_scale ( self . _all_h5groups [ dim ] ) for subgroup in self . groups . values ( ) : subgroup . _attach_dim_scales ( ) | Attach dimension scales to all variables . |
38,427 | def _detach_dim_scale ( self , name ) : for var in self . variables . values ( ) : for n , dim in enumerate ( var . dimensions ) : if dim == name : var . _h5ds . dims [ n ] . detach_scale ( self . _all_h5groups [ dim ] ) for subgroup in self . groups . values ( ) : if dim not in subgroup . _h5group : subgroup . _detach_dim_scale ( name ) | Detach the dimension scale corresponding to a dimension name . |
38,428 | def resize_dimension ( self , dimension , size ) : if self . dimensions [ dimension ] is not None : raise ValueError ( "Dimension '%s' is not unlimited and thus " "cannot be resized." % dimension ) self . _current_dim_sizes [ dimension ] = size for var in self . variables . values ( ) : new_shape = list ( var . shape ) for i , d in enumerate ( var . dimensions ) : if d == dimension : new_shape [ i ] = size new_shape = tuple ( new_shape ) if new_shape != var . shape : var . _h5ds . resize ( new_shape ) for i in self . groups . values ( ) : i . resize_dimension ( dimension , size ) | Resize a dimension to a certain size . |
38,429 | def alignVec_quat ( vec ) : alpha = np . arctan2 ( vec [ 1 ] , vec [ 0 ] ) beta = np . arccos ( vec [ 2 ] ) gamma = - alpha * vec [ 2 ] cb = np . cos ( 0.5 * beta ) sb = np . sin ( 0.5 * beta ) return np . array ( [ cb * np . cos ( 0.5 * ( alpha + gamma ) ) , sb * np . sin ( 0.5 * ( gamma - alpha ) ) , sb * np . cos ( 0.5 * ( gamma - alpha ) ) , cb * np . sin ( 0.5 * ( alpha + gamma ) ) ] ) | Returns a unit quaternion that will align vec with the z - axis |
38,430 | def rotate_in_plane ( chi , phase ) : v = chi . T sp = np . sin ( phase ) cp = np . cos ( phase ) res = 1. * v res [ 0 ] = v [ 0 ] * cp + v [ 1 ] * sp res [ 1 ] = v [ 1 ] * cp - v [ 0 ] * sp return res . T | For transforming spins between the coprecessing and coorbital frames |
38,431 | def transform_error_coorb_to_inertial ( vec_coorb , vec_err_coorb , orbPhase , quat_copr ) : np . random . seed ( 0 ) dist_coorb = np . array ( [ np . random . normal ( m , s , 1000 ) for m , s in zip ( vec_coorb , vec_err_coorb ) ] ) . T dist_copr = rotate_in_plane ( dist_coorb , - orbPhase ) dist_inertial = transformTimeDependentVector ( np . array ( [ quat_copr for _ in dist_copr ] ) . T , dist_copr . T ) . T vec_err_inertial = np . std ( dist_inertial , axis = 0 ) return vec_err_inertial | Transform error in a vector from the coorbital frame to the inertial frame . Generates distributions in the coorbital frame transforms them to inertial frame and returns 1 - simga widths in the inertial frame . |
38,432 | def _extra_regression_kwargs ( self ) : omega_switch_test = 0.019 extra_args = [ ] extra_args . append ( { 'omega0' : 5e-3 , 'PN_approximant' : 'SpinTaylorT4' , 'PN_dt' : 0.1 , 'PN_spin_order' : 7 , 'PN_phase_order' : 7 , 'omega_switch' : omega_switch_test , } ) extra_args . append ( { 'omega0' : 6e-3 , 'PN_approximant' : 'SpinTaylorT1' , 'PN_dt' : 0.5 , 'PN_spin_order' : 5 , 'PN_phase_order' : 7 , 'omega_switch' : omega_switch_test , } ) extra_args . append ( { 'omega0' : 7e-3 , 'PN_approximant' : 'SpinTaylorT2' , 'PN_dt' : 1 , 'PN_spin_order' : 7 , 'PN_phase_order' : 5 , 'omega_switch' : omega_switch_test , } ) extra_args . append ( { 'omega0' : 3e-2 } ) extra_args . append ( { 'omega0' : 5e-2 } ) return extra_args | List of additional kwargs to use in regression tests . |
38,433 | def _evolve_spins ( self , q , chiA0 , chiB0 , omega0 , PN_approximant , PN_dt , PN_spin0 , PN_phase0 , omega0_nrsur ) : if omega0 < omega0_nrsur : chiA0_nrsur_copr , chiB0_nrsur_copr , quat0_nrsur_copr , phi0_nrsur , omega0_nrsur = evolve_pn_spins ( q , chiA0 , chiB0 , omega0 , omega0_nrsur , approximant = PN_approximant , dt = PN_dt , spinO = PN_spin0 , phaseO = PN_phase0 ) else : chiA0_nrsur_copr , chiB0_nrsur_copr , quat0_nrsur_copr , phi0_nrsur , omega0_nrsur = chiA0 , chiB0 , [ 1 , 0 , 0 , 0 ] , 0 , omega0 if self . nrsur is None : self . _load_NRSur7dq2 ( ) quat , orbphase , chiA_copr , chiB_copr = self . nrsur . get_dynamics ( q , chiA0_nrsur_copr , chiB0_nrsur_copr , init_quat = quat0_nrsur_copr , init_phase = phi0_nrsur , omega_ref = omega0_nrsur , allow_extrapolation = True ) fitnode_time = - 100 nodeIdx = np . argmin ( np . abs ( self . nrsur . tds - fitnode_time ) ) quat_fitnode = quat . T [ nodeIdx ] orbphase_fitnode = orbphase [ nodeIdx ] chiA_coorb_fitnode = utils . rotate_in_plane ( chiA_copr [ nodeIdx ] , orbphase_fitnode ) chiB_coorb_fitnode = utils . rotate_in_plane ( chiB_copr [ nodeIdx ] , orbphase_fitnode ) return chiA_coorb_fitnode , chiB_coorb_fitnode , quat_fitnode , orbphase_fitnode | Evolves spins of the component BHs from an initial orbital frequency = omega0 until t = - 100 M from the peak of the waveform . If omega0 < omega0_nrsur use PN to evolve the spins until orbital frequency = omega0 . Then evolves further with the NRSur7dq2 waveform model until t = - 100M from the peak . |
38,434 | def _eval_wrapper ( self , fit_key , q , chiA , chiB , ** kwargs ) : chiA = np . array ( chiA ) chiB = np . array ( chiB ) allow_extrap = kwargs . pop ( 'allow_extrap' , False ) self . _check_param_limits ( q , chiA , chiB , allow_extrap ) omega0 = kwargs . pop ( 'omega0' , None ) PN_approximant = kwargs . pop ( 'PN_approximant' , 'SpinTaylorT4' ) PN_dt = kwargs . pop ( 'PN_dt' , 0.1 ) PN_spin_order = kwargs . pop ( 'PN_spin_order' , 7 ) PN_phase_order = kwargs . pop ( 'PN_phase_order' , 7 ) omega_switch = kwargs . pop ( 'omega_switch' , 0.018 ) self . _check_unused_kwargs ( kwargs ) if omega0 is None : x = np . concatenate ( ( [ q ] , chiA , chiB ) ) else : chiA_coorb_fitnode , chiB_coorb_fitnode , quat_fitnode , orbphase_fitnode = self . _evolve_spins ( q , chiA , chiB , omega0 , PN_approximant , PN_dt , PN_spin_order , PN_phase_order , omega_switch ) x = np . concatenate ( ( [ q ] , chiA_coorb_fitnode , chiB_coorb_fitnode ) ) def eval_vector_fit ( x , fit_key ) : res = self . _evaluate_fits ( x , fit_key ) fit_val = res . T [ 0 ] fit_err = res . T [ 1 ] if omega0 is not None : fit_val = utils . transform_vector_coorb_to_inertial ( fit_val , orbphase_fitnode , quat_fitnode ) fit_err = utils . transform_error_coorb_to_inertial ( fit_val , fit_err , orbphase_fitnode , quat_fitnode ) return fit_val , fit_err if fit_key == 'mf' or fit_key == 'all' : mf , mf_err = self . _evaluate_fits ( x , 'mf' ) if fit_key == 'mf' : return mf , mf_err if fit_key == 'chif' or fit_key == 'all' : chif , chif_err = eval_vector_fit ( x , 'chif' ) if fit_key == 'chif' : return chif , chif_err if fit_key == 'vf' or fit_key == 'all' : vf , vf_err = eval_vector_fit ( x , 'vf' ) if fit_key == 'vf' : return vf , vf_err if fit_key == 'all' : return mf , chif , vf , mf_err , chif_err , vf_err | Evaluates the surfinBH7dq2 model . |
38,435 | def LoadFits ( name ) : if name not in fits_collection . keys ( ) : raise Exception ( 'Invalid fit name : %s' % name ) else : testPath = DataPath ( ) + '/' + fits_collection [ name ] . data_url . split ( '/' ) [ - 1 ] if ( not os . path . isfile ( testPath ) ) : DownloadData ( name ) fit = fits_collection [ name ] . fit_class ( name . split ( 'surfinBH' ) [ - 1 ] ) print ( 'Loaded %s fit.' % name ) return fit | Loads data for a fit . If data is not available downloads it before loading . |
38,436 | def _eval_wrapper ( self , fit_key , q , chiA , chiB , ** kwargs ) : chiA = np . array ( chiA ) chiB = np . array ( chiB ) allow_extrap = kwargs . pop ( 'allow_extrap' , False ) self . _check_param_limits ( q , chiA , chiB , allow_extrap ) self . _check_unused_kwargs ( kwargs ) x = [ q , chiA [ 2 ] , chiB [ 2 ] ] if fit_key == 'mf' or fit_key == 'all' : mf , mf_err = self . _evaluate_fits ( x , 'mf' ) if fit_key == 'mf' : return mf , mf_err if fit_key == 'chif' or fit_key == 'all' : chifz , chifz_err = self . _evaluate_fits ( x , 'chifz' ) chif = np . array ( [ 0 , 0 , chifz ] ) chif_err = np . array ( [ 0 , 0 , chifz_err ] ) if fit_key == 'chif' : return chif , chif_err if fit_key == 'vf' or fit_key == 'all' : vfx , vfx_err = self . _evaluate_fits ( x , 'vfx' ) vfy , vfy_err = self . _evaluate_fits ( x , 'vfy' ) vf = np . array ( [ vfx , vfy , 0 ] ) vf_err = np . array ( [ vfx_err , vfy_err , 0 ] ) if fit_key == 'vf' : return vf , vf_err if fit_key == 'all' : return mf , chif , vf , mf_err , chif_err , vf_err | Evaluates the surfinBH3dq8 model . |
38,437 | def evolve_pn_spins ( q , chiA0 , chiB0 , omega0 , omegaTimesM_final , approximant = 'SpinTaylorT4' , dt = 0.1 , spinO = 7 , phaseO = 7 ) : omega , phi , chiA , chiB , lNhat , e1 = lal_spin_evloution_wrapper ( approximant , q , omega0 , chiA0 , chiB0 , dt , spinO , phaseO ) end_idx = np . argmin ( np . abs ( omega - omegaTimesM_final ) ) omegaTimesM_end = omega [ end_idx ] chiA_end = chiA [ end_idx ] chiB_end = chiB [ end_idx ] lNhat_end = lNhat [ end_idx ] phi_end = phi [ end_idx ] q_copr_end = _utils . alignVec_quat ( lNhat_end ) chiA_end_copr = _utils . transformTimeDependentVector ( np . array ( [ q_copr_end ] ) . T , np . array ( [ chiA_end ] ) . T , inverse = 1 ) . T [ 0 ] chiB_end_copr = _utils . transformTimeDependentVector ( np . array ( [ q_copr_end ] ) . T , np . array ( [ chiB_end ] ) . T , inverse = 1 ) . T [ 0 ] return chiA_end_copr , chiB_end_copr , q_copr_end , phi_end , omegaTimesM_end | Evolves PN spins from a starting orbital frequency and spins to a final frequency . |
38,438 | def qual ( obj ) : return u'{}.{}' . format ( obj . __class__ . __module__ , obj . __class__ . __name__ ) | Return fully qualified name of a class . |
38,439 | def count ( self , txn , prefix = None ) : key_from = struct . pack ( '>H' , self . _slot ) if prefix : key_from += self . _serialize_key ( prefix ) kfl = len ( key_from ) cnt = 0 cursor = txn . _txn . cursor ( ) has_more = cursor . set_range ( key_from ) while has_more : _key = cursor . key ( ) _prefix = _key [ : kfl ] if _prefix != key_from : break cnt += 1 has_more = cursor . next ( ) return cnt | Count number of records in the persistent map . When no prefix is given the total number of records is returned . When a prefix is given only the number of records with keys that have this prefix are counted . |
38,440 | def count_range ( self , txn , from_key , to_key ) : key_from = struct . pack ( '>H' , self . _slot ) + self . _serialize_key ( from_key ) to_key = struct . pack ( '>H' , self . _slot ) + self . _serialize_key ( to_key ) cnt = 0 cursor = txn . _txn . cursor ( ) has_more = cursor . set_range ( key_from ) while has_more : if cursor . key ( ) >= to_key : break cnt += 1 has_more = cursor . next ( ) return cnt | Counter number of records in the perstistent map with keys within the given range . |
38,441 | def _read_dict ( self , f ) : d = { } for k , item in f . items ( ) : if type ( item ) == h5py . _hl . dataset . Dataset : v = item . value if type ( v ) == np . string_ : v = str ( v ) if type ( v ) == str and v == "NONE" : d [ k ] = None elif type ( v ) == str and v == "EMPTYARR" : d [ k ] = np . array ( [ ] ) elif isinstance ( v , bytes ) : d [ k ] = v . decode ( 'utf-8' ) else : d [ k ] = v elif k [ : 5 ] == "DICT_" : d [ k [ 5 : ] ] = self . _read_dict ( item ) elif k [ : 5 ] == "LIST_" : tmpD = self . _read_dict ( item ) d [ k [ 5 : ] ] = [ tmpD [ str ( i ) ] for i in range ( len ( tmpD ) ) ] return d | Converts h5 groups to dictionaries |
38,442 | def _load_scalar_fit ( self , fit_key = None , h5file = None , fit_data = None ) : if ( fit_key is None ) ^ ( h5file is None ) : raise ValueError ( "Either specify both fit_key and h5file, or" " neither" ) if not ( ( fit_key is None ) ^ ( fit_data is None ) ) : raise ValueError ( "Specify exactly one of fit_key and fit_data." ) if fit_data is None : fit_data = self . _read_dict ( h5file [ fit_key ] ) if 'fitType' in fit_data . keys ( ) and fit_data [ 'fitType' ] == 'GPR' : fit = _eval_pysur . evaluate_fit . getGPRFitAndErrorEvaluator ( fit_data ) else : fit = _eval_pysur . evaluate_fit . getFitEvaluator ( fit_data ) return fit | Loads a single fit |
38,443 | def _load_vector_fit ( self , fit_key , h5file ) : vector_fit = [ ] for i in range ( len ( h5file [ fit_key ] . keys ( ) ) ) : fit_data = self . _read_dict ( h5file [ fit_key ] [ 'comp_%d' % i ] ) vector_fit . append ( self . _load_scalar_fit ( fit_data = fit_data ) ) return vector_fit | Loads a vector of fits |
38,444 | def _check_unused_kwargs ( self , kwargs ) : if len ( kwargs . keys ( ) ) != 0 : unused = "" for k in kwargs . keys ( ) : unused += "'%s', " % k if unused [ - 2 : ] == ", " : unused = unused [ : - 2 ] raise Exception ( 'Unused keys in kwargs: %s' % unused ) | Call this at the end of call module to check if all the kwargs have been used . Assumes kwargs were extracted using pop . |
38,445 | def _check_param_limits ( self , q , chiA , chiB , allow_extrap ) : if q < 1 : raise ValueError ( 'Mass ratio should be >= 1.' ) chiAmag = np . sqrt ( np . sum ( chiA ** 2 ) ) chiBmag = np . sqrt ( np . sum ( chiB ** 2 ) ) if chiAmag > 1 + 1e-14 : raise ValueError ( 'Spin magnitude of BhA > 1.' ) if chiBmag > 1 + 1e-14 : raise ValueError ( 'Spin magnitude of BhB > 1.' ) if self . aligned_spin_only : if np . sqrt ( np . sum ( chiA [ : 2 ] ** 2 ) ) > 1e-14 : raise ValueError ( 'The x & y components of chiA should be zero.' ) if np . sqrt ( np . sum ( chiB [ : 2 ] ** 2 ) ) > 1e-14 : raise ValueError ( 'The x & y components of chiB should be zero.' ) if allow_extrap : return if q > self . hard_param_lims [ 'q' ] + 1e-14 : raise ValueError ( 'Mass ratio outside allowed range.' ) elif q > self . soft_param_lims [ 'q' ] : warnings . warn ( 'Mass ratio outside training range.' ) if chiAmag > self . hard_param_lims [ 'chiAmag' ] + 1e-14 : raise ValueError ( 'Spin magnitude of BhA outside allowed range.' ) elif chiAmag > self . soft_param_lims [ 'chiAmag' ] : warnings . warn ( 'Spin magnitude of BhA outside training range.' ) if chiBmag > self . hard_param_lims [ 'chiBmag' ] + 1e-14 : raise ValueError ( 'Spin magnitude of BhB outside allowed range.' ) elif chiBmag > self . soft_param_lims [ 'chiBmag' ] : warnings . warn ( 'Spin magnitude of BhB outside training range.' ) | Checks that params are within allowed range of paramters . Raises a warning if outside self . soft_param_lims limits and raises an error if outside self . hard_param_lims . If allow_extrap = True skips these checks . |
38,446 | def slot ( self , slot_index , marshal = None , unmarshal = None , build = None , cast = None , compress = False ) : def decorate ( o ) : assert isinstance ( o , PersistentMap ) name = o . __class__ . __name__ assert slot_index not in self . _index_to_slot assert name not in self . _name_to_slot o . _zlmdb_slot = slot_index o . _zlmdb_marshal = marshal o . _zlmdb_unmarshal = unmarshal o . _zlmdb_build = build o . _zlmdb_cast = cast o . _zlmdb_compress = compress _slot = Slot ( slot_index , name , o ) self . _index_to_slot [ slot_index ] = _slot self . _name_to_slot [ name ] = _slot return o return decorate | Decorator for use on classes derived from zlmdb . PersistentMap . The decorator define slots in a LMDB database schema based on persistent maps and slot configuration . |
38,447 | def DataPath ( ) : return os . path . abspath ( '%s/data' % ( os . path . dirname ( os . path . realpath ( __file__ ) ) ) ) | Return the default path for fit data h5 files |
38,448 | def init_services ( service_definitions , service_context , state_db , client_authn_factory = None ) : service = { } for service_name , service_configuration in service_definitions . items ( ) : try : kwargs = service_configuration [ 'kwargs' ] except KeyError : kwargs = { } kwargs . update ( { 'service_context' : service_context , 'state_db' : state_db , 'client_authn_factory' : client_authn_factory } ) if isinstance ( service_configuration [ 'class' ] , str ) : _srv = util . importer ( service_configuration [ 'class' ] ) ( ** kwargs ) else : _srv = service_configuration [ 'class' ] ( ** kwargs ) try : service [ _srv . service_name ] = _srv except AttributeError : raise ValueError ( "Could not load '{}'" . format ( service_name ) ) return service | Initiates a set of services |
38,449 | def gather_request_args ( self , ** kwargs ) : ar_args = kwargs . copy ( ) for prop in self . msg_type . c_param . keys ( ) : if prop in ar_args : continue else : try : ar_args [ prop ] = getattr ( self . service_context , prop ) except AttributeError : try : ar_args [ prop ] = self . conf [ 'request_args' ] [ prop ] except KeyError : try : ar_args [ prop ] = self . service_context . register_args [ prop ] except KeyError : try : ar_args [ prop ] = self . default_request_args [ prop ] except KeyError : pass return ar_args | Go through the attributes that the message class can contain and add values if they are missing but exists in the client info or when there are default values . |
38,450 | def method_args ( self , context , ** kwargs ) : try : _args = self . conf [ context ] . copy ( ) except KeyError : _args = kwargs else : _args . update ( kwargs ) return _args | Collect the set of arguments that should be used by a set of methods |
38,451 | def do_pre_construct ( self , request_args , ** kwargs ) : _args = self . method_args ( 'pre_construct' , ** kwargs ) post_args = { } for meth in self . pre_construct : request_args , _post_args = meth ( request_args , service = self , ** _args ) post_args . update ( _post_args ) return request_args , post_args | Will run the pre_construct methods one by one in the order given . |
38,452 | def do_post_construct ( self , request_args , ** kwargs ) : _args = self . method_args ( 'post_construct' , ** kwargs ) for meth in self . post_construct : request_args = meth ( request_args , service = self , ** _args ) return request_args | Will run the post_construct methods one at the time in order . |
38,453 | def construct ( self , request_args = None , ** kwargs ) : if request_args is None : request_args = { } request_args , post_args = self . do_pre_construct ( request_args , ** kwargs ) if 'state' in self . msg_type . c_param and 'state' in kwargs : if 'state' not in request_args : request_args [ 'state' ] = kwargs [ 'state' ] _args = self . gather_request_args ( ** request_args ) request = self . msg_type ( ** _args ) return self . do_post_construct ( request , ** post_args ) | Instantiate the request as a message class instance with attribute values gathered in a pre_construct method or in the gather_request_args method . |
38,454 | def init_authentication_method ( self , request , authn_method , http_args = None , ** kwargs ) : if http_args is None : http_args = { } if authn_method : logger . debug ( 'Client authn method: {}' . format ( authn_method ) ) return self . client_authn_factory ( authn_method ) . construct ( request , self , http_args = http_args , ** kwargs ) else : return http_args | Will run the proper client authentication method . Each such method will place the necessary information in the necessary place . A method may modify the request . |
38,455 | def construct_request ( self , request_args = None , ** kwargs ) : if request_args is None : request_args = { } return self . construct ( request_args , ** kwargs ) | The method where everything is setup for sending the request . The request information is gathered and the where and how of sending the request is decided . |
38,456 | def get_endpoint ( self ) : if self . endpoint : return self . endpoint else : return self . service_context . provider_info [ self . endpoint_name ] | Find the service endpoint |
38,457 | def get_authn_header ( self , request , authn_method , ** kwargs ) : headers = { } if authn_method : h_arg = self . init_authentication_method ( request , authn_method , ** kwargs ) try : headers = h_arg [ 'headers' ] except KeyError : pass return headers | Construct an authorization specification to be sent in the HTTP header . |
38,458 | def get_request_parameters ( self , request_body_type = "" , method = "" , authn_method = '' , request_args = None , http_args = None , ** kwargs ) : if not method : method = self . http_method if not authn_method : authn_method = self . get_authn_method ( ) if not request_body_type : request_body_type = self . request_body_type request = self . construct_request ( request_args = request_args , ** kwargs ) _info = { 'method' : method } _args = kwargs . copy ( ) if self . service_context . issuer : _args [ 'iss' ] = self . service_context . issuer _headers = self . get_authn_header ( request , authn_method , authn_endpoint = self . endpoint_name , ** _args ) try : endpoint_url = kwargs [ 'endpoint' ] except KeyError : endpoint_url = self . get_endpoint ( ) _info [ 'url' ] = get_http_url ( endpoint_url , request , method = method ) if method == 'POST' : if request_body_type == 'urlencoded' : content_type = URL_ENCODED elif request_body_type in [ 'jws' , 'jwe' , 'jose' ] : content_type = JOSE_ENCODED else : content_type = JSON_ENCODED _info [ 'body' ] = get_http_body ( request , content_type ) _headers . update ( { 'Content-Type' : content_type } ) if _headers : _info [ 'headers' ] = _headers return _info | Builds the request message and constructs the HTTP headers . |
38,459 | def get_urlinfo ( info ) : if '?' in info or '#' in info : parts = urlparse ( info ) scheme , netloc , path , params , query , fragment = parts [ : 6 ] if query : info = query else : info = fragment return info | Pick out the fragment or query part from a URL . |
38,460 | def get_conf_attr ( self , attr , default = None ) : if attr in self . conf : return self . conf [ attr ] else : return default | Get the value of a attribute in the configuration |
38,461 | def post_parse_response ( self , response , ** kwargs ) : if "scope" not in response : try : _key = kwargs [ 'state' ] except KeyError : pass else : if _key : item = self . get_item ( oauth2 . AuthorizationRequest , 'auth_request' , _key ) try : response [ "scope" ] = item [ "scope" ] except KeyError : pass return response | Add scope claim to response from the request if not present in the response |
38,462 | def get_id_token_hint ( self , request_args = None , ** kwargs ) : request_args = self . multiple_extend_request_args ( request_args , kwargs [ 'state' ] , [ 'id_token' ] , [ 'auth_response' , 'token_response' , 'refresh_token_response' ] , orig = True ) try : request_args [ 'id_token_hint' ] = request_args [ 'id_token' ] except KeyError : pass else : del request_args [ 'id_token' ] return request_args , { } | Add id_token_hint to request |
38,463 | def get_state ( self , key ) : _data = self . state_db . get ( key ) if not _data : raise KeyError ( key ) else : return State ( ) . from_json ( _data ) | Get the state connected to a given key . |
38,464 | def store_item ( self , item , item_type , key ) : try : _state = self . get_state ( key ) except KeyError : _state = State ( ) try : _state [ item_type ] = item . to_json ( ) except AttributeError : _state [ item_type ] = item self . state_db . set ( key , _state . to_json ( ) ) | Store a service response . |
38,465 | def get_iss ( self , key ) : _state = self . get_state ( key ) if not _state : raise KeyError ( key ) return _state [ 'iss' ] | Get the Issuer ID |
38,466 | def extend_request_args ( self , args , item_cls , item_type , key , parameters , orig = False ) : try : item = self . get_item ( item_cls , item_type , key ) except KeyError : pass else : for parameter in parameters : if orig : try : args [ parameter ] = item [ parameter ] except KeyError : pass else : try : args [ parameter ] = item [ verified_claim_name ( parameter ) ] except KeyError : try : args [ parameter ] = item [ parameter ] except KeyError : pass return args | Add a set of parameters and their value to a set of request arguments . |
38,467 | def get_state_by_X ( self , x , xtyp ) : _state = self . state_db . get ( KEY_PATTERN [ xtyp ] . format ( x ) ) if _state : return _state else : raise KeyError ( 'Unknown {}: "{}"' . format ( xtyp , x ) ) | Find the state value by providing the x value . Will raise an exception if the x value is absent from the state data base . |
38,468 | def import_keys ( self , keyspec ) : for where , spec in keyspec . items ( ) : if where == 'file' : for typ , files in spec . items ( ) : if typ == 'rsa' : for fil in files : _key = RSAKey ( key = import_private_rsa_key_from_file ( fil ) , use = 'sig' ) _kb = KeyBundle ( ) _kb . append ( _key ) self . keyjar . add_kb ( '' , _kb ) elif where == 'url' : for iss , url in spec . items ( ) : kb = KeyBundle ( source = url ) self . keyjar . add_kb ( iss , kb ) | The client needs it s own set of keys . It can either dynamically create them or load them from local storage . This method can also fetch other entities keys provided the URL points to a JWKS . |
38,469 | def assertion_jwt ( client_id , keys , audience , algorithm , lifetime = 600 ) : _now = utc_time_sans_frac ( ) at = AuthnToken ( iss = client_id , sub = client_id , aud = audience , jti = rndstr ( 32 ) , exp = _now + lifetime , iat = _now ) logger . debug ( 'AuthnToken: {}' . format ( at . to_dict ( ) ) ) return at . to_jwt ( key = keys , algorithm = algorithm ) | Create a signed Json Web Token containing some information . |
38,470 | def valid_service_context ( service_context , when = 0 ) : eta = getattr ( service_context , 'client_secret_expires_at' , 0 ) now = when or utc_time_sans_frac ( ) if eta != 0 and eta < now : return False return True | Check if the client_secret has expired |
38,471 | def construct ( self , request , service = None , http_args = None , ** kwargs ) : if http_args is None : http_args = { } if "headers" not in http_args : http_args [ "headers" ] = { } try : passwd = kwargs [ "password" ] except KeyError : try : passwd = request [ "client_secret" ] except KeyError : passwd = service . service_context . client_secret try : user = kwargs [ "user" ] except KeyError : user = service . service_context . client_id credentials = "{}:{}" . format ( quote_plus ( user ) , quote_plus ( passwd ) ) authz = base64 . urlsafe_b64encode ( credentials . encode ( "utf-8" ) ) . decode ( "utf-8" ) http_args [ "headers" ] [ "Authorization" ] = "Basic {}" . format ( authz ) try : del request [ "client_secret" ] except ( KeyError , TypeError ) : pass if isinstance ( request , AccessTokenRequest ) and request [ 'grant_type' ] == 'authorization_code' : if 'client_id' not in request : try : request [ 'client_id' ] = service . service_context . client_id except AttributeError : pass else : try : _req = request . c_param [ "client_id" ] [ VREQUIRED ] except ( KeyError , AttributeError ) : _req = False if not _req : try : del request [ "client_id" ] except KeyError : pass return http_args | Construct a dictionary to be added to the HTTP request headers |
38,472 | def construct ( self , request , service = None , http_args = None , ** kwargs ) : _acc_token = '' for _token_type in [ 'access_token' , 'refresh_token' ] : _acc_token = find_token ( request , _token_type , service , ** kwargs ) if _acc_token : break if not _acc_token : raise KeyError ( 'No access or refresh token available' ) else : request [ "access_token" ] = _acc_token return http_args | Will add a token to the request if not present |
38,473 | def choose_algorithm ( self , context , ** kwargs ) : try : algorithm = kwargs [ "algorithm" ] except KeyError : algorithm = DEF_SIGN_ALG [ context ] if not algorithm : raise AuthnFailure ( "Missing algorithm specification" ) return algorithm | Pick signing algorithm |
38,474 | def get_signing_key ( self , algorithm , service_context ) : return service_context . keyjar . get_signing_key ( alg2keytype ( algorithm ) , alg = algorithm ) | Pick signing key based on signing algorithm to be used |
38,475 | def get_key_by_kid ( self , kid , algorithm , service_context ) : _key = service_context . keyjar . get_key_by_kid ( kid ) if _key : ktype = alg2keytype ( algorithm ) if _key . kty != ktype : raise NoMatchingKey ( "Wrong key type" ) else : return _key else : raise NoMatchingKey ( "No key with kid:%s" % kid ) | Pick a key that matches a given key ID and signing algorithm . |
38,476 | def construct ( self , request , service = None , http_args = None , ** kwargs ) : if 'client_assertion' in kwargs : request [ "client_assertion" ] = kwargs [ 'client_assertion' ] if 'client_assertion_type' in kwargs : request [ 'client_assertion_type' ] = kwargs [ 'client_assertion_type' ] else : request [ "client_assertion_type" ] = JWT_BEARER elif 'client_assertion' in request : if 'client_assertion_type' not in request : request [ "client_assertion_type" ] = JWT_BEARER else : algorithm = None _context = service . service_context if kwargs [ 'authn_endpoint' ] in [ 'token_endpoint' ] : try : algorithm = _context . behaviour [ 'token_endpoint_auth_signing_alg' ] except ( KeyError , AttributeError ) : pass audience = _context . provider_info [ 'token_endpoint' ] else : audience = _context . provider_info [ 'issuer' ] if not algorithm : algorithm = self . choose_algorithm ( ** kwargs ) ktype = alg2keytype ( algorithm ) try : if 'kid' in kwargs : signing_key = [ self . get_key_by_kid ( kwargs [ "kid" ] , algorithm , _context ) ] elif ktype in _context . kid [ "sig" ] : try : signing_key = [ self . get_key_by_kid ( _context . kid [ "sig" ] [ ktype ] , algorithm , _context ) ] except KeyError : signing_key = self . get_signing_key ( algorithm , _context ) else : signing_key = self . get_signing_key ( algorithm , _context ) except NoMatchingKey as err : logger . error ( "%s" % sanitize ( err ) ) raise try : _args = { 'lifetime' : kwargs [ 'lifetime' ] } except KeyError : _args = { } request [ "client_assertion" ] = assertion_jwt ( _context . client_id , signing_key , audience , algorithm , ** _args ) request [ "client_assertion_type" ] = JWT_BEARER try : del request [ "client_secret" ] except KeyError : pass if not request . c_param [ "client_id" ] [ VREQUIRED ] : try : del request [ "client_id" ] except KeyError : pass return { } | Constructs a client assertion and signs it with a key . The request is modified as a side effect . |
38,477 | def get_endpoint ( self ) : try : _iss = self . service_context . issuer except AttributeError : _iss = self . endpoint if _iss . endswith ( '/' ) : return OIDCONF_PATTERN . format ( _iss [ : - 1 ] ) else : return OIDCONF_PATTERN . format ( _iss ) | Find the issuer ID and from it construct the service endpoint |
38,478 | def _update_service_context ( self , resp , ** kwargs ) : issuer = self . service_context . issuer if "issuer" in resp : _pcr_issuer = resp [ "issuer" ] if resp [ "issuer" ] . endswith ( "/" ) : if issuer . endswith ( "/" ) : _issuer = issuer else : _issuer = issuer + "/" else : if issuer . endswith ( "/" ) : _issuer = issuer [ : - 1 ] else : _issuer = issuer try : self . service_context . allow [ 'issuer_mismatch' ] except KeyError : if _issuer != _pcr_issuer : raise OidcServiceError ( "provider info issuer mismatch '%s' != '%s'" % ( _issuer , _pcr_issuer ) ) else : _pcr_issuer = issuer self . service_context . issuer = _pcr_issuer self . service_context . provider_info = resp try : _srvs = self . service_context . service except AttributeError : pass else : if self . service_context . service : for key , val in resp . items ( ) : if key . endswith ( "_endpoint" ) : for _srv in self . service_context . service . values ( ) : if _srv . endpoint_name == key : _srv . endpoint = val try : kj = self . service_context . keyjar except KeyError : kj = KeyJar ( ) if 'jwks_uri' in resp : kj . load_keys ( _pcr_issuer , jwks_uri = resp [ 'jwks_uri' ] ) elif 'jwks' in resp : kj . load_keys ( _pcr_issuer , jwks = resp [ 'jwks' ] ) self . service_context . keyjar = kj | Deal with Provider Config Response . Based on the provider info response a set of parameters in different places needs to be set . |
38,479 | def get_http_url ( url , req , method = 'GET' ) : if method in [ "GET" , "DELETE" ] : if req . keys ( ) : _req = req . copy ( ) comp = urlsplit ( str ( url ) ) if comp . query : _req . update ( parse_qs ( comp . query ) ) _query = str ( _req . to_urlencoded ( ) ) return urlunsplit ( ( comp . scheme , comp . netloc , comp . path , _query , comp . fragment ) ) else : return url else : return url | Add a query part representing the request to a url that may already contain a query part . Only done if the HTTP method used is GET or DELETE . |
38,480 | def get_http_body ( req , content_type = URL_ENCODED ) : if URL_ENCODED in content_type : return req . to_urlencoded ( ) elif JSON_ENCODED in content_type : return req . to_json ( ) elif JOSE_ENCODED in content_type : return req else : raise UnSupported ( "Unsupported content type: '%s'" % content_type ) | Get the message into the format that should be places in the body part of a HTTP request . |
38,481 | def importer ( name ) : c1 , c2 = modsplit ( name ) module = importlib . import_module ( c1 ) return getattr ( module , c2 ) | Import by name |
38,482 | def rndstr ( size = 16 ) : _basech = string . ascii_letters + string . digits return "" . join ( [ rnd . choice ( _basech ) for _ in range ( size ) ] ) | Returns a string of random ascii characters or digits |
38,483 | def add_redirect_uris ( request_args , service = None , ** kwargs ) : _context = service . service_context if "redirect_uris" not in request_args : try : _cbs = _context . callbacks except AttributeError : request_args [ 'redirect_uris' ] = _context . redirect_uris else : _uris = [ v for k , v in _cbs . items ( ) if not k . startswith ( '__' ) ] request_args [ 'redirect_uris' ] = _uris return request_args , { } | Add redirect_uris to the request arguments . |
38,484 | def match_preferences ( self , pcr = None , issuer = None ) : if not pcr : pcr = self . service_context . provider_info regreq = oidc . RegistrationRequest for _pref , _prov in PREFERENCE2PROVIDER . items ( ) : try : vals = self . service_context . client_preferences [ _pref ] except KeyError : continue try : _pvals = pcr [ _prov ] except KeyError : try : _pvals = PROVIDER_DEFAULT [ _pref ] except KeyError : logger . info ( 'No info from provider on {} and no default' . format ( _pref ) ) _pvals = vals if isinstance ( vals , str ) : if vals in _pvals : self . service_context . behaviour [ _pref ] = vals else : try : vtyp = regreq . c_param [ _pref ] except KeyError : if isinstance ( vals , list ) : self . service_context . behaviour [ _pref ] = [ v for v in vals if v in _pvals ] elif vals in _pvals : self . service_context . behaviour [ _pref ] = vals else : if isinstance ( vtyp [ 0 ] , list ) : self . service_context . behaviour [ _pref ] = [ ] for val in vals : if val in _pvals : self . service_context . behaviour [ _pref ] . append ( val ) else : for val in vals : if val in _pvals : self . service_context . behaviour [ _pref ] = val break if _pref not in self . service_context . behaviour : raise ConfigurationError ( "OP couldn't match preference:%s" % _pref , pcr ) for key , val in self . service_context . client_preferences . items ( ) : if key in self . service_context . behaviour : continue try : vtyp = regreq . c_param [ key ] if isinstance ( vtyp [ 0 ] , list ) : pass elif isinstance ( val , list ) and not isinstance ( val , str ) : val = val [ 0 ] except KeyError : pass if key not in PREFERENCE2PROVIDER : self . service_context . behaviour [ key ] = val logger . debug ( 'service_context behaviour: {}' . format ( self . service_context . behaviour ) ) | Match the clients preferences against what the provider can do . This is to prepare for later client registration and or what functionality the client actually will use . In the client configuration the client preferences are expressed . These are then compared with the Provider Configuration information . If the Provider has left some claims out defaults specified in the standard will be used . |
38,485 | def soundexCode ( self , char ) : lang = get_language ( char ) try : if lang == "en_US" : return _soundex_map [ "soundex_en" ] [ charmap [ lang ] . index ( char ) ] else : return _soundex_map [ "soundex" ] [ charmap [ lang ] . index ( char ) ] except : pass return 0 | Return the soundex code for given character |
38,486 | def soundex ( self , name , length = 8 ) : sndx = [ ] fc = name [ 0 ] for c in name [ 1 : ] . lower ( ) : d = str ( self . soundexCode ( c ) ) if d == '0' : continue if len ( sndx ) == 0 : sndx . append ( d ) elif d != sndx [ - 1 ] : sndx . append ( d ) sndx . insert ( 0 , fc ) if get_language ( name [ 0 ] ) == 'en_US' : return '' . join ( sndx ) if len ( sndx ) < length : sndx . extend ( repeat ( '0' , length ) ) return '' . join ( sndx [ : length ] ) return '' . join ( sndx [ : length ] ) | Calculate soundex of given string |
38,487 | def compare ( self , string1 , string2 ) : if string1 == string2 : return 0 string1_lang = get_language ( string1 [ 0 ] ) string2_lang = get_language ( string2 [ 0 ] ) if ( string1_lang == 'en_US' and string2_lang != 'en_US' ) or ( string1_lang != 'en_US' and string2_lang == 'en_US' ) : return - 1 soundex1 = self . soundex ( string1 ) soundex2 = self . soundex ( string2 ) if soundex1 [ 1 : ] == soundex2 [ 1 : ] : if string1_lang == string2_lang : return 1 else : return 2 return - 1 | Compare soundex of given strings |
38,488 | def get_response_for_url ( self , url ) : if not url or "//" not in url : raise ValueError ( "Missing or invalid url: %s" % url ) render_url = self . BASE_URL + url headers = { 'X-Prerender-Token' : self . token , } r = self . session . get ( render_url , headers = headers , allow_redirects = False ) assert r . status_code < 500 return self . build_django_response_from_requests_response ( r ) | Accepts a fully - qualified url . Returns an HttpResponse passing through all headers and the status code . |
38,489 | def update_url ( self , url = None , regex = None ) : if not url and not regex : raise ValueError ( "Neither a url or regex was provided to update_url." ) headers = { 'X-Prerender-Token' : self . token , 'Content-Type' : 'application/json' , } data = { 'prerenderToken' : settings . PRERENDER_TOKEN , } if url : data [ "url" ] = url if regex : data [ "regex" ] = regex r = self . session . post ( self . RECACHE_URL , headers = headers , data = data ) return r . status_code < 500 | Accepts a fully - qualified url or regex . Returns True if successful False if not successful . |
38,490 | def update_url ( self , url = None ) : if not url : raise ValueError ( "Neither a url or regex was provided to update_url." ) post_url = "%s%s" % ( self . BASE_URL , url ) r = self . session . post ( post_url ) return int ( r . status_code ) < 500 | Accepts a fully - qualified url . Returns True if successful False if not successful . |
38,491 | def create ( self , validated_data ) : if 'user' not in validated_data : validated_data [ 'user' ] = self . context [ 'request' ] . user return super ( RefreshTokenSerializer , self ) . create ( validated_data ) | Override create to provide a user via request . user by default . |
38,492 | def has_object_permission ( self , request , view , obj ) : user = request . user if not user . is_authenticated : return False elif user . is_staff or user . is_superuser : return True return user == obj . user | Allow staff or superusers and the owner of the object itself . |
38,493 | def clear ( self ) : with self . _cond : to_notify = self . _initial - self . _value self . _value = self . _initial self . _cond . notify ( to_notify ) | Release the semaphore of all of its bounds setting the internal counter back to its original bind limit . Notify an equivalent amount of threads that they can run . |
38,494 | def _api_wrapper ( fn ) : def _convert ( value ) : if isinstance ( value , _datetime . date ) : return value . strftime ( '%s' ) return value @ _six . wraps ( fn ) def _fn ( self , command , ** params ) : with self . startup_lock : if self . timer . ident is None : self . timer . setDaemon ( True ) self . timer . start ( ) params = dict ( ( key , _convert ( value ) ) for key , value in _six . iteritems ( params ) if value is not None ) self . semaphore . acquire ( ) resp = fn ( self , command , ** params ) try : respdata = resp . json ( object_hook = _AutoCastDict ) except : resp . raise_for_status ( ) raise Exception ( 'No JSON object could be decoded' ) if 'error' in respdata : raise PoloniexCommandException ( respdata [ 'error' ] ) resp . raise_for_status ( ) return respdata return _fn | API function decorator that performs rate limiting and error checking . |
38,495 | def returnOrderBook ( self , currencyPair = 'all' , depth = '50' ) : return self . _public ( 'returnOrderBook' , currencyPair = currencyPair , depth = depth ) | Returns the order book for a given market as well as a sequence number for use with the Push API and an indicator specifying whether the market is frozen . You may set currencyPair to all to get the order books of all markets . |
38,496 | def returnDepositsWithdrawals ( self , start = 0 , end = 2 ** 32 - 1 ) : return self . _private ( 'returnDepositsWithdrawals' , start = start , end = end ) | Returns your deposit and withdrawal history within a range specified by the start and end POST parameters both of which should be given as UNIX timestamps . |
38,497 | def buy ( self , currencyPair , rate , amount , fillOrKill = None , immediateOrCancel = None , postOnly = None ) : return self . _private ( 'buy' , currencyPair = currencyPair , rate = rate , amount = amount , fillOrKill = fillOrKill , immediateOrCancel = immediateOrCancel , postOnly = postOnly ) | Places a limit buy order in a given market . Required POST parameters are currencyPair rate and amount . If successful the method will return the order number . You may optionally set fillOrKill immediateOrCancel postOnly to 1 . A fill - or - kill order will either fill in its entirety or be completely aborted . An immediate - or - cancel order can be partially or completely filled but any portion of the order that cannot be filled immediately will be canceled rather than left on the order book . A post - only order will only be placed if no portion of it fills immediately ; this guarantees you will never pay the taker fee on any part of the order that fills . |
38,498 | def moveOrder ( self , orderNumber , rate , amount = None , postOnly = None , immediateOrCancel = None ) : return self . _private ( 'moveOrder' , orderNumber = orderNumber , rate = rate , amount = amount , postOnly = postOnly , immediateOrCancel = immediateOrCancel ) | Cancels an order and places a new one of the same type in a single atomic transaction meaning either both operations will succeed or both will fail . Required POST parameters are orderNumber and rate ; you may optionally specify amount if you wish to change the amount of the new order . postOnly or immediateOrCancel may be specified for exchange orders but will have no effect on margin orders . |
38,499 | def withdraw ( self , currency , amount , address , paymentId = None ) : return self . _private ( 'withdraw' , currency = currency , amount = amount , address = address , paymentId = paymentId ) | Immediately places a withdrawal for a given currency with no email confirmation . In order to use this method the withdrawal privilege must be enabled for your API key . Required POST parameters are currency amount and address . For XMR withdrawals you may optionally specify paymentId . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.