idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
7,800 | def format_endpoint_argument_doc ( argument ) : doc = argument . doc_dict ( ) # Trim the strings a bit doc [ 'description' ] = clean_description ( py_doc_trim ( doc [ 'description' ] ) ) details = doc . get ( 'detailed_description' , None ) if details is not None : doc [ 'detailed_description' ] = clean_description ( py_doc_trim ( details ) ) return doc | Return documentation about the argument that an endpoint accepts . | 102 | 10 |
7,801 | def format_endpoint_returns_doc ( endpoint ) : description = clean_description ( py_doc_trim ( endpoint . _returns . _description ) ) return { 'description' : description , 'resource_name' : endpoint . _returns . _value_type , 'resource_type' : endpoint . _returns . __class__ . __name__ } | Return documentation about the resource that an endpoint returns . | 82 | 10 |
7,802 | def save ( self , * args , * * kwargs ) : self . body_formatted = sanetize_text ( self . body ) super ( Contact , self ) . save ( ) | Create formatted version of body text . | 42 | 7 |
7,803 | def get_current_membership_for_org ( self , account_num , verbose = False ) : all_memberships = self . get_memberships_for_org ( account_num = account_num , verbose = verbose ) # Look for first membership that hasn't expired yet. for membership in all_memberships : if ( membership . expiration_date and membership . expiration_date > datetime . datetime . now ( ) ) : # noqa return membership # noqa return None | Return a current membership for this org or None if there is none . | 108 | 14 |
7,804 | def get_memberships_for_org ( self , account_num , verbose = False ) : if not self . client . session_id : self . client . request_session ( ) query = "SELECT Objects() FROM Membership " "WHERE Owner = '%s' ORDER BY ExpirationDate" % account_num membership_list = self . get_long_query ( query , verbose = verbose ) return membership_list or [ ] | Retrieve all memberships associated with an organization ordered by expiration date . | 95 | 14 |
7,805 | def get_all_memberships ( self , limit_to = 100 , max_calls = None , parameters = None , since_when = None , start_record = 0 , verbose = False ) : if not self . client . session_id : self . client . request_session ( ) query = "SELECT Objects() FROM Membership" # collect all where parameters into a list of # (key, operator, value) tuples where_params = [ ] if parameters : for k , v in parameters . items ( ) : where_params . append ( ( k , "=" , v ) ) if since_when : d = datetime . date . today ( ) - datetime . timedelta ( days = since_when ) where_params . append ( ( 'LastModifiedDate' , ">" , "'%s 00:00:00'" % d ) ) if where_params : query += " WHERE " query += " AND " . join ( [ "%s %s %s" % ( p [ 0 ] , p [ 1 ] , p [ 2 ] ) for p in where_params ] ) query += " ORDER BY LocalID" # note, get_long_query is overkill when just looking at # one org, but it still only executes once # `get_long_query` uses `ms_object_to_model` to return Organizations membership_list = self . get_long_query ( query , limit_to = limit_to , max_calls = max_calls , start_record = start_record , verbose = verbose ) return membership_list or [ ] | Retrieve all memberships updated since since_when | 343 | 10 |
7,806 | def get_all_membership_products ( self , verbose = False ) : if not self . client . session_id : self . client . request_session ( ) query = "SELECT Objects() FROM MembershipDuesProduct" membership_product_list = self . get_long_query ( query , verbose = verbose ) return membership_product_list or [ ] | Retrieves membership product objects | 80 | 6 |
7,807 | def get_driver ( self , desired_capabilities = None ) : override_caps = desired_capabilities or { } desired_capabilities = self . config . make_selenium_desired_capabilities ( ) desired_capabilities . update ( override_caps ) browser_string = self . config . browser chromedriver_version = None if self . remote : driver = self . remote_service . build_driver ( desired_capabilities ) # There is no equivalent for BrowserStack. if browser_string == "CHROME" and self . remote_service . name == "saucelabs" : chromedriver_version = desired_capabilities . get ( "chromedriver-version" , None ) if chromedriver_version is None : raise ValueError ( "when using Chrome, you must set a " "``chromedriver-version`` capability so that Selenic " "can detect which version of Chromedriver will " "be used." ) else : if browser_string == "CHROME" : chromedriver_path = self . local_conf [ "CHROMEDRIVER_PATH" ] driver = webdriver . Chrome ( chromedriver_path , chrome_options = self . local_conf . get ( "CHROME_OPTIONS" ) , desired_capabilities = desired_capabilities , service_log_path = self . local_conf [ "SERVICE_LOG_PATH" ] , service_args = self . local_conf . get ( "SERVICE_ARGS" ) ) version_line = subprocess . check_output ( [ chromedriver_path , "--version" ] ) version_str = re . match ( ur"^ChromeDriver (\d+\.\d+)" , version_line ) . group ( 1 ) chromedriver_version = StrictVersion ( version_str ) elif browser_string == "FIREFOX" : profile = self . local_conf . get ( "FIREFOX_PROFILE" ) or FirefoxProfile ( ) binary = self . local_conf . get ( "FIREFOX_BINARY" ) or FirefoxBinary ( ) driver = webdriver . Firefox ( profile , binary , capabilities = desired_capabilities ) elif browser_string == "INTERNETEXPLORER" : driver = webdriver . Ie ( ) elif browser_string == "OPERA" : driver = webdriver . Opera ( ) else : # SAFARI # HTMLUNIT # HTMLUNITWITHJS # IPHONE # IPAD # ANDROID # PHANTOMJS raise ValueError ( "can't start a local " + browser_string ) # Check that what we get is what the config wanted... driver_caps = NormalizedCapabilities ( driver . desired_capabilities ) browser_version = re . sub ( r"\..*$" , "" , driver_caps [ "browserVersion" ] ) if driver_caps [ "platformName" ] . upper ( ) != self . config . platform : raise ValueError ( "the platform you want is not the one " "you are running selenic on" ) if browser_version != self . config . version : raise ValueError ( "the version installed is not the one " "you wanted" ) # On BrowserStack we cannot set the version of chromedriver or # query it. So we make the reasonable assuption that the # version of chromedriver is greater than 2.13. (There have # been at least 7 releases after 2.13 at the time of writing.) if ( self . remote_service and self . remote_service . name == "browserstack" ) or ( chromedriver_version is not None and chromedriver_version > StrictVersion ( "2.13" ) ) : # We patch ActionChains. chromedriver_element_center_patch ( ) # We need to mark the driver as needing the patch. setattr ( driver , CHROMEDRIVER_ELEMENT_CENTER_PATCH_FLAG , True ) driver = self . patch ( driver ) return driver | Creates a Selenium driver on the basis of the configuration file upon which this object was created . | 875 | 20 |
7,808 | def update_ff_binary_env ( self , variable ) : if self . config . browser != 'FIREFOX' : return binary = self . local_conf . get ( 'FIREFOX_BINARY' ) if binary is None : return # pylint: disable=protected-access binary . _firefox_env [ variable ] = os . environ [ variable ] | If a FIREFOX_BINARY was specified this method updates an environment variable used by the FirefoxBinary instance to the current value of the variable in the environment . | 82 | 34 |
7,809 | def regex ( self , protocols , localhost = True ) : p = r"^" # protocol p += r"(?:(?:(?:{}):)?//)" . format ( '|' . join ( protocols ) ) # basic auth (optional) p += r"(?:\S+(?::\S*)?@)?" p += r"(?:" # ip exclusion: private and local networks p += r"(?!(?:10|127)(?:\.\d{1,3}){3})" p += r"(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})" p += r"(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})" # ip excluding loopback (0.0.0.0), reserved space (244.0.0.0) # and network/broadcast addresses p += r"(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])" p += r"(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}" p += r"(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))" p += r"|" # hostname p += r"(?:" p += r"(?:" p += r"[a-z0-9\u00a1-\uffff][a-z0-9\u00a1-\uffff_-]{0,62})?" p += r"[a-z0-9\u00a1-\uffff]" p += r"\." if not localhost else r"[\.]?|localhost" p += r")+" # tld p += r"(?:[a-z\u00a1-\uffff]{2,}\.?)" p += r")" # port (optional) p += r"(?::\d{2,5})?" # path (optional) p += r"(?:[/?#]\S*)?" p += r"$" return p | URL Validation regex Based on regular expression by Diego Perini ( | 511 | 13 |
7,810 | def add_layers ( self , * layers ) : for layer in layers : if layer . name ( ) in self . __layers . keys ( ) : raise ValueError ( 'Layer "%s" already exists' % layer . name ( ) ) self . __layers [ layer . name ( ) ] = layer | Append given layers to this onion | 67 | 7 |
7,811 | def index ( objects , attr ) : with warnings . catch_warnings ( ) : warnings . simplefilter ( "ignore" ) return { getattr ( obj , attr ) : obj for obj in objects } | Generate a mapping of a list of objects indexed by the given attr . | 45 | 16 |
7,812 | def register ( self , typedef ) : if typedef in self . bound_types : return if not self . is_compatible ( typedef ) : raise ValueError ( "Incompatible type {} for engine {}" . format ( typedef , self ) ) if typedef not in self . unbound_types : self . unbound_types . add ( typedef ) typedef . _register ( self ) | Add the typedef to this engine if it is compatible . | 86 | 12 |
7,813 | def bind ( self , * * config ) : while self . unbound_types : typedef = self . unbound_types . pop ( ) try : load , dump = typedef . bind ( self , * * config ) self . bound_types [ typedef ] = { "load" : load , "dump" : dump } except Exception : self . unbound_types . add ( typedef ) raise | Bind all unbound types to the engine . | 87 | 9 |
7,814 | def load ( self , typedef , value , * * kwargs ) : try : bound_type = self . bound_types [ typedef ] except KeyError : raise DeclareException ( "Can't load unknown type {}" . format ( typedef ) ) else : # Don't need to try/catch since load/dump are bound together return bound_type [ "load" ] ( value , * * kwargs ) | Return the result of the bound load method for a typedef | 91 | 12 |
7,815 | def get_configdir ( name ) : configdir = os . environ . get ( '%sCONFIGDIR' % name . upper ( ) ) if configdir is not None : return os . path . abspath ( configdir ) p = None h = _get_home ( ) if ( ( sys . platform . startswith ( 'linux' ) or sys . platform . startswith ( 'darwin' ) ) and h is not None ) : p = os . path . join ( h , '.config/' + name ) elif h is not None : p = os . path . join ( h , '.' + name ) if not os . path . exists ( p ) : os . makedirs ( p ) return p | Return the string representing the configuration directory . | 159 | 8 |
7,816 | def ordered_yaml_dump ( data , stream = None , Dumper = None , * * kwds ) : Dumper = Dumper or yaml . Dumper class OrderedDumper ( Dumper ) : pass def _dict_representer ( dumper , data ) : return dumper . represent_mapping ( yaml . resolver . BaseResolver . DEFAULT_MAPPING_TAG , data . items ( ) ) OrderedDumper . add_representer ( OrderedDict , _dict_representer ) return yaml . dump ( data , stream , OrderedDumper , * * kwds ) | Dumps the stream from an OrderedDict . Taken from | 137 | 13 |
7,817 | def safe_load ( fname ) : lock = fasteners . InterProcessLock ( fname + '.lck' ) lock . acquire ( ) try : with open ( fname ) as f : return ordered_yaml_load ( f ) except : raise finally : lock . release ( ) | Load the file fname and make sure it can be done in parallel | 62 | 14 |
7,818 | def safe_dump ( d , fname , * args , * * kwargs ) : if osp . exists ( fname ) : os . rename ( fname , fname + '~' ) lock = fasteners . InterProcessLock ( fname + '.lck' ) lock . acquire ( ) try : with open ( fname , 'w' ) as f : ordered_yaml_dump ( d , f , * args , * * kwargs ) except : raise finally : lock . release ( ) | Savely dump d to fname using yaml | 111 | 10 |
7,819 | def project_map ( self ) : # first update with the experiments in the memory (the others should # already be loaded within the :attr:`exp_files` attribute) for key , val in self . items ( ) : if isinstance ( val , dict ) : l = self . _project_map [ val [ 'project' ] ] elif isinstance ( val , Archive ) : l = self . _project_map [ val . project ] else : continue if key not in l : l . append ( key ) return self . _project_map | A mapping from project name to experiments | 118 | 7 |
7,820 | def exp_files ( self ) : ret = OrderedDict ( ) # restore the order of the experiments exp_file = self . exp_file if osp . exists ( exp_file ) : for key , val in safe_load ( exp_file ) . items ( ) : ret [ key ] = val for project , d in self . projects . items ( ) : project_path = d [ 'root' ] config_path = osp . join ( project_path , '.project' ) if not osp . exists ( config_path ) : continue for fname in glob . glob ( osp . join ( config_path , '*.yml' ) ) : if fname == '.project.yml' : continue exp = osp . splitext ( osp . basename ( fname ) ) [ 0 ] if not isinstance ( ret . get ( exp ) , Archive ) : ret [ exp ] = osp . join ( config_path , exp + '.yml' ) if exp not in self . _project_map [ project ] : self . _project_map [ project ] . append ( exp ) return ret | A mapping from experiment to experiment configuration file | 245 | 8 |
7,821 | def save ( self ) : for exp , d in dict ( self ) . items ( ) : if isinstance ( d , dict ) : project_path = self . projects [ d [ 'project' ] ] [ 'root' ] d = self . rel_paths ( copy . deepcopy ( d ) ) fname = osp . join ( project_path , '.project' , exp + '.yml' ) if not osp . exists ( osp . dirname ( fname ) ) : os . makedirs ( osp . dirname ( fname ) ) safe_dump ( d , fname , default_flow_style = False ) exp_file = self . exp_file # to be 100% sure we do not write to the file from multiple processes lock = fasteners . InterProcessLock ( exp_file + '.lck' ) lock . acquire ( ) safe_dump ( OrderedDict ( ( exp , val if isinstance ( val , Archive ) else None ) for exp , val in self . items ( ) ) , exp_file , default_flow_style = False ) lock . release ( ) | Save the experiment configuration | 241 | 4 |
7,822 | def as_ordereddict ( self ) : if six . PY2 : d = OrderedDict ( ) copied = dict ( self ) for key in self : d [ key ] = copied [ key ] else : d = OrderedDict ( self ) return d | Convenience method to convert this object into an OrderedDict | 57 | 14 |
7,823 | def remove ( self , experiment ) : try : project_path = self . projects [ self [ experiment ] [ 'project' ] ] [ 'root' ] except KeyError : return config_path = osp . join ( project_path , '.project' , experiment + '.yml' ) for f in [ config_path , config_path + '~' , config_path + '.lck' ] : if os . path . exists ( f ) : os . remove ( f ) del self [ experiment ] | Remove the configuration of an experiment | 109 | 6 |
7,824 | def save ( self ) : project_paths = OrderedDict ( ) for project , d in OrderedDict ( self ) . items ( ) : if isinstance ( d , dict ) : project_path = d [ 'root' ] fname = osp . join ( project_path , '.project' , '.project.yml' ) if not osp . exists ( osp . dirname ( fname ) ) : os . makedirs ( osp . dirname ( fname ) ) if osp . exists ( fname ) : os . rename ( fname , fname + '~' ) d = self . rel_paths ( copy . deepcopy ( d ) ) safe_dump ( d , fname , default_flow_style = False ) project_paths [ project ] = project_path else : project_paths = self . project_paths [ project ] self . project_paths = project_paths safe_dump ( project_paths , self . all_projects , default_flow_style = False ) | Save the project configuration | 229 | 4 |
7,825 | def save ( self ) : self . projects . save ( ) self . experiments . save ( ) safe_dump ( self . global_config , self . _globals_file , default_flow_style = False ) | Save the entire configuration files | 47 | 5 |
7,826 | def reverseCommit ( self ) : self . baseClass . setText ( self . oldText ) self . qteWidget . SCISetStylingEx ( 0 , 0 , self . style ) | Replace the current widget content with the original text . Note that the original text has styling information available whereas the new text does not . | 42 | 27 |
7,827 | def placeCursor ( self , line , col ) : num_lines , num_col = self . qteWidget . getNumLinesAndColumns ( ) # Place the cursor at the specified position if possible. if line >= num_lines : line , col = num_lines , num_col else : text = self . qteWidget . text ( line ) if col >= len ( text ) : col = len ( text ) - 1 self . qteWidget . setCursorPosition ( line , col ) | Try to place the cursor in line at col if possible otherwise place it at the end . | 109 | 18 |
7,828 | def reverseCommit ( self ) : # Put the document into the 'before' state. self . baseClass . setText ( self . textBefore ) self . qteWidget . SCISetStylingEx ( 0 , 0 , self . styleBefore ) | Put the document into the before state . | 54 | 8 |
7,829 | def fromMimeData ( self , data ) : # Only insert the element if it is available in plain text. if data . hasText ( ) : self . insert ( data . text ( ) ) # Tell the underlying QsciScintilla object that the MIME data # object was indeed empty. return ( QtCore . QByteArray ( ) , False ) | Paste the clipboard data at the current cursor position . | 76 | 11 |
7,830 | def keyPressEvent ( self , keyEvent : QtGui . QKeyEvent ) : undoObj = UndoInsert ( self , keyEvent . text ( ) ) self . qteUndoStack . push ( undoObj ) | Undo safe wrapper for the native keyPressEvent method . | 48 | 12 |
7,831 | def replaceSelectedText ( self , text : str ) : undoObj = UndoReplaceSelectedText ( self , text ) self . qteUndoStack . push ( undoObj ) | Undo safe wrapper for the native replaceSelectedText method . | 41 | 13 |
7,832 | def insert ( self , text : str ) : undoObj = UndoInsert ( self , text ) self . qteUndoStack . push ( undoObj ) | Undo safe wrapper for the native insert method . | 34 | 10 |
7,833 | def insertAt ( self , text : str , line : int , col : int ) : undoObj = UndoInsertAt ( self , text , line , col ) self . qteUndoStack . push ( undoObj ) | Undo safe wrapper for the native insertAt method . | 48 | 11 |
7,834 | def append ( self , text : str ) : pos = self . getCursorPosition ( ) line , col = self . getNumLinesAndColumns ( ) undoObj = UndoInsertAt ( self , text , line , col ) self . qteUndoStack . push ( undoObj ) self . setCursorPosition ( * pos ) | Undo safe wrapper for the native append method . | 74 | 10 |
7,835 | def setText ( self , text : str ) : undoObj = UndoSetText ( self , text ) self . qteUndoStack . push ( undoObj ) | Undo safe wrapper for the native setText method . | 36 | 11 |
7,836 | def SCIGetStyledText ( self , selectionPos : tuple ) : # Sanity check. if not self . isSelectionPositionValid ( selectionPos ) : return None # Convert the start- and end point of the selection into # stream offsets. Ensure that start comes before end. start = self . positionFromLineIndex ( * selectionPos [ : 2 ] ) end = self . positionFromLineIndex ( * selectionPos [ 2 : ] ) if start > end : start , end = end , start # Allocate a large enough buffer. bufSize = 2 * ( end - start ) + 2 buf = bytearray ( bufSize ) # Fetch the text- and styling information. numRet = self . SendScintilla ( self . SCI_GETSTYLEDTEXT , start , end , buf ) # The last two bytes are always Zero according to the # Scintilla documentation, so remove them. buf = buf [ : - 2 ] # Double check that we did not receive more bytes than the buffer # was long. if numRet > bufSize : qteMain . qteLogger . error ( 'SCI_GETSTYLEDTEX function returned more' ' bytes than expected.' ) text = buf [ 0 : : 2 ] style = buf [ 1 : : 2 ] return ( text , style ) | Pythonic wrapper for the SCI_GETSTYLEDTEXT command . | 281 | 15 |
7,837 | def SCISetStyling ( self , line : int , col : int , numChar : int , style : bytearray ) : if not self . isPositionValid ( line , col ) : return pos = self . positionFromLineIndex ( line , col ) self . SendScintilla ( self . SCI_STARTSTYLING , pos , 0xFF ) self . SendScintilla ( self . SCI_SETSTYLING , numChar , style ) | Pythonic wrapper for the SCI_SETSTYLING command . | 103 | 14 |
7,838 | def SCISetStylingEx ( self , line : int , col : int , style : bytearray ) : if not self . isPositionValid ( line , col ) : return pos = self . positionFromLineIndex ( line , col ) self . SendScintilla ( self . SCI_STARTSTYLING , pos , 0xFF ) self . SendScintilla ( self . SCI_SETSTYLINGEX , len ( style ) , style ) | Pythonic wrapper for the SCI_SETSTYLINGEX command . | 102 | 15 |
7,839 | def qteSetLexer ( self , lexer ) : if ( lexer is not None ) and ( not issubclass ( lexer , Qsci . QsciLexer ) ) : QtmacsOtherError ( 'lexer must be a class object and derived from' ' <b>QsciLexer</b>' ) return # Install and backup the lexer class. self . qteLastLexer = lexer if lexer is None : self . setLexer ( None ) else : self . setLexer ( lexer ( ) ) # Make all fonts in the style mono space. self . setMonospace ( ) | Specify the lexer to use . | 136 | 8 |
7,840 | def setMonospace ( self ) : font = bytes ( 'courier new' , 'utf-8' ) for ii in range ( 32 ) : self . SendScintilla ( self . SCI_STYLESETFONT , ii , font ) | Fix the fonts of the first 32 styles to a mono space one . | 55 | 14 |
7,841 | def setModified ( self , isModified : bool ) : if not isModified : self . qteUndoStack . saveState ( ) super ( ) . setModified ( isModified ) | Set the modified state to isModified . | 44 | 9 |
7,842 | def attribute ( func ) : def inner ( self ) : name , attribute_type = func ( self ) if not name : name = func . __name__ try : return attribute_type ( self . et . attrib [ name ] ) except KeyError : raise AttributeError return inner | Decorator used to declare that property is a tag attribute | 60 | 12 |
7,843 | def section ( func ) : def inner ( self ) : return func ( self ) ( self . et . find ( func . __name__ ) ) return inner | Decorator used to declare that the property is xml section | 33 | 12 |
7,844 | def tag_value ( func ) : def inner ( self ) : tag , attrib , attrib_type = func ( self ) tag_obj = self . et . find ( tag ) if tag_obj is not None : try : return attrib_type ( self . et . find ( tag ) . attrib [ attrib ] ) except KeyError : raise AttributeError return inner | Decorator used to declare that the property is attribute of embedded tag | 82 | 14 |
7,845 | def tag_value_setter ( tag , attrib ) : def outer ( func ) : def inner ( self , value ) : tag_elem = self . et . find ( tag ) if tag_elem is None : et = ElementTree . fromstring ( "<{}></{}>" . format ( tag , tag ) ) self . et . append ( et ) tag_elem = self . et . find ( tag ) tag_elem . attrib [ attrib ] = str ( value ) return inner return outer | Decorator used to declare that the setter function is an attribute of embedded tag | 113 | 17 |
7,846 | def run ( self , value , model = None , context = None ) : res = self . validate ( value , model , context ) if not isinstance ( res , Error ) : err = 'Validator "{}" result must be of type "{}", got "{}"' raise InvalidErrorType ( err . format ( self . __class__ . __name__ , Error , type ( res ) ) ) return res | Run validation Wraps concrete implementation to ensure custom validators return proper type of result . | 86 | 17 |
7,847 | def _collect_data ( self ) : all_data = [ ] for line in self . engine . run_engine ( ) : logging . debug ( "Adding {} to all_data" . format ( line ) ) all_data . append ( line . copy ( ) ) logging . debug ( "all_data is now {}" . format ( all_data ) ) return all_data | Returns a list of all the data gathered from the engine iterable . | 82 | 14 |
7,848 | def _get_module_name_from_fname ( fname ) : fname = fname . replace ( ".pyc" , ".py" ) for mobj in sys . modules . values ( ) : if ( hasattr ( mobj , "__file__" ) and mobj . __file__ and ( mobj . __file__ . replace ( ".pyc" , ".py" ) == fname ) ) : module_name = mobj . __name__ return module_name raise RuntimeError ( "Module could not be found" ) | Get module name from module file name . | 119 | 8 |
7,849 | def get_function_args ( func , no_self = False , no_varargs = False ) : par_dict = signature ( func ) . parameters # Mark positional and/or keyword arguments (if any) pos = lambda x : x . kind == Parameter . VAR_POSITIONAL kw = lambda x : x . kind == Parameter . VAR_KEYWORD opts = [ "" , "*" , "**" ] args = [ "{prefix}{arg}" . format ( prefix = opts [ pos ( value ) + 2 * kw ( value ) ] , arg = par ) for par , value in par_dict . items ( ) ] # Filter out 'self' from parameter list (optional) self_filtered_args = ( args if not args else ( args [ 1 if ( args [ 0 ] == "self" ) and no_self else 0 : ] ) ) # Filter out positional or keyword arguments (optional) pos = lambda x : ( len ( x ) > 1 ) and ( x [ 0 ] == "*" ) and ( x [ 1 ] != "*" ) kw = lambda x : ( len ( x ) > 2 ) and ( x [ : 2 ] == "**" ) varargs_filtered_args = [ arg for arg in self_filtered_args if ( not no_varargs ) or all ( [ no_varargs , not pos ( arg ) , not kw ( arg ) ] ) ] return tuple ( varargs_filtered_args ) | Return tuple of the function argument names in the order of the function signature . | 326 | 15 |
7,850 | def get_module_name ( module_obj ) : if not is_object_module ( module_obj ) : raise RuntimeError ( "Argument `module_obj` is not valid" ) name = module_obj . __name__ msg = "Module object `{name}` could not be found in loaded modules" if name not in sys . modules : raise RuntimeError ( msg . format ( name = name ) ) return name | r Retrieve the module name from a module object . | 92 | 11 |
7,851 | def private_props ( obj ) : # Get private properties but NOT magic methods props = [ item for item in dir ( obj ) ] priv_props = [ _PRIVATE_PROP_REGEXP . match ( item ) for item in props ] call_props = [ callable ( getattr ( obj , item ) ) for item in props ] iobj = zip ( props , priv_props , call_props ) for obj_name in [ prop for prop , priv , call in iobj if priv and ( not call ) ] : yield obj_name | Yield private properties of an object . | 123 | 8 |
7,852 | def _check_intersection ( self , other ) : # pylint: disable=C0123 props = [ "_callables_db" , "_reverse_callables_db" , "_modules_dict" ] for prop in props : self_dict = getattr ( self , prop ) other_dict = getattr ( other , prop ) keys_self = set ( self_dict . keys ( ) ) keys_other = set ( other_dict . keys ( ) ) for key in keys_self & keys_other : svalue = self_dict [ key ] ovalue = other_dict [ key ] same_type = type ( svalue ) == type ( ovalue ) if same_type : list_comp = isinstance ( svalue , list ) and any ( [ item not in svalue for item in ovalue ] ) str_comp = isinstance ( svalue , str ) and svalue != ovalue dict_comp = isinstance ( svalue , dict ) and svalue != ovalue comp = any ( [ list_comp , str_comp , dict_comp ] ) if ( not same_type ) or ( same_type and comp ) : emsg = "Conflicting information between objects" raise RuntimeError ( emsg ) | Check that intersection of two objects has the same information . | 267 | 11 |
7,853 | def get_callable_from_line ( self , module_file , lineno ) : module_name = _get_module_name_from_fname ( module_file ) if module_name not in self . _modules_dict : self . trace ( [ module_file ] ) ret = None # Sort callables by starting line number iobj = sorted ( self . _modules_dict [ module_name ] , key = lambda x : x [ "code_id" ] [ 1 ] ) for value in iobj : if value [ "code_id" ] [ 1 ] <= lineno <= value [ "last_lineno" ] : ret = value [ "name" ] elif value [ "code_id" ] [ 1 ] > lineno : break return ret if ret else module_name | Get the callable that the line number belongs to . | 174 | 11 |
7,854 | def refresh ( self ) : self . trace ( list ( self . _fnames . keys ( ) ) , _refresh = True ) | Re - traces modules modified since the time they were traced . | 29 | 12 |
7,855 | def save ( self , callables_fname ) : # Validate file name _validate_fname ( callables_fname ) # JSON keys have to be strings but the reverse callables dictionary # keys are tuples, where the first item is a file name and the # second item is the starting line of the callable within that file # (dictionary value), thus need to convert the key to a string items = self . _reverse_callables_db . items ( ) fdict = { "_callables_db" : self . _callables_db , "_reverse_callables_db" : dict ( [ ( str ( k ) , v ) for k , v in items ] ) , "_modules_dict" : self . _modules_dict , "_fnames" : self . _fnames , "_module_names" : self . _module_names , "_class_names" : self . _class_names , } with open ( callables_fname , "w" ) as fobj : json . dump ( fdict , fobj ) | r Save traced modules information to a JSON _ file . | 229 | 11 |
7,856 | def _close_callable ( self , node , force = False ) : # Only nodes that have a line number can be considered for closing # callables. Similarly, only nodes with lines greater than the one # already processed can be considered for closing callables try : lineno = node . lineno except AttributeError : return if lineno <= self . _processed_line : return # [[[cog # code = """ # print(pcolor('Close callable @ line = {0}'.format(lineno), 'green')) # """ # cog.out(code) # ]]] # [[[end]]] # Extract node name for property closing. Once a property is found, # it can only be closed out by a node type that has a name name = "" try : name = ( node . name if hasattr ( node , "name" ) else ( node . targets [ 0 ] . id if hasattr ( node . targets [ 0 ] , "id" ) else node . targets [ 0 ] . value . id ) ) except AttributeError : pass # Traverse backwards through call stack and close callables as needed indent = self . _get_indent ( node ) count = - 1 # [[[cog # code = """ # print( # pcolor( # ' Name {0} @ {1}, indent = {2}'.format( # name if name else 'None', lineno, indent # ), # 'yellow' # ) # ) # """ # cog.out(code) # ]]] # [[[end]]] dlist = [ ] while count >= - len ( self . _indent_stack ) : element_full_name = self . _indent_stack [ count ] [ "full_name" ] edict = self . _callables_db . get ( element_full_name , None ) stack_indent = self . _indent_stack [ count ] [ "level" ] open_callable = element_full_name and ( not edict [ "last_lineno" ] ) # [[[cog # code = """ # print( # pcolor( # ' Name {0}, indent, {1}, stack_indent {2}'.format( # element_full_name, indent, stack_indent # ), # 'yellow' # ) # ) # """ # cog.out(code) # ]]] # [[[end]]] if open_callable and ( force or ( indent < stack_indent ) or ( ( indent == stack_indent ) and ( ( edict [ "type" ] != "prop" ) or ( ( edict [ "type" ] == "prop" ) and ( name and ( name != element_full_name ) ) ) ) ) ) : # [[[cog # code = """ # print( # pcolor( # ' Closing {0} @ {1}'.format( # element_full_name, lineno-1 # ), # 'yellow' # ) # ) # """ # cog.out(code) # ]]] # [[[end]]] edict [ "last_lineno" ] = lineno - 1 dlist . append ( count ) if indent > stack_indent : break count -= 1 # Callables have to be removed from stack when they are closed, # otherwise if a callable is subsequently followed after a few # lines by another callable at a further indentation level (like a for # loop) the second callable would incorrectly appear within the scope # of the first callable stack = self . _indent_stack stack_length = len ( self . _indent_stack ) dlist = [ item for item in dlist if stack [ item ] [ "type" ] != "module" ] for item in dlist : del self . _indent_stack [ stack_length + item ] | Record last line number of callable . | 824 | 8 |
7,857 | def _get_indent ( self , node ) : lineno = node . lineno if lineno > len ( self . _lines ) : return - 1 wsindent = self . _wsregexp . match ( self . _lines [ lineno - 1 ] ) return len ( wsindent . group ( 1 ) ) | Get node indentation level . | 73 | 6 |
7,858 | def _in_class ( self , node ) : # Move left one indentation level and check if that callable is a class indent = self . _get_indent ( node ) for indent_dict in reversed ( self . _indent_stack ) : # pragma: no branch if ( indent_dict [ "level" ] < indent ) or ( indent_dict [ "type" ] == "module" ) : return indent_dict [ "type" ] == "class" | Find if callable is function or method . | 103 | 9 |
7,859 | def _pop_indent_stack ( self , node , node_type = None , action = None ) : indent = self . _get_indent ( node ) indent_stack = copy . deepcopy ( self . _indent_stack ) # Find enclosing scope while ( len ( indent_stack ) > 1 ) and ( ( ( indent <= indent_stack [ - 1 ] [ "level" ] ) and ( indent_stack [ - 1 ] [ "type" ] != "module" ) ) or ( indent_stack [ - 1 ] [ "type" ] == "prop" ) ) : self . _close_callable ( node ) indent_stack . pop ( ) # Construct new callable name name = ( ( node . targets [ 0 ] . id if hasattr ( node . targets [ 0 ] , "id" ) else node . targets [ 0 ] . value . id ) if node_type == "prop" else node . name ) element_full_name = "." . join ( [ self . _module ] + [ indent_dict [ "prefix" ] for indent_dict in indent_stack if indent_dict [ "type" ] != "module" ] + [ name ] ) + ( "({0})" . format ( action ) if action else "" ) # Add new callable entry to indentation stack self . _indent_stack = indent_stack self . _indent_stack . append ( { "level" : indent , "prefix" : name , "type" : node_type , "full_name" : element_full_name , "lineno" : node . lineno , } ) return element_full_name | Get callable full name . | 357 | 6 |
7,860 | def generic_visit ( self , node ) : # [[[cog # cog.out("print(pcolor('Enter generic visitor', 'magenta'))") # ]]] # [[[end]]] # A generic visitor that potentially closes callables is needed to # close enclosed callables that are not at the end of the enclosing # callable, otherwise the ending line of the enclosed callable would # be the ending line of the enclosing callable, which would be # incorrect self . _close_callable ( node ) super ( _AstTreeScanner , self ) . generic_visit ( node ) | Implement generic node . | 131 | 5 |
7,861 | def visit_Assign ( self , node ) : # [[[cog # cog.out("print(pcolor('Enter assign visitor', 'magenta'))") # ]]] # [[[end]]] # ### # Class-level assignment may also be a class attribute that is not # a managed attribute, record it anyway, no harm in doing so as it # is not attached to a callable if self . _in_class ( node ) : element_full_name = self . _pop_indent_stack ( node , "prop" ) code_id = ( self . _fname , node . lineno ) self . _processed_line = node . lineno self . _callables_db [ element_full_name ] = { "name" : element_full_name , "type" : "prop" , "code_id" : code_id , "last_lineno" : None , } self . _reverse_callables_db [ code_id ] = element_full_name # [[[cog # code = """ # print( # pcolor( # 'Visiting property {0} @ {1}'.format( # element_full_name, code_id[1] # ), # 'green' # ) # ) # """ # cog.out(code) # ]]] # [[[end]]] # Get property actions self . generic_visit ( node ) | Implement assignment walker . | 305 | 6 |
7,862 | def visit_ClassDef ( self , node ) : # [[[cog # cog.out("print(pcolor('Enter class visitor', 'magenta'))") # ]]] # [[[end]]] # Get class information (name, line number, etc.) element_full_name = self . _pop_indent_stack ( node , "class" ) code_id = ( self . _fname , node . lineno ) self . _processed_line = node . lineno # Add class entry to dictionaries self . _class_names . append ( element_full_name ) self . _callables_db [ element_full_name ] = { "name" : element_full_name , "type" : "class" , "code_id" : code_id , "last_lineno" : None , } self . _reverse_callables_db [ code_id ] = element_full_name # [[[cog # code = """ # print( # pcolor( # 'Visiting class {0} @ {1}, indent = {2}'.format( # element_full_name, code_id[1], self._get_indent(node) # ), # 'green' # ) # ) # """ # cog.out(code) # ]]] # [[[end]]] self . generic_visit ( node ) | Implement class walker . | 298 | 6 |
7,863 | def run ( task_creators , args , task_selectors = [ ] ) : if args . reset_dep : sys . exit ( DoitMain ( WrapitLoader ( args , task_creators ) ) . run ( [ 'reset-dep' ] ) ) else : sys . exit ( DoitMain ( WrapitLoader ( args , task_creators ) ) . run ( task_selectors ) ) | run doit using task_creators | 89 | 8 |
7,864 | def tasks_by_tag ( self , registry_tag ) : if registry_tag not in self . __registry . keys ( ) : return None tasks = self . __registry [ registry_tag ] return tasks if self . __multiple_tasks_per_tag__ is True else tasks [ 0 ] | Get tasks from registry by its tag | 66 | 7 |
7,865 | def count ( self ) : result = 0 for tasks in self . __registry . values ( ) : result += len ( tasks ) return result | Registered task count | 30 | 3 |
7,866 | def add ( cls , task_cls ) : if task_cls . __registry_tag__ is None and cls . __skip_none_registry_tag__ is True : return cls . registry_storage ( ) . add ( task_cls ) | Add task class to storage | 60 | 5 |
7,867 | def my_func ( name ) : # Add exception exobj = addex ( TypeError , "Argument `name` is not valid" ) # Conditionally raise exception exobj ( not isinstance ( name , str ) ) print ( "My name is {0}" . format ( name ) ) | Sample function . | 63 | 3 |
7,868 | def add_prioritized ( self , command_obj , priority ) : if priority not in self . __priorities . keys ( ) : self . __priorities [ priority ] = [ ] self . __priorities [ priority ] . append ( command_obj ) | Add command with the specified priority | 59 | 6 |
7,869 | def __track_vars ( self , command_result ) : command_env = command_result . environment ( ) for var_name in self . tracked_vars ( ) : if var_name in command_env . keys ( ) : self . __vars [ var_name ] = command_env [ var_name ] | Check if there are any tracked variable inside the result . And keep them for future use . | 71 | 18 |
7,870 | def qteStartRecordingHook ( self , msgObj ) : if self . qteRecording : self . qteMain . qteStatus ( 'Macro recording already enabled' ) return # Update status flag. self . qteRecording = True # Reset the variables. self . qteMain . qteStatus ( 'Macro recording started' ) self . recorded_keysequence = QtmacsKeysequence ( ) # Connect the 'keypressed' and 'abort' signals. self . qteMain . qtesigKeyparsed . connect ( self . qteKeyPress ) self . qteMain . qtesigAbort . connect ( self . qteStopRecordingHook ) | Commence macro recording . | 152 | 5 |
7,871 | def qteStopRecordingHook ( self , msgObj ) : # Update status flag and disconnect all signals. if self . qteRecording : self . qteRecording = False self . qteMain . qteStatus ( 'Macro recording stopped' ) self . qteMain . qtesigKeyparsed . disconnect ( self . qteKeyPress ) self . qteMain . qtesigAbort . disconnect ( self . qteStopRecordingHook ) | Stop macro recording . | 104 | 4 |
7,872 | def qteReplayKeysequenceHook ( self , msgObj ) : # Quit if there is nothing to replay. if self . recorded_keysequence . toString ( ) == '' : return # Stop the recording before the replay, if necessary. if self . qteRecording : return # Simulate the key presses. self . qteMain . qteEmulateKeypresses ( self . recorded_keysequence ) | Replay the macro sequence . | 89 | 6 |
7,873 | def qteKeyPress ( self , msgObj ) : # Unpack the data structure. ( srcObj , keysequence , macroName ) = msgObj . data # Return immediately if the key sequence does not specify a # macro (yet). if macroName is None : return # If the macro to repeat is this very macro then disable the # macro proxy, otherwise execute the macro that would have run # originally. if macroName == self . qteMacroName ( ) : self . abort ( ) else : msg = 'Executing macro {} through {}' msg = msg . format ( macroName , self . qteMacroName ( ) ) self . qteMain . qteStatus ( msg ) self . qteMain . qteRunMacro ( macroName , srcObj , keysequence ) | Record the key presses . | 168 | 5 |
7,874 | def abort ( self , msgObj ) : self . qteMain . qtesigKeyparsed . disconnect ( self . qteKeyPress ) self . qteMain . qtesigAbort . disconnect ( self . abort ) self . qteActive = False self . qteMain . qteEnableMacroProcessing ( ) | Disconnect all signals and turn macro processing in the event handler back on . | 72 | 15 |
7,875 | def get_new_client ( request_session = False ) : from . client import ConciergeClient client = ConciergeClient ( access_key = os . environ [ "MS_ACCESS_KEY" ] , secret_key = os . environ [ "MS_SECRET_KEY" ] , association_id = os . environ [ "MS_ASSOCIATION_ID" ] ) if request_session : client . request_session ( ) return client | Return a new ConciergeClient pulling secrets from the environment . | 102 | 13 |
7,876 | def submit_msql_object_query ( object_query , client = None ) : client = client or get_new_client ( ) if not client . session_id : client . request_session ( ) result = client . execute_object_query ( object_query ) execute_msql_result = result [ "body" ] [ "ExecuteMSQLResult" ] membersuite_object_list = [ ] if execute_msql_result [ "Success" ] : result_value = execute_msql_result [ "ResultValue" ] if result_value [ "ObjectSearchResult" ] [ "Objects" ] : # Multiple results. membersuite_object_list = [ ] for obj in ( result_value [ "ObjectSearchResult" ] [ "Objects" ] [ "MemberSuiteObject" ] ) : membersuite_object = membersuite_object_factory ( obj ) membersuite_object_list . append ( membersuite_object ) elif result_value [ "SingleObject" ] [ "ClassType" ] : # Only one result. membersuite_object = membersuite_object_factory ( execute_msql_result [ "ResultValue" ] [ "SingleObject" ] ) membersuite_object_list . append ( membersuite_object ) elif ( result_value [ "ObjectSearchResult" ] [ "Objects" ] is None and result_value [ "SingleObject" ] [ "ClassType" ] is None ) : raise NoResultsError ( result = execute_msql_result ) return membersuite_object_list else : # @TODO Fix - exposing only the first of possibly many errors here. raise ExecuteMSQLError ( result = execute_msql_result ) | Submit object_query to MemberSuite returning . models . MemberSuiteObjects . | 388 | 18 |
7,877 | def value_for_key ( membersuite_object_data , key ) : key_value_dicts = { d [ 'Key' ] : d [ 'Value' ] for d in membersuite_object_data [ "Fields" ] [ "KeyValueOfstringanyType" ] } return key_value_dicts [ key ] | Return the value for key of membersuite_object_data . | 76 | 14 |
7,878 | def usesTime ( self , fmt = None ) : if fmt is None : fmt = self . _fmt if not isinstance ( fmt , basestring ) : fmt = fmt [ 0 ] return fmt . find ( '%(asctime)' ) >= 0 | Check if the format uses the creation time of the record . | 56 | 12 |
7,879 | def qteIsQtmacsWidget ( widgetObj ) : if widgetObj is None : return False if hasattr ( widgetObj , '_qteAdmin' ) : return True # Keep track of the already visited objects to avoid infinite loops. visited = [ widgetObj ] # Traverse the hierarchy until a parent features the '_qteAdmin' # attribute, the parent is None, or the parent is an already # visited widget. wid = widgetObj . parent ( ) while wid not in visited : if hasattr ( wid , '_qteAdmin' ) : return True elif wid is None : return False else : visited . append ( wid ) wid = wid . parent ( ) return False | Determine if a widget is part of Qtmacs widget hierarchy . | 146 | 15 |
7,880 | def qteGetAppletFromWidget ( widgetObj ) : if widgetObj is None : return None if hasattr ( widgetObj , '_qteAdmin' ) : return widgetObj . _qteAdmin . qteApplet # Keep track of the already visited objects to avoid infinite loops. visited = [ widgetObj ] # Traverse the hierarchy until a parent features the '_qteAdmin' # attribute, the parent is None, or the parent is an already # visited widget. wid = widgetObj . parent ( ) while wid not in visited : if hasattr ( wid , '_qteAdmin' ) : return wid . _qteAdmin . qteApplet elif wid is None : return None else : visited . append ( wid ) wid = wid . parent ( ) return None | Return the parent applet of widgetObj . | 167 | 9 |
7,881 | def setHookName ( self , name : str ) : self . isHook = True self . messengerName = name | Specify that the message will be delivered with the hook name . | 26 | 13 |
7,882 | def setSignalName ( self , name : str ) : self . isHook = False self . messengerName = name | Specify that the message will be delivered with the signal name . | 26 | 13 |
7,883 | def qteSetKeyFilterPolicy ( self , receiveBefore : bool = False , useQtmacs : bool = None , receiveAfter : bool = False ) : # Store key filter policy flags. self . filterKeyEvents = useQtmacs self . receiveBeforeQtmacsParser = receiveBefore self . receiveAfterQtmacsParser = receiveAfter | Set the policy on how Qtmacs filters keyboard events for a particular widgets . | 73 | 16 |
7,884 | def appendQKeyEvent ( self , keyEvent : QtGui . QKeyEvent ) : # Store the QKeyEvent. self . keylistKeyEvent . append ( keyEvent ) # Convenience shortcuts. mod = keyEvent . modifiers ( ) key = keyEvent . key ( ) # Add the modifier and key to the list. The modifier is a # QFlag structure and must by typecast to an integer to avoid # difficulties with the hashing in the ``match`` routine of # the ``QtmacsKeymap`` object. self . keylistQtConstants . append ( ( int ( mod ) , key ) ) | Append another key to the key sequence represented by this object . | 132 | 13 |
7,885 | def qteInsertKey ( self , keysequence : QtmacsKeysequence , macroName : str ) : # Get a dedicated reference to self to facilitate traversing # through the key map. keyMap = self # Get the key sequence as a list of tuples, where each tuple # contains the the control modifier and the key code, and both # are specified as Qt constants. keysequence = keysequence . toQtKeylist ( ) # Traverse the shortcut sequence and generate new keys as # necessary. for key in keysequence [ : - 1 ] : # If the key does not yet exist add an empty dictionary # (it will be filled later). if key not in keyMap : keyMap [ key ] = { } # Similarly, if the key does exist but references anything # other than a dictionary (eg. a previously installed # ``QtmacdMacro`` instance), then delete it. if not isinstance ( keyMap [ key ] , dict ) : keyMap [ key ] = { } # Go one level down in the key-map tree. keyMap = keyMap [ key ] # Assign the new macro object associated with this key. keyMap [ keysequence [ - 1 ] ] = macroName | Insert a new key into the key map and associate it with a macro . | 257 | 15 |
7,886 | def qteRemoveKey ( self , keysequence : QtmacsKeysequence ) : # Get a dedicated reference to self to facilitate traversing # through the key map. keyMap = self # Keep a reference to the root element in the key map. keyMapRef = keyMap # Get the key sequence as a list of tuples, where each tuple # contains the the control modifier and the key code, and both # are specified as Qt constants. keysequence = keysequence . toQtKeylist ( ) # ------------------------------------------------------------ # Remove the leaf element from the tree. # ------------------------------------------------------------ for key in keysequence [ : - 1 ] : # Quit if the key does not exist. This can happen if the # user tries to remove a key that has never been # registered. if key not in keyMap : return # Go one level down in the key-map tree. keyMap = keyMap [ key ] # The specified key sequence does not exist if the leaf # element (ie. last entry in the key sequence) is missing. if keysequence [ - 1 ] not in keyMap : return else : # Remove the leaf. keyMap . pop ( keysequence [ - 1 ] ) # ------------------------------------------------------------ # Prune the prefix path defined by ``keysequence`` and remove # all empty dictionaries. Start at the leaf level. # ------------------------------------------------------------ # Drop the last element in the key sequence, because it was # removed in the above code fragment already. keysequence = keysequence [ : - 1 ] # Now successively remove the key sequence in reverse order. while ( len ( keysequence ) ) : # Start at the root and move to the last branch level # before the leaf level. keyMap = keyMapRef for key in keysequence [ : - 1 ] : keyMap = keyMap [ key ] # If the leaf is a non-empty dictionary then another key # with the same prefix still exists. In this case do # nothing. However, if the leaf is now empty it must be # removed. if len ( keyMap [ key ] ) : return else : keyMap . pop ( key ) | Remove keysequence from this key map . | 441 | 8 |
7,887 | def match ( self , keysequence : QtmacsKeysequence ) : try : # Look up the ``keysequence`` in the current key map (ie. # this very object which inherits from ``dict``). If # ``keysequence`` does not lead to a valid macro then # return **None**. macroName = self for _ in keysequence . toQtKeylist ( ) : macroName = macroName [ _ ] except KeyError : # This error occurs if the keyboard sequence does not lead # to any macro and is therefore invalid. return ( None , False ) # At this point we know that the key sequence entered so far # exists. Two possibilities from here on forward: 1) the key # sequence now points to a macro or 2) the key sequence is # still incomplete. if isinstance ( macroName , dict ) : # Another dictionary --> key sequence is still incomplete. return ( None , True ) else : # Macro object --> return it. return ( macroName , True ) | Look up the key sequence in key map . | 209 | 9 |
7,888 | def _qteGetLabelInstance ( self ) : # Create a label with the proper colour appearance. layout = self . layout ( ) label = QtGui . QLabel ( self ) style = 'QLabel { background-color : white; color : blue; }' label . setStyleSheet ( style ) return label | Return an instance of a QLabel with the correct color scheme . | 68 | 13 |
7,889 | def _qteUpdateLabelWidths ( self ) : layout = self . layout ( ) # Remove all labels from the list and add them again in the # new order. for ii in range ( layout . count ( ) ) : label = layout . itemAt ( ii ) layout . removeItem ( label ) # Add all labels and ensure they have appropriate width. for item in self . _qteModeList : label = item [ 2 ] width = label . fontMetrics ( ) . size ( 0 , str ( item [ 1 ] ) ) . width ( ) label . setMaximumWidth ( width ) label . setMinimumWidth ( width ) layout . addWidget ( label ) # Remove the width constraint from the last label so that # it can expand to the right. _ , _ , label = self . _qteModeList [ - 1 ] label . setMaximumWidth ( 1600000 ) | Ensure all but the last QLabel are only as wide as necessary . | 186 | 15 |
7,890 | def qteGetMode ( self , mode : str ) : for item in self . _qteModeList : if item [ 0 ] == mode : return item return None | Return a tuple containing the mode its value and its associated QLabel instance . | 36 | 15 |
7,891 | def qteAddMode ( self , mode : str , value ) : # Add the label to the layout and the local mode list. label = self . _qteGetLabelInstance ( ) label . setText ( value ) self . _qteModeList . append ( ( mode , value , label ) ) self . _qteUpdateLabelWidths ( ) | Append label for mode and display value on it . | 76 | 11 |
7,892 | def qteChangeModeValue ( self , mode : str , value ) : # Search through the list for ``mode``. for idx , item in enumerate ( self . _qteModeList ) : if item [ 0 ] == mode : # Update the displayed value in the label. label = item [ 2 ] label . setText ( value ) # Overwrite the old data record with the updated one # and adjust the widths of the modes. self . _qteModeList [ idx ] = ( mode , value , label ) self . _qteUpdateLabelWidths ( ) return True return False | Change the value of mode to value . | 129 | 8 |
7,893 | def qteInsertMode ( self , pos : int , mode : str , value ) : # Add the label to the list. label = self . _qteGetLabelInstance ( ) label . setText ( value ) self . _qteModeList . insert ( pos , ( mode , value , label ) ) self . _qteUpdateLabelWidths ( ) | Insert mode at position pos . | 77 | 6 |
7,894 | def qteRemoveMode ( self , mode : str ) : # Search through the list for ``mode``. for idx , item in enumerate ( self . _qteModeList ) : if item [ 0 ] == mode : # Remove the record and delete the label. self . _qteModeList . remove ( item ) item [ 2 ] . hide ( ) item [ 2 ] . deleteLater ( ) self . _qteUpdateLabelWidths ( ) return True return False | Remove mode and associated label . | 102 | 6 |
7,895 | def _get_bases ( type_ ) : # type: (type) -> Tuple[type, type] try : class _ ( type_ ) : # type: ignore """Check if type_ is subclassable.""" BaseClass = type_ except TypeError : BaseClass = object class MetaClass ( _ValidationMeta , BaseClass . __class__ ) : # type: ignore """Use the type_ meta and include base validation functionality.""" return BaseClass , MetaClass | Get the base and meta classes to use in creating a subclass . | 101 | 13 |
7,896 | def _instantiate ( class_ , type_ , __value , * args , * * kwargs ) : try : return class_ ( __value , * args , * * kwargs ) except TypeError : try : return type_ ( __value , * args , * * kwargs ) except Exception : # pylint: disable=broad-except return __value | Instantiate the object if possible . | 81 | 7 |
7,897 | def _get_fullname ( obj ) : # type: (Any) -> str if not hasattr ( obj , "__name__" ) : obj = obj . __class__ if obj . __module__ in ( "builtins" , "__builtin__" ) : return obj . __name__ return "{}.{}" . format ( obj . __module__ , obj . __name__ ) | Get the full name of an object including the module . | 86 | 11 |
7,898 | def get ( self , key , recursive = False , sorted = False , quorum = False , timeout = None ) : return self . adapter . get ( key , recursive = recursive , sorted = sorted , quorum = quorum , timeout = timeout ) | Gets a value of key . | 52 | 7 |
7,899 | def wait ( self , key , index = 0 , recursive = False , sorted = False , quorum = False , timeout = None ) : return self . adapter . get ( key , recursive = recursive , sorted = sorted , quorum = quorum , wait = True , wait_index = index , timeout = timeout ) | Waits until a node changes . | 66 | 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.