idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
23,300
def acquire ( self ) : while self . size ( ) == 0 or self . size ( ) < self . _minsize : _conn = yield from self . _create_new_conn ( ) if _conn is None : break self . _pool . put_nowait ( _conn ) conn = None while not conn : _conn = yield from self . _pool . get ( ) if _conn . reader . at_eof ( ) or _conn . reader . e...
Acquire connection from the pool or spawn new one if pool maxsize permits .
23,301
def release ( self , conn ) : self . _in_use . remove ( conn ) if conn . reader . at_eof ( ) or conn . reader . exception ( ) : self . _do_close ( conn ) else : self . _pool . put_nowait ( conn )
Releases connection back to the pool .
23,302
def get ( self , conn , key , default = None ) : values , _ = yield from self . _multi_get ( conn , key ) return values . get ( key , default )
Gets a single value from the server .
23,303
def gets ( self , conn , key , default = None ) : values , cas_tokens = yield from self . _multi_get ( conn , key , with_cas = True ) return values . get ( key , default ) , cas_tokens . get ( key )
Gets a single value from the server together with the cas token .
23,304
def multi_get ( self , conn , * keys ) : values , _ = yield from self . _multi_get ( conn , * keys ) return tuple ( values . get ( key ) for key in keys )
Takes a list of keys and returns a list of values .
23,305
def stats ( self , conn , args = None ) : if args is None : args = b'' conn . writer . write ( b'' . join ( ( b'stats ' , args , b'\r\n' ) ) ) result = { } resp = yield from conn . reader . readline ( ) while resp != b'END\r\n' : terms = resp . split ( ) if len ( terms ) == 2 and terms [ 0 ] == b'STAT' : result [ terms...
Runs a stats command on the server .
23,306
def append ( self , conn , key , value , exptime = 0 ) : flags = 0 return ( yield from self . _storage_command ( conn , b'append' , key , value , flags , exptime ) )
Add data to an existing key after existing data
23,307
def prepend ( self , conn , key , value , exptime = 0 ) : flags = 0 return ( yield from self . _storage_command ( conn , b'prepend' , key , value , flags , exptime ) )
Add data to an existing key before existing data
23,308
def incr ( self , conn , key , increment = 1 ) : assert self . _validate_key ( key ) resp = yield from self . _incr_decr ( conn , b'incr' , key , increment ) return resp
Command is used to change data for some item in - place incrementing it . The data for the item is treated as decimal representation of a 64 - bit unsigned integer .
23,309
def decr ( self , conn , key , decrement = 1 ) : assert self . _validate_key ( key ) resp = yield from self . _incr_decr ( conn , b'decr' , key , decrement ) return resp
Command is used to change data for some item in - place decrementing it . The data for the item is treated as decimal representation of a 64 - bit unsigned integer .
23,310
def touch ( self , conn , key , exptime ) : assert self . _validate_key ( key ) _cmd = b' ' . join ( [ b'touch' , key , str ( exptime ) . encode ( 'utf-8' ) ] ) cmd = _cmd + b'\r\n' resp = yield from self . _execute_simple_command ( conn , cmd ) if resp not in ( const . TOUCHED , const . NOT_FOUND ) : raise ClientExcep...
The command is used to update the expiration time of an existing item without fetching it .
23,311
def version ( self , conn ) : command = b'version\r\n' response = yield from self . _execute_simple_command ( conn , command ) if not response . startswith ( const . VERSION ) : raise ClientException ( 'Memcached version failed' , response ) version , number = response . split ( ) return number
Current version of the server .
23,312
def flush_all ( self , conn ) : command = b'flush_all\r\n' response = yield from self . _execute_simple_command ( conn , command ) if const . OK != response : raise ClientException ( 'Memcached flush_all failed' , response )
Its effect is to invalidate all existing items immediately
23,313
def create_account ( self , short_name , author_name = None , author_url = None , replace_token = True ) : response = self . _telegraph . method ( 'createAccount' , values = { 'short_name' : short_name , 'author_name' : author_name , 'author_url' : author_url } ) if replace_token : self . _telegraph . access_token = re...
Create a new Telegraph account
23,314
def edit_account_info ( self , short_name = None , author_name = None , author_url = None ) : return self . _telegraph . method ( 'editAccountInfo' , values = { 'short_name' : short_name , 'author_name' : author_name , 'author_url' : author_url } )
Update information about a Telegraph account . Pass only the parameters that you want to edit
23,315
def revoke_access_token ( self ) : response = self . _telegraph . method ( 'revokeAccessToken' ) self . _telegraph . access_token = response . get ( 'access_token' ) return response
Revoke access_token and generate a new one for example if the user would like to reset all connected sessions or you have reasons to believe the token was compromised . On success returns dict with new access_token and auth_url fields
23,316
def get_page ( self , path , return_content = True , return_html = True ) : response = self . _telegraph . method ( 'getPage' , path = path , values = { 'return_content' : return_content } ) if return_content and return_html : response [ 'content' ] = nodes_to_html ( response [ 'content' ] ) return response
Get a Telegraph page
23,317
def create_page ( self , title , content = None , html_content = None , author_name = None , author_url = None , return_content = False ) : if content is None : content = html_to_nodes ( html_content ) content_json = json . dumps ( content ) return self . _telegraph . method ( 'createPage' , values = { 'title' : title ...
Create a new Telegraph page
23,318
def get_account_info ( self , fields = None ) : return self . _telegraph . method ( 'getAccountInfo' , { 'fields' : json . dumps ( fields ) if fields else None } )
Get information about a Telegraph account
23,319
def get_views ( self , path , year = None , month = None , day = None , hour = None ) : return self . _telegraph . method ( 'getViews' , path = path , values = { 'year' : year , 'month' : month , 'day' : day , 'hour' : hour } )
Get the number of views for a Telegraph article
23,320
def upload_file ( f ) : with FilesOpener ( f ) as files : response = requests . post ( 'https://telegra.ph/upload' , files = files ) . json ( ) if isinstance ( response , list ) : error = response [ 0 ] . get ( 'error' ) else : error = response . get ( 'error' ) if error : raise TelegraphException ( error ) return [ i ...
Upload file to Telegra . ph s servers . Returns a list of links . Allowed only . jpg . jpeg . png . gif and . mp4 files .
23,321
def get_by_natural_key ( self , * args ) : kwargs = self . natural_key_kwargs ( * args ) for name , rel_to in self . model . get_natural_key_info ( ) : if not rel_to : continue nested_key = extract_nested_key ( kwargs , rel_to , name ) if nested_key : try : kwargs [ name ] = rel_to . objects . get_by_natural_key ( * ne...
Return the object corresponding to the provided natural key .
23,322
def create_by_natural_key ( self , * args ) : kwargs = self . natural_key_kwargs ( * args ) for name , rel_to in self . model . get_natural_key_info ( ) : if not rel_to : continue nested_key = extract_nested_key ( kwargs , rel_to , name ) if nested_key : kwargs [ name ] , is_new = ( rel_to . objects . get_or_create_by_...
Create a new object from the provided natural key values . If the natural key contains related objects recursively get or create them by their natural keys .
23,323
def get_or_create_by_natural_key ( self , * args ) : try : return self . get_by_natural_key ( * args ) , False except self . model . DoesNotExist : return self . create_by_natural_key ( * args ) , True
get_or_create + get_by_natural_key
23,324
def resolve_keys ( self , keys , auto_create = False ) : resolved = { } success = True for key in keys : if auto_create : resolved [ key ] = self . find ( * key ) else : try : resolved [ key ] = self . get_by_natural_key ( * key ) except self . model . DoesNotExist : success = False resolved [ key ] = None return resol...
Resolve the list of given keys into objects if possible . Returns a mapping and a success indicator .
23,325
def get_natural_key_info ( cls ) : fields = cls . get_natural_key_def ( ) info = [ ] for name in fields : field = cls . _meta . get_field ( name ) rel_to = None if hasattr ( field , 'rel' ) : rel_to = field . rel . to if field . rel else None elif hasattr ( field , 'remote_field' ) : if field . remote_field : rel_to = ...
Derive natural key from first unique_together definition noting which fields are related objects vs . regular fields .
23,326
def get_natural_key_fields ( cls ) : natural_key = [ ] for name , rel_to in cls . get_natural_key_info ( ) : if not rel_to : natural_key . append ( name ) else : nested_key = rel_to . get_natural_key_fields ( ) natural_key . extend ( [ name + '__' + nname for nname in nested_key ] ) return natural_key
Determine actual natural key field list incorporating the natural keys of related objects as needed .
23,327
def natural_key ( self ) : vals = [ reduce ( getattr , name . split ( '__' ) , self ) for name in self . get_natural_key_fields ( ) ] return vals
Return the natural key for this object .
23,328
def derive_coordinates ( self ) : if self . _coordinates_resolved : return if self . seg_map is not None : self . start , self . filename , include_ref = self . seg_map . derive_source_offset ( self . start ) self . end , end_filename , _ = self . seg_map . derive_source_offset ( self . end , is_end = True ) else : end...
Depending on the compilation source some members of the SourceRef object may be incomplete . Calling this function performs the necessary derivations to complete the object .
23,329
def format_message ( self , severity , text , src_ref ) : lines = [ ] if severity >= Severity . ERROR : color = Fore . RED elif severity >= Severity . WARNING : color = Fore . YELLOW else : color = Fore . GREEN if src_ref is None : lines . append ( color + Style . BRIGHT + severity . name . lower ( ) + ": " + Style . R...
Formats the message prior to emitting it .
23,330
def emit_message ( self , lines ) : for line in lines : print ( line , file = sys . stderr )
Emit message . Default printer emits messages to stderr
23,331
def get_value ( self ) : if ( self . _value is None ) and ( self . expr is not None ) : self . _value = self . expr . get_value ( ) return self . _value
Evaluate self . expr to get the parameter s value
23,332
def is_castable ( src , dst ) : if ( ( src in [ int , bool ] ) or rdltypes . is_user_enum ( src ) ) and ( dst in [ int , bool ] ) : return True elif ( src == rdltypes . ArrayPlaceholder ) and ( dst == rdltypes . ArrayPlaceholder ) : if src . element_type is None : return True elif src . element_type == dst . element_ty...
Check if src type can be cast to dst type
23,333
def predict_type ( self ) : current_comp = self . ref_root for name , array_suffixes , name_src_ref in self . ref_elements : current_comp = current_comp . get_child_by_name ( name ) if current_comp is None : self . msg . fatal ( "Could not resolve hierarchical reference to '%s'" % name , name_src_ref ) for array_suffix...
Traverse the ref_elements path and determine the component type being referenced . Also do some checks on the array indexes
23,334
def get_value ( self , eval_width = None ) : resolved_ref_elements = [ ] for name , array_suffixes , name_src_ref in self . ref_elements : idx_list = [ suffix . get_value ( ) for suffix in array_suffixes ] resolved_ref_elements . append ( ( name , idx_list , name_src_ref ) ) cref = rdltypes . ComponentRef ( self . ref_...
Build a resolved ComponentRef container that describes the relative path
23,335
def predict_type ( self ) : inst_type = self . inst_ref . predict_type ( ) if self . prop_ref_type . allowed_inst_type != inst_type : self . msg . fatal ( "'%s' is not a valid property of instance" % self . prop_ref_type . get_name ( ) , self . src_ref ) return self . prop_ref_type
Predict the type of the inst_ref and make sure the property being referenced is allowed
23,336
def get_group_node_size ( node ) : if ( not node . inst . children or ( not isinstance ( node . inst . children [ - 1 ] , comp . AddressableComponent ) ) ) : return 0 last_child_node = Node . _factory ( node . inst . children [ - 1 ] , node . env , node ) return ( last_child_node . inst . addr_offset + last_child_node ...
Shared getter for AddrmapNode and RegfileNode s size property
23,337
def add_derived_property ( cls , getter_function , name = None ) : if name is None : name = getter_function . __name__ mp = property ( fget = getter_function ) setattr ( cls , name , mp )
Register a user - defined derived property
23,338
def children ( self , unroll = False , skip_not_present = True ) : for child_inst in self . inst . children : if skip_not_present : if not child_inst . properties . get ( 'ispresent' , True ) : continue if unroll and isinstance ( child_inst , comp . AddressableComponent ) and child_inst . is_array : range_list = [ rang...
Returns an iterator that provides nodes for all immediate children of this component .
23,339
def descendants ( self , unroll = False , skip_not_present = True , in_post_order = False ) : for child in self . children ( unroll , skip_not_present ) : if in_post_order : yield from child . descendants ( unroll , skip_not_present , in_post_order ) yield child if not in_post_order : yield from child . descendants ( u...
Returns an iterator that provides nodes for all descendants of this component .
23,340
def signals ( self , skip_not_present = True ) : for child in self . children ( skip_not_present = skip_not_present ) : if isinstance ( child , SignalNode ) : yield child
Returns an iterator that provides nodes for all immediate signals of this component .
23,341
def fields ( self , skip_not_present = True ) : for child in self . children ( skip_not_present = skip_not_present ) : if isinstance ( child , FieldNode ) : yield child
Returns an iterator that provides nodes for all immediate fields of this component .
23,342
def registers ( self , unroll = False , skip_not_present = True ) : for child in self . children ( unroll , skip_not_present ) : if isinstance ( child , RegNode ) : yield child
Returns an iterator that provides nodes for all immediate registers of this component .
23,343
def find_by_path ( self , path ) : pathparts = path . split ( '.' ) current_node = self for pathpart in pathparts : m = re . fullmatch ( r'^(\w+)((?:\[(?:\d+|0[xX][\da-fA-F]+)\])*)$' , pathpart ) if not m : raise ValueError ( "Invalid path" ) inst_name , array_suffix = m . group ( 1 , 2 ) idx_list = [ int ( s , 0 ) for...
Finds the descendant node that is located at the relative path Returns None if not found Raises exception if path is malformed or array index is out of range
23,344
def get_property ( self , prop_name , ** kwargs ) : ovr_default = False default = None if 'default' in kwargs : ovr_default = True default = kwargs . pop ( 'default' ) if kwargs : raise TypeError ( "got an unexpected keyword argument '%s'" % list ( kwargs . keys ( ) ) [ 0 ] ) if prop_name in self . inst . properties : ...
Gets the SystemRDL component property
23,345
def list_properties ( self , list_all = False ) : if list_all : props = [ ] for k , v in self . env . property_rules . rdl_properties . items ( ) : if type ( self . inst ) in v . bindable_to : props . append ( k ) for k , v in self . env . property_rules . user_properties . items ( ) : if type ( self . inst ) in v . bi...
Lists properties associated with this node . By default only lists properties that were explicitly set . If list_all is set to True then lists all valid properties of this component type
23,346
def get_path ( self , hier_separator = "." , array_suffix = "[{index:d}]" , empty_array_suffix = "[]" ) : if self . parent and not isinstance ( self . parent , RootNode ) : return ( self . parent . get_path ( hier_separator , array_suffix , empty_array_suffix ) + hier_separator + self . get_path_segment ( array_suffix ...
Generate an absolute path string to this node
23,347
def get_html_desc ( self , markdown_inst = None ) : desc_str = self . get_property ( "desc" ) if desc_str is None : return None return rdlformatcode . rdlfc_to_html ( desc_str , self , md = markdown_inst )
Translates the node s desc property into HTML .
23,348
def address_offset ( self ) : if self . inst . is_array : if self . current_idx is None : raise ValueError ( "Index of array element must be known to derive address" ) idx = 0 for i in range ( len ( self . current_idx ) ) : sz = 1 for j in range ( i + 1 , len ( self . inst . array_dimensions ) ) : sz *= self . inst . a...
Byte address offset of this node relative to it s parent
23,349
def absolute_address ( self ) : if self . parent and not isinstance ( self . parent , RootNode ) : return self . parent . absolute_address + self . address_offset else : return self . address_offset
Get the absolute byte address of this node .
23,350
def top ( self ) : for child in self . children ( skip_not_present = False ) : if not isinstance ( child , AddrmapNode ) : continue return child raise RuntimeError
Returns the top - level addrmap node
23,351
def is_sw_writable ( self ) : sw = self . get_property ( 'sw' ) return sw in ( rdltypes . AccessType . rw , rdltypes . AccessType . rw1 , rdltypes . AccessType . w , rdltypes . AccessType . w1 )
Field is writable by software
23,352
def is_sw_readable ( self ) : sw = self . get_property ( 'sw' ) return sw in ( rdltypes . AccessType . rw , rdltypes . AccessType . rw1 , rdltypes . AccessType . r )
Field is readable by software
23,353
def implements_storage ( self ) : sw = self . get_property ( 'sw' ) hw = self . get_property ( 'hw' ) if sw in ( rdltypes . AccessType . rw , rdltypes . AccessType . rw1 ) : return True if hw == rdltypes . AccessType . rw : return True if ( sw in ( rdltypes . AccessType . w , rdltypes . AccessType . w1 ) ) and ( hw == ...
True if combination of field access properties imply that the field implements a storage element .
23,354
def visitComponent_def ( self , ctx : SystemRDLParser . Component_defContext ) : if ctx . component_anon_def ( ) is not None : comp_def = self . visit ( ctx . component_anon_def ( ) ) elif ctx . component_named_def ( ) is not None : comp_def = self . visit ( ctx . component_named_def ( ) ) else : raise RuntimeError com...
Create and possibly instantiate a component
23,355
def define_component ( self , body , type_token , def_name , param_defs ) : for subclass in ComponentVisitor . __subclasses__ ( ) : if subclass . comp_type == self . _CompType_Map [ type_token . type ] : visitor = subclass ( self . compiler , def_name , param_defs ) return visitor . visit ( body ) raise RuntimeError
Given component definition recurse to another ComponentVisitor to define a new component
23,356
def get_instance_assignment ( self , ctx ) : if ctx is None : return None visitor = ExprVisitor ( self . compiler ) expr = visitor . visit ( ctx . expr ( ) ) expr = expressions . AssignmentCast ( self . compiler . env , SourceRef . from_antlr ( ctx . op ) , expr , int ) expr . predict_type ( ) return expr
Gets the integer expression in any of the four instance assignment operators ( =
23,357
def visitParam_def ( self , ctx : SystemRDLParser . Param_defContext ) : self . compiler . namespace . enter_scope ( ) param_defs = [ ] for elem in ctx . getTypedRuleContexts ( SystemRDLParser . Param_def_elemContext ) : param_def = self . visit ( elem ) param_defs . append ( param_def ) self . compiler . namespace . e...
Parameter Definition block
23,358
def visitParam_def_elem ( self , ctx : SystemRDLParser . Param_def_elemContext ) : data_type_token = self . visit ( ctx . data_type ( ) ) param_data_type = self . datatype_from_token ( data_type_token ) if ctx . array_type_suffix ( ) is None : param_type = param_data_type else : param_type = rdltypes . ArrayPlaceholder...
Individual parameter definition elements
23,359
def datatype_from_token ( self , token ) : if token . type == SystemRDLParser . ID : typ = self . compiler . namespace . lookup_type ( get_ID_text ( token ) ) if typ is None : self . msg . fatal ( "Type '%s' is not defined" % get_ID_text ( token ) , SourceRef . from_antlr ( token ) ) if rdltypes . is_user_enum ( typ ) ...
Given a SystemRDLParser token lookup the type This only includes types under the data_type grammar rule
23,360
def get_rdltype ( value ) : if isinstance ( value , ( int , bool , str ) ) : return type ( value ) elif is_user_enum ( type ( value ) ) : return type ( value ) elif is_user_struct ( type ( value ) ) : return type ( value ) elif isinstance ( value , enum . Enum ) : return type ( value ) elif isinstance ( value , list ) ...
Given a value return the type identifier object used within the RDL compiler If not a supported type return None
23,361
def get_html_desc ( self , markdown_inst = None ) : desc_str = self . _rdl_desc_ if desc_str is None : return None return rdlformatcode . rdlfc_to_html ( desc_str , md = markdown_inst )
Translates the enum s desc property into HTML .
23,362
def get_scope_path ( cls , scope_separator = "::" ) : if cls . get_parent_scope ( ) is None : return "" elif isinstance ( cls . get_parent_scope ( ) , comp . Root ) : return "" else : parent_path = cls . get_parent_scope ( ) . get_scope_path ( scope_separator ) if parent_path : return ( parent_path + scope_separator + ...
Generate a string that represents this enum s declaration namespace scope .
23,363
def define_new ( cls , name , members , is_abstract = False ) : m = OrderedDict ( cls . _members ) if set ( m . keys ( ) ) & set ( members . keys ( ) ) : raise ValueError ( "'members' contains keys that overlap with parent" ) m . update ( members ) dct = { '_members' : m , '_is_abstract' : is_abstract , } newcls = type...
Define a new struct type derived from the current type .
23,364
def define_udp ( self , name , valid_type , valid_components = None , default = None ) : if valid_components is None : valid_components = [ comp . Field , comp . Reg , comp . Regfile , comp . Addrmap , comp . Mem , comp . Signal , ] if name in self . env . property_rules . rdl_properties : raise ValueError ( "name '%s'...
Pre - define a user - defined property .
23,365
def compile_file ( self , path , incl_search_paths = None ) : if incl_search_paths is None : incl_search_paths = [ ] fpp = preprocessor . FilePreprocessor ( self . env , path , incl_search_paths ) preprocessed_text , seg_map = fpp . preprocess ( ) input_stream = preprocessor . PreprocessedInputStream ( preprocessed_tex...
Parse & compile a single file and append it to RDLCompiler s root namespace .
23,366
def elaborate ( self , top_def_name = None , inst_name = None , parameters = None ) : if parameters is None : parameters = { } if top_def_name is not None : if top_def_name not in self . root . comp_defs : self . msg . fatal ( "Elaboration target '%s' not found" % top_def_name ) top_def = self . root . comp_defs [ top_...
Elaborates the design for the given top - level addrmap component .
23,367
def get_default ( self , node ) : if self . opposite_property in node . inst . properties : return not node . inst . properties [ self . opposite_property ] else : return self . default
If not explicitly set check if the opposite was set first before returning default
23,368
def get_default ( self , node ) : if node . inst . properties . get ( "onread" , None ) == rdltypes . OnReadType . rset : return True else : return self . default
If not explicitly set check if onread sets the equivalent
23,369
def assign_value ( self , comp_def , value , src_ref ) : super ( ) . assign_value ( comp_def , value , src_ref ) if "rclr" in comp_def . properties : del comp_def . properties [ "rclr" ] if "rset" in comp_def . properties : del comp_def . properties [ "rset" ]
Overrides other related properties
23,370
def get_default ( self , node ) : if node . inst . properties . get ( "rset" , False ) : return rdltypes . OnReadType . rset elif node . inst . properties . get ( "rclr" , False ) : return rdltypes . OnReadType . rclr else : return self . default
If not explicitly set check if rset or rclr imply the value
23,371
def get_default ( self , node ) : if node . inst . properties . get ( "onwrite" , None ) == rdltypes . OnWriteType . woclr : return True else : return self . default
If not explicitly set check if onwrite sets the equivalent
23,372
def get_default ( self , node ) : if node . inst . properties . get ( "woset" , False ) : return rdltypes . OnWriteType . woset elif node . inst . properties . get ( "woclr" , False ) : return rdltypes . OnWriteType . woclr else : return self . default
If not explicitly set check if woset or woclr imply the value
23,373
def assign_value ( self , comp_def , value , src_ref ) : super ( ) . assign_value ( comp_def , value , src_ref ) comp_def . properties [ 'incrthreshold' ] = value
Set both alias and actual value
23,374
def get_default ( self , node ) : if node . inst . properties . get ( "intr" , False ) : return not node . inst . properties . get ( "sticky" , False ) else : return False
Unless specified otherwise intr fields are implicitly stickybit
23,375
def resolve_addresses ( self , node ) : prop_alignment = self . alignment_stack [ - 1 ] if prop_alignment is None : prop_alignment = 1 prev_node = None for child_node in node . children ( skip_not_present = False ) : if not isinstance ( child_node , AddressableNode ) : continue if child_node . inst . addr_offset is not...
Resolve addresses of children of Addrmap and Regfile components
23,376
def get_ID_text ( token ) : if isinstance ( token , CommonToken ) : text = token . text else : text = token . getText ( ) text = text . lstrip ( '\\' ) return text
Get the text from the ID token . Strips off leading slash escape if present
23,377
def derive_source_offset ( self , offset , is_end = False ) : for segment in self . segments : if offset <= segment . end : if isinstance ( segment , MacroSegment ) : if is_end : return ( segment . src_end , segment . src , segment . incl_ref ) else : return ( segment . src_start , segment . src , segment . incl_ref ) ...
Given a post - preprocessed coordinate derives the corresponding coordinate in the original source file .
23,378
def preprocess ( self ) : tokens = self . tokenize ( ) pl_segments , has_perl_tags = self . get_perl_segments ( tokens ) str_parts = [ ] smap = segment_map . SegmentMap ( ) offset = 0 if has_perl_tags : emit_list = self . run_perl_miniscript ( pl_segments ) for entry in emit_list : if entry [ 'type' ] == "ref" : pl_seg...
Run preprocessor on a top - level file .
23,379
def tokenize ( self ) : tokens = [ ] token_spec = [ ( 'mlc' , r'/\*.*?\*/' ) , ( 'slc' , r'//[^\r\n]*?\r?\n' ) , ( 'perl' , r'<%.*?%>' ) , ( 'incl' , r'`include' ) , ] tok_regex = '|' . join ( '(?P<%s>%s)' % pair for pair in token_spec ) for m in re . finditer ( tok_regex , self . text , re . DOTALL ) : if m . lastgrou...
Tokenize the input text
23,380
def parse_include ( self , start ) : i = start while i : if self . text [ i ] == '\n' : i += 1 break i -= 1 line_start = i if not ( self . text [ line_start : start ] == "" or self . text [ line_start : start ] . isspace ( ) ) : self . env . msg . fatal ( "Unexpected text before include" , messages . SourceRef ( line_s...
Extract include from text based on start position of token
23,381
def run_perl_miniscript ( self , segments ) : if shutil . which ( "perl" ) is None : self . env . msg . fatal ( "Input contains Perl preprocessor tags, but an installation of Perl could not be found" ) lines = [ ] for i , pp_seg in enumerate ( segments ) : if isinstance ( pp_seg , PPPUnalteredSegment ) : lines . append...
Generates and runs a perl miniscript that derives the text that will be emitted from the preprocessor
23,382
def get_default_properties ( self , comp_type ) : props = { } for scope in self . default_property_ns_stack [ : - 1 ] : props . update ( scope ) prop_names = list ( props . keys ( ) ) for prop_name in prop_names : rule = self . env . property_rules . lookup_property ( prop_name ) if rule is None : self . msg . fatal ( ...
Returns a flattened dictionary of all default property assignments visible in the current scope that apply to the current component type .
23,383
def get_scope_path ( self , scope_separator = "::" ) : if self . parent_scope is None : return "" elif isinstance ( self . parent_scope , Root ) : return "" else : parent_path = self . parent_scope . get_scope_path ( scope_separator ) if parent_path : return ( parent_path + scope_separator + self . parent_scope . type_...
Generate a string that represents this component s declaration namespace scope .
23,384
def n_elements ( self ) : if self . is_array : return functools . reduce ( operator . mul , self . array_dimensions ) else : return 1
Total number of array elements . If array is multidimensional array is flattened . Returns 1 if not an array .
23,385
def walk ( self , node , * listeners : RDLListener ) : for listener in listeners : self . do_enter ( node , listener ) for child in node . children ( unroll = self . unroll , skip_not_present = self . skip_not_present ) : self . walk ( child , * listeners ) for listener in listeners : self . do_exit ( node , listener )
Initiates the walker to traverse the current node and its children . Calls the corresponding callback for each of the listeners provided in the order that they are listed .
23,386
def get_function ( fn_name ) : module_name , callable_name = fn_name . split ( ':' ) current = globals ( ) if not callable_name : callable_name = module_name else : import importlib try : module = importlib . import_module ( module_name ) except ImportError : log . error ( "failed to import %s" , module_name ) raise cu...
Retrieve the function defined by the function_name .
23,387
def parse_command_line ( argv ) : import textwrap example = textwrap . dedent ( ) . format ( os . path . basename ( argv [ 0 ] ) ) formatter_class = argparse . RawDescriptionHelpFormatter parser = argparse . ArgumentParser ( description = "Python mass editor" , epilog = example , formatter_class = formatter_class ) par...
Parse command line argument . See - h option .
23,388
def get_paths ( patterns , start_dirs = None , max_depth = 1 ) : if len ( patterns ) == 1 and not start_dirs : pattern = patterns [ 0 ] directory = os . path . dirname ( pattern ) if directory : patterns = [ os . path . basename ( pattern ) ] start_dirs = directory max_depth = 1 if not start_dirs or start_dirs == '.' :...
Retrieve files that match any of the patterns .
23,389
def edit_files ( patterns , expressions = None , functions = None , executables = None , start_dirs = None , max_depth = 1 , dry_run = True , output = sys . stdout , encoding = None , newline = None ) : if not is_list ( patterns ) : raise TypeError ( "patterns should be a list" ) if expressions and not is_list ( expres...
Process patterns with MassEdit .
23,390
def command_line ( argv ) : arguments = parse_command_line ( argv ) if arguments . generate : generate_fixer_file ( arguments . generate ) paths = edit_files ( arguments . patterns , expressions = arguments . expressions , functions = arguments . functions , executables = arguments . executables , start_dirs = argument...
Instantiate an editor and process arguments .
23,391
def import_module ( module ) : if isinstance ( module , list ) : all_modules = module else : all_modules = [ module ] for mod in all_modules : globals ( ) [ mod ] = __import__ ( mod . strip ( ) )
Import module that are needed for the code expr to compile .
23,392
def __edit_line ( line , code , code_obj ) : try : result = eval ( code_obj , globals ( ) , locals ( ) ) except TypeError as ex : log . error ( "failed to execute %s: %s" , code , ex ) raise if result is None : log . error ( "cannot process line '%s' with %s" , line , code ) raise RuntimeError ( 'failed to process line...
Edit a line with one code object built in the ctor .
23,393
def edit_line ( self , line ) : for code , code_obj in self . code_objs . items ( ) : line = self . __edit_line ( line , code , code_obj ) return line
Edit a single line using the code expression .
23,394
def edit_content ( self , original_lines , file_name ) : lines = [ self . edit_line ( line ) for line in original_lines ] for function in self . _functions : try : lines = list ( function ( lines , file_name ) ) except UnicodeDecodeError as err : log . error ( 'failed to process %s: %s' , file_name , err ) return lines...
Processes a file contents .
23,395
def append_code_expr ( self , code ) : if isinstance ( code , str ) and not isinstance ( code , unicode ) : code = unicode ( code ) if not isinstance ( code , unicode ) : raise TypeError ( "string expected" ) log . debug ( "compiling code %s..." , code ) try : code_obj = compile ( code , '<string>' , 'eval' ) self . co...
Compile argument and adds it to the list of code objects .
23,396
def append_function ( self , function ) : if not hasattr ( function , '__call__' ) : function = get_function ( function ) if not hasattr ( function , '__call__' ) : raise ValueError ( "function is expected to be callable" ) self . _functions . append ( function ) log . debug ( "registered %s" , function . __name__ )
Append the function to the list of functions to be called .
23,397
def append_executable ( self , executable ) : if isinstance ( executable , str ) and not isinstance ( executable , unicode ) : executable = unicode ( executable ) if not isinstance ( executable , unicode ) : raise TypeError ( "expected executable name as str, not {}" . format ( executable . __class__ . __name__ ) ) sel...
Append san executable os command to the list to be called .
23,398
def set_functions ( self , functions ) : for func in functions : try : self . append_function ( func ) except ( ValueError , AttributeError ) as ex : log . error ( "'%s' is not a callable function: %s" , func , ex ) raise
Check functions passed as argument and set them to be used .
23,399
def write_mnefiff ( data , filename ) : from mne import create_info , set_log_level from mne . io import RawArray set_log_level ( WARNING ) TRIAL = 0 info = create_info ( list ( data . axis [ 'chan' ] [ TRIAL ] ) , data . s_freq , [ 'eeg' , ] * data . number_of ( 'chan' ) [ TRIAL ] ) UNITS = 1e-6 fiff = RawArray ( data...
Export data to MNE using FIFF format .