idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
239,700
def _find_current_phase ( self , global_step ) : epoch_size = sum ( phase . steps for phase in self . _phases ) epoch = int ( global_step // epoch_size ) steps_in = global_step % epoch_size for phase in self . _phases : if steps_in < phase . steps : return phase , epoch , steps_in steps_in -= phase . steps
Determine the current phase based on the global step .
239,701
def _define_step ( self , done , score , summary ) : if done . shape . ndims == 0 : done = done [ None ] if score . shape . ndims == 0 : score = score [ None ] score_mean = streaming_mean . StreamingMean ( ( ) , tf . float32 ) with tf . control_dependencies ( [ done , score , summary ] ) : done_score = tf . gather ( sc...
Combine operations of a phase .
239,702
def _store_checkpoint ( self , sess , saver , global_step ) : if not self . _logdir or not saver : return tf . gfile . MakeDirs ( self . _logdir ) filename = os . path . join ( self . _logdir , 'model.ckpt' ) saver . save ( sess , filename , global_step )
Store a checkpoint if a log directory was provided to the constructor .
239,703
def _define_loop ( graph , logdir , train_steps , eval_steps ) : loop = tools . Loop ( logdir , graph . step , graph . should_log , graph . do_report , graph . force_reset ) loop . add_phase ( 'train' , graph . done , graph . score , graph . summary , train_steps , report_every = train_steps , log_every = train_steps /...
Create and configure a training loop with training and evaluation phases .
239,704
def train ( config , env_processes ) : tf . reset_default_graph ( ) if config . update_every % config . num_agents : tf . logging . warn ( 'Number of agents should divide episodes per update.' ) with tf . device ( '/cpu:0' ) : batch_env = utility . define_batch_env ( lambda : _create_environment ( config ) , config . n...
Training and evaluation entry point yielding scores .
239,705
def main ( _ ) : utility . set_up_logging ( ) if not FLAGS . config : raise KeyError ( 'You must specify a configuration.' ) logdir = FLAGS . logdir and os . path . expanduser ( os . path . join ( FLAGS . logdir , '{}-{}' . format ( FLAGS . timestamp , FLAGS . config ) ) ) try : config = utility . load_config ( logdir ...
Create or load configuration and launch the trainer .
239,706
def iterate_sequences ( consumer_fn , output_template , sequences , length , chunk_length = None , batch_size = None , num_epochs = 1 , padding_value = 0 ) : if not length . shape [ 0 ] . value : raise ValueError ( 'Batch size of length tensor must be set.' ) num_sequences = length . shape [ 0 ] . value sequences = dic...
Iterate over batches of chunks of sequences for multiple epochs .
239,707
def chunk_sequence ( sequence , chunk_length = 200 , padding_value = 0 ) : if 'length' in sequence : length = sequence . pop ( 'length' ) else : length = tf . shape ( tools . nested . flatten ( sequence ) [ 0 ] ) [ 0 ] num_chunks = ( length - 1 ) // chunk_length + 1 padding_length = chunk_length * num_chunks - length p...
Split a nested dict of sequence tensors into a batch of chunks .
239,708
def remove_padding ( sequence ) : length = sequence . pop ( 'length' ) sequence = tools . nested . map ( lambda tensor : tensor [ : length ] , sequence ) return sequence
Selects the used frames of a sequence up to its length .
239,709
def transform ( self , value ) : with tf . name_scope ( self . _name + '/transform' ) : no_batch_dim = value . shape . ndims == self . _mean . shape . ndims if no_batch_dim : value = value [ None , ... ] if self . _center : value -= self . _mean [ None , ... ] if self . _scale : value /= tf . cond ( self . _count > 1 ,...
Normalize a single or batch tensor .
239,710
def update ( self , value ) : with tf . name_scope ( self . _name + '/update' ) : if value . shape . ndims == self . _mean . shape . ndims : value = value [ None , ... ] count = tf . shape ( value ) [ 0 ] with tf . control_dependencies ( [ self . _count . assign_add ( count ) ] ) : step = tf . cast ( self . _count , tf...
Update the mean and variance estimates .
239,711
def reset ( self ) : with tf . name_scope ( self . _name + '/reset' ) : return tf . group ( self . _count . assign ( 0 ) , self . _mean . assign ( tf . zeros_like ( self . _mean ) ) , self . _var_sum . assign ( tf . zeros_like ( self . _var_sum ) ) )
Reset the estimates of mean and variance .
239,712
def summary ( self ) : with tf . name_scope ( self . _name + '/summary' ) : mean_summary = tf . cond ( self . _count > 0 , lambda : self . _summary ( 'mean' , self . _mean ) , str ) std_summary = tf . cond ( self . _count > 1 , lambda : self . _summary ( 'stddev' , self . _std ( ) ) , str ) return tf . summary . merge ...
Summary string of mean and standard deviation .
239,713
def _std ( self ) : variance = tf . cond ( self . _count > 1 , lambda : self . _var_sum / tf . cast ( self . _count - 1 , tf . float32 ) , lambda : tf . ones_like ( self . _var_sum ) * float ( 'nan' ) ) return tf . sqrt ( variance + 1e-4 )
Computes the current estimate of the standard deviation .
239,714
def _summary ( self , name , tensor ) : if tensor . shape . ndims == 0 : return tf . summary . scalar ( name , tensor ) else : return tf . summary . histogram ( name , tensor )
Create a scalar or histogram summary matching the rank of the tensor .
239,715
def length ( self , rows = None ) : rows = tf . range ( self . _capacity ) if rows is None else rows return tf . gather ( self . _length , rows )
Tensor holding the current length of episodes .
239,716
def append ( self , transitions , rows = None ) : rows = tf . range ( self . _capacity ) if rows is None else rows assert rows . shape . ndims == 1 assert_capacity = tf . assert_less ( rows , self . _capacity , message = 'capacity exceeded' ) with tf . control_dependencies ( [ assert_capacity ] ) : assert_max_length = ...
Append a batch of transitions to rows of the memory .
239,717
def replace ( self , episodes , length , rows = None ) : rows = tf . range ( self . _capacity ) if rows is None else rows assert rows . shape . ndims == 1 assert_capacity = tf . assert_less ( rows , self . _capacity , message = 'capacity exceeded' ) with tf . control_dependencies ( [ assert_capacity ] ) : assert_max_le...
Replace full episodes .
239,718
def data ( self , rows = None ) : rows = tf . range ( self . _capacity ) if rows is None else rows assert rows . shape . ndims == 1 episode = tools . nested . map ( lambda var : tf . gather ( var , rows ) , self . _buffers ) length = tf . gather ( self . _length , rows ) return episode , length
Access a batch of episodes from the memory .
239,719
def clear ( self , rows = None ) : rows = tf . range ( self . _capacity ) if rows is None else rows assert rows . shape . ndims == 1 return tf . scatter_update ( self . _length , rows , tf . zeros_like ( rows ) )
Reset episodes in the memory .
239,720
def _parse_shape ( self , space ) : if isinstance ( space , gym . spaces . Discrete ) : return ( ) if isinstance ( space , gym . spaces . Box ) : return space . shape raise NotImplementedError ( )
Get a tensor shape from a OpenAI Gym space .
239,721
def _parse_dtype ( self , space ) : if isinstance ( space , gym . spaces . Discrete ) : return tf . int32 if isinstance ( space , gym . spaces . Box ) : return tf . float32 raise NotImplementedError ( )
Get a tensor dtype from a OpenAI Gym space .
239,722
def begin_episode ( self , agent_indices ) : with tf . name_scope ( 'begin_episode/' ) : if self . _last_state is None : reset_state = tf . no_op ( ) else : reset_state = utility . reinit_nested_vars ( self . _last_state , agent_indices ) reset_buffer = self . _current_episodes . clear ( agent_indices ) with tf . contr...
Reset the recurrent states and stored episode .
239,723
def perform ( self , agent_indices , observ ) : with tf . name_scope ( 'perform/' ) : observ = self . _observ_filter . transform ( observ ) if self . _last_state is None : state = None else : state = tools . nested . map ( lambda x : tf . gather ( x , agent_indices ) , self . _last_state ) with tf . device ( '/gpu:0' i...
Compute batch of actions and a summary for a batch of observation .
239,724
def experience ( self , agent_indices , observ , action , reward , unused_done , unused_nextob ) : with tf . name_scope ( 'experience/' ) : return tf . cond ( self . _is_training , lambda : self . _define_experience ( agent_indices , observ , action , reward ) , str )
Process the transition tuple of the current step .
239,725
def end_episode ( self , agent_indices ) : with tf . name_scope ( 'end_episode/' ) : return tf . cond ( self . _is_training , lambda : self . _define_end_episode ( agent_indices ) , str )
Add episodes to the memory and perform update steps if memory is full .
239,726
def _initialize_policy ( self ) : with tf . device ( '/gpu:0' if self . _use_gpu else '/cpu:0' ) : network = functools . partial ( self . _config . network , self . _config , self . _batch_env . action_space ) self . _network = tf . make_template ( 'network' , network ) output = self . _network ( tf . zeros_like ( self...
Initialize the policy .
239,727
def _initialize_memory ( self , policy_params ) : template = ( self . _batch_env . observ [ 0 ] , self . _batch_env . action [ 0 ] , tools . nested . map ( lambda x : x [ 0 , 0 ] , policy_params ) , self . _batch_env . reward [ 0 ] ) with tf . variable_scope ( 'ppo_temporary' ) : self . _current_episodes = parts . Epis...
Initialize temporary and permanent memory .
239,728
def _training ( self ) : with tf . device ( '/gpu:0' if self . _use_gpu else '/cpu:0' ) : with tf . name_scope ( 'training' ) : assert_full = tf . assert_equal ( self . _num_finished_episodes , self . _config . update_every ) with tf . control_dependencies ( [ assert_full ] ) : data = self . _finished_episodes . data (...
Perform multiple training iterations of both policy and value baseline .
239,729
def _perform_update_steps ( self , observ , action , old_policy_params , reward , length ) : return_ = utility . discounted_return ( reward , length , self . _config . discount ) value = self . _network ( observ , length ) . value if self . _config . gae_lambda : advantage = utility . lambda_advantage ( reward , value ...
Perform multiple update steps of value function and policy .
239,730
def _update_step ( self , sequence ) : observ , action , old_policy_params , reward , advantage = sequence [ 'sequence' ] length = sequence [ 'length' ] old_policy = self . _policy_type ( ** old_policy_params ) value_loss , value_summary = self . _value_loss ( observ , reward , length ) network = self . _network ( obse...
Compute the current combined loss and perform a gradient update step .
239,731
def _value_loss ( self , observ , reward , length ) : with tf . name_scope ( 'value_loss' ) : value = self . _network ( observ , length ) . value return_ = utility . discounted_return ( reward , length , self . _config . discount ) advantage = return_ - value value_loss = 0.5 * self . _mask ( advantage ** 2 , length ) ...
Compute the loss function for the value baseline .
239,732
def _policy_loss ( self , old_policy , policy , action , advantage , length ) : with tf . name_scope ( 'policy_loss' ) : kl = tf . contrib . distributions . kl_divergence ( old_policy , policy ) kl = tf . check_numerics ( kl , 'kl' ) kl = tf . reduce_mean ( self . _mask ( kl , length ) , 1 ) policy_gradient = tf . exp ...
Compute the policy loss composed of multiple components .
239,733
def _adjust_penalty ( self , observ , old_policy_params , length ) : old_policy = self . _policy_type ( ** old_policy_params ) with tf . name_scope ( 'adjust_penalty' ) : network = self . _network ( observ , length ) print_penalty = tf . Print ( 0 , [ self . _penalty ] , 'current penalty: ' ) with tf . control_dependen...
Adjust the KL policy between the behavioral and current policy .
239,734
def _mask ( self , tensor , length , padding_value = 0 ) : with tf . name_scope ( 'mask' ) : range_ = tf . range ( tensor . shape [ 1 ] . value ) mask = range_ [ None , : ] < length [ : , None ] if tensor . shape . ndims > 2 : for _ in range ( tensor . shape . ndims - 2 ) : mask = mask [ ... , None ] mask = tf . tile (...
Set padding elements of a batch of sequences to a constant .
239,735
def main ( self , * args , ** kwargs ) : self . start ( * args , ** kwargs ) try : while 1 : body , message = yield self . receive ( ) handler = self . get_handler ( message ) handler ( body , message ) finally : self . stop ( * args , ** kwargs )
Implement the actor main loop by waiting forever for messages .
239,736
def send ( self , method , args = { } , to = None , nowait = False , ** kwargs ) : if to is None : to = self . routing_key r = self . call_or_cast ( method , args , routing_key = to , nowait = nowait , ** kwargs ) if not nowait : return r . get ( )
Call method on agent listening to routing_key .
239,737
def throw ( self , method , args = { } , nowait = False , ** kwargs ) : r = self . call_or_cast ( method , args , type = ACTOR_TYPE . RR , nowait = nowait , ** kwargs ) if not nowait : return r
Call method on one of the agents in round robin .
239,738
def scatter ( self , method , args = { } , nowait = False , timeout = None , ** kwargs ) : timeout = timeout if timeout is not None else self . default_timeout r = self . call_or_cast ( method , args , type = ACTOR_TYPE . SCATTER , nowait = nowait , timeout = timeout , ** kwargs ) if not nowait : return r . gather ( ti...
Broadcast method to all agents .
239,739
def call_or_cast ( self , method , args = { } , nowait = False , ** kwargs ) : return ( nowait and self . cast or self . call ) ( method , args , ** kwargs )
Apply remote method asynchronously or synchronously depending on the value of nowait .
239,740
def cast ( self , method , args = { } , declare = None , retry = None , retry_policy = None , type = None , exchange = None , ** props ) : retry = self . retry if retry is None else retry body = { 'class' : self . name , 'method' : method , 'args' : args } _retry_policy = self . retry_policy if retry_policy : _retry_po...
Send message to actor . Discarding replies .
239,741
def handle_call ( self , body , message ) : try : r = self . _DISPATCH ( body , ticket = message . properties [ 'reply_to' ] ) except self . Next : pass else : self . reply ( message , r )
Handle call message .
239,742
def _on_message ( self , body , message ) : if message . properties . get ( 'reply_to' ) : handler = self . handle_call else : handler = self . handle_cast def handle ( ) : try : handler ( body , message ) except Exception : raise except BaseException : message . ack ( ) raise else : message . ack ( ) handle ( )
What to do when a message is received .
239,743
def parse_options ( self , prog_name , arguments ) : if '--version' in arguments : self . exit_status ( self . version , fh = sys . stdout ) parser = self . create_parser ( prog_name ) options , args = parser . parse_args ( arguments ) return options , args
Parse the available options .
239,744
def get ( self , ** kwargs ) : "What kind of arguments should be pass here" kwargs . setdefault ( 'limit' , 1 ) return self . _first ( self . gather ( ** kwargs ) )
What kind of arguments should be pass here
239,745
def _gather ( self , * args , ** kwargs ) : propagate = kwargs . pop ( 'propagate' , True ) return ( self . to_python ( reply , propagate = propagate ) for reply in self . actor . _collect_replies ( * args , ** kwargs ) )
Generator over the results
239,746
def to_python ( self , reply , propagate = True ) : try : return reply [ 'ok' ] except KeyError : error = self . Error ( * reply . get ( 'nok' ) or ( ) ) if propagate : raise error return error
Extracts the value out of the reply message .
239,747
def spawn ( self , cls , kwargs = { } , nowait = False ) : actor_id = uuid ( ) if str ( qualname ( cls ) ) == '__builtin__.unicode' : name = cls else : name = qualname ( cls ) res = self . call ( 'spawn' , { 'cls' : name , 'id' : actor_id , 'kwargs' : kwargs } , type = ACTOR_TYPE . RR , nowait = nowait ) return ActorPr...
Spawn a new actor on a celery worker by sending a remote command to the worker .
239,748
def select ( self , cls , ** kwargs ) : name = qualname ( cls ) id = first_reply ( self . scatter ( 'select' , { 'cls' : name } , limit = 1 ) , cls ) return ActorProxy ( name , id , agent = self , connection = self . connection , ** kwargs )
Get the id of already spawned actor
239,749
def process_message ( self , actor , body , message ) : if actor is not self and self . is_green ( ) : self . pool . spawn_n ( actor . _on_message , body , message ) else : if not self . is_green ( ) and message . properties . get ( 'reply_to' ) : warn ( 'Starting a blocking call (%s) on actor (%s) ' 'when greenlets ar...
Process actor message depending depending on the the worker settings .
239,750
def get_outer_frame_variables ( ) : cur_filename = inspect . getframeinfo ( inspect . currentframe ( ) ) . filename outer_frame = next ( f for f in inspect . getouterframes ( inspect . currentframe ( ) ) if f . filename != cur_filename ) variables = { } variables . update ( outer_frame . frame . f_globals ) variables ....
Get a dict of local and global variables of the first outer frame from another file .
239,751
def extract_table_names ( query ) : tables_blocks = re . findall ( r'(?:FROM|JOIN)\s+(\w+(?:\s*,\s*\w+)*)' , query , re . IGNORECASE ) tables = [ tbl for block in tables_blocks for tbl in re . findall ( r'\w+' , block ) ] return set ( tables )
Extract table names from an SQL query .
239,752
def write_table ( df , tablename , conn ) : with catch_warnings ( ) : filterwarnings ( 'ignore' , message = 'The provided table name \'%s\' is not found exactly as such in the database' % tablename ) to_sql ( df , name = tablename , con = conn , index = not any ( name is None for name in df . index . names ) )
Write a dataframe to the database .
239,753
def make_benchark ( n_train , n_test , n_dim = 2 ) : X_train = np . random . rand ( n_train , n_dim ) y_train = np . random . rand ( n_train ) X_test = np . random . rand ( n_test , n_dim ) res = { } for variogram_model in VARIOGRAM_MODELS : tic = time ( ) OK = OrdinaryKriging ( X_train [ : , 0 ] , X_train [ : , 1 ] , ...
Compute the benchmarks for Ordianry Kriging
239,754
def print_benchmark ( n_train , n_test , n_dim , res ) : print ( '=' * 80 ) print ( ' ' * 10 , 'N_dim={}, N_train={}, N_test={}' . format ( n_dim , n_train , n_test ) ) print ( '=' * 80 ) print ( '\n' , '# Training the model' , '\n' ) print ( '|' . join ( [ '{:>11} ' . format ( el ) for el in [ 't_train (s)' ] + VARIOG...
Print the benchmarks
239,755
def display_variogram_model ( self ) : fig = plt . figure ( ) ax = fig . add_subplot ( 111 ) ax . plot ( self . lags , self . semivariance , 'r*' ) ax . plot ( self . lags , self . variogram_function ( self . variogram_model_parameters , self . lags ) , 'k-' ) plt . show ( )
Displays variogram model with the actual binned data .
239,756
def plot_epsilon_residuals ( self ) : fig = plt . figure ( ) ax = fig . add_subplot ( 111 ) ax . scatter ( range ( self . epsilon . size ) , self . epsilon , c = 'k' , marker = '*' ) ax . axhline ( y = 0.0 ) plt . show ( )
Plots the epsilon residuals for the variogram fit .
239,757
def print_statistics ( self ) : print ( "Q1 =" , self . Q1 ) print ( "Q2 =" , self . Q2 ) print ( "cR =" , self . cR )
Prints out the Q1 Q2 and cR statistics for the variogram fit . NOTE that ideally Q1 is close to zero Q2 is close to 1 and cR is as small as possible .
239,758
def _adjust_for_anisotropy ( X , center , scaling , angle ) : center = np . asarray ( center ) [ None , : ] angle = np . asarray ( angle ) * np . pi / 180 X -= center Ndim = X . shape [ 1 ] if Ndim == 1 : raise NotImplementedError ( 'Not implemnented yet?' ) elif Ndim == 2 : stretch = np . array ( [ [ 1 , 0 ] , [ 0 , s...
Adjusts data coordinates to take into account anisotropy . Can also be used to take into account data scaling . Angles are CCW about specified axes . Scaling is applied in rotated coordinate system .
239,759
def _calculate_variogram_model ( lags , semivariance , variogram_model , variogram_function , weight ) : if variogram_model == 'linear' : x0 = [ ( np . amax ( semivariance ) - np . amin ( semivariance ) ) / ( np . amax ( lags ) - np . amin ( lags ) ) , np . amin ( semivariance ) ] bnds = ( [ 0. , 0. ] , [ np . inf , np...
Function that fits a variogram model when parameters are not specified . Returns variogram model parameters that minimize the RMSE between the specified variogram function and the actual calculated variogram points .
239,760
def _krige ( X , y , coords , variogram_function , variogram_model_parameters , coordinates_type ) : zero_index = None zero_value = False if coordinates_type == 'euclidean' : d = squareform ( pdist ( X , metric = 'euclidean' ) ) bd = np . squeeze ( cdist ( X , coords [ None , : ] , metric = 'euclidean' ) ) elif coordin...
Sets up and solves the ordinary kriging system for the given coordinate pair . This function is only used for the statistics calculations .
239,761
def _find_statistics ( X , y , variogram_function , variogram_model_parameters , coordinates_type ) : delta = np . zeros ( y . shape ) sigma = np . zeros ( y . shape ) for i in range ( y . shape [ 0 ] ) : if i == 0 : continue else : k , ss = _krige ( X [ : i , : ] , y [ : i ] , X [ i , : ] , variogram_function , variog...
Calculates variogram fit statistics . Returns the delta sigma and epsilon values for the variogram fit . These arrays are used for statistics calculations .
239,762
def fit ( self , p , x , y ) : self . regression_model . fit ( p , y ) ml_pred = self . regression_model . predict ( p ) print ( 'Finished learning regression model' ) self . krige . fit ( x = x , y = y - ml_pred ) print ( 'Finished kriging residuals' )
fit the regression method and also Krige the residual
239,763
def score ( self , p , x , y , sample_weight = None ) : return r2_score ( y_pred = self . predict ( p , x ) , y_true = y , sample_weight = sample_weight )
Overloading default regression score method
239,764
def _exec_loop_moving_window ( self , a_all , bd_all , mask , bd_idx ) : import scipy . linalg . lapack npt = bd_all . shape [ 0 ] n = bd_idx . shape [ 1 ] kvalues = np . zeros ( npt ) sigmasq = np . zeros ( npt ) for i in np . nonzero ( ~ mask ) [ 0 ] : b_selector = bd_idx [ i ] bd = bd_all [ i ] a_selector = np . con...
Solves the kriging system by looping over all specified points . Uses only a certain number of closest points . Not very memory intensive but the loop is done in pure Python .
239,765
def get_frame_info ( tb , context_lines = 7 , simple = False ) : lineno = tb . tb_lineno function = tb . tb_frame . f_code . co_name variables = tb . tb_frame . f_locals files = { } if simple : fn = tb . tb_frame . f_code . co_filename else : fn = tb . tb_frame . f_globals . get ( '__file__' ) if not fn : fn = os . pat...
Return a dict of information about a given traceback .
239,766
def get_html_output ( self ) : def html_splitlines ( lines ) : open_tag_re = re . compile ( r'<(\w+)(\s.*)?[^/]?>' ) close_tag_re = re . compile ( r'</(\w+)>' ) open_tags = [ ] for line in lines : for tag in open_tags : line = tag . group ( 0 ) + line open_tags = [ ] for tag in open_tag_re . finditer ( line ) : open_ta...
Return line generator .
239,767
def get_columns ( model = None , fields = None , meta = None ) : if model : M = get_model ( model ) else : M = None if fields is not None : f = fields if M : if meta and hasattr ( M , meta ) : m = getattr ( model , meta ) if hasattr ( m , 'fields' ) : f = m . fields else : f = M . _fields_list else : f = M . _fields_li...
Get model columns list
239,768
def get_field ( name , model = None ) : if '.' in name : m , name = name . split ( '.' ) model = get_model ( m ) if model : return getattr ( model , name , None )
get model field according to name the name can be like model . column
239,769
def get_column ( name , model = None ) : if '.' in name : m , name = name . split ( '.' ) model = get_model ( m ) if model : return model . c . get ( name )
get table column according to name the name can be like model . column
239,770
def _process_file ( self , obj , fobj , field ) : from uliweb import settings paths = [ ] upload_to = self . upload_to or self . _get_upload_path ( field , 'upload_to' , obj ) if upload_to : self . fileserving . to_path = upload_to upload_to_sub = self . upload_to_sub or self . _get_upload_path ( field , 'upload_to_sub...
obj is record object fobj is data field is FileField instance
239,771
def count ( self , query ) : if self . manual : return self . total if isinstance ( query , Select ) : q = query . with_only_columns ( [ func . count ( ) ] ) . order_by ( None ) . limit ( None ) . offset ( None ) return do_ ( q ) . scalar ( ) return query . count ( )
If query is Select object this function will try to get count of select
239,772
def get_data ( self , query , fields_convert_map , encoding = 'utf-8' , auto_convert = True , include_hidden = False , header = None ) : fields_convert_map = fields_convert_map or { } d = self . fields_convert_map . copy ( ) d . update ( fields_convert_map ) if isinstance ( query , Select ) : query = do_ ( query ) for ...
If convert = True will convert field value
239,773
def objects ( self , json_result = False ) : self . rows_num = 0 query = self . query ( ) if not isinstance ( query , ( orm . Result , list , dict ) ) : query = do_ ( query ) for record in query : self . rows_num += 1 r = self . object ( record , json_result ) self . _cal_sum ( record ) yield r total = self . _render_s...
Return a generator of all processed data it just like render but it ll not return a table or json format data but just data . And the data will be processed by fields_convert_map if passed .
239,774
def query_all ( self ) : return self . query_model ( self . model , self . condition , order_by = self . order_by , group_by = self . group_by , having = self . having )
Query all records without limit and offset .
239,775
def copy ( self ) : missing = object ( ) result = object . __new__ ( self . __class__ ) for name in self . __slots__ : val = getattr ( self , name , missing ) if val is not missing : setattr ( result , name , val ) return result
Create a flat copy of the dict .
239,776
def list ( self ) : before , after = self . filename_template . split ( '%s' , 1 ) filename_re = re . compile ( r'%s(.{5,})%s$' % ( re . escape ( before ) , re . escape ( after ) ) ) result = [ ] for filename in os . listdir ( self . path ) : if filename . endswith ( _fs_transaction_suffix ) : continue match = filename...
Lists all sessions in the store .
239,777
def to_timezone ( dt , tzinfo = None ) : if not dt : return dt tz = pick_timezone ( tzinfo , __timezone__ ) if not tz : return dt dttz = getattr ( dt , 'tzinfo' , None ) if not dttz : return dt . replace ( tzinfo = tz ) else : return dt . astimezone ( tz )
Convert a datetime to timezone
239,778
def to_date ( dt , tzinfo = None , format = None ) : d = to_datetime ( dt , tzinfo , format ) if not d : return d return date ( d . year , d . month , d . day )
Convert a datetime to date with tzinfo
239,779
def to_time ( dt , tzinfo = None , format = None ) : d = to_datetime ( dt , tzinfo , format ) if not d : return d return time_ ( d . hour , d . minute , d . second , d . microsecond , tzinfo = d . tzinfo )
Convert a datetime to time with tzinfo
239,780
def to_datetime ( dt , tzinfo = None , format = None ) : if not dt : return dt tz = pick_timezone ( tzinfo , __timezone__ ) if isinstance ( dt , ( str , unicode ) ) : if not format : formats = DEFAULT_DATETIME_INPUT_FORMATS else : formats = list ( format ) d = None for fmt in formats : try : d = datetime . strptime ( d...
Convert a date or time to datetime with tzinfo
239,781
def parse_time ( t ) : if isinstance ( t , ( str , unicode ) ) : b = re_time . match ( t ) if b : v , unit = int ( b . group ( 1 ) ) , b . group ( 2 ) if unit == 's' : return v * 1000 elif unit == 'm' : return v * 60 * 1000 elif unit == 'h' : return v * 60 * 60 * 1000 else : return v else : raise TimeFormatError ( t ) ...
Parse string time format to microsecond
239,782
def process_exception ( self , request , e ) : if isinstance ( e , RedirectException ) : response = e . get_response ( ) self . process_response ( request , response )
Still process session data when specially Exception
239,783
def jsonp ( data , ** json_kwargs ) : from uliweb import request if 'jsonp' in json_kwargs : cb = json_kwargs . pop ( 'jsonp' ) else : cb = 'callback' begin = str ( request . GET . get ( cb ) ) if not begin : raise BadRequest ( "Can't found %s parameter in request's query_string" % cb ) if not r_callback . match ( begi...
jsonp is callback key name
239,784
def get_url_adapter ( _domain_name ) : from werkzeug . _compat import wsgi_decoding_dance domain = application . domains . get ( _domain_name , { } ) server_name = None if domain . get ( 'domain' , '' ) : server_name = domain [ 'domain' ] try : env = { } environ = request . environ env [ 'url_scheme' ] = environ [ 'wsg...
Fetch a domain url_adapter object and bind it to according domain
239,785
def get_app_dir ( app ) : path = __app_dirs__ . get ( app ) if path is not None : return path else : p = app . split ( '.' ) try : path = pkg . resource_filename ( p [ 0 ] , '' ) except ImportError as e : log . error ( "Can't import app %s" % app ) log . exception ( e ) path = '' if len ( p ) > 1 : path = os . path . j...
Get an app s directory
239,786
def get_file ( self , filename , dir = 'static' ) : if os . path . exists ( filename ) : return filename dirs = self . apps if dir : fname = os . path . join ( dir , filename ) else : fname = filename for d in reversed ( dirs ) : path = pkg . resource_filename ( d , fname ) if os . path . exists ( path ) : return path ...
get_file will search from apps directory
239,787
def get_template_dirs ( self ) : def if_not_empty ( dir ) : if not os . path . exists ( dir ) : return for root , dirs , files in os . walk ( dir ) : if dirs : return True for f in files : if f != 'readme.txt' : return True template_dirs = [ os . path . join ( self . project_dir , x ) for x in settings . GLOBAL . TEMPL...
Get templates directory from apps but in reversed order so the same named template file will be overrided by latter defined app
239,788
def get_lock ( key , value = None , expiry_time = 60 ) : from uliweb . utils . common import get_uuid redis = get_redis ( ) value = value or get_uuid ( ) return redis . set ( key , value , ex = expiry_time , nx = True )
Get a distribute lock
239,789
def set_lock ( key , value = None , expiry_time = 60 ) : from uliweb . utils . common import get_uuid redis = get_redis ( ) value = value or get_uuid ( ) return redis . set ( key , value , ex = expiry_time , xx = True )
Force to set a distribute lock
239,790
def after_init_apps ( sender ) : from uliweb import settings from uliweb . utils . common import log check = settings . get_var ( 'REDIS/check_version' ) if check : client = get_redis ( ) try : info = client . info ( ) except Exception as e : log . exception ( e ) log . error ( 'Redis is not started!' ) return redis_ve...
Check redis version
239,791
def _make_text_block ( name , content , content_type = None ) : if content_type == 'xhtml' : return u'<%s type="xhtml"><div xmlns="%s">%s</div></%s>\n' % ( name , XHTML_NAMESPACE , content , name ) if not content_type : return u'<%s>%s</%s>\n' % ( name , escape ( content ) , name ) return u'<%s type="%s">%s</%s>\n' % (...
Helper function for the builder that creates an XML text block .
239,792
def _style_range ( self , cell , cell_range , border = None , fill = None , font = None , alignment = None ) : from openpyxl . styles import Border , Side top = left = right = bottom = Side ( border_style = 'thin' , color = self . border_color ) def border_add ( border , top = None , right = None , left = None , bottom...
Apply styles to a range of cells as if they were a single cell .
239,793
def url_unquote ( string , charset = 'utf-8' , errors = 'replace' , unsafe = '' ) : rv = _unquote_to_bytes ( string , unsafe ) if charset is not None : rv = rv . decode ( charset , errors ) return rv
URL decode a single string with a given encoding . If the charset is set to None no unicode decoding is performed and raw bytes are returned .
239,794
def decode_netloc ( self ) : rv = _decode_idna ( self . host or '' ) if ':' in rv : rv = '[%s]' % rv port = self . port if port is not None : rv = '%s:%d' % ( rv , port ) auth = ':' . join ( filter ( None , [ _url_unquote_legacy ( self . raw_username or '' , '/:%@' ) , _url_unquote_legacy ( self . raw_password or '' , ...
Decodes the netloc part into a string .
239,795
def decode ( self , charset = 'utf-8' , errors = 'replace' ) : return URL ( self . scheme . decode ( 'ascii' ) , self . decode_netloc ( ) , self . path . decode ( charset , errors ) , self . query . decode ( charset , errors ) , self . fragment . decode ( charset , errors ) )
Decodes the URL to a tuple made out of strings . The charset is only being used for the path query and fragment .
239,796
def _mixed_join ( iterable , sentinel ) : iterator = iter ( iterable ) first_item = next ( iterator , sentinel ) if isinstance ( first_item , bytes ) : return first_item + b'' . join ( iterator ) return first_item + u'' . join ( iterator )
concatenate any string type in an intelligent way .
239,797
def _buf_append ( self , string ) : if not self . _buf : self . _buf = string else : self . _buf += string
Replace string directly without appending to an empty string avoiding type issues .
239,798
def quote_etag ( etag , weak = False ) : if '"' in etag : raise ValueError ( 'invalid etag' ) etag = '"%s"' % etag if weak : etag = 'w/' + etag return etag
Quote an etag .
239,799
def parse_etags ( value ) : if not value : return ETags ( ) strong = [ ] weak = [ ] end = len ( value ) pos = 0 while pos < end : match = _etag_re . match ( value , pos ) if match is None : break is_weak , quoted , raw = match . groups ( ) if raw == '*' : return ETags ( star_tag = True ) elif quoted : raw = quoted if i...
Parse an etag header .