idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
16,600 | def bowtie ( self ) : for i in range ( self . cpus ) : # Send the threads to the merge method. :args is empty as I'm using threads = Thread ( target = self . align , args = ( ) ) # Set the daemon to true - something to do with thread management threads . setDaemon ( True ) # Start the threading threads . start ( ) with progressbar ( self . metadata ) as bar : for sample in bar : # Initialise the mapping GenObject sample . mapping = GenObject ( ) # Set an easier to write shortcut for sample.general sagen = sample . general if sagen . bestassemblyfile != "NA" : sagen . QualimapResults = os . path . join ( sagen . outputdirectory , 'qualimap_results' ) # Set the results folder # Create this results folder if necessary make_path ( sagen . QualimapResults ) # Set file names sagen . sortedbam = os . path . join ( sagen . QualimapResults , '{}_sorted.bam' . format ( sample . name ) ) filenoext = os . path . splitext ( sagen . filteredfile ) [ 0 ] sagen . filenoext = filenoext sagen . bowtie2results = os . path . join ( sagen . QualimapResults , sample . name ) # Use fancy new bowtie2 wrapper bowtie2build = Bowtie2BuildCommandLine ( reference = sagen . bestassemblyfile , bt2 = sagen . bowtie2results ) sample . mapping . BamFile = sagen . bowtie2results + "_sorted.bam" # SAMtools sort v1.3 has different run parameters samsort = SamtoolsSortCommandline ( input = sample . mapping . BamFile , o = True , out_prefix = "-" ) samtools = [ SamtoolsViewCommandline ( b = True , S = True , input_file = "-" ) , samsort ] indict = { 'D' : 5 , 'R' : 1 , 'num_mismatches' : 0 , 'seed_length' : 22 , 'i_func' : "S,0,2.50" } # Update the dictionary with the appropriate parameters for paired- vs. single-ended assemblies try : _ = sample . general . mergedreads if len ( sample . general . trimmedcorrectedfastqfiles ) == 2 : indict . update ( { 'm1' : sample . general . trimmedcorrectedfastqfiles [ 0 ] , 'm2' : sample . general . trimmedcorrectedfastqfiles [ 1 ] } ) else : indict . update ( { 'U' : sample . general . trimmedcorrectedfastqfiles [ 0 ] } ) except AttributeError : if len ( sample . general . assemblyfastq ) == 2 : indict . update ( { 'm1' : sample . general . assemblyfastq [ 0 ] , 'm2' : sample . general . assemblyfastq [ 1 ] } ) else : indict . update ( { 'U' : sample . general . assemblyfastq [ 0 ] } ) bowtie2align = Bowtie2CommandLine ( bt2 = sagen . bowtie2results , threads = self . threads , samtools = samtools , * * indict ) # Convert the commands to strings to allow them to be JSON serialized sample . commands . bowtie2align = str ( bowtie2align ) sample . commands . bowtie2build = str ( bowtie2build ) self . bowqueue . put ( ( sample , sample . commands . bowtie2build , sample . commands . bowtie2align ) ) else : sample . commands . samtools = "NA" sample . mapping . MeanInsertSize = 'NA' sample . mapping . MeanCoveragedata = 'NA' self . bowqueue . join ( ) | Create threads and commands for performing reference mapping for qualimap analyses | 828 | 13 |
16,601 | def pilon ( self ) : logging . info ( 'Improving quality of assembly with pilon' ) for i in range ( self . cpus ) : # Send the threads to the merge method. :args is empty as I'm using threads = Thread ( target = self . pilonthreads , args = ( ) ) # Set the daemon to true - something to do with thread management threads . setDaemon ( True ) # Start the threading threads . start ( ) with progressbar ( self . metadata ) as bar : for sample in bar : if sample . general . bestassemblyfile != 'NA' : if sample . general . polish : # Set the name of the unfiltered assembly output file sample . general . contigsfile = sample . general . assemblyfile sample . mapping . pilondir = os . path . join ( sample . general . QualimapResults , 'pilon' ) make_path ( sample . mapping . pilondir ) # Create the command line command sample . mapping . piloncmd = 'pilon --genome {} --bam {} --fix bases --threads {} ' '--outdir {} --changes --mindepth 0.25' . format ( sample . general . contigsfile , sample . mapping . BamFile , self . threads , sample . mapping . pilondir ) self . pilonqueue . put ( sample ) else : sample . general . contigsfile = sample . general . assemblyfile self . pilonqueue . join ( ) | Run pilon to fix any misassemblies in the contigs - will look for SNPs and indels | 314 | 22 |
16,602 | def filter ( self ) : logging . info ( 'Filtering contigs' ) for i in range ( self . cpus ) : # Send the threads to the filter method threads = Thread ( target = self . filterthreads , args = ( ) ) # Set the daemon to true - something to do with thread management threads . setDaemon ( True ) # Start the threading threads . start ( ) with progressbar ( self . metadata ) as bar : for sample in bar : # Set the name of the unfiltered assembly output file if sample . general . bestassemblyfile != 'NA' : sample . general . contigsfile = sample . general . assemblyfile self . filterqueue . put ( sample ) self . filterqueue . join ( ) | Filter contigs based on depth | 156 | 6 |
16,603 | def clear ( self ) : for sample in self . metadata : try : delattr ( sample . depth , 'bases' ) delattr ( sample . depth , 'coverage' ) delattr ( sample . depth , 'length' ) delattr ( sample . depth , 'stddev' ) except AttributeError : pass | Clear out large attributes from the metadata objects | 69 | 8 |
16,604 | def pages_to_json ( queryset ) : # selection may be in the wrong order, and order matters queryset = queryset . order_by ( 'tree_id' , 'lft' ) return simplejson . dumps ( { JSON_PAGE_EXPORT_NAME : JSON_PAGE_EXPORT_VERSION , 'pages' : [ page . dump_json_data ( ) for page in queryset ] } , indent = JSON_PAGE_EXPORT_INDENT , sort_keys = True ) | Return a JSON string export of the pages in queryset . | 116 | 13 |
16,605 | def validate_pages_json_data ( d , preferred_lang ) : from . models import Page errors = [ ] seen_complete_slugs = dict ( ( lang [ 0 ] , set ( ) ) for lang in settings . PAGE_LANGUAGES ) valid_templates = set ( t [ 0 ] for t in settings . get_page_templates ( ) ) valid_templates . add ( settings . PAGE_DEFAULT_TEMPLATE ) if d [ JSON_PAGE_EXPORT_NAME ] != JSON_PAGE_EXPORT_VERSION : return [ _ ( 'Unsupported file version: %s' ) % repr ( d [ JSON_PAGE_EXPORT_NAME ] ) ] , [ ] pages = d [ 'pages' ] for p in pages : # use the complete slug as a way to identify pages in errors slug = p [ 'complete_slug' ] . get ( preferred_lang , None ) seen_parent = False for lang , s in p [ 'complete_slug' ] . items ( ) : if lang not in seen_complete_slugs : continue seen_complete_slugs [ lang ] . add ( s ) if '/' not in s : # root level, no parent req'd seen_parent = True if not seen_parent : parent_slug , ignore = s . rsplit ( '/' , 1 ) if parent_slug in seen_complete_slugs [ lang ] : seen_parent = True else : parent = Page . objects . from_path ( parent_slug , lang , exclude_drafts = False ) if parent and parent . get_complete_slug ( lang ) == parent_slug : # parent not included, but exists on site seen_parent = True if not slug : slug = s if not slug : errors . append ( _ ( "%s has no common language with this site" ) % ( p [ 'complete_slug' ] . values ( ) [ 0 ] , ) ) continue if not seen_parent : errors . append ( _ ( "%s did not include its parent page and a matching" " one was not found on this site" ) % ( slug , ) ) if p [ 'template' ] not in valid_templates : errors . append ( _ ( "%s uses a template not found on this site: %s" ) % ( slug , p [ 'template' ] ) ) continue import_fields = set ( p [ 'content' ] . keys ( ) ) import_fields |= set ( ( 'meta_title' , 'meta_description' , 'meta_keywords' , 'meta_author' , 'fb_page_type' , 'fb_image' ) ) template_fields = set ( p . name for p in get_placeholders ( p [ 'template' ] ) if p . name not in ( 'title' , 'slug' ) ) template_fields |= set ( ( 'meta_title' , 'meta_description' , 'meta_keywords' , 'meta_author' , 'fb_page_type' , 'fb_image' ) ) if template_fields != import_fields : errors . append ( _ ( "%s template contents are different than our " "template: %s" ) % ( slug , p [ 'template' ] ) ) continue return errors | Check if an import of d will succeed and return errors . | 716 | 12 |
16,606 | def import_po_files ( path = 'poexport' , stdout = None ) : import polib from basic_cms . models import Page , Content source_language = settings . PAGE_DEFAULT_LANGUAGE source_list = [ ] pages_to_invalidate = [ ] for page in Page . objects . published ( ) : source_list . extend ( page . content_by_language ( source_language ) ) if stdout is None : import sys stdout = sys . stdout if not path . endswith ( '/' ) : path += '/' for lang in settings . PAGE_LANGUAGES : if lang [ 0 ] != settings . PAGE_DEFAULT_LANGUAGE : stdout . write ( "Update language %s.\n" % lang [ 0 ] ) po_path = path + lang [ 0 ] + '.po' po = polib . pofile ( po_path ) for entry in po : meta_data = entry . tcomment . split ( do_not_msg ) [ 1 ] . split ( "\n" ) placeholder_name = meta_data [ 1 ] . split ( '=' ) [ 1 ] page_id = int ( meta_data [ 2 ] . split ( '=' ) [ 1 ] ) page = Page . objects . get ( id = page_id ) current_content = Content . objects . get_content ( page , lang [ 0 ] , placeholder_name ) if current_content != entry . msgstr : stdout . write ( "Update page %d placeholder %s.\n" % ( page_id , placeholder_name ) ) Content . objects . create_content_if_changed ( page , lang [ 0 ] , placeholder_name , entry . msgstr ) if page not in pages_to_invalidate : pages_to_invalidate . append ( page ) for page in pages_to_invalidate : page . invalidate ( ) stdout . write ( "Import finished from %s.\n" % path ) | Import all the content updates from the po files into the pages . | 436 | 13 |
16,607 | def setCalibration ( self , db_boost_array , frequencies , frange ) : self . calibrationVector = db_boost_array self . calibrationFrequencies = frequencies self . calibrationFrange = frange for test in self . _tests : test . setCalibration ( db_boost_array , frequencies , frange ) | Sets calibration for all tests | 72 | 6 |
16,608 | def insert ( self , stim , position ) : if position == - 1 : position = self . rowCount ( ) stim . setReferenceVoltage ( self . caldb , self . calv ) stim . setCalibration ( self . calibrationVector , self . calibrationFrequencies , self . calibrationFrange ) self . _tests . insert ( position , stim ) | Inserts a new stimulus into the list at the given position | 79 | 12 |
16,609 | def verify ( self , windowSize = None ) : if self . rowCount ( ) == 0 : return "Protocol must have at least one test" if self . caldb is None or self . calv is None : return "Protocol reference voltage not set" for test in self . _tests : msg = test . verify ( windowSize ) if msg : return msg return 0 | Verify that this protocol model is valid . Return 0 if sucessful a failure message otherwise | 81 | 19 |
16,610 | def open_any ( filename ) : if filename . endswith ( ".gz" ) : return gzip . open if filename . endswith ( ".bz2" ) : return bz2 . BZ2File return open | Helper to open also compressed files | 50 | 6 |
16,611 | def _get_group_no ( self , tag_name ) : if tag_name in self . full : return self . groups . index ( self . full [ tag_name ] [ "parent" ] ) else : return len ( self . groups ) | Takes tag name and returns the number of the group to which tag belongs | 54 | 15 |
16,612 | async def add ( self , setname , ip , timeout = 0 ) : args = [ 'add' , '-exist' , setname , ip , 'timeout' , timeout ] return await self . start ( __class__ . CMD , * args ) | Adds the given IP address to the given ipset . If a timeout is given the IP will stay in the ipset for the given duration . Else it s added forever . | 56 | 37 |
16,613 | async def list ( self , setname = None ) : args = [ 'list' ] if setname is not None : args . append ( setname ) return await self . start ( __class__ . CMD , * args ) | Lists the existing ipsets . | 50 | 8 |
16,614 | def setup ( self , interval ) : self . trace_counter = 0 self . _halt = False self . interval = interval | Prepares the tests for execution interval in ms | 27 | 9 |
16,615 | def run ( self ) : self . _initialize_run ( ) stimuli = self . protocol_model . allTests ( ) self . acq_thread = threading . Thread ( target = self . _worker , args = ( stimuli , ) , ) # save the current calibration to data file doc if self . save_data : info = { 'calibration_used' : self . calname , 'calibration_range' : self . cal_frange } self . datafile . set_metadata ( self . current_dataset_name , info ) # save the start time and set last tick to expired, so first # acquisition loop iteration executes immediately self . start_time = time . time ( ) self . last_tick = self . start_time - ( self . interval / 1000 ) self . acq_thread . start ( ) return self . acq_thread | Runs the acquisition | 190 | 4 |
16,616 | def train ( self , x_data , y_data ) : x_train , _ , y_train , _ = train_test_split ( x_data , y_data , test_size = 0.67 , random_state = None ) # cross-split self . model . fit ( x_train , y_train ) | Trains model on inputs | 72 | 5 |
16,617 | def get_max_similar ( string , lst ) : max_similarity , index = 0.0 , - 1 for i , candidate in enumerate ( lst ) : sim = how_similar_are ( str ( string ) , str ( candidate ) ) if sim > max_similarity : max_similarity , index = sim , i return max_similarity , index | Finds most similar string in list | 81 | 7 |
16,618 | def get_average_length_of_string ( strings ) : if not strings : return 0 return sum ( len ( word ) for word in strings ) / len ( strings ) | Computes average length of words | 37 | 6 |
16,619 | def true_false_returns ( func ) : @ functools . wraps ( func ) def _execute ( * args , * * kwargs ) : """Executes function, if error returns False, else True :param args: args of function :param kwargs: extra args of function :param *args: args :param **kwargs: extra args :return: True iff ok, else False """ try : func ( * args , * * kwargs ) return True except : return False return _execute | Executes function if error returns False else True | 110 | 9 |
16,620 | def none_returns ( func ) : @ functools . wraps ( func ) def _execute ( * args , * * kwargs ) : """Executes function, if error returns None else value of function :param args: args of function :param kwargs: extra args of function :param *args: args :param **kwargs: extra args :return: None else value of function """ try : return func ( * args , * * kwargs ) except : return None return _execute | Executes function if error returns None else value of function | 106 | 11 |
16,621 | def select_dag_nodes ( reftrack ) : refobj = reftrack . get_refobj ( ) if not refobj : return parentns = common . get_namespace ( refobj ) ns = cmds . getAttr ( "%s.namespace" % refobj ) fullns = ":" . join ( ( parentns . rstrip ( ":" ) , ns . lstrip ( ":" ) ) ) c = cmds . namespaceInfo ( fullns , listOnlyDependencyNodes = True , dagPath = True , recurse = True ) dag = cmds . ls ( c , dag = True , ap = True ) cmds . select ( dag , replace = True ) | Select all dag nodes of the given reftrack | 153 | 10 |
16,622 | def get_scenenode ( self , nodes ) : scenenodes = cmds . ls ( nodes , type = 'jb_sceneNode' ) assert scenenodes , "Found no scene nodes!" return sorted ( scenenodes ) [ 0 ] | Get the scenenode in the given nodes | 55 | 9 |
16,623 | def reference ( self , refobj , taskfileinfo ) : # work in root namespace with common . preserve_namespace ( ":" ) : jbfile = JB_File ( taskfileinfo ) filepath = jbfile . get_fullpath ( ) ns_suggestion = reftrack . get_namespace ( taskfileinfo ) newnodes = cmds . file ( filepath , reference = True , namespace = ns_suggestion , returnNewNodes = True ) # You could also use the filename returned by the file command to query the reference node. # Atm there is a but, that if you import the file before, the command fails. # So we get all new reference nodes and query the one that is not referenced for refnode in cmds . ls ( newnodes , type = 'reference' ) : if not cmds . referenceQuery ( refnode , isNodeReferenced = True ) : node = refnode break ns = cmds . referenceQuery ( node , namespace = True ) # query the actual new namespace content = cmds . namespaceInfo ( ns , listOnlyDependencyNodes = True , dagPath = True ) # get the content # connect reftrack with scenenode scenenode = self . get_scenenode ( content ) self . get_refobjinter ( ) . connect_reftrack_scenenode ( refobj , scenenode ) reccontent = cmds . namespaceInfo ( ns , listOnlyDependencyNodes = True , dagPath = True , recurse = True ) # get the content + content of children dagcontent = cmds . ls ( reccontent , ap = True , assemblies = True ) # get only the top level dagnodes so we can group them if not dagcontent : return node # no need for a top group if there are not dagnodes to group # group the dagnodes grpname = reftrack . get_groupname ( taskfileinfo ) reftrack . group_content ( dagcontent , ns , grpname , "jb_asset" ) return node | Reference the given taskfileinfo into the scene and return the created reference node | 451 | 15 |
16,624 | def replace ( self , refobj , reference , taskfileinfo ) : jbfile = JB_File ( taskfileinfo ) filepath = jbfile . get_fullpath ( ) cmds . file ( filepath , loadReference = reference ) ns = cmds . referenceQuery ( reference , namespace = True ) # query the actual new namespace content = cmds . namespaceInfo ( ns , listOnlyDependencyNodes = True , dagPath = True ) # get the content scenenode = self . get_scenenode ( content ) # get the scene node self . get_refobjinter ( ) . connect_reftrack_scenenode ( refobj , scenenode ) | Replace the given reference with the given taskfileinfo | 151 | 11 |
16,625 | def delete ( self , refobj ) : refobjinter = self . get_refobjinter ( ) reference = refobjinter . get_reference ( refobj ) if reference : fullns = cmds . referenceQuery ( reference , namespace = True ) cmds . file ( removeReference = True , referenceNode = reference ) else : parentns = common . get_namespace ( refobj ) ns = cmds . getAttr ( "%s.namespace" % refobj ) fullns = ":" . join ( ( parentns . rstrip ( ":" ) , ns . lstrip ( ":" ) ) ) cmds . namespace ( removeNamespace = fullns , deleteNamespaceContent = True ) | Delete the content of the given refobj | 150 | 8 |
16,626 | def import_reference ( self , refobj , reference ) : cmds . file ( importReference = True , referenceNode = reference ) | Import the given reference | 28 | 4 |
16,627 | def create_options_model ( self , taskfileinfos ) : rootdata = ListItemData ( [ "Asset/Shot" , "Task" , "Descriptor" , "Version" , "Releasetype" ] ) rootitem = TreeItem ( rootdata ) tasks = defaultdict ( list ) for tfi in taskfileinfos : tasks [ tfi . task ] . append ( tfi ) for task in reversed ( sorted ( tasks . keys ( ) , key = lambda t : t . department . ordervalue ) ) : tfis = tasks [ task ] taskdata = djitemdata . TaskItemData ( task ) taskitem = TreeItem ( taskdata , rootitem ) for tfi in reversed ( tfis ) : tfidata = TaskFileInfoItemData ( tfi ) TreeItem ( tfidata , taskitem ) return TreeModel ( rootitem ) | Create a new treemodel that has the taskfileinfos as internal_data of the leaves . | 191 | 22 |
16,628 | def get_scene_suggestions ( self , current ) : l = [ ] if isinstance ( current , djadapter . models . Asset ) : l . append ( current ) l . extend ( list ( current . assets . all ( ) ) ) return l | Return a list with elements for reftracks for the current scene with this type . | 55 | 18 |
16,629 | def init_ui ( self , ) : self . mm = MenuManager . get ( ) p = self . mm . menus [ 'Jukebox' ] self . menu = self . mm . create_menu ( "Preferences" , p , command = self . run ) | Create the menu \ Preferences \ under \ Jukebox \ to start the plugin | 58 | 16 |
16,630 | def setupArgparse ( ) : parser = argparse . ArgumentParser ( ) # Required arguments parser . add_argument ( "callsign" , help = "Callsign of radio" ) parser . add_argument ( "id" , type = int , help = "ID number radio" ) # Optional arguments parser . add_argument ( "-l" , "--loopback" , action = "store_true" , help = "Use software loopback serial port" ) parser . add_argument ( "-p" , "--port" , default = "/dev/ttyUSB0" , help = "Physical serial port of radio" ) # Parse and return arguments return parser . parse_args ( ) | Sets up argparse module to create command line options and parse them . | 150 | 15 |
16,631 | def setupSerialPort ( loopback , port ) : if loopback : # Implement loopback software serial port testSerial = SerialTestClass ( ) serialPort = testSerial . serialPort else : # TODO enable serial port command line options (keep simple for user!) serialPort = serial . Serial ( port , 115200 , timeout = 0 ) return serialPort | Sets up serial port by connecting to phsyical or software port . | 74 | 15 |
16,632 | def main ( ) : print ( "Executing faradayio-cli version {0}" . format ( __version__ ) ) # Setup command line arguments try : args = setupArgparse ( ) except argparse . ArgumentError as error : raise SystemExit ( error ) # Setup serial port try : serialPort = setupSerialPort ( args . loopback , args . port ) except serial . SerialException as error : raise SystemExit ( error ) # Create TUN adapter name tunName = "{0}-{1}" . format ( args . callsign . upper ( ) , args . id ) # Create threading event for TUN thread control # set() causes while loop to continuously run until clear() is run isRunning = threading . Event ( ) isRunning . set ( ) # Setup TUN adapter and start try : tun = Monitor ( serialPort = serialPort , name = tunName , isRunning = isRunning ) tun . start ( ) except pytun . Error as error : print ( "Warning! faradayio-cli must be run with sudo privileges!" ) raise SystemExit ( error ) # loop infinitely until KeyboardInterrupt, then clear() event, exit thread try : while True : # Check for KeyboardInterrupt every 100ms time . sleep ( 0.1 ) except KeyboardInterrupt : tun . isRunning . clear ( ) tun . join ( ) | Main function of faradayio - cli client . | 285 | 11 |
16,633 | def lookup_email ( args ) : email = args . email if email is None : email = gituseremail ( ) if email is None : raise RuntimeError ( textwrap . dedent ( """\ unable to determine a git email Specify --email option\ """ ) ) debug ( "email is {email}" . format ( email = email ) ) return email | Return the email address to use when creating git objects or exit program . | 76 | 14 |
16,634 | def lookup_user ( args ) : user = args . user if user is None : user = gitusername ( ) if user is None : raise RuntimeError ( textwrap . dedent ( """\ unable to determine a git user name Specify --user option\ """ ) ) debug ( "user name is {user}" . format ( user = user ) ) return user | Return the user name to use when creating git objects or exit program . | 77 | 14 |
16,635 | def current_timestamp ( ) : now = datetime . utcnow ( ) timestamp = now . isoformat ( ) [ 0 : 19 ] + 'Z' debug ( "generated timestamp: {now}" . format ( now = timestamp ) ) return timestamp | Returns current time as ISO8601 formatted string in the Zulu TZ | 54 | 15 |
16,636 | def calc_spectrum ( signal , rate ) : npts = len ( signal ) padto = 1 << ( npts - 1 ) . bit_length ( ) # print 'length of signal {}, pad to {}'.format(npts, padto) npts = padto sp = np . fft . rfft ( signal , n = padto ) / npts # print('sp len ', len(sp)) freq = np . arange ( ( npts / 2 ) + 1 ) / ( npts / rate ) # print('freq len ', len(freq)) return freq , abs ( sp ) | Return the spectrum and frequency indexes for real - valued input signal | 142 | 12 |
16,637 | def spectrogram ( source , nfft = 512 , overlap = 90 , window = 'hanning' , caldb = 93 , calv = 2.83 ) : if isinstance ( source , basestring ) : fs , wavdata = audioread ( source ) else : fs , wavdata = source # truncate to nears ms duration = float ( len ( wavdata ) ) / fs desired_npts = int ( ( np . trunc ( duration * 1000 ) / 1000 ) * fs ) # print 'LENGTH {}, DESIRED {}'.format(len(wavdata), desired_npts) wavdata = wavdata [ : desired_npts ] duration = len ( wavdata ) / fs if VERBOSE : amp = rms ( wavdata , fs ) print 'RMS of input signal to spectrogram' , amp # normalize if len ( wavdata ) > 0 and np . max ( abs ( wavdata ) ) != 0 : wavdata = wavdata / np . max ( abs ( wavdata ) ) if window == 'hanning' : winfnc = mlab . window_hanning elif window == 'hamming' : winfnc = np . hamming ( nfft ) elif window == 'blackman' : winfnc = np . blackman ( nfft ) elif window == 'bartlett' : winfnc = np . bartlett ( nfft ) elif window == None or window == 'none' : winfnc = mlab . window_none noverlap = int ( nfft * ( float ( overlap ) / 100 ) ) Pxx , freqs , bins = mlab . specgram ( wavdata , NFFT = nfft , Fs = fs , noverlap = noverlap , pad_to = nfft * 2 , window = winfnc , detrend = mlab . detrend_none , sides = 'default' , scale_by_freq = False ) # log of zero is -inf, which is not great for plotting Pxx [ Pxx == 0 ] = np . nan # convert to db scale for display spec = 20. * np . log10 ( Pxx ) # set 0 to miniumum value in spec? # would be great to have spec in db SPL, and set any -inf to 0 spec [ np . isnan ( spec ) ] = np . nanmin ( spec ) return spec , freqs , bins , duration | Produce a matrix of spectral intensity uses matplotlib s specgram function . Output is in dB scale . | 545 | 22 |
16,638 | def convolve_filter ( signal , impulse_response ) : if impulse_response is not None : # print 'interpolated calibration'#, self.calibration_frequencies adjusted_signal = fftconvolve ( signal , impulse_response ) adjusted_signal = adjusted_signal [ len ( impulse_response ) / 2 : len ( adjusted_signal ) - len ( impulse_response ) / 2 + 1 ] return adjusted_signal else : return signal | Convovle the two input signals if impulse_response is None returns the unaltered signal | 103 | 20 |
16,639 | def attenuation_curve ( signal , resp , fs , calf , smooth_pts = 99 ) : # remove dc offset y = resp - np . mean ( resp ) x = signal # frequencies present in calibration spectrum npts = len ( y ) fq = np . arange ( npts / 2 + 1 ) / ( float ( npts ) / fs ) # convert time signals to frequency domain Y = np . fft . rfft ( y ) X = np . fft . rfft ( x ) # take the magnitude of signals Ymag = np . sqrt ( Y . real ** 2 + Y . imag ** 2 ) # equivalent to abs(Y) Xmag = np . sqrt ( X . real ** 2 + X . imag ** 2 ) # convert to decibel scale YmagdB = 20 * np . log10 ( Ymag ) XmagdB = 20 * np . log10 ( Xmag ) # now we can substract to get attenuation curve diffdB = XmagdB - YmagdB # may want to smooth results here? diffdB = smooth ( diffdB , smooth_pts ) # shift by the given calibration frequency to align attenutation # with reference point set by user fidx = ( np . abs ( fq - calf ) ) . argmin ( ) diffdB -= diffdB [ fidx ] return diffdB | Calculate an attenuation roll - off curve from a signal and its recording | 292 | 16 |
16,640 | def calibrate_signal ( signal , resp , fs , frange ) : # remove dc offset from recorded response (synthesized orignal shouldn't have one) dc = np . mean ( resp ) resp = resp - dc npts = len ( signal ) f0 = np . ceil ( frange [ 0 ] / ( float ( fs ) / npts ) ) f1 = np . floor ( frange [ 1 ] / ( float ( fs ) / npts ) ) y = resp # y = y/np.amax(y) # normalize Y = np . fft . rfft ( y ) x = signal # x = x/np.amax(x) # normalize X = np . fft . rfft ( x ) H = Y / X # still issues warning because all of Y/X is executed to selected answers from # H = np.where(X.real!=0, Y/X, 1) # H[:f0].real = 1 # H[f1:].real = 1 # H = smooth(H) A = X / H return np . fft . irfft ( A ) | Given original signal and recording spits out a calibrated signal | 254 | 11 |
16,641 | def multiply_frequencies ( signal , fs , frange , calibration_frequencies , attendB ) : npts = len ( signal ) padto = 1 << ( npts - 1 ) . bit_length ( ) X = np . fft . rfft ( signal , n = padto ) npts = padto f = np . arange ( ( npts / 2 ) + 1 ) / ( npts / fs ) fidx_low = ( np . abs ( f - frange [ 0 ] ) ) . argmin ( ) fidx_high = ( np . abs ( f - frange [ 1 ] ) ) . argmin ( ) cal_func = interp1d ( calibration_frequencies , attendB ) roi = f [ fidx_low : fidx_high ] Hroi = cal_func ( roi ) H = np . zeros ( ( len ( X ) , ) ) H [ fidx_low : fidx_high ] = Hroi H = smooth ( H ) # print 'H dB max', np.amax(H) H = 10 ** ( ( H ) . astype ( float ) / 20 ) # print 'H amp max', np.amax(H) # Xadjusted = X.copy() # Xadjusted[fidx_low:fidx_high] *= H # Xadjusted = smooth(Xadjusted) Xadjusted = X * H # print 'X max', np.amax(abs(X)) # print 'Xadjusted max', np.amax(abs(Xadjusted)) signal_calibrated = np . fft . irfft ( Xadjusted ) return signal_calibrated [ : len ( signal ) ] | Given a vector of dB attenuations adjust signal by multiplication in the frequency domain | 378 | 15 |
16,642 | def audioread ( filename ) : try : if '.wav' in filename . lower ( ) : fs , signal = wv . read ( filename ) elif '.call' in filename . lower ( ) : with open ( filename , 'rb' ) as f : signal = np . fromfile ( f , dtype = np . int16 ) fs = 333333 else : raise IOError ( "Unsupported audio format for file: {}" . format ( filename ) ) except : print u"Problem reading wav file" raise signal = signal . astype ( float ) return fs , signal | Reads an audio signal from file . | 124 | 8 |
16,643 | def audiorate ( filename ) : if '.wav' in filename . lower ( ) : wf = wave . open ( filename ) fs = wf . getframerate ( ) wf . close ( ) elif '.call' in filename . lower ( ) : fs = 333333 else : raise IOError ( "Unsupported audio format for file: {}" . format ( filename ) ) return fs | Determines the samplerate of the given audio recording file | 84 | 13 |
16,644 | def init_ui ( self , ) : self . sidebar = self . get_maya_sidebar ( ) self . lay = self . sidebar . layout ( ) self . tool_pb = QtGui . QPushButton ( "JB Wins" ) self . tooltip = JB_WindowToolTip ( ) self . tooltip . install_tooltip ( self . tool_pb ) self . lay . addWidget ( self . tool_pb ) self . tool_pb . clicked . connect ( self . tooltip . show ) | Create the tooltip in the sidebar | 110 | 6 |
16,645 | def uninit_ui ( self ) : self . lay . removeWidget ( self . tool_pb ) self . tooltip . deleteLater ( ) self . tool_pb . deleteLater ( ) | Delete the tooltip | 40 | 3 |
16,646 | def open_acqdata ( filename , user = 'unknown' , filemode = 'w-' ) : if filename . lower ( ) . endswith ( ( ".hdf5" , ".h5" ) ) : return HDF5Data ( filename , user , filemode ) elif filename . lower ( ) . endswith ( ( ".pst" , ".raw" ) ) : return BatlabData ( filename , user , filemode ) else : print "File format not supported: " , filename | Opens and returns the correct AcquisitionData object according to filename extention . | 109 | 15 |
16,647 | def columnCount ( self , parent = QtCore . QModelIndex ( ) ) : if parent . isValid ( ) : return self . _stim . columnCount ( parent . row ( ) ) else : return self . _stim . columnCount ( ) | Determines the numbers of columns the view will draw | 53 | 11 |
16,648 | def removeItem ( self , index ) : self . _stim . removeComponent ( index . row ( ) , index . column ( ) ) | Alias for removeComponent | 29 | 4 |
16,649 | def setEditor ( self , name ) : editor = get_stimulus_editor ( name ) self . editor = editor self . _stim . setStimType ( name ) | Sets the editor class for this Stimulus | 37 | 9 |
16,650 | def showEditor ( self ) : if self . editor is not None : editor = self . editor ( ) editor . setModel ( self ) factory = get_stimulus_factory ( self . _stim . stimType ( ) ) editor . editingFinished . connect ( factory . update ) return editor else : logger = logging . getLogger ( 'main' ) logger . warning ( 'Erm, no editor available :(' ) | Creates and shows an editor for this Stimulus | 91 | 10 |
16,651 | def randomToggle ( self , randomize ) : if randomize : self . _stim . setReorderFunc ( order_function ( 'random' ) , 'random' ) else : self . _stim . reorder = None | Sets the reorder function on this StimulusModel to a randomizer or none alternately | 50 | 19 |
16,652 | def assert_variable_type ( variable , expected_type , raise_exception = True ) : # if expected type is not a list make it one if not isinstance ( expected_type , list ) : expected_type = [ expected_type ] # make sure all entries in the expected_type list are types for t in expected_type : if not isinstance ( t , type ) : raise ValueError ( 'expected_type argument "%s" is not a type' % str ( t ) ) # make sure raise_exception is a bool if not isinstance ( raise_exception , bool ) : raise ValueError ( 'raise_exception argument "%s" is not a bool' % str ( raise_exception ) ) # check the type of the variable against the list # then raise an exception or return True if not len ( [ ( t ) for t in expected_type if isinstance ( variable , t ) ] ) : error_message = '"%s" is not an instance of type %s. It is of type %s' % ( str ( variable ) , ' or ' . join ( [ str ( t ) for t in expected_type ] ) , str ( type ( variable ) ) ) if raise_exception : raise ValueError ( error_message ) else : return False , error_message return True , None | Return True if a variable is of a certain type or types . Otherwise raise a ValueError exception . | 285 | 20 |
16,653 | def closeEvent ( self , event ) : self . ok . setText ( "Checking..." ) QtGui . QApplication . processEvents ( ) self . model ( ) . cleanComponents ( ) self . model ( ) . purgeAutoSelected ( ) msg = self . model ( ) . verify ( ) if not msg : msg = self . model ( ) . warning ( ) if msg : warnBox = QtGui . QMessageBox ( QtGui . QMessageBox . Warning , 'Warning - Invalid Settings' , '{}. Do you want to change this?' . format ( msg ) ) yesButton = warnBox . addButton ( self . tr ( 'Edit' ) , QtGui . QMessageBox . YesRole ) noButton = warnBox . addButton ( self . tr ( 'Ignore' ) , QtGui . QMessageBox . NoRole ) warnBox . exec_ ( ) if warnBox . clickedButton ( ) == yesButton : event . ignore ( ) self . ok . setText ( "OK" ) | Verifies the stimulus before closing warns user with a dialog if there are any problems | 222 | 16 |
16,654 | def close ( self , reason = None ) : with self . _closing : if self . _closed : return self . _websocket . close ( ) self . _consumer . join ( ) self . _consumer = None self . _websocket = None self . _closed = True for cb in self . _close_callbacks : cb ( self , reason ) | Stop consuming messages and perform an orderly shutdown . | 81 | 9 |
16,655 | def dropEvent ( self , event ) : super ( TrashWidget , self ) . dropEvent ( event ) self . itemTrashed . emit ( ) | Emits the itemTrashed signal data contained in drag operation left to be garbage collected | 31 | 17 |
16,656 | def choose ( self , choose_from ) : for choice in self . elements : if choice in choose_from : return ImplementationChoice ( choice , choose_from [ choice ] ) raise LookupError ( self . elements , choose_from . keys ( ) ) | given a mapping of implementations choose one based on the current settings returns a key value pair | 54 | 17 |
16,657 | def remove ( self ) : import shutil printtime ( 'Removing large and/or temporary files' , self . start ) removefolder = list ( ) for sample in self . metadata : # Use os.walk to iterate through all the files in the sample output directory for path , dirs , files in os . walk ( sample . general . outputdirectory ) : for item in files : # Use regex to find files to remove if re . search ( ".fastq$" , item ) or re . search ( ".fastq.gz$" , item ) or re . search ( ".bam$" , item ) or re . search ( ".bt2$" , item ) or re . search ( ".tab$" , item ) or re . search ( "^before" , item ) or re . search ( "^baitedtargets" , item ) or re . search ( "_combined.csv$" , item ) or re . search ( "^scaffolds" , item ) or re . search ( ".fastg$" , item ) or re . search ( ".gfa$" , item ) or re . search ( ".bai$" , item ) or 'coregenome' in path or 'prophages' in path : # Keep the baitedtargets.fa, core genome, and merged metagenome files if item != 'baitedtargets.fa' and not re . search ( "coregenome" , item ) and not re . search ( "paired" , item ) : # Remove the unnecessary files try : os . remove ( os . path . join ( path , item ) ) except IOError : pass # Clear out the folders for folder in removefolder : try : shutil . rmtree ( folder ) except ( OSError , TypeError ) : pass | Removes unnecessary temporary files generated by the pipeline | 390 | 9 |
16,658 | def load_info ( self ) : headers = { "Content-type" : "application/x-www-form-urlencoded" , "Accept" : "text/plain" , 'Referer' : 'http://' + self . domain + '/login.phtml' , "User-Agent" : user_agent } req = self . session . get ( 'http://' + self . domain + '/team_news.phtml' , headers = headers ) . content soup = BeautifulSoup ( req ) self . title = soup . title . string estado = soup . find ( 'div' , { 'id' : 'content' } ) . find ( 'div' , { 'id' : 'manager' } ) . string if estado : print estado . strip ( ) return [ s . extract ( ) for s in soup ( 'strong' ) ] if ( soup . find ( 'div' , { 'id' : 'userid' } ) != None ) : self . myid = soup . find ( 'div' , { 'id' : 'userid' } ) . p . text . strip ( ) [ 2 : ] self . money = int ( soup . find ( 'div' , { 'id' : 'manager_money' } ) . p . text . strip ( ) . replace ( "." , "" ) [ : - 2 ] ) self . teamvalue = int ( soup . find ( 'div' , { 'id' : 'teamvalue' } ) . p . text . strip ( ) . replace ( "." , "" ) [ : - 2 ] ) self . community_id = soup . find ( 'link' ) [ 'href' ] [ 24 : ] self . username = soup . find ( 'div' , { 'id' : 'username' } ) . p . a . text | Get info from logged account | 397 | 5 |
16,659 | def get_news ( self ) : headers = { "Content-type" : "application/x-www-form-urlencoded" , "Accept" : "text/plain" , 'Referer' : 'http://' + self . domain + '/login.phtml' , "User-Agent" : user_agent } req = self . session . get ( 'http://' + self . domain + '/team_news.phtml' , headers = headers ) . content soup = BeautifulSoup ( req ) news = [ ] for i in soup . find_all ( 'div' , { 'class' , 'article_content_text' } ) : news . append ( i . text ) return news | Get all the news from first page | 154 | 7 |
16,660 | def logout ( self ) : headers = { "Content-type" : "application/x-www-form-urlencoded" , "Accept" : "text/plain" , "User-Agent" : user_agent } self . session . get ( 'http://' + self . domain + '/logout.phtml' , headers = headers ) | Logout from Comunio | 77 | 6 |
16,661 | def standings ( self ) : headers = { "Content-type" : "application/x-www-form-urlencoded" , "Accept" : "text/plain" , "User-Agent" : user_agent } req = self . session . get ( 'http://' + self . domain + '/standings.phtml' , headers = headers ) . content soup = BeautifulSoup ( req ) table = soup . find ( 'table' , { 'id' : 'tablestandings' } ) . find_all ( 'tr' ) clasificacion = [ ] [ clasificacion . append ( ( '%s\t%s\t%s\t%s\t%s' ) % ( tablas . find ( 'td' ) . text , tablas . find ( 'div' ) [ 'id' ] , tablas . a . text , tablas . find_all ( 'td' ) [ 3 ] . text , tablas . find_all ( 'td' ) [ 4 ] . text ) ) for tablas in table [ 1 : ] ] return clasificacion | Get standings from the community s account | 243 | 7 |
16,662 | def info_user ( self , userid ) : headers = { "Content-type" : "application/x-www-form-urlencoded" , "Accept" : "text/plain" , 'Referer' : 'http://' + self . domain + '/standings.phtml' , "User-Agent" : user_agent } req = self . session . get ( 'http://' + self . domain + '/playerInfo.phtml?pid=' + userid , headers = headers ) . content soup = BeautifulSoup ( req ) title = soup . title . string community = soup . find_all ( 'table' , border = 0 ) [ 1 ] . a . text info = [ ] info . append ( title ) info . append ( community ) for i in soup . find_all ( 'table' , border = 0 ) [ 1 ] . find_all ( 'td' ) [ 1 : ] : info . append ( i . text ) for i in soup . find ( 'table' , cellpadding = 2 ) . find_all ( 'tr' ) [ 1 : ] : cad = i . find_all ( 'td' ) numero = cad [ 0 ] . text nombre = cad [ 2 ] . text . strip ( ) team = cad [ 3 ] . find ( 'img' ) [ 'alt' ] precio = cad [ 4 ] . text . replace ( "." , "" ) puntos = cad [ 5 ] . text posicion = cad [ 6 ] . text info . append ( [ numero , nombre , team , precio , puntos , posicion ] ) return info | Get user info using a ID | 352 | 6 |
16,663 | def lineup_user ( self , userid ) : headers = { "Content-type" : "application/x-www-form-urlencoded" , "Accept" : "text/plain" , 'Referer' : 'http://' + self . domain + '/standings.phtml' , "User-Agent" : user_agent } req = self . session . get ( 'http://' + self . domain + '/playerInfo.phtml?pid=' + userid , headers = headers ) . content soup = BeautifulSoup ( req ) info = [ ] for i in soup . find_all ( 'td' , { 'class' : 'name_cont' } ) : info . append ( i . text . strip ( ) ) return info | Get user lineup using a ID | 164 | 6 |
16,664 | def info_community ( self , teamid ) : headers = { "Content-type" : "application/x-www-form-urlencoded" , "Accept" : "text/plain" , 'Referer' : 'http://' + self . domain + '/standings.phtml' , "User-Agent" : user_agent } req = self . session . get ( 'http://' + self . domain + '/teamInfo.phtml?tid=' + teamid , headers = headers ) . content soup = BeautifulSoup ( req ) info = [ ] for i in soup . find ( 'table' , cellpadding = 2 ) . find_all ( 'tr' ) [ 1 : ] : info . append ( '%s\t%s\t%s\t%s\t%s' % ( i . find ( 'td' ) . text , i . find ( 'a' ) [ 'href' ] . split ( 'pid=' ) [ 1 ] , i . a . text , i . find_all ( 'td' ) [ 2 ] . text , i . find_all ( 'td' ) [ 3 ] . text ) ) return info | Get comunity info using a ID | 257 | 7 |
16,665 | def info_player ( self , pid ) : headers = { "Content-type" : "application/x-www-form-urlencoded" , "Accept" : "text/plain" , 'Referer' : 'http://' + self . domain + '/team_news.phtml' , "User-Agent" : user_agent } req = self . session . get ( 'http://' + self . domain + '/tradableInfo.phtml?tid=' + pid , headers = headers ) . content soup = BeautifulSoup ( req ) info = [ ] info . append ( soup . title . text . strip ( ) ) for i in soup . find ( 'table' , cellspacing = 1 ) . find_all ( 'tr' ) : info . append ( i . find_all ( 'td' ) [ 1 ] . text . replace ( "." , "" ) ) return info | Get info football player using a ID | 197 | 7 |
16,666 | def info_player_id ( self , name ) : number = 0 name = name . title ( ) . replace ( " " , "+" ) headers = { "Content-type" : "application/x-www-form-urlencoded" , "Accept" : "text/plain" , 'Referer' : 'http://' + self . domain + '/team_news.phtml' , "User-Agent" : user_agent } req = self . session . get ( 'http://stats.comunio.es/search.php?name=' + name , headers = headers ) . content soup = BeautifulSoup ( req ) for i in soup . find_all ( 'a' , { 'class' , 'nowrap' } ) : number = re . search ( "([0-9]+)-" , str ( i ) ) . group ( 1 ) break # Solo devuelve la primera coincidencia return number | Get id using name football player | 203 | 6 |
16,667 | def club ( self , cid ) : headers = { "Content-type" : "application/x-www-form-urlencoded" , "Accept" : "text/plain" , 'Referer' : 'http://' + self . domain + '/' , "User-Agent" : user_agent } req = self . session . get ( 'http://' + self . domain + '/clubInfo.phtml?cid=' + cid , headers = headers ) . content soup = BeautifulSoup ( req ) plist = [ ] for i in soup . find ( 'table' , cellpadding = 2 ) . find_all ( 'tr' ) [ 1 : ] : plist . append ( '%s\t%s\t%s\t%s\t%s' % ( i . find_all ( 'td' ) [ 0 ] . text , i . find_all ( 'td' ) [ 1 ] . text , i . find_all ( 'td' ) [ 2 ] . text , i . find_all ( 'td' ) [ 3 ] . text , i . find_all ( 'td' ) [ 4 ] . text ) ) return soup . title . text , plist | Get info by real team using a ID | 266 | 8 |
16,668 | def team_id ( self , team ) : #UTF-8 comparison headers = { "Content-type" : "application/x-www-form-urlencoded" , "Accept" : "text/plain" , 'Referer' : 'http://' + self . domain + '/' , "User-Agent" : user_agent } req = self . session . get ( 'http://' + self . domain , headers = headers ) . content soup = BeautifulSoup ( req ) for i in soup . find ( 'table' , cellpadding = 2 ) . find_all ( 'tr' ) : #Get teamid from the bets team1 = i . find ( 'a' ) [ 'title' ] team2 = i . find_all ( 'a' ) [ 1 ] [ 'title' ] if ( team == team1 ) : return i . find ( 'a' ) [ 'href' ] . split ( 'cid=' ) [ 1 ] elif ( team == team2 ) : return i . find_all ( 'a' ) [ 1 ] [ 'href' ] . split ( 'cid=' ) [ 1 ] return None | Get team ID using a real team name | 250 | 8 |
16,669 | def user_id ( self , user ) : headers = { "Content-type" : "application/x-www-form-urlencoded" , "Accept" : "text/plain" , 'Referer' : 'http://' + self . domain + '/team_news.phtml' , "User-Agent" : user_agent } req = self . session . get ( 'http://' + self . domain + '/standings.phtml' , headers = headers ) . content soup = BeautifulSoup ( req ) for i in soup . find ( 'table' , cellpadding = 2 ) . find_all ( 'tr' ) : try : if ( user == i . find_all ( 'td' ) [ 2 ] . text . encode ( 'utf8' ) ) : return i . find ( 'a' ) [ 'href' ] . split ( 'pid=' ) [ 1 ] except : continue return None | Get userid from a name | 201 | 6 |
16,670 | def players_onsale ( self , community_id , only_computer = False ) : headers = { "Content-type" : "application/x-www-form-urlencoded" , "Accept" : "text/plain" , 'Referer' : 'http://' + self . domain + '/team_news.phtml' , "User-Agent" : user_agent } req = self . session . get ( 'http://' + self . domain + '/teamInfo.phtml?tid=' + community_id , headers = headers ) . content soup = BeautifulSoup ( req ) current_year = dt . today ( ) . year current_month = dt . today ( ) . month on_sale = [ ] year_flag = 0 for i in soup . find_all ( 'table' , { 'class' , 'tablecontent03' } ) [ 2 ] . find_all ( 'tr' ) [ 1 : ] : name = i . find_all ( 'td' ) [ 0 ] . text . strip ( ) team = i . find ( 'img' ) [ 'alt' ] min_price = i . find_all ( 'td' ) [ 2 ] . text . replace ( "." , "" ) . strip ( ) market_price = i . find_all ( 'td' ) [ 3 ] . text . replace ( "." , "" ) . strip ( ) points = i . find_all ( 'td' ) [ 4 ] . text . strip ( ) . strip ( ) # Controlamos el cambio de año, ya que comunio no lo dá if current_month <= 7 and int ( i . find_all ( 'td' ) [ 5 ] . text [ 3 : 5 ] ) > 7 : year_flag = 1 date = str ( current_year - year_flag ) + i . find_all ( 'td' ) [ 5 ] . text [ 3 : 5 ] + i . find_all ( 'td' ) [ 5 ] . text [ : 2 ] owner = i . find_all ( 'td' ) [ 6 ] . text . strip ( ) position = i . find_all ( 'td' ) [ 7 ] . text . strip ( ) # Comprobamos si solamente queremos los de la computadora o no if ( only_computer and owner == 'Computer' ) or not only_computer : on_sale . append ( [ name , team , min_price , market_price , points , date , owner , position ] ) return on_sale | Returns the football players currently on sale | 557 | 7 |
16,671 | def bids_to_you ( self ) : headers = { "Content-type" : "application/x-www-form-urlencoded" , "Accept" : "text/plain" , 'Referer' : 'http://' + self . domain + '/team_news.phtml' , "User-Agent" : user_agent } req = self . session . get ( 'http://' + self . domain + '/exchangemarket.phtml?viewoffers_x=' , headers = headers ) . content soup = BeautifulSoup ( req ) table = [ ] for i in soup . find ( 'table' , { 'class' , 'tablecontent03' } ) . find_all ( 'tr' ) [ 1 : ] : player , owner , team , price , bid_date , trans_date , status = self . _parse_bid_table ( i ) table . append ( [ player , owner , team , price , bid_date , trans_date , status ] ) return table | Get bids made to you | 220 | 5 |
16,672 | def _parse_bid_table ( self , table ) : player = table . find_all ( 'td' ) [ 0 ] . text owner = table . find_all ( 'td' ) [ 1 ] . text team = table . find ( 'img' ) [ 'alt' ] price = int ( table . find_all ( 'td' ) [ 3 ] . text . replace ( "." , "" ) ) bid_date = table . find_all ( 'td' ) [ 4 ] . text trans_date = table . find_all ( 'td' ) [ 5 ] . text status = table . find_all ( 'td' ) [ 6 ] . text return player , owner , team , price , bid_date , trans_date , status | Convert table row values into strings | 163 | 7 |
16,673 | def run ( self ) : while not self . stopped . isSet ( ) : try : # if the current state is idle, just block and wait forever # if the current state is any other state, then a timeout of 200ms should # be reasonable in all cases. timeout = ( self . _state != 'idle' ) and 0.2 or None rdlist , _ , _ = select . select ( [ self . _socket . fileno ( ) ] , [ ] , [ ] , timeout ) if not rdlist : if self . _state != 'idle' : self . _state = 'idle' continue data = self . _socket . recv ( 1024 ) if not data : # check if the socket is still valid try : os . fstat ( recv . _socket . fileno ( ) ) except socket . error : break continue code = utils . mangleIR ( data , ignore_errors = True ) codeName = self . codeMap . get ( code ) # some manufacturers repeat their IR codes several times in rapid # succession. by tracking the last code, we can eliminate redundant # state changes if codeName and ( self . _state != codeName ) : self . _state = codeName for callback in self . _callbacks : callback ( codeName ) except : time . sleep ( 0.1 ) | Main loop of KIRA thread . | 284 | 8 |
16,674 | def convert_vec2_to_vec4 ( scale , data ) : it = iter ( data ) while True : yield next ( it ) * scale # x yield next ( it ) * scale # y yield 0.0 # z yield 1.0 | transforms an array of 2d coords into 4d | 53 | 12 |
16,675 | def calculate_edges ( self , excludes ) : edges = [ ] MEW = 100.0 if excludes is None : excludes = [ 0 ] * len ( self . indices ) * 2 for i in range ( 0 , len ( self . indices ) , 3 ) : # each triangle i0 = self . indices [ i + 0 ] * 4 i1 = self . indices [ i + 1 ] * 4 i2 = self . indices [ i + 2 ] * 4 e0 = excludes [ i + 0 ] e1 = excludes [ i + 1 ] e2 = excludes [ i + 2 ] p0 = self . vertices [ i0 : i0 + 4 ] p1 = self . vertices [ i1 : i1 + 4 ] p2 = self . vertices [ i2 : i2 + 4 ] v0 = self . vec2minus ( p2 , p1 ) v1 = self . vec2minus ( p2 , p0 ) v2 = self . vec2minus ( p1 , p0 ) area = fabs ( v1 [ 0 ] * v2 [ 1 ] - v1 [ 1 ] * v2 [ 0 ] ) c0 = ( area / self . magnitude ( v0 ) , e1 * MEW , e2 * MEW ) c1 = ( e0 * MEW , area / self . magnitude ( v1 ) , e2 * MEW ) c2 = ( e0 * MEW , e1 * MEW , area / self . magnitude ( v2 ) ) edges . extend ( p0 ) edges . extend ( c0 ) edges . extend ( p1 ) edges . extend ( c1 ) edges . extend ( p2 ) edges . extend ( c2 ) return create_vertex_buffer ( edges ) | Builds a vertex list adding barycentric coordinates to each vertex . | 378 | 14 |
16,676 | def get_bin ( self , arch = 'x86' ) : bin_dir = os . path . join ( self . vc_dir , 'bin' ) if arch == 'x86' : arch = '' cl_path = os . path . join ( bin_dir , arch , 'cl.exe' ) link_path = os . path . join ( bin_dir , arch , 'link.exe' ) ml_name = 'ml.exe' if arch in [ 'x86_amd64' , 'amd64' ] : ml_name = 'ml64.exe' ml_path = os . path . join ( bin_dir , arch , ml_name ) if os . path . isfile ( cl_path ) and os . path . isfile ( link_path ) and os . path . isfile ( ml_path ) : logging . info ( _ ( 'using cl.exe: %s' ) , cl_path ) logging . info ( _ ( 'using link.exe: %s' ) , link_path ) logging . info ( _ ( 'using %s: %s' ) , ml_name , ml_path ) run_cl = partial ( run_program , cl_path ) run_link = partial ( run_program , link_path ) run_ml = partial ( run_program , ml_path ) return self . Bin ( run_cl , run_link , run_ml ) logging . debug ( _ ( 'cl.exe not found: %s' ) , cl_path ) logging . debug ( _ ( 'link.exe not found: %s' ) , link_path ) logging . debug ( _ ( '%s not found: %s' ) , ml_name , ml_path ) return self . Bin ( None , None , None ) | Get binaries of Visual C ++ . | 390 | 7 |
16,677 | def get_inc ( self ) : dirs = [ ] for part in [ '' , 'atlmfc' ] : include = os . path . join ( self . vc_dir , part , 'include' ) if os . path . isdir ( include ) : logging . info ( _ ( 'using include: %s' ) , include ) dirs . append ( include ) else : logging . debug ( _ ( 'include not found: %s' ) , include ) return dirs | Get include directories of Visual C ++ . | 105 | 8 |
16,678 | def get_lib ( self , arch = 'x86' ) : if arch == 'x86' : arch = '' if arch == 'x64' : arch = 'amd64' lib = os . path . join ( self . vc_dir , 'lib' , arch ) if os . path . isdir ( lib ) : logging . info ( _ ( 'using lib: %s' ) , lib ) return [ lib ] logging . debug ( _ ( 'lib not found: %s' ) , lib ) return [ ] | Get lib directories of Visual C ++ . | 114 | 8 |
16,679 | def get_bin_and_lib ( self , x64 = False , native = False ) : if x64 : msvc = self . bin64 paths = self . lib64 else : msvc = self . bin32 paths = self . lib if native : arch = 'x64' if x64 else 'x86' paths += self . sdk . get_lib ( arch , native = True ) else : attr = 'lib64' if x64 else 'lib' paths += getattr ( self . sdk , attr ) return msvc , paths | Get bin and lib . | 120 | 5 |
16,680 | def get_inc ( self , native = False ) : if self . sdk_version == 'v7.0A' : include = os . path . join ( self . sdk_dir , 'include' ) if os . path . isdir ( include ) : logging . info ( _ ( 'using include: %s' ) , include ) return [ include ] logging . debug ( _ ( 'include not found: %s' ) , include ) return [ ] if self . sdk_version == 'v8.1' : dirs = [ ] if native : parts = [ 'km' , os . path . join ( 'km' , 'crt' ) , 'shared' ] else : parts = [ 'um' , 'winrt' , 'shared' ] for part in parts : include = os . path . join ( self . sdk_dir , 'include' , part ) if os . path . isdir ( include ) : logging . info ( _ ( 'using include: %s' ) , include ) dirs . append ( include ) else : logging . debug ( _ ( 'inc not found: %s' ) , include ) return dirs if self . sdk_version == 'v10.0' : dirs = [ ] extra = os . path . join ( 'include' , '10.0.10240.0' ) for mode in [ 'um' , 'ucrt' , 'shared' , 'winrt' ] : include = os . path . join ( self . sdk_dir , extra , mode ) if os . path . isdir ( include ) : logging . info ( _ ( 'using include: %s' ) , include ) dirs . append ( include ) else : logging . debug ( _ ( 'inc not found: %s' ) , include ) return dirs message = 'unknown sdk version: {}' . format ( self . sdk_version ) raise RuntimeError ( message ) | Get include directories of Windows SDK . | 421 | 7 |
16,681 | def get_lib ( self , arch = 'x86' , native = False ) : if self . sdk_version == 'v7.0A' : if arch == 'x86' : arch = '' lib = os . path . join ( self . sdk_dir , 'lib' , arch ) if os . path . isdir ( lib ) : logging . info ( _ ( 'using lib: %s' ) , lib ) return [ lib ] logging . debug ( _ ( 'lib not found: %s' ) , lib ) return [ ] if self . sdk_version == 'v8.1' : if native : extra = os . path . join ( 'winv6.3' , 'km' ) else : extra = os . path . join ( 'winv6.3' , 'um' ) lib = os . path . join ( self . sdk_dir , 'lib' , extra , arch ) if os . path . isdir ( lib ) : logging . info ( _ ( 'using lib: %s' ) , lib ) return [ lib ] logging . debug ( _ ( 'lib not found: %s' ) , lib ) return [ ] if self . sdk_version == 'v10.0' : dirs = [ ] extra = os . path . join ( 'lib' , '10.0.10240.0' ) for mode in [ 'um' , 'ucrt' ] : lib = os . path . join ( self . sdk_dir , extra , mode , arch ) if os . path . isdir ( lib ) : logging . info ( _ ( 'using lib: %s' ) , lib ) dirs . append ( lib ) else : logging . debug ( _ ( 'lib not found: %s' ) , lib ) return dirs message = 'unknown sdk version: {}' . format ( self . sdk_version ) raise RuntimeError ( message ) | Get lib directories of Windows SDK . | 418 | 7 |
16,682 | def get_tool_dir ( ) : def _is_comntools ( name ) : return re . match ( r'vs\d+comntools' , name . lower ( ) ) def _get_version_from_name ( name ) : return ( re . search ( r'\d+' , name ) . group ( 0 ) , name ) names = [ name for name in os . environ if _is_comntools ( name ) ] logging . debug ( _ ( 'found vscomntools: %s' ) , names ) versions = [ _get_version_from_name ( name ) for name in names ] logging . debug ( _ ( 'extracted versions: %s' ) , versions ) try : version = max ( versions ) except ValueError : raise OSError ( _ ( 'Failed to find the VSCOMNTOOLS. ' 'Have you installed Visual Studio?' ) ) else : logging . info ( _ ( 'using version: %s' ) , version ) vscomntools = os . environ [ version [ 1 ] ] logging . info ( _ ( 'using vscomntools: %s' ) , vscomntools ) return vscomntools | Get the directory of Visual Studio from environment variables . | 263 | 10 |
16,683 | def get_vs_dir_from_tool_dir ( self ) : index = self . tool_dir . find ( r'Common7\Tools' ) return self . tool_dir [ : index ] | Get the directory of Visual Studio from the directory Tools . | 44 | 11 |
16,684 | def get_vc_dir_from_vs_dir ( self ) : vc_dir = os . path . join ( self . vs_dir , 'vc' ) if os . path . isdir ( vc_dir ) : logging . info ( _ ( 'using vc: %s' ) , vc_dir ) return vc_dir logging . debug ( _ ( 'vc not found: %s' ) , vc_dir ) return '' | Get Visual C ++ directory from Visual Studio directory . | 100 | 10 |
16,685 | def get_sdk_version ( self ) : name = 'VCVarsQueryRegistry.bat' path = os . path . join ( self . tool_dir , name ) batch = read_file ( path ) if not batch : raise RuntimeError ( _ ( 'failed to find the SDK version' ) ) regex = r'(?<=\\Microsoft SDKs\\Windows\\).+?(?=")' try : version = re . search ( regex , batch ) . group ( ) except AttributeError : return '' else : logging . debug ( _ ( 'SDK version: %s' ) , version ) return version | Get the version of Windows SDK from VCVarsQueryRegistry . bat . | 134 | 16 |
16,686 | def get_sdk_dir ( self ) : if not WINREG : return '' path = r'\Microsoft\Microsoft SDKs\Windows' for node in [ 'SOFTWARE' , r'SOFTWARE\Wow6432Node' ] : for hkey in [ HKEY_LOCAL_MACHINE , HKEY_CURRENT_USER ] : sub_key = node + path + '\\' + self . sdk_version try : key = OpenKey ( hkey , sub_key ) except OSError : logging . debug ( _ ( 'key not found: %s' ) , sub_key ) continue else : logging . info ( _ ( 'using key: %s' ) , sub_key ) value_name = 'InstallationFolder' try : value = QueryValueEx ( key , value_name ) except OSError : return '' logging . info ( _ ( 'using dir: %s' ) , value [ 0 ] ) return value [ 0 ] return '' | Get the directory of Windows SDK from registry . | 213 | 9 |
16,687 | def main ( self ) : logging . info ( 'Preparing metadata' ) # If this script is run as part of a pipeline, the metadata objects will already exist if not self . metadata : self . filer ( ) else : self . objectprep ( ) # Use the number of metadata objects to calculate the number of cores to use per sample in multi-threaded # methods with sequence calls to multi-threaded applications try : self . threads = int ( self . cpus / len ( self . metadata ) ) if self . cpus / len ( self . metadata ) > 1 else 1 except ( TypeError , ZeroDivisionError ) : self . threads = self . cpus logging . info ( 'Reading and formatting primers' ) self . primers ( ) logging . info ( 'Baiting .fastq files against primers' ) self . bait ( ) logging . info ( 'Baiting .fastq files against previously baited .fastq files' ) self . doublebait ( ) logging . info ( 'Assembling contigs from double-baited .fastq files' ) self . assemble_amplicon_spades ( ) logging . info ( 'Creating BLAST database' ) self . make_blastdb ( ) logging . info ( 'Running BLAST analyses' ) self . blastnthreads ( ) logging . info ( 'Parsing BLAST results' ) self . parseblast ( ) logging . info ( 'Clearing amplicon files from previous iterations' ) self . ampliconclear ( ) logging . info ( 'Creating reports' ) self . reporter ( ) | Run the necessary methods | 335 | 4 |
16,688 | def objectprep ( self ) : for sample in self . metadata : setattr ( sample , self . analysistype , GenObject ( ) ) # Set the destination folder sample [ self . analysistype ] . outputdir = os . path . join ( self . path , self . analysistype ) # Make the destination folder make_path ( sample [ self . analysistype ] . outputdir ) sample [ self . analysistype ] . baitedfastq = os . path . join ( sample [ self . analysistype ] . outputdir , '{at}_targetMatches.fastq.gz' . format ( at = self . analysistype ) ) # Set the file type for the downstream analysis sample [ self . analysistype ] . filetype = self . filetype if self . filetype == 'fasta' : sample [ self . analysistype ] . assemblyfile = sample . general . bestassemblyfile | If the script is being run as part of a pipeline create and populate the objects for the current analysis | 197 | 20 |
16,689 | def bait ( self ) : with progressbar ( self . metadata ) as bar : for sample in bar : if sample . general . bestassemblyfile != 'NA' : # Only need to perform baiting on FASTQ files if sample [ self . analysistype ] . filetype == 'fastq' : # Make the system call - allow for single- or paired-end reads if len ( sample . general . fastqfiles ) == 2 : # Create the command to run the baiting - ref: primer file, k: shortest primer length # in1, in2: paired inputs, hdist: number of mismatches, interleaved: use interleaved output # outm: single, zipped output file of reads that match the target file sample [ self . analysistype ] . bbdukcmd = 'bbduk.sh ref={primerfile} k={klength} in1={forward} in2={reverse} ' 'hdist={mismatches} threads={threads} interleaved=t outm={outfile}' . format ( primerfile = self . formattedprimers , klength = self . klength , forward = sample . general . trimmedcorrectedfastqfiles [ 0 ] , reverse = sample . general . trimmedcorrectedfastqfiles [ 1 ] , mismatches = self . mismatches , threads = str ( self . cpus ) , outfile = sample [ self . analysistype ] . baitedfastq ) else : sample [ self . analysistype ] . bbdukcmd = 'bbduk.sh ref={primerfile} k={klength} in={fastq} hdist={mismatches} ' 'threads={threads} interleaved=t outm={outfile}' . format ( primerfile = self . formattedprimers , klength = self . klength , fastq = sample . general . trimmedcorrectedfastqfiles [ 0 ] , mismatches = self . mismatches , threads = str ( self . cpus ) , outfile = sample [ self . analysistype ] . baitedfastq ) # Run the system call (if necessary) if not os . path . isfile ( sample [ self . analysistype ] . baitedfastq ) : run_subprocess ( sample [ self . analysistype ] . bbdukcmd ) | Use bbduk to bait FASTQ reads from input files using the primer file as the target | 504 | 21 |
16,690 | def doublebait ( self ) : with progressbar ( self . metadata ) as bar : for sample in bar : if sample . general . bestassemblyfile != 'NA' : if sample [ self . analysistype ] . filetype == 'fastq' : sample [ self . analysistype ] . doublebaitedfastq = os . path . join ( sample [ self . analysistype ] . outputdir , '{at}_doubletargetMatches.fastq.gz' . format ( at = self . analysistype ) ) # Make the system call if len ( sample . general . fastqfiles ) == 2 : # Create the command to run the baiting sample [ self . analysistype ] . bbdukcmd2 = 'bbduk.sh ref={baitfile} in1={forward} in2={reverse} hdist={mismatches} ' 'threads={threads} interleaved=t outm={outfile}' . format ( baitfile = sample [ self . analysistype ] . baitedfastq , forward = sample . general . trimmedcorrectedfastqfiles [ 0 ] , reverse = sample . general . trimmedcorrectedfastqfiles [ 1 ] , mismatches = self . mismatches , threads = str ( self . cpus ) , outfile = sample [ self . analysistype ] . doublebaitedfastq ) else : sample [ self . analysistype ] . bbdukcmd2 = 'bbduk.sh ref={baitfile} in={fastq} hdist={mismatches} threads={threads} ' 'interleaved=t outm={outfile}' . format ( baitfile = sample [ self . analysistype ] . baitedfastq , fastq = sample . general . trimmedcorrectedfastqfiles [ 0 ] , mismatches = self . mismatches , threads = str ( self . cpus ) , outfile = sample [ self . analysistype ] . doublebaitedfastq ) # Run the system call (if necessary) if not os . path . isfile ( sample [ self . analysistype ] . doublebaitedfastq ) : run_subprocess ( sample [ self . analysistype ] . bbdukcmd2 ) | In order to ensure that there is enough sequence data to bridge the gap between the two primers the paired . fastq files produced above will be used to bait the original input . fastq files | 485 | 39 |
16,691 | def assemble_amplicon_spades ( self ) : for _ in self . metadata : # Send the threads to the merge method. :args is empty as I'm using threads = Thread ( target = self . assemble , args = ( ) ) # Set the daemon to true - something to do with thread management threads . setDaemon ( True ) # Start the threading threads . start ( ) for sample in self . metadata : if sample . general . bestassemblyfile != 'NA' : if sample [ self . analysistype ] . filetype == 'fastq' : sample [ self . analysistype ] . spadesoutput = os . path . join ( sample [ self . analysistype ] . outputdir , self . analysistype ) # Removed --careful, as there was an issue with the .fastq reads following baiting - something to # do with the names, or the interleaving. Subsequent testing showed no real changes to assemblies if len ( sample . general . fastqfiles ) == 2 : sample [ self . analysistype ] . spadescommand = 'spades.py -k {klength} --only-assembler --12 {fastq} -o {outfile} -t {threads}' . format ( klength = self . kmers , fastq = sample [ self . analysistype ] . doublebaitedfastq , outfile = sample [ self . analysistype ] . spadesoutput , threads = self . threads ) else : sample [ self . analysistype ] . spadescommand = 'spades.py -k {klength} --only-assembler -s {fastq} -o {outfile} -t {threads}' . format ( klength = self . kmers , fastq = sample [ self . analysistype ] . doublebaitedfastq , outfile = sample [ self . analysistype ] . spadesoutput , threads = self . threads ) sample [ self . analysistype ] . assemblyfile = os . path . join ( sample [ self . analysistype ] . spadesoutput , 'contigs.fasta' ) self . queue . put ( sample ) self . queue . join ( ) | Use SPAdes to assemble the amplicons using the double - baited . fastq files | 470 | 19 |
16,692 | def make_blastdb ( self ) : # remove the path and the file extension for easier future globbing db = os . path . splitext ( self . formattedprimers ) [ 0 ] nhr = '{db}.nhr' . format ( db = db ) # add nhr for searching if not os . path . isfile ( str ( nhr ) ) : # Create the databases command = 'makeblastdb -in {primerfile} -parse_seqids -max_file_sz 2GB -dbtype nucl -out {outfile}' . format ( primerfile = self . formattedprimers , outfile = db ) run_subprocess ( command ) | Create a BLAST database of the primer file | 147 | 9 |
16,693 | def ampliconclear ( self ) : for sample in self . metadata : # Set the name of the amplicon FASTA file sample [ self . analysistype ] . ampliconfile = os . path . join ( sample [ self . analysistype ] . outputdir , '{sn}_amplicons.fa' . format ( sn = sample . name ) ) try : os . remove ( sample [ self . analysistype ] . ampliconfile ) except IOError : pass | Clear previously created amplicon files to prepare for the appending of data to fresh files | 103 | 17 |
16,694 | def writeline ( self , line , line_number ) : tmp_file = tempfile . TemporaryFile ( 'w+' ) if not line . endswith ( os . linesep ) : line += os . linesep try : with open ( self . path , 'r' ) as file_handle : for count , new_line in enumerate ( file_handle ) : if count == line_number : new_line = line tmp_file . write ( new_line ) tmp_file . seek ( 0 ) with open ( self . path , 'w' ) as file_handle : for new_line in tmp_file : file_handle . write ( new_line ) finally : tmp_file . close ( ) | Rewrite a single line in the file . | 155 | 9 |
16,695 | def paths ( self ) : contents = os . listdir ( self . path ) contents = ( os . path . join ( self . path , path ) for path in contents ) contents = ( VenvPath ( path ) for path in contents ) return contents | Get an iter of VenvPaths within the directory . | 53 | 12 |
16,696 | def shebang ( self ) : with open ( self . path , 'rb' ) as file_handle : hashtag = file_handle . read ( 2 ) if hashtag == b'#!' : file_handle . seek ( 0 ) return file_handle . readline ( ) . decode ( 'utf8' ) return None | Get the file shebang if is has one . | 68 | 10 |
16,697 | def shebang ( self , new_shebang ) : if not self . shebang : raise ValueError ( 'Cannot modify a shebang if it does not exist.' ) if not new_shebang . startswith ( '#!' ) : raise ValueError ( 'Invalid shebang.' ) self . writeline ( new_shebang , 0 ) | Write a new shebang to the file . | 75 | 9 |
16,698 | def _find_vpath ( self ) : with open ( self . path , 'r' ) as file_handle : for count , line in enumerate ( file_handle ) : match = self . read_pattern . match ( line ) if match : return match . group ( 1 ) , count return None , None | Find the VIRTUAL_ENV path entry . | 67 | 11 |
16,699 | def vpath ( self , new_vpath ) : _ , line_number = self . _find_vpath ( ) new_vpath = self . write_pattern . format ( new_vpath ) self . writeline ( new_vpath , line_number ) | Change the path to the virtual environment . | 59 | 8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.