idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
18,100
def cumprod ( vari , axis = None ) : if isinstance ( vari , Poly ) : if np . prod ( vari . shape ) == 1 : return vari . copy ( ) if axis is None : vari = chaospy . poly . shaping . flatten ( vari ) axis = 0 vari = chaospy . poly . shaping . rollaxis ( vari , axis ) out = [ vari [ 0 ] ] for poly in vari [ 1 : ] : out . ...
Perform the cumulative product of a shapeable quantity over a given axis .
18,101
def quad_leja ( order , dist ) : from chaospy . distributions import evaluation if len ( dist ) > 1 and evaluation . get_dependencies ( * list ( dist ) ) : raise evaluation . DependencyError ( "Leja quadrature do not supper distribution with dependencies." ) if len ( dist ) > 1 : if isinstance ( order , int ) : out = [...
Generate Leja quadrature node .
18,102
def create_objective ( dist , abscissas ) : abscissas_ = numpy . array ( abscissas [ 1 : - 1 ] ) def obj ( absisa ) : out = - numpy . sqrt ( dist . pdf ( absisa ) ) out *= numpy . prod ( numpy . abs ( abscissas_ - absisa ) ) return out return obj
Create objective function .
18,103
def create_weights ( nodes , dist ) : poly = chaospy . quad . generate_stieltjes ( dist , len ( nodes ) - 1 , retall = True ) [ 0 ] poly = chaospy . poly . flatten ( chaospy . poly . Poly ( poly ) ) weights_inverse = poly ( nodes ) weights = numpy . linalg . inv ( weights_inverse ) return weights [ : , 0 ]
Create weights for the Laja method .
18,104
def gill_king ( mat , eps = 1e-16 ) : if not scipy . sparse . issparse ( mat ) : mat = numpy . asfarray ( mat ) assert numpy . allclose ( mat , mat . T ) size = mat . shape [ 0 ] mat_diag = mat . diagonal ( ) gamma = abs ( mat_diag ) . max ( ) off_diag = abs ( mat - numpy . diag ( mat_diag ) ) . max ( ) delta = eps * m...
Gill - King algorithm for modified cholesky decomposition .
18,105
def _gill_king ( mat , beta , delta ) : size = mat . shape [ 0 ] if scipy . sparse . issparse ( mat ) : lowtri = scipy . sparse . eye ( * mat . shape ) else : lowtri = numpy . eye ( size ) d_vec = numpy . zeros ( size , dtype = float ) for idx in range ( size ) : if idx == 0 : idz = [ ] else : idz = numpy . s_ [ : idx ...
Backend function for the Gill - King algorithm .
18,106
def approximate_moment ( dist , K , retall = False , control_var = None , rule = "F" , order = 1000 , ** kws ) : dim = len ( dist ) shape = K . shape size = int ( K . size / dim ) K = K . reshape ( dim , size ) if dim > 1 : shape = shape [ 1 : ] X , W = quad . generate_quadrature ( order , dist , rule = rule , normaliz...
Approximation method for estimation of raw statistical moments .
18,107
def approximate_density ( dist , xloc , parameters = None , cache = None , eps = 1.e-7 ) : if parameters is None : parameters = dist . prm . copy ( ) if cache is None : cache = { } xloc = numpy . asfarray ( xloc ) lo , up = numpy . min ( xloc ) , numpy . max ( xloc ) mu = .5 * ( lo + up ) eps = numpy . where ( xloc < m...
Approximate the probability density function .
18,108
def create_van_der_corput_samples ( idx , number_base = 2 ) : assert number_base > 1 idx = numpy . asarray ( idx ) . flatten ( ) + 1 out = numpy . zeros ( len ( idx ) , dtype = float ) base = float ( number_base ) active = numpy . ones ( len ( idx ) , dtype = bool ) while numpy . any ( active ) : out [ active ] += ( id...
Van der Corput samples .
18,109
def add ( * args ) : if len ( args ) > 2 : return add ( args [ 0 ] , add ( args [ 1 ] , args [ 1 : ] ) ) if len ( args ) == 1 : return args [ 0 ] part1 , part2 = args if isinstance ( part2 , Poly ) : if part2 . dim > part1 . dim : part1 = chaospy . dimension . setdim ( part1 , part2 . dim ) elif part2 . dim < part1 . d...
Polynomial addition .
18,110
def mul ( * args ) : if len ( args ) > 2 : return add ( args [ 0 ] , add ( args [ 1 ] , args [ 1 : ] ) ) if len ( args ) == 1 : return args [ 0 ] part1 , part2 = args if not isinstance ( part2 , Poly ) : if isinstance ( part2 , ( float , int ) ) : part2 = np . asarray ( part2 ) if not part2 . shape : core = part1 . A ....
Polynomial multiplication .
18,111
def plot ( self , resolution_constant_regions = 20 , resolution_smooth_regions = 200 ) : if self . eps == 0 : x = [ ] y = [ ] for I , value in zip ( self . _indicator_functions , self . _values ) : x . append ( I . L ) y . append ( value ) x . append ( I . R ) y . append ( value ) return x , y else : n = float ( resolu...
Return arrays x y for plotting the piecewise constant function . Just the minimum number of straight lines are returned if eps = 0 otherwise resolution_constant_regions plotting intervals are insed in the constant regions with resolution_smooth_regions plotting intervals in the smoothed regions .
18,112
def gradient ( poly ) : return differential ( poly , chaospy . poly . collection . basis ( 1 , 1 , poly . dim ) )
Gradient of a polynomial .
18,113
def create_korobov_samples ( order , dim , base = 17797 ) : values = numpy . empty ( dim ) values [ 0 ] = 1 for idx in range ( 1 , dim ) : values [ idx ] = base * values [ idx - 1 ] % ( order + 1 ) grid = numpy . mgrid [ : dim , : order + 1 ] out = values [ grid [ 0 ] ] * ( grid [ 1 ] + 1 ) / ( order + 1. ) % 1. return...
Create Korobov lattice samples .
18,114
def quad_genz_keister ( order , dist , rule = 24 ) : assert isinstance ( rule , int ) if len ( dist ) > 1 : if isinstance ( order , int ) : values = [ quad_genz_keister ( order , d , rule ) for d in dist ] else : values = [ quad_genz_keister ( order [ i ] , dist [ i ] , rule ) for i in range ( len ( dist ) ) ] abscissa...
Genz - Keister quadrature rule .
18,115
def Perc ( poly , q , dist , sample = 10000 , ** kws ) : shape = poly . shape poly = polynomials . flatten ( poly ) q = numpy . array ( q ) / 100. dim = len ( dist ) Z = dist . sample ( sample , ** kws ) if dim == 1 : Z = ( Z , ) q = numpy . array ( [ q ] ) poly1 = poly ( * Z ) mi , ma = dist . range ( ) . reshape ( 2 ...
Percentile function .
18,116
def probabilistic_collocation ( order , dist , subset = .1 ) : abscissas , weights = chaospy . quad . collection . golub_welsch ( order , dist ) likelihood = dist . pdf ( abscissas ) alpha = numpy . random . random ( len ( weights ) ) alpha = likelihood > alpha * subset * numpy . max ( likelihood ) abscissas = abscissa...
Probabilistic collocation method .
18,117
def get_function ( rule , domain , normalize , ** parameters ) : from . . . distributions . baseclass import Dist if isinstance ( domain , Dist ) : lower , upper = domain . range ( ) parameters [ "dist" ] = domain else : lower , upper = numpy . array ( domain ) parameters [ "lower" ] = lower parameters [ "upper" ] = up...
Create a quadrature function and set default parameter values .
18,118
def fit_regression ( polynomials , abscissas , evals , rule = "LS" , retall = False , order = 0 , alpha = - 1 , ) : abscissas = numpy . asarray ( abscissas ) if len ( abscissas . shape ) == 1 : abscissas = abscissas . reshape ( 1 , * abscissas . shape ) evals = numpy . array ( evals ) poly_evals = polynomials ( * absci...
Fit a polynomial chaos expansion using linear regression .
18,119
def quad_genz_keister_24 ( order ) : order = sorted ( GENZ_KEISTER_24 . keys ( ) ) [ order ] abscissas , weights = GENZ_KEISTER_24 [ order ] abscissas = numpy . array ( abscissas ) weights = numpy . array ( weights ) weights /= numpy . sum ( weights ) abscissas *= numpy . sqrt ( 2 ) return abscissas , weights
Hermite Genz - Keister 24 rule .
18,120
def contains_call_signature ( caller , key ) : try : args = inspect . signature ( caller ) . parameters except AttributeError : args = inspect . getargspec ( caller ) . args return key in args
Check if a function or method call signature contains a specific argument .
18,121
def Sens_m_sample ( poly , dist , samples , rule = "R" ) : dim = len ( dist ) generator = Saltelli ( dist , samples , poly , rule = rule ) zeros = [ 0 ] * dim ones = [ 1 ] * dim index = [ 0 ] * dim variance = numpy . var ( generator [ zeros ] , - 1 ) matrix_0 = generator [ zeros ] matrix_1 = generator [ ones ] mean = ....
First order sensitivity indices estimated using Saltelli s method .
18,122
def Sens_m2_sample ( poly , dist , samples , rule = "R" ) : dim = len ( dist ) generator = Saltelli ( dist , samples , poly , rule = rule ) zeros = [ 0 ] * dim ones = [ 1 ] * dim index = [ 0 ] * dim variance = numpy . var ( generator [ zeros ] , - 1 ) matrix_0 = generator [ zeros ] matrix_1 = generator [ ones ] mean = ...
Second order sensitivity indices estimated using Saltelli s method .
18,123
def Sens_t_sample ( poly , dist , samples , rule = "R" ) : generator = Saltelli ( dist , samples , poly , rule = rule ) dim = len ( dist ) zeros = [ 0 ] * dim variance = numpy . var ( generator [ zeros ] , - 1 ) return numpy . array ( [ 1 - numpy . mean ( ( generator [ ~ index ] - generator [ zeros ] ) ** 2 , - 1 , ) /...
Total order sensitivity indices estimated using Saltelli s method .
18,124
def get_matrix ( self , indices ) : new = numpy . empty ( self . samples1 . shape ) for idx in range ( len ( indices ) ) : if indices [ idx ] : new [ idx ] = self . samples1 [ idx ] else : new [ idx ] = self . samples2 [ idx ] if self . poly : new = self . poly ( * new ) return new
Retrieve Saltelli matrix .
18,125
def generate_stieltjes ( dist , order , accuracy = 100 , normed = False , retall = False , ** kws ) : from . . import distributions assert not distributions . evaluation . get_dependencies ( dist ) if len ( dist ) > 1 : orth , norms , coeff1 , coeff2 = zip ( * [ generate_stieltjes ( _ , order , accuracy , normed , reta...
Discretized Stieltjes method .
18,126
def _stieltjes_analytical ( dist , order , normed ) : dimensions = len ( dist ) mom_order = numpy . arange ( order + 1 ) . repeat ( dimensions ) mom_order = mom_order . reshape ( order + 1 , dimensions ) . T coeff1 , coeff2 = dist . ttr ( mom_order ) coeff2 [ : , 0 ] = 1. poly = chaospy . poly . collection . core . var...
Stieltjes method with analytical recurrence coefficients .
18,127
def _stieltjes_approx ( dist , order , accuracy , normed , ** kws ) : kws [ "rule" ] = kws . get ( "rule" , "C" ) assert kws [ "rule" ] . upper ( ) != "G" absisas , weights = chaospy . quad . generate_quadrature ( accuracy , dist . range ( ) , ** kws ) weights = weights * dist . pdf ( absisas ) poly = chaospy . poly . ...
Stieltjes method with approximative recurrence coefficients .
18,128
def set_state ( seed_value = None , step = None ) : global RANDOM_SEED if seed_value is not None : RANDOM_SEED = seed_value if step is not None : RANDOM_SEED += step
Set random seed .
18,129
def rule_generator ( * funcs ) : dim = len ( funcs ) tensprod_rule = create_tensorprod_function ( funcs ) assert hasattr ( tensprod_rule , "__call__" ) mv_rule = create_mv_rule ( tensprod_rule , dim ) assert hasattr ( mv_rule , "__call__" ) return mv_rule
Constructor for creating multivariate quadrature generator .
18,130
def create_tensorprod_function ( funcs ) : dim = len ( funcs ) def tensprod_rule ( order , part = None ) : order = order * numpy . ones ( dim , int ) values = [ funcs [ idx ] ( order [ idx ] ) for idx in range ( dim ) ] abscissas = [ numpy . array ( _ [ 0 ] ) . flatten ( ) for _ in values ] abscissas = chaospy . quad ....
Combine 1 - D rules into multivariate rule using tensor product .
18,131
def create_mv_rule ( tensorprod_rule , dim ) : def mv_rule ( order , sparse = False , part = None ) : if sparse : order = numpy . ones ( dim , dtype = int ) * order tensorprod_rule_ = lambda order , part = part : tensorprod_rule ( order , part = part ) return chaospy . quad . sparse_grid ( tensorprod_rule_ , order ) re...
Convert tensor product rule into a multivariate quadrature generator .
18,132
def quad_fejer ( order , lower = 0 , upper = 1 , growth = False , part = None ) : order = numpy . asarray ( order , dtype = int ) . flatten ( ) lower = numpy . asarray ( lower ) . flatten ( ) upper = numpy . asarray ( upper ) . flatten ( ) dim = max ( lower . size , upper . size , order . size ) order = numpy . ones ( ...
Generate the quadrature abscissas and weights in Fejer quadrature .
18,133
def _fejer ( order , composite = None ) : r order = int ( order ) if order == 0 : return numpy . array ( [ .5 ] ) , numpy . array ( [ 1. ] ) order += 2 theta = ( order - numpy . arange ( order + 1 ) ) * numpy . pi / order abscisas = 0.5 * numpy . cos ( theta ) + 0.5 N , K = numpy . mgrid [ : order + 1 , : order // 2 ] ...
r Backend method .
18,134
def create_latin_hypercube_samples ( order , dim = 1 ) : randoms = numpy . random . random ( order * dim ) . reshape ( ( dim , order ) ) for dim_ in range ( dim ) : perm = numpy . random . permutation ( order ) randoms [ dim_ ] = ( perm + randoms [ dim_ ] ) / order return randoms
Latin Hypercube sampling .
18,135
def create_hammersley_samples ( order , dim = 1 , burnin = - 1 , primes = ( ) ) : if dim == 1 : return create_halton_samples ( order = order , dim = 1 , burnin = burnin , primes = primes ) out = numpy . empty ( ( dim , order ) , dtype = float ) out [ : dim - 1 ] = create_halton_samples ( order = order , dim = dim - 1 ,...
Create samples from the Hammersley set .
18,136
def create_primes ( threshold ) : if threshold == 2 : return [ 2 ] elif threshold < 2 : return [ ] numbers = list ( range ( 3 , threshold + 1 , 2 ) ) root_of_threshold = threshold ** 0.5 half = int ( ( threshold + 1 ) / 2 - 1 ) idx = 0 counter = 3 while counter <= root_of_threshold : if numbers [ idx ] : idy = int ( ( ...
Generate prime values using sieve of Eratosthenes method .
18,137
def evaluate_inverse ( distribution , u_data , cache = None , parameters = None ) : if cache is None : cache = { } out = numpy . zeros ( u_data . shape ) if hasattr ( distribution , "_ppf" ) : parameters = load_parameters ( distribution , "_ppf" , parameters = parameters , cache = cache ) out [ : ] = distribution . _pp...
Evaluate inverse Rosenblatt transformation .
18,138
def mom_recurse ( self , idxi , idxj , idxk ) : rank_ = min ( chaospy . bertran . rank ( idxi , self . dim ) , chaospy . bertran . rank ( idxj , self . dim ) , chaospy . bertran . rank ( idxk , self . dim ) ) par , axis0 = chaospy . bertran . parent ( idxk , self . dim ) gpar , _ = chaospy . bertran . parent ( par , se...
Backend mement main loop .
18,139
def Sens_m_nataf ( order , dist , samples , vals , ** kws ) : assert dist . __class__ . __name__ == "Copula" trans = dist . prm [ "trans" ] assert trans . __class__ . __name__ == "nataf" vals = numpy . array ( vals ) cov = trans . prm [ "C" ] cov = numpy . dot ( cov , cov . T ) marginal = dist . prm [ "dist" ] dim = le...
Variance - based decomposition through the Nataf distribution .
18,140
def quad_golub_welsch ( order , dist , accuracy = 100 , ** kws ) : order = numpy . array ( order ) * numpy . ones ( len ( dist ) , dtype = int ) + 1 _ , _ , coeff1 , coeff2 = chaospy . quad . generate_stieltjes ( dist , numpy . max ( order ) , accuracy = accuracy , retall = True , ** kws ) dimensions = len ( dist ) abs...
Golub - Welsch algorithm for creating quadrature nodes and weights .
18,141
def _golbub_welsch ( orders , coeff1 , coeff2 ) : abscisas , weights = [ ] , [ ] for dim , order in enumerate ( orders ) : if order : bands = numpy . zeros ( ( 2 , order ) ) bands [ 0 ] = coeff1 [ dim , : order ] bands [ 1 , : - 1 ] = numpy . sqrt ( coeff2 [ dim , 1 : order ] ) vals , vecs = scipy . linalg . eig_banded...
Recurrence coefficients to abscisas and weights .
18,142
def Kurt ( poly , dist = None , fisher = True , ** kws ) : if isinstance ( poly , distributions . Dist ) : x = polynomials . variable ( len ( poly ) ) poly , dist = x , poly else : poly = polynomials . Poly ( poly ) if fisher : adjust = 3 else : adjust = 0 shape = poly . shape poly = polynomials . flatten ( poly ) m1 =...
Kurtosis operator .
18,143
def basis ( start , stop = None , dim = 1 , sort = "G" , cross_truncation = 1. ) : if stop is None : start , stop = numpy . array ( 0 ) , start start = numpy . array ( start , dtype = int ) stop = numpy . array ( stop , dtype = int ) dim = max ( start . size , stop . size , dim ) indices = numpy . array ( chaospy . ber...
Create an N - dimensional unit polynomial basis .
18,144
def cutoff ( poly , * args ) : if len ( args ) == 1 : low , high = 0 , args [ 0 ] else : low , high = args [ : 2 ] core_old = poly . A core_new = { } for key in poly . keys : if low <= numpy . sum ( key ) < high : core_new [ key ] = core_old [ key ] return Poly ( core_new , poly . dim , poly . shape , poly . dtype )
Remove polynomial components with order outside a given interval .
18,145
def prange ( N = 1 , dim = 1 ) : A = { } r = numpy . arange ( N , dtype = int ) key = numpy . zeros ( dim , dtype = int ) for i in range ( N ) : key [ - 1 ] = i A [ tuple ( key ) ] = 1 * ( r == i ) return Poly ( A , dim , ( N , ) , int )
Constructor to create a range of polynomials where the exponent vary .
18,146
def rolldim ( P , n = 1 ) : dim = P . dim shape = P . shape dtype = P . dtype A = dict ( ( ( key [ n : ] + key [ : n ] , P . A [ key ] ) for key in P . keys ) ) return Poly ( A , dim , shape , dtype )
Roll the axes .
18,147
def swapdim ( P , dim1 = 1 , dim2 = 0 ) : if not isinstance ( P , Poly ) : return numpy . swapaxes ( P , dim1 , dim2 ) dim = P . dim shape = P . shape dtype = P . dtype if dim1 == dim2 : return P m = max ( dim1 , dim2 ) if P . dim <= m : P = chaospy . poly . dimension . setdim ( P , m + 1 ) dim = m + 1 A = { } for key ...
Swap the dim between two variables .
18,148
def tril ( P , k = 0 ) : A = P . A . copy ( ) for key in P . keys : A [ key ] = numpy . tril ( P . A [ key ] ) return Poly ( A , dim = P . dim , shape = P . shape )
Lower triangle of coefficients .
18,149
def tricu ( P , k = 0 ) : tri = numpy . sum ( numpy . mgrid [ [ slice ( 0 , _ , 1 ) for _ in P . shape ] ] , 0 ) tri = tri < len ( tri ) + k if isinstance ( P , Poly ) : A = P . A . copy ( ) B = { } for key in P . keys : B [ key ] = A [ key ] * tri return Poly ( B , shape = P . shape , dim = P . dim , dtype = P . dtype...
Cross - diagonal upper triangle .
18,150
def variable ( dims = 1 ) : if dims == 1 : return Poly ( { ( 1 , ) : 1 } , dim = 1 , shape = ( ) ) return Poly ( { tuple ( indices ) : indices for indices in numpy . eye ( dims , dtype = int ) } , dim = dims , shape = ( dims , ) )
Simple constructor to create single variables to create polynomials .
18,151
def all ( A , ax = None ) : if isinstance ( A , Poly ) : out = numpy . zeros ( A . shape , dtype = bool ) B = A . A for key in A . keys : out += all ( B [ key ] , ax ) return out return numpy . all ( A , ax )
Test if all values in A evaluate to True
18,152
def around ( A , decimals = 0 ) : if isinstance ( A , Poly ) : B = A . A . copy ( ) for key in A . keys : B [ key ] = around ( B [ key ] , decimals ) return Poly ( B , A . dim , A . shape , A . dtype ) return numpy . around ( A , decimals )
Evenly round to the given number of decimals .
18,153
def diag ( A , k = 0 ) : if isinstance ( A , Poly ) : core , core_new = A . A , { } for key in A . keys : core_new [ key ] = numpy . diag ( core [ key ] , k ) return Poly ( core_new , A . dim , None , A . dtype ) return numpy . diag ( A , k )
Extract or construct a diagonal polynomial array .
18,154
def prune ( A , threshold ) : if isinstance ( A , Poly ) : B = A . A . copy ( ) for key in A . keys : values = B [ key ] . copy ( ) values [ numpy . abs ( values ) < threshold ] = 0. B [ key ] = values return Poly ( B , A . dim , A . shape , A . dtype ) A = A . copy ( ) A [ numpy . abs ( A ) < threshold ] = 0. return A
Remove coefficients that is not larger than a given threshold .
18,155
def _range ( self , xloc , cache ) : uloc = numpy . zeros ( ( 2 , len ( self ) ) ) for dist in evaluation . sorted_dependencies ( self , reverse = True ) : if dist not in self . inverse_map : continue idx = self . inverse_map [ dist ] xloc_ = xloc [ idx ] . reshape ( 1 , - 1 ) uloc [ : , idx ] = evaluation . evaluate_b...
Special handle for finding bounds on constrained dists .
18,156
def Spearman ( poly , dist , sample = 10000 , retall = False , ** kws ) : samples = dist . sample ( sample , ** kws ) poly = polynomials . flatten ( poly ) Y = poly ( * samples ) if retall : return spearmanr ( Y . T ) return spearmanr ( Y . T ) [ 0 ]
Calculate Spearman s rank - order correlation coefficient .
18,157
def _diff ( self , x , th , eps ) : foo = lambda y : self . igen ( numpy . sum ( self . gen ( y , th ) , 0 ) , th ) out1 = out2 = 0. sign = 1 - 2 * ( x > .5 ) . T for I in numpy . ndindex ( * ( ( 2 , ) * ( len ( x ) - 1 ) + ( 1 , ) ) ) : eps_ = numpy . array ( I ) * eps x_ = ( x . T + sign * eps_ ) . T out1 += ( - 1 ) ...
Differentiation function .
18,158
def available_services ( ) : all_datas = ( ) data = ( ) for class_path in settings . TH_SERVICES : class_name = class_path . rsplit ( '.' , 1 ) [ 1 ] data = ( class_name , class_name . rsplit ( 'Service' , 1 ) [ 1 ] ) all_datas = ( data , ) + all_datas return all_datas
get the available services to be activated
18,159
def handle ( self , * args , ** options ) : trigger_id = options . get ( 'trigger_id' ) trigger = TriggerService . objects . filter ( id = int ( trigger_id ) , status = True , user__is_active = True , provider_failed__lt = settings . DJANGO_TH . get ( 'failed_tries' , 10 ) , consumer_failed__lt = settings . DJANGO_TH ....
get the trigger to fire
18,160
def read_data ( self , ** kwargs ) : trigger_id = kwargs . get ( 'trigger_id' ) trigger = Pushbullet . objects . get ( trigger_id = trigger_id ) date_triggered = kwargs . get ( 'date_triggered' ) data = list ( ) pushes = self . pushb . get_pushes ( ) for p in pushes : title = 'From Pushbullet' created = arrow . get ( p...
get the data from the service as the pushbullet service does not have any date in its API linked to the note add the triggered date to the dict data thus the service will be triggered when data will be found
18,161
def html_entity_decode_char ( self , m , defs = htmlentities . entitydefs ) : try : char = defs [ m . group ( 1 ) ] return "&{char};" . format ( char = char ) except ValueError : return m . group ( 0 ) except KeyError : return m . group ( 0 )
decode html entity into one of the html char
18,162
def html_entity_decode_codepoint ( self , m , defs = htmlentities . codepoint2name ) : try : char = defs [ m . group ( 1 ) ] return "&{char};" . format ( char = char ) except ValueError : return m . group ( 0 ) except KeyError : return m . group ( 0 )
decode html entity into one of the codepoint2name
18,163
def html_entity_decode ( self ) : pattern = re . compile ( r"&#(\w+?);" ) string = pattern . sub ( self . html_entity_decode_char , self . my_string ) return pattern . sub ( self . html_entity_decode_codepoint , string )
entry point of this set of tools to decode html entities
18,164
def read_data ( self , ** kwargs ) : trigger_id = kwargs . get ( 'trigger_id' ) date_triggered = kwargs . get ( 'date_triggered' ) data = list ( ) since = arrow . get ( date_triggered ) . timestamp if self . token is not None : pockets = self . pocket . get ( since = since , state = "unread" ) content = '' if pockets i...
get the data from the service As the pocket service does not have any date in its API linked to the note add the triggered date to the dict data thus the service will be triggered when data will be found
18,165
def remove_prohibited_element ( tag_name , document_element ) : elements = document_element . getElementsByTagName ( tag_name ) for element in elements : p = element . parentNode p . removeChild ( element )
To fit the Evernote DTD need drop this tag name
18,166
def _get_content ( data , which_content ) : content = '' if data . get ( which_content ) : if isinstance ( data . get ( which_content ) , feedparser . FeedParserDict ) : content = data . get ( which_content ) [ 'value' ] elif not isinstance ( data . get ( which_content ) , str ) : if 'value' in data . get ( which_conte...
get the content that could be hidden in the middle of content or summary detail from the data of the provider
18,167
def get_request_token ( self , request ) : if self . oauth == 'oauth1' : oauth = OAuth1Session ( self . consumer_key , client_secret = self . consumer_secret ) request_token = oauth . fetch_request_token ( self . REQ_TOKEN ) request . session [ 'oauth_token' ] = request_token [ 'oauth_token' ] request . session [ 'oaut...
request the token to the external service
18,168
def save_data ( self , trigger_id , ** data ) : title , content = super ( ServiceEvernote , self ) . save_data ( trigger_id , ** data ) trigger = Evernote . objects . get ( trigger_id = trigger_id ) note_store = self . _notestore ( trigger_id , data ) if isinstance ( note_store , evernote . api . client . Store ) : not...
let s save the data don t want to handle empty title nor content otherwise this will produce an Exception by the Evernote s API
18,169
def get_evernote_client ( self , token = None ) : if token : return EvernoteClient ( token = token , sandbox = self . sandbox ) else : return EvernoteClient ( consumer_key = self . consumer_key , consumer_secret = self . consumer_secret , sandbox = self . sandbox )
get the token from evernote
18,170
def auth ( self , request ) : client = self . get_evernote_client ( ) request_token = client . get_request_token ( self . callback_url ( request ) ) request . session [ 'oauth_token' ] = request_token [ 'oauth_token' ] request . session [ 'oauth_token_secret' ] = request_token [ 'oauth_token_secret' ] return client . g...
let s auth the user to the Service
18,171
def get_context_data ( self , ** kwargs ) : triggers_enabled = triggers_disabled = services_activated = ( ) context = super ( TriggerListView , self ) . get_context_data ( ** kwargs ) if self . kwargs . get ( 'trigger_filtered_by' ) : page_link = reverse ( 'trigger_filter_by' , kwargs = { 'trigger_filtered_by' : self ....
get the data of the view
18,172
def datas ( self ) : data = feedparser . parse ( self . URL_TO_PARSE , agent = self . USER_AGENT ) if data . bozo == 1 : data . entries = '' return data
read the data from a given URL or path to a local file
18,173
def finalcallback ( request , ** kwargs ) : default_provider . load_services ( ) service_name = kwargs . get ( 'service_name' ) service_object = default_provider . get_service ( service_name ) lets_callback = getattr ( service_object , 'callback' ) return render_to_response ( lets_callback ( request ) )
let s do the callback of the related service after the auth request from UserServiceCreateView
18,174
def filter_that ( self , criteria , data ) : import re prog = re . compile ( criteria ) return True if prog . match ( data ) else False
this method just use the module re to check if the data contain the string to find
18,175
def load_services ( self , services = settings . TH_SERVICES ) : kwargs = { } for class_path in services : module_name , class_name = class_path . rsplit ( '.' , 1 ) klass = import_from_path ( class_path ) service = klass ( None , ** kwargs ) self . register ( class_name , service )
get the service from the settings
18,176
def recycle ( ) : for service in cache . iter_keys ( 'th_*' ) : try : service_value = cache . get ( service , version = 2 ) cache . set ( service , service_value ) cache . delete_pattern ( service , version = 2 ) except ValueError : pass logger . info ( 'recycle of cache done!' )
the purpose of this tasks is to recycle the data from the cache with version = 2 in the main cache
18,177
def handle ( self , * args , ** options ) : now = arrow . utcnow ( ) . to ( settings . TIME_ZONE ) now = now . date ( ) digest = Digest . objects . filter ( date_end = str ( now ) ) . order_by ( 'user' , 'date_end' ) users = digest . distinct ( 'user' ) subject = 'Your digester' msg_plain = render_to_string ( 'digest/e...
get all the digest data to send to each user
18,178
def get_notebook ( note_store , my_notebook ) : notebook_id = 0 notebooks = note_store . listNotebooks ( ) for notebook in notebooks : if notebook . name . lower ( ) == my_notebook . lower ( ) : notebook_id = notebook . guid break return notebook_id
get the notebook from its name
18,179
def set_notebook ( note_store , my_notebook , notebook_id ) : if notebook_id == 0 : new_notebook = Types . Notebook ( ) new_notebook . name = my_notebook new_notebook . defaultNotebook = False notebook_id = note_store . createNotebook ( new_notebook ) . guid return notebook_id
create a notebook
18,180
def set_note_attribute ( data ) : na = False if data . get ( 'link' ) : na = Types . NoteAttributes ( ) na . sourceURL = data . get ( 'link' ) return na
add the link of the source in the note
18,181
def is_primitive ( val ) : return isinstance ( val , ( str , bool , float , complex , bytes , six . text_type ) + six . string_types + six . integer_types )
Checks if the passed value is a primitive type .
18,182
def split_every ( parts , iterable ) : return takewhile ( bool , ( list ( islice ( iterable , parts ) ) for _ in count ( ) ) )
Split an iterable into parts of length parts
18,183
def compute_partition_size ( result , processes ) : try : return max ( math . ceil ( len ( result ) / processes ) , 1 ) except TypeError : return 1
Attempts to compute the partition size to evenly distribute work across processes . Defaults to 1 if the length of result cannot be determined .
18,184
def evaluate ( self , sequence ) : last_cache_index = self . cache_scan ( ) transformations = self . transformations [ last_cache_index : ] return self . engine . evaluate ( sequence , transformations )
Compute the lineage on the sequence .
18,185
def _wrap ( value ) : if is_primitive ( value ) : return value if isinstance ( value , ( dict , set ) ) or is_namedtuple ( value ) : return value elif isinstance ( value , collections . Iterable ) : try : if type ( value ) . __name__ == 'DataFrame' : import pandas if isinstance ( value , pandas . DataFrame ) : return S...
Wraps the passed value in a Sequence if it is not a primitive . If it is a string argument it is expanded to a list of characters .
18,186
def cartesian ( self , * iterables , ** kwargs ) : return self . _transform ( transformations . cartesian_t ( iterables , kwargs . get ( 'repeat' , 1 ) ) )
Returns the cartesian product of the passed iterables with the specified number of repetitions .
18,187
def drop ( self , n ) : if n <= 0 : return self . _transform ( transformations . drop_t ( 0 ) ) else : return self . _transform ( transformations . drop_t ( n ) )
Drop the first n elements of the sequence .
18,188
def drop_right ( self , n ) : return self . _transform ( transformations . CACHE_T , transformations . drop_right_t ( n ) )
Drops the last n elements of the sequence .
18,189
def take ( self , n ) : if n <= 0 : return self . _transform ( transformations . take_t ( 0 ) ) else : return self . _transform ( transformations . take_t ( n ) )
Take the first n elements of the sequence .
18,190
def count ( self , func ) : n = 0 for element in self : if func ( element ) : n += 1 return n
Counts the number of elements in the sequence which satisfy the predicate func .
18,191
def reduce ( self , func , * initial ) : if len ( initial ) == 0 : return _wrap ( reduce ( func , self ) ) elif len ( initial ) == 1 : return _wrap ( reduce ( func , self , initial [ 0 ] ) ) else : raise ValueError ( 'reduce takes exactly one optional parameter for initial value' )
Reduce sequence of elements using func . API mirrors functools . reduce
18,192
def product ( self , projection = None ) : if self . empty ( ) : if projection : return projection ( 1 ) else : return 1 if self . size ( ) == 1 : if projection : return projection ( self . first ( ) ) else : return self . first ( ) if projection : return self . map ( projection ) . reduce ( mul ) else : return self . ...
Takes product of elements in sequence .
18,193
def sum ( self , projection = None ) : if projection : return sum ( self . map ( projection ) ) else : return sum ( self )
Takes sum of elements in sequence .
18,194
def average ( self , projection = None ) : length = self . size ( ) if projection : return sum ( self . map ( projection ) ) / length else : return sum ( self ) / length
Takes the average of elements in the sequence
18,195
def sliding ( self , size , step = 1 ) : return self . _transform ( transformations . sliding_t ( _wrap , size , step ) )
Groups elements in fixed size blocks by passing a sliding window over them .
18,196
def sorted ( self , key = None , reverse = False ) : return self . _transform ( transformations . sorted_t ( key = key , reverse = reverse ) )
Uses python sort and its passed arguments to sort the input .
18,197
def slice ( self , start , until ) : return self . _transform ( transformations . slice_t ( start , until ) )
Takes a slice of the sequence starting at start and until but not including until .
18,198
def to_list ( self , n = None ) : if n is None : self . cache ( ) return self . _base_sequence else : return self . cache ( ) . take ( n ) . list ( )
Converts sequence to list of elements .
18,199
def to_jsonl ( self , path , mode = 'wb' , compression = None ) : with universal_write_open ( path , mode = mode , compression = compression ) as output : output . write ( ( self . map ( json . dumps ) . make_string ( '\n' ) + '\n' ) . encode ( 'utf-8' ) )
Saves the sequence to a jsonl file . Each element is mapped using json . dumps then written with a newline separating each element .