idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
23,300
def regularization ( variables , regtype , regcoef , name = "regularization" ) : with tf . name_scope ( name ) : if regtype != 'none' : regs = tf . constant ( 0.0 ) for v in variables : if regtype == 'l2' : regs = tf . add ( regs , tf . nn . l2_loss ( v ) ) elif regtype == 'l1' : regs = tf . add ( regs , tf . reduce_sum ( tf . abs ( v ) ) ) return tf . multiply ( regcoef , regs ) else : return None
Compute the regularization tensor .
23,301
def accuracy ( mod_y , ref_y , summary = True , name = "accuracy" ) : with tf . name_scope ( name ) : mod_pred = tf . argmax ( mod_y , 1 ) correct_pred = tf . equal ( mod_pred , tf . argmax ( ref_y , 1 ) ) accuracy = tf . reduce_mean ( tf . cast ( correct_pred , tf . float32 ) ) if summary : tf . summary . scalar ( 'accuracy' , accuracy ) return accuracy
Accuracy computation op .
23,302
def pretrain_procedure ( self , layer_objs , layer_graphs , set_params_func , train_set , validation_set = None ) : next_train = train_set next_valid = validation_set for l , layer_obj in enumerate ( layer_objs ) : print ( 'Training layer {}...' . format ( l + 1 ) ) next_train , next_valid = self . _pretrain_layer_and_gen_feed ( layer_obj , set_params_func , next_train , next_valid , layer_graphs [ l ] ) return next_train , next_valid
Perform unsupervised pretraining of the model .
23,303
def _pretrain_layer_and_gen_feed ( self , layer_obj , set_params_func , train_set , validation_set , graph ) : layer_obj . fit ( train_set , train_set , validation_set , validation_set , graph = graph ) with graph . as_default ( ) : set_params_func ( layer_obj , graph ) next_train = layer_obj . transform ( train_set , graph = graph ) if validation_set is not None : next_valid = layer_obj . transform ( validation_set , graph = graph ) else : next_valid = None return next_train , next_valid
Pretrain a single autoencoder and encode the data for the next layer .
23,304
def get_layers_output ( self , dataset ) : layers_out = [ ] with self . tf_graph . as_default ( ) : with tf . Session ( ) as self . tf_session : self . tf_saver . restore ( self . tf_session , self . model_path ) for l in self . layer_nodes : layers_out . append ( l . eval ( { self . input_data : dataset , self . keep_prob : 1 } ) ) if layers_out == [ ] : raise Exception ( "This method is not implemented for this model" ) else : return layers_out
Get output from each layer of the network .
23,305
def get_parameters ( self , params , graph = None ) : g = graph if graph is not None else self . tf_graph with g . as_default ( ) : with tf . Session ( ) as self . tf_session : self . tf_saver . restore ( self . tf_session , self . model_path ) out = { } for par in params : if type ( params [ par ] ) == list : for i , p in enumerate ( params [ par ] ) : out [ par + '-' + str ( i + 1 ) ] = p . eval ( ) else : out [ par ] = params [ par ] . eval ( ) return out
Get the parameters of the model .
23,306
def fit ( self , train_X , train_Y , val_X = None , val_Y = None , graph = None ) : if len ( train_Y . shape ) != 1 : num_classes = train_Y . shape [ 1 ] else : raise Exception ( "Please convert the labels with one-hot encoding." ) g = graph if graph is not None else self . tf_graph with g . as_default ( ) : self . build_model ( train_X . shape [ 1 ] , num_classes ) with tf . Session ( ) as self . tf_session : summary_objs = tf_utils . init_tf_ops ( self . tf_session ) self . tf_merged_summaries = summary_objs [ 0 ] self . tf_summary_writer = summary_objs [ 1 ] self . tf_saver = summary_objs [ 2 ] self . _train_model ( train_X , train_Y , val_X , val_Y ) self . tf_saver . save ( self . tf_session , self . model_path )
Fit the model to the data .
23,307
def predict ( self , test_X ) : with self . tf_graph . as_default ( ) : with tf . Session ( ) as self . tf_session : self . tf_saver . restore ( self . tf_session , self . model_path ) feed = { self . input_data : test_X , self . keep_prob : 1 } return self . mod_y . eval ( feed )
Predict the labels for the test set .
23,308
def score ( self , test_X , test_Y ) : with self . tf_graph . as_default ( ) : with tf . Session ( ) as self . tf_session : self . tf_saver . restore ( self . tf_session , self . model_path ) feed = { self . input_data : test_X , self . input_labels : test_Y , self . keep_prob : 1 } return self . accuracy . eval ( feed )
Compute the mean accuracy over the test set .
23,309
def pretrain ( self , train_set , validation_set = None ) : self . do_pretrain = True def set_params_func ( autoenc , autoencgraph ) : params = autoenc . get_parameters ( graph = autoencgraph ) self . encoding_w_ . append ( params [ 'enc_w' ] ) self . encoding_b_ . append ( params [ 'enc_b' ] ) return SupervisedModel . pretrain_procedure ( self , self . autoencoders , self . autoencoder_graphs , set_params_func = set_params_func , train_set = train_set , validation_set = validation_set )
Perform Unsupervised pretraining of the autoencoder .
23,310
def init_tf_ops ( sess ) : summary_merged = tf . summary . merge_all ( ) init_op = tf . global_variables_initializer ( ) saver = tf . train . Saver ( ) sess . run ( init_op ) run_id = 0 for e in os . listdir ( Config ( ) . logs_dir ) : if e [ : 3 ] == 'run' : r = int ( e [ 3 : ] ) if r > run_id : run_id = r run_id += 1 run_dir = os . path . join ( Config ( ) . logs_dir , 'run' + str ( run_id ) ) print ( 'Tensorboard logs dir for this run is %s' % ( run_dir ) ) summary_writer = tf . summary . FileWriter ( run_dir , sess . graph ) return ( summary_merged , summary_writer , saver )
Initialize TensorFlow operations .
23,311
def run_summaries ( sess , merged_summaries , summary_writer , epoch , feed , tens ) : try : result = sess . run ( [ merged_summaries , tens ] , feed_dict = feed ) summary_str = result [ 0 ] out = result [ 1 ] summary_writer . add_summary ( summary_str , epoch ) except tf . errors . InvalidArgumentError : out = sess . run ( tens , feed_dict = feed ) return out
Run the summaries and error computation on the validation set .
23,312
def pretrain ( self , train_set , validation_set = None ) : self . do_pretrain = True def set_params_func ( rbmmachine , rbmgraph ) : params = rbmmachine . get_parameters ( graph = rbmgraph ) self . encoding_w_ . append ( params [ 'W' ] ) self . encoding_b_ . append ( params [ 'bh_' ] ) return SupervisedModel . pretrain_procedure ( self , self . rbms , self . rbm_graphs , set_params_func = set_params_func , train_set = train_set , validation_set = validation_set )
Perform Unsupervised pretraining of the DBN .
23,313
def _create_encode_layer ( self ) : with tf . name_scope ( "encoder" ) : activation = tf . add ( tf . matmul ( self . input_data , self . W_ ) , self . bh_ ) if self . enc_act_func : self . encode = self . enc_act_func ( activation ) else : self . encode = activation return self
Create the encoding layer of the network .
23,314
def _create_decode_layer ( self ) : with tf . name_scope ( "decoder" ) : activation = tf . add ( tf . matmul ( self . encode , tf . transpose ( self . W_ ) ) , self . bv_ ) if self . dec_act_func : self . reconstruction = self . dec_act_func ( activation ) else : self . reconstruction = activation return self
Create the decoding layer of the network .
23,315
def sample_prob ( probs , rand ) : return tf . nn . relu ( tf . sign ( probs - rand ) )
Get samples from a tensor of probabilities .
23,316
def corrupt_input ( data , sess , corrtype , corrfrac ) : corruption_ratio = np . round ( corrfrac * data . shape [ 1 ] ) . astype ( np . int ) if corrtype == 'none' : return np . copy ( data ) if corrfrac > 0.0 : if corrtype == 'masking' : return masking_noise ( data , sess , corrfrac ) elif corrtype == 'salt_and_pepper' : return salt_and_pepper_noise ( data , corruption_ratio ) else : return np . copy ( data )
Corrupt a fraction of data according to the chosen noise method .
23,317
def xavier_init ( fan_in , fan_out , const = 1 ) : low = - const * np . sqrt ( 6.0 / ( fan_in + fan_out ) ) high = const * np . sqrt ( 6.0 / ( fan_in + fan_out ) ) return tf . random_uniform ( ( fan_in , fan_out ) , minval = low , maxval = high )
Xavier initialization of network weights .
23,318
def gen_batches ( data , batch_size ) : data = np . array ( data ) for i in range ( 0 , data . shape [ 0 ] , batch_size ) : yield data [ i : i + batch_size ]
Divide input data into batches .
23,319
def to_one_hot ( dataY ) : nc = 1 + np . max ( dataY ) onehot = [ np . zeros ( nc , dtype = np . int8 ) for _ in dataY ] for i , j in enumerate ( dataY ) : onehot [ i ] [ j ] = 1 return onehot
Convert the vector of labels dataY into one - hot encoding .
23,320
def conv2bin ( data ) : if data . min ( ) < 0 or data . max ( ) > 1 : data = normalize ( data ) out_data = data . copy ( ) for i , sample in enumerate ( out_data ) : for j , val in enumerate ( sample ) : if np . random . random ( ) <= val : out_data [ i ] [ j ] = 1 else : out_data [ i ] [ j ] = 0 return out_data
Convert a matrix of probabilities into binary values .
23,321
def masking_noise ( data , sess , v ) : data_noise = data . copy ( ) rand = tf . random_uniform ( data . shape ) data_noise [ sess . run ( tf . nn . relu ( tf . sign ( v - rand ) ) ) . astype ( np . bool ) ] = 0 return data_noise
Apply masking noise to data in X .
23,322
def salt_and_pepper_noise ( X , v ) : X_noise = X . copy ( ) n_features = X . shape [ 1 ] mn = X . min ( ) mx = X . max ( ) for i , sample in enumerate ( X ) : mask = np . random . randint ( 0 , n_features , v ) for m in mask : if np . random . random ( ) < 0.5 : X_noise [ i ] [ m ] = mn else : X_noise [ i ] [ m ] = mx return X_noise
Apply salt and pepper noise to data in X .
23,323
def expand_args ( ** args_to_expand ) : layers = args_to_expand [ 'layers' ] try : items = args_to_expand . iteritems ( ) except AttributeError : items = args_to_expand . items ( ) for key , val in items : if isinstance ( val , list ) and len ( val ) != len ( layers ) : args_to_expand [ key ] = [ val [ 0 ] for _ in layers ] return args_to_expand
Expand the given lists into the length of the layers .
23,324
def flag_to_list ( flagval , flagtype ) : if flagtype == 'int' : return [ int ( _ ) for _ in flagval . split ( ',' ) if _ ] elif flagtype == 'float' : return [ float ( _ ) for _ in flagval . split ( ',' ) if _ ] elif flagtype == 'str' : return [ _ for _ in flagval . split ( ',' ) if _ ] else : raise Exception ( "incorrect type" )
Convert a string of comma - separated tf flags to a list of values .
23,325
def str2actfunc ( act_func ) : if act_func == 'sigmoid' : return tf . nn . sigmoid elif act_func == 'tanh' : return tf . nn . tanh elif act_func == 'relu' : return tf . nn . relu
Convert activation function name to tf function .
23,326
def random_seed_np_tf ( seed ) : if seed >= 0 : np . random . seed ( seed ) tf . set_random_seed ( seed ) return True else : return False
Seed numpy and tensorflow random number generators .
23,327
def gen_image ( img , width , height , outfile , img_type = 'grey' ) : assert len ( img ) == width * height or len ( img ) == width * height * 3 if img_type == 'grey' : misc . imsave ( outfile , img . reshape ( width , height ) ) elif img_type == 'color' : misc . imsave ( outfile , img . reshape ( 3 , width , height ) )
Save an image with the given parameters .
23,328
def build_model ( self , n_features , n_classes ) : self . _create_placeholders ( n_features , n_classes ) self . _create_layers ( n_classes ) self . cost = self . loss . compile ( self . mod_y , self . input_labels ) self . train_step = self . trainer . compile ( self . cost ) self . accuracy = Evaluation . accuracy ( self . mod_y , self . input_labels )
Create the computational graph of the model .
23,329
def max_pool ( x , dim ) : return tf . nn . max_pool ( x , ksize = [ 1 , dim , dim , 1 ] , strides = [ 1 , dim , dim , 1 ] , padding = 'SAME' )
Max pooling operation .
23,330
def reconstruct ( self , data , graph = None ) : g = graph if graph is not None else self . tf_graph with g . as_default ( ) : with tf . Session ( ) as self . tf_session : self . tf_saver . restore ( self . tf_session , self . model_path ) feed = { self . input_data : data , self . keep_prob : 1 } return self . reconstruction . eval ( feed )
Reconstruct data according to the model .
23,331
def score ( self , data , data_ref , graph = None ) : g = graph if graph is not None else self . tf_graph with g . as_default ( ) : with tf . Session ( ) as self . tf_session : self . tf_saver . restore ( self . tf_session , self . model_path ) feed = { self . input_data : data , self . input_labels : data_ref , self . keep_prob : 1 } return self . cost . eval ( feed )
Compute the reconstruction loss over the test set .
23,332
def compile ( self , cost , name_scope = "train" ) : with tf . name_scope ( name_scope ) : return self . opt_ . minimize ( cost )
Compile the optimizer with the given training parameters .
23,333
def compile ( self , mod_y , ref_y , regterm = None ) : with tf . name_scope ( self . name ) : if self . lfunc == 'cross_entropy' : clip_inf = tf . clip_by_value ( mod_y , 1e-10 , float ( 'inf' ) ) clip_sup = tf . clip_by_value ( 1 - mod_y , 1e-10 , float ( 'inf' ) ) cost = - tf . reduce_mean ( tf . add ( tf . multiply ( ref_y , tf . log ( clip_inf ) ) , tf . multiply ( tf . subtract ( 1.0 , ref_y ) , tf . log ( clip_sup ) ) ) ) elif self . lfunc == 'softmax_cross_entropy' : cost = tf . losses . softmax_cross_entropy ( ref_y , mod_y ) elif self . lfunc == 'mse' : cost = tf . sqrt ( tf . reduce_mean ( tf . square ( tf . subtract ( ref_y , mod_y ) ) ) ) else : cost = None if cost is not None : cost = cost + regterm if regterm is not None else cost tf . summary . scalar ( self . lfunc , cost ) else : cost = None return cost
Compute the loss function tensor .
23,334
def build_model ( self , n_features , encoding_w = None , encoding_b = None ) : self . _create_placeholders ( n_features , n_features ) if encoding_w and encoding_b : self . encoding_w_ = encoding_w self . encoding_b_ = encoding_b else : self . _create_variables ( n_features ) self . _create_encoding_layers ( ) self . _create_decoding_layers ( ) variables = [ ] variables . extend ( self . encoding_w_ ) variables . extend ( self . encoding_b_ ) regterm = Layers . regularization ( variables , self . regtype , self . regcoef ) self . cost = self . loss . compile ( self . reconstruction , self . input_labels , regterm = regterm ) self . train_step = self . trainer . compile ( self . cost )
Create the computational graph for the reconstruction task .
23,335
def _create_feed_dict ( self , data ) : return { self . input_data : data , self . hrand : np . random . rand ( data . shape [ 0 ] , self . num_hidden ) , self . vrand : np . random . rand ( data . shape [ 0 ] , data . shape [ 1 ] ) }
Create the dictionary of data to feed to tf session during training .
23,336
def build_model ( self , n_features , regtype = 'none' ) : self . _create_placeholders ( n_features ) self . _create_variables ( n_features ) self . encode = self . sample_hidden_from_visible ( self . input_data ) [ 0 ] self . reconstruction = self . sample_visible_from_hidden ( self . encode , n_features ) hprob0 , hstate0 , vprob , hprob1 , hstate1 = self . gibbs_sampling_step ( self . input_data , n_features ) positive = self . compute_positive_association ( self . input_data , hprob0 , hstate0 ) nn_input = vprob for step in range ( self . gibbs_sampling_steps - 1 ) : hprob , hstate , vprob , hprob1 , hstate1 = self . gibbs_sampling_step ( nn_input , n_features ) nn_input = vprob negative = tf . matmul ( tf . transpose ( vprob ) , hprob1 ) self . w_upd8 = self . W . assign_add ( self . learning_rate * ( positive - negative ) / self . batch_size ) self . bh_upd8 = self . bh_ . assign_add ( tf . multiply ( self . learning_rate , tf . reduce_mean ( tf . subtract ( hprob0 , hprob1 ) , 0 ) ) ) self . bv_upd8 = self . bv_ . assign_add ( tf . multiply ( self . learning_rate , tf . reduce_mean ( tf . subtract ( self . input_data , vprob ) , 0 ) ) ) variables = [ self . W , self . bh_ , self . bv_ ] regterm = Layers . regularization ( variables , self . regtype , self . regcoef ) self . cost = self . loss . compile ( vprob , self . input_data , regterm = regterm )
Build the Restricted Boltzmann Machine model in TensorFlow .
23,337
def gibbs_sampling_step ( self , visible , n_features ) : hprobs , hstates = self . sample_hidden_from_visible ( visible ) vprobs = self . sample_visible_from_hidden ( hprobs , n_features ) hprobs1 , hstates1 = self . sample_hidden_from_visible ( vprobs ) return hprobs , hstates , vprobs , hprobs1 , hstates1
Perform one step of gibbs sampling .
23,338
def sample_hidden_from_visible ( self , visible ) : hprobs = tf . nn . sigmoid ( tf . add ( tf . matmul ( visible , self . W ) , self . bh_ ) ) hstates = utilities . sample_prob ( hprobs , self . hrand ) return hprobs , hstates
Sample the hidden units from the visible units .
23,339
def sample_visible_from_hidden ( self , hidden , n_features ) : visible_activation = tf . add ( tf . matmul ( hidden , tf . transpose ( self . W ) ) , self . bv_ ) if self . visible_unit_type == 'bin' : vprobs = tf . nn . sigmoid ( visible_activation ) elif self . visible_unit_type == 'gauss' : vprobs = tf . truncated_normal ( ( 1 , n_features ) , mean = visible_activation , stddev = self . stddev ) else : vprobs = None return vprobs
Sample the visible units from the hidden units .
23,340
def compute_positive_association ( self , visible , hidden_probs , hidden_states ) : if self . visible_unit_type == 'bin' : positive = tf . matmul ( tf . transpose ( visible ) , hidden_states ) elif self . visible_unit_type == 'gauss' : positive = tf . matmul ( tf . transpose ( visible ) , hidden_probs ) else : positive = None return positive
Compute positive associations between visible and hidden units .
23,341
def load_model ( self , shape , gibbs_sampling_steps , model_path ) : n_features , self . num_hidden = shape [ 0 ] , shape [ 1 ] self . gibbs_sampling_steps = gibbs_sampling_steps self . build_model ( n_features ) init_op = tf . global_variables_initializer ( ) self . tf_saver = tf . train . Saver ( ) with tf . Session ( ) as self . tf_session : self . tf_session . run ( init_op ) self . tf_saver . restore ( self . tf_session , model_path )
Load a trained model from disk .
23,342
def get_parameters ( self , graph = None ) : g = graph if graph is not None else self . tf_graph with g . as_default ( ) : with tf . Session ( ) as self . tf_session : self . tf_saver . restore ( self . tf_session , self . model_path ) return { 'W' : self . W . eval ( ) , 'bh_' : self . bh_ . eval ( ) , 'bv_' : self . bv_ . eval ( ) }
Return the model parameters in the form of numpy arrays .
23,343
def edit_distance ( seq1 , seq2 , action_function = lowest_cost_action , test = operator . eq ) : m = len ( seq1 ) n = len ( seq2 ) if seq1 == seq2 : return 0 , n if m == 0 : return n , 0 if n == 0 : return m , 0 v0 = [ 0 ] * ( n + 1 ) v1 = [ 0 ] * ( n + 1 ) m0 = [ 0 ] * ( n + 1 ) m1 = [ 0 ] * ( n + 1 ) for i in range ( 1 , n + 1 ) : v0 [ i ] = i for i in range ( 1 , m + 1 ) : v1 [ 0 ] = i for j in range ( 1 , n + 1 ) : cost = 0 if test ( seq1 [ i - 1 ] , seq2 [ j - 1 ] ) else 1 ins_cost = v1 [ j - 1 ] + 1 del_cost = v0 [ j ] + 1 sub_cost = v0 [ j - 1 ] + cost ins_match = m1 [ j - 1 ] del_match = m0 [ j ] sub_match = m0 [ j - 1 ] + int ( not cost ) action = action_function ( ins_cost , del_cost , sub_cost , ins_match , del_match , sub_match , cost ) if action in [ EQUAL , REPLACE ] : v1 [ j ] = sub_cost m1 [ j ] = sub_match elif action == INSERT : v1 [ j ] = ins_cost m1 [ j ] = ins_match elif action == DELETE : v1 [ j ] = del_cost m1 [ j ] = del_match else : raise Exception ( 'Invalid dynamic programming option returned!' ) for i in range ( 0 , n + 1 ) : v0 [ i ] = v1 [ i ] m0 [ i ] = m1 [ i ] return v1 [ n ] , m1 [ n ]
Computes the edit distance between the two given sequences . This uses the relatively fast method that only constructs two columns of the 2d array for edits . This function actually uses four columns because we track the number of matches too .
23,344
def get_opcodes_from_bp_table ( bp ) : x = len ( bp ) - 1 y = len ( bp [ 0 ] ) - 1 opcodes = [ ] while x != 0 or y != 0 : this_bp = bp [ x ] [ y ] opcodes . append ( this_bp ) if this_bp [ 0 ] == EQUAL or this_bp [ 0 ] == REPLACE : x = x - 1 y = y - 1 elif this_bp [ 0 ] == INSERT : y = y - 1 elif this_bp [ 0 ] == DELETE : x = x - 1 opcodes . reverse ( ) return opcodes
Given a 2d list structure collect the opcodes from the best path .
23,345
def main ( ) : if len ( sys . argv ) != 3 : print ( 'Usage: {} <file1> <file2>' . format ( sys . argv [ 0 ] ) ) exit ( - 1 ) file1 = sys . argv [ 1 ] file2 = sys . argv [ 2 ] with open ( file1 ) as f1 , open ( file2 ) as f2 : for line1 , line2 in zip ( f1 , f2 ) : print ( "Line 1: {}" . format ( line1 . strip ( ) ) ) print ( "Line 2: {}" . format ( line2 . strip ( ) ) ) dist , _ , _ = edit_distance_backpointer ( line1 . split ( ) , line2 . split ( ) ) print ( 'Distance: {}' . format ( dist ) ) print ( '=' * 80 )
Read two files line - by - line and print edit distances between each pair of lines . Will terminate at the end of the shorter of the two files .
23,346
def ratio ( self ) : return 2.0 * self . matches ( ) / ( len ( self . seq1 ) + len ( self . seq2 ) )
Ratio of matches to the average sequence length .
23,347
def _compute_distance_fast ( self ) : d , m = edit_distance ( self . seq1 , self . seq2 , action_function = self . action_function , test = self . test ) if self . dist : assert d == self . dist if self . _matches : assert m == self . _matches self . dist = d self . _matches = m
Calls edit_distance and asserts that if we already have values for matches and distance that they match .
23,348
def newbie ( cls , * args , ** kwargs ) : parser = cls ( * args , ** kwargs ) subparser = parser . add_subparsers ( dest = 'command' ) parents = [ parser . pparser , parser . output_parser ] sparser = subparser . add_parser ( 'search' , help = 'Perform new search of items' , parents = parents ) parser . search_group = sparser . add_argument_group ( 'search options' ) parser . search_group . add_argument ( '-c' , '--collection' , help = 'Name of collection' , default = None ) h = 'One or more scene IDs from provided collection (ignores other parameters)' parser . search_group . add_argument ( '--ids' , help = h , nargs = '*' , default = None ) parser . search_group . add_argument ( '--bbox' , help = 'Bounding box (min lon, min lat, max lon, max lat)' , nargs = 4 ) parser . search_group . add_argument ( '--intersects' , help = 'GeoJSON Feature (file or string)' ) parser . search_group . add_argument ( '--datetime' , help = 'Single date/time or begin and end date/time (e.g., 2017-01-01/2017-02-15)' ) parser . search_group . add_argument ( '-p' , '--property' , nargs = '*' , help = 'Properties of form KEY=VALUE (<, >, <=, >=, = supported)' ) parser . search_group . add_argument ( '--sort' , help = 'Sort by fields' , nargs = '*' ) h = 'Only output how many Items found' parser . search_group . add_argument ( '--found' , help = h , action = 'store_true' , default = False ) parser . search_group . add_argument ( '--url' , help = 'URL of the API' , default = config . API_URL ) parents . append ( parser . download_parser ) lparser = subparser . add_parser ( 'load' , help = 'Load items from previous search' , parents = parents ) lparser . add_argument ( 'items' , help = 'GeoJSON file of Items' ) return parser
Create a newbie class with all the skills needed
23,349
def main ( items = None , printmd = None , printcal = False , found = False , save = None , download = None , requestor_pays = False , ** kwargs ) : if items is None : search = Search . search ( ** kwargs ) if found : num = search . found ( ) print ( '%s items found' % num ) return num items = search . items ( ) else : items = Items . load ( items ) print ( '%s items found' % len ( items ) ) if printmd is not None : print ( items . summary ( printmd ) ) if printcal : print ( items . calendar ( ) ) if save is not None : items . save ( filename = save ) if download is not None : if 'ALL' in download : download = set ( [ k for i in items for k in i . assets ] ) for key in download : items . download ( key = key , path = config . DATADIR , filename = config . FILENAME , requestor_pays = requestor_pays ) return items
Main function for performing a search
23,350
def found ( self ) : if 'ids' in self . kwargs : cid = self . kwargs [ 'query' ] [ 'collection' ] [ 'eq' ] return len ( self . items_by_id ( self . kwargs [ 'ids' ] , cid ) ) kwargs = { 'page' : 1 , 'limit' : 0 } kwargs . update ( self . kwargs ) results = self . query ( ** kwargs ) return results [ 'meta' ] [ 'found' ]
Small query to determine total number of hits
23,351
def collection ( cls , cid ) : url = urljoin ( config . API_URL , 'collections/%s' % cid ) return Collection ( cls . query ( url = url ) )
Get a Collection record
23,352
def items_by_id ( cls , ids , collection ) : col = cls . collection ( collection ) items = [ ] base_url = urljoin ( config . API_URL , 'collections/%s/items' % collection ) for id in ids : try : items . append ( Item ( cls . query ( urljoin ( base_url , id ) ) ) ) except SatSearchError as err : pass return Items ( items , collections = [ col ] )
Return Items from collection with matching ids
23,353
def items ( self , limit = 10000 ) : _limit = 500 if 'ids' in self . kwargs : col = self . kwargs . get ( 'query' , { } ) . get ( 'collection' , { } ) . get ( 'eq' , None ) if col is None : raise SatSearchError ( 'Collection required when searching by id' ) return self . items_by_id ( self . kwargs [ 'ids' ] , col ) items = [ ] found = self . found ( ) if found > limit : logger . warning ( 'There are more items found (%s) than the limit (%s) provided.' % ( found , limit ) ) maxitems = min ( found , limit ) kwargs = { 'page' : 1 , 'limit' : min ( _limit , maxitems ) } kwargs . update ( self . kwargs ) while len ( items ) < maxitems : items += [ Item ( i ) for i in self . query ( ** kwargs ) [ 'features' ] ] kwargs [ 'page' ] += 1 collections = [ ] for c in set ( [ item . properties [ 'collection' ] for item in items if 'collection' in item . properties ] ) : collections . append ( self . collection ( c ) ) return Items ( items , collections = collections , search = self . kwargs )
Return all of the Items and Collections for this search
23,354
def copy_byte_range ( infile , outfile , start = None , stop = None , bufsize = 16 * 1024 ) : if start is not None : infile . seek ( start ) while 1 : to_read = min ( bufsize , stop + 1 - infile . tell ( ) if stop else bufsize ) buf = infile . read ( to_read ) if not buf : break outfile . write ( buf )
Like shutil . copyfileobj but only copy a range of the streams .
23,355
def parse_byte_range ( byte_range ) : if byte_range . strip ( ) == '' : return None , None m = BYTE_RANGE_RE . match ( byte_range ) if not m : raise ValueError ( 'Invalid byte range %s' % byte_range ) first , last = [ x and int ( x ) for x in m . groups ( ) ] if last and last < first : raise ValueError ( 'Invalid byte range %s' % byte_range ) return first , last
Returns the two numbers in bytes = 123 - 456 or throws ValueError .
23,356
def cache_page ( * args , ** kwargs ) : decorator = _django_cache_page ( * args , ** kwargs ) def flavoured_decorator ( func ) : return vary_on_flavour_fetch ( decorator ( vary_on_flavour_update ( func ) ) ) return flavoured_decorator
Same as django s cache_page decorator but wraps the view into additional decorators before and after that . Makes it possible to serve multiple flavours without getting into trouble with django s caching that doesn t know about flavours .
23,357
def CheckLineLength ( filename , linenumber , clean_lines , errors ) : line = clean_lines . raw_lines [ linenumber ] if len ( line ) > _lint_state . linelength : return errors ( filename , linenumber , 'linelength' , 'Lines should be <= %d characters long' % ( _lint_state . linelength ) )
Check for lines longer than the recommended length
23,358
def CheckUpperLowerCase ( filename , linenumber , clean_lines , errors ) : line = clean_lines . lines [ linenumber ] if ContainsCommand ( line ) : command = GetCommand ( line ) if IsCommandMixedCase ( command ) : return errors ( filename , linenumber , 'readability/wonkycase' , 'Do not use mixed case commands' ) if clean_lines . have_seen_uppercase is None : clean_lines . have_seen_uppercase = IsCommandUpperCase ( command ) else : is_upper = IsCommandUpperCase ( command ) if is_upper != clean_lines . have_seen_uppercase : return errors ( filename , linenumber , 'readability/mixedcase' , 'Do not mix upper and lower case commands' )
Check that commands are either lower case or upper case but not both
23,359
def CheckCommandSpaces ( filename , linenumber , clean_lines , errors ) : line = clean_lines . lines [ linenumber ] match = ContainsCommand ( line ) if match and len ( match . group ( 2 ) ) : errors ( filename , linenumber , 'whitespace/extra' , "Extra spaces between '%s' and its ()" % ( match . group ( 1 ) ) ) if match : spaces_after_open = len ( _RE_COMMAND_START_SPACES . match ( line ) . group ( 1 ) ) initial_spaces = GetInitialSpaces ( line ) initial_linenumber = linenumber end = None while True : line = clean_lines . lines [ linenumber ] end = _RE_COMMAND_END_SPACES . search ( line ) if end : break linenumber += 1 if linenumber >= len ( clean_lines . lines ) : break if linenumber == len ( clean_lines . lines ) and not end : errors ( filename , initial_linenumber , 'syntax' , 'Unable to find the end of this command' ) if end : spaces_before_end = len ( end . group ( 1 ) ) initial_spaces = GetInitialSpaces ( line ) if initial_linenumber != linenumber and spaces_before_end >= initial_spaces : spaces_before_end -= initial_spaces if spaces_after_open != spaces_before_end : errors ( filename , initial_linenumber , 'whitespace/mismatch' , 'Mismatching spaces inside () after command' )
No extra spaces between command and parenthesis
23,360
def CheckRepeatLogic ( filename , linenumber , clean_lines , errors ) : line = clean_lines . lines [ linenumber ] for cmd in _logic_commands : if re . search ( r'\b%s\b' % cmd , line . lower ( ) ) : m = _RE_LOGIC_CHECK . search ( line ) if m : errors ( filename , linenumber , 'readability/logic' , 'Expression repeated inside %s; ' 'better to use only %s()' % ( cmd , m . group ( 1 ) ) ) break
Check for logic inside else endif etc
23,361
def plot_hurst_hist ( ) : import matplotlib . pyplot as plt hs = [ nolds . hurst_rs ( np . random . random ( size = 10000 ) , corrected = True ) for _ in range ( 100 ) ] plt . hist ( hs , bins = 20 ) plt . xlabel ( "esimated value of hurst exponent" ) plt . ylabel ( "number of experiments" ) plt . show ( )
Plots a histogram of values obtained for the hurst exponent of uniformly distributed white noise .
23,362
def hurst_compare_nvals ( data , nvals = None ) : import matplotlib . pyplot as plt data = np . asarray ( data ) n_all = np . arange ( 2 , len ( data ) + 1 ) dd_all = nolds . hurst_rs ( data , nvals = n_all , debug_data = True , fit = "poly" ) dd_def = nolds . hurst_rs ( data , debug_data = True , fit = "poly" ) n_def = np . round ( np . exp ( dd_def [ 1 ] [ 0 ] ) ) . astype ( "int32" ) n_div = n_all [ np . where ( len ( data ) % n_all [ : - 1 ] == 0 ) ] dd_div = nolds . hurst_rs ( data , nvals = n_div , debug_data = True , fit = "poly" ) def corr ( nvals ) : return [ np . log ( nolds . expected_rs ( n ) ) for n in nvals ] l_all = plt . plot ( dd_all [ 1 ] [ 0 ] , dd_all [ 1 ] [ 1 ] - corr ( n_all ) , "o" ) l_def = plt . plot ( dd_def [ 1 ] [ 0 ] , dd_def [ 1 ] [ 1 ] - corr ( n_def ) , "o" ) l_div = plt . plot ( dd_div [ 1 ] [ 0 ] , dd_div [ 1 ] [ 1 ] - corr ( n_div ) , "o" ) l_cst = [ ] t_cst = [ ] if nvals is not None : dd_cst = nolds . hurst_rs ( data , nvals = nvals , debug_data = True , fit = "poly" ) l_cst = plt . plot ( dd_cst [ 1 ] [ 0 ] , dd_cst [ 1 ] [ 1 ] - corr ( nvals ) , "o" ) l_cst = l_cst t_cst = [ "custom" ] plt . xlabel ( "log(n)" ) plt . ylabel ( "log((R/S)_n - E[(R/S)_n])" ) plt . legend ( l_all + l_def + l_div + l_cst , [ "all" , "default" , "divisors" ] + t_cst ) labeled_data = zip ( [ dd_all [ 0 ] , dd_def [ 0 ] , dd_div [ 0 ] ] , [ "all" , "def" , "div" ] ) for data , label in labeled_data : print ( "%s: %.3f" % ( label , data ) ) if nvals is not None : print ( "custom: %.3f" % dd_cst [ 0 ] ) plt . show ( )
Creates a plot that compares the results of different choices for nvals for the function hurst_rs .
23,363
def fbm ( n , H = 0.75 ) : assert H > 0 and H < 1 def R ( t , s ) : twoH = 2 * H return 0.5 * ( s ** twoH + t ** twoH - np . abs ( t - s ) ** twoH ) gamma = R ( * np . mgrid [ 0 : n , 0 : n ] ) w , P = np . linalg . eigh ( gamma ) L = np . diag ( w ) sigma = np . dot ( np . dot ( P , np . sqrt ( L ) ) , np . linalg . inv ( P ) ) v = np . random . randn ( n ) return np . dot ( sigma , v )
Generates fractional brownian motions of desired length .
23,364
def qrandom ( n ) : import quantumrandom return np . concatenate ( [ quantumrandom . get_data ( data_type = 'uint16' , array_length = 1024 ) for i in range ( int ( np . ceil ( n / 1024.0 ) ) ) ] ) [ : n ]
Creates an array of n true random numbers obtained from the quantum random number generator at qrng . anu . edu . au
23,365
def load_qrandom ( ) : fname = "datasets/qrandom.npy" with pkg_resources . resource_stream ( __name__ , fname ) as f : return np . load ( f )
Loads a set of 10000 random numbers generated by qrandom .
23,366
def load_brown72 ( ) : fname = "datasets/brown72.npy" with pkg_resources . resource_stream ( __name__ , fname ) as f : return np . load ( f )
Loads the dataset brown72 with a prescribed Hurst exponent of 0 . 72
23,367
def tent_map ( x , steps , mu = 2 ) : for _ in range ( steps ) : x = mu * x if x < 0.5 else mu * ( 1 - x ) yield x
Generates a time series of the tent map .
23,368
def logistic_map ( x , steps , r = 4 ) : r for _ in range ( steps ) : x = r * x * ( 1 - x ) yield x
r Generates a time series of the logistic map .
23,369
def delay_embedding ( data , emb_dim , lag = 1 ) : data = np . asarray ( data ) min_len = ( emb_dim - 1 ) * lag + 1 if len ( data ) < min_len : msg = "cannot embed data of length {} with embedding dimension {} " + "and lag {}, minimum required length is {}" raise ValueError ( msg . format ( len ( data ) , emb_dim , lag , min_len ) ) m = len ( data ) - min_len + 1 indices = np . repeat ( [ np . arange ( emb_dim ) * lag ] , m , axis = 0 ) indices += np . arange ( m ) . reshape ( ( m , 1 ) ) return data [ indices ]
Perform a time - delay embedding of a time series
23,370
def lyap_r_len ( ** kwargs ) : min_len = ( kwargs [ 'emb_dim' ] - 1 ) * kwargs [ 'lag' ] + 1 min_len += kwargs [ 'trajectory_len' ] - 1 min_len += kwargs [ 'min_tsep' ] * 2 + 1 return min_len
Helper function that calculates the minimum number of data points required to use lyap_r .
23,371
def lyap_e_len ( ** kwargs ) : m = ( kwargs [ 'emb_dim' ] - 1 ) // ( kwargs [ 'matrix_dim' ] - 1 ) min_len = kwargs [ 'emb_dim' ] min_len += m min_len += kwargs [ 'min_tsep' ] * 2 min_len += kwargs [ 'min_nb' ] return min_len
Helper function that calculates the minimum number of data points required to use lyap_e .
23,372
def sampen ( data , emb_dim = 2 , tolerance = None , dist = rowwise_chebyshev , debug_plot = False , debug_data = False , plot_file = None ) : data = np . asarray ( data ) if tolerance is None : tolerance = 0.2 * np . std ( data ) n = len ( data ) tVecs = delay_embedding ( np . asarray ( data ) , emb_dim + 1 , lag = 1 ) plot_data = [ ] counts = [ ] for m in [ emb_dim , emb_dim + 1 ] : counts . append ( 0 ) plot_data . append ( [ ] ) tVecsM = tVecs [ : n - m + 1 , : m ] for i in range ( len ( tVecsM ) - 1 ) : dsts = dist ( tVecsM [ i + 1 : ] , tVecsM [ i ] ) if debug_plot : plot_data [ - 1 ] . extend ( dsts ) counts [ - 1 ] += np . sum ( dsts < tolerance ) if counts [ 1 ] == 0 : saen = np . inf else : saen = - np . log ( 1.0 * counts [ 1 ] / counts [ 0 ] ) if debug_plot : plot_dists ( plot_data , tolerance , m , title = "sampEn = {:.3f}" . format ( saen ) , fname = plot_file ) if debug_data : return ( saen , plot_data ) else : return saen
Computes the sample entropy of the given data .
23,373
def binary_n ( total_N , min_n = 50 ) : max_exp = np . log2 ( 1.0 * total_N / min_n ) max_exp = int ( np . floor ( max_exp ) ) return [ int ( np . floor ( 1.0 * total_N / ( 2 ** i ) ) ) for i in range ( 1 , max_exp + 1 ) ]
Creates a list of values by successively halving the total length total_N until the resulting value is less than min_n .
23,374
def expected_h ( nvals , fit = "RANSAC" ) : rsvals = [ expected_rs ( n ) for n in nvals ] poly = poly_fit ( np . log ( nvals ) , np . log ( rsvals ) , 1 , fit = fit ) return poly [ 0 ]
Uses expected_rs to calculate the expected value for the Hurst exponent h based on the values of n used for the calculation .
23,375
def corr_dim ( data , emb_dim , rvals = None , dist = rowwise_euclidean , fit = "RANSAC" , debug_plot = False , debug_data = False , plot_file = None ) : data = np . asarray ( data ) if rvals is None : sd = np . std ( data ) rvals = logarithmic_r ( 0.1 * sd , 0.5 * sd , 1.03 ) n = len ( data ) orbit = delay_embedding ( data , emb_dim , lag = 1 ) dists = np . array ( [ dist ( orbit , orbit [ i ] ) for i in range ( len ( orbit ) ) ] ) csums = [ ] for r in rvals : s = 1.0 / ( n * ( n - 1 ) ) * np . sum ( dists < r ) csums . append ( s ) csums = np . array ( csums ) nonzero = np . where ( csums != 0 ) rvals = np . array ( rvals ) [ nonzero ] csums = csums [ nonzero ] if len ( csums ) == 0 : poly = [ np . nan , np . nan ] else : poly = poly_fit ( np . log ( rvals ) , np . log ( csums ) , 1 ) if debug_plot : plot_reg ( np . log ( rvals ) , np . log ( csums ) , poly , "log(r)" , "log(C(r))" , fname = plot_file ) if debug_data : return ( poly [ 0 ] , ( np . log ( rvals ) , np . log ( csums ) , poly ) ) else : return poly [ 0 ]
Calculates the correlation dimension with the Grassberger - Procaccia algorithm
23,376
def check_status ( status , expected , path , headers = None , resp_headers = None , body = None , extras = None ) : if status in expected : return msg = ( 'Expect status %r from Google Storage. But got status %d.\n' 'Path: %r.\n' 'Request headers: %r.\n' 'Response headers: %r.\n' 'Body: %r.\n' 'Extra info: %r.\n' % ( expected , status , path , headers , resp_headers , body , extras ) ) if status == httplib . UNAUTHORIZED : raise AuthorizationError ( msg ) elif status == httplib . FORBIDDEN : raise ForbiddenError ( msg ) elif status == httplib . NOT_FOUND : raise NotFoundError ( msg ) elif status == httplib . REQUEST_TIMEOUT : raise TimeoutError ( msg ) elif status == httplib . REQUESTED_RANGE_NOT_SATISFIABLE : raise InvalidRange ( msg ) elif ( status == httplib . OK and 308 in expected and httplib . OK not in expected ) : raise FileClosedError ( msg ) elif status >= 500 : raise ServerError ( msg ) else : raise FatalError ( msg )
Check HTTP response status is expected .
23,377
def _get_default_retry_params ( ) : default = getattr ( _thread_local_settings , 'default_retry_params' , None ) if default is None or not default . belong_to_current_request ( ) : return RetryParams ( ) else : return copy . copy ( default )
Get default RetryParams for current request and current thread .
23,378
def _should_retry ( resp ) : return ( resp . status_code == httplib . REQUEST_TIMEOUT or ( resp . status_code >= 500 and resp . status_code < 600 ) )
Given a urlfetch response decide whether to retry that request .
23,379
def _eager_tasklet ( tasklet ) : @ utils . wrapping ( tasklet ) def eager_wrapper ( * args , ** kwds ) : fut = tasklet ( * args , ** kwds ) _run_until_rpc ( ) return fut return eager_wrapper
Decorator to turn tasklet to run eagerly .
23,380
def run ( self , tasklet , ** kwds ) : start_time = time . time ( ) n = 1 while True : e = None result = None got_result = False try : result = yield tasklet ( ** kwds ) got_result = True if not self . should_retry ( result ) : raise ndb . Return ( result ) except runtime . DeadlineExceededError : logging . debug ( 'Tasklet has exceeded request deadline after %s seconds total' , time . time ( ) - start_time ) raise except self . retriable_exceptions as e : pass if n == 1 : logging . debug ( 'Tasklet is %r' , tasklet ) delay = self . retry_params . delay ( n , start_time ) if delay <= 0 : logging . debug ( 'Tasklet failed after %s attempts and %s seconds in total' , n , time . time ( ) - start_time ) if got_result : raise ndb . Return ( result ) elif e is not None : raise e else : assert False , 'Should never reach here.' if got_result : logging . debug ( 'Got result %r from tasklet.' , result ) else : logging . debug ( 'Got exception "%r" from tasklet.' , e ) logging . debug ( 'Retry in %s seconds.' , delay ) n += 1 yield tasklets . sleep ( delay )
Run a tasklet with retry .
23,381
def _check ( cls , name , val , can_be_zero = False , val_type = float ) : valid_types = [ val_type ] if val_type is float : valid_types . append ( int ) if type ( val ) not in valid_types : raise TypeError ( 'Expect type %s for parameter %s' % ( val_type . __name__ , name ) ) if val < 0 : raise ValueError ( 'Value for parameter %s has to be greater than 0' % name ) if not can_be_zero and val == 0 : raise ValueError ( 'Value for parameter %s can not be 0' % name ) return val
Check init arguments .
23,382
def delay ( self , n , start_time ) : if ( n > self . max_retries or ( n > self . min_retries and time . time ( ) - start_time > self . max_retry_period ) ) : return - 1 return min ( math . pow ( self . backoff_factor , n - 1 ) * self . initial_delay , self . max_delay )
Calculate delay before the next retry .
23,383
def open ( filename , mode = 'r' , content_type = None , options = None , read_buffer_size = storage_api . ReadBuffer . DEFAULT_BUFFER_SIZE , retry_params = None , _account_id = None , offset = 0 ) : common . validate_file_path ( filename ) api = storage_api . _get_storage_api ( retry_params = retry_params , account_id = _account_id ) filename = api_utils . _quote_filename ( filename ) if mode == 'w' : common . validate_options ( options ) return storage_api . StreamingBuffer ( api , filename , content_type , options ) elif mode == 'r' : if content_type or options : raise ValueError ( 'Options and content_type can only be specified ' 'for writing mode.' ) return storage_api . ReadBuffer ( api , filename , buffer_size = read_buffer_size , offset = offset ) else : raise ValueError ( 'Invalid mode %s.' % mode )
Opens a Google Cloud Storage file and returns it as a File - like object .
23,384
def delete ( filename , retry_params = None , _account_id = None ) : api = storage_api . _get_storage_api ( retry_params = retry_params , account_id = _account_id ) common . validate_file_path ( filename ) filename = api_utils . _quote_filename ( filename ) status , resp_headers , content = api . delete_object ( filename ) errors . check_status ( status , [ 204 ] , filename , resp_headers = resp_headers , body = content )
Delete a Google Cloud Storage file .
23,385
def get_location ( bucket , retry_params = None , _account_id = None ) : return _get_bucket_attribute ( bucket , 'location' , 'LocationConstraint' , retry_params = retry_params , _account_id = _account_id )
Returns the location for the given bucket .
23,386
def get_storage_class ( bucket , retry_params = None , _account_id = None ) : return _get_bucket_attribute ( bucket , 'storageClass' , 'StorageClass' , retry_params = retry_params , _account_id = _account_id )
Returns the storage class for the given bucket .
23,387
def _get_bucket_attribute ( bucket , query_param , xml_response_tag , retry_params = None , _account_id = None ) : api = storage_api . _get_storage_api ( retry_params = retry_params , account_id = _account_id ) common . validate_bucket_path ( bucket ) status , headers , content = api . get_bucket ( '%s?%s' % ( bucket , query_param ) ) errors . check_status ( status , [ 200 ] , bucket , resp_headers = headers , body = content ) root = ET . fromstring ( content ) if root . tag == xml_response_tag and root . text : return root . text return None
Helper method to request a bucket parameter and parse the response .
23,388
def stat ( filename , retry_params = None , _account_id = None ) : common . validate_file_path ( filename ) api = storage_api . _get_storage_api ( retry_params = retry_params , account_id = _account_id ) status , headers , content = api . head_object ( api_utils . _quote_filename ( filename ) ) errors . check_status ( status , [ 200 ] , filename , resp_headers = headers , body = content ) file_stat = common . GCSFileStat ( filename = filename , st_size = common . get_stored_content_length ( headers ) , st_ctime = common . http_time_to_posix ( headers . get ( 'last-modified' ) ) , etag = headers . get ( 'etag' ) , content_type = headers . get ( 'content-type' ) , metadata = common . get_metadata ( headers ) ) return file_stat
Get GCSFileStat of a Google Cloud storage file .
23,389
def copy2 ( src , dst , metadata = None , retry_params = None ) : common . validate_file_path ( src ) common . validate_file_path ( dst ) if metadata is None : metadata = { } copy_meta = 'COPY' else : copy_meta = 'REPLACE' metadata . update ( { 'x-goog-copy-source' : src , 'x-goog-metadata-directive' : copy_meta } ) api = storage_api . _get_storage_api ( retry_params = retry_params ) status , resp_headers , content = api . put_object ( api_utils . _quote_filename ( dst ) , headers = metadata ) errors . check_status ( status , [ 200 ] , src , metadata , resp_headers , body = content )
Copy the file content from src to dst .
23,390
def listbucket ( path_prefix , marker = None , prefix = None , max_keys = None , delimiter = None , retry_params = None , _account_id = None ) : if prefix : common . validate_bucket_path ( path_prefix ) bucket = path_prefix else : bucket , prefix = common . _process_path_prefix ( path_prefix ) if marker and marker . startswith ( bucket ) : marker = marker [ len ( bucket ) + 1 : ] api = storage_api . _get_storage_api ( retry_params = retry_params , account_id = _account_id ) options = { } if marker : options [ 'marker' ] = marker if max_keys : options [ 'max-keys' ] = max_keys if prefix : options [ 'prefix' ] = prefix if delimiter : options [ 'delimiter' ] = delimiter return _Bucket ( api , bucket , options )
Returns a GCSFileStat iterator over a bucket .
23,391
def compose ( list_of_files , destination_file , files_metadata = None , content_type = None , retry_params = None , _account_id = None ) : api = storage_api . _get_storage_api ( retry_params = retry_params , account_id = _account_id ) if os . getenv ( 'SERVER_SOFTWARE' ) . startswith ( 'Dev' ) : def _temp_func ( file_list , destination_file , content_type ) : bucket = '/' + destination_file . split ( '/' ) [ 1 ] + '/' with open ( destination_file , 'w' , content_type = content_type ) as gcs_merge : for source_file in file_list : with open ( bucket + source_file [ 'Name' ] , 'r' ) as gcs_source : gcs_merge . write ( gcs_source . read ( ) ) compose_object = _temp_func else : compose_object = api . compose_object file_list , _ = _validate_compose_list ( destination_file , list_of_files , files_metadata , 32 ) compose_object ( file_list , destination_file , content_type )
Runs the GCS Compose on the given files .
23,392
def _validate_compose_list ( destination_file , file_list , files_metadata = None , number_of_files = 32 ) : common . validate_file_path ( destination_file ) bucket = destination_file [ 0 : ( destination_file . index ( '/' , 1 ) + 1 ) ] try : if isinstance ( file_list , types . StringTypes ) : raise TypeError list_len = len ( file_list ) except TypeError : raise TypeError ( 'file_list must be a list' ) if list_len > number_of_files : raise ValueError ( 'Compose attempted to create composite with too many' '(%i) components; limit is (%i).' % ( list_len , number_of_files ) ) if list_len <= 0 : raise ValueError ( 'Compose operation requires at' ' least one component; 0 provided.' ) if files_metadata is None : files_metadata = [ ] elif len ( files_metadata ) > list_len : raise ValueError ( 'files_metadata contains more entries(%i)' ' than file_list(%i)' % ( len ( files_metadata ) , list_len ) ) list_of_files = [ ] for source_file , meta_data in itertools . izip_longest ( file_list , files_metadata ) : if not isinstance ( source_file , str ) : raise TypeError ( 'Each item of file_list must be a string' ) if source_file . startswith ( '/' ) : logging . warn ( 'Detected a "/" at the start of the file, ' 'Unless the file name contains a "/" it ' ' may cause files to be misread' ) if source_file . startswith ( bucket ) : logging . warn ( 'Detected bucket name at the start of the file, ' 'must not specify the bucket when listing file_names.' ' May cause files to be misread' ) common . validate_file_path ( bucket + source_file ) list_entry = { } if meta_data is not None : list_entry . update ( meta_data ) list_entry [ 'Name' ] = source_file list_of_files . append ( list_entry ) return list_of_files , bucket
Validates the file_list and merges the file_list files_metadata .
23,393
def _next_file_gen ( self , root ) : for e in root . getiterator ( common . _T_CONTENTS ) : st_ctime , size , etag , key = None , None , None , None for child in e . getiterator ( '*' ) : if child . tag == common . _T_LAST_MODIFIED : st_ctime = common . dt_str_to_posix ( child . text ) elif child . tag == common . _T_ETAG : etag = child . text elif child . tag == common . _T_SIZE : size = child . text elif child . tag == common . _T_KEY : key = child . text yield common . GCSFileStat ( self . _path + '/' + key , size , etag , st_ctime ) e . clear ( ) yield None
Generator for next file element in the document .
23,394
def _next_dir_gen ( self , root ) : for e in root . getiterator ( common . _T_COMMON_PREFIXES ) : yield common . GCSFileStat ( self . _path + '/' + e . find ( common . _T_PREFIX ) . text , st_size = None , etag = None , st_ctime = None , is_dir = True ) e . clear ( ) yield None
Generator for next directory element in the document .
23,395
def _should_get_another_batch ( self , content ) : if ( 'max-keys' in self . _options and self . _options [ 'max-keys' ] <= common . _MAX_GET_BUCKET_RESULT ) : return False elements = self . _find_elements ( content , set ( [ common . _T_IS_TRUNCATED , common . _T_NEXT_MARKER ] ) ) if elements . get ( common . _T_IS_TRUNCATED , 'false' ) . lower ( ) != 'true' : return False next_marker = elements . get ( common . _T_NEXT_MARKER ) if next_marker is None : self . _options . pop ( 'marker' , None ) return False self . _options [ 'marker' ] = next_marker return True
Whether to issue another GET bucket call .
23,396
def _find_elements ( self , result , elements ) : element_mapping = { } result = StringIO . StringIO ( result ) for _ , e in ET . iterparse ( result , events = ( 'end' , ) ) : if not elements : break if e . tag in elements : element_mapping [ e . tag ] = e . text elements . remove ( e . tag ) return element_mapping
Find interesting elements from XML .
23,397
def create_file ( self , filename ) : self . response . write ( 'Creating file %s\n' % filename ) write_retry_params = gcs . RetryParams ( backoff_factor = 1.1 ) gcs_file = gcs . open ( filename , 'w' , content_type = 'text/plain' , options = { 'x-goog-meta-foo' : 'foo' , 'x-goog-meta-bar' : 'bar' } , retry_params = write_retry_params ) gcs_file . write ( 'abcde\n' ) gcs_file . write ( 'f' * 1024 * 4 + '\n' ) gcs_file . close ( ) self . tmp_filenames_to_clean_up . append ( filename )
Create a file .
23,398
def list_bucket ( self , bucket ) : self . response . write ( 'Listbucket result:\n' ) page_size = 1 stats = gcs . listbucket ( bucket + '/foo' , max_keys = page_size ) while True : count = 0 for stat in stats : count += 1 self . response . write ( repr ( stat ) ) self . response . write ( '\n' ) if count != page_size or count == 0 : break stats = gcs . listbucket ( bucket + '/foo' , max_keys = page_size , marker = stat . filename )
Create several files and paginate through them .
23,399
def CreateFile ( filename ) : with gcs . open ( filename , 'w' ) as f : f . write ( 'abcde\n' ) blobstore_filename = '/gs' + filename return blobstore . create_gs_key ( blobstore_filename )
Create a GCS file with GCS client lib .