idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
30,600
def _join_inlines ( self , soup ) : elements = soup . find_all ( True ) for elem in elements : if self . _inline ( elem ) : elem . unwrap ( ) return soup
Unwraps inline elements defined in self . _inline_tags .
30,601
def temp_filename ( self ) : handle , filename = tempfile . mkstemp ( ) os . close ( handle ) return filename
Return a unique tempfile name .
30,602
def process ( filename , encoding = DEFAULT_ENCODING , extension = None , ** kwargs ) : if not os . path . exists ( filename ) : raise exceptions . MissingFileError ( filename ) if extension : ext = extension if not ext . startswith ( '.' ) : ext = '.' + ext ext = ext . lower ( ) else : _ , ext = os . path . splitext (...
This is the core function used for extracting text . It routes the filename to the appropriate parser and returns the extracted text as a byte - string encoded with encoding .
30,603
def _get_available_extensions ( ) : extensions = [ ] parsers_dir = os . path . join ( os . path . dirname ( __file__ ) ) glob_filename = os . path . join ( parsers_dir , "*" + _FILENAME_SUFFIX + ".py" ) ext_re = re . compile ( glob_filename . replace ( '*' , "(?P<ext>\w+)" ) ) for filename in glob . glob ( glob_filenam...
Get a list of available file extensions to make it easy for tab - completion and exception handling .
30,604
def parse_requirements ( requirements_filename ) : dependencies , dependency_links = [ ] , [ ] requirements_dir = os . path . dirname ( requirements_filename ) with open ( requirements_filename , 'r' ) as stream : for line in stream : line = line . strip ( ) if line . startswith ( "-r" ) : filename = os . path . join (...
read in the dependencies from the requirements files
30,605
def build_interactions ( self , data ) : interactions = _IncrementalCOOMatrix ( self . interactions_shape ( ) , np . int32 ) weights = _IncrementalCOOMatrix ( self . interactions_shape ( ) , np . float32 ) for datum in data : user_idx , item_idx , weight = self . _unpack_datum ( datum ) interactions . append ( user_idx...
Build an interaction matrix .
30,606
def mapping ( self ) : return ( self . _user_id_mapping , self . _user_feature_mapping , self . _item_id_mapping , self . _item_feature_mapping , )
Return the constructed mappings .
30,607
def _get_movielens_path ( ) : return os . path . join ( os . path . dirname ( os . path . abspath ( __file__ ) ) , 'movielens.zip' )
Get path to the movielens dataset file .
30,608
def _download_movielens ( dest_path ) : url = 'http://files.grouplens.org/datasets/movielens/ml-100k.zip' req = requests . get ( url , stream = True ) with open ( dest_path , 'wb' ) as fd : for chunk in req . iter_content ( ) : fd . write ( chunk )
Download the dataset .
30,609
def _get_movie_raw_metadata ( ) : path = _get_movielens_path ( ) if not os . path . isfile ( path ) : _download_movielens ( path ) with zipfile . ZipFile ( path ) as datafile : return datafile . read ( 'ml-100k/u.item' ) . decode ( errors = 'ignore' ) . split ( '\n' )
Get raw lines of the genre file .
30,610
def _initialize ( self , no_components , no_item_features , no_user_features ) : self . item_embeddings = ( ( self . random_state . rand ( no_item_features , no_components ) - 0.5 ) / no_components ) . astype ( np . float32 ) self . item_embedding_gradients = np . zeros_like ( self . item_embeddings ) self . item_embed...
Initialise internal latent representations .
30,611
def _run_epoch ( self , item_features , user_features , interactions , sample_weight , num_threads , loss , ) : if loss in ( "warp" , "bpr" , "warp-kos" ) : positives_lookup = CSRMatrix ( self . _get_positives_lookup_matrix ( interactions ) ) shuffle_indices = np . arange ( len ( interactions . data ) , dtype = np . in...
Run an individual epoch .
30,612
def predict ( self , user_ids , item_ids , item_features = None , user_features = None , num_threads = 1 ) : self . _check_initialized ( ) if not isinstance ( user_ids , np . ndarray ) : user_ids = np . repeat ( np . int32 ( user_ids ) , len ( item_ids ) ) if isinstance ( item_ids , ( list , tuple ) ) : item_ids = np ....
Compute the recommendation score for user - item pairs .
30,613
def get_item_representations ( self , features = None ) : self . _check_initialized ( ) if features is None : return self . item_biases , self . item_embeddings features = sp . csr_matrix ( features , dtype = CYTHON_DTYPE ) return features * self . item_biases , features * self . item_embeddings
Get the latent representations for items given model and features .
30,614
def get_user_representations ( self , features = None ) : self . _check_initialized ( ) if features is None : return self . user_biases , self . user_embeddings features = sp . csr_matrix ( features , dtype = CYTHON_DTYPE ) return features * self . user_biases , features * self . user_embeddings
Get the latent representations for users given model and features .
30,615
def _adjust_returns ( returns , adjustment_factor ) : if isinstance ( adjustment_factor , ( float , int ) ) and adjustment_factor == 0 : return returns return returns - adjustment_factor
Returns the returns series adjusted by adjustment_factor . Optimizes for the case of adjustment_factor being 0 by returning returns itself not a copy!
30,616
def annualization_factor ( period , annualization ) : if annualization is None : try : factor = ANNUALIZATION_FACTORS [ period ] except KeyError : raise ValueError ( "Period cannot be '{}'. " "Can be '{}'." . format ( period , "', '" . join ( ANNUALIZATION_FACTORS . keys ( ) ) ) ) else : factor = annualization return f...
Return annualization factor from period entered or if a custom value is passed in .
30,617
def simple_returns ( prices ) : if isinstance ( prices , ( pd . DataFrame , pd . Series ) ) : out = prices . pct_change ( ) . iloc [ 1 : ] else : out = np . diff ( prices , axis = 0 ) np . divide ( out , prices [ : - 1 ] , out = out ) return out
Compute simple returns from a timeseries of prices .
30,618
def cum_returns ( returns , starting_value = 0 , out = None ) : if len ( returns ) < 1 : return returns . copy ( ) nanmask = np . isnan ( returns ) if np . any ( nanmask ) : returns = returns . copy ( ) returns [ nanmask ] = 0 allocated_output = out is None if allocated_output : out = np . empty_like ( returns ) np . a...
Compute cumulative returns from simple returns .
30,619
def cum_returns_final ( returns , starting_value = 0 ) : if len ( returns ) == 0 : return np . nan if isinstance ( returns , pd . DataFrame ) : result = ( returns + 1 ) . prod ( ) else : result = np . nanprod ( returns + 1 , axis = 0 ) if starting_value == 0 : result -= 1 else : result *= starting_value return result
Compute total returns from simple returns .
30,620
def aggregate_returns ( returns , convert_to ) : def cumulate_returns ( x ) : return cum_returns ( x ) . iloc [ - 1 ] if convert_to == WEEKLY : grouping = [ lambda x : x . year , lambda x : x . isocalendar ( ) [ 1 ] ] elif convert_to == MONTHLY : grouping = [ lambda x : x . year , lambda x : x . month ] elif convert_to...
Aggregates returns by week month or year .
30,621
def max_drawdown ( returns , out = None ) : allocated_output = out is None if allocated_output : out = np . empty ( returns . shape [ 1 : ] ) returns_1d = returns . ndim == 1 if len ( returns ) < 1 : out [ ( ) ] = np . nan if returns_1d : out = out . item ( ) return out returns_array = np . asanyarray ( returns ) cumul...
Determines the maximum drawdown of a strategy .
30,622
def annual_return ( returns , period = DAILY , annualization = None ) : if len ( returns ) < 1 : return np . nan ann_factor = annualization_factor ( period , annualization ) num_years = len ( returns ) / ann_factor ending_value = cum_returns_final ( returns , starting_value = 1 ) return ending_value ** ( 1 / num_years ...
Determines the mean annual growth rate of returns . This is equivilent to the compound annual growth rate .
30,623
def annual_volatility ( returns , period = DAILY , alpha = 2.0 , annualization = None , out = None ) : allocated_output = out is None if allocated_output : out = np . empty ( returns . shape [ 1 : ] ) returns_1d = returns . ndim == 1 if len ( returns ) < 2 : out [ ( ) ] = np . nan if returns_1d : out = out . item ( ) r...
Determines the annual volatility of a strategy .
30,624
def calmar_ratio ( returns , period = DAILY , annualization = None ) : max_dd = max_drawdown ( returns = returns ) if max_dd < 0 : temp = annual_return ( returns = returns , period = period , annualization = annualization ) / abs ( max_dd ) else : return np . nan if np . isinf ( temp ) : return np . nan return temp
Determines the Calmar ratio or drawdown ratio of a strategy .
30,625
def omega_ratio ( returns , risk_free = 0.0 , required_return = 0.0 , annualization = APPROX_BDAYS_PER_YEAR ) : if len ( returns ) < 2 : return np . nan if annualization == 1 : return_threshold = required_return elif required_return <= - 1 : return np . nan else : return_threshold = ( 1 + required_return ) ** ( 1. / an...
Determines the Omega ratio of a strategy .
30,626
def sharpe_ratio ( returns , risk_free = 0 , period = DAILY , annualization = None , out = None ) : allocated_output = out is None if allocated_output : out = np . empty ( returns . shape [ 1 : ] ) return_1d = returns . ndim == 1 if len ( returns ) < 2 : out [ ( ) ] = np . nan if return_1d : out = out . item ( ) return...
Determines the Sharpe ratio of a strategy .
30,627
def sortino_ratio ( returns , required_return = 0 , period = DAILY , annualization = None , out = None , _downside_risk = None ) : allocated_output = out is None if allocated_output : out = np . empty ( returns . shape [ 1 : ] ) return_1d = returns . ndim == 1 if len ( returns ) < 2 : out [ ( ) ] = np . nan if return_1...
Determines the Sortino ratio of a strategy .
30,628
def downside_risk ( returns , required_return = 0 , period = DAILY , annualization = None , out = None ) : allocated_output = out is None if allocated_output : out = np . empty ( returns . shape [ 1 : ] ) returns_1d = returns . ndim == 1 if len ( returns ) < 1 : out [ ( ) ] = np . nan if returns_1d : out = out . item (...
Determines the downside deviation below a threshold
30,629
def excess_sharpe ( returns , factor_returns , out = None ) : allocated_output = out is None if allocated_output : out = np . empty ( returns . shape [ 1 : ] ) returns_1d = returns . ndim == 1 if len ( returns ) < 2 : out [ ( ) ] = np . nan if returns_1d : out = out . item ( ) return out active_return = _adjust_returns...
Determines the Excess Sharpe of a strategy .
30,630
def _to_pandas ( ob ) : if isinstance ( ob , ( pd . Series , pd . DataFrame ) ) : return ob if ob . ndim == 1 : return pd . Series ( ob ) elif ob . ndim == 2 : return pd . DataFrame ( ob ) else : raise ValueError ( 'cannot convert array of dim > 2 to a pandas structure' , )
Convert an array - like to a pandas object .
30,631
def _aligned_series ( * many_series ) : head = many_series [ 0 ] tail = many_series [ 1 : ] n = len ( head ) if ( isinstance ( head , np . ndarray ) and all ( len ( s ) == n and isinstance ( s , np . ndarray ) for s in tail ) ) : return many_series return ( v for _ , v in iteritems ( pd . concat ( map ( _to_pandas , ma...
Return a new list of series containing the data in the input series but with their indices aligned . NaNs will be filled in for missing values .
30,632
def roll_alpha_beta ( returns , factor_returns , window = 10 , ** kwargs ) : returns , factor_returns = _aligned_series ( returns , factor_returns ) return roll_alpha_beta_aligned ( returns , factor_returns , window = window , ** kwargs )
Computes alpha and beta over a rolling window .
30,633
def stability_of_timeseries ( returns ) : if len ( returns ) < 2 : return np . nan returns = np . asanyarray ( returns ) returns = returns [ ~ np . isnan ( returns ) ] cum_log_returns = np . log1p ( returns ) . cumsum ( ) rhat = stats . linregress ( np . arange ( len ( cum_log_returns ) ) , cum_log_returns ) [ 2 ] retu...
Determines R - squared of a linear fit to the cumulative log returns . Computes an ordinary least squares linear fit and returns R - squared .
30,634
def capture ( returns , factor_returns , period = DAILY ) : return ( annual_return ( returns , period = period ) / annual_return ( factor_returns , period = period ) )
Compute capture ratio .
30,635
def up_capture ( returns , factor_returns , ** kwargs ) : return up ( returns , factor_returns , function = capture , ** kwargs )
Compute the capture ratio for periods when the benchmark return is positive
30,636
def down_capture ( returns , factor_returns , ** kwargs ) : return down ( returns , factor_returns , function = capture , ** kwargs )
Compute the capture ratio for periods when the benchmark return is negative
30,637
def up_down_capture ( returns , factor_returns , ** kwargs ) : return ( up_capture ( returns , factor_returns , ** kwargs ) / down_capture ( returns , factor_returns , ** kwargs ) )
Computes the ratio of up_capture to down_capture .
30,638
def up_alpha_beta ( returns , factor_returns , ** kwargs ) : return up ( returns , factor_returns , function = alpha_beta_aligned , ** kwargs )
Computes alpha and beta for periods when the benchmark return is positive .
30,639
def down_alpha_beta ( returns , factor_returns , ** kwargs ) : return down ( returns , factor_returns , function = alpha_beta_aligned , ** kwargs )
Computes alpha and beta for periods when the benchmark return is negative .
30,640
def roll ( * args , ** kwargs ) : func = kwargs . pop ( 'function' ) window = kwargs . pop ( 'window' ) if len ( args ) > 2 : raise ValueError ( "Cannot pass more than 2 return sets" ) if len ( args ) == 2 : if not isinstance ( args [ 0 ] , type ( args [ 1 ] ) ) : raise ValueError ( "The two returns arguments are not t...
Calculates a given statistic across a rolling time period .
30,641
def up ( returns , factor_returns , ** kwargs ) : func = kwargs . pop ( 'function' ) returns = returns [ factor_returns > 0 ] factor_returns = factor_returns [ factor_returns > 0 ] return func ( returns , factor_returns , ** kwargs )
Calculates a given statistic filtering only positive factor return periods .
30,642
def down ( returns , factor_returns , ** kwargs ) : func = kwargs . pop ( 'function' ) returns = returns [ factor_returns < 0 ] factor_returns = factor_returns [ factor_returns < 0 ] return func ( returns , factor_returns , ** kwargs )
Calculates a given statistic filtering only negative factor return periods .
30,643
def get_treasury_yield ( start = None , end = None , period = '3MO' ) : if start is None : start = '1/1/1970' if end is None : end = _1_bday_ago ( ) treasury = web . DataReader ( "DGS3{}" . format ( period ) , "fred" , start , end ) treasury = treasury . ffill ( ) return treasury
Load treasury yields from FRED .
30,644
def default_returns_func ( symbol , start = None , end = None ) : if start is None : start = '1/1/1970' if end is None : end = _1_bday_ago ( ) start = get_utc_timestamp ( start ) end = get_utc_timestamp ( end ) if symbol == 'SPY' : filepath = data_path ( 'spy.csv' ) rets = get_returns_cached ( filepath , get_symbol_ret...
Gets returns for a symbol . Queries Yahoo Finance . Attempts to cache SPY .
30,645
def perf_attrib ( returns , positions , factor_returns , factor_loadings ) : risk_exposures_portfolio = compute_exposures ( positions , factor_loadings ) perf_attrib_by_factor = risk_exposures_portfolio . multiply ( factor_returns ) common_returns = perf_attrib_by_factor . sum ( axis = 'columns' ) specific_returns = re...
Attributes the performance of a returns stream to a set of risk factors .
30,646
def compute_exposures ( positions , factor_loadings ) : risk_exposures = factor_loadings . multiply ( positions , axis = 'rows' ) return risk_exposures . groupby ( level = 'dt' ) . sum ( )
Compute daily risk factor exposures .
30,647
def has_pending ( self ) : if self . workqueue : return True for assigned_unit in self . assigned_work . values ( ) : if self . _pending_of ( assigned_unit ) > 0 : return True return False
Return True if there are pending test items .
30,648
def add_node ( self , node ) : assert node not in self . assigned_work self . assigned_work [ node ] = OrderedDict ( )
Add a new node to the scheduler .
30,649
def remove_node ( self , node ) : workload = self . assigned_work . pop ( node ) if not self . _pending_of ( workload ) : return None for work_unit in workload . values ( ) : for nodeid , completed in work_unit . items ( ) : if not completed : crashitem = nodeid break else : continue break else : raise RuntimeError ( "...
Remove a node from the scheduler .
30,650
def add_node_collection ( self , node , collection ) : assert node in self . assigned_work if self . collection_is_completed : assert self . collection if collection != self . collection : other_node = next ( iter ( self . registered_collections . keys ( ) ) ) msg = report_collection_diff ( self . collection , collecti...
Add the collected test items from a node .
30,651
def _assign_work_unit ( self , node ) : assert self . workqueue scope , work_unit = self . workqueue . popitem ( last = False ) assigned_to_node = self . assigned_work . setdefault ( node , default = OrderedDict ( ) ) assigned_to_node [ scope ] = work_unit worker_collection = self . registered_collections [ node ] node...
Assign a work unit to a node .
30,652
def _pending_of ( self , workload ) : pending = sum ( list ( scope . values ( ) ) . count ( False ) for scope in workload . values ( ) ) return pending
Return the number of pending tests in a workload .
30,653
def _reschedule ( self , node ) : if node . shutting_down : return if not self . workqueue : node . shutdown ( ) return self . log ( "Number of units waiting for node:" , len ( self . workqueue ) ) if self . _pending_of ( self . assigned_work [ node ] ) > 2 : return self . _assign_work_unit ( node )
Maybe schedule new items on the node .
30,654
def schedule ( self ) : assert self . collection_is_completed if self . collection is not None : for node in self . nodes : self . _reschedule ( node ) return if not self . _check_nodes_have_same_collection ( ) : self . log ( "**Different tests collected, aborting run**" ) return self . collection = list ( next ( iter ...
Initiate distribution of the test collection .
30,655
def schedule ( self ) : assert self . collection_is_completed for node , pending in self . node2pending . items ( ) : if node in self . _started : continue if not pending : pending [ : ] = range ( len ( self . node2collection [ node ] ) ) node . send_runtest_all ( ) node . shutdown ( ) else : node . send_runtest_some (...
Schedule the test items on the nodes
30,656
def has_pending ( self ) : if self . pending : return True for pending in self . node2pending . values ( ) : if pending : return True return False
Return True if there are pending test items
30,657
def check_schedule ( self , node , duration = 0 ) : if node . shutting_down : return if self . pending : num_nodes = len ( self . node2pending ) items_per_node_min = max ( 2 , len ( self . pending ) // num_nodes // 4 ) items_per_node_max = max ( 2 , len ( self . pending ) // num_nodes // 2 ) node_pending = self . node2...
Maybe schedule new items on the node
30,658
def remove_node ( self , node ) : pending = self . node2pending . pop ( node ) if not pending : return crashitem = self . collection [ pending . pop ( 0 ) ] self . pending . extend ( pending ) for node in self . node2pending : self . check_schedule ( node ) return crashitem
Remove a node from the scheduler
30,659
def schedule ( self ) : assert self . collection_is_completed if self . collection is not None : for node in self . nodes : self . check_schedule ( node ) return if not self . _check_nodes_have_same_collection ( ) : self . log ( "**Different tests collected, aborting run**" ) return self . collection = list ( self . no...
Initiate distribution of the test collection
30,660
def _check_nodes_have_same_collection ( self ) : node_collection_items = list ( self . node2collection . items ( ) ) first_node , col = node_collection_items [ 0 ] same_collection = True for node , collection in node_collection_items [ 1 : ] : msg = report_collection_diff ( col , collection , first_node . gateway . id ...
Return True if all nodes have collected the same items .
30,661
def loop_once ( self ) : while 1 : if not self . _active_nodes : self . triggershutdown ( ) raise RuntimeError ( "Unexpectedly no active workers available" ) try : eventcall = self . queue . get ( timeout = 2.0 ) break except Empty : continue callname , kwargs = eventcall assert callname , kwargs method = "worker_" + c...
Process one callback from one of the workers .
30,662
def worker_workerready ( self , node , workerinfo ) : node . workerinfo = workerinfo node . workerinfo [ "id" ] = node . gateway . id node . workerinfo [ "spec" ] = node . gateway . spec node . slaveinfo = node . workerinfo self . config . hook . pytest_testnodeready ( node = node ) if self . shuttingdown : node . shut...
Emitted when a node first starts up .
30,663
def worker_workerfinished ( self , node ) : self . config . hook . pytest_testnodedown ( node = node , error = None ) if node . workeroutput [ "exitstatus" ] == 2 : self . shouldstop = "%s received keyboard-interrupt" % ( node , ) self . worker_errordown ( node , "keyboard-interrupt" ) return if node in self . sched . ...
Emitted when node executes its pytest_sessionfinish hook .
30,664
def worker_errordown ( self , node , error ) : self . config . hook . pytest_testnodedown ( node = node , error = error ) try : crashitem = self . sched . remove_node ( node ) except KeyError : pass else : if crashitem : self . handle_crashitem ( crashitem , node ) self . _failed_nodes_count += 1 maximum_reached = ( se...
Emitted by the WorkerController when a node dies .
30,665
def worker_collectionfinish ( self , node , ids ) : if self . shuttingdown : return self . config . hook . pytest_xdist_node_collection_finished ( node = node , ids = ids ) self . _session . testscollected = len ( ids ) self . sched . add_node_collection ( node , ids ) if self . terminal : self . trdist . setstatus ( n...
worker has finished test collection .
30,666
def worker_logstart ( self , node , nodeid , location ) : self . config . hook . pytest_runtest_logstart ( nodeid = nodeid , location = location )
Emitted when a node calls the pytest_runtest_logstart hook .
30,667
def worker_logfinish ( self , node , nodeid , location ) : self . config . hook . pytest_runtest_logfinish ( nodeid = nodeid , location = location )
Emitted when a node calls the pytest_runtest_logfinish hook .
30,668
def worker_collectreport ( self , node , rep ) : assert not rep . passed self . _failed_worker_collectreport ( node , rep )
Emitted when a node calls the pytest_collectreport hook .
30,669
def _clone_node ( self , node ) : spec = node . gateway . spec spec . id = None self . nodemanager . group . allocate_id ( spec ) node = self . nodemanager . setup_node ( spec , self . queue . put ) self . _active_nodes . add ( node ) return node
Return new node based on an existing one .
30,670
def rsync_roots ( self , gateway ) : if self . roots : for root in self . roots : self . rsync ( gateway , root , ** self . rsyncoptions )
Rsync the set of roots to the node s gateway cwd .
30,671
def _getrsyncoptions ( self ) : ignores = list ( self . DEFAULT_IGNORES ) ignores += self . config . option . rsyncignore ignores += self . config . getini ( "rsyncignore" ) return { "ignores" : ignores , "verbose" : self . config . option . verbose }
Get options to be passed for rsync .
30,672
def sendcommand ( self , name , ** kwargs ) : self . log ( "sending command %s(**%s)" % ( name , kwargs ) ) self . channel . send ( ( name , kwargs ) )
send a named parametrized command to the other side .
30,673
def process_from_remote ( self , eventcall ) : try : if eventcall == self . ENDMARK : err = self . channel . _getremoteerror ( ) if not self . _down : if not err or isinstance ( err , EOFError ) : err = "Not properly terminated" self . notify_inproc ( "errordown" , node = self , error = err ) self . _down = True return...
this gets called for each object we receive from the other side and if the channel closes .
30,674
def report_collection_diff ( from_collection , to_collection , from_id , to_id ) : if from_collection == to_collection : return None diff = unified_diff ( from_collection , to_collection , fromfile = from_id , tofile = to_id ) error_message = ( u"Different tests were collected between {from_id} and {to_id}. " u"The dif...
Report the collected test difference between two nodes .
30,675
def apply_search ( queryset , search , schema = None ) : ast = DjangoQLParser ( ) . parse ( search ) schema = schema or DjangoQLSchema schema_instance = schema ( queryset . model ) schema_instance . validate ( ast ) return queryset . filter ( build_filter ( ast , schema_instance ) )
Applies search written in DjangoQL mini - language to given queryset
30,676
def get_options ( self ) : choices = self . _field_choices ( ) if choices : return [ c [ 1 ] for c in choices ] else : return self . model . objects . order_by ( self . name ) . values_list ( self . name , flat = True )
Override this method to provide custom suggestion options
30,677
def get_lookup_value ( self , value ) : choices = self . _field_choices ( ) if choices : if isinstance ( value , list ) : return [ c [ 0 ] for c in choices if c [ 1 ] in value ] else : for c in choices : if c [ 1 ] == value : return c [ 0 ] return value
Override this method to convert displayed values to lookup values
30,678
def get_operator ( self , operator ) : op = { '=' : '' , '>' : '__gt' , '>=' : '__gte' , '<' : '__lt' , '<=' : '__lte' , '~' : '__icontains' , 'in' : '__in' , } . get ( operator ) if op is not None : return op , False op = { '!=' : '' , '!~' : '__icontains' , 'not in' : '__in' , } [ operator ] return op , True
Get a comparison suffix to be used in Django ORM & inversion flag for it
30,679
def introspect ( self , model , exclude = ( ) ) : result = { } open_set = deque ( [ model ] ) closed_set = list ( exclude ) while open_set : model = open_set . popleft ( ) model_label = self . model_label ( model ) if model_label in closed_set : continue model_fields = OrderedDict ( ) for field in self . get_fields ( m...
Start with given model and recursively walk through its relationships .
30,680
def get_fields ( self , model ) : return sorted ( [ f . name for f in model . _meta . get_fields ( ) if f . name != 'password' ] )
By default returns all field names of a given model .
30,681
def validate ( self , node ) : assert isinstance ( node , Node ) if isinstance ( node . operator , Logical ) : self . validate ( node . left ) self . validate ( node . right ) return assert isinstance ( node . left , Name ) assert isinstance ( node . operator , Comparison ) assert isinstance ( node . right , ( Const , ...
Validate DjangoQL AST tree vs . current schema
30,682
def find_column ( self , t ) : cr = max ( self . text . rfind ( l , 0 , t . lexpos ) for l in self . line_terminators ) if cr == - 1 : return t . lexpos + 1 return t . lexpos - cr
Returns token position in current text starting from 1
30,683
async def execute_filter ( filter_ : FilterObj , args ) : if filter_ . is_async : return await filter_ . filter ( * args , ** filter_ . kwargs ) else : return filter_ . filter ( * args , ** filter_ . kwargs )
Helper for executing filter
30,684
async def check_filters ( filters : typing . Iterable [ FilterObj ] , args ) : data = { } if filters is not None : for filter_ in filters : f = await execute_filter ( filter_ , args ) if not f : raise FilterNotPassed ( ) elif isinstance ( f , dict ) : data . update ( f ) return data
Check list of filters
30,685
def validate ( cls , full_config : typing . Dict [ str , typing . Any ] ) -> typing . Optional [ typing . Dict [ str , typing . Any ] ] : pass
Validate and parse config .
30,686
async def check ( self , * args ) : data = { } for target in self . targets : result = await target ( * args ) if not result : return False if isinstance ( result , dict ) : data . update ( result ) if not data : return True return data
All filters must return a positive result
30,687
async def send_message ( user_id : int , text : str , disable_notification : bool = False ) -> bool : try : await bot . send_message ( user_id , text , disable_notification = disable_notification ) except exceptions . BotBlocked : log . error ( f"Target [ID:{user_id}]: blocked by user" ) except exceptions . ChatNotFoun...
Safe messages sender
30,688
def get_full_command ( self ) : if self . is_command ( ) : command , _ , args = self . text . partition ( ' ' ) return command , args
Split command and args
30,689
def get_command ( self , pure = False ) : command = self . get_full_command ( ) if command : command = command [ 0 ] if pure : command , _ , _ = command [ 1 : ] . partition ( '@' ) return command
Get command from message
30,690
def parse_entities ( self , as_html = True ) : text = self . text or self . caption if text is None : raise TypeError ( "This message doesn't have any text." ) quote_fn = md . quote_html if as_html else md . escape_md entities = self . entities or self . caption_entities if not entities : return quote_fn ( text ) if no...
Text or caption formatted as HTML or Markdown .
30,691
def url ( self ) -> str : if self . chat . type not in [ ChatType . SUPER_GROUP , ChatType . CHANNEL ] : raise TypeError ( 'Invalid chat type!' ) elif not self . chat . username : raise TypeError ( 'This chat does not have @username' ) return f"https://t.me/{self.chat.username}/{self.message_id}"
Get URL for the message
30,692
def link ( self , text , as_html = True ) -> str : try : url = self . url except TypeError : if as_html : return md . quote_html ( text ) return md . escape_md ( text ) if as_html : return md . hlink ( text , url ) return md . link ( text , url )
Generate URL for using in text messages with HTML or MD parse mode
30,693
async def answer ( self , text , parse_mode = None , disable_web_page_preview = None , disable_notification = None , reply_markup = None , reply = False ) -> Message : return await self . bot . send_message ( chat_id = self . chat . id , text = text , parse_mode = parse_mode , disable_web_page_preview = disable_web_pag...
Answer to this message
30,694
async def answer_photo ( self , photo : typing . Union [ base . InputFile , base . String ] , caption : typing . Union [ base . String , None ] = None , disable_notification : typing . Union [ base . Boolean , None ] = None , reply_markup = None , reply = False ) -> Message : return await self . bot . send_photo ( chat...
Use this method to send photos .
30,695
async def forward ( self , chat_id , disable_notification = None ) -> Message : return await self . bot . forward_message ( chat_id , self . chat . id , self . message_id , disable_notification )
Forward this message
30,696
async def delete ( self ) : return await self . bot . delete_message ( self . chat . id , self . message_id )
Delete this message
30,697
def new ( self , * args , ** kwargs ) -> str : args = list ( args ) data = [ self . prefix ] for part in self . _part_names : value = kwargs . pop ( part , None ) if value is None : if args : value = args . pop ( 0 ) else : raise ValueError ( f"Value for '{part}' is not passed!" ) if value is not None and not isinstanc...
Generate callback data
30,698
async def cmd_id ( message : types . Message ) : if message . reply_to_message : target = message . reply_to_message . from_user chat = message . chat elif message . forward_from and message . chat . type == ChatType . PRIVATE : target = message . forward_from chat = message . forward_from or message . chat else : targ...
Return info about user .
30,699
async def on_shutdown ( app ) : await bot . delete_webhook ( ) await dp . storage . close ( ) await dp . storage . wait_closed ( )
Graceful shutdown . This method is recommended by aiohttp docs .