idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
22,600
def prepare ( self , variables ) : initializedsteps = [ ] if variables is None : variables = dict ( ) for step , params , _resources , _files in self . steps : new_params = _complete_parameters ( params , variables ) initializedsteps . append ( step ( new_params ) ) return initializedsteps
Initialize all steps in this recipe using their parameters .
22,601
def _prepare_resources ( self , variables , overrides = None ) : if overrides is None : overrides = { } res_map = { } own_map = { } for decl in self . resources . values ( ) : resource = overrides . get ( decl . name ) if resource is None : args = _complete_parameters ( decl . args , variables ) resource = decl . type ...
Create and optionally open all shared resources .
22,602
def _cleanup_resources ( self , initialized_resources ) : cleanup_errors = [ ] for name , res in initialized_resources . items ( ) : try : if res . opened : res . close ( ) except Exception : _type , value , traceback = sys . exc_info ( ) cleanup_errors . append ( ( name , value , traceback ) ) if len ( cleanup_errors ...
Cleanup all resources that we own that are open .
22,603
def run ( self , variables = None , overrides = None ) : old_dir = os . getcwd ( ) try : os . chdir ( self . run_directory ) initialized_steps = self . prepare ( variables ) owned_resources = { } try : print ( "Running in %s" % self . run_directory ) initialized_resources , owned_resources = self . _prepare_resources (...
Initialize and run this recipe .
22,604
def generate ( env ) : c_file , cxx_file = SCons . Tool . createCFileBuilders ( env ) c_file . add_action ( '.y' , YaccAction ) c_file . add_emitter ( '.y' , yEmitter ) c_file . add_action ( '.yacc' , YaccAction ) c_file . add_emitter ( '.yacc' , yEmitter ) c_file . add_action ( '.ym' , YaccAction ) c_file . add_emitte...
Add Builders and construction variables for yacc to an Environment .
22,605
def generate ( env ) : SCons . Tool . createSharedLibBuilder ( env ) SCons . Tool . createProgBuilder ( env ) env [ 'LINK' ] = '$CC' env [ 'LINKFLAGS' ] = SCons . Util . CLVar ( '' ) env [ 'LINKCOM' ] = '$LINK -q $LINKFLAGS -e$TARGET $SOURCES $LIBS' env [ 'LIBDIRPREFIX' ] = '' env [ 'LIBDIRSUFFIX' ] = '' env [ 'LIBLINK...
Add Builders and construction variables for Borland ilink to an Environment .
22,606
def find_sdk_dir ( self ) : if not SCons . Util . can_read_reg : debug ( 'find_sdk_dir(): can not read registry' ) return None hkey = self . HKEY_FMT % self . hkey_data debug ( 'find_sdk_dir(): checking registry:{}' . format ( hkey ) ) try : sdk_dir = common . read_reg ( hkey ) except SCons . Util . WinError as e : deb...
Try to find the MS SDK from the registry .
22,607
def get_sdk_dir ( self ) : try : return self . _sdk_dir except AttributeError : sdk_dir = self . find_sdk_dir ( ) self . _sdk_dir = sdk_dir return sdk_dir
Return the MSSSDK given the version string .
22,608
def get_sdk_vc_script ( self , host_arch , target_arch ) : if ( host_arch == 'amd64' and target_arch == 'x86' ) : host_arch = target_arch arch_string = target_arch if ( host_arch != target_arch ) : arch_string = '%s_%s' % ( host_arch , target_arch ) debug ( "sdk.py: get_sdk_vc_script():arch_string:%s host_arch:%s targe...
Return the script to initialize the VC compiler installed by SDK
22,609
def format_rpc ( data ) : address , rpc_id , args , resp , _status = data name = rpc_name ( rpc_id ) if isinstance ( args , ( bytes , bytearray ) ) : arg_str = hexlify ( args ) else : arg_str = repr ( args ) if isinstance ( resp , ( bytes , bytearray ) ) : resp_str = hexlify ( resp ) else : resp_str = repr ( resp ) ret...
Format an RPC call and response .
22,610
async def start ( self ) : self . _command_task . start ( ) try : await self . _cleanup_old_connections ( ) except Exception : await self . stop ( ) raise iotile_id = next ( iter ( self . adapter . devices ) ) self . device = self . adapter . devices [ iotile_id ] self . _logger . info ( "Serving device 0x%04X over BLE...
Start serving access to devices over bluetooth .
22,611
async def stop ( self ) : await self . _command_task . future_command ( [ '_set_mode' , 0 , 0 ] ) await self . _cleanup_old_connections ( ) self . _command_task . stop ( ) self . _stream . stop ( ) self . _serial_port . close ( ) await super ( BLED112Server , self ) . stop ( )
Safely shut down this interface
22,612
async def _call_rpc ( self , header ) : length , _ , cmd , feature , address = struct . unpack ( "<BBBBB" , bytes ( header ) ) rpc_id = ( feature << 8 ) | cmd payload = self . rpc_payload [ : length ] self . _logger . debug ( "Calling RPC %d:%04X with %s" , address , rpc_id , binascii . hexlify ( payload ) ) exception ...
Call an RPC given a header and possibly a previously sent payload
22,613
def format_script ( sensor_graph ) : records = [ ] records . append ( SetGraphOnlineRecord ( False , address = 8 ) ) records . append ( ClearDataRecord ( address = 8 ) ) records . append ( ResetGraphRecord ( address = 8 ) ) for node in sensor_graph . nodes : records . append ( AddNodeRecord ( str ( node ) , address = 8...
Create a binary script containing this sensor graph .
22,614
def dump ( self ) : walkers = { } walkers . update ( { str ( walker . selector ) : walker . dump ( ) for walker in self . _queue_walkers } ) walkers . update ( { str ( walker . selector ) : walker . dump ( ) for walker in self . _virtual_walkers } ) return { u'engine' : self . _engine . dump ( ) , u'rollover_storage' :...
Dump the state of this SensorLog .
22,615
def set_rollover ( self , area , enabled ) : if area == u'streaming' : self . _rollover_streaming = enabled elif area == u'storage' : self . _rollover_storage = enabled else : raise ArgumentError ( "You must pass one of 'storage' or 'streaming' to set_rollover" , area = area )
Configure whether rollover is enabled for streaming or storage streams .
22,616
def watch ( self , selector , callback ) : if selector not in self . _monitors : self . _monitors [ selector ] = set ( ) self . _monitors [ selector ] . add ( callback )
Call a function whenever a stream changes .
22,617
def create_walker ( self , selector , skip_all = True ) : if selector . buffered : walker = BufferedStreamWalker ( selector , self . _engine , skip_all = skip_all ) self . _queue_walkers . append ( walker ) return walker if selector . match_type == DataStream . CounterType : walker = CounterStreamWalker ( selector ) el...
Create a stream walker based on the given selector .
22,618
def destroy_walker ( self , walker ) : if walker . buffered : self . _queue_walkers . remove ( walker ) else : self . _virtual_walkers . remove ( walker )
Destroy a previously created stream walker .
22,619
def restore_walker ( self , dumped_state ) : selector_string = dumped_state . get ( u'selector' ) if selector_string is None : raise ArgumentError ( "Invalid stream walker state in restore_walker, missing 'selector' key" , state = dumped_state ) selector = DataStreamSelector . FromString ( selector_string ) walker = se...
Restore a stream walker that was previously serialized .
22,620
def clear ( self ) : for walker in self . _virtual_walkers : walker . skip_all ( ) self . _engine . clear ( ) for walker in self . _queue_walkers : walker . skip_all ( ) self . _last_values = { }
Clear all data from this sensor_log .
22,621
def push ( self , stream , reading ) : reading = copy . copy ( reading ) reading . stream = stream . encode ( ) if stream . buffered : output_buffer = stream . output if self . id_assigner is not None : reading . reading_id = self . id_assigner ( stream , reading ) try : self . _engine . push ( reading ) except Storage...
Push a reading into a stream updating any associated stream walkers .
22,622
def _erase_buffer ( self , output_buffer ) : erase_size = self . _model . get ( u'buffer_erase_size' ) buffer_type = u'storage' if output_buffer : buffer_type = u'streaming' old_readings = self . _engine . popn ( buffer_type , erase_size ) for reading in old_readings : stream = DataStream . FromEncoded ( reading . stre...
Erase readings in the specified buffer to make space .
22,623
def inspect_last ( self , stream , only_allocated = False ) : if only_allocated : found = False for walker in self . _virtual_walkers : if walker . matches ( stream ) : found = True break if not found : raise UnresolvedIdentifierError ( "inspect_last could not find an allocated virtual streamer for the desired stream" ...
Return the last value pushed into a stream .
22,624
def _run_exitfuncs ( ) : while _exithandlers : func , targs , kargs = _exithandlers . pop ( ) func ( * targs , ** kargs )
run any registered exit functions
22,625
def _windowsLdmodTargets ( target , source , env , for_signature ) : return _dllTargets ( target , source , env , for_signature , 'LDMODULE' )
Get targets for loadable modules .
22,626
def _windowsLdmodSources ( target , source , env , for_signature ) : return _dllSources ( target , source , env , for_signature , 'LDMODULE' )
Get sources for loadable modules .
22,627
def _dllEmitter ( target , source , env , paramtp ) : SCons . Tool . msvc . validate_vars ( env ) extratargets = [ ] extrasources = [ ] dll = env . FindIxes ( target , '%sPREFIX' % paramtp , '%sSUFFIX' % paramtp ) no_import_lib = env . get ( 'no_import_lib' , 0 ) if not dll : raise SCons . Errors . UserError ( 'A share...
Common implementation of dll emitter .
22,628
def embedManifestDllCheck ( target , source , env ) : if env . get ( 'WINDOWS_EMBED_MANIFEST' , 0 ) : manifestSrc = target [ 0 ] . get_abspath ( ) + '.manifest' if os . path . exists ( manifestSrc ) : ret = ( embedManifestDllAction ) ( [ target [ 0 ] ] , None , env ) if ret : raise SCons . Errors . UserError ( "Unable ...
Function run by embedManifestDllCheckAction to check for existence of manifest and other conditions and embed the manifest by calling embedManifestDllAction if so .
22,629
def embedManifestExeCheck ( target , source , env ) : if env . get ( 'WINDOWS_EMBED_MANIFEST' , 0 ) : manifestSrc = target [ 0 ] . get_abspath ( ) + '.manifest' if os . path . exists ( manifestSrc ) : ret = ( embedManifestExeAction ) ( [ target [ 0 ] ] , None , env ) if ret : raise SCons . Errors . UserError ( "Unable ...
Function run by embedManifestExeCheckAction to check for existence of manifest and other conditions and embed the manifest by calling embedManifestExeAction if so .
22,630
def generate ( env ) : global PSAction if PSAction is None : PSAction = SCons . Action . Action ( '$PSCOM' , '$PSCOMSTR' ) global DVIPSAction if DVIPSAction is None : DVIPSAction = SCons . Action . Action ( DviPsFunction , strfunction = DviPsStrFunction ) global PSBuilder if PSBuilder is None : PSBuilder = SCons . Buil...
Add Builders and construction variables for dvips to an Environment .
22,631
def build_library ( tile , libname , chip ) : dirs = chip . build_dirs ( ) output_name = '%s_%s.a' % ( libname , chip . arch_name ( ) ) if os . path . exists ( 'firmware' ) : VariantDir ( dirs [ 'build' ] , os . path . join ( 'firmware' , 'src' ) , duplicate = 0 ) else : VariantDir ( dirs [ 'build' ] , 'src' , duplicat...
Build a static ARM cortex library
22,632
def setup_environment ( chip , args_file = None ) : config = ConfigManager ( ) if platform . system ( ) == 'Windows' : env = Environment ( tools = [ 'mingw' ] , ENV = os . environ ) else : env = Environment ( tools = [ 'default' ] , ENV = os . environ ) env [ 'INCPREFIX' ] = '-I"' env [ 'INCSUFFIX' ] = '"' env [ 'CPPDE...
Setup the SCons environment for compiling arm cortex code .
22,633
def tb_h_file_creation ( target , source , env ) : files = [ str ( x ) for x in source ] try : desc = TBDescriptor ( files ) except pyparsing . ParseException as e : raise BuildError ( "Could not parse tilebus file" , parsing_exception = e ) block = desc . get_block ( config_only = True ) block . render_template ( bloc...
Compile tilebus file into only . h files corresponding to config variables for inclusion in a library
22,634
def checksum_creation_action ( target , source , env ) : import crcmod crc32_func = crcmod . mkCrcFun ( 0x104C11DB7 , initCrc = 0xFFFFFFFF , rev = False , xorOut = 0 ) with open ( str ( source [ 0 ] ) , 'rb' ) as f : data = f . read ( ) data = data [ : - 4 ] magicbin = data [ - 4 : ] magic , = struct . unpack ( '<L' , ...
Create a linker command file for patching an application checksum into a firmware image
22,635
def create_arg_file ( target , source , env ) : output_name = str ( target [ 0 ] ) with open ( output_name , "w" ) as outfile : for define in env . get ( 'CPPDEFINES' , [ ] ) : outfile . write ( define + '\n' ) include_folders = target [ 0 ] . RDirs ( tuple ( env . get ( 'CPPPATH' , [ ] ) ) ) include_folders . append (...
Create an argument file containing - I and - D arguments to gcc .
22,636
def merge_hex_executables ( target , source , env ) : output_name = str ( target [ 0 ] ) hex_final = IntelHex ( ) for image in source : file = str ( image ) root , ext = os . path . splitext ( file ) file_format = ext [ 1 : ] if file_format == 'elf' : file = root + '.hex' hex_data = IntelHex ( file ) hex_data . start_a...
Combine all hex files into a singular executable file .
22,637
def ensure_image_is_hex ( input_path ) : family = utilities . get_family ( 'module_settings.json' ) target = family . platform_independent_target ( ) build_dir = target . build_dirs ( ) [ 'build' ] if platform . system ( ) == 'Windows' : env = Environment ( tools = [ 'mingw' ] , ENV = os . environ ) else : env = Enviro...
Return a path to a hex version of a firmware image .
22,638
def _dispatch_rpc ( self , address , rpc_id , arg_payload ) : if self . emulator . is_tile_busy ( address ) : self . _track_change ( 'device.rpc_busy_response' , ( address , rpc_id , arg_payload , None , None ) , formatter = format_rpc ) raise BusyRPCResponse ( ) try : resp = super ( EmulatedDevice , self ) . call_rpc ...
Background work queue handler to dispatch RPCs .
22,639
def rpc ( self , address , rpc_id , * args , ** kwargs ) : if isinstance ( rpc_id , RPCDeclaration ) : arg_format = rpc_id . arg_format resp_format = rpc_id . resp_format rpc_id = rpc_id . rpc_id else : arg_format = kwargs . get ( 'arg_format' , None ) resp_format = kwargs . get ( 'resp_format' , None ) arg_payload = b...
Immediately dispatch an RPC inside this EmulatedDevice .
22,640
def trace_sync ( self , data , timeout = 5.0 ) : done = AwaitableResponse ( ) self . trace ( data , callback = done . set_result ) return done . wait ( timeout )
Send tracing data and wait for it to finish .
22,641
def stream_sync ( self , report , timeout = 120.0 ) : done = AwaitableResponse ( ) self . stream ( report , callback = done . set_result ) return done . wait ( timeout )
Send a report and wait for it to finish .
22,642
def synchronize_task ( self , func , * args , ** kwargs ) : async def _runner ( ) : return func ( * args , ** kwargs ) return self . emulator . run_task_external ( _runner ( ) )
Run callable in the rpc thread and wait for it to finish .
22,643
def load_metascenario ( self , scenario_list ) : for scenario in scenario_list : name = scenario . get ( 'name' ) if name is None : raise DataError ( "Scenario in scenario list is missing a name parameter" , scenario = scenario ) tile_address = scenario . get ( 'tile' ) args = scenario . get ( 'args' , { } ) dest = sel...
Load one or more scenarios from a list .
22,644
def associated_stream ( self ) : if not self . important : raise InternalError ( "You may only call autocopied_stream on when DataStream.important is True" , stream = self ) if self . stream_id >= DataStream . ImportantSystemStorageStart : stream_type = DataStream . BufferedType else : stream_type = DataStream . Output...
Return the corresponding output or storage stream for an important system input .
22,645
def FromString ( cls , string_rep ) : rep = str ( string_rep ) parts = rep . split ( ) if len ( parts ) > 3 : raise ArgumentError ( "Too many whitespace separated parts of stream designator" , input_string = string_rep ) elif len ( parts ) == 3 and parts [ 0 ] != u'system' : raise ArgumentError ( "Too many whitespace s...
Create a DataStream from a string representation .
22,646
def FromEncoded ( self , encoded ) : stream_type = ( encoded >> 12 ) & 0b1111 stream_system = bool ( encoded & ( 1 << 11 ) ) stream_id = ( encoded & ( ( 1 << 11 ) - 1 ) ) return DataStream ( stream_type , stream_id , stream_system )
Create a DataStream from an encoded 16 - bit unsigned integer .
22,647
def as_stream ( self ) : if not self . singular : raise ArgumentError ( "Attempted to convert a non-singular selector to a data stream, it matches multiple" , selector = self ) return DataStream ( self . match_type , self . match_id , self . match_spec == DataStreamSelector . MatchSystemOnly )
Convert this selector to a DataStream .
22,648
def FromStream ( cls , stream ) : if stream . system : specifier = DataStreamSelector . MatchSystemOnly else : specifier = DataStreamSelector . MatchUserOnly return DataStreamSelector ( stream . stream_type , stream . stream_id , specifier )
Create a DataStreamSelector from a DataStream .
22,649
def FromEncoded ( cls , encoded ) : match_spec = encoded & ( ( 1 << 11 ) | ( 1 << 15 ) ) match_type = ( encoded & ( 0b111 << 12 ) ) >> 12 match_id = encoded & ( ( 1 << 11 ) - 1 ) if match_spec not in cls . SpecifierEncodingMap : raise ArgumentError ( "Unknown encoded match specifier" , match_spec = match_spec , known_s...
Create a DataStreamSelector from an encoded 16 - bit value .
22,650
def FromString ( cls , string_rep ) : rep = str ( string_rep ) rep = rep . replace ( u'node' , '' ) rep = rep . replace ( u'nodes' , '' ) if rep . startswith ( u'all' ) : parts = rep . split ( ) spec_string = u'' if len ( parts ) == 3 : spec_string = parts [ 1 ] stream_type = parts [ 2 ] elif len ( parts ) == 2 : strea...
Create a DataStreamSelector from a string .
22,651
def matches ( self , stream ) : if self . match_type != stream . stream_type : return False if self . match_id is not None : return self . match_id == stream . stream_id if self . match_spec == DataStreamSelector . MatchUserOnly : return not stream . system elif self . match_spec == DataStreamSelector . MatchSystemOnly...
Check if this selector matches the given stream
22,652
def encode ( self ) : match_id = self . match_id if match_id is None : match_id = ( 1 << 11 ) - 1 return ( self . match_type << 12 ) | DataStreamSelector . SpecifierEncodings [ self . match_spec ] | match_id
Encode this stream as a packed 16 - bit unsigned integer .
22,653
def generate ( env ) : M4Action = SCons . Action . Action ( '$M4COM' , '$M4COMSTR' ) bld = SCons . Builder . Builder ( action = M4Action , src_suffix = '.m4' ) env [ 'BUILDERS' ] [ 'M4' ] = bld env [ 'M4' ] = 'm4' env [ 'M4FLAGS' ] = SCons . Util . CLVar ( '-E' ) env [ 'M4COM' ] = 'cd ${SOURCE.rsrcdir} && $M4 $M4FLAGS ...
Add Builders and construction variables for m4 to an Environment .
22,654
def generate ( env ) : env . AppendUnique ( LATEXSUFFIXES = SCons . Tool . LaTeXSuffixes ) from . import dvi dvi . generate ( env ) from . import pdf pdf . generate ( env ) bld = env [ 'BUILDERS' ] [ 'DVI' ] bld . add_action ( '.ltx' , LaTeXAuxAction ) bld . add_action ( '.latex' , LaTeXAuxAction ) bld . add_emitter ( ...
Add Builders and construction variables for LaTeX to an Environment .
22,655
def encode_priority ( self , facility , priority ) : return ( facility << 3 ) | self . priority_map . get ( priority , self . LOG_WARNING )
Encode the facility and priority . You can pass in strings or integers - if strings are passed the facility_names and priority_names mapping dictionaries are used to convert them to integers .
22,656
def close ( self ) : self . acquire ( ) try : if self . transport is not None : self . transport . close ( ) super ( Rfc5424SysLogHandler , self ) . close ( ) finally : self . release ( )
Closes the socket .
22,657
def sonTraceRootPath ( ) : import sonLib . bioio i = os . path . abspath ( sonLib . bioio . __file__ ) return os . path . split ( os . path . split ( os . path . split ( i ) [ 0 ] ) [ 0 ] ) [ 0 ]
function for finding external location
22,658
def linOriginRegression ( points ) : j = sum ( [ i [ 0 ] for i in points ] ) k = sum ( [ i [ 1 ] for i in points ] ) if j != 0 : return k / j , j , k return 1 , j , k
computes a linear regression starting at zero
22,659
def close ( i , j , tolerance ) : return i <= j + tolerance and i >= j - tolerance
check two float values are within a bound of one another
22,660
def filterOverlappingAlignments ( alignments ) : l = [ ] alignments = alignments [ : ] sortAlignments ( alignments ) alignments . reverse ( ) for pA1 in alignments : for pA2 in l : if pA1 . contig1 == pA2 . contig1 and getPositiveCoordinateRangeOverlap ( pA1 . start1 + 1 , pA1 . end1 , pA2 . start1 + 1 , pA2 . end1 ) i...
Filter alignments to be non - overlapping .
22,661
def binaryTree_depthFirstNumbers ( binaryTree , labelTree = True , dontStopAtID = True ) : traversalIDs = { } def traverse ( binaryTree , mid = 0 , leafNo = 0 ) : if binaryTree . internal and ( dontStopAtID or binaryTree . iD is None ) : midStart = mid j , leafNo = traverse ( binaryTree . left , mid , leafNo ) mid = j ...
get mid - order depth first tree numbers
22,662
def binaryTree_nodeNames ( binaryTree ) : def fn ( binaryTree , labels ) : if binaryTree . internal : fn ( binaryTree . left , labels ) fn ( binaryTree . right , labels ) labels [ binaryTree . traversalID . mid ] = labels [ binaryTree . left . traversalID . mid ] + "_" + labels [ binaryTree . right . traversalID . mid ...
creates names for the leave and internal nodes of the newick tree from the leaf labels
22,663
def makeRandomBinaryTree ( leafNodeNumber = None ) : while True : nodeNo = [ - 1 ] def fn ( ) : nodeNo [ 0 ] += 1 if random . random ( ) > 0.6 : i = str ( nodeNo [ 0 ] ) return BinaryTree ( 0.00001 + random . random ( ) * 0.8 , True , fn ( ) , fn ( ) , i ) else : return BinaryTree ( 0.00001 + random . random ( ) * 0.8 ...
Creates a random binary tree .
22,664
def getRandomBinaryTreeLeafNode ( binaryTree ) : if binaryTree . internal == True : if random . random ( ) > 0.5 : return getRandomBinaryTreeLeafNode ( binaryTree . left ) else : return getRandomBinaryTreeLeafNode ( binaryTree . right ) else : return binaryTree
Get random binary tree node .
22,665
def transformByDistance ( wV , subModel , alphabetSize = 4 ) : nc = [ 0.0 ] * alphabetSize for i in xrange ( 0 , alphabetSize ) : j = wV [ i ] k = subModel [ i ] for l in xrange ( 0 , alphabetSize ) : nc [ l ] += j * k [ l ] return nc
transform wV by given substitution matrix
22,666
def normaliseWV ( wV , normFac = 1.0 ) : f = sum ( wV ) / normFac return [ i / f for i in wV ]
make char probs divisible by one
22,667
def felsensteins ( binaryTree , subMatrices , ancestorProbs , leaves , alphabetSize ) : l = { } def upPass ( binaryTree ) : if binaryTree . internal : i = branchUp ( binaryTree . left ) j = branchUp ( binaryTree . right ) k = multiplyWV ( i , j , alphabetSize ) l [ binaryTree . traversalID . mid ] = ( k , i , j ) retur...
calculates the un - normalised probabilties of each non - gap residue position
22,668
def annotateTree ( bT , fn ) : l = [ None ] * bT . traversalID . midEnd def fn2 ( bT ) : l [ bT . traversalID . mid ] = fn ( bT ) if bT . internal : fn2 ( bT . left ) fn2 ( bT . right ) fn2 ( bT ) return l
annotate a tree in an external array using the given function
22,669
def remodelTreeRemovingRoot ( root , node ) : import bioio assert root . traversalID . mid != node hash = { } def fn ( bT ) : if bT . traversalID . mid == node : assert bT . internal == False return [ bT ] elif bT . internal : i = fn ( bT . left ) if i is None : i = fn ( bT . right ) if i is not None : hash [ i [ - 1 ]...
Node is mid order number
22,670
def moveRoot ( root , branch ) : import bioio if root . traversalID . mid == branch : return bioio . newickTreeParser ( bioio . printBinaryTree ( root , True ) ) def fn2 ( tree , seq ) : if seq is not None : return '(' + bioio . printBinaryTree ( tree , True ) [ : - 1 ] + ',' + seq + ')' return bioio . printBinaryTree ...
Removes the old root and places the new root at the mid point along the given branch
22,671
def checkGeneTreeMatchesSpeciesTree ( speciesTree , geneTree , processID ) : def fn ( tree , l ) : if tree . internal : fn ( tree . left , l ) fn ( tree . right , l ) else : l . append ( processID ( tree . iD ) ) l = [ ] fn ( speciesTree , l ) l2 = [ ] fn ( geneTree , l2 ) for i in l2 : assert i in l
Function to check ids in gene tree all match nodes in species tree
22,672
def calculateProbableRootOfGeneTree ( speciesTree , geneTree , processID = lambda x : x ) : if geneTree . traversalID . midEnd <= 3 : return ( 0 , 0 , geneTree ) checkGeneTreeMatchesSpeciesTree ( speciesTree , geneTree , processID ) l = [ ] def fn ( tree ) : if tree . traversalID . mid != geneTree . left . traversalID ...
Goes through each root possible branch making it the root . Returns tree that requires the minimum number of duplications .
22,673
def redirectLoggerStreamHandlers ( oldStream , newStream ) : for handler in list ( logger . handlers ) : if handler . stream == oldStream : handler . close ( ) logger . removeHandler ( handler ) for handler in logger . handlers : if handler . stream == newStream : return logger . addHandler ( logging . StreamHandler ( ...
Redirect the stream of a stream handler to a different stream
22,674
def popen ( command , tempFile ) : fileHandle = open ( tempFile , 'w' ) logger . debug ( "Running the command: %s" % command ) sts = subprocess . call ( command , shell = True , stdout = fileHandle , bufsize = - 1 ) fileHandle . close ( ) if sts != 0 : raise RuntimeError ( "Command: %s exited with non-zero status %i" %...
Runs a command and captures standard out in the given temp file .
22,675
def popenCatch ( command , stdinString = None ) : logger . debug ( "Running the command: %s" % command ) if stdinString != None : process = subprocess . Popen ( command , shell = True , stdin = subprocess . PIPE , stdout = subprocess . PIPE , bufsize = - 1 ) output , nothing = process . communicate ( stdinString ) else...
Runs a command and return standard out .
22,676
def getTotalCpuTimeAndMemoryUsage ( ) : me = resource . getrusage ( resource . RUSAGE_SELF ) childs = resource . getrusage ( resource . RUSAGE_CHILDREN ) totalCpuTime = me . ru_utime + me . ru_stime + childs . ru_utime + childs . ru_stime totalMemoryUsage = me . ru_maxrss + me . ru_maxrss return totalCpuTime , totalMem...
Gives the total cpu time and memory usage of itself and its children .
22,677
def saveInputs ( savedInputsDir , listOfFilesAndDirsToSave ) : logger . info ( "Saving the inputs: %s to the directory: %s" % ( " " . join ( listOfFilesAndDirsToSave ) , savedInputsDir ) ) assert os . path . isdir ( savedInputsDir ) createdFiles = [ ] for fileName in listOfFilesAndDirsToSave : if os . path . isfile ( f...
Copies the list of files to a directory created in the save inputs dir and returns the name of this directory .
22,678
def nameValue ( name , value , valueType = str , quotes = False ) : if valueType == bool : if value : return "--%s" % name return "" if value is None : return "" if quotes : return "--%s '%s'" % ( name , valueType ( value ) ) return "--%s %s" % ( name , valueType ( value ) )
Little function to make it easier to make name value strings for commands .
22,679
def makeSubDir ( dirName ) : if not os . path . exists ( dirName ) : os . mkdir ( dirName ) os . chmod ( dirName , 0777 ) return dirName
Makes a given subdirectory if it doesn t already exist making sure it us public .
22,680
def getTempFile ( suffix = "" , rootDir = None ) : if rootDir is None : handle , tmpFile = tempfile . mkstemp ( suffix ) os . close ( handle ) return tmpFile else : tmpFile = os . path . join ( rootDir , "tmp_" + getRandomAlphaNumericString ( ) + suffix ) open ( tmpFile , 'w' ) . close ( ) os . chmod ( tmpFile , 0777 )...
Returns a string representing a temporary file that must be manually deleted
22,681
def getTempDirectory ( rootDir = None ) : if rootDir is None : return tempfile . mkdtemp ( ) else : if not os . path . exists ( rootDir ) : try : os . makedirs ( rootDir ) except OSError : pass while True : tmpDir = os . path . join ( rootDir , "tmp_" + getRandomAlphaNumericString ( ) ) if not os . path . exists ( tmpD...
returns a temporary directory that must be manually deleted . rootDir will be created if it does not exist .
22,682
def catFiles ( filesToCat , catFile ) : if len ( filesToCat ) == 0 : open ( catFile , 'w' ) . close ( ) return maxCat = 25 system ( "cat %s > %s" % ( " " . join ( filesToCat [ : maxCat ] ) , catFile ) ) filesToCat = filesToCat [ maxCat : ] while len ( filesToCat ) > 0 : system ( "cat %s >> %s" % ( " " . join ( filesToC...
Cats a bunch of files into one file . Ensures a no more than maxCat files are concatenated at each step .
22,683
def prettyXml ( elem ) : roughString = ET . tostring ( elem , "utf-8" ) reparsed = minidom . parseString ( roughString ) return reparsed . toprettyxml ( indent = " " )
Return a pretty - printed XML string for the ElementTree Element .
22,684
def fastaEncodeHeader ( attributes ) : for i in attributes : assert len ( str ( i ) . split ( ) ) == 1 return "|" . join ( [ str ( i ) for i in attributes ] )
Decodes the fasta header
22,685
def fastaWrite ( fileHandleOrFile , name , seq , mode = "w" ) : fileHandle = _getFileHandle ( fileHandleOrFile , mode ) valid_chars = { x for x in string . ascii_letters + "-" } try : assert any ( [ isinstance ( seq , unicode ) , isinstance ( seq , str ) ] ) except AssertionError : raise RuntimeError ( "Sequence is not...
Writes out fasta file
22,686
def fastqRead ( fileHandleOrFile ) : fileHandle = _getFileHandle ( fileHandleOrFile ) line = fileHandle . readline ( ) while line != '' : if line [ 0 ] == '@' : name = line [ 1 : - 1 ] seq = fileHandle . readline ( ) [ : - 1 ] plus = fileHandle . readline ( ) if plus [ 0 ] != '+' : raise RuntimeError ( "Got unexpected ...
Reads a fastq file iteratively
22,687
def _getMultiFastaOffsets ( fasta ) : f = open ( fasta , 'r' ) i = 0 j = f . read ( 1 ) l = [ ] while j != '' : i += 1 if j == '>' : i += 1 while f . read ( 1 ) != '\n' : i += 1 l . append ( i ) j = f . read ( 1 ) f . close ( ) return l
Reads in columns of multiple alignment and returns them iteratively
22,688
def fastaReadHeaders ( fasta ) : headers = [ ] fileHandle = open ( fasta , 'r' ) line = fileHandle . readline ( ) while line != '' : assert line [ - 1 ] == '\n' if line [ 0 ] == '>' : headers . append ( line [ 1 : - 1 ] ) line = fileHandle . readline ( ) fileHandle . close ( ) return headers
Returns a list of fasta header lines excluding
22,689
def fastaAlignmentRead ( fasta , mapFn = ( lambda x : x ) , l = None ) : if l is None : l = _getMultiFastaOffsets ( fasta ) else : l = l [ : ] seqNo = len ( l ) for i in xrange ( 0 , seqNo ) : j = open ( fasta , 'r' ) j . seek ( l [ i ] ) l [ i ] = j column = [ sys . maxint ] * seqNo if seqNo != 0 : while True : for j ...
reads in columns of multiple alignment and returns them iteratively
22,690
def fastaAlignmentWrite ( columnAlignment , names , seqNo , fastaFile , filter = lambda x : True ) : fastaFile = open ( fastaFile , 'w' ) columnAlignment = [ i for i in columnAlignment if filter ( i ) ] for seq in xrange ( 0 , seqNo ) : fastaFile . write ( ">%s\n" % names [ seq ] ) for column in columnAlignment : fasta...
Writes out column alignment to given file multi - fasta format
22,691
def getRandomSequence ( length = 500 ) : fastaHeader = "" for i in xrange ( int ( random . random ( ) * 100 ) ) : fastaHeader = fastaHeader + random . choice ( [ 'A' , 'C' , '0' , '9' , ' ' , '\t' ] ) return ( fastaHeader , "" . join ( [ random . choice ( [ 'A' , 'C' , 'T' , 'G' , 'A' , 'C' , 'T' , 'G' , 'A' , 'C' , 'T...
Generates a random name and sequence .
22,692
def mutateSequence ( seq , distance ) : subProb = distance inProb = 0.05 * distance deProb = 0.05 * distance contProb = 0.9 l = [ ] bases = [ 'A' , 'C' , 'T' , 'G' ] i = 0 while i < len ( seq ) : if random . random ( ) < subProb : l . append ( random . choice ( bases ) ) else : l . append ( seq [ i ] ) if random . rand...
Mutates the DNA sequence for use in testing .
22,693
def newickTreeParser ( newickTree , defaultDistance = DEFAULT_DISTANCE , sortNonBinaryNodes = False , reportUnaryNodes = False ) : newickTree = newickTree . replace ( "(" , " ( " ) newickTree = newickTree . replace ( ")" , " ) " ) newickTree = newickTree . replace ( ":" , " : " ) newickTree = newickTree . replace ( ";"...
lax newick tree parser
22,694
def pWMRead ( fileHandle , alphabetSize = 4 ) : lines = fileHandle . readlines ( ) assert len ( lines ) == alphabetSize l = [ [ float ( i ) ] for i in lines [ 0 ] . split ( ) ] for line in lines [ 1 : ] : l2 = [ float ( i ) for i in line . split ( ) ] assert len ( l ) == len ( l2 ) for i in xrange ( 0 , len ( l ) ) : l...
reads in standard position weight matrix format rows are different types of base columns are individual residues
22,695
def pWMWrite ( fileHandle , pWM , alphabetSize = 4 ) : for i in xrange ( 0 , alphabetSize ) : fileHandle . write ( "%s\n" % ' ' . join ( [ str ( pWM [ j ] [ i ] ) for j in xrange ( 0 , len ( pWM ) ) ] ) )
Writes file in standard PWM format is reverse of pWMParser
22,696
def cigarRead ( fileHandleOrFile ) : fileHandle = _getFileHandle ( fileHandleOrFile ) p = re . compile ( "cigar:\\s+(.+)\\s+([0-9]+)\\s+([0-9]+)\\s+([\\+\\-\\.])\\s+(.+)\\s+([0-9]+)\\s+([0-9]+)\\s+([\\+\\-\\.])\\s+([^\\s]+)(\\s+(.*)\\s*)*" ) line = fileHandle . readline ( ) while line != '' : pA = cigarReadFromString (...
Reads a list of pairwise alignments into a pairwise alignment structure .
22,697
def cigarWrite ( fileHandle , pairwiseAlignment , withProbs = True ) : if len ( pairwiseAlignment . operationList ) == 0 : logger . info ( "Writing zero length pairwiseAlignment to file!" ) strand1 = "+" if not pairwiseAlignment . strand1 : strand1 = "-" strand2 = "+" if not pairwiseAlignment . strand2 : strand2 = "-" ...
Writes out the pairwiseAlignment to the file stream .
22,698
def getRandomPairwiseAlignment ( ) : i , j , k , l = _getRandomSegment ( ) m , n , o , p = _getRandomSegment ( ) score = random . choice ( xrange ( - 1000 , 1000 ) ) return PairwiseAlignment ( i , j , k , l , m , n , o , p , score , getRandomOperationList ( abs ( k - j ) , abs ( o - n ) ) )
Gets a random pairwiseAlignment .
22,699
def addEdgeToGraph ( parentNodeName , childNodeName , graphFileHandle , colour = "black" , length = "10" , weight = "1" , dir = "none" , label = "" , style = "" ) : graphFileHandle . write ( 'edge[color=%s,len=%s,weight=%s,dir=%s,label="%s",style=%s];\n' % ( colour , length , weight , dir , label , style ) ) graphFileH...
Links two nodes in the graph together .