idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
61,400 | def mergeNewSeqs ( seqArray , mergedDir , numProcs , areUniform , logger ) : MSBWTGen . clearAuxiliaryData ( mergedDir ) midPoint = len ( seqArray ) / 3 mergedDir1 = mergedDir + '0' mergedDir2 = mergedDir + '1' mergedDir3 = mergedDir + '2' try : shutil . rmtree ( mergedDir1 ) except : pass try : shutil . rmtree ( merge... | This function takes a series of sequences and creates a big BWT by merging the smaller ones Mostly a test function no real purpose to the tool as of now |
61,401 | def compareKmerProfiles ( profileFN1 , profileFN2 ) : fp1 = open ( profileFN1 , 'r' ) fp2 = open ( profileFN2 , 'r' ) oneNorm = 0 twoNorm = 0 sumDeltas = 0 dotProduct = 0 tot1 = float ( fp1 . readline ( ) . strip ( '\n' ) . split ( ',' ) [ 1 ] ) tot2 = float ( fp2 . readline ( ) . strip ( '\n' ) . split ( ',' ) [ 1 ] )... | This function takes two kmer profiles and compare them for similarity . |
61,402 | def parseProfileLine ( fp ) : nextLine = fp . readline ( ) if nextLine == None or nextLine == '' : return ( None , None ) else : pieces = nextLine . strip ( '\n' ) . split ( ',' ) return ( pieces [ 0 ] , int ( pieces [ 1 ] ) ) | Helper function for profile parsing |
61,403 | def reverseComplement ( seq ) : revComp = '' complement = { 'A' : 'T' , 'C' : 'G' , 'G' : 'C' , 'T' : 'A' , 'N' : 'N' , '$' : '$' } for c in reversed ( seq ) : revComp += complement [ c ] return revComp | Helper function for generating reverse - complements |
61,404 | def countOccurrencesOfSeq ( self , seq , givenRange = None ) : if givenRange == None : if not self . searchCache . has_key ( seq [ - self . cacheDepth : ] ) : res = self . findIndicesOfStr ( seq [ - self . cacheDepth : ] ) self . searchCache [ seq [ - self . cacheDepth : ] ] = ( int ( res [ 0 ] ) , int ( res [ 1 ] ) ) ... | This function counts the number of occurrences of the given sequence |
61,405 | def recoverString ( self , strIndex , withIndex = False ) : retNums = [ ] indices = [ ] currIndex = strIndex prevChar = self . getCharAtIndex ( currIndex ) currIndex = self . getOccurrenceOfCharAtIndex ( prevChar , currIndex ) while currIndex != strIndex : retNums . append ( prevChar ) if withIndex : indices . append (... | This will return the string that starts at the given index |
61,406 | def getOccurrenceOfCharAtIndex ( self , sym , index ) : binID = index >> self . bitPower if ( binID << self . bitPower ) == index : ret = self . partialFM [ binID ] [ sym ] else : ret = self . partialFM [ binID ] [ sym ] + np . bincount ( self . bwt [ binID << self . bitPower : index ] , minlength = 6 ) [ sym ] return ... | This functions gets the FM - index value of a character at the specified position |
61,407 | def loadMsbwt ( self , dirName , logger ) : self . dirName = dirName self . bwt = np . load ( self . dirName + '/comp_msbwt.npy' , 'r' ) self . constructTotalCounts ( logger ) self . constructIndexing ( ) self . constructFMIndex ( logger ) | This functions loads a BWT file and constructs total counts indexes start positions and constructs an FM index in memory |
61,408 | def getCharAtIndex ( self , index ) : binID = index >> self . bitPower bwtIndex = self . refFM [ binID ] trueIndex = np . sum ( self . partialFM [ binID ] ) - self . offsetSum dist = index - trueIndex if binID == self . refFM . shape [ 0 ] - 1 : endRange = self . bwt . shape [ 0 ] else : endRange = self . refFM [ binID... | Used for searching this function masks the complexity behind retrieving a specific character at a specific index in our compressed BWT . |
61,409 | def getBWTRange ( self , start , end ) : startBlockIndex = start >> self . bitPower endBlockIndex = int ( math . floor ( float ( end ) / self . binSize ) ) trueStart = startBlockIndex * self . binSize return self . decompressBlocks ( startBlockIndex , endBlockIndex ) [ start - trueStart : end - trueStart ] | This function masks the complexity of retrieving a chunk of the BWT from the compressed format |
61,410 | def decompressBlocks ( self , startBlock , endBlock ) : expectedIndex = startBlock * self . binSize trueIndex = np . sum ( self . partialFM [ startBlock ] ) - self . offsetSum dist = expectedIndex - trueIndex startRange = self . refFM [ startBlock ] if endBlock >= self . refFM . shape [ 0 ] - 1 : endRange = self . bwt ... | This is mostly a helper function to get BWT range but I wanted it to be a separate thing for use possibly in decompression |
61,411 | def decode_html ( html ) : if isinstance ( html , unicode ) : return html match = CHARSET_META_TAG_PATTERN . search ( html ) if match : declared_encoding = match . group ( 1 ) . decode ( "ASCII" ) with ignored ( LookupError ) : return html . decode ( declared_encoding , "ignore" ) with ignored ( UnicodeDecodeError ) : ... | Converts bytes stream containing an HTML page into Unicode . Tries to guess character encoding from meta tag of by chardet library . |
61,412 | def build_document ( html_content , base_href = None ) : assert html_content is not None if isinstance ( html_content , unicode ) : html_content = html_content . encode ( "utf8" , "xmlcharrefreplace" ) try : document = document_fromstring ( html_content , parser = UTF8_PARSER ) except ( ParserError , XMLSyntaxError ) :... | Requires that the html_content not be None |
61,413 | def _parse_properties ( self ) : props_dict = self . data . get ( 'properties' , { } ) for prop_name in self . KNOWN_PROPERTIES : if prop_name in props_dict : setattr ( self , prop_name , props_dict . get ( prop_name ) ) else : setattr ( self , prop_name , None ) | Nodes have properties which are facts like the name description url etc . Loop through each of them and set it as attributes on this company so that we can make calls like company . name person . description |
61,414 | def _parse_relationship ( self ) : rs_dict = self . data . get ( 'relationships' , { } ) for rs_name in self . KNOWN_RELATIONSHIPS : if rs_name in rs_dict : setattr ( self , rs_name , Relationship ( rs_name , rs_dict . get ( rs_name ) ) ) else : setattr ( self , rs_name , NoneRelationshipSingleton ) | Nodes have Relationships and similarly to properties we set it as an attribute on the Organization so we can make calls like company . current_team person . degrees |
61,415 | def open ( self ) : self . startTime = datetime . datetime . now ( ) self . offset = 0 return self | Reset time and counts . |
61,416 | def update ( self , sent ) : self . offset = sent now = datetime . datetime . now ( ) elapsed = ( now - self . startTime ) . total_seconds ( ) if elapsed > 0 : mbps = ( sent * 8 / ( 10 ** 6 ) ) / elapsed else : mbps = None self . _display ( sent , now , self . name , mbps ) | Update self and parent with intermediate progress . |
61,417 | def _display ( self , sent , now , chunk , mbps ) : if self . parent is not None : self . parent . _display ( self . parent . offset + sent , now , chunk , mbps ) return elapsed = now - self . startTime if sent > 0 and self . total is not None and sent <= self . total : eta = ( self . total - sent ) * elapsed . total_s... | Display intermediate progress . |
61,418 | def close ( self ) : if self . parent : self . parent . update ( self . parent . offset + self . offset ) return self . output . write ( "\n" ) self . output . flush ( ) | Stop overwriting display or update parent . |
61,419 | def _printUUID ( uuid , detail = 'word' ) : if not isinstance ( detail , int ) : detail = detailNum [ detail ] if detail > detailNum [ 'word' ] : return uuid if uuid is None : return None return "%s...%s" % ( uuid [ : 4 ] , uuid [ - 4 : ] ) | Return friendly abbreviated string for uuid . |
61,420 | def skipDryRun ( logger , dryRun , level = logging . DEBUG ) : if not isinstance ( level , int ) : level = logging . getLevelName ( level ) return ( functools . partial ( _logDryRun , logger , level ) if dryRun else functools . partial ( logger . log , level ) ) | Return logging function . |
61,421 | def listVolumes ( self ) : for ( vol , paths ) in self . paths . items ( ) : for path in paths : if path . startswith ( '/' ) : continue if path == '.' : continue if self . userVolume is not None and os . path . basename ( path ) != self . userVolume : continue yield vol break | Return list of all volumes in this Store s selected directory . |
61,422 | def getSendPath ( self , volume ) : try : return self . _fullPath ( next ( iter ( self . getPaths ( volume ) ) ) ) except StopIteration : return None | Get a path appropriate for sending the volume from this Store . |
61,423 | def selectReceivePath ( self , paths ) : logger . debug ( "%s" , paths ) if not paths : path = os . path . basename ( self . userPath ) + '/Anon' try : path = [ p for p in paths if not p . startswith ( "/" ) ] [ 0 ] except IndexError : path = os . path . relpath ( list ( paths ) [ 0 ] , self . userPath ) return self . ... | From a set of source paths recommend a destination path . |
61,424 | def _relativePath ( self , fullPath ) : if fullPath is None : return None assert fullPath . startswith ( "/" ) , fullPath path = os . path . relpath ( fullPath , self . userPath ) if not path . startswith ( "../" ) : return path elif self . ignoreExtraVolumes : return None else : return fullPath | Return fullPath relative to Store directory . |
61,425 | def setSize ( self , size , sizeIsEstimated ) : self . _size = size self . _sizeIsEstimated = sizeIsEstimated if self . fromVol is not None and size is not None and not sizeIsEstimated : Diff . theKnownSizes [ self . toUUID ] [ self . fromUUID ] = size | Update size . |
61,426 | def sendTo ( self , dest , chunkSize ) : vol = self . toVol paths = self . sink . getPaths ( vol ) if self . sink == dest : logger . info ( "Keep: %s" , self ) self . sink . keep ( self ) else : skipDryRun ( logger , dest . dryrun , 'INFO' ) ( "Xfer: %s" , self ) receiveContext = dest . receive ( self , paths ) sendCon... | Send this difference to the dest Store . |
61,427 | def writeInfoLine ( self , stream , fromUUID , size ) : if size is None or fromUUID is None : return if not isinstance ( size , int ) : logger . warning ( "Bad size: %s" , size ) return stream . write ( str ( "%s\t%s\t%d\n" % ( self . uuid , fromUUID , size , ) ) ) | Write one line of diff information . |
61,428 | def writeInfo ( self , stream ) : for ( fromUUID , size ) in Diff . theKnownSizes [ self . uuid ] . iteritems ( ) : self . writeInfoLine ( stream , fromUUID , size ) | Write information about diffs into a file stream for use later . |
61,429 | def hasInfo ( self ) : count = len ( [ None for ( fromUUID , size ) in Diff . theKnownSizes [ self . uuid ] . iteritems ( ) if size is not None and fromUUID is not None ] ) return count > 0 | Will have information to write . |
61,430 | def readInfo ( stream ) : try : for line in stream : ( toUUID , fromUUID , size ) = line . split ( ) try : size = int ( size ) except Exception : logger . warning ( "Bad size: %s" , size ) continue logger . debug ( "diff info: %s %s %d" , toUUID , fromUUID , size ) Diff . theKnownSizes [ toUUID ] [ fromUUID ] = size ex... | Read previously - written information about diffs . |
61,431 | def make ( cls , vol ) : if isinstance ( vol , cls ) : return vol elif vol is None : return None else : return cls ( vol , None ) | Convert uuid to Volume if necessary . |
61,432 | def hasEdge ( self , diff ) : return diff . toVol in [ d . toVol for d in self . diffs [ diff . fromVol ] ] | Test whether edge is in this sink . |
61,433 | def _parseKeyName ( self , name ) : if name . endswith ( Store . theInfoExtension ) : return { 'type' : 'info' } match = self . keyPattern . match ( name ) if not match : return None match = match . groupdict ( ) match . update ( type = 'diff' ) return match | Returns dict with fullpath to from . |
61,434 | def humanize ( number ) : units = ( 'bytes' , 'KiB' , 'MiB' , 'GiB' , 'TiB' ) base = 1024 if number is None : return None pow = int ( math . log ( number , base ) ) if number > 0 else 0 pow = min ( pow , len ( units ) - 1 ) mantissa = number / ( base ** pow ) return "%.4g %s" % ( mantissa , units [ pow ] ) | Return a human - readable string for number . |
61,435 | def receive ( self , path , diff , showProgress = True ) : directory = os . path . dirname ( path ) cmd = [ "btrfs" , "receive" , "-e" , directory ] if Store . skipDryRun ( logger , self . dryrun ) ( "Command: %s" , cmd ) : return None if not os . path . exists ( directory ) : os . makedirs ( directory ) process = subp... | Return a context manager for stream that will store a diff . |
61,436 | def iterDiffs ( self ) : nodes = self . nodes . values ( ) nodes . sort ( key = lambda node : self . _height ( node ) ) for node in nodes : yield node . diff | Return all diffs used in optimal network . |
61,437 | def _prune ( self ) : done = False while not done : done = True for node in [ node for node in self . nodes . values ( ) if node . intermediate ] : if not [ dep for dep in self . nodes . values ( ) if dep . previous == node . volume ] : del self . nodes [ node . volume ] done = False | Get rid of all intermediate nodes that aren t needed . |
61,438 | def __compress_attributes ( self , dic ) : result = { } for k , v in dic . iteritems ( ) : if isinstance ( v , types . ListType ) and len ( v ) == 1 : if k not in ( 'msExchMailboxSecurityDescriptor' , 'msExchSafeSendersHash' , 'msExchBlockedSendersHash' , 'replicationSignature' , 'msExchSafeRecipientsHash' , 'sIDHistor... | This will convert all attributes that are list with only one item string into simple string . It seems that LDAP always return lists even when it doesn t make sense . |
61,439 | def _keepVol ( self , vol ) : if vol is None : return if vol in self . extraVolumes : del self . extraVolumes [ vol ] return if vol not in self . paths : raise Exception ( "%s not in %s" % ( vol , self ) ) paths = [ os . path . basename ( path ) for path in self . paths [ vol ] ] newPath = self . selectReceivePath ( pa... | Mark this volume to be kept in path . |
61,440 | def write ( self , keyArgs ) : args = array . array ( 'B' , ( 0 , ) * self . size ) self . _struct . pack_into ( args , 0 , * list ( self . yieldArgs ( keyArgs ) ) ) return args | Write specified key arguments into data structure . |
61,441 | def popValue ( self , argList ) : return self . _Tuple ( * [ typeObj . popValue ( argList ) for ( name , typeObj ) in self . _types . items ( ) ] ) | Take a flat arglist and pop relevent values and return as a value or tuple . |
61,442 | def read ( self , structure ) : start = self . offset self . skip ( structure . size ) return structure . read ( self . buf , start ) | Read and advance . |
61,443 | def readView ( self , newLength = None ) : if newLength is None : newLength = self . len result = self . peekView ( newLength ) self . skip ( newLength ) return result | Return a view of the next newLength bytes and skip it . |
61,444 | def peekView ( self , newLength ) : return memoryview ( self . buf ) [ self . offset : self . offset + newLength ] | Return a view of the next newLength bytes . |
61,445 | def readBuffer ( self , newLength ) : result = Buffer ( self . buf , self . offset , newLength ) self . skip ( newLength ) return result | Read next chunk as another buffer . |
61,446 | def _IOC ( cls , dir , op , structure = None ) : control = cls ( dir , op , structure ) def do ( dev , ** args ) : return control ( dev , ** args ) return do | Encode an ioctl id . |
61,447 | def IOWR ( cls , op , structure ) : return cls . _IOC ( READ | WRITE , op , structure ) | Returns an ioctl Device method with READ and WRITE arguments . |
61,448 | def bytes2uuid ( b ) : if b . strip ( chr ( 0 ) ) == '' : return None s = b . encode ( 'hex' ) return "%s-%s-%s-%s-%s" % ( s [ 0 : 8 ] , s [ 8 : 12 ] , s [ 12 : 16 ] , s [ 16 : 20 ] , s [ 20 : ] ) | Return standard human - friendly UUID . |
61,449 | def fullPath ( self ) : for ( ( dirTree , dirID , dirSeq ) , ( dirPath , name ) ) in self . links . items ( ) : try : path = self . fileSystem . volumes [ dirTree ] . fullPath if path is not None : return path + ( "/" if path [ - 1 ] != "/" else "" ) + dirPath + name except Exception : logging . debug ( "Haven't import... | Return full butter path from butter root . |
61,450 | def linuxPaths ( self ) : for ( ( dirTree , dirID , dirSeq ) , ( dirPath , name ) ) in self . links . items ( ) : for path in self . fileSystem . volumes [ dirTree ] . linuxPaths : yield path + "/" + dirPath + name if self . fullPath in self . fileSystem . mounts : yield self . fileSystem . mounts [ self . fullPath ] | Return full paths from linux root . |
61,451 | def destroy ( self ) : path = next ( iter ( self . linuxPaths ) ) directory = _Directory ( os . path . dirname ( path ) ) with directory as device : device . SNAP_DESTROY ( name = str ( os . path . basename ( path ) ) , ) | Delete this subvolume from the filesystem . |
61,452 | def copy ( self , path ) : directoryPath = os . path . dirname ( path ) if not os . path . exists ( directoryPath ) : os . makedirs ( directoryPath ) logger . debug ( 'Create copy of %s in %s' , os . path . basename ( path ) , directoryPath ) with self . _snapshot ( ) as source , _Directory ( directoryPath ) as dest : ... | Make another snapshot of this into dirName . |
61,453 | def subvolumes ( self ) : self . SYNC ( ) self . _getDevices ( ) self . _getRoots ( ) self . _getMounts ( ) self . _getUsage ( ) volumes = self . volumes . values ( ) volumes . sort ( key = ( lambda v : v . fullPath ) ) return volumes | Subvolumes contained in this mount . |
61,454 | def _rescanSizes ( self , force = True ) : status = self . QUOTA_CTL ( cmd = BTRFS_QUOTA_CTL_ENABLE ) . status logger . debug ( "CTL Status: %s" , hex ( status ) ) status = self . QUOTA_RESCAN_STATUS ( ) logger . debug ( "RESCAN Status: %s" , status ) if not status . flags : if not force : return self . QUOTA_RESCAN ( ... | Zero and recalculate quota sizes to subvolume sizes will be correct . |
61,455 | def TLV_GET ( attrs , attrNum , format ) : attrView = attrs [ attrNum ] if format == 's' : format = str ( attrView . len ) + format try : ( result , ) = struct . unpack_from ( format , attrView . buf , attrView . offset ) except TypeError : ( result , ) = struct . unpack_from ( format , str ( bytearray ( attrView . buf... | Get a tag - length - value encoded attribute . |
61,456 | def TLV_PUT ( attrs , attrNum , format , value ) : attrView = attrs [ attrNum ] if format == 's' : format = str ( attrView . len ) + format struct . pack_into ( format , attrView . buf , attrView . offset , value ) | Put a tag - length - value encoded attribute . |
61,457 | def command ( name , mode ) : def decorator ( fn ) : commands [ name ] = fn . __name__ _Client . _addMethod ( fn . __name__ , name , mode ) return fn return decorator | Label a method as a command with name . |
61,458 | def diff ( self , diff ) : if diff is None : return None return dict ( toVol = diff . toUUID , fromVol = diff . fromUUID , size = diff . size , sizeIsEstimated = diff . sizeIsEstimated , ) | Serialize to a dictionary . |
61,459 | def _open ( self ) : if self . _process is not None : return cmd = [ 'ssh' , self . _host , 'sudo' , 'buttersink' , '--server' , '--mode' , self . _mode , self . _directory ] logger . debug ( "Connecting with: %s" , cmd ) self . _process = subprocess . Popen ( cmd , stdin = subprocess . PIPE , stderr = sys . stderr , s... | Open connection to remote host . |
61,460 | def _close ( self ) : if self . _process is None : return self . quit ( ) self . _process . stdin . close ( ) logger . debug ( "Waiting for ssh process to finish..." ) self . _process . wait ( ) self . _process = None | Close connection to remote host . |
61,461 | def run ( self ) : normalized = os . path . normpath ( self . path ) + ( "/" if self . path . endswith ( "/" ) else "" ) if self . path != normalized : sys . stderr . write ( "Please use full path '%s'" % ( normalized , ) ) return - 1 self . butterStore = ButterStore . ButterStore ( None , self . path , self . mode , d... | Run the server . Returns with system error code . |
61,462 | def _sendResult ( self , result ) : try : result = json . dumps ( result ) except Exception as error : result = json . dumps ( self . _errorInfo ( command , error ) ) sys . stdout . write ( result ) sys . stdout . write ( "\n" ) sys . stdout . flush ( ) | Send parseable json result of command . |
61,463 | def version ( self ) : return dict ( buttersink = theVersion , btrfs = self . butterStore . butter . btrfsVersion , linux = platform . platform ( ) , ) | Return kernel and btrfs version . |
61,464 | def send ( self , diffTo , diffFrom ) : diff = self . toObj . diff ( diffTo , diffFrom ) self . _open ( self . butterStore . send ( diff ) ) | Do a btrfs send . |
61,465 | def receive ( self , path , diffTo , diffFrom ) : diff = self . toObj . diff ( diffTo , diffFrom ) self . _open ( self . butterStore . receive ( diff , [ path , ] ) ) | Receive a btrfs diff . |
61,466 | def fillVolumesAndPaths ( self ) : return [ ( self . toDict . vol ( vol ) , paths ) for vol , paths in self . butterStore . paths . items ( ) ] | Get all volumes for initialization . |
61,467 | def load_lists ( keys = [ ] , values = [ ] , name = 'NT' ) : mapping = dict ( zip ( keys , values ) ) return mapper ( mapping , _nt_name = name ) | Map namedtuples given a pair of key value lists . |
61,468 | def load_json ( data = None , path = None , name = 'NT' ) : if data and not path : return mapper ( json . loads ( data ) , _nt_name = name ) if path and not data : return mapper ( json . load ( path ) , _nt_name = name ) if data and path : raise ValueError ( 'expected one source and received two' ) | Map namedtuples with json data . |
61,469 | def load_yaml ( data = None , path = None , name = 'NT' ) : if data and not path : return mapper ( yaml . load ( data ) , _nt_name = name ) if path and not data : with open ( path , 'r' ) as f : data = yaml . load ( f ) return mapper ( data , _nt_name = name ) if data and path : raise ValueError ( 'expected one source ... | Map namedtuples with yaml data . |
61,470 | def mapper ( mapping , _nt_name = 'NT' ) : if isinstance ( mapping , Mapping ) and not isinstance ( mapping , AsDict ) : for key , value in list ( mapping . items ( ) ) : mapping [ key ] = mapper ( value ) return namedtuple_wrapper ( _nt_name , ** mapping ) elif isinstance ( mapping , list ) : return [ mapper ( item ) ... | Convert mappings to namedtuples recursively . |
61,471 | def ignore ( mapping ) : if isinstance ( mapping , Mapping ) : return AsDict ( mapping ) elif isinstance ( mapping , list ) : return [ ignore ( item ) for item in mapping ] return mapping | Use ignore to prevent a mapping from being mapped to a namedtuple . |
61,472 | def ensure_dir ( dir_path ) : exists = dir_exists ( dir_path ) if not exists : try : os . makedirs ( dir_path ) except ( Exception , RuntimeError ) , e : raise Exception ( "Unable to create directory %s. Cause %s" % ( dir_path , e ) ) return exists | If DIR_PATH does not exist makes it . Failing that raises Exception . Returns True if dir already existed ; False if it had to be made . |
61,473 | def validate_openssl ( ) : try : open_ssl_exe = which ( "openssl" ) if not open_ssl_exe : raise Exception ( "No openssl exe found in path" ) try : execute_command ( [ open_ssl_exe , "s_client" , "invalidDummyCommand" ] ) except subprocess . CalledProcessError as e : if "fallback_scsv" not in e . output : raise Exceptio... | Validates OpenSSL to ensure it has TLS_FALLBACK_SCSV supported |
61,474 | def validate_against_current_config ( self , current_rs_conf ) : if not current_rs_conf : return my_host = self . get_host ( ) current_member_confs = current_rs_conf [ 'members' ] err = None for curr_mem_conf in current_member_confs : if ( self . id and self . id == curr_mem_conf [ '_id' ] and not is_same_address ( my_... | Validates the member document against current rs conf 1 - If there is a member in current config with _id equals to my id then ensure hosts addresses resolve to the same host |
61,475 | def get_dump_best_secondary ( self , max_repl_lag = None ) : secondary_lag_tuples = [ ] primary_member = self . get_primary_member ( ) if not primary_member : raise MongoctlException ( "Unable to determine primary member for" " cluster '%s'" % self . id ) master_status = primary_member . get_server ( ) . get_member_rs_... | Returns the best secondary member to be used for dumping best = passives with least lags if no passives then least lag |
61,476 | def is_replicaset_initialized ( self ) : for member in self . get_members ( ) : server = member . get_server ( ) if server . has_joined_replica ( ) : return True return False | iterate on all members and check if any has joined the replica |
61,477 | def match_member_id ( self , member_conf , current_member_confs ) : if current_member_confs is None : return None for curr_mem_conf in current_member_confs : if is_same_address ( member_conf [ 'host' ] , curr_mem_conf [ 'host' ] ) : return curr_mem_conf [ '_id' ] return None | Attempts to find an id for member_conf where fom current members confs there exists a element . Returns the id of an element of current confs WHERE member_conf . host and element . host are EQUAL or map to same host |
61,478 | def get_os_dist_info ( ) : distribution = platform . dist ( ) dist_name = distribution [ 0 ] . lower ( ) dist_version_str = distribution [ 1 ] if dist_name and dist_version_str : return dist_name , dist_version_str else : return None , None | Returns the distribution info |
61,479 | def get_mongo_version ( self ) : if self . _mongo_version : return self . _mongo_version mongo_version = self . read_current_mongo_version ( ) if not mongo_version : mongo_version = self . get_configured_mongo_version ( ) self . _mongo_version = mongo_version return self . _mongo_version | Gets mongo version of the server if it is running . Otherwise return version configured in mongoVersion property |
61,480 | def get_server_build_info ( self ) : if self . is_online ( ) : try : return self . get_mongo_client ( ) . server_info ( ) except OperationFailure , ofe : log_exception ( ofe ) if "there are no users authenticated" in str ( ofe ) : admin_db = self . get_db ( "admin" , no_auth = False ) return admin_db . command ( "build... | issues a buildinfo command |
61,481 | def authenticate_db ( self , db , dbname , retry = True ) : log_verbose ( "Server '%s' attempting to authenticate to db '%s'" % ( self . id , dbname ) ) login_user = self . get_login_user ( dbname ) username = None password = None auth_success = False if login_user : username = login_user [ "username" ] if "password" i... | Returns True if we manage to auth to the given db else False . |
61,482 | def needs_repl_key ( self ) : cluster = self . get_cluster ( ) return ( self . supports_repl_key ( ) and cluster is not None and cluster . get_repl_key ( ) is not None ) | We need a repl key if you are auth + a cluster member + version is None or > = 2 . 0 . 0 |
61,483 | def exact_or_minor_exe_version_match ( executable_name , exe_version_tuples , version ) : exe = exact_exe_version_match ( executable_name , exe_version_tuples , version ) if not exe : exe = minor_exe_version_match ( executable_name , exe_version_tuples , version ) return exe | IF there is an exact match then use it OTHERWISE try to find a minor version match |
61,484 | def seconds ( num ) : now = pytime . time ( ) end = now + num until ( end ) | Pause for this many seconds |
61,485 | def _pre_mongod_server_start ( server , options_override = None ) : lock_file_path = server . get_lock_file_path ( ) no_journal = ( server . get_cmd_option ( "nojournal" ) or ( options_override and "nojournal" in options_override ) ) if ( os . path . exists ( lock_file_path ) and server . is_arbiter_server ( ) and no_j... | Does necessary work before starting a server |
61,486 | def prepare_mongod_server ( server ) : log_info ( "Preparing server '%s' for use as configured..." % server . id ) cluster = server . get_cluster ( ) if server . supports_local_users ( ) : users . setup_server_local_users ( server ) if not server . is_cluster_member ( ) or server . is_standalone_config_server ( ) : use... | Contains post start server operations |
61,487 | def _rlimit_min ( one_val , nother_val ) : if one_val < 0 or nother_val < 0 : return max ( one_val , nother_val ) else : return min ( one_val , nother_val ) | Returns the more stringent rlimit value . - 1 means no limit . |
61,488 | def parse ( self , data ) : graph = self . _init_graph ( ) if 'type' not in data or data [ 'type' ] != 'NetworkGraph' : raise ParserError ( 'Parse error, not a NetworkGraph object' ) required_keys = [ 'protocol' , 'version' , 'metric' , 'nodes' , 'links' ] for key in required_keys : if key not in data : raise ParserErr... | Converts a NetJSON NetworkGraph object to a NetworkX Graph object which is then returned . Additionally checks for protocol version revision and metric . |
61,489 | def parse ( self , data ) : graph = self . _init_graph ( ) server = self . _server_common_name graph . add_node ( server ) if data is None : clients = [ ] links = [ ] else : clients = data . client_list . values ( ) links = data . routing_table . values ( ) for client in clients : if client . common_name == 'UNDEF' : c... | Converts a OpenVPN JSON to a NetworkX Graph object which is then returned . |
61,490 | def _txtinfo_to_python ( self , data ) : self . _format = 'txtinfo' lines = data . split ( '\n' ) try : start = lines . index ( 'Table: Topology' ) + 2 except ValueError : raise ParserError ( 'Unrecognized format' ) topology_lines = [ line for line in lines [ start : ] if line ] parsed_lines = [ ] for line in topology_... | Converts txtinfo format to python |
61,491 | def _get_primary_address ( self , mac_address , node_list ) : for local_addresses in node_list : if mac_address in local_addresses : return local_addresses [ 0 ] return mac_address | Uses the _get_aggregated_node_list structure to find the primary mac address associated to a secondary one if none is found returns itself . |
61,492 | def _get_aggregated_node_list ( self , data ) : node_list = [ ] for node in data : local_addresses = [ node [ 'primary' ] ] if 'secondary' in node : local_addresses += node [ 'secondary' ] node_list . append ( local_addresses ) return node_list | Returns list of main and secondary mac addresses . |
61,493 | def _parse_alfred_vis ( self , data ) : graph = self . _init_graph ( ) if 'source_version' in data : self . version = data [ 'source_version' ] if 'vis' not in data : raise ParserError ( 'Parse error, "vis" key not found' ) node_list = self . _get_aggregated_node_list ( data [ 'vis' ] ) for node in data [ "vis" ] : for... | Converts a alfred - vis JSON object to a NetworkX Graph object which is then returned . Additionally checks for source_vesion to determine the batman - adv version . |
61,494 | def json ( self , dict = False , ** kwargs ) : try : graph = self . graph except AttributeError : raise NotImplementedError ( ) return _netjson_networkgraph ( self . protocol , self . version , self . revision , self . metric , graph . nodes ( data = True ) , graph . edges ( data = True ) , dict , ** kwargs ) | Outputs NetJSON format |
61,495 | def diff ( old , new ) : protocol = new . protocol version = new . version revision = new . revision metric = new . metric in_both = _find_unchanged ( old . graph , new . graph ) added_nodes , added_edges = _make_diff ( old . graph , new . graph , in_both ) removed_nodes , removed_edges = _make_diff ( new . graph , old... | Returns differences of two network topologies old and new in NetJSON NetworkGraph compatible format |
61,496 | def _make_diff ( old , new , both ) : diff_edges = new . copy ( ) not_different = [ tuple ( edge ) for edge in both ] diff_edges . remove_edges_from ( not_different ) diff_nodes = new . copy ( ) not_different = [ ] for new_node in new . nodes ( ) : if new_node in old . nodes ( ) : not_different . append ( new_node ) di... | calculates differences between topologies old and new returns a tuple with two network graph objects the first graph contains the added nodes the secnod contains the added links |
61,497 | def _find_unchanged ( old , new ) : edges = [ ] old_edges = [ set ( edge ) for edge in old . edges ( ) ] new_edges = [ set ( edge ) for edge in new . edges ( ) ] for old_edge in old_edges : if old_edge in new_edges : edges . append ( set ( old_edge ) ) return edges | returns edges that are in both old and new |
61,498 | def _find_changed ( old , new , both ) : old_edges = [ ] for edge in old . edges ( data = True ) : if set ( ( edge [ 0 ] , edge [ 1 ] ) ) not in both : continue cost = ( edge [ 2 ] [ 'weight' ] , ) old_edges . append ( set ( ( edge [ 0 ] , edge [ 1 ] , cost ) ) ) new_edges = [ ] for edge in new . edges ( data = True ) ... | returns links that have changed cost |
61,499 | def parse ( self , data ) : graph = self . _init_graph ( ) if len ( data ) != 0 : if "links" not in data [ 0 ] : raise ParserError ( 'Parse error, "links" key not found' ) for node in data : for link in node [ 'links' ] : cost = ( link [ 'txRate' ] + link [ 'rxRate' ] ) / 2.0 graph . add_edge ( node [ 'name' ] , link [... | Converts a BMX6 b6m JSON to a NetworkX Graph object which is then returned . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.