idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
11,100 | def dialect_class ( self , adapter ) : if self . dialects . get ( adapter ) : return self . dialects [ adapter ] try : class_prefix = getattr ( __import__ ( 'db.' + adapter , globals ( ) , locals ( ) , [ '__class_prefix__' ] ) , '__class_prefix__' ) driver = self . _import_class ( 'db.' + adapter + '.dialect.' + class_prefix + 'Dialect' ) except ImportError : raise DBError ( "Must install adapter `%s` or doesn't support" % ( adapter ) ) self . dialects [ adapter ] = driver return driver | Get dialect sql class by adapter | 142 | 6 |
11,101 | def _import_class ( self , module2cls ) : d = module2cls . rfind ( "." ) classname = module2cls [ d + 1 : len ( module2cls ) ] m = __import__ ( module2cls [ 0 : d ] , globals ( ) , locals ( ) , [ classname ] ) return getattr ( m , classname ) | Import class by module dot split string | 86 | 7 |
11,102 | def rebuild ( self , gridRect ) : scene = self . scene ( ) if ( not scene ) : return self . setVisible ( gridRect . contains ( self . pos ( ) ) ) self . setZValue ( 100 ) path = QPainterPath ( ) path . moveTo ( 0 , 0 ) path . lineTo ( 0 , gridRect . height ( ) ) tip = '' tip_point = None self . _ellipses = [ ] items = scene . collidingItems ( self ) self . _basePath = QPainterPath ( path ) for item in items : item_path = item . path ( ) found = None for y in range ( int ( gridRect . top ( ) ) , int ( gridRect . bottom ( ) ) ) : point = QPointF ( self . pos ( ) . x ( ) , y ) if ( item_path . contains ( point ) ) : found = QPointF ( 0 , y - self . pos ( ) . y ( ) ) break if ( found ) : path . addEllipse ( found , 6 , 6 ) self . _ellipses . append ( found ) # update the value information value = scene . valueAt ( self . mapToScene ( found ) ) tip_point = self . mapToScene ( found ) hruler = scene . horizontalRuler ( ) vruler = scene . verticalRuler ( ) x_value = hruler . formatValue ( value [ 0 ] ) y_value = vruler . formatValue ( value [ 1 ] ) tip = '<b>x:</b> %s<br/><b>y:</b> %s' % ( x_value , y_value ) self . setPath ( path ) self . setVisible ( True ) # show the popup widget if ( tip ) : anchor = XPopupWidget . Anchor . RightCenter widget = self . scene ( ) . chartWidget ( ) tip_point = widget . mapToGlobal ( widget . mapFromScene ( tip_point ) ) XPopupWidget . showToolTip ( tip , anchor = anchor , parent = widget , point = tip_point , foreground = QColor ( 'blue' ) , background = QColor ( 148 , 148 , 255 ) ) | Rebuilds the tracker item . | 482 | 7 |
11,103 | def get_access_token ( self ) : if self . token_info and not self . is_token_expired ( self . token_info ) : return self . token_info [ 'access_token' ] token_info = self . _request_access_token ( ) token_info = self . _add_custom_values_to_token_info ( token_info ) self . token_info = token_info return self . token_info [ 'access_token' ] | If a valid access token is in memory returns it Else feches a new token and returns it | 106 | 19 |
11,104 | def _request_access_token ( self ) : payload = { 'grant_type' : 'authorization_code' , 'code' : code , 'redirect_uri' : self . redirect_uri } headers = _make_authorization_headers ( self . client_id , self . client_secret ) response = requests . post ( self . OAUTH_TOKEN_URL , data = payload , headers = headers , verify = LOGIN_VERIFY_SSL_CERT ) if response . status_code is not 200 : raise MercedesMeAuthError ( response . reason ) token_info = response . json ( ) return token_info | Gets client credentials access token | 141 | 6 |
11,105 | def get_cached_token ( self ) : token_info = None if self . cache_path : try : f = open ( self . cache_path ) token_info_string = f . read ( ) f . close ( ) token_info = json . loads ( token_info_string ) if self . is_token_expired ( token_info ) : token_info = self . refresh_access_token ( token_info [ 'refresh_token' ] ) except IOError : pass return token_info | Gets a cached auth token | 113 | 6 |
11,106 | def get_authorize_url ( self , state = None ) : payload = { 'client_id' : self . client_id , 'response_type' : 'code' , 'redirect_uri' : self . redirect_uri , 'scope' : self . scope } urlparams = urllib . parse . urlencode ( payload ) return "%s?%s" % ( self . OAUTH_AUTHORIZE_URL , urlparams ) | Gets the URL to use to authorize this app | 101 | 10 |
11,107 | def get_access_token ( self , code ) : payload = { 'redirect_uri' : self . redirect_uri , 'code' : code , 'grant_type' : 'authorization_code' } headers = self . _make_authorization_headers ( ) response = requests . post ( self . OAUTH_TOKEN_URL , data = payload , headers = headers , verify = LOGIN_VERIFY_SSL_CERT ) if response . status_code is not 200 : raise MercedesMeAuthError ( response . reason ) token_info = response . json ( ) token_info = self . _add_custom_values_to_token_info ( token_info ) self . _save_token_info ( token_info ) return token_info | Gets the access token for the app given the code | 169 | 11 |
11,108 | def _add_custom_values_to_token_info ( self , token_info ) : token_info [ 'expires_at' ] = int ( time . time ( ) ) + token_info [ 'expires_in' ] token_info [ 'scope' ] = self . scope return token_info | Store some values that aren t directly provided by a Web API response . | 69 | 14 |
11,109 | def clear ( self , autoBuild = True ) : for action in self . _actionGroup . actions ( ) : self . _actionGroup . removeAction ( action ) action = QAction ( '' , self ) action . setObjectName ( 'place_holder' ) self . _actionGroup . addAction ( action ) if autoBuild : self . rebuild ( ) | Clears the actions for this widget . | 76 | 8 |
11,110 | def copyFilepath ( self ) : clipboard = QApplication . instance ( ) . clipboard ( ) clipboard . setText ( self . filepath ( ) ) clipboard . setText ( self . filepath ( ) , clipboard . Selection ) | Copies the current filepath contents to the current clipboard . | 48 | 12 |
11,111 | def pickFilepath ( self ) : mode = self . filepathMode ( ) filepath = '' filepaths = [ ] curr_dir = nativestring ( self . _filepathEdit . text ( ) ) if ( not curr_dir ) : curr_dir = QDir . currentPath ( ) if mode == XFilepathEdit . Mode . SaveFile : filepath = QFileDialog . getSaveFileName ( self , self . windowTitle ( ) , curr_dir , self . filepathTypes ( ) ) elif mode == XFilepathEdit . Mode . OpenFile : filepath = QFileDialog . getOpenFileName ( self , self . windowTitle ( ) , curr_dir , self . filepathTypes ( ) ) elif mode == XFilepathEdit . Mode . OpenFiles : filepaths = QFileDialog . getOpenFileNames ( self , self . windowTitle ( ) , curr_dir , self . filepathTypes ( ) ) else : filepath = QFileDialog . getExistingDirectory ( self , self . windowTitle ( ) , curr_dir ) if filepath : if type ( filepath ) == tuple : filepath = filepath [ 0 ] self . setFilepath ( nativestring ( filepath ) ) elif filepaths : self . setFilepaths ( map ( str , filepaths ) ) | Prompts the user to select a filepath from the system based on the \ current filepath mode . | 299 | 22 |
11,112 | def showMenu ( self , pos ) : menu = QMenu ( self ) menu . setAttribute ( Qt . WA_DeleteOnClose ) menu . addAction ( 'Clear' ) . triggered . connect ( self . clearFilepath ) menu . addSeparator ( ) menu . addAction ( 'Copy Filepath' ) . triggered . connect ( self . copyFilepath ) menu . exec_ ( self . mapToGlobal ( pos ) ) | Popups a menu for this widget . | 93 | 8 |
11,113 | def validateFilepath ( self ) : if ( not self . isValidated ( ) ) : return valid = self . isValid ( ) if ( not valid ) : fg = self . invalidForeground ( ) bg = self . invalidBackground ( ) else : fg = self . validForeground ( ) bg = self . validBackground ( ) palette = self . palette ( ) palette . setColor ( palette . Base , bg ) palette . setColor ( palette . Text , fg ) self . _filepathEdit . setPalette ( palette ) | Alters the color scheme based on the validation settings . | 119 | 11 |
11,114 | def clear ( self ) : self . uiQueryTXT . setText ( '' ) self . uiQueryTREE . clear ( ) self . uiGroupingTXT . setText ( '' ) self . uiSortingTXT . setText ( '' ) | Clears the information for this edit . | 58 | 8 |
11,115 | def save ( self ) : record = self . record ( ) if not record : logger . warning ( 'No record has been defined for %s.' % self ) return False if not self . signalsBlocked ( ) : self . aboutToSaveRecord . emit ( record ) self . aboutToSave . emit ( ) values = self . saveValues ( ) # ignore columns that are the same (fixes bugs in encrypted columns) check = values . copy ( ) for column_name , value in check . items ( ) : try : equals = value == record . recordValue ( column_name ) except UnicodeWarning : equals = False if equals : check . pop ( column_name ) # check to see if nothing has changed if not check and record . isRecord ( ) : if not self . signalsBlocked ( ) : self . recordSaved . emit ( record ) self . saved . emit ( ) self . _saveSignalBlocked = False else : self . _saveSignalBlocked = True if self . autoCommitOnSave ( ) : status , result = record . commit ( ) if status == 'errored' : if 'db_error' in result : msg = nativestring ( result [ 'db_error' ] ) else : msg = 'An unknown database error has occurred.' QMessageBox . information ( self , 'Commit Error' , msg ) return False return True # validate the modified values success , msg = record . validateValues ( check ) if ( not success ) : QMessageBox . information ( None , 'Could Not Save' , msg ) return False record . setRecordValues ( * * values ) success , msg = record . validateRecord ( ) if not success : QMessageBox . information ( None , 'Could Not Save' , msg ) return False if ( self . autoCommitOnSave ( ) ) : result = record . commit ( ) if 'errored' in result : QMessageBox . information ( None , 'Could Not Save' , msg ) return False if ( not self . signalsBlocked ( ) ) : self . recordSaved . emit ( record ) self . saved . emit ( ) self . _saveSignalBlocked = False else : self . _saveSignalBlocked = True return True | Saves the changes from the ui to this widgets record instance . | 475 | 14 |
11,116 | def add_dynamic_element ( self , name , description ) : self . _pb . add ( Name = name , Description = description , Value = "*" ) return self | Adds a dynamic namespace element to the end of the Namespace . | 38 | 13 |
11,117 | def Chrome ( headless = False , user_agent = None , profile_path = None ) : chromedriver = drivers . ChromeDriver ( headless , user_agent , profile_path ) return chromedriver . driver | Starts and returns a Selenium webdriver object for Chrome . | 47 | 13 |
11,118 | def Firefox ( headless = False , user_agent = None , profile_path = None ) : firefoxdriver = drivers . FirefoxDriver ( headless , user_agent , profile_path ) return firefoxdriver . driver | Starts and returns a Selenium webdriver object for Firefox . | 47 | 13 |
11,119 | def cancel ( self ) : if self . _running : self . interrupt ( ) self . _running = False self . _cancelled = True self . loadingFinished . emit ( ) | Cancels the current lookup . | 40 | 7 |
11,120 | def loadBatch ( self , records ) : try : curr_batch = records [ : self . batchSize ( ) ] next_batch = records [ self . batchSize ( ) : ] curr_records = list ( curr_batch ) if self . _preloadColumns : for record in curr_records : record . recordValues ( self . _preloadColumns ) if len ( curr_records ) == self . batchSize ( ) : self . loadedRecords [ object , object ] . emit ( curr_records , next_batch ) else : self . loadedRecords [ object ] . emit ( curr_records ) except ConnectionLostError : self . connectionLost . emit ( ) except Interruption : pass | Loads the records for this instance in a batched mode . | 162 | 13 |
11,121 | def names ( self ) : if getattr ( self , 'key' , None ) is None : result = [ ] else : result = [ self . key ] if hasattr ( self , 'aliases' ) : result . extend ( self . aliases ) return result | Names by which the instance can be retrieved . | 56 | 9 |
11,122 | def autoLayout ( self , size = None ) : if size is None : size = self . _view . size ( ) self . setSceneRect ( 0 , 0 , size . width ( ) , size . height ( ) ) for item in self . items ( ) : if isinstance ( item , XWalkthroughGraphic ) : item . autoLayout ( size ) | Updates the layout for the graphics within this scene . | 77 | 11 |
11,123 | def prepare ( self ) : for item in self . items ( ) : if isinstance ( item , XWalkthroughGraphic ) : item . prepare ( ) | Prepares the items for display . | 33 | 7 |
11,124 | def autoLayout ( self , size ) : # update the children alignment direction = self . property ( 'direction' , QtGui . QBoxLayout . TopToBottom ) x = 0 y = 0 base_off_x = 0 base_off_y = 0 for i , child in enumerate ( self . childItems ( ) ) : off_x = 6 + child . boundingRect ( ) . width ( ) off_y = 6 + child . boundingRect ( ) . height ( ) if direction == QtGui . QBoxLayout . TopToBottom : child . setPos ( x , y ) y += off_y elif direction == QtGui . QBoxLayout . BottomToTop : y -= off_y child . setPos ( x , y ) if not base_off_y : base_off_y = off_y elif direction == QtGui . QBoxLayout . LeftToRight : child . setPos ( x , y ) x += off_x else : x -= off_x child . setPos ( x , y ) if not base_off_x : base_off_x = off_x #---------------------------------------------------------------------- pos = self . property ( 'pos' ) align = self . property ( 'align' ) offset = self . property ( 'offset' ) rect = self . boundingRect ( ) if pos : x = pos . x ( ) y = pos . y ( ) elif align == QtCore . Qt . AlignCenter : x = ( size . width ( ) - rect . width ( ) ) / 2.0 y = ( size . height ( ) - rect . height ( ) ) / 2.0 else : if align & QtCore . Qt . AlignLeft : x = 0 elif align & QtCore . Qt . AlignRight : x = ( size . width ( ) - rect . width ( ) ) else : x = ( size . width ( ) - rect . width ( ) ) / 2.0 if align & QtCore . Qt . AlignTop : y = 0 elif align & QtCore . Qt . AlignBottom : y = ( size . height ( ) - rect . height ( ) ) else : y = ( size . height ( ) - rect . height ( ) ) / 2.0 if offset : x += offset . x ( ) y += offset . y ( ) x += base_off_x y += base_off_y self . setPos ( x , y ) | Lays out this widget within the graphics scene . | 525 | 10 |
11,125 | def prepare ( self ) : text = self . property ( 'caption' ) if text : capw = int ( self . property ( 'caption_width' , 0 ) ) item = self . addText ( text , capw ) | Prepares this graphic item to be displayed . | 51 | 9 |
11,126 | def prepare ( self ) : # determine if we already have a snapshot setup pixmap = self . property ( 'pixmap' ) if pixmap is not None : return super ( XWalkthroughSnapshot , self ) . prepare ( ) # otherwise, setup the snapshot widget = self . property ( 'widget' ) if type ( widget ) in ( unicode , str ) : widget = self . findReference ( widget ) if not widget : return super ( XWalkthroughSnapshot , self ) . prepare ( ) # test if this is an overlay option if self . property ( 'overlay' ) and widget . parent ( ) : ref = self . referenceWidget ( ) if ref == widget : pos = QtCore . QPoint ( 0 , 0 ) else : glbl_pos = widget . mapToGlobal ( QtCore . QPoint ( 0 , 0 ) ) pos = ref . mapFromGlobal ( glbl_pos ) self . setProperty ( 'pos' , pos ) # crop out the options crop = self . property ( 'crop' , QtCore . QRect ( 0 , 0 , 0 , 0 ) ) if crop : rect = widget . rect ( ) if crop . width ( ) : rect . setWidth ( crop . width ( ) ) if crop . height ( ) : rect . setHeight ( crop . height ( ) ) if crop . x ( ) : rect . setX ( rect . width ( ) - crop . x ( ) ) if crop . y ( ) : rect . setY ( rect . height ( ) - crop . y ( ) ) pixmap = QtGui . QPixmap . grabWidget ( widget , rect ) else : pixmap = QtGui . QPixmap . grabWidget ( widget ) scaled = self . property ( 'scaled' ) if scaled : pixmap = pixmap . scaled ( pixmap . width ( ) * scaled , pixmap . height ( ) * scaled , QtCore . Qt . KeepAspectRatio , QtCore . Qt . SmoothTransformation ) kwds = { } kwds [ 'whatsThis' ] = widget . whatsThis ( ) kwds [ 'toolTip' ] = widget . toolTip ( ) kwds [ 'windowTitle' ] = widget . windowTitle ( ) kwds [ 'objectName' ] = widget . objectName ( ) self . setProperty ( 'caption' , self . property ( 'caption' , '' ) . format ( * * kwds ) ) self . setProperty ( 'pixmap' , pixmap ) self . addPixmap ( pixmap ) return super ( XWalkthroughSnapshot , self ) . prepare ( ) | Prepares the information for this graphic . | 578 | 8 |
11,127 | def get_real_layer_path ( self , path ) : filename = path . split ( '/' ) [ - 1 ] local_path = path filetype = os . path . splitext ( filename ) [ 1 ] # Url if re . match ( r'^[a-zA-Z]+://' , path ) : local_path = os . path . join ( DATA_DIRECTORY , filename ) if not os . path . exists ( local_path ) : sys . stdout . write ( '* Downloading %s...\n' % filename ) self . download_file ( path , local_path ) elif self . args . redownload : os . remove ( local_path ) sys . stdout . write ( '* Redownloading %s...\n' % filename ) self . download_file ( path , local_path ) # Non-existant file elif not os . path . exists ( local_path ) : raise Exception ( '%s does not exist' % local_path ) real_path = path # Zip files if filetype == '.zip' : slug = os . path . splitext ( filename ) [ 0 ] real_path = os . path . join ( DATA_DIRECTORY , slug ) if not os . path . exists ( real_path ) : sys . stdout . write ( '* Unzipping...\n' ) self . unzip_file ( local_path , real_path ) return real_path | Get the path the actual layer file . | 320 | 8 |
11,128 | def download_file ( self , url , local_path ) : response = requests . get ( url , stream = True ) with open ( local_path , 'wb' ) as f : for chunk in tqdm ( response . iter_content ( chunk_size = 1024 ) , unit = 'KB' ) : if chunk : # filter out keep-alive new chunks f . write ( chunk ) f . flush ( ) | Download a file from a remote host . | 90 | 8 |
11,129 | def unzip_file ( self , zip_path , output_path ) : with zipfile . ZipFile ( zip_path , 'r' ) as z : z . extractall ( output_path ) | Unzip a local file into a specified directory . | 44 | 10 |
11,130 | def process_ogr2ogr ( self , name , layer , input_path ) : output_path = os . path . join ( TEMP_DIRECTORY , '%s.json' % name ) if os . path . exists ( output_path ) : os . remove ( output_path ) ogr2ogr_cmd = [ 'ogr2ogr' , '-f' , 'GeoJSON' , '-clipsrc' , self . config [ 'bbox' ] ] if 'where' in layer : ogr2ogr_cmd . extend ( [ '-where' , '"%s"' % layer [ 'where' ] ] ) ogr2ogr_cmd . extend ( [ output_path , input_path ] ) sys . stdout . write ( '* Running ogr2ogr\n' ) if self . args . verbose : sys . stdout . write ( ' %s\n' % ' ' . join ( ogr2ogr_cmd ) ) r = envoy . run ( ' ' . join ( ogr2ogr_cmd ) ) if r . status_code != 0 : sys . stderr . write ( r . std_err ) return output_path | Process a layer using ogr2ogr . | 269 | 10 |
11,131 | def process_topojson ( self , name , layer , input_path ) : output_path = os . path . join ( TEMP_DIRECTORY , '%s.topojson' % name ) # Use local topojson binary topojson_binary = 'node_modules/bin/topojson' if not os . path . exists ( topojson_binary ) : # try with global topojson binary topojson_binary = 'topojson' topo_cmd = [ topojson_binary , '-o' , output_path ] if 'id-property' in layer : topo_cmd . extend ( [ '--id-property' , layer [ 'id-property' ] ] ) if layer . get ( 'all-properties' , False ) : topo_cmd . append ( '-p' ) elif 'properties' in layer : topo_cmd . extend ( [ '-p' , ',' . join ( layer [ 'properties' ] ) ] ) topo_cmd . extend ( [ '--' , input_path ] ) sys . stdout . write ( '* Running TopoJSON\n' ) if self . args . verbose : sys . stdout . write ( ' %s\n' % ' ' . join ( topo_cmd ) ) r = envoy . run ( ' ' . join ( topo_cmd ) ) if r . status_code != 0 : sys . stderr . write ( r . std_err ) return output_path | Process layer using topojson . | 331 | 7 |
11,132 | def merge ( self , paths ) : # Use local topojson binary topojson_binary = 'node_modules/bin/topojson' if not os . path . exists ( topojson_binary ) : # try with global topojson binary topojson_binary = 'topojson' merge_cmd = '%(binary)s -o %(output_path)s --bbox -p -- %(paths)s' % { 'output_path' : self . args . output_path , 'paths' : ' ' . join ( paths ) , 'binary' : topojson_binary } sys . stdout . write ( 'Merging layers\n' ) if self . args . verbose : sys . stdout . write ( ' %s\n' % merge_cmd ) r = envoy . run ( merge_cmd ) if r . status_code != 0 : sys . stderr . write ( r . std_err ) | Merge data layers into a single topojson file . | 211 | 12 |
11,133 | def createMenu ( self ) : name , accepted = QInputDialog . getText ( self , 'Create Menu' , 'Name: ' ) if ( accepted ) : self . addMenuItem ( self . createMenuItem ( name ) , self . uiMenuTREE . currentItem ( ) ) | Creates a new menu with the given name . | 63 | 10 |
11,134 | def removeItem ( self ) : item = self . uiMenuTREE . currentItem ( ) if ( not item ) : return opts = QMessageBox . Yes | QMessageBox . No answer = QMessageBox . question ( self , 'Remove Item' , 'Are you sure you want to remove this ' ' item?' , opts ) if ( answer == QMessageBox . Yes ) : parent = item . parent ( ) if ( parent ) : parent . takeChild ( parent . indexOfChild ( item ) ) else : tree = self . uiMenuTREE tree . takeTopLevelItem ( tree . indexOfTopLevelItem ( item ) ) | Removes the item from the menu . | 140 | 8 |
11,135 | def renameMenu ( self ) : item = self . uiMenuTREE . currentItem ( ) name , accepted = QInputDialog . getText ( self , 'Rename Menu' , 'Name:' , QLineEdit . Normal , item . text ( 0 ) ) if ( accepted ) : item . setText ( 0 , name ) | Prompts the user to supply a new name for the menu . | 71 | 14 |
11,136 | def showMenu ( self ) : item = self . uiMenuTREE . currentItem ( ) menu = QMenu ( self ) act = menu . addAction ( 'Add Menu...' ) act . setIcon ( QIcon ( projexui . resources . find ( 'img/folder.png' ) ) ) act . triggered . connect ( self . createMenu ) if ( item and item . data ( 0 , Qt . UserRole ) == 'menu' ) : act = menu . addAction ( 'Rename Menu...' ) ico = QIcon ( projexui . resources . find ( 'img/edit.png' ) ) act . setIcon ( ico ) act . triggered . connect ( self . renameMenu ) act = menu . addAction ( 'Add Separator' ) act . setIcon ( QIcon ( projexui . resources . find ( 'img/ui/splitter.png' ) ) ) act . triggered . connect ( self . createSeparator ) menu . addSeparator ( ) act = menu . addAction ( 'Remove Item' ) act . setIcon ( QIcon ( projexui . resources . find ( 'img/remove.png' ) ) ) act . triggered . connect ( self . removeItem ) act . setEnabled ( item is not None ) menu . exec_ ( QCursor . pos ( ) ) | Creates a menu to display for the editing of template information . | 294 | 13 |
11,137 | def init_app ( self , app ) : host = app . config . get ( 'STATS_HOSTNAME' , 'localhost' ) port = app . config . get ( 'STATS_PORT' , 8125 ) base_key = app . config . get ( 'STATS_BASE_KEY' , app . name ) client = _StatsClient ( host = host , port = port , prefix = base_key , ) app . before_request ( client . flask_time_start ) app . after_request ( client . flask_time_end ) if not hasattr ( app , 'extensions' ) : app . extensions = { } app . extensions . setdefault ( 'stats' , { } ) app . extensions [ 'stats' ] [ self ] = client return client | Inititialise the extension with the app object . | 170 | 10 |
11,138 | def depends ( func = None , after = None , before = None , priority = None ) : if not ( func is None or inspect . ismethod ( func ) or inspect . isfunction ( func ) ) : raise ValueError ( "depends decorator can only be used on functions or methods" ) if not ( after or before or priority ) : raise ValueError ( "depends decorator needs at least one argument" ) # This avoids some nesting in the decorator # If called without func the decorator was called with optional args # so we'll return a function with those args filled in. if func is None : return partial ( depends , after = after , before = before , priority = priority ) def self_check ( a , b ) : if a == b : raise ValueError ( "Test '{}' cannot depend on itself" . format ( a ) ) def handle_dep ( conditions , _before = True ) : if conditions : if type ( conditions ) is not list : conditions = [ conditions ] for cond in conditions : if hasattr ( cond , '__call__' ) : cond = cond . __name__ self_check ( func . __name__ , cond ) if _before : soft_dependencies [ cond ] . add ( func . __name__ ) else : dependencies [ func . __name__ ] . add ( cond ) handle_dep ( before ) handle_dep ( after , False ) if priority : priorities [ func . __name__ ] = priority @ wraps ( func ) def inner ( * args , * * kwargs ) : return func ( * args , * * kwargs ) return inner | Decorator to specify test dependencies | 343 | 7 |
11,139 | def split_on_condition ( seq , condition ) : l1 , l2 = tee ( ( condition ( item ) , item ) for item in seq ) return ( i for p , i in l1 if p ) , ( i for p , i in l2 if not p ) | Split a sequence into two iterables without looping twice | 60 | 11 |
11,140 | def prepare_suite ( self , suite ) : all_tests = { } for s in suite : m = re . match ( r'(\w+)\s+\(.+\)' , str ( s ) ) if m : name = m . group ( 1 ) else : name = str ( s ) . split ( '.' ) [ - 1 ] all_tests [ name ] = s return self . orderTests ( all_tests , suite ) | Prepare suite and determine test ordering | 98 | 7 |
11,141 | def dependency_ran ( self , test ) : for d in ( self . test_name ( i ) for i in dependencies [ test ] ) : if d not in self . ok_results : return "Required test '{}' did not run (does it exist?)" . format ( d ) return None | Returns an error string if any of the dependencies did not run | 65 | 12 |
11,142 | def class_path ( cls ) : if cls . __module__ == '__main__' : path = None else : path = os . path . dirname ( inspect . getfile ( cls ) ) if not path : path = os . getcwd ( ) return os . path . realpath ( path ) | Return the path to the source file of the given class . | 69 | 12 |
11,143 | def caller_path ( steps = 1 ) : frame = sys . _getframe ( steps + 1 ) try : path = os . path . dirname ( frame . f_code . co_filename ) finally : del frame if not path : path = os . getcwd ( ) return os . path . realpath ( path ) | Return the path to the source file of the current frames caller . | 70 | 13 |
11,144 | def resource ( self , * resources ) : resources = tuple ( self . resources ) + resources return Resource ( self . client , resources ) | Resource builder with resources url | 28 | 5 |
11,145 | def match ( self , version ) : if isinstance ( version , basestring ) : version = Version . parse ( version ) return self . operator ( version , self . version ) | Match version with the constraint . | 38 | 6 |
11,146 | def warnings ( filename , board = 'pro' , hwpack = 'arduino' , mcu = '' , f_cpu = '' , extra_lib = '' , ver = '' , # home='auto', backend = 'arscons' , ) : cc = Arduino ( board = board , hwpack = hwpack , mcu = mcu , f_cpu = f_cpu , extra_lib = extra_lib , ver = ver , # home=home, backend = backend , ) cc . build ( filename ) print 'backend:' , cc . backend print 'MCU:' , cc . mcu_compiler ( ) # print 'avr-gcc:', AvrGcc().version() print print ( '=============================================' ) print ( 'SIZE' ) print ( '=============================================' ) print 'program:' , cc . size ( ) . program_bytes print 'data:' , cc . size ( ) . data_bytes core_warnings = [ x for x in cc . warnings if 'gcc' in x ] + [ x for x in cc . warnings if 'core' in x ] lib_warnings = [ x for x in cc . warnings if 'lib_' in x ] notsketch_warnings = core_warnings + lib_warnings sketch_warnings = [ x for x in cc . warnings if x not in notsketch_warnings ] print print ( '=============================================' ) print ( 'WARNINGS' ) print ( '=============================================' ) print print ( 'core' ) print ( '-------------------' ) print ( '\n' . join ( core_warnings ) ) print print ( 'lib' ) print ( '-------------------' ) print ( '\n' . join ( lib_warnings ) ) print print ( 'sketch' ) print ( '-------------------' ) print ( '\n' . join ( sketch_warnings ) ) | build Arduino sketch and display results | 415 | 6 |
11,147 | def accept ( self ) : if ( not self . save ( ) ) : return for i in range ( self . uiActionTREE . topLevelItemCount ( ) ) : item = self . uiActionTREE . topLevelItem ( i ) action = item . action ( ) action . setShortcut ( QKeySequence ( item . text ( 1 ) ) ) super ( XShortcutDialog , self ) . accept ( ) | Saves the current settings for the actions in the list and exits the dialog . | 93 | 16 |
11,148 | def clear ( self ) : item = self . uiActionTREE . currentItem ( ) if ( not item ) : return self . uiShortcutTXT . setText ( '' ) item . setText ( 1 , '' ) | Clears the current settings for the current action . | 50 | 10 |
11,149 | def updateAction ( self ) : item = self . uiActionTREE . currentItem ( ) if ( item ) : action = item . action ( ) else : action = QAction ( ) self . uiShortcutTXT . setText ( action . shortcut ( ) . toString ( ) ) | Updates the action to edit based on the current item . | 64 | 12 |
11,150 | def declassify ( to_remove , * args , * * kwargs ) : def argdecorate ( fn ) : """ enable the to_remove argument to the decorator. """ # wrap the function to get the original docstring @ wraps ( fn ) def declassed ( * args , * * kwargs ) : # call the method ret = fn ( * args , * * kwargs ) # catch errors that are thrown by the api try : # ensure that ret is a list if type ( ret ) is list : return [ r [ to_remove ] for r in ret ] return ret [ to_remove ] except KeyError : return ret return declassed return argdecorate | flatten the return values of the mite api . | 144 | 11 |
11,151 | def clean_dict ( d ) : ktd = list ( ) for k , v in d . items ( ) : if not v : ktd . append ( k ) elif type ( v ) is dict : d [ k ] = clean_dict ( v ) for k in ktd : d . pop ( k ) return d | remove the keys with None values . | 70 | 7 |
11,152 | def load ( self ) : if self . _loaded : return self . setChildIndicatorPolicy ( self . DontShowIndicatorWhenChildless ) self . _loaded = True column = self . schemaColumn ( ) if not column . isReference ( ) : return ref = column . referenceModel ( ) if not ref : return columns = sorted ( ref . schema ( ) . columns ( ) , key = lambda x : x . name ( ) . strip ( '_' ) ) for column in columns : XOrbColumnItem ( self , column ) | Loads the children for this item . | 116 | 8 |
11,153 | def refresh ( self ) : self . setUpdatesEnabled ( False ) self . blockSignals ( True ) self . clear ( ) tableType = self . tableType ( ) if not tableType : self . setUpdatesEnabled ( True ) self . blockSignals ( False ) return schema = tableType . schema ( ) columns = list ( sorted ( schema . columns ( ) , key = lambda x : x . name ( ) . strip ( '_' ) ) ) for column in columns : XOrbColumnItem ( self , column ) self . setUpdatesEnabled ( True ) self . blockSignals ( False ) | Resets the data for this navigator . | 131 | 9 |
11,154 | def acceptColumn ( self ) : self . navigator ( ) . hide ( ) self . lineEdit ( ) . setText ( self . navigator ( ) . currentSchemaPath ( ) ) self . emitSchemaColumnChanged ( self . navigator ( ) . currentColumn ( ) ) | Accepts the current item as the current column . | 61 | 10 |
11,155 | def showPopup ( self ) : nav = self . navigator ( ) nav . move ( self . mapToGlobal ( QPoint ( 0 , self . height ( ) ) ) ) nav . resize ( 400 , 250 ) nav . show ( ) | Displays the popup associated with this navigator . | 52 | 10 |
11,156 | def sha256 ( content ) : if isinstance ( content , str ) : content = content . encode ( 'utf-8' ) return hashlib . sha256 ( content ) . hexdigest ( ) | Finds the sha256 hash of the content . | 45 | 11 |
11,157 | def cursor ( self , as_dict = False ) : self . ensure_connect ( ) ctype = self . real_ctype ( as_dict ) return self . _connect . cursor ( ctype ) | Gets the cursor by type if as_dict is ture make a dict sql connection cursor | 44 | 19 |
11,158 | def members ( self ) : resp = self . _rtm_client . get ( 'v1/current_team.members?all=true' ) if resp . is_fail ( ) : raise RTMServiceError ( 'Failed to get members of current team' , resp ) return resp . data [ 'result' ] | Gets members of current team | 71 | 6 |
11,159 | def channels ( self ) : resp = self . _rtm_client . get ( 'v1/current_team.channels' ) if resp . is_fail ( ) : raise RTMServiceError ( 'Failed to get channels of current team' , resp ) return resp . data [ 'result' ] | Gets channels of current team | 68 | 6 |
11,160 | def info ( self , user_id ) : resp = self . _rtm_client . get ( 'v1/user.info?user_id={}' . format ( user_id ) ) if resp . is_fail ( ) : raise RTMServiceError ( 'Failed to get user information' , resp ) return resp . data [ 'result' ] | Gets user information by user id | 80 | 7 |
11,161 | def info ( self , channel_id ) : resource = 'v1/channel.info?channel_id={}' . format ( channel_id ) resp = self . _rtm_client . get ( resource ) if resp . is_fail ( ) : raise RTMServiceError ( "Failed to get channel information" , resp ) return resp . data [ 'result' ] | Gets channel information by channel id | 83 | 7 |
11,162 | def _transform_to_dict ( result ) : result_dict = { } property_list = result . item for item in property_list : result_dict [ item . key [ 0 ] ] = item . value [ 0 ] return result_dict | Transform the array from Ideone into a Python dictionary . | 53 | 11 |
11,163 | def _collapse_language_array ( language_array ) : language_dict = { } for language in language_array . item : key = language . key [ 0 ] value = language . value [ 0 ] language_dict [ key ] = value return language_dict | Convert the Ideone language list into a Python dictionary . | 57 | 12 |
11,164 | def _translate_language_name ( self , language_name ) : languages = self . languages ( ) language_id = None # Check for exact match first including the whole version # string for ideone_index , ideone_language in languages . items ( ) : if ideone_language . lower ( ) == language_name . lower ( ) : return ideone_index # Check for a match of just the language name without any # version information simple_languages = dict ( ( k , v . split ( '(' ) [ 0 ] . strip ( ) ) for ( k , v ) in languages . items ( ) ) for ideone_index , simple_name in simple_languages . items ( ) : if simple_name . lower ( ) == language_name . lower ( ) : return ideone_index # Give up, but first find a similar name, suggest it and error # out language_choices = languages . values ( ) + simple_languages . values ( ) similar_choices = difflib . get_close_matches ( language_name , language_choices , n = 3 , cutoff = 0.3 ) # Add quotes and delimit with strings for easier to read # output similar_choices_string = ", " . join ( [ "'" + s + "'" for s in similar_choices ] ) error_string = ( "Couldn't match '%s' to an Ideone accepted language.\n" "Did you mean one of the following: %s" ) raise IdeoneError ( error_string % ( language_name , similar_choices_string ) ) | Translate a human readable langauge name into its Ideone integer representation . | 346 | 16 |
11,165 | def create_submission ( self , source_code , language_name = None , language_id = None , std_input = "" , run = True , private = False ) : language_id = language_id or self . _translate_language_name ( language_name ) result = self . client . service . createSubmission ( self . user , self . password , source_code , language_id , std_input , run , private ) result_dict = Ideone . _transform_to_dict ( result ) Ideone . _handle_error ( result_dict ) return result_dict | Create a submission and upload it to Ideone . | 129 | 10 |
11,166 | def submission_status ( self , link ) : result = self . client . service . getSubmissionStatus ( self . user , self . password , link ) result_dict = Ideone . _transform_to_dict ( result ) Ideone . _handle_error ( result_dict ) return result_dict | Given the unique link of a submission returns its current status . | 65 | 12 |
11,167 | def submission_details ( self , link , with_source = True , with_input = True , with_output = True , with_stderr = True , with_compilation_info = True ) : result = self . client . service . getSubmissionDetails ( self . user , self . password , link , with_source , with_input , with_output , with_stderr , with_compilation_info ) result_dict = Ideone . _transform_to_dict ( result ) Ideone . _handle_error ( result_dict ) return result_dict | Return a dictionary of requested details about a submission with the id of link . | 125 | 15 |
11,168 | def languages ( self ) : if self . _language_dict is None : result = self . client . service . getLanguages ( self . user , self . password ) result_dict = Ideone . _transform_to_dict ( result ) Ideone . _handle_error ( result_dict ) languages = result_dict [ 'languages' ] result_dict [ 'languages' ] = Ideone . _collapse_language_array ( languages ) self . _language_dict = result_dict [ 'languages' ] return self . _language_dict | Get a list of supported languages and cache it . | 121 | 10 |
11,169 | def is_binary ( filename ) : with open ( filename , 'rb' ) as fp : data = fp . read ( 1024 ) if not data : return False if b'\0' in data : return True return False | Returns True if the file is binary | 49 | 7 |
11,170 | def walk_files ( args , root , directory , action ) : for entry in os . listdir ( directory ) : if is_hidden ( args , entry ) : continue if is_excluded_directory ( args , entry ) : continue if is_in_default_excludes ( entry ) : continue if not is_included ( args , entry ) : continue if is_excluded ( args , entry , directory ) : continue entry = os . path . join ( directory , entry ) if os . path . isdir ( entry ) : walk_files ( args , root , entry , action ) if os . path . isfile ( entry ) : if is_binary ( entry ) : continue action ( entry ) | Recusively go do the subdirectories of the directory calling the action on each file | 150 | 18 |
11,171 | def main ( args = None ) : parser = ArgumentParser ( usage = __usage__ ) parser . add_argument ( "--no-skip-hidden" , action = "store_false" , dest = "skip_hidden" , help = "Do not skip hidden files. " "Use this if you know what you are doing..." ) parser . add_argument ( "--include" , dest = "includes" , action = "append" , help = "Only replace in files matching theses patterns" ) parser . add_argument ( "--exclude" , dest = "excludes" , action = "append" , help = "Ignore files matching theses patterns" ) parser . add_argument ( "--backup" , action = "store_true" , dest = "backup" , help = "Create a backup for each file. " "By default, files are modified in place" ) parser . add_argument ( "--go" , action = "store_true" , dest = "go" , help = "Perform changes rather than just printing then" ) parser . add_argument ( "--dry-run" , "-n" , action = "store_false" , dest = "go" , help = "Do not change anything. This is the default" ) parser . add_argument ( "--color" , choices = [ "always" , "never" , "auto" ] , help = "When to colorize the output. " "Default: when output is a tty" ) parser . add_argument ( "--no-color" , action = "store_false" , dest = "color" , help = "Do not colorize output" ) parser . add_argument ( "--quiet" , "-q" , action = "store_true" , dest = "quiet" , help = "Do not produce any output" ) parser . add_argument ( "pattern" ) parser . add_argument ( "replacement" ) parser . add_argument ( "paths" , nargs = "*" ) parser . set_defaults ( includes = list ( ) , excludes = list ( ) , skip_hidden = True , backup = False , go = False , color = "auto" , quiet = False , ) args = parser . parse_args ( args = args ) setup_colors ( args ) repl_main ( args ) | manages options when called from command line | 510 | 8 |
11,172 | def load ( self ) : if self . _loaded : return self . _loaded = True self . setChildIndicatorPolicy ( self . DontShowIndicatorWhenChildless ) if not self . isFolder ( ) : return path = self . filepath ( ) if not os . path . isdir ( path ) : path = os . path . dirname ( path ) for name in os . listdir ( path ) : # ignore 'hidden' folders if name . startswith ( '_' ) and not name . startswith ( '__' ) : continue # ignore special cases (only want modules for this) if '-' in name : continue # use the index or __init__ information if name in ( 'index.html' , '__init__.html' ) : self . _url = 'file:///%s/%s' % ( path , name ) continue # otherwise, load a childitem filepath = os . path . join ( path , name ) folder = os . path . isdir ( filepath ) XdkEntryItem ( self , filepath , folder = folder ) | Loads this item . | 235 | 5 |
11,173 | def get_version ( module ) : version_names = [ "__version__" , "get_version" , "version" ] version_names . extend ( [ name . upper ( ) for name in version_names ] ) for name in version_names : try : version = getattr ( module , name ) except AttributeError : continue if callable ( version ) : version = version ( ) try : version = "." . join ( [ str ( i ) for i in version . __iter__ ( ) ] ) except AttributeError : pass return version | Attempts to read a version attribute from the given module that could be specified via several different names and formats . | 119 | 21 |
11,174 | def get_setup_attribute ( attribute , setup_path ) : args = [ "python" , setup_path , "--%s" % attribute ] return Popen ( args , stdout = PIPE ) . communicate ( ) [ 0 ] . decode ( 'utf-8' ) . strip ( ) | Runs the project s setup . py script in a process with an arg that will print out the value for a particular attribute such as author or version and returns the value . | 66 | 35 |
11,175 | def fetch_items ( self , category , * * kwargs ) : from_date = kwargs [ 'from_date' ] logger . info ( "Fetching modules from %s" , str ( from_date ) ) from_date_ts = datetime_to_utc ( from_date ) . timestamp ( ) nmodules = 0 stop_fetching = False raw_pages = self . client . modules ( ) for raw_modules in raw_pages : modules = [ mod for mod in self . parse_json ( raw_modules ) ] for module in modules : # Check timestamps to stop fetching more modules # because modules fetched sorted by 'updated_at' # from newest to oldest. updated_at_ts = self . metadata_updated_on ( module ) if from_date_ts > updated_at_ts : stop_fetching = True break owner = module [ 'owner' ] [ 'username' ] name = module [ 'name' ] module [ 'releases' ] = self . __fetch_and_parse_releases ( owner , name ) module [ 'owner_data' ] = self . __get_or_fetch_owner ( owner ) yield module nmodules += 1 if stop_fetching : break logger . info ( "Fetch process completed: %s modules fetched" , nmodules ) | Fetch the modules | 296 | 4 |
11,176 | def parse_json ( raw_json ) : result = json . loads ( raw_json ) if 'results' in result : result = result [ 'results' ] return result | Parse a Puppet forge JSON stream . | 37 | 8 |
11,177 | def modules ( self ) : resource = self . RMODULES params = { self . PLIMIT : self . max_items , self . PSORT_BY : self . VLATEST_RELEASE } for page in self . _fetch ( resource , params ) : yield page | Fetch modules pages . | 62 | 5 |
11,178 | def releases ( self , owner , module ) : resource = self . RRELEASES params = { self . PMODULE : owner + '-' + module , self . PLIMIT : self . max_items , self . PSHOW_DELETED : 'true' , self . PSORT_BY : self . VRELEASE_DATE , } for page in self . _fetch ( resource , params ) : yield page | Fetch the releases of a module . | 93 | 8 |
11,179 | def reset_tree ( self ) : self . tree = { } self . tree [ 'leaves' ] = [ ] self . tree [ 'levels' ] = [ ] self . tree [ 'is_ready' ] = False | Resets the current tree to empty . | 49 | 8 |
11,180 | def add_leaves ( self , values_array , do_hash = False ) : self . tree [ 'is_ready' ] = False [ self . _add_leaf ( value , do_hash ) for value in values_array ] | Add leaves to the tree . | 52 | 6 |
11,181 | def make_tree ( self ) : self . tree [ 'is_ready' ] = False leaf_count = len ( self . tree [ 'leaves' ] ) if leaf_count > 0 : # skip this whole process if there are no leaves added to the tree self . _unshift ( self . tree [ 'levels' ] , self . tree [ 'leaves' ] ) while len ( self . tree [ 'levels' ] [ 0 ] ) > 1 : self . _unshift ( self . tree [ 'levels' ] , self . _calculate_next_level ( ) ) self . tree [ 'is_ready' ] = True | Generates the merkle tree . | 140 | 8 |
11,182 | def duration_to_timedelta ( obj ) : matches = DURATION_PATTERN . search ( obj ) matches = matches . groupdict ( default = "0" ) matches = { k : int ( v ) for k , v in matches . items ( ) } return timedelta ( * * matches ) | Converts duration to timedelta | 67 | 6 |
11,183 | def timedelta_to_duration ( obj ) : minutes , hours , days = 0 , 0 , 0 seconds = int ( obj . total_seconds ( ) ) if seconds > 59 : minutes = seconds // 60 seconds = seconds % 60 if minutes > 59 : hours = minutes // 60 minutes = minutes % 60 if hours > 23 : days = hours // 24 hours = hours % 24 response = [ ] if days : response . append ( '%sd' % days ) if hours : response . append ( '%sh' % hours ) if minutes : response . append ( '%sm' % minutes ) if seconds or not response : response . append ( '%ss' % seconds ) return "" . join ( response ) | Converts timedelta to duration | 149 | 6 |
11,184 | def create_dm_pkg ( secret , username ) : secret = tools . EncodeString ( secret ) username = tools . EncodeString ( username ) pkg_format = '>HHHH32sHH32s' pkg_vals = [ IK_RAD_PKG_VER , IK_RAD_PKG_AUTH , IK_RAD_PKG_USR_PWD_TAG , len ( secret ) , secret . ljust ( 32 , '\x00' ) , IK_RAD_PKG_CMD_ARGS_TAG , len ( username ) , username . ljust ( 32 , '\x00' ) ] return struct . pack ( pkg_format , * pkg_vals ) | create ikuai dm message | 163 | 7 |
11,185 | def clearBreakpoints ( self ) : self . markerDeleteAll ( self . _breakpointMarker ) if ( not self . signalsBlocked ( ) ) : self . breakpointsChanged . emit ( ) | Clears the file of all the breakpoints . | 43 | 10 |
11,186 | def unindentSelection ( self ) : sel = self . getSelection ( ) for line in range ( sel [ 0 ] , sel [ 2 ] + 1 ) : self . unindent ( line ) | Unindents the current selected text . | 48 | 8 |
11,187 | def _removePunctuation ( text_string ) : try : return text_string . translate ( None , _punctuation ) except TypeError : return text_string . translate ( str . maketrans ( '' , '' , _punctuation ) ) | Removes punctuation symbols from a string . | 56 | 9 |
11,188 | def _removeStopwords ( text_list ) : output_list = [ ] for word in text_list : if word . lower ( ) not in _stopwords : output_list . append ( word ) return output_list | Removes stopwords contained in a list of words . | 48 | 11 |
11,189 | def getBlocks ( sentences , n ) : blocks = [ ] for i in range ( 0 , len ( sentences ) , n ) : blocks . append ( sentences [ i : ( i + n ) ] ) return blocks | Get blocks of n sentences together . | 45 | 7 |
11,190 | def __destroyLockedView ( self ) : if self . _lockedView : self . _lockedView . close ( ) self . _lockedView . deleteLater ( ) self . _lockedView = None | Destroys the locked view from this widget . | 43 | 10 |
11,191 | def clear ( self ) : # go through and properly destroy all the items for this tree for item in self . traverseItems ( ) : if isinstance ( item , XTreeWidgetItem ) : item . destroy ( ) super ( XTreeWidget , self ) . clear ( ) | Removes all the items from this tree widget . This will go through and also destroy any XTreeWidgetItems prior to the model clearing its references . | 57 | 30 |
11,192 | def exportAs ( self , action ) : plugin = self . exporter ( unwrapVariant ( action . data ( ) ) ) if not plugin : return False ftypes = '{0} (*{1});;All Files (*.*)' . format ( plugin . name ( ) , plugin . filetype ( ) ) filename = QtGui . QFileDialog . getSaveFileName ( self . window ( ) , 'Export Data' , '' , ftypes ) if type ( filename ) == tuple : filename = filename [ 0 ] if filename : return self . export ( nativestring ( filename ) , exporter = plugin ) return False | Prompts the user to export the information for this tree based on the available exporters . | 135 | 19 |
11,193 | def headerHideColumn ( self ) : self . setColumnHidden ( self . _headerIndex , True ) # ensure we at least have 1 column visible found = False for col in range ( self . columnCount ( ) ) : if ( not self . isColumnHidden ( col ) ) : found = True break if ( not found ) : self . setColumnHidden ( 0 , False ) | Hides the current column set by the header index . | 80 | 11 |
11,194 | def headerSortAscending ( self ) : self . setSortingEnabled ( True ) self . sortByColumn ( self . _headerIndex , QtCore . Qt . AscendingOrder ) | Sorts the column at the current header index by ascending order . | 40 | 13 |
11,195 | def headerSortDescending ( self ) : self . setSortingEnabled ( True ) self . sortByColumn ( self . _headerIndex , QtCore . Qt . DescendingOrder ) | Sorts the column at the current header index by descending order . | 39 | 13 |
11,196 | def highlightByAlternate ( self ) : palette = QtGui . QApplication . palette ( ) palette . setColor ( palette . HighlightedText , palette . color ( palette . Text ) ) clr = palette . color ( palette . AlternateBase ) palette . setColor ( palette . Highlight , clr . darker ( 110 ) ) self . setPalette ( palette ) | Sets the palette highlighting for this tree widget to use a darker version of the alternate color vs . the standard highlighting . | 80 | 24 |
11,197 | def smartResizeColumnsToContents ( self ) : self . blockSignals ( True ) self . setUpdatesEnabled ( False ) header = self . header ( ) header . blockSignals ( True ) columns = range ( self . columnCount ( ) ) sizes = [ self . columnWidth ( c ) for c in columns ] header . resizeSections ( header . ResizeToContents ) for col in columns : width = self . columnWidth ( col ) if ( width < sizes [ col ] ) : self . setColumnWidth ( col , sizes [ col ] ) header . blockSignals ( False ) self . setUpdatesEnabled ( True ) self . blockSignals ( False ) | Resizes the columns to the contents based on the user preferences . | 146 | 13 |
11,198 | def gevent_run ( app , monkey_patch = True , start = True , debug = False , * * kwargs ) : # pragma: no cover if monkey_patch : from gevent import monkey monkey . patch_all ( ) import gevent gevent . spawn ( app . run , debug = debug , * * kwargs ) if start : while not app . stopped : gevent . sleep ( 0.1 ) | Run your app in gevent . spawn run simple loop if start == True | 92 | 15 |
11,199 | def dict_update ( d , u ) : for k , v in six . iteritems ( u ) : if isinstance ( v , collections . Mapping ) : r = dict_update ( d . get ( k , { } ) , v ) d [ k ] = r else : d [ k ] = u [ k ] return d | Recursive dict update | 72 | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.