idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
10,800 | def parse_dge ( dge_path : str , entrez_id_header : str , log2_fold_change_header : str , adj_p_header : str , entrez_delimiter : str , base_mean_header : Optional [ str ] = None ) -> List [ Gene ] : if dge_path . endswith ( '.xlsx' ) : return parsers . parse_excel ( dge_path , entrez_id_header = entrez_id_header , log_fold_change_header = log2_fold_change_header , adjusted_p_value_header = adj_p_header , entrez_delimiter = entrez_delimiter , base_mean_header = base_mean_header , ) if dge_path . endswith ( '.csv' ) : return parsers . parse_csv ( dge_path , entrez_id_header = entrez_id_header , log_fold_change_header = log2_fold_change_header , adjusted_p_value_header = adj_p_header , entrez_delimiter = entrez_delimiter , base_mean_header = base_mean_header , ) if dge_path . endswith ( '.tsv' ) : return parsers . parse_csv ( dge_path , entrez_id_header = entrez_id_header , log_fold_change_header = log2_fold_change_header , adjusted_p_value_header = adj_p_header , entrez_delimiter = entrez_delimiter , base_mean_header = base_mean_header , sep = "\t" ) raise ValueError ( f'Unsupported extension: {dge_path}' ) | Parse a differential expression file . | 396 | 7 |
10,801 | def _load ( self , file_path : Text ) -> None : # noinspection PyUnresolvedReferences module_ = types . ModuleType ( 'settings' ) module_ . __file__ = file_path try : with open ( file_path , encoding = 'utf-8' ) as f : exec ( compile ( f . read ( ) , file_path , 'exec' ) , module_ . __dict__ ) except IOError as e : e . strerror = 'Unable to load configuration file ({})' . format ( e . strerror ) raise for key in dir ( module_ ) : if CONFIG_ATTR . match ( key ) : self [ key ] = getattr ( module_ , key ) | Load the configuration from a plain Python file . This file is executed on its own . | 157 | 17 |
10,802 | def _settings ( self ) -> Settings : if self . __dict__ [ '__settings' ] is None : self . __dict__ [ '__settings' ] = Settings ( ) for file_path in self . _get_files ( ) : if file_path : # noinspection PyProtectedMember self . __dict__ [ '__settings' ] . _load ( file_path ) return self . __dict__ [ '__settings' ] | Return the actual settings object or create it if missing . | 97 | 11 |
10,803 | async def _start ( self , key : Text ) -> None : for _ in range ( 0 , 1000 ) : with await self . pool as r : just_set = await r . set ( self . lock_key ( key ) , '' , expire = settings . REGISTER_LOCK_TIME , exist = r . SET_IF_NOT_EXIST , ) if just_set : break await asyncio . sleep ( settings . REDIS_POLL_INTERVAL ) | Start the lock . | 101 | 4 |
10,804 | async def _get ( self , key : Text ) -> Dict [ Text , Any ] : try : with await self . pool as r : return ujson . loads ( await r . get ( self . register_key ( key ) ) ) except ( ValueError , TypeError ) : return { } | Get the value for the key . It is automatically deserialized from JSON and returns an empty dictionary by default . | 64 | 23 |
10,805 | async def _replace ( self , key : Text , data : Dict [ Text , Any ] ) -> None : with await self . pool as r : await r . set ( self . register_key ( key ) , ujson . dumps ( data ) ) | Replace the register with a new value . | 55 | 9 |
10,806 | def getFileName ( self , suffix = None , extension = "jar" ) : assert ( self . _artifactId is not None ) assert ( self . _version is not None ) return "{0}-{1}{2}{3}" . format ( self . _artifactId , self . _version . getRawString ( ) , "-" + suffix . lstrip ( "-" ) if suffix is not None else "" , "." + extension . lstrip ( "." ) if extension is not None else "" ) | Returns the basename of the artifact s file using Maven s conventions . | 111 | 15 |
10,807 | def getPath ( self , suffix = None , extension = "jar" , separator = os . sep ) : assert ( self . _groupId is not None ) resultComponents = [ self . _groupId . replace ( "." , separator ) ] if self . _artifactId is not None : resultComponents . append ( self . _artifactId ) version = self . _version if version is not None : resultComponents . append ( version . getRawString ( ) ) resultComponents . append ( self . getFileName ( suffix , extension ) ) return separator . join ( resultComponents ) | Returns the full path relative to the root of a Maven repository of the current artifact using Maven s conventions . | 132 | 23 |
10,808 | def allele_support_df ( loci , sources ) : return pandas . DataFrame ( allele_support_rows ( loci , sources ) , columns = EXPECTED_COLUMNS ) | Returns a DataFrame of allele counts for all given loci in the read sources | 42 | 16 |
10,809 | def variant_support ( variants , allele_support_df , ignore_missing = False ) : missing = [ c for c in EXPECTED_COLUMNS if c not in allele_support_df . columns ] if missing : raise ValueError ( "Missing columns: %s" % " " . join ( missing ) ) # Ensure our start and end fields are ints. allele_support_df [ [ "interbase_start" , "interbase_end" ] ] = ( allele_support_df [ [ "interbase_start" , "interbase_end" ] ] . astype ( int ) ) sources = sorted ( allele_support_df [ "source" ] . unique ( ) ) allele_support_dict = collections . defaultdict ( dict ) for ( i , row ) in allele_support_df . iterrows ( ) : key = ( row [ 'source' ] , row . contig , row . interbase_start , row . interbase_end ) allele_support_dict [ key ] [ row . allele ] = row [ "count" ] # We want an exception on bad lookups, so convert to a regular dict. allele_support_dict = dict ( allele_support_dict ) dataframe_dicts = collections . defaultdict ( lambda : collections . defaultdict ( list ) ) for variant in variants : for source in sources : key = ( source , variant . contig , variant . start - 1 , variant . end ) try : alleles = allele_support_dict [ key ] except KeyError : message = ( "No allele counts in source %s for variant %s" % ( source , str ( variant ) ) ) if ignore_missing : logging . warning ( message ) alleles = { } else : raise ValueError ( message ) alt = alleles . get ( variant . alt , 0 ) ref = alleles . get ( variant . ref , 0 ) total = sum ( alleles . values ( ) ) other = total - alt - ref dataframe_dicts [ "num_alt" ] [ source ] . append ( alt ) dataframe_dicts [ "num_ref" ] [ source ] . append ( ref ) dataframe_dicts [ "num_other" ] [ source ] . append ( other ) dataframe_dicts [ "total_depth" ] [ source ] . append ( total ) dataframe_dicts [ "alt_fraction" ] [ source ] . append ( float ( alt ) / max ( 1 , total ) ) dataframe_dicts [ "any_alt_fraction" ] [ source ] . append ( float ( alt + other ) / max ( 1 , total ) ) dataframes = dict ( ( label , pandas . DataFrame ( value , index = variants ) ) for ( label , value ) in dataframe_dicts . items ( ) ) return pandas . Panel ( dataframes ) | Collect the read evidence support for the given variants . | 618 | 10 |
10,810 | def sndinfo ( path : str ) -> SndInfo : backend = _getBackend ( path ) logger . debug ( f"sndinfo: using backend {backend.name}" ) return backend . getinfo ( path ) | Get info about a soundfile | 50 | 6 |
10,811 | def asmono ( samples : np . ndarray , channel : Union [ int , str ] = 0 ) -> np . ndarray : if numchannels ( samples ) == 1 : # it could be [1,2,3,4,...], or [[1], [2], [3], [4], ...] if isinstance ( samples [ 0 ] , float ) : return samples elif isinstance ( samples [ 0 ] , np . dnarray ) : return np . reshape ( samples , ( len ( samples ) , ) ) else : raise TypeError ( "Samples should be numeric, found: %s" % str ( type ( samples [ 0 ] ) ) ) if isinstance ( channel , int ) : return samples [ : , channel ] elif channel == 'mix' : return _mix ( samples , scale_by_numchannels = True ) else : raise ValueError ( "channel has to be an integer indicating a channel," " or 'mix' to mix down all channels" ) | convert samples to mono if they are not mono already . | 216 | 12 |
10,812 | def getchannel ( samples : np . ndarray , ch : int ) -> np . ndarray : N = numchannels ( samples ) if ch > ( N - 1 ) : raise ValueError ( "channel %d out of range" % ch ) if N == 1 : return samples return samples [ : , ch ] | Returns a view into a channel of samples . | 69 | 9 |
10,813 | def bitdepth ( data : np . ndarray , snap : bool = True ) -> int : data = asmono ( data ) maxitems = min ( 4096 , data . shape [ 0 ] ) maxbits = max ( x . as_integer_ratio ( ) [ 1 ] for x in data [ : maxitems ] ) . bit_length ( ) if snap : if maxbits <= 8 : maxbits = 8 elif maxbits <= 16 : maxbits = 16 elif maxbits <= 24 : maxbits = 24 elif maxbits <= 32 : maxbits = 32 else : maxbits = 64 return maxbits | returns the number of bits actually used to represent the data . | 132 | 13 |
10,814 | def sndwrite_like ( samples : np . ndarray , likefile : str , outfile : str ) -> None : info = sndinfo ( likefile ) sndwrite ( samples , info . samplerate , outfile , encoding = info . encoding ) | Write samples to outfile with samplerate and encoding taken from likefile | 58 | 15 |
10,815 | def _wavReadData ( fid , size : int , channels : int , encoding : str , bigendian : bool ) -> np . ndarray : bits = int ( encoding [ 3 : ] ) if bits == 8 : data = np . fromfile ( fid , dtype = np . ubyte , count = size ) if channels > 1 : data = data . reshape ( - 1 , channels ) else : bytes = bits // 8 if encoding in ( 'pcm16' , 'pcm32' , 'pcm64' ) : if bigendian : dtype = '>i%d' % bytes else : dtype = '<i%d' % bytes data = np . fromfile ( fid , dtype = dtype , count = size // bytes ) if channels > 1 : data = data . reshape ( - 1 , channels ) elif encoding [ : 3 ] == 'flt' : print ( "flt32!" ) if bits == 32 : if bigendian : dtype = '>f4' else : dtype = '<f4' else : raise NotImplementedError data = np . fromfile ( fid , dtype = dtype , count = size // bytes ) if channels > 1 : data = data . reshape ( - 1 , channels ) elif encoding == 'pcm24' : # this conversion approach is really bad for long files # TODO: do the same but in chunks data = _numpy24to32bit ( np . fromfile ( fid , dtype = np . ubyte , count = size ) , bigendian = False ) if channels > 1 : data = data . reshape ( - 1 , channels ) return data | adapted from scipy . io . wavfile . _read_data_chunk | 363 | 20 |
10,816 | def _wavGetInfo ( f : Union [ IO , str ] ) -> Tuple [ SndInfo , Dict [ str , Any ] ] : if isinstance ( f , ( str , bytes ) ) : f = open ( f , 'rb' ) needsclosing = True else : needsclosing = False fsize , bigendian = _wavReadRiff ( f ) fmt = ">i" if bigendian else "<i" while ( f . tell ( ) < fsize ) : chunk_id = f . read ( 4 ) if chunk_id == b'fmt ' : chunksize , sampfmt , chans , sr , byterate , align , bits = _wavReadFmt ( f , bigendian ) elif chunk_id == b'data' : datasize = _struct . unpack ( fmt , f . read ( 4 ) ) [ 0 ] nframes = int ( datasize / ( chans * ( bits / 8 ) ) ) break else : _warnings . warn ( "chunk not understood: %s" % chunk_id ) data = f . read ( 4 ) size = _struct . unpack ( fmt , data ) [ 0 ] f . seek ( size , 1 ) encoding = _encoding ( sampfmt , bits ) if needsclosing : f . close ( ) info = SndInfo ( sr , nframes , chans , encoding , "wav" ) return info , { 'fsize' : fsize , 'bigendian' : bigendian , 'datasize' : datasize } | Read the info of a wav file . taken mostly from scipy . io . wavfile | 341 | 21 |
10,817 | def connect ( self ) : family , stype , proto , cname , sockaddr = self . best_connection_params ( self . host , self . port ) self . sock = socket . socket ( family , stype ) self . sock . settimeout ( self . timeout ) self . sock . connect ( sockaddr ) | Create connection to server | 68 | 4 |
10,818 | def getchallenge ( self ) : self . sock . send ( CHALLENGE_PACKET ) # wait challenge response for packet in self . read_iterator ( self . CHALLENGE_TIMEOUT ) : if packet . startswith ( CHALLENGE_RESPONSE_HEADER ) : return parse_challenge_response ( packet ) | Return server challenge | 78 | 3 |
10,819 | def send ( self , command ) : if self . secure_rcon == self . RCON_NOSECURE : self . sock . send ( rcon_nosecure_packet ( self . password , command ) ) elif self . secure_rcon == self . RCON_SECURE_TIME : self . sock . send ( rcon_secure_time_packet ( self . password , command ) ) elif self . secure_rcon == self . RCON_SECURE_CHALLENGE : challenge = self . getchallenge ( ) self . sock . send ( rcon_secure_challenge_packet ( self . password , challenge , command ) ) else : raise ValueError ( "Bad value of secure_rcon" ) | Send rcon command to server | 165 | 6 |
10,820 | def parse ( html_string , wrapper = Parser , * args , * * kwargs ) : return Parser ( lxml . html . fromstring ( html_string ) , * args , * * kwargs ) | Parse html with wrapper | 48 | 5 |
10,821 | def str2int ( string_with_int ) : return int ( "" . join ( [ char for char in string_with_int if char in string . digits ] ) or 0 ) | Collect digits from a string | 40 | 5 |
10,822 | def to_unicode ( obj , encoding = 'utf-8' ) : if isinstance ( obj , string_types ) or isinstance ( obj , binary_type ) : if not isinstance ( obj , text_type ) : obj = text_type ( obj , encoding ) return obj | Convert string to unicode string | 62 | 7 |
10,823 | def strip_spaces ( s ) : return u" " . join ( [ c for c in s . split ( u' ' ) if c ] ) | Strip excess spaces from a string | 33 | 7 |
10,824 | def strip_linebreaks ( s ) : return u"\n" . join ( [ c for c in s . split ( u'\n' ) if c ] ) | Strip excess line breaks from a string | 37 | 8 |
10,825 | def get ( self , selector , index = 0 , default = None ) : elements = self ( selector ) if elements : try : return elements [ index ] except ( IndexError ) : pass return default | Get first element from CSSSelector | 41 | 7 |
10,826 | def html ( self , unicode = False ) : html = lxml . html . tostring ( self . element , encoding = self . encoding ) if unicode : html = html . decode ( self . encoding ) return html | Return HTML of element | 47 | 4 |
10,827 | def parse ( self , func , * args , * * kwargs ) : result = [ ] for element in self . xpath ( 'child::node()' ) : if isinstance ( element , Parser ) : children = element . parse ( func , * args , * * kwargs ) element_result = func ( element , children , * args , * * kwargs ) if element_result : result . append ( element_result ) else : result . append ( element ) return u"" . join ( result ) | Parse element with given function | 112 | 6 |
10,828 | def _wrap_result ( self , func ) : def wrapper ( * args ) : result = func ( * args ) if hasattr ( result , '__iter__' ) and not isinstance ( result , etree . _Element ) : return [ self . _wrap_element ( element ) for element in result ] else : return self . _wrap_element ( result ) return wrapper | Wrap result in Parser instance | 81 | 7 |
10,829 | def _wrap_element ( self , result ) : if isinstance ( result , lxml . html . HtmlElement ) : return Parser ( result ) else : return result | Wrap single element in Parser instance | 37 | 8 |
10,830 | def parse_inline ( self ) : if self . inline_children : self . children = parser . parse_inline ( self . children ) elif isinstance ( getattr ( self , 'children' , None ) , list ) : for child in self . children : if isinstance ( child , BlockElement ) : child . parse_inline ( ) | Inline parsing is postponed so that all link references are seen before that . | 73 | 15 |
10,831 | def work_model_factory ( * , validator = validators . is_work_model , * * kwargs ) : kwargs [ 'ld_type' ] = 'AbstractWork' return _model_factory ( validator = validator , * * kwargs ) | Generate a Work model . | 63 | 6 |
10,832 | def manifestation_model_factory ( * , validator = validators . is_manifestation_model , ld_type = 'CreativeWork' , * * kwargs ) : return _model_factory ( validator = validator , ld_type = ld_type , * * kwargs ) | Generate a Manifestation model . | 71 | 7 |
10,833 | def right_model_factory ( * , validator = validators . is_right_model , ld_type = 'Right' , * * kwargs ) : return _model_factory ( validator = validator , ld_type = ld_type , * * kwargs ) | Generate a Right model . | 67 | 6 |
10,834 | def copyright_model_factory ( * , validator = validators . is_copyright_model , * * kwargs ) : kwargs [ 'ld_type' ] = 'Copyright' return _model_factory ( validator = validator , * * kwargs ) | Generate a Copyright model . | 63 | 6 |
10,835 | def mark_error_retryable ( error ) : if isinstance ( error , Exception ) : alsoProvides ( error , IRetryableError ) elif inspect . isclass ( error ) and issubclass ( error , Exception ) : classImplements ( error , IRetryableError ) else : raise ValueError ( 'only exception objects or types may be marked retryable' ) | Mark an exception instance or type as retryable . If this exception is caught by pyramid_retry then it may retry the request . | 85 | 29 |
10,836 | def is_last_attempt ( request ) : environ = request . environ attempt = environ . get ( 'retry.attempt' ) attempts = environ . get ( 'retry.attempts' ) if attempt is None or attempts is None : return True return attempt + 1 == attempts | Return True if the request is on its last attempt meaning that pyramid_retry will not be issuing any new attempts regardless of what happens when executing this request . | 66 | 32 |
10,837 | def includeme ( config ) : settings = config . get_settings ( ) config . add_view_predicate ( 'last_retry_attempt' , LastAttemptPredicate ) config . add_view_predicate ( 'retryable_error' , RetryableErrorPredicate ) def register ( ) : attempts = int ( settings . get ( 'retry.attempts' ) or 3 ) settings [ 'retry.attempts' ] = attempts activate_hook = settings . get ( 'retry.activate_hook' ) activate_hook = config . maybe_dotted ( activate_hook ) policy = RetryableExecutionPolicy ( attempts , activate_hook = activate_hook , ) config . set_execution_policy ( policy ) # defer registration to allow time to modify settings config . action ( None , register , order = PHASE1_CONFIG ) | Activate the pyramid_retry execution policy in your application . | 191 | 13 |
10,838 | def filter_butter_coeffs ( filtertype , freq , samplerate , order = 5 ) : # type: (str, Union[float, Tuple[float, float]], int, int) -> Tuple[np.ndarray, np.ndarray] assert filtertype in ( 'low' , 'high' , 'band' ) nyq = 0.5 * samplerate if isinstance ( freq , tuple ) : assert filtertype == 'band' low , high = freq low /= nyq high /= nyq b , a = signal . butter ( order , [ low , high ] , btype = 'band' ) else : freq = freq / nyq b , a = signal . butter ( order , freq , btype = filtertype ) return b , a | calculates the coefficients for a digital butterworth filter | 181 | 11 |
10,839 | def filter_butter ( samples , samplerate , filtertype , freq , order = 5 ) : # type: (np.ndarray, int, str, float, int) -> np.ndarray assert filtertype in ( 'low' , 'high' , 'band' ) b , a = filter_butter_coeffs ( filtertype , freq , samplerate , order = order ) return apply_multichannel ( samples , lambda data : signal . lfilter ( b , a , data ) ) | Filters the samples with a digital butterworth filter | 113 | 10 |
10,840 | def token_middleware ( ctx , get_response ) : async def middleware ( request ) : params = request . setdefault ( 'params' , { } ) if params . get ( "token" ) is None : params [ 'token' ] = ctx . token return await get_response ( request ) return middleware | Reinject token and consistency into requests . | 70 | 9 |
10,841 | def rebuild ( self ) : scene = self . scene ( ) if ( not scene ) : return sourcePos = self . sourceItem ( ) . viewItem ( ) . pos ( ) sourceRect = self . sourceItem ( ) . viewItem ( ) . rect ( ) targetPos = self . targetItem ( ) . viewItem ( ) . pos ( ) targetRect = self . targetItem ( ) . viewItem ( ) . rect ( ) cellWidth = scene . ganttWidget ( ) . cellWidth ( ) startX = sourcePos . x ( ) + sourceRect . width ( ) - ( cellWidth / 2.0 ) startY = sourcePos . y ( ) + ( sourceRect . height ( ) / 2.0 ) endX = targetPos . x ( ) - 2 endY = targetPos . y ( ) + ( targetRect . height ( ) / 2.0 ) path = QPainterPath ( ) path . moveTo ( startX , startY ) path . lineTo ( startX , endY ) path . lineTo ( endX , endY ) a = QPointF ( endX - 10 , endY - 3 ) b = QPointF ( endX , endY ) c = QPointF ( endX - 10 , endY + 3 ) self . _polygon = QPolygonF ( [ a , b , c , a ] ) path . addPolygon ( self . _polygon ) self . setPath ( path ) | Rebuilds the dependency path for this item . | 313 | 10 |
10,842 | def _writeBlock ( block , blockID ) : with open ( "blockIDs.txt" , "a" ) as fp : fp . write ( "blockID: " + str ( blockID ) + "\n" ) sentences = "" for sentence in block : sentences += sentence + "," fp . write ( "block sentences: " + sentences [ : - 1 ] + "\n" ) fp . write ( "\n" ) | writes the block to a file with the id | 95 | 10 |
10,843 | def _writeSentenceInBlock ( sentence , blockID , sentenceID ) : with open ( "sentenceIDs.txt" , "a" ) as fp : fp . write ( "sentenceID: " + str ( blockID ) + "_" + str ( sentenceID ) + "\n" ) fp . write ( "sentence string: " + sentence + "\n" ) fp . write ( "\n" ) | writes the sentence in a block to a file with the id | 94 | 13 |
10,844 | def _writeWordFromSentenceInBlock ( word , blockID , sentenceID , wordID ) : with open ( "wordIDs.txt" , "a" ) as fp : fp . write ( "wordID: " + str ( blockID ) + "_" + str ( sentenceID ) + "_" + str ( wordID ) + "\n" ) fp . write ( "wordString: " + word + "\n" ) fp . write ( "\n" ) | writes the word from a sentence in a block to a file with the id | 105 | 16 |
10,845 | def _writeBk ( target = "sentenceContainsTarget(+SID,+WID)." , treeDepth = "3" , nodeSize = "3" , numOfClauses = "8" ) : with open ( 'bk.txt' , 'w' ) as bk : bk . write ( "useStdLogicVariables: true\n" ) bk . write ( "setParam: treeDepth=" + str ( treeDepth ) + '.\n' ) bk . write ( "setParam: nodeSize=" + str ( nodeSize ) + '.\n' ) bk . write ( "setParam: numOfClauses=" + str ( numOfClauses ) + '.\n' ) bk . write ( "mode: nextSentenceInBlock(+BID,+SID,-SID).\n" ) bk . write ( "mode: nextSentenceInBlock(+BID,-SID,+SID).\n" ) bk . write ( "mode: earlySentenceInBlock(+BID,-SID).\n" ) bk . write ( "mode: midWaySentenceInBlock(+BID,-SID).\n" ) bk . write ( "mode: lateSentenceInBlock(+BID,-SID).\n" ) bk . write ( "mode: sentenceInBlock(-SID,+BID).\n" ) bk . write ( "mode: wordString(+WID,#WSTR).\n" ) bk . write ( "mode: partOfSpeechTag(+WID,#WPOS).\n" ) bk . write ( "mode: nextWordInSentence(+SID,+WID,-WID).\n" ) bk . write ( "mode: earlyWordInSentence(+SID,-WID).\n" ) bk . write ( "mode: midWayWordInSentence(+SID,-WID).\n" ) bk . write ( "mode: lateWordInSentence(+SID,-WID).\n" ) bk . write ( "mode: wordInSentence(-WID,+SID).\n" ) bk . write ( "mode: " + target + "\n" ) return | Writes a background file to disk . | 513 | 8 |
10,846 | def traverse_depth_first_pre_order ( self , callback ) : n = len ( self . suftab ) root = [ 0 , 0 , n - 1 , "" ] # <l, i, j, char> def _traverse_top_down ( interval ) : # TODO: Rewrite with stack? As in bottom-up callback ( interval ) i , j = interval [ 1 ] , interval [ 2 ] if i != j : children = self . _get_child_intervals ( i , j ) children . sort ( key = lambda child : child [ 3 ] ) for child in children : _traverse_top_down ( child ) _traverse_top_down ( root ) | Visits the internal nodes of the enhanced suffix array in depth - first pre - order . | 152 | 18 |
10,847 | def traverse_depth_first_post_order ( self , callback ) : # a. Reimplement without python lists?.. # b. Interface will require it to have not internal nodes only?.. # (but actually this implementation gives a ~2x gain of performance) last_interval = None n = len ( self . suftab ) stack = [ [ 0 , 0 , None , [ ] ] ] # <l, i, j, children> for i in xrange ( 1 , n ) : lb = i - 1 while self . lcptab [ i ] < stack [ - 1 ] [ 0 ] : stack [ - 1 ] [ 2 ] = i - 1 last_interval = stack . pop ( ) callback ( last_interval ) lb = last_interval [ 1 ] if self . lcptab [ i ] <= stack [ - 1 ] [ 0 ] : stack [ - 1 ] [ 3 ] . append ( last_interval ) last_interval = None if self . lcptab [ i ] > stack [ - 1 ] [ 0 ] : if last_interval : stack . append ( [ self . lcptab [ i ] , lb , None , [ last_interval ] ] ) last_interval = None else : stack . append ( [ self . lcptab [ i ] , lb , None , [ ] ] ) stack [ - 1 ] [ 2 ] = n - 1 callback ( stack [ - 1 ] ) | Visits the internal nodes of the enhanced suffix array in depth - first post - order . | 317 | 18 |
10,848 | def _DecodeKey ( self , key ) : if self . dict . attrindex . HasBackward ( key ) : return self . dict . attrindex . GetBackward ( key ) return key | Turn a key into a string if possible | 44 | 8 |
10,849 | def AddAttribute ( self , key , value ) : if isinstance ( value , list ) : values = value else : values = [ value ] ( key , values ) = self . _EncodeKeyValues ( key , values ) self . setdefault ( key , [ ] ) . extend ( values ) | Add an attribute to the packet . | 63 | 7 |
10,850 | def CreateAuthenticator ( ) : data = [ ] for i in range ( 16 ) : data . append ( random_generator . randrange ( 0 , 256 ) ) if six . PY3 : return bytes ( data ) else : return '' . join ( chr ( b ) for b in data ) | Create a packet autenticator . All RADIUS packets contain a sixteen byte authenticator which is used to authenticate replies from the RADIUS server and in the password hiding algorithm . This function returns a suitable random string that can be used as an authenticator . | 65 | 54 |
10,851 | def DecodePacket ( self , packet ) : try : ( self . code , self . id , length , self . authenticator ) = struct . unpack ( '!BBH16s' , packet [ 0 : 20 ] ) except struct . error : raise PacketError ( 'Packet header is corrupt' ) if len ( packet ) != length : raise PacketError ( 'Packet has invalid length' ) if length > 8192 : raise PacketError ( 'Packet length is too long (%d)' % length ) self . clear ( ) packet = packet [ 20 : ] while packet : try : ( key , attrlen ) = struct . unpack ( '!BB' , packet [ 0 : 2 ] ) except struct . error : raise PacketError ( 'Attribute header is corrupt' ) if attrlen < 2 : raise PacketError ( 'Attribute length is too small (%d)' % attrlen ) value = packet [ 2 : attrlen ] if key == 26 : # 26 is the Vendor-Specific attribute ( vendor , subattrs ) = self . _PktDecodeVendorAttribute ( value ) if vendor is None : self . setdefault ( key , [ ] ) . append ( value ) else : for ( k , v ) in subattrs : self . setdefault ( ( vendor , k ) , [ ] ) . append ( v ) else : self . setdefault ( key , [ ] ) . append ( value ) packet = packet [ attrlen : ] | Initialize the object from raw packet data . Decode a packet as received from the network and decode it . | 320 | 22 |
10,852 | def PwDecrypt ( self , password ) : buf = password pw = six . b ( '' ) last = self . authenticator while buf : hash = md5_constructor ( self . secret + last ) . digest ( ) if six . PY3 : for i in range ( 16 ) : pw += bytes ( ( hash [ i ] ^ buf [ i ] , ) ) else : for i in range ( 16 ) : pw += chr ( ord ( hash [ i ] ) ^ ord ( buf [ i ] ) ) ( last , buf ) = ( buf [ : 16 ] , buf [ 16 : ] ) while pw . endswith ( six . b ( '\x00' ) ) : pw = pw [ : - 1 ] return pw . decode ( 'utf-8' ) | Unobfuscate a RADIUS password . RADIUS hides passwords in packets by using an algorithm based on the MD5 hash of the packet authenticator and RADIUS secret . This function reverses the obfuscation process . | 176 | 47 |
10,853 | def PwCrypt ( self , password ) : if self . authenticator is None : self . authenticator = self . CreateAuthenticator ( ) if isinstance ( password , six . text_type ) : password = password . encode ( 'utf-8' ) buf = password if len ( password ) % 16 != 0 : buf += six . b ( '\x00' ) * ( 16 - ( len ( password ) % 16 ) ) hash = md5_constructor ( self . secret + self . authenticator ) . digest ( ) result = six . b ( '' ) last = self . authenticator while buf : hash = md5_constructor ( self . secret + last ) . digest ( ) if six . PY3 : for i in range ( 16 ) : result += bytes ( ( hash [ i ] ^ buf [ i ] , ) ) else : for i in range ( 16 ) : result += chr ( ord ( hash [ i ] ) ^ ord ( buf [ i ] ) ) last = result [ - 16 : ] buf = buf [ 16 : ] return result | Obfuscate password . RADIUS hides passwords in packets by using an algorithm based on the MD5 hash of the packet authenticator and RADIUS secret . If no authenticator has been set before calling PwCrypt one is created automatically . Changing the authenticator after setting a password that has been encrypted using this function will not work . | 229 | 69 |
10,854 | def clear ( self ) : # preserve the collapse button super ( XToolBar , self ) . clear ( ) # clears out the toolbar if self . isCollapsable ( ) : self . _collapseButton = QToolButton ( self ) self . _collapseButton . setAutoRaise ( True ) self . _collapseButton . setSizePolicy ( QSizePolicy . Expanding , QSizePolicy . Expanding ) self . addWidget ( self . _collapseButton ) self . refreshButton ( ) # create connection self . _collapseButton . clicked . connect ( self . toggleCollapsed ) elif self . _collapseButton : self . _collapseButton . setParent ( None ) self . _collapseButton . deleteLater ( ) self . _collapseButton = None | Clears out this toolbar from the system . | 168 | 9 |
10,855 | def refreshButton ( self ) : collapsed = self . isCollapsed ( ) btn = self . _collapseButton if not btn : return btn . setMaximumSize ( MAX_SIZE , MAX_SIZE ) # set up a vertical scrollbar if self . orientation ( ) == Qt . Vertical : btn . setMaximumHeight ( 12 ) else : btn . setMaximumWidth ( 12 ) icon = '' # collapse/expand a vertical toolbar if self . orientation ( ) == Qt . Vertical : if collapsed : self . setFixedWidth ( self . _collapsedSize ) btn . setMaximumHeight ( MAX_SIZE ) btn . setArrowType ( Qt . RightArrow ) else : self . setMaximumWidth ( MAX_SIZE ) self . _precollapseSize = None btn . setMaximumHeight ( 12 ) btn . setArrowType ( Qt . LeftArrow ) else : if collapsed : self . setFixedHeight ( self . _collapsedSize ) btn . setMaximumWidth ( MAX_SIZE ) btn . setArrowType ( Qt . DownArrow ) else : self . setMaximumHeight ( 1000 ) self . _precollapseSize = None btn . setMaximumWidth ( 12 ) btn . setArrowType ( Qt . UpArrow ) for index in range ( 1 , self . layout ( ) . count ( ) ) : item = self . layout ( ) . itemAt ( index ) if not item . widget ( ) : continue if collapsed : item . widget ( ) . setMaximumSize ( 0 , 0 ) else : item . widget ( ) . setMaximumSize ( MAX_SIZE , MAX_SIZE ) if not self . isCollapsable ( ) : btn . hide ( ) else : btn . show ( ) | Refreshes the button for this toolbar . | 378 | 9 |
10,856 | def match ( self , url ) : return list ( { message for message in self . active ( ) if message . is_global or message . match ( url ) } ) | Return a list of all active Messages which match the given URL . | 36 | 13 |
10,857 | def paint ( self , painter , option , widget ) : scene = self . scene ( ) if not scene : return scene . chart ( ) . renderer ( ) . drawItem ( self , painter , option ) | Draws this item with the inputed painter . This will call the scene s renderer to draw this item . | 44 | 23 |
10,858 | def is_pg_at_least_nine_two ( self ) : if self . _is_pg_at_least_nine_two is None : results = self . version ( ) regex = re . compile ( "PostgreSQL (\d+\.\d+\.\d+) on" ) matches = regex . match ( results [ 0 ] . version ) version = matches . groups ( ) [ 0 ] if version > '9.2.0' : self . _is_pg_at_least_nine_two = True else : self . _is_pg_at_least_nine_two = False return self . _is_pg_at_least_nine_two | Some queries have different syntax depending what version of postgres we are querying against . | 153 | 17 |
10,859 | def execute ( self , statement ) : # Make the sql statement easier to read in case some of the queries we # run end up in the output sql = statement . replace ( '\n' , '' ) sql = ' ' . join ( sql . split ( ) ) self . cursor . execute ( sql ) return self . cursor . fetchall ( ) | Execute the given sql statement . | 73 | 7 |
10,860 | def calls ( self , truncate = False ) : if self . pg_stat_statement ( ) : if truncate : select = """ SELECT CASE WHEN length(query) < 40 THEN query ELSE substr(query, 0, 38) || '..' END AS qry, """ else : select = 'SELECT query,' return self . execute ( sql . CALLS . format ( select = select ) ) else : return [ self . get_missing_pg_stat_statement_error ( ) ] | Show 10 most frequently called queries . Requires the pg_stat_statements Postgres module to be installed . | 105 | 22 |
10,861 | def blocking ( self ) : return self . execute ( sql . BLOCKING . format ( query_column = self . query_column , pid_column = self . pid_column ) ) | Display queries holding locks other queries are waiting to be released . | 40 | 12 |
10,862 | def outliers ( self , truncate = False ) : if self . pg_stat_statement ( ) : if truncate : query = """ CASE WHEN length(query) < 40 THEN query ELSE substr(query, 0, 38) || '..' END """ else : query = 'query' return self . execute ( sql . OUTLIERS . format ( query = query ) ) else : return [ self . get_missing_pg_stat_statement_error ( ) ] | Show 10 queries that have longest execution time in aggregate . Requires the pg_stat_statments Postgres module to be installed . | 101 | 26 |
10,863 | def long_running_queries ( self ) : if self . is_pg_at_least_nine_two ( ) : idle = "AND state <> 'idle'" else : idle = "AND current_query <> '<IDLE>'" return self . execute ( sql . LONG_RUNNING_QUERIES . format ( pid_column = self . pid_column , query_column = self . query_column , idle = idle ) ) | Show all queries longer than five minutes by descending duration . | 101 | 11 |
10,864 | def locks ( self ) : return self . execute ( sql . LOCKS . format ( pid_column = self . pid_column , query_column = self . query_column ) ) | Display queries with active locks . | 40 | 6 |
10,865 | def ps ( self ) : if self . is_pg_at_least_nine_two ( ) : idle = "AND state <> 'idle'" else : idle = "AND current_query <> '<IDLE>'" return self . execute ( sql . PS . format ( pid_column = self . pid_column , query_column = self . query_column , idle = idle ) ) | View active queries with execution time . | 88 | 7 |
10,866 | def publish ( self , metrics , config ) : if len ( metrics ) > 0 : with open ( config [ "file" ] , 'a' ) as outfile : for metric in metrics : outfile . write ( json_format . MessageToJson ( metric . _pb , including_default_value_fields = True ) ) | Publishes metrics to a file in JSON format . | 71 | 10 |
10,867 | def clean_name ( self ) : name = self . cleaned_data [ 'name' ] reserved_names = self . _meta . model . _meta . get_all_field_names ( ) if name not in reserved_names : return name raise ValidationError ( _ ( 'Attribute name must not clash with reserved names' ' ("%s")' ) % '", "' . join ( reserved_names ) ) | Avoid name clashes between static and dynamic attributes . | 89 | 9 |
10,868 | def save ( self , commit = True ) : if self . errors : raise ValueError ( "The %s could not be saved because the data didn't" " validate." % self . instance . _meta . object_name ) # create entity instance, don't save yet instance = super ( BaseDynamicEntityForm , self ) . save ( commit = False ) # assign attributes for name in instance . get_schema_names ( ) : value = self . cleaned_data . get ( name ) setattr ( instance , name , value ) # save entity and its attributes if commit : instance . save ( ) return instance | Saves this form s cleaned_data into model instance self . instance and related EAV attributes . | 129 | 20 |
10,869 | def refresh ( self ) : table = self . tableType ( ) search = nativestring ( self . _pywidget . text ( ) ) if search == self . _lastSearch : return self . _lastSearch = search if not search : return if search in self . _cache : records = self . _cache [ search ] else : records = table . select ( where = self . baseQuery ( ) , order = self . order ( ) ) records = list ( records . search ( search , limit = self . limit ( ) ) ) self . _cache [ search ] = records self . _records = records self . model ( ) . setStringList ( map ( str , self . _records ) ) self . complete ( ) | Refreshes the contents of the completer based on the current text . | 156 | 15 |
10,870 | def initialize ( self , force = False ) : if force or ( self . isVisible ( ) and not self . isInitialized ( ) and not self . signalsBlocked ( ) ) : self . _initialized = True self . initialized . emit ( ) | Initializes the view if it is visible or being loaded . | 53 | 12 |
10,871 | def destroySingleton ( cls ) : singleton_key = '_{0}__singleton' . format ( cls . __name__ ) singleton = getattr ( cls , singleton_key , None ) if singleton is not None : setattr ( cls , singleton_key , None ) singleton . close ( ) singleton . deleteLater ( ) | Destroys the singleton instance of this class if one exists . | 81 | 14 |
10,872 | def adjustSize ( self ) : # adjust the close button align = self . closeAlignment ( ) if align & QtCore . Qt . AlignTop : y = 6 else : y = self . height ( ) - 38 if align & QtCore . Qt . AlignLeft : x = 6 else : x = self . width ( ) - 38 self . _closeButton . move ( x , y ) # adjust the central widget widget = self . centralWidget ( ) if widget is not None : center = self . rect ( ) . center ( ) widget . move ( center . x ( ) - widget . width ( ) / 2 , center . y ( ) - widget . height ( ) / 2 ) | Adjusts the size of this widget as the parent resizes . | 147 | 13 |
10,873 | def keyPressEvent ( self , event ) : if event . key ( ) == QtCore . Qt . Key_Escape : self . reject ( ) super ( XOverlayWidget , self ) . keyPressEvent ( event ) | Exits the modal window on an escape press . | 48 | 11 |
10,874 | def eventFilter ( self , object , event ) : if object == self . parent ( ) and event . type ( ) == QtCore . QEvent . Resize : self . resize ( event . size ( ) ) elif event . type ( ) == QtCore . QEvent . Close : self . setResult ( 0 ) return False | Resizes this overlay as the widget resizes . | 70 | 10 |
10,875 | def resizeEvent ( self , event ) : super ( XOverlayWidget , self ) . resizeEvent ( event ) self . adjustSize ( ) | Handles a resize event for this overlay centering the central widget if one is found . | 30 | 18 |
10,876 | def setCentralWidget ( self , widget ) : self . _centralWidget = widget if widget is not None : widget . setParent ( self ) widget . installEventFilter ( self ) # create the drop shadow effect effect = QtGui . QGraphicsDropShadowEffect ( self ) effect . setColor ( QtGui . QColor ( 'black' ) ) effect . setBlurRadius ( 80 ) effect . setOffset ( 0 , 0 ) widget . setGraphicsEffect ( effect ) | Sets the central widget for this overlay to the inputed widget . | 102 | 14 |
10,877 | def setClosable ( self , state ) : self . _closable = state if state : self . _closeButton . show ( ) else : self . _closeButton . hide ( ) | Sets whether or not the user should be able to close this overlay widget . | 42 | 16 |
10,878 | def setVisible ( self , state ) : super ( XOverlayWidget , self ) . setVisible ( state ) if not state : self . setResult ( 0 ) | Closes this widget and kills the result . | 37 | 9 |
10,879 | def showEvent ( self , event ) : super ( XOverlayWidget , self ) . showEvent ( event ) # raise to the top self . raise_ ( ) self . _closeButton . setVisible ( self . isClosable ( ) ) widget = self . centralWidget ( ) if widget : center = self . rect ( ) . center ( ) start_x = end_x = center . x ( ) - widget . width ( ) / 2 start_y = - widget . height ( ) end_y = center . y ( ) - widget . height ( ) / 2 start = QtCore . QPoint ( start_x , start_y ) end = QtCore . QPoint ( end_x , end_y ) # create the movement animation anim = QtCore . QPropertyAnimation ( self ) anim . setPropertyName ( 'pos' ) anim . setTargetObject ( widget ) anim . setStartValue ( start ) anim . setEndValue ( end ) anim . setDuration ( 500 ) anim . setEasingCurve ( QtCore . QEasingCurve . InOutQuad ) anim . finished . connect ( anim . deleteLater ) anim . start ( ) | Ensures this widget is the top - most widget for its parent . | 251 | 15 |
10,880 | def modal ( widget , parent = None , align = QtCore . Qt . AlignTop | QtCore . Qt . AlignRight , blurred = True ) : if parent is None : parent = QtGui . QApplication . instance ( ) . activeWindow ( ) overlay = XOverlayWidget ( parent ) overlay . setAttribute ( QtCore . Qt . WA_DeleteOnClose ) overlay . setCentralWidget ( widget ) overlay . setCloseAlignment ( align ) overlay . show ( ) return overlay | Creates a modal dialog for this overlay with the inputed widget . If the user accepts the widget then 1 will be returned otherwise 0 will be returned . | 106 | 32 |
10,881 | def applyCommand ( self ) : # generate the command information cursor = self . textCursor ( ) cursor . movePosition ( cursor . EndOfLine ) line = projex . text . nativestring ( cursor . block ( ) . text ( ) ) at_end = cursor . atEnd ( ) modifiers = QApplication . instance ( ) . keyboardModifiers ( ) mod_mode = at_end or modifiers == Qt . ShiftModifier # test the line for information if mod_mode and line . endswith ( ':' ) : cursor . movePosition ( cursor . EndOfLine ) line = re . sub ( '^>>> ' , '' , line ) line = re . sub ( '^\.\.\. ' , '' , line ) count = len ( line ) - len ( line . lstrip ( ) ) + 4 self . insertPlainText ( '\n... ' + count * ' ' ) return False elif mod_mode and line . startswith ( '...' ) and ( line . strip ( ) != '...' or not at_end ) : cursor . movePosition ( cursor . EndOfLine ) line = re . sub ( '^\.\.\. ' , '' , line ) count = len ( line ) - len ( line . lstrip ( ) ) self . insertPlainText ( '\n... ' + count * ' ' ) return False # if we're not at the end of the console, then add it to the end elif line . startswith ( '>>>' ) or line . startswith ( '...' ) : # move to the top of the command structure line = projex . text . nativestring ( cursor . block ( ) . text ( ) ) while line . startswith ( '...' ) : cursor . movePosition ( cursor . PreviousBlock ) line = projex . text . nativestring ( cursor . block ( ) . text ( ) ) # calculate the command cursor . movePosition ( cursor . EndOfLine ) line = projex . text . nativestring ( cursor . block ( ) . text ( ) ) ended = False lines = [ ] while True : # add the new block lines . append ( line ) if cursor . atEnd ( ) : ended = True break # move to the next line cursor . movePosition ( cursor . NextBlock ) cursor . movePosition ( cursor . EndOfLine ) line = projex . text . nativestring ( cursor . block ( ) . text ( ) ) # check for a new command or the end of the command if not line . startswith ( '...' ) : break command = '\n' . join ( lines ) # if we did not end up at the end of the command block, then # copy it for modification if not ( ended and command ) : self . waitForInput ( ) self . insertPlainText ( command . replace ( '>>> ' , '' ) ) cursor . movePosition ( cursor . End ) return False else : self . waitForInput ( ) return False self . executeCommand ( command ) return True | Applies the current line of code as an interactive python command . | 656 | 13 |
10,882 | def gotoHome ( self ) : mode = QTextCursor . MoveAnchor # select the home if QApplication . instance ( ) . keyboardModifiers ( ) == Qt . ShiftModifier : mode = QTextCursor . KeepAnchor cursor = self . textCursor ( ) block = projex . text . nativestring ( cursor . block ( ) . text ( ) ) cursor . movePosition ( QTextCursor . StartOfBlock , mode ) if block . startswith ( '>>> ' ) : cursor . movePosition ( QTextCursor . Right , mode , 4 ) elif block . startswith ( '... ' ) : match = re . match ( '...\s*' , block ) cursor . movePosition ( QTextCursor . Right , mode , match . end ( ) ) self . setTextCursor ( cursor ) | Navigates to the home position for the edit . | 186 | 11 |
10,883 | def waitForInput ( self ) : self . _waitingForInput = False try : if self . isDestroyed ( ) or self . isReadOnly ( ) : return except RuntimeError : return self . moveCursor ( QTextCursor . End ) if self . textCursor ( ) . block ( ) . text ( ) == '>>> ' : return # if there is already text on the line, then start a new line newln = '>>> ' if projex . text . nativestring ( self . textCursor ( ) . block ( ) . text ( ) ) : newln = '\n' + newln # insert the text self . setCurrentMode ( 'standard' ) self . insertPlainText ( newln ) self . scrollToEnd ( ) self . _blankCache = '' | Inserts a new input command into the console editor . | 175 | 11 |
10,884 | def accept ( self ) : for i in range ( self . uiConfigSTACK . count ( ) ) : widget = self . uiConfigSTACK . widget ( i ) if ( not widget ) : continue if ( not widget . save ( ) ) : self . uiConfigSTACK . setCurrentWidget ( widget ) return False # close all the widgets in the stack for i in range ( self . uiConfigSTACK . count ( ) ) : widget = self . uiConfigSTACK . widget ( i ) if ( not widget ) : continue widget . close ( ) if ( self == XConfigDialog . _instance ) : XConfigDialog . _instance = None super ( XConfigDialog , self ) . accept ( ) | Saves all the current widgets and closes down . | 155 | 10 |
10,885 | def reject ( self ) : if ( self == XConfigDialog . _instance ) : XConfigDialog . _instance = None super ( XConfigDialog , self ) . reject ( ) | Overloads the reject method to clear up the instance variable . | 38 | 12 |
10,886 | def showConfig ( self ) : item = self . uiPluginTREE . currentItem ( ) if not isinstance ( item , PluginItem ) : return plugin = item . plugin ( ) widget = self . findChild ( QWidget , plugin . uniqueName ( ) ) if ( not widget ) : widget = plugin . createWidget ( self ) widget . setObjectName ( plugin . uniqueName ( ) ) self . uiConfigSTACK . addWidget ( widget ) self . uiConfigSTACK . setCurrentWidget ( widget ) | Show the config widget for the currently selected plugin . | 112 | 10 |
10,887 | def cli ( server , port , client ) : tn = telnetlib . Telnet ( host = server , port = port ) tn . write ( 'kill %s\n' % client . encode ( 'utf-8' ) ) tn . write ( 'exit\n' ) os . _exit ( 0 ) | OpenVPN client_kill method | 71 | 6 |
10,888 | def adjustButtons ( self ) : tabbar = self . tabBar ( ) tabbar . adjustSize ( ) w = self . width ( ) - self . _optionsButton . width ( ) - 2 self . _optionsButton . move ( w , 0 ) if self . count ( ) : need_update = self . _addButton . property ( 'alone' ) != False if need_update : self . _addButton . setProperty ( 'alone' , False ) self . _addButton . move ( tabbar . width ( ) , 1 ) self . _addButton . setFixedHeight ( tabbar . height ( ) ) else : need_update = self . _addButton . property ( 'alone' ) != True if need_update : self . _addButton . setProperty ( 'alone' , True ) self . _addButton . move ( tabbar . width ( ) + 2 , 1 ) self . _addButton . stackUnder ( self . currentWidget ( ) ) # force refresh on the stylesheet (Qt limitation for updates) if need_update : app = QApplication . instance ( ) app . setStyleSheet ( app . styleSheet ( ) ) | Updates the position of the buttons based on the current geometry . | 251 | 13 |
10,889 | def publish ( self , message , routing_key = None ) : if routing_key is None : routing_key = self . routing_key return self . client . publish_to_exchange ( self . name , message = message , routing_key = routing_key ) | Publish message to exchange | 58 | 5 |
10,890 | def publish ( self , message ) : return self . client . publish_to_queue ( self . name , message = message ) | Publish message to queue | 27 | 5 |
10,891 | def adjustContentsMargins ( self ) : anchor = self . anchor ( ) mode = self . currentMode ( ) # margins for a dialog if ( mode == XPopupWidget . Mode . Dialog ) : self . setContentsMargins ( 0 , 0 , 0 , 0 ) # margins for a top anchor point elif ( anchor & ( XPopupWidget . Anchor . TopLeft | XPopupWidget . Anchor . TopCenter | XPopupWidget . Anchor . TopRight ) ) : self . setContentsMargins ( 0 , self . popupPadding ( ) + 5 , 0 , 0 ) # margins for a bottom anchor point elif ( anchor & ( XPopupWidget . Anchor . BottomLeft | XPopupWidget . Anchor . BottomCenter | XPopupWidget . Anchor . BottomRight ) ) : self . setContentsMargins ( 0 , 0 , 0 , self . popupPadding ( ) ) # margins for a left anchor point elif ( anchor & ( XPopupWidget . Anchor . LeftTop | XPopupWidget . Anchor . LeftCenter | XPopupWidget . Anchor . LeftBottom ) ) : self . setContentsMargins ( self . popupPadding ( ) , 0 , 0 , 0 ) # margins for a right anchor point else : self . setContentsMargins ( 0 , 0 , self . popupPadding ( ) , 0 ) self . adjustMask ( ) | Adjusts the contents for this widget based on the anchor and \ mode . | 304 | 15 |
10,892 | def adjustMask ( self ) : if self . currentMode ( ) == XPopupWidget . Mode . Dialog : self . clearMask ( ) return path = self . borderPath ( ) bitmap = QBitmap ( self . width ( ) , self . height ( ) ) bitmap . fill ( QColor ( 'white' ) ) with XPainter ( bitmap ) as painter : painter . setRenderHint ( XPainter . Antialiasing ) pen = QPen ( QColor ( 'black' ) ) pen . setWidthF ( 0.75 ) painter . setPen ( pen ) painter . setBrush ( QColor ( 'black' ) ) painter . drawPath ( path ) self . setMask ( bitmap ) | Updates the alpha mask for this popup widget . | 158 | 10 |
10,893 | def adjustSize ( self ) : widget = self . centralWidget ( ) if widget is None : super ( XPopupWidget , self ) . adjustSize ( ) return widget . adjustSize ( ) hint = widget . minimumSizeHint ( ) size = widget . minimumSize ( ) width = max ( size . width ( ) , hint . width ( ) ) height = max ( size . height ( ) , hint . height ( ) ) width += 20 height += 20 if self . _buttonBoxVisible : height += self . buttonBox ( ) . height ( ) + 10 if self . _titleBarVisible : height += max ( self . _dialogButton . height ( ) , self . _closeButton . height ( ) ) + 10 curr_w = self . width ( ) curr_h = self . height ( ) # determine if we need to move based on our anchor anchor = self . anchor ( ) if anchor & ( self . Anchor . LeftBottom | self . Anchor . RightBottom | self . Anchor . BottomLeft | self . Anchor . BottomCenter | self . Anchor . BottomRight ) : delta_y = height - curr_h elif anchor & ( self . Anchor . LeftCenter | self . Anchor . RightCenter ) : delta_y = ( height - curr_h ) / 2 else : delta_y = 0 if anchor & ( self . Anchor . RightTop | self . Anchor . RightCenter | self . Anchor . RightTop | self . Anchor . TopRight ) : delta_x = width - curr_w elif anchor & ( self . Anchor . TopCenter | self . Anchor . BottomCenter ) : delta_x = ( width - curr_w ) / 2 else : delta_x = 0 self . setMinimumSize ( width , height ) self . resize ( width , height ) pos = self . pos ( ) pos . setX ( pos . x ( ) - delta_x ) pos . setY ( pos . y ( ) - delta_y ) self . move ( pos ) | Adjusts the size of this popup to best fit the new widget size . | 443 | 15 |
10,894 | def close ( self ) : widget = self . centralWidget ( ) if widget and not widget . close ( ) : return super ( XPopupWidget , self ) . close ( ) | Closes the popup widget and central widget . | 38 | 9 |
10,895 | def refreshLabels ( self ) : itemCount = self . itemCount ( ) title = self . itemsTitle ( ) if ( not itemCount ) : self . _itemsLabel . setText ( ' %s per page' % title ) else : msg = ' %s per page, %i %s total' % ( title , itemCount , title ) self . _itemsLabel . setText ( msg ) | Refreshes the labels to display the proper title and count information . | 86 | 14 |
10,896 | def import_modules_from_package ( package ) : path = [ os . path . dirname ( __file__ ) , '..' ] + package . split ( '.' ) path = os . path . join ( * path ) for root , dirs , files in os . walk ( path ) : for filename in files : if filename . startswith ( '__' ) or not filename . endswith ( '.py' ) : continue new_package = "." . join ( root . split ( os . sep ) ) . split ( "...." ) [ 1 ] module_name = '%s.%s' % ( new_package , filename [ : - 3 ] ) if module_name not in sys . modules : __import__ ( module_name ) | Import modules from package and append into sys . modules | 165 | 10 |
10,897 | def request ( self , request_method , api_method , * args , * * kwargs ) : url = self . _build_url ( api_method ) resp = requests . request ( request_method , url , * args , * * kwargs ) try : rv = resp . json ( ) except ValueError : raise RequestFailedError ( resp , 'not a json body' ) if not resp . ok : raise RequestFailedError ( resp , rv . get ( 'error' ) ) return rv | Perform a request . | 113 | 5 |
10,898 | def updateCurrentValue ( self , value ) : xsnap = None ysnap = None if value != self . endValue ( ) : xsnap = self . targetObject ( ) . isXSnappedToGrid ( ) ysnap = self . targetObject ( ) . isYSnappedToGrid ( ) self . targetObject ( ) . setXSnapToGrid ( False ) self . targetObject ( ) . setYSnapToGrid ( False ) super ( XNodeAnimation , self ) . updateCurrentValue ( value ) if value != self . endValue ( ) : self . targetObject ( ) . setXSnapToGrid ( xsnap ) self . targetObject ( ) . setYSnapToGrid ( ysnap ) | Disables snapping during the current value update to ensure a smooth transition for node animations . Since this can only be called via code we don t need to worry about snapping to the grid for a user . | 153 | 40 |
10,899 | def adjustTitleFont ( self ) : left , top , right , bottom = self . contentsMargins ( ) r = self . roundingRadius ( ) # include text padding left += 5 + r / 2 top += 5 + r / 2 right += 5 + r / 2 bottom += 5 + r / 2 r = self . rect ( ) rect_l = r . left ( ) + left rect_r = r . right ( ) - right rect_t = r . top ( ) + top rect_b = r . bottom ( ) - bottom # ensure we have a valid rect rect = QRect ( rect_l , rect_t , rect_r - rect_l , rect_b - rect_t ) if rect . width ( ) < 10 : return font = XFont ( QApplication . font ( ) ) font . adaptSize ( self . displayName ( ) , rect , wordWrap = self . wordWrap ( ) ) self . _titleFont = font | Adjusts the font used for the title based on the current with and \ display name . | 206 | 18 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.