idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
246,900
def _process_registry ( registry , call_func ) : from django . core . exceptions import ImproperlyConfigured from django . apps import apps for key , value in list ( registry . items ( ) ) : model = apps . get_model ( * key . split ( '.' ) ) if model is None : raise ImproperlyConfigured ( _ ( '%(key)s is not a model' )...
Given a dictionary and a registration function process the registry
335
10
246,901
def field_exists ( app_name , model_name , field_name ) : model = apps . get_model ( app_name , model_name ) table_name = model . _meta . db_table cursor = connection . cursor ( ) field_info = connection . introspection . get_table_description ( cursor , table_name ) field_names = [ f . name for f in field_info ] retur...
Does the FK or M2M table exist in the database already?
98
15
246,902
def drop_field ( app_name , model_name , field_name ) : app_config = apps . get_app_config ( app_name ) model = app_config . get_model ( model_name ) field = model . _meta . get_field ( field_name ) with connection . schema_editor ( ) as schema_editor : schema_editor . remove_field ( model , field )
Drop the given field from the app s model
88
9
246,903
def migrate_app ( sender , * args , * * kwargs ) : from . registration import registry if 'app_config' not in kwargs : return app_config = kwargs [ 'app_config' ] app_name = app_config . label fields = [ fld for fld in list ( registry . _field_registry . keys ( ) ) if fld . startswith ( app_name ) ] sid = transaction ....
Migrate all models of this app registered
229
8
246,904
def get_absolute_url ( self ) : from django . urls import NoReverseMatch if self . alternate_url : return self . alternate_url try : prefix = reverse ( 'categories_tree_list' ) except NoReverseMatch : prefix = '/' ancestors = list ( self . get_ancestors ( ) ) + [ self , ] return prefix + '/' . join ( [ force_text ( i ....
Return a path
106
3
246,905
def get_content_type ( self , content_type ) : qs = self . get_queryset ( ) return qs . filter ( content_type__name = content_type )
Get all the items of the given content type related to this item .
42
14
246,906
def get_relation_type ( self , relation_type ) : qs = self . get_queryset ( ) return qs . filter ( relation_type = relation_type )
Get all the items of the given relationship type related to this item .
40
14
246,907
def handle_class_prepared ( sender , * * kwargs ) : from . settings import M2M_REGISTRY , FK_REGISTRY from . registration import registry sender_app = sender . _meta . app_label sender_name = sender . _meta . model_name for key , val in list ( FK_REGISTRY . items ( ) ) : app_name , model_name = key . split ( '.' ) if a...
See if this class needs registering of fields
207
8
246,908
def get_queryset ( self , request ) : qs = self . model . _default_manager . get_queryset ( ) qs . __class__ = TreeEditorQuerySet return qs
Returns a QuerySet of all model instances that can be edited by the admin site . This is used by changelist_view .
45
26
246,909
def deactivate ( self , request , queryset ) : selected_cats = self . model . objects . filter ( pk__in = [ int ( x ) for x in request . POST . getlist ( '_selected_action' ) ] ) for item in selected_cats : if item . active : item . active = False item . save ( ) item . children . all ( ) . update ( active = False )
Set active to False for selected items
90
7
246,910
def get_indent ( self , string ) : indent_amt = 0 if string [ 0 ] == '\t' : return '\t' for char in string : if char == ' ' : indent_amt += 1 else : return ' ' * indent_amt
Look through the string and count the spaces
60
8
246,911
def make_category ( self , string , parent = None , order = 1 ) : cat = Category ( name = string . strip ( ) , slug = slugify ( SLUG_TRANSLITERATOR ( string . strip ( ) ) ) [ : 49 ] , # arent=parent, order = order ) cat . _tree_manager . insert_node ( cat , parent , 'last-child' , True ) cat . save ( ) if parent : pare...
Make and save a category object from a string
118
9
246,912
def parse_lines ( self , lines ) : indent = '' level = 0 if lines [ 0 ] [ 0 ] == ' ' or lines [ 0 ] [ 0 ] == '\t' : raise CommandError ( "The first line in the file cannot start with a space or tab." ) # This keeps track of the current parents at a given level current_parents = { 0 : None } for line in lines : if len (...
Do the work of parsing each line
239
7
246,913
def handle ( self , * file_paths , * * options ) : import os for file_path in file_paths : if not os . path . isfile ( file_path ) : print ( "File %s not found." % file_path ) continue f = open ( file_path , 'r' ) data = f . readlines ( ) f . close ( ) self . parse_lines ( data )
Handle the basic import
90
4
246,914
def get_cat_model ( model ) : try : if isinstance ( model , string_types ) : model_class = apps . get_model ( * model . split ( "." ) ) elif issubclass ( model , CategoryBase ) : model_class = model if model_class is None : raise TypeError except TypeError : raise TemplateSyntaxError ( "Unknown model submitted: %s" % m...
Return a class from a string or class
94
8
246,915
def get_category ( category_string , model = Category ) : model_class = get_cat_model ( model ) category = str ( category_string ) . strip ( "'\"" ) category = category . strip ( '/' ) cat_list = category . split ( '/' ) if len ( cat_list ) == 0 : return None try : categories = model_class . objects . filter ( name = c...
Convert a string including a path and return the Category object
203
12
246,916
def get_category_drilldown ( parser , token ) : bits = token . split_contents ( ) error_str = '%(tagname)s tag should be in the format {%% %(tagname)s ' '"category name" [using "app.Model"] as varname %%} or ' '{%% %(tagname)s category_obj as varname %%}.' if len ( bits ) == 4 : if bits [ 2 ] != 'as' : raise template ....
Retrieves the specified category its ancestors and its immediate children as an iterable .
327
17
246,917
def get_top_level_categories ( parser , token ) : bits = token . split_contents ( ) usage = 'Usage: {%% %s [using "app.Model"] as <variable> %%}' % bits [ 0 ] if len ( bits ) == 3 : if bits [ 1 ] != 'as' : raise template . TemplateSyntaxError ( usage ) varname = bits [ 2 ] model = "categories.category" elif len ( bits ...
Retrieves an alphabetical list of all the categories that have no parents .
226
16
246,918
def tree_queryset ( value ) : from django . db . models . query import QuerySet from copy import deepcopy if not isinstance ( value , QuerySet ) : return value qs = value qs2 = deepcopy ( qs ) # Reaching into the bowels of query sets to find out whether the qs is # actually filtered and we need to do the INCLUDE_ANCEST...
Converts a normal queryset from an MPTT model to include all the ancestors so a filtered subset of items can be formatted correctly
324
27
246,919
def convolve ( data , h , res_g = None , sub_blocks = None ) : if not len ( data . shape ) in [ 1 , 2 , 3 ] : raise ValueError ( "dim = %s not supported" % ( len ( data . shape ) ) ) if len ( data . shape ) != len ( h . shape ) : raise ValueError ( "dimemnsion of data (%s) and h (%s) are different" % ( len ( data . sha...
convolves 1d - 3d data with kernel h
407
11
246,920
def _convolve3_old ( data , h , dev = None ) : if dev is None : dev = get_device ( ) if dev is None : raise ValueError ( "no OpenCLDevice found..." ) dtype = data . dtype . type dtypes_options = { np . float32 : "" , np . uint16 : "-D SHORTTYPE" } if not dtype in dtypes_options : raise TypeError ( "data type %s not sup...
convolves 3d data with kernel h on the GPU Device dev boundary conditions are clamping to edge . h is converted to float32
273
27
246,921
def _scale_shape ( dshape , scale = ( 1 , 1 , 1 ) ) : nshape = np . round ( np . array ( dshape ) * np . array ( scale ) ) return tuple ( nshape . astype ( np . int ) )
returns the shape after scaling ( should be the same as ndimage . zoom
56
17
246,922
def fftshift ( arr_obj , axes = None , res_g = None , return_buffer = False ) : if axes is None : axes = list ( range ( arr_obj . ndim ) ) if isinstance ( arr_obj , OCLArray ) : if not arr_obj . dtype . type in DTYPE_KERNEL_NAMES : raise NotImplementedError ( "only works for float32 or complex64" ) elif isinstance ( ar...
gpu version of fftshift for numpy arrays or OCLArrays
343
15
246,923
def _fftshift_single ( d_g , res_g , ax = 0 ) : dtype_kernel_name = { np . float32 : "fftshift_1_f" , np . complex64 : "fftshift_1_c" } N = d_g . shape [ ax ] N1 = 1 if ax == 0 else np . prod ( d_g . shape [ : ax ] ) N2 = 1 if ax == len ( d_g . shape ) - 1 else np . prod ( d_g . shape [ ax + 1 : ] ) dtype = d_g . dtype...
basic fftshift of an OCLArray
222
9
246,924
def fft_convolve ( data , h , res_g = None , plan = None , inplace = False , kernel_is_fft = False , kernel_is_fftshifted = False ) : if isinstance ( data , np . ndarray ) : return _fft_convolve_numpy ( data , h , plan = plan , kernel_is_fft = kernel_is_fft , kernel_is_fftshifted = kernel_is_fftshifted ) elif isinstanc...
convolves data with kernel h via FFTs
194
10
246,925
def _fft_convolve_numpy ( data , h , plan = None , kernel_is_fft = False , kernel_is_fftshifted = False ) : if data . shape != h . shape : raise ValueError ( "data and kernel must have same size! %s vs %s " % ( str ( data . shape ) , str ( h . shape ) ) ) data_g = OCLArray . from_array ( data . astype ( np . complex64 ...
convolving via opencl fft for numpy arrays
240
12
246,926
def _fft_convolve_gpu ( data_g , h_g , res_g = None , plan = None , inplace = False , kernel_is_fft = False ) : assert_bufs_type ( np . complex64 , data_g , h_g ) if data_g . shape != h_g . shape : raise ValueError ( "data and kernel must have same size! %s vs %s " % ( str ( data_g . shape ) , str ( h_g . shape ) ) ) i...
fft convolve for gpu buffer
328
8
246,927
def median_filter ( data , size = 3 , cval = 0 , res_g = None , sub_blocks = None ) : if data . ndim == 2 : _filt = make_filter ( _median_filter_gpu_2d ( ) ) elif data . ndim == 3 : _filt = make_filter ( _median_filter_gpu_3d ( ) ) else : raise ValueError ( "currently only 2 or 3 dimensional data is supported" ) return...
median filter of given size
141
6
246,928
def rotate ( data , axis = ( 1. , 0 , 0 ) , angle = 0. , center = None , mode = "constant" , interpolation = "linear" ) : if center is None : center = tuple ( [ s // 2 for s in data . shape ] ) cx , cy , cz = center m = np . dot ( mat4_translate ( cx , cy , cz ) , np . dot ( mat4_rotate ( angle , * axis ) , mat4_transl...
rotates data around axis by a given angle
150
9
246,929
def map_coordinates ( data , coordinates , interpolation = "linear" , mode = 'constant' ) : if not ( isinstance ( data , np . ndarray ) and data . ndim in ( 2 , 3 ) ) : raise ValueError ( "input data has to be a 2d or 3d array!" ) coordinates = np . asarray ( coordinates , np . int32 ) if not ( coordinates . shape [ 0 ...
Map data to new coordinates by interpolation . The array of coordinates is used to find for each point in the output the corresponding coordinates in the input .
665
30
246,930
def pad_to_shape ( d , dshape , mode = "constant" ) : if d . shape == dshape : return d diff = np . array ( dshape ) - np . array ( d . shape ) #first shrink slices = tuple ( slice ( - x // 2 , x // 2 ) if x < 0 else slice ( None , None ) for x in diff ) res = d [ slices ] #then pad # return np.pad(res,[(n/2,n-n/2) if ...
pad array d to shape dshape
188
7
246,931
def pad_to_power2 ( data , axis = None , mode = "constant" ) : if axis is None : axis = list ( range ( data . ndim ) ) if np . all ( [ _is_power2 ( n ) for i , n in enumerate ( data . shape ) if i in axis ] ) : return data else : return pad_to_shape ( data , [ ( _next_power_of_2 ( n ) if i in axis else n ) for i , n in...
pad data to a shape of power 2 if axis == None all axis are padded
121
16
246,932
def max_filter ( data , size = 7 , res_g = None , sub_blocks = ( 1 , 1 , 1 ) ) : if data . ndim == 2 : _filt = make_filter ( _generic_filter_gpu_2d ( FUNC = "(val>res?val:res)" , DEFAULT = "-INFINITY" ) ) elif data . ndim == 3 : _filt = make_filter ( _generic_filter_gpu_3d ( FUNC = "(val>res?val:res)" , DEFAULT = "-INF...
maximum filter of given size
158
5
246,933
def min_filter ( data , size = 7 , res_g = None , sub_blocks = ( 1 , 1 , 1 ) ) : if data . ndim == 2 : _filt = make_filter ( _generic_filter_gpu_2d ( FUNC = "(val<res?val:res)" , DEFAULT = "INFINITY" ) ) elif data . ndim == 3 : _filt = make_filter ( _generic_filter_gpu_3d ( FUNC = "(val<res?val:res)" , DEFAULT = "INFIN...
minimum filter of given size
176
5
246,934
def uniform_filter ( data , size = 7 , res_g = None , sub_blocks = ( 1 , 1 , 1 ) , normalized = True ) : if normalized : if np . isscalar ( size ) : norm = size else : norm = np . int32 ( np . prod ( size ) ) ** ( 1. / len ( size ) ) FUNC = "res+val/%s" % norm else : FUNC = "res+val" if data . ndim == 2 : _filt = make_...
mean filter of given size
212
5
246,935
def _gauss_filter ( data , sigma = 4 , res_g = None , sub_blocks = ( 1 , 1 , 1 ) ) : truncate = 4. radius = tuple ( int ( truncate * s + 0.5 ) for s in sigma ) size = tuple ( 2 * r + 1 for r in radius ) s = sigma [ 0 ] if data . ndim == 2 : _filt = make_filter ( _generic_filter_gpu_2d ( FUNC = "res+(val*native_exp((flo...
gaussian filter of given size
312
6
246,936
def _separable_series2 ( h , N = 1 ) : if min ( h . shape ) < N : raise ValueError ( "smallest dimension of h is smaller than approximation order! (%s < %s)" % ( min ( h . shape ) , N ) ) U , S , V = linalg . svd ( h ) hx = [ - U [ : , n ] * np . sqrt ( S [ n ] ) for n in range ( N ) ] hy = [ - V [ n , : ] * np . sqrt ...
finds separable approximations to the 2d function 2d h
149
15
246,937
def _separable_approx2 ( h , N = 1 ) : return np . cumsum ( [ np . outer ( fy , fx ) for fy , fx in _separable_series2 ( h , N ) ] , 0 )
returns the N first approximations to the 2d function h whose sum should be h
56
19
246,938
def _separable_approx3 ( h , N = 1 ) : return np . cumsum ( [ np . einsum ( "i,j,k" , fz , fy , fx ) for fz , fy , fx in _separable_series3 ( h , N ) ] , 0 )
returns the N first approximations to the 3d function h
72
14
246,939
def separable_approx ( h , N = 1 ) : if h . ndim == 2 : return _separable_approx2 ( h , N ) elif h . ndim == 3 : return _separable_approx3 ( h , N ) else : raise ValueError ( "unsupported array dimension: %s (only 2d or 3d) " % h . ndim )
finds the k - th rank approximation to h where k = 1 .. N
86
16
246,940
def tables ( self ) : _tables = set ( ) for attr in six . itervalues ( self . __dict__ ) : if isinstance ( attr , list ) : for item in attr : if isinstance ( item , Node ) : _tables |= item . tables ( ) elif isinstance ( attr , Node ) : _tables |= attr . tables ( ) return _tables
Generic method that does a depth - first search on the node attributes .
92
14
246,941
def fix_identities ( self , uniq = None ) : if not hasattr ( self , 'children' ) : return self uniq = list ( set ( self . flat ( ) ) ) if uniq is None else uniq for i , child in enumerate ( self . children ) : if not hasattr ( child , 'children' ) : assert child in uniq self . children [ i ] = uniq [ uniq . index ( chi...
Make pattern - tree tips point to same object if they are equal .
110
14
246,942
def find_version ( fname ) : version = "" with open ( fname , "r" ) as fp : reg = re . compile ( r'__version__ = [\'"]([^\'"]*)[\'"]' ) for line in fp : m = reg . match ( line ) if m : version = m . group ( 1 ) break if not version : raise RuntimeError ( "Cannot find version information" ) return version
Attempts to find the version number in the file names fname . Raises RuntimeError if not found .
95
21
246,943
def format_context ( context : Context , formatter : typing . Union [ str , Formatter ] = "full" ) -> str : if not context : return "" if callable ( formatter ) : formatter_func = formatter else : if formatter in CONTEXT_FORMATTERS : formatter_func = CONTEXT_FORMATTERS [ formatter ] else : raise ValueError ( f'Invalid ...
Output the a context dictionary as a string .
104
9
246,944
def make_banner ( text : typing . Optional [ str ] = None , context : typing . Optional [ Context ] = None , banner_template : typing . Optional [ str ] = None , context_format : ContextFormat = "full" , ) -> str : banner_text = text or speak ( ) banner_template = banner_template or BANNER_TEMPLATE ctx = format_context...
Generates a full banner with version info the given text and a formatted list of context variables .
127
19
246,945
def config ( config_dict : typing . Mapping ) -> Config : logger . debug ( f"Updating with {config_dict}" ) _cfg . update ( config_dict ) return _cfg
Configures the konch shell . This function should be called in a . konchrc file .
42
22
246,946
def named_config ( name : str , config_dict : typing . Mapping ) -> None : names = ( name if isinstance ( name , Iterable ) and not isinstance ( name , ( str , bytes ) ) else [ name ] ) for each in names : _config_registry [ each ] = Config ( * * config_dict )
Adds a named config to the config registry . The first argument may either be a string or a collection of strings .
74
23
246,947
def __ensure_directory_in_path ( filename : Path ) -> None : directory = Path ( filename ) . parent . resolve ( ) if directory not in sys . path : logger . debug ( f"Adding {directory} to sys.path" ) sys . path . insert ( 0 , str ( directory ) )
Ensures that a file s directory is in the Python path .
67
14
246,948
def use_file ( filename : typing . Union [ Path , str , None ] , trust : bool = False ) -> typing . Union [ types . ModuleType , None ] : config_file = filename or resolve_path ( CONFIG_FILE ) def preview_unauthorized ( ) -> None : if not config_file : return None print ( SEPARATOR , file = sys . stderr ) with Path ( c...
Load filename as a python file . Import filename and return it as a module .
482
16
246,949
def resolve_path ( filename : Path ) -> typing . Union [ Path , None ] : current = Path . cwd ( ) # Stop search at home directory sentinel_dir = Path . home ( ) . parent . resolve ( ) while current != sentinel_dir : target = Path ( current ) / Path ( filename ) if target . exists ( ) : return target . resolve ( ) else ...
Find a file by walking up parent directories until the file is found . Return the absolute path of the file .
94
22
246,950
def parse_args ( argv : typing . Optional [ typing . Sequence ] = None ) -> typing . Dict [ str , str ] : return docopt ( __doc__ , argv = argv , version = __version__ )
Exposes the docopt command - line arguments parser . Return a dictionary of arguments .
50
17
246,951
def main ( argv : typing . Optional [ typing . Sequence ] = None ) -> typing . NoReturn : args = parse_args ( argv ) if args [ "--debug" ] : logging . basicConfig ( format = "%(levelname)s %(filename)s: %(message)s" , level = logging . DEBUG ) logger . debug ( args ) config_file : typing . Union [ Path , None ] if args...
Main entry point for the konch CLI .
465
10
246,952
def init_autoreload ( mode : int ) -> None : from IPython . extensions import autoreload ip = get_ipython ( ) # type: ignore # noqa: F821 autoreload . load_ipython_extension ( ip ) ip . magics_manager . magics [ "line" ] [ "autoreload" ] ( str ( mode ) )
Load and initialize the IPython autoreload extension .
83
11
246,953
def read_tabular ( table_file , sheetname = 'Sheet1' ) : if isinstance ( table_file , str ) : extension = table_file . split ( '.' ) [ - 1 ] if extension in [ 'xls' , 'xlsx' ] : table = pd . read_excel ( table_file , sheetname = sheetname ) elif extension == 'csv' : table = pd . read_csv ( table_file , encoding = 'UTF-...
Reads a vensim syntax model which has been formatted as a table .
521
16
246,954
def read_xmile ( xmile_file ) : from . import py_backend from . py_backend . xmile . xmile2py import translate_xmile py_model_file = translate_xmile ( xmile_file ) model = load ( py_model_file ) model . xmile_file = xmile_file return model
Construct a model object from . xmile file .
77
10
246,955
def read_vensim ( mdl_file ) : from . py_backend . vensim . vensim2py import translate_vensim from . py_backend import functions py_model_file = translate_vensim ( mdl_file ) model = functions . Model ( py_model_file ) model . mdl_file = mdl_file return model
Construct a model from Vensim . mdl file .
82
12
246,956
def cache ( horizon ) : def cache_step ( func ) : """ Decorator for caching at a step level""" @ wraps ( func ) def cached ( * args ) : """Step wise cache function""" try : # fails if cache is out of date or not instantiated data = func . __globals__ [ '__data' ] assert cached . cache_t == data [ 'time' ] ( ) assert ha...
Put a wrapper around a model function
286
7
246,957
def ramp ( time , slope , start , finish = 0 ) : t = time ( ) if t < start : return 0 else : if finish <= 0 : return slope * ( t - start ) elif t > finish : return slope * ( finish - start ) else : return slope * ( t - start )
Implements vensim s and xmile s RAMP function
65
14
246,958
def pulse ( time , start , duration ) : t = time ( ) return 1 if start <= t < start + duration else 0
Implements vensim s PULSE function
27
11
246,959
def pulse_train ( time , start , duration , repeat_time , end ) : t = time ( ) if start <= t < end : return 1 if ( t - start ) % repeat_time < duration else 0 else : return 0
Implements vensim s PULSE TRAIN function
50
13
246,960
def lookup_extrapolation ( x , xs , ys ) : length = len ( xs ) if x < xs [ 0 ] : dx = xs [ 1 ] - xs [ 0 ] dy = ys [ 1 ] - ys [ 0 ] k = dy / dx return ys [ 0 ] + ( x - xs [ 0 ] ) * k if x > xs [ length - 1 ] : dx = xs [ length - 1 ] - xs [ length - 2 ] dy = ys [ length - 1 ] - ys [ length - 2 ] k = dy / dx return ys [ l...
Intermediate values are calculated with linear interpolation between the intermediate points . Out - of - range values are calculated with linear extrapolation from the last two values at either end .
167
35
246,961
def xidz ( numerator , denominator , value_if_denom_is_zero ) : small = 1e-6 # What is considered zero according to Vensim Help if abs ( denominator ) < small : return value_if_denom_is_zero else : return numerator * 1.0 / denominator
Implements Vensim s XIDZ function . This function executes a division robust to denominator being zero . In the case of zero denominator the final argument is returned .
72
37
246,962
def initialize ( self , initialization_order = None ) : # Initialize time if self . time is None : if self . time_initialization is None : self . time = Time ( ) else : self . time = self . time_initialization ( ) # if self.time is None: # self.time = time # self.components.time = self.time # self.components.functions....
This function tries to initialize the stateful objects .
232
10
246,963
def set_components ( self , params ) : # It might make sense to allow the params argument to take a pandas series, where # the indices of the series are variable names. This would make it easier to # do a Pandas apply on a DataFrame of parameter values. However, this may conflict # with a pandas series being passed in ...
Set the value of exogenous model elements . Element values can be passed as keyword = value pairs in the function call . Values can be numeric type or pandas Series . Series will be interpolated by integrator .
270
43
246,964
def _timeseries_component ( self , series ) : # this is only called if the set_component function recognizes a pandas series # Todo: raise a warning if extrapolating from the end of the series. return lambda : np . interp ( self . time ( ) , series . index , series . values )
Internal function for creating a timeseries model element
68
9
246,965
def set_state ( self , t , state ) : self . time . update ( t ) for key , value in state . items ( ) : # TODO Implement map with reference between component and stateful element? component_name = utils . get_value_by_insensitive_key_or_value ( key , self . components . _namespace ) if component_name is not None : state...
Set the system state .
229
5
246,966
def clear_caches ( self ) : for element_name in dir ( self . components ) : element = getattr ( self . components , element_name ) if hasattr ( element , 'cache_val' ) : delattr ( element , 'cache_val' )
Clears the Caches for all model elements
58
9
246,967
def doc ( self ) : collector = [ ] for name , varname in self . components . _namespace . items ( ) : try : docstring = getattr ( self . components , varname ) . __doc__ lines = docstring . split ( '\n' ) collector . append ( { 'Real Name' : name , 'Py Name' : varname , 'Eqn' : lines [ 2 ] . replace ( "Original Eqn:" ,...
Formats a table of documentation strings to help users remember variable names and understand how they are translated into python safe names .
293
24
246,968
def initialize ( self ) : self . time . update ( self . components . initial_time ( ) ) self . time . stage = 'Initialization' super ( Model , self ) . initialize ( )
Initializes the simulation model
42
5
246,969
def _format_return_timestamps ( self , return_timestamps = None ) : if return_timestamps is None : # Build based upon model file Start, Stop times and Saveper # Vensim's standard is to expect that the data set includes the `final time`, # so we have to add an extra period to make sure we get that value in what # numpy'...
Format the passed in return timestamps value as a numpy array . If no value is passed build up array of timestamps based upon model start and end times and the saveper value .
322
40
246,970
def run ( self , params = None , return_columns = None , return_timestamps = None , initial_condition = 'original' , reload = False ) : if reload : self . reload ( ) if params : self . set_components ( params ) self . set_initial_condition ( initial_condition ) return_timestamps = self . _format_return_timestamps ( ret...
Simulate the model s behavior over time . Return a pandas dataframe with timestamps as rows model elements as columns .
255
26
246,971
def _default_return_columns ( self ) : return_columns = [ ] parsed_expr = [ ] for key , value in self . components . _namespace . items ( ) : if hasattr ( self . components , value ) : sig = signature ( getattr ( self . components , value ) ) # The `*args` reference handles the py2.7 decorator. if len ( set ( sig . par...
Return a list of the model elements that does not include lookup functions or other functions that take parameters .
144
20
246,972
def set_initial_condition ( self , initial_condition ) : if isinstance ( initial_condition , tuple ) : # Todo: check the values more than just seeing if they are a tuple. self . set_state ( * initial_condition ) elif isinstance ( initial_condition , str ) : if initial_condition . lower ( ) in [ 'original' , 'o' ] : sel...
Set the initial conditions of the integration .
160
8
246,973
def _euler_step ( self , dt ) : self . state = self . state + self . ddt ( ) * dt
Performs a single step in the euler integration updating stateful components
30
14
246,974
def _integrate ( self , time_steps , capture_elements , return_timestamps ) : # Todo: consider adding the timestamp to the return elements, and using that as the index outputs = [ ] for t2 in time_steps [ 1 : ] : if self . time ( ) in return_timestamps : outputs . append ( { key : getattr ( self . components , key ) ( ...
Performs euler integration
202
5
246,975
def merge_partial_elements ( element_list ) : outs = dict ( ) # output data structure for element in element_list : if element [ 'py_expr' ] != "None" : # for name = element [ 'py_name' ] if name not in outs : # Use 'expr' for Vensim models, and 'eqn' for Xmile (This makes the Vensim equation prettier.) eqn = element [...
merges model elements which collectively all define the model component mostly for multidimensional subscripts
434
18
246,976
def add_n_delay ( delay_input , delay_time , initial_value , order , subs , subscript_dict ) : # the py name has to be unique to all the passed parameters, or if there are two things # that delay the output by different amounts, they'll overwrite the original function... stateful = { 'py_name' : utils . make_python_ide...
Creates code to instantiate a stateful Delay object and provides reference to that object s output .
296
20
246,977
def add_n_smooth ( smooth_input , smooth_time , initial_value , order , subs , subscript_dict ) : stateful = { 'py_name' : utils . make_python_identifier ( '_smooth_%s_%s_%s_%s' % ( smooth_input , smooth_time , initial_value , order ) ) [ 0 ] , 'real_name' : 'Smooth of %s' % smooth_input , 'doc' : 'Smooth time: %s \n S...
Constructs stock and flow chains that implement the calculation of a smoothing function .
262
16
246,978
def add_initial ( initial_input ) : stateful = { 'py_name' : utils . make_python_identifier ( '_initial_%s' % initial_input ) [ 0 ] , 'real_name' : 'Smooth of %s' % initial_input , 'doc' : 'Returns the value taken on during the initialization phase' , 'py_expr' : 'functions.Initial(lambda: %s)' % ( initial_input ) , 'u...
Constructs a stateful object for handling vensim s Initial functionality
173
14
246,979
def add_macro ( macro_name , filename , arg_names , arg_vals ) : func_args = '{ %s }' % ', ' . join ( [ "'%s': lambda: %s" % ( key , val ) for key , val in zip ( arg_names , arg_vals ) ] ) stateful = { 'py_name' : '_macro_' + macro_name + '_' + '_' . join ( [ utils . make_python_identifier ( f ) [ 0 ] for f in arg_vals...
Constructs a stateful object instantiating a Macro
275
10
246,980
def add_incomplete ( var_name , dependencies ) : warnings . warn ( '%s has no equation specified' % var_name , SyntaxWarning , stacklevel = 2 ) # first arg is `self` reference return "functions.incomplete(%s)" % ', ' . join ( dependencies [ 1 : ] ) , [ ]
Incomplete functions don t really need to be builders as they add no new real structure but it s helpful to have a function in which we can raise a warning about the incomplete equation at translate time .
73
40
246,981
def get_model_elements ( model_str ) : model_structure_grammar = _include_common_grammar ( r""" model = (entry / section)+ sketch? entry = element "~" element "~" element ("~" element)? "|" section = element "~" element "|" sketch = ~r".*" #anything # Either an escape group, or a character that is not tilde or pipe ele...
Takes in a string representing model text and splits it into elements
390
13
246,982
def get_equation_components ( equation_str ) : component_structure_grammar = _include_common_grammar ( r""" entry = component / subscript_definition / lookup_definition component = name _ subscriptlist? _ "=" _ expression subscript_definition = name _ ":" _ subscript _ ("," _ subscript)* lookup_definition = name _ &"("...
Breaks down a string representing only the equation part of a model element . Recognizes the various types of model elements that may exist and identifies them .
535
30
246,983
def parse_units ( units_str ) : if not len ( units_str ) : return units_str , ( None , None ) if units_str [ - 1 ] == ']' : units , lims = units_str . rsplit ( '[' ) # type: str, str else : units = units_str lims = '?, ?]' lims = tuple ( [ float ( x ) if x . strip ( ) != '?' else None for x in lims . strip ( ']' ) . sp...
Extract and parse the units Extract the bounds over which the expression is assumed to apply .
125
18
246,984
def parse_lookup_expression ( element ) : lookup_grammar = r""" lookup = _ "(" range? _ ( "(" _ number _ "," _ number _ ")" _ ","? _ )+ ")" number = ("+"/"-")? ~r"\d+\.?\d*(e[+-]\d+)?" _ = ~r"[\s\\]*" # whitespace character range = _ "[" ~r"[^\]]*" "]" _ "," """ parser = parsimonious . Grammar ( lookup_grammar ) tree =...
This syntax parses lookups that are defined with their own element
399
13
246,985
def dict_find ( in_dict , value ) : # Todo: make this robust to repeated values # Todo: make this robust to missing values return list ( in_dict . keys ( ) ) [ list ( in_dict . values ( ) ) . index ( value ) ]
Helper function for looking up directory keys by their values . This isn t robust to repeated values
60
18
246,986
def find_subscript_name ( subscript_dict , element ) : if element in subscript_dict . keys ( ) : return element for name , elements in subscript_dict . items ( ) : if element in elements : return name
Given a subscript dictionary and a member of a subscript family return the first key of which the member is within the value list . If element is already a subscript name return that
48
34
246,987
def make_coord_dict ( subs , subscript_dict , terse = True ) : sub_elems_list = [ y for x in subscript_dict . values ( ) for y in x ] coordinates = { } for sub in subs : if sub in sub_elems_list : name = find_subscript_name ( subscript_dict , sub ) coordinates [ name ] = [ sub ] elif not terse : coordinates [ sub ] = s...
This is for assisting with the lookup of a particular element such that the output of this function would take the place of %s in this expression
104
28
246,988
def make_python_identifier ( string , namespace = None , reserved_words = None , convert = 'drop' , handle = 'force' ) : if namespace is None : namespace = dict ( ) if reserved_words is None : reserved_words = list ( ) if string in namespace : return namespace [ string ] , namespace # create a working copy (and make it...
Takes an arbitrary string and creates a valid Python identifier .
504
12
246,989
def make_flat_df ( frames , return_addresses ) : # Todo: could also try a list comprehension here, or parallel apply visited = list ( map ( lambda x : visit_addresses ( x , return_addresses ) , frames ) ) return pd . DataFrame ( visited )
Takes a list of dictionaries each representing what is returned from the model at a particular time and creates a dataframe whose columns correspond to the keys of return addresses
64
33
246,990
def visit_addresses ( frame , return_addresses ) : outdict = dict ( ) for real_name , ( pyname , address ) in return_addresses . items ( ) : if address : xrval = frame [ pyname ] . loc [ address ] if xrval . size > 1 : outdict [ real_name ] = xrval else : outdict [ real_name ] = float ( np . squeeze ( xrval . values ) ...
Visits all of the addresses returns a new dict which contains just the addressed elements
122
16
246,991
def validate_request ( request ) : if getattr ( settings , 'BASICAUTH_DISABLE' , False ) : # Not to use this env return True if 'HTTP_AUTHORIZATION' not in request . META : return False authorization_header = request . META [ 'HTTP_AUTHORIZATION' ] ret = extract_basicauth ( authorization_header ) if not ret : return Fa...
Check an incoming request .
200
5
246,992
def _find_address_range ( addresses ) : first = last = addresses [ 0 ] last_index = 0 for ip in addresses [ 1 : ] : if ip . _ip == last . _ip + 1 : last = ip last_index += 1 else : break return ( first , last , last_index )
Find a sequence of addresses .
67
6
246,993
def _prefix_from_prefix_int ( self , prefixlen ) : if not isinstance ( prefixlen , ( int , long ) ) : raise NetmaskValueError ( '%r is not an integer' % prefixlen ) prefixlen = int ( prefixlen ) if not ( 0 <= prefixlen <= self . _max_prefixlen ) : raise NetmaskValueError ( '%d is not a valid prefix length' % prefixlen ...
Validate and return a prefix length integer .
97
9
246,994
def output_colored ( code , text , is_bold = False ) : if is_bold : code = '1;%s' % code return '\033[%sm%s\033[0m' % ( code , text )
Create function to output with color sequence
52
7
246,995
def _set_asset_paths ( self , app ) : webpack_stats = app . config [ 'WEBPACK_MANIFEST_PATH' ] try : with app . open_resource ( webpack_stats , 'r' ) as stats_json : stats = json . load ( stats_json ) if app . config [ 'WEBPACK_ASSETS_URL' ] : self . assets_url = app . config [ 'WEBPACK_ASSETS_URL' ] else : self . asse...
Read in the manifest json file which acts as a manifest for assets . This allows us to get the asset path as well as hashed names .
174
29
246,996
def javascript_tag ( self , * args ) : tags = [ ] for arg in args : asset_path = self . asset_url_for ( '{0}.js' . format ( arg ) ) if asset_path : tags . append ( '<script src="{0}"></script>' . format ( asset_path ) ) return '\n' . join ( tags )
Convenience tag to output 1 or more javascript tags .
83
12
246,997
def asset_url_for ( self , asset ) : if '//' in asset : return asset if asset not in self . assets : return None return '{0}{1}' . format ( self . assets_url , self . assets [ asset ] )
Lookup the hashed asset path of a file name unless it starts with something that resembles a web address then take it as is .
55
27
246,998
def pre_change_receiver ( self , instance : Model , action : Action ) : if action == Action . CREATE : group_names = set ( ) else : group_names = set ( self . group_names ( instance ) ) # use a thread local dict to be safe... if not hasattr ( instance , '__instance_groups' ) : instance . __instance_groups = threading ....
Entry point for triggering the old_binding from save signals .
145
12
246,999
def post_change_receiver ( self , instance : Model , action : Action , * * kwargs ) : try : old_group_names = instance . __instance_groups . observers [ self ] except ( ValueError , KeyError ) : old_group_names = set ( ) if action == Action . DELETE : new_group_names = set ( ) else : new_group_names = set ( self . grou...
Triggers the old_binding to possibly send to its group .
245
14