idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
17,300
def post ( self , url , params = { } , files = [ ] ) : url = self . host + url try : if files : return self . post_multipart ( url , params , files ) else : data = urllib . parse . urlencode ( params ) if not PY3 : data = str ( data ) resp = requests . post ( url , data = data , headers = self . headers , auth = self ....
Issues a POST request against the API allows for multipart data uploads
17,301
def json_parse ( self , response ) : try : data = response . json ( ) except ValueError : data = { 'meta' : { 'status' : 500 , 'msg' : 'Server Error' } , 'response' : { "error" : "Malformed JSON or HTML was returned." } } if 200 <= data [ 'meta' ] [ 'status' ] <= 399 : return data [ 'response' ] else : return data
Wraps and abstracts response validation and JSON parsing to make sure the user gets the correct response .
17,302
def post_multipart ( self , url , params , files ) : resp = requests . post ( url , data = params , params = params , files = files , headers = self . headers , allow_redirects = False , auth = self . oauth ) return self . json_parse ( resp )
Generates and issues a multipart request for data files
17,303
def avatar ( self , blogname , size = 64 ) : url = "/v2/blog/{}/avatar/{}" . format ( blogname , size ) return self . send_api_request ( "get" , url )
Retrieves the url of the blog s avatar
17,304
def tagged ( self , tag , ** kwargs ) : kwargs . update ( { 'tag' : tag } ) return self . send_api_request ( "get" , '/v2/tagged' , kwargs , [ 'before' , 'limit' , 'filter' , 'tag' , 'api_key' ] , True )
Gets a list of posts tagged with the given tag
17,305
def posts ( self , blogname , type = None , ** kwargs ) : if type is None : url = '/v2/blog/{}/posts' . format ( blogname ) else : url = '/v2/blog/{}/posts/{}' . format ( blogname , type ) return self . send_api_request ( "get" , url , kwargs , [ 'id' , 'tag' , 'limit' , 'offset' , 'before' , 'reblog_info' , 'notes_inf...
Gets a list of posts from a particular blog
17,306
def blog_info ( self , blogname ) : url = "/v2/blog/{}/info" . format ( blogname ) return self . send_api_request ( "get" , url , { } , [ 'api_key' ] , True )
Gets the information of the given blog
17,307
def blog_following ( self , blogname , ** kwargs ) : url = "/v2/blog/{}/following" . format ( blogname ) return self . send_api_request ( "get" , url , kwargs , [ 'limit' , 'offset' ] )
Gets the publicly exposed list of blogs that a blog follows
17,308
def like ( self , id , reblog_key ) : url = "/v2/user/like" params = { 'id' : id , 'reblog_key' : reblog_key } return self . send_api_request ( "post" , url , params , [ 'id' , 'reblog_key' ] )
Like the post of the given blog
17,309
def unlike ( self , id , reblog_key ) : url = "/v2/user/unlike" params = { 'id' : id , 'reblog_key' : reblog_key } return self . send_api_request ( "post" , url , params , [ 'id' , 'reblog_key' ] )
Unlike the post of the given blog
17,310
def create_photo ( self , blogname , ** kwargs ) : kwargs . update ( { "type" : "photo" } ) return self . _send_post ( blogname , kwargs )
Create a photo post or photoset on a blog
17,311
def create_text ( self , blogname , ** kwargs ) : kwargs . update ( { "type" : "text" } ) return self . _send_post ( blogname , kwargs )
Create a text post on a blog
17,312
def create_quote ( self , blogname , ** kwargs ) : kwargs . update ( { "type" : "quote" } ) return self . _send_post ( blogname , kwargs )
Create a quote post on a blog
17,313
def create_link ( self , blogname , ** kwargs ) : kwargs . update ( { "type" : "link" } ) return self . _send_post ( blogname , kwargs )
Create a link post on a blog
17,314
def create_chat ( self , blogname , ** kwargs ) : kwargs . update ( { "type" : "chat" } ) return self . _send_post ( blogname , kwargs )
Create a chat post on a blog
17,315
def reblog ( self , blogname , ** kwargs ) : url = "/v2/blog/{}/post/reblog" . format ( blogname ) valid_options = [ 'id' , 'reblog_key' , 'comment' ] + self . _post_valid_options ( kwargs . get ( 'type' , None ) ) if 'tags' in kwargs and kwargs [ 'tags' ] : kwargs [ 'tags' ] = "," . join ( kwargs [ 'tags' ] ) return s...
Creates a reblog on the given blogname
17,316
def delete_post ( self , blogname , id ) : url = "/v2/blog/{}/post/delete" . format ( blogname ) return self . send_api_request ( 'post' , url , { 'id' : id } , [ 'id' ] )
Deletes a post with the given id
17,317
def _send_post ( self , blogname , params ) : url = "/v2/blog/{}/post" . format ( blogname ) valid_options = self . _post_valid_options ( params . get ( 'type' , None ) ) if len ( params . get ( "tags" , [ ] ) ) > 0 : params [ 'tags' ] = "," . join ( params [ 'tags' ] ) return self . send_api_request ( "post" , url , p...
Formats parameters and sends the API request off . Validates common and per - post - type parameters and formats your tags for you .
17,318
def send_api_request ( self , method , url , params = { } , valid_parameters = [ ] , needs_api_key = False ) : if needs_api_key : params . update ( { 'api_key' : self . request . consumer_key } ) valid_parameters . append ( 'api_key' ) files = { } if 'data' in params : if isinstance ( params [ 'data' ] , list ) : for i...
Sends the url with parameters to the requested url validating them to make sure that they are what we expect to have passed to us
17,319
def run ( path , code = None , params = None , ** meta ) : tree = compile ( code , path , "exec" , ast . PyCF_ONLY_AST ) McCabeChecker . max_complexity = int ( params . get ( 'complexity' , 10 ) ) return [ { 'lnum' : lineno , 'offset' : offset , 'text' : text , 'type' : McCabeChecker . _code } for lineno , offset , tex...
MCCabe code checking .
17,320
def split_csp_str ( val ) : seen = set ( ) values = val if isinstance ( val , ( list , tuple ) ) else val . strip ( ) . split ( ',' ) return [ x for x in values if x and not ( x in seen or seen . add ( x ) ) ]
Split comma separated string into unique values keeping their order .
17,321
def parse_linters ( linters ) : result = list ( ) for name in split_csp_str ( linters ) : linter = LINTERS . get ( name ) if linter : result . append ( ( name , linter ) ) else : logging . warning ( "Linter `%s` not found." , name ) return result
Initialize choosen linters .
17,322
def get_default_config_file ( rootdir = None ) : if rootdir is None : return DEFAULT_CONFIG_FILE for path in CONFIG_FILES : path = os . path . join ( rootdir , path ) if os . path . isfile ( path ) and os . access ( path , os . R_OK ) : return path
Search for configuration file .
17,323
def parse_options ( args = None , config = True , rootdir = CURDIR , ** overrides ) : args = args or [ ] options = PARSER . parse_args ( args ) options . file_params = dict ( ) options . linters_params = dict ( ) if config : cfg = get_config ( str ( options . options ) , rootdir = rootdir ) for opt , val in cfg . defau...
Parse options from command line and configuration files .
17,324
def _override_options ( options , ** overrides ) : for opt , val in overrides . items ( ) : passed_value = getattr ( options , opt , _Default ( ) ) if opt in ( 'ignore' , 'select' ) and passed_value : value = process_value ( opt , passed_value . value ) value += process_value ( opt , val ) setattr ( options , opt , val...
Override options .
17,325
def process_value ( name , value ) : action = ACTIONS . get ( name ) if not action : return value if callable ( action . type ) : return action . type ( value ) if action . const : return bool ( int ( value ) ) return value
Compile option value .
17,326
def get_config ( ini_path = None , rootdir = None ) : config = Namespace ( ) config . default_section = 'pylama' if not ini_path : path = get_default_config_file ( rootdir ) if path : config . read ( path ) else : config . read ( ini_path ) return config
Load configuration from INI .
17,327
def setup_logger ( options ) : LOGGER . setLevel ( logging . INFO if options . verbose else logging . WARN ) if options . report : LOGGER . removeHandler ( STREAM ) LOGGER . addHandler ( logging . FileHandler ( options . report , mode = 'w' ) ) if options . options : LOGGER . info ( 'Try to read configuration from: %r'...
Do the logger setup with options .
17,328
def run ( path , code = None , params = None , ** meta ) : import _ast builtins = params . get ( "builtins" , "" ) if builtins : builtins = builtins . split ( "," ) tree = compile ( code , path , "exec" , _ast . PyCF_ONLY_AST ) w = checker . Checker ( tree , path , builtins = builtins ) w . messages = sorted ( w . mess...
Check code with pyflakes .
17,329
def check_path ( options , rootdir = None , candidates = None , code = None ) : if not candidates : candidates = [ ] for path_ in options . paths : path = op . abspath ( path_ ) if op . isdir ( path ) : for root , _ , files in walk ( path ) : candidates += [ op . relpath ( op . join ( root , f ) , CURDIR ) for f in fil...
Check path .
17,330
def shell ( args = None , error = True ) : if args is None : args = sys . argv [ 1 : ] options = parse_options ( args ) setup_logger ( options ) LOGGER . info ( options ) if options . hook : from . hook import install_hook for path in options . paths : return install_hook ( path ) return process_paths ( options , error...
Endpoint for console .
17,331
def process_paths ( options , candidates = None , error = True ) : errors = check_path ( options , rootdir = CURDIR , candidates = candidates ) if options . format in [ 'pycodestyle' , 'pep8' ] : pattern = "%(filename)s:%(lnum)s:%(col)s: %(text)s" elif options . format == 'pylint' : pattern = "%(filename)s:%(lnum)s: [%...
Process files and log errors .
17,332
def reset ( self , source ) : self . tokens = [ ] self . source = source self . pos = 0
Reset scanner s state .
17,333
def scan ( self ) : self . pre_scan ( ) token = None end = len ( self . source ) while self . pos < end : best_pat = None best_pat_len = 0 for p , regexp in self . patterns : m = regexp . match ( self . source , self . pos ) if m : best_pat = p best_pat_len = len ( m . group ( 0 ) ) break if best_pat is None : raise Sy...
Scan source and grab tokens .
17,334
def pre_scan ( self ) : escape_re = re . compile ( r'\\\n[\t ]+' ) self . source = escape_re . sub ( '' , self . source )
Prepare string for scanning .
17,335
def iteritems ( self , raw = False ) : for key in self : yield key , self . __getitem__ ( key , raw = raw )
Iterate self items .
17,336
def read ( self , * files , ** params ) : for f in files : try : with io . open ( f , encoding = 'utf-8' ) as ff : NS_LOGGER . info ( 'Read from `{0}`' . format ( ff . name ) ) self . parse ( ff . read ( ) , ** params ) except ( IOError , TypeError , SyntaxError , io . UnsupportedOperation ) : if not self . silent_read...
Read and parse INI files .
17,337
def write ( self , f ) : if isinstance ( f , str ) : f = io . open ( f , 'w' , encoding = 'utf-8' ) if not hasattr ( f , 'read' ) : raise AttributeError ( "Wrong type of file: {0}" . format ( type ( f ) ) ) NS_LOGGER . info ( 'Write to `{0}`' . format ( f . name ) ) for section in self . sections . keys ( ) : f . write...
Write namespace as INI file .
17,338
def parse ( self , source , update = True , ** params ) : scanner = INIScanner ( source ) scanner . scan ( ) section = self . default_section name = None for token in scanner . tokens : if token [ 0 ] == 'KEY_VALUE' : name , value = re . split ( '[=:]' , token [ 1 ] , 1 ) name , value = name . strip ( ) , value . strip...
Parse INI source as string .
17,339
def parse_modeline ( code ) : seek = MODELINE_RE . search ( code ) if seek : return dict ( v . split ( '=' ) for v in seek . group ( 1 ) . split ( ':' ) ) return dict ( )
Parse params from file s modeline .
17,340
def prepare_params ( modeline , fileconfig , options ) : params = dict ( skip = False , ignore = [ ] , select = [ ] , linters = [ ] ) if options : params [ 'ignore' ] = list ( options . ignore ) params [ 'select' ] = list ( options . select ) for config in filter ( None , [ modeline , fileconfig ] ) : for key in ( 'ign...
Prepare and merge a params from modelines and configs .
17,341
def filter_errors ( errors , select = None , ignore = None , ** params ) : select = select or [ ] ignore = ignore or [ ] for e in errors : for s in select : if e . number . startswith ( s ) : yield e break else : for s in ignore : if e . number . startswith ( s ) : break else : yield e
Filter errors by select and ignore options .
17,342
def filter_skiplines ( code , errors ) : if not errors : return errors enums = set ( er . lnum for er in errors ) removed = set ( [ num for num , l in enumerate ( code . split ( '\n' ) , 1 ) if num in enums and SKIP_PATTERN ( l ) ] ) if removed : errors = [ er for er in errors if er . lnum not in removed ] return error...
Filter lines by noqa .
17,343
def check_async ( paths , options , rootdir = None ) : LOGGER . info ( 'Async code checking is enabled.' ) path_queue = Queue . Queue ( ) result_queue = Queue . Queue ( ) for num in range ( CPU_COUNT ) : worker = Worker ( path_queue , result_queue ) worker . setDaemon ( True ) LOGGER . info ( 'Start worker #%s' , ( num...
Check given paths asynchronously .
17,344
def run ( self ) : while True : path , params = self . path_queue . get ( ) errors = run ( path , ** params ) self . result_queue . put ( errors ) self . path_queue . task_done ( )
Run tasks from queue .
17,345
def _parse ( self , line ) : try : result = line . split ( ':' , maxsplit = 4 ) filename , line_num_txt , column_txt , message_type , text = result except ValueError : return try : self . line_num = int ( line_num_txt . strip ( ) ) self . column = int ( column_txt . strip ( ) ) except ValueError : return self . filenam...
Parse the output line
17,346
def to_result ( self ) : text = [ self . text ] if self . note : text . append ( self . note ) return { 'lnum' : self . line_num , 'col' : self . column , 'text' : ' - ' . join ( text ) , 'type' : self . types . get ( self . message_type , '' ) }
Convert to the Linter . run return value
17,347
def run ( path , code = None , params = None , ** meta ) : args = [ path , '--follow-imports=skip' , '--show-column-numbers' ] stdout , stderr , status = api . run ( args ) messages = [ ] for line in stdout . split ( '\n' ) : line . strip ( ) if not line : continue message = _MyPyMessage ( line ) if message . valid : i...
Check code with mypy .
17,348
def prepare_value ( value ) : if isinstance ( value , ( list , tuple , set ) ) : return "," . join ( value ) if isinstance ( value , bool ) : return "y" if value else "n" return str ( value )
Prepare value to pylint .
17,349
def run ( path , code = None , params = None , ** meta ) : parser = get_parser ( ) for option in parser . option_list : if option . dest and option . dest in params : value = params [ option . dest ] if isinstance ( value , str ) : params [ option . dest ] = option . convert_value ( option , value ) for key in [ "filen...
Check code with pycodestyle .
17,350
def init_file ( self , filename , lines , expected , line_offset ) : super ( _PycodestyleReport , self ) . init_file ( filename , lines , expected , line_offset ) self . errors = [ ]
Prepare storage for errors .
17,351
def error ( self , line_number , offset , text , check ) : code = super ( _PycodestyleReport , self ) . error ( line_number , offset , text , check ) if code : self . errors . append ( dict ( text = text , type = code . replace ( 'E' , 'C' ) , col = offset + 1 , lnum = line_number , ) )
Save errors .
17,352
def run ( path , code = None , params = None , ** meta ) : if 'ignore_decorators' in params : ignore_decorators = params [ 'ignore_decorators' ] else : ignore_decorators = None check_source_args = ( code , path , ignore_decorators ) if THIRD_ARG else ( code , path ) return [ { 'lnum' : e . line , 'text' : ( e . message...
pydocstyle code checking .
17,353
def run ( path , code = None , params = None , ignore = None , select = None , ** meta ) : complexity = params . get ( 'complexity' , 10 ) no_assert = params . get ( 'no_assert' , False ) show_closures = params . get ( 'show_closures' , False ) visitor = ComplexityVisitor . from_code ( code , no_assert = no_assert ) bl...
Check code with Radon .
17,354
def git_hook ( error = True ) : _ , files_modified , _ = run ( "git diff-index --cached --name-only HEAD" ) options = parse_options ( ) setup_logger ( options ) if sys . version_info >= ( 3 , ) : candidates = [ f . decode ( 'utf-8' ) for f in files_modified ] else : candidates = [ str ( f ) for f in files_modified ] if...
Run pylama after git commit .
17,355
def hg_hook ( ui , repo , node = None , ** kwargs ) : seen = set ( ) paths = [ ] if len ( repo ) : for rev in range ( repo [ node ] , len ( repo ) ) : for file_ in repo [ rev ] . files ( ) : file_ = op . join ( repo . root , file_ ) if file_ in seen or not op . exists ( file_ ) : continue seen . add ( file_ ) paths . a...
Run pylama after mercurial commit .
17,356
def install_git ( path ) : hook = op . join ( path , 'pre-commit' ) with open ( hook , 'w' ) as fd : fd . write ( ) chmod ( hook , 484 )
Install hook in Git repository .
17,357
def install_hg ( path ) : hook = op . join ( path , 'hgrc' ) if not op . isfile ( hook ) : open ( hook , 'w+' ) . close ( ) c = ConfigParser ( ) c . readfp ( open ( hook , 'r' ) ) if not c . has_section ( 'hooks' ) : c . add_section ( 'hooks' ) if not c . has_option ( 'hooks' , 'commit' ) : c . set ( 'hooks' , 'commit'...
Install hook in Mercurial repository .
17,358
def install_hook ( path ) : git = op . join ( path , '.git' , 'hooks' ) hg = op . join ( path , '.hg' ) if op . exists ( git ) : install_git ( git ) LOGGER . warn ( 'Git hook has been installed.' ) elif op . exists ( hg ) : install_hg ( hg ) LOGGER . warn ( 'Mercurial hook has been installed.' ) else : LOGGER . error (...
Auto definition of SCM and hook installation .
17,359
def run ( path , code = None , params = None , ** meta ) : code = converter ( code ) line_numbers = commented_out_code_line_numbers ( code ) lines = code . split ( '\n' ) result = [ ] for line_number in line_numbers : line = lines [ line_number - 1 ] result . append ( dict ( lnum = line_number , offset = len ( line ) -...
Eradicate code checking .
17,360
def remove_duplicates ( errors ) : passed = defaultdict ( list ) for error in errors : key = error . linter , error . number if key in DUPLICATES : if key in passed [ error . lnum ] : continue passed [ error . lnum ] = DUPLICATES [ key ] yield error
Filter duplicates from given error s list .
17,361
def fork ( self , strictindex , new_value ) : forked_chunk = YAMLChunk ( deepcopy ( self . _ruamelparsed ) , pointer = self . pointer , label = self . label , key_association = copy ( self . _key_association ) , ) forked_chunk . contents [ self . ruamelindex ( strictindex ) ] = new_value . as_marked_up ( ) forked_chunk...
Return a chunk referring to the same location in a duplicated document .
17,362
def make_child_of ( self , chunk ) : if self . is_mapping ( ) : for key , value in self . contents . items ( ) : self . key ( key , key ) . pointer . make_child_of ( chunk . pointer ) self . val ( key ) . make_child_of ( chunk ) elif self . is_sequence ( ) : for index , item in enumerate ( self . contents ) : self . in...
Link one YAML chunk to another .
17,363
def _select ( self , pointer ) : return YAMLChunk ( self . _ruamelparsed , pointer = pointer , label = self . _label , strictparsed = self . _strictparsed , key_association = copy ( self . _key_association ) , )
Get a YAMLChunk referenced by a pointer .
17,364
def index ( self , strictindex ) : return self . _select ( self . _pointer . index ( self . ruamelindex ( strictindex ) ) )
Return a chunk in a sequence referenced by index .
17,365
def ruamelindex ( self , strictindex ) : return ( self . key_association . get ( strictindex , strictindex ) if self . is_mapping ( ) else strictindex )
Get the ruamel equivalent of a strict parsed index .
17,366
def val ( self , strictkey ) : ruamelkey = self . ruamelindex ( strictkey ) return self . _select ( self . _pointer . val ( ruamelkey , strictkey ) )
Return a chunk referencing a value in a mapping with the key key .
17,367
def key ( self , key , strictkey = None ) : return self . _select ( self . _pointer . key ( key , strictkey ) )
Return a chunk referencing a key in a mapping with the name key .
17,368
def textslice ( self , start , end ) : return self . _select ( self . _pointer . textslice ( start , end ) )
Return a chunk referencing a slice of a scalar text value .
17,369
def flatten ( items ) : for x in items : if isinstance ( x , Iterable ) and not isinstance ( x , ( str , bytes ) ) : for sub_x in flatten ( x ) : yield sub_x else : yield x
Yield items from any nested iterable .
17,370
def comma_separated_positions ( text ) : chunks = [ ] start = 0 end = 0 for item in text . split ( "," ) : space_increment = 1 if item [ 0 ] == " " else 0 start += space_increment end += len ( item . lstrip ( ) ) + space_increment chunks . append ( ( start , end ) ) start += len ( item . lstrip ( ) ) + 1 end = start re...
Start and end positions of comma separated text items .
17,371
def ruamel_structure ( data , validator = None ) : if isinstance ( data , dict ) : if len ( data ) == 0 : raise exceptions . CannotBuildDocumentsFromEmptyDictOrList ( "Document must be built with non-empty dicts and lists" ) return CommentedMap ( [ ( ruamel_structure ( key ) , ruamel_structure ( value ) ) for key , val...
Take dicts and lists and return a ruamel . yaml style structure of CommentedMaps CommentedSeqs and data .
17,372
def rbdd ( * keywords ) : settings = _personal_settings ( ) . data settings [ "engine" ] [ "rewrite" ] = True _storybook ( settings [ "engine" ] ) . with_params ( ** { "python version" : settings [ "params" ] [ "python version" ] } ) . only_uninherited ( ) . shortcut ( * keywords ) . play ( )
Run story matching keywords and rewrite story if code changed .
17,373
def rerun ( version = "3.7.0" ) : from commandlib import Command Command ( DIR . gen . joinpath ( "py{0}" . format ( version ) , "bin" , "python" ) ) ( DIR . gen . joinpath ( "state" , "examplepythoncode.py" ) ) . in_dir ( DIR . gen . joinpath ( "state" ) ) . run ( )
Rerun last example code block with specified version of python .
17,374
def data ( self ) : if isinstance ( self . _value , CommentedMap ) : mapping = OrderedDict ( ) for key , value in self . _value . items ( ) : mapping [ key . data ] = value . data return mapping elif isinstance ( self . _value , CommentedSeq ) : return [ item . data for item in self . _value ] else : return self . _val...
Returns raw data representation of the document or document segment .
17,375
def as_yaml ( self ) : dumped = dump ( self . as_marked_up ( ) , Dumper = StrictYAMLDumper , allow_unicode = True ) return dumped if sys . version_info [ 0 ] == 3 else dumped . decode ( "utf8" )
Render the YAML node and subnodes as string .
17,376
def text ( self ) : if isinstance ( self . _value , CommentedMap ) : raise TypeError ( "{0} is a mapping, has no text value." . format ( repr ( self ) ) ) if isinstance ( self . _value , CommentedSeq ) : raise TypeError ( "{0} is a sequence, has no text value." . format ( repr ( self ) ) ) return self . _text
Return string value of scalar whatever value it was parsed as .
17,377
def partition_source ( src ) : ast_obj = ast . parse ( src . encode ( 'UTF-8' ) ) visitor = TopLevelImportVisitor ( ) visitor . visit ( ast_obj ) line_offsets = get_line_offsets_by_line_no ( src ) chunks = [ ] startpos = 0 pending_chunk_type = None possible_ending_tokens = None seen_import = False for ( token_type , to...
Partitions source into a list of CodePartition s for import refactoring .
17,378
def separate_comma_imports ( partitions ) : def _inner ( ) : for partition in partitions : if partition . code_type is CodeType . IMPORT : import_obj = import_obj_from_str ( partition . src ) if import_obj . has_multiple_imports : for new_import_obj in import_obj . split_imports ( ) : yield CodePartition ( CodeType . I...
Turns import a b into import a and import b
17,379
def _module_to_base_modules ( s ) : parts = s . split ( '.' ) for i in range ( 1 , len ( parts ) ) : yield '.' . join ( parts [ : i ] )
return all module names that would be imported due to this import - import
17,380
def apply_thresholds ( input , thresholds , choices ) : condlist = [ input <= threshold for threshold in thresholds ] if len ( condlist ) == len ( choices ) - 1 : condlist += [ True ] assert len ( condlist ) == len ( choices ) , "apply_thresholds must be called with the same number of thresholds than choices, or one mo...
Return one of the choices depending on the input position compared to thresholds for each input .
17,381
def update ( self , period = None , start = None , stop = None , value = None ) : if period is not None : if start is not None or stop is not None : raise TypeError ( "Wrong input for 'update' method: use either 'update(period, value = value)' or 'update(start = start, stop = stop, value = value)'. You cannot both use ...
Change the value for a given period .
17,382
def merge ( self , other ) : for child_name , child in other . children . items ( ) : self . add_child ( child_name , child )
Merges another ParameterNode into the current node .
17,383
def add_child ( self , name , child ) : if name in self . children : raise ValueError ( "{} has already a child named {}" . format ( self . name , name ) ) if not ( isinstance ( child , ParameterNode ) or isinstance ( child , Parameter ) or isinstance ( child , Scale ) ) : raise TypeError ( "child must be of type Param...
Add a new child to the node .
17,384
def replace_variable ( self , variable ) : name = variable . __name__ if self . variables . get ( name ) is not None : del self . variables [ name ] self . load_variable ( variable , update = False )
Replaces an existing OpenFisca variable in the tax and benefit system by a new one .
17,385
def add_variables_from_file ( self , file_path ) : try : file_name = path . splitext ( path . basename ( file_path ) ) [ 0 ] module_name = '{}_{}_{}' . format ( id ( self ) , hash ( path . abspath ( file_path ) ) , file_name ) module_directory = path . dirname ( file_path ) try : module = load_module ( module_name , * ...
Adds all OpenFisca variables contained in a given file to the tax and benefit system .
17,386
def add_variables_from_directory ( self , directory ) : py_files = glob . glob ( path . join ( directory , "*.py" ) ) for py_file in py_files : self . add_variables_from_file ( py_file ) subdirectories = glob . glob ( path . join ( directory , "*/" ) ) for subdirectory in subdirectories : self . add_variables_from_dire...
Recursively explores a directory and adds all OpenFisca variables found there to the tax and benefit system .
17,387
def load_extension ( self , extension ) : try : package = importlib . import_module ( extension ) extension_directory = package . __path__ [ 0 ] except ImportError : message = linesep . join ( [ traceback . format_exc ( ) , 'Error loading extension: `{}` is neither a directory, nor a package.' . format ( extension ) , ...
Loads an extension to the tax and benefit system .
17,388
def apply_reform ( self , reform_path ) : from openfisca_core . reforms import Reform try : reform_package , reform_name = reform_path . rsplit ( '.' , 1 ) except ValueError : raise ValueError ( '`{}` does not seem to be a path pointing to a reform. A path looks like `some_country_package.reforms.some_reform.`' . forma...
Generates a new tax and benefit system applying a reform to the tax and benefit system .
17,389
def get_variable ( self , variable_name , check_existence = False ) : variables = self . variables found = variables . get ( variable_name ) if not found and check_existence : raise VariableNotFound ( variable_name , self ) return found
Get a variable from the tax and benefit system .
17,390
def neutralize_variable ( self , variable_name ) : self . variables [ variable_name ] = get_neutralized_variable ( self . get_variable ( variable_name ) )
Neutralizes an OpenFisca variable existing in the tax and benefit system .
17,391
def load_parameters ( self , path_to_yaml_dir ) : parameters = ParameterNode ( '' , directory_path = path_to_yaml_dir ) if self . preprocess_parameters is not None : parameters = self . preprocess_parameters ( parameters ) self . parameters = parameters
Loads the legislation parameter for a directory containing YAML parameters files .
17,392
def get_parameters_at_instant ( self , instant ) : if isinstance ( instant , periods . Period ) : instant = instant . start elif isinstance ( instant , ( str , int ) ) : instant = periods . instant ( instant ) else : assert isinstance ( instant , periods . Instant ) , "Expected an Instant (e.g. Instant((2017, 1, 1)) )....
Get the parameters of the legislation at a given instant
17,393
def get_package_metadata ( self ) : if self . baseline : return self . baseline . get_package_metadata ( ) fallback_metadata = { 'name' : self . __class__ . __name__ , 'version' : '' , 'repository_url' : '' , 'location' : '' , } module = inspect . getmodule ( self ) if not module . __package__ : return fallback_metadat...
Gets metatada relative to the country package the tax and benefit system is built from .
17,394
def get_variables ( self , entity = None ) : if not entity : return self . variables else : return { variable_name : variable for variable_name , variable in self . variables . items ( ) if variable . entity . key == entity . key }
Gets all variables contained in a tax and benefit system .
17,395
def build_from_dict ( self , tax_benefit_system , input_dict ) : input_dict = self . explicit_singular_entities ( tax_benefit_system , input_dict ) if any ( key in tax_benefit_system . entities_plural ( ) for key in input_dict . keys ( ) ) : return self . build_from_entities ( tax_benefit_system , input_dict ) else : r...
Build a simulation from input_dict
17,396
def build_from_entities ( self , tax_benefit_system , input_dict ) : input_dict = deepcopy ( input_dict ) simulation = Simulation ( tax_benefit_system , tax_benefit_system . instantiate_entities ( ) ) for ( variable_name , _variable ) in tax_benefit_system . variables . items ( ) : self . register_variable ( variable_n...
Build a simulation from a Python dict input_dict fully specifying entities .
17,397
def build_from_variables ( self , tax_benefit_system , input_dict ) : count = _get_person_count ( input_dict ) simulation = self . build_default_simulation ( tax_benefit_system , count ) for variable , value in input_dict . items ( ) : if not isinstance ( value , dict ) : if self . default_period is None : raise Situat...
Build a simulation from a Python dict input_dict describing variables values without expliciting entities .
17,398
def explicit_singular_entities ( self , tax_benefit_system , input_dict ) : singular_keys = set ( input_dict ) . intersection ( tax_benefit_system . entities_by_singular ( ) ) if not singular_keys : return input_dict result = { entity_id : entity_description for ( entity_id , entity_description ) in input_dict . items ...
Preprocess input_dict to explicit entities defined using the single - entity shortcut
17,399
def add_person_entity ( self , entity , instances_json ) : check_type ( instances_json , dict , [ entity . plural ] ) entity_ids = list ( map ( str , instances_json . keys ( ) ) ) self . persons_plural = entity . plural self . entity_ids [ self . persons_plural ] = entity_ids self . entity_counts [ self . persons_plura...
Add the simulation s instances of the persons entity as described in instances_json .