idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
51,500 | async def get ( self ) : shepherd = self . request . app . vmshepherd data = { 'presets' : { } , 'config' : shepherd . config } presets = await shepherd . preset_manager . list_presets ( ) runtime = shepherd . runtime_manager for name in presets : preset = shepherd . preset_manager . get_preset ( name ) data [ 'presets... | Inject all preset data to Panel and Render a Home Page |
51,501 | def serialize ( dictionary ) : data = [ ] for key , value in dictionary . items ( ) : data . append ( '{0}="{1}"' . format ( key , value ) ) return ', ' . join ( data ) | Turn dictionary into argument like string . |
51,502 | def getAmountOfHostsConnected ( self , lanInterfaceId = 1 , timeout = 1 ) : namespace = Lan . getServiceType ( "getAmountOfHostsConnected" ) + str ( lanInterfaceId ) uri = self . getControlURL ( namespace ) results = self . execute ( uri , namespace , "GetHostNumberOfEntries" , timeout = timeout ) return int ( results ... | Execute NewHostNumberOfEntries action to get the amount of known hosts . |
51,503 | def getHostDetailsByIndex ( self , index , lanInterfaceId = 1 , timeout = 1 ) : namespace = Lan . getServiceType ( "getHostDetailsByIndex" ) + str ( lanInterfaceId ) uri = self . getControlURL ( namespace ) results = self . execute ( uri , namespace , "GetGenericHostEntry" , timeout = timeout , NewIndex = index ) retur... | Execute GetGenericHostEntry action to get detailed information s of a connected host . |
51,504 | def getHostDetailsByMACAddress ( self , macAddress , lanInterfaceId = 1 , timeout = 1 ) : namespace = Lan . getServiceType ( "getHostDetailsByMACAddress" ) + str ( lanInterfaceId ) uri = self . getControlURL ( namespace ) results = self . execute ( uri , namespace , "GetSpecificHostEntry" , timeout = timeout , NewMACAd... | Get host details for a host specified by its MAC address . |
51,505 | def getEthernetInfo ( self , lanInterfaceId = 1 , timeout = 1 ) : namespace = Lan . getServiceType ( "getEthernetInfo" ) + str ( lanInterfaceId ) uri = self . getControlURL ( namespace ) results = self . execute ( uri , namespace , "GetInfo" , timeout = timeout ) return EthernetInfo ( results ) | Execute GetInfo action to get information s about the Ethernet interface . |
51,506 | def getEthernetStatistic ( self , lanInterfaceId = 1 , timeout = 1 ) : namespace = Lan . getServiceType ( "getEthernetStatistic" ) + str ( lanInterfaceId ) uri = self . getControlURL ( namespace ) results = self . execute ( uri , namespace , "GetStatistics" , timeout = timeout ) return EthernetStatistic ( results ) | Execute GetStatistics action to get statistics of the Ethernet interface . |
51,507 | def setEnable ( self , status , lanInterfaceId = 1 , timeout = 1 ) : namespace = Lan . getServiceType ( "setEnable" ) + str ( lanInterfaceId ) uri = self . getControlURL ( namespace ) if status : setStatus = 1 else : setStatus = 0 self . execute ( uri , namespace , "SetEnable" , timeout = timeout , NewEnable = setStatu... | Set enable status for a LAN interface be careful you don t cut yourself off . |
51,508 | def authenticate ( self ) : if not hasattr ( self , 'client' ) : self . client = uservoice . Client ( self . subdomain , self . api_key , self . api_secret ) | authenticate with uservoice by creating a client . |
51,509 | def post_ticket ( self , title , body ) : ticket = { 'subject' : title , 'message' : body } response = self . client . post ( "/api/v1/tickets.json" , { 'email' : self . email , 'ticket' : ticket } ) [ 'ticket' ] bot . info ( response [ 'url' ] ) | post_ticket will post a ticket to the uservoice helpdesk |
51,510 | def _metadata ( image , datapath ) : metadata = { 'series_number' : 0 , 'datadir' : datapath } spacing = image . GetSpacing ( ) metadata [ 'voxelsize_mm' ] = [ spacing [ 2 ] , spacing [ 0 ] , spacing [ 1 ] , ] return metadata | Function which returns metadata dict . |
51,511 | def Get3DData ( self , datapath , qt_app = None , dataplus_format = True , gui = False , start = 0 , stop = None , step = 1 , convert_to_gray = True , series_number = None , use_economic_dtype = True , dicom_expected = None , ** kwargs ) : self . orig_datapath = datapath datapath = os . path . expanduser ( datapath ) i... | Returns 3D data and its metadata . |
51,512 | def __ReadFromDirectory ( self , datapath , dicom_expected = None ) : start = self . start stop = self . stop step = self . step kwargs = self . kwargs gui = self . gui if ( dicom_expected is not False ) and ( dcmr . is_dicom_dir ( datapath ) ) : logger . debug ( 'Dir - DICOM' ) logger . debug ( "dicom_expected " + str... | This function is actually the ONE which reads 3D data from file |
51,513 | def _fix_sitk_bug ( path , metadata ) : ds = dicom . read_file ( path ) try : metadata [ "voxelsize_mm" ] [ 0 ] = ds . SpacingBetweenSlices except Exception as e : logger . warning ( "Read dicom 'SpacingBetweenSlices' failed: " , e ) return metadata | There is a bug in simple ITK for Z axis in 3D images . This is a fix . |
51,514 | def get_pid ( pid = None ) : if pid == None : if os . environ . get ( "PID" , None ) != None : pid = int ( os . environ . get ( "PID" ) ) else : pid = os . getpid ( ) print ( "pid is %s" % pid ) return pid | get_pid will return a pid of interest . First we use given variable then environmental variable PID and then PID of running process |
51,515 | def load_stored_routine ( self ) : try : self . _routine_name = os . path . splitext ( os . path . basename ( self . _source_filename ) ) [ 0 ] if os . path . exists ( self . _source_filename ) : if os . path . isfile ( self . _source_filename ) : self . _m_time = int ( os . path . getmtime ( self . _source_filename ) ... | Loads the stored routine into the instance of MySQL . |
51,516 | def __read_source_file ( self ) : with open ( self . _source_filename , 'r' , encoding = self . _routine_file_encoding ) as file : self . _routine_source_code = file . read ( ) self . _routine_source_code_lines = self . _routine_source_code . split ( "\n" ) | Reads the file with the source of the stored routine . |
51,517 | def __substitute_replace_pairs ( self ) : self . _set_magic_constants ( ) routine_source = [ ] i = 0 for line in self . _routine_source_code_lines : self . _replace [ '__LINE__' ] = "'%d'" % ( i + 1 ) for search , replace in self . _replace . items ( ) : tmp = re . findall ( search , line , re . IGNORECASE ) if tmp : l... | Substitutes all replace pairs in the source of the stored routine . |
51,518 | def _log_exception ( self , exception ) : self . _io . error ( str ( exception ) . strip ( ) . split ( os . linesep ) ) | Logs an exception . |
51,519 | def __get_placeholders ( self ) : ret = True pattern = re . compile ( '(@[A-Za-z0-9_.]+(%(max-)?type)?@)' ) matches = pattern . findall ( self . _routine_source_code ) placeholders = [ ] if len ( matches ) != 0 : for tmp in matches : placeholder = tmp [ 0 ] if placeholder . lower ( ) not in self . _replace_pairs : rais... | Extracts the placeholders from the stored routine source . |
51,520 | def _get_designation_type ( self ) : positions = self . _get_specification_positions ( ) if positions [ 0 ] != - 1 and positions [ 1 ] != - 1 : pattern = re . compile ( r'^\s*--\s+type\s*:\s*(\w+)\s*(.+)?\s*' , re . IGNORECASE ) for line_number in range ( positions [ 0 ] , positions [ 1 ] + 1 ) : matches = pattern . fi... | Extracts the designation type of the stored routine . |
51,521 | def _get_specification_positions ( self ) : start = - 1 for ( i , line ) in enumerate ( self . _routine_source_code_lines ) : if self . _is_start_of_stored_routine ( line ) : start = i end = - 1 for ( i , line ) in enumerate ( self . _routine_source_code_lines ) : if self . _is_start_of_stored_routine_body ( line ) : e... | Returns a tuple with the start and end line numbers of the stored routine specification . |
51,522 | def __get_doc_block_lines ( self ) : line1 = None line2 = None i = 0 for line in self . _routine_source_code_lines : if re . match ( r'\s*/\*\*' , line ) : line1 = i if re . match ( r'\s*\*/' , line ) : line2 = i if self . _is_start_of_stored_routine ( line ) : break i += 1 return line1 , line2 | Returns the start and end line of the DOcBlock of the stored routine code . |
51,523 | def __get_doc_block_parts_wrapper ( self ) : self . __get_doc_block_parts_source ( ) helper = self . _get_data_type_helper ( ) parameters = list ( ) for parameter_info in self . _parameters : parameters . append ( { 'parameter_name' : parameter_info [ 'name' ] , 'python_type' : helper . column_type_to_python_type ( par... | Generates the DocBlock parts to be used by the wrapper generator . |
51,524 | def _update_metadata ( self ) : self . _pystratum_metadata [ 'routine_name' ] = self . _routine_name self . _pystratum_metadata [ 'designation' ] = self . _designation_type self . _pystratum_metadata [ 'table_name' ] = self . _table_name self . _pystratum_metadata [ 'parameters' ] = self . _parameters self . _pystratum... | Updates the metadata of the stored routine . |
51,525 | def _set_magic_constants ( self ) : real_path = os . path . realpath ( self . _source_filename ) self . _replace [ '__FILE__' ] = "'%s'" % real_path self . _replace [ '__ROUTINE__' ] = "'%s'" % self . _routine_name self . _replace [ '__DIR__' ] = "'%s'" % os . path . dirname ( real_path ) | Adds magic constants to replace list . |
51,526 | def _unset_magic_constants ( self ) : if '__FILE__' in self . _replace : del self . _replace [ '__FILE__' ] if '__ROUTINE__' in self . _replace : del self . _replace [ '__ROUTINE__' ] if '__DIR__' in self . _replace : del self . _replace [ '__DIR__' ] if '__LINE__' in self . _replace : del self . _replace [ '__LINE__' ... | Removes magic constants from current replace list . |
51,527 | def _print_sql_with_error ( self , sql , error_line ) : if os . linesep in sql : lines = sql . split ( os . linesep ) digits = math . ceil ( math . log ( len ( lines ) + 1 , 10 ) ) i = 1 for line in lines : if i == error_line : self . _io . text ( '<error>{0:{width}} {1}</error>' . format ( i , line , width = digits , ... | Writes a SQL statement with an syntax error to the output . The line where the error occurs is highlighted . |
51,528 | def list_filter ( lst , startswith = None , notstartswith = None , contain = None , notcontain = None ) : keeped = [ ] for item in lst : keep = False if startswith is not None : if item . startswith ( startswith ) : keep = True if notstartswith is not None : if not item . startswith ( notstartswith ) : keep = True if c... | Keep in list items according to filter parameters . |
51,529 | def split_dict ( dct , keys ) : if type ( dct ) == collections . OrderedDict : dict_in = collections . OrderedDict ( ) dict_out = collections . OrderedDict ( ) else : dict_in = { } dict_out = { } for key , value in dct . items : if key in keys : dict_in [ key ] = value else : dict_out [ key ] = value return dict_in , d... | Split dict into two subdicts based on keys . |
51,530 | def recursive_update ( d , u ) : for k , v in u . iteritems ( ) : if isinstance ( v , collections . Mapping ) : r = recursive_update ( d . get ( k , { } ) , v ) d [ k ] = r else : d [ k ] = u [ k ] return d | Dict recursive update . |
51,531 | def flatten_dict_join_keys ( dct , join_symbol = " " ) : return dict ( flatten_dict ( dct , join = lambda a , b : a + join_symbol + b ) ) | Flatten dict with defined key join symbol . |
51,532 | def list_contains ( list_of_strings , substring , return_true_false_array = False ) : key_tf = [ keyi . find ( substring ) != - 1 for keyi in list_of_strings ] if return_true_false_array : return key_tf keys_to_remove = list_of_strings [ key_tf ] return keys_to_remove | Get strings in list which contains substring . |
51,533 | def df_drop_duplicates ( df , ignore_key_pattern = "time" ) : keys_to_remove = list_contains ( df . keys ( ) , ignore_key_pattern ) ks = copy . copy ( list ( df . keys ( ) ) ) for key in keys_to_remove : ks . remove ( key ) df = df . drop_duplicates ( ks ) return df | Drop duplicates from dataframe ignore columns with keys containing defined pattern . |
51,534 | def ndarray_to_list_in_structure ( item , squeeze = True ) : tp = type ( item ) if tp == np . ndarray : if squeeze : item = item . squeeze ( ) item = item . tolist ( ) elif tp == list : for i in range ( len ( item ) ) : item [ i ] = ndarray_to_list_in_structure ( item [ i ] ) elif tp == dict : for lab in item : item [ ... | Change ndarray in structure of lists and dicts into lists . |
51,535 | def dict_find_key ( dd , value ) : key = next ( key for key , val in dd . items ( ) if val == value ) return key | Find first suitable key in dict . |
51,536 | def sort_list_of_dicts ( lst_of_dct , keys , reverse = False , ** sort_args ) : if type ( keys ) != list : keys = [ keys ] lst_of_dct . sort ( key = lambda x : [ ( ( False , x [ key ] ) if key in x else ( True , 0 ) ) for key in keys ] , reverse = reverse , ** sort_args ) return lst_of_dct | Sort list of dicts by one or multiple keys . |
51,537 | def ordered_dict_to_dict ( config ) : if type ( config ) == collections . OrderedDict : config = dict ( config ) if type ( config ) == list : for i in range ( 0 , len ( config ) ) : config [ i ] = ordered_dict_to_dict ( config [ i ] ) elif type ( config ) == dict : for key in config : config [ key ] = ordered_dict_to_d... | Use dict instead of ordered dict in structure . |
51,538 | def _get_option ( config , supplement , section , option , fallback = None ) : if supplement : return_value = supplement . get ( section , option , fallback = config . get ( section , option , fallback = fallback ) ) else : return_value = config . get ( section , option , fallback = fallback ) if fallback is None and r... | Reads an option for a configuration file . |
51,539 | def _read_configuration ( config_filename ) : config = ConfigParser ( ) config . read ( config_filename ) if 'supplement' in config [ 'database' ] : path = os . path . dirname ( config_filename ) + '/' + config . get ( 'database' , 'supplement' ) config_supplement = ConfigParser ( ) config_supplement . read ( path ) el... | Checks the supplement file . |
51,540 | def record_asciinema ( ) : import asciinema . config as aconfig from asciinema . api import Api cfg = aconfig . load ( ) api = Api ( cfg . api_url , os . environ . get ( "USER" ) , cfg . install_id ) recorder = HelpMeRecord ( api ) code = recorder . execute ( ) if code == 0 and os . path . exists ( recorder . filename ... | a wrapper around generation of an asciinema . api . Api and a custom recorder to pull out the input arguments to the Record from argparse . The function generates a filename in advance and a return code so we can check the final status . |
51,541 | def sendWakeOnLan ( self , macAddress , lanInterfaceId = 1 , timeout = 1 ) : namespace = Fritz . getServiceType ( "sendWakeOnLan" ) + str ( lanInterfaceId ) uri = self . getControlURL ( namespace ) self . execute ( uri , namespace , "X_AVM-DE_WakeOnLANByMACAddress" , timeout = timeout , NewMACAddress = macAddress ) | Send a wake up package to a device specified by its MAC address . |
51,542 | def doUpdate ( self , timeout = 1 ) : namespace = Fritz . getServiceType ( "doUpdate" ) uri = self . getControlURL ( namespace ) results = self . execute ( uri , namespace , "X_AVM-DE_DoUpdate" , timeout = timeout ) return results [ "NewUpgradeAvailable" ] , results [ "NewX_AVM-DE_UpdateState" ] | Do a software update of the Fritz Box if available . |
51,543 | def isOptimizedForIPTV ( self , wifiInterfaceId = 1 , timeout = 1 ) : namespace = Fritz . getServiceType ( "isOptimizedForIPTV" ) + str ( wifiInterfaceId ) uri = self . getControlURL ( namespace ) results = self . execute ( uri , namespace , "X_AVM-DE_GetIPTVOptimized" , timeout = timeout ) return bool ( int ( results ... | Return if the Wifi interface is optimized for IP TV |
51,544 | def setOptimizedForIPTV ( self , status , wifiInterfaceId = 1 , timeout = 1 ) : namespace = Fritz . getServiceType ( "setOptimizedForIPTV" ) + str ( wifiInterfaceId ) uri = self . getControlURL ( namespace ) if status : setStatus = 1 else : setStatus = 0 arguments = { "timeout" : timeout , "NewX_AVM-DE_IPTVoptimize" : ... | Set if the Wifi interface is optimized for IP TV |
51,545 | def getCallList ( self , timeout = 1 ) : namespace = Fritz . getServiceType ( "getCallList" ) uri = self . getControlURL ( namespace ) results = self . execute ( uri , namespace , "GetCallList" ) proxies = { } if self . httpProxy : proxies = { "https" : self . httpProxy } if self . httpsProxy : proxies = { "http" : sel... | Get the list of phone calls made |
51,546 | def upload_to_pypi ( ) : x = prompt ( "Are you sure to upload the current version to pypi?" ) if not x or not x . lower ( ) in [ "y" , "yes" ] : return local ( "rm -rf dist" ) local ( "python setup.py sdist" ) version = _get_cur_version ( ) fn = "RPIO-%s.tar.gz" % version put ( "dist/%s" % fn , "/tmp/" ) with cd ( "/tm... | Upload sdist and bdist_eggs to pypi |
51,547 | def _threaded_callback ( callback , * args ) : t = Thread ( target = callback , args = args ) t . daemon = True t . start ( ) | Internal wrapper to start a callback in threaded mode . Using the daemon mode to not block the main thread from exiting . |
51,548 | def del_interrupt_callback ( self , gpio_id ) : debug ( "- removing interrupts on gpio %s" % gpio_id ) gpio_id = _GPIO . channel_to_gpio ( gpio_id ) fileno = self . _map_gpioid_to_fileno [ gpio_id ] self . _epoll . unregister ( fileno ) f = self . _map_fileno_to_file [ fileno ] del self . _map_fileno_to_file [ fileno ]... | Delete all interrupt callbacks from a certain gpio |
51,549 | def _handle_interrupt ( self , fileno , val ) : val = int ( val ) edge = self . _map_fileno_to_options [ fileno ] [ "edge" ] if ( edge == 'rising' and val == 0 ) or ( edge == 'falling' and val == 1 ) : return debounce = self . _map_fileno_to_options [ fileno ] [ "debounce_timeout_s" ] if debounce : t = time . time ( ) ... | Internally distributes interrupts to all attached callbacks |
51,550 | def cleanup_tcpsockets ( self ) : for fileno in self . _tcp_client_sockets . keys ( ) : self . close_tcp_client ( fileno ) for fileno , items in self . _tcp_server_sockets . items ( ) : socket , cb = items debug ( "- _cleanup server socket connection (fd %s)" % fileno ) self . _epoll . unregister ( fileno ) socket . cl... | Closes all TCP connections and then the socket servers |
51,551 | def add_channel_pulse ( dma_channel , gpio , start , width ) : return _PWM . add_channel_pulse ( dma_channel , gpio , start , width ) | Add a pulse for a specific GPIO to a dma channel subcycle . start and width are multiples of the pulse - width increment granularity . |
51,552 | def unique ( _list ) : ret = [ ] for item in _list : if item not in ret : ret . append ( item ) return ret | Makes the list have unique items only and maintains the order |
51,553 | def preprocess_query ( query ) : query = re . sub ( r'(\s(FROM|JOIN)\s`[^`]+`)\s`[^`]+`' , r'\1' , query , flags = re . IGNORECASE ) query = re . sub ( r'`([^`]+)`\.`([^`]+)`' , r'\1.\2' , query ) return query | Perform initial query cleanup |
51,554 | def normalize_likes ( sql ) : sql = sql . replace ( '%' , '' ) sql = re . sub ( r"LIKE '[^\']+'" , 'LIKE X' , sql ) matches = re . finditer ( r'(or|and) [^\s]+ LIKE X' , sql , flags = re . IGNORECASE ) matches = [ match . group ( 0 ) for match in matches ] if matches else None if matches : for match in set ( matches ) ... | Normalize and wrap LIKE statements |
51,555 | def generalize_sql ( sql ) : if sql is None : return None sql = re . sub ( r'\s{2,}' , ' ' , sql ) sql = remove_comments_from_sql ( sql ) sql = normalize_likes ( sql ) sql = re . sub ( r"\\\\" , '' , sql ) sql = re . sub ( r"\\'" , '' , sql ) sql = re . sub ( r'\\"' , '' , sql ) sql = re . sub ( r"'[^\']*'" , 'X' , sql... | Removes most variables from an SQL query and replaces them with X or N for numbers . |
51,556 | def deblur_system_call ( params , input_fp ) : logger = logging . getLogger ( __name__ ) logger . debug ( '[%s] deblur system call params %s, input_fp %s' % ( mp . current_process ( ) . name , params , input_fp ) ) script_name = "deblur" script_subprogram = "workflow" command = [ script_name , script_subprogram , '--se... | Build deblur command for subprocess . |
51,557 | def run_functor ( functor , * args , ** kwargs ) : try : return functor ( * args , ** kwargs ) except Exception : raise Exception ( "" . join ( traceback . format_exception ( * sys . exc_info ( ) ) ) ) | Given a functor run it and return its result . We can use this with multiprocessing . map and map it over a list of job functors to do them . |
51,558 | def parallel_deblur ( inputs , params , pos_ref_db_fp , neg_ref_dp_fp , jobs_to_start = 1 ) : logger = logging . getLogger ( __name__ ) logger . info ( 'parallel deblur started for %d inputs' % len ( inputs ) ) remove_param_list = [ '-O' , '--jobs-to-start' , '--seqs-fp' , '--pos-ref-db-fp' , '--neg-ref-db-fp' ] skipne... | Dispatch execution over a pool of processors |
51,559 | def trim_seqs ( input_seqs , trim_len , left_trim_len ) : logger = logging . getLogger ( __name__ ) okseqs = 0 totseqs = 0 if trim_len < - 1 : raise ValueError ( "Invalid trim_len: %d" % trim_len ) for label , seq in input_seqs : totseqs += 1 if trim_len == - 1 : okseqs += 1 yield label , seq elif len ( seq ) >= trim_l... | Trim FASTA sequences to specified length . |
51,560 | def dereplicate_seqs ( seqs_fp , output_fp , min_size = 2 , use_log = False , threads = 1 ) : logger = logging . getLogger ( __name__ ) logger . info ( 'dereplicate seqs file %s' % seqs_fp ) log_name = "%s.log" % output_fp params = [ 'vsearch' , '--derep_fulllength' , seqs_fp , '--output' , output_fp , '--sizeout' , '-... | Dereplicate FASTA sequences and remove singletons using VSEARCH . |
51,561 | def build_index_sortmerna ( ref_fp , working_dir ) : logger = logging . getLogger ( __name__ ) logger . info ( 'build_index_sortmerna files %s to' ' dir %s' % ( ref_fp , working_dir ) ) all_db = [ ] for db in ref_fp : fasta_dir , fasta_filename = split ( db ) index_basename = splitext ( fasta_filename ) [ 0 ] db_output... | Build a SortMeRNA index for all reference databases . |
51,562 | def filter_minreads_samples_from_table ( table , minreads = 1 , inplace = True ) : logger = logging . getLogger ( __name__ ) logger . debug ( 'filter_minreads_started. minreads=%d' % minreads ) samp_sum = table . sum ( axis = 'sample' ) samp_ids = table . ids ( axis = 'sample' ) bad_samples = samp_ids [ samp_sum < minr... | Filter samples from biom table that have less than minreads reads total |
51,563 | def fasta_from_biom ( table , fasta_file_name ) : logger = logging . getLogger ( __name__ ) logger . debug ( 'saving biom table sequences to fasta file %s' % fasta_file_name ) with open ( fasta_file_name , 'w' ) as f : for cseq in table . ids ( axis = 'observation' ) : f . write ( '>%s\n%s\n' % ( cseq , cseq ) ) logger... | Save sequences from a biom table to a fasta file |
51,564 | def remove_artifacts_from_biom_table ( table_filename , fasta_filename , ref_fp , biom_table_dir , ref_db_fp , threads = 1 , verbose = False , sim_thresh = None , coverage_thresh = None ) : logger = logging . getLogger ( __name__ ) logger . info ( 'getting 16s sequences from the biom table' ) clean_fp , num_seqs_left ,... | Remove artifacts from a biom table using SortMeRNA |
51,565 | def remove_artifacts_seqs ( seqs_fp , ref_fp , working_dir , ref_db_fp , negate = False , threads = 1 , verbose = False , sim_thresh = None , coverage_thresh = None ) : logger = logging . getLogger ( __name__ ) logger . info ( 'remove_artifacts_seqs file %s' % seqs_fp ) if stat ( seqs_fp ) . st_size == 0 : logger . war... | Remove artifacts from FASTA file using SortMeRNA . |
51,566 | def multiple_sequence_alignment ( seqs_fp , threads = 1 ) : logger = logging . getLogger ( __name__ ) logger . info ( 'multiple_sequence_alignment seqs file %s' % seqs_fp ) if threads == 0 : threads = - 1 if stat ( seqs_fp ) . st_size == 0 : logger . warning ( 'msa failed. file %s has no reads' % seqs_fp ) return None ... | Perform multiple sequence alignment on FASTA file using MAFFT . |
51,567 | def split_sequence_file_on_sample_ids_to_files ( seqs , outdir ) : logger = logging . getLogger ( __name__ ) logger . info ( 'split_sequence_file_on_sample_ids_to_files' ' for file %s into dir %s' % ( seqs , outdir ) ) outputs = { } for bits in sequence_generator ( seqs ) : sample = sample_id_from_read_id ( bits [ 0 ] ... | Split FASTA file on sample IDs . |
51,568 | def write_biom_table ( table , biom_fp ) : logger = logging . getLogger ( __name__ ) logger . debug ( 'write_biom_table to file %s' % biom_fp ) with biom_open ( biom_fp , 'w' ) as f : table . to_hdf5 ( h5grp = f , generated_by = "deblur" ) logger . debug ( 'wrote to BIOM file %s' % biom_fp ) | Write BIOM table to file . |
51,569 | def get_files_for_table ( input_dir , file_end = '.trim.derep.no_artifacts' '.msa.deblur.no_chimeras' ) : logger = logging . getLogger ( __name__ ) logger . debug ( 'get_files_for_table input dir %s, ' 'file-ending %s' % ( input_dir , file_end ) ) names = [ ] for cfile in glob ( join ( input_dir , "*%s" % file_end ) ) ... | Get a list of files to add to the output table |
51,570 | def launch_workflow ( seqs_fp , working_dir , mean_error , error_dist , indel_prob , indel_max , trim_length , left_trim_length , min_size , ref_fp , ref_db_fp , threads_per_sample = 1 , sim_thresh = None , coverage_thresh = None ) : logger = logging . getLogger ( __name__ ) logger . info ( '---------------------------... | Launch full deblur workflow for a single post split - libraries fasta file |
51,571 | def start_log ( level = logging . DEBUG , filename = None ) : if filename is None : tstr = time . ctime ( ) tstr = tstr . replace ( ' ' , '.' ) tstr = tstr . replace ( ':' , '.' ) filename = 'deblur.log.%s' % tstr logging . basicConfig ( filename = filename , level = level , format = '%(levelname)s(%(thread)d)' '%(asct... | start the logger for the run |
51,572 | def get_sequences ( input_seqs ) : try : seqs = [ Sequence ( id , seq ) for id , seq in input_seqs ] except Exception : seqs = [ ] if len ( seqs ) == 0 : logger = logging . getLogger ( __name__ ) logger . warn ( 'No sequences found in fasta file!' ) return None aligned_lengths = set ( s . length for s in seqs ) unalign... | Returns a list of Sequences |
51,573 | def deblur ( input_seqs , mean_error = 0.005 , error_dist = None , indel_prob = 0.01 , indel_max = 3 ) : logger = logging . getLogger ( __name__ ) if error_dist is None : error_dist = get_default_error_profile ( ) logger . debug ( 'Using error profile %s' % error_dist ) seqs = get_sequences ( input_seqs ) if seqs is No... | Deblur the reads |
51,574 | def to_fasta ( self ) : prefix , suffix = re . split ( '(?<=size=)\w+' , self . label , maxsplit = 1 ) new_count = int ( round ( self . frequency ) ) new_label = "%s%d%s" % ( prefix , new_count , suffix ) return ">%s\n%s\n" % ( new_label , self . sequence ) | Returns a string with the sequence in fasta format |
51,575 | def render_select2_options_code ( self , options , id_ ) : output = [ ] for key , value in options . items ( ) : if isinstance ( value , ( dict , list ) ) : value = json . dumps ( value ) output . append ( "data-{name}='{value}'" . format ( name = key , value = mark_safe ( value ) ) ) return mark_safe ( ' ' . join ( ou... | Render options for select2 . |
51,576 | def render_js_code ( self , id_ , * args , ** kwargs ) : if id_ : options = self . render_select2_options_code ( dict ( self . get_options ( ) ) , id_ ) return mark_safe ( self . html . format ( id = id_ , options = options ) ) return u'' | Render html container for Select2 widget with options . |
51,577 | def render ( self , name , value , attrs = None , ** kwargs ) : output = super ( Select2Mixin , self ) . render ( name , value , attrs = attrs , ** kwargs ) id_ = attrs [ 'id' ] output += self . render_js_code ( id_ , name , value , attrs = attrs , ** kwargs ) return mark_safe ( output ) | Extend base class s render method by appending javascript inline text to html output . |
51,578 | def select2_modelform ( model , attrs = None , form_class = es2_forms . FixedModelForm ) : classname = '%sForm' % model . _meta . object_name meta = select2_modelform_meta ( model , attrs = attrs ) return type ( classname , ( form_class , ) , { 'Meta' : meta } ) | Return ModelForm class for model with select2 widgets . |
51,579 | def parse ( self , text ) : gen = self . lexer . lex ( text ) next_val_fn = partial ( next , * ( gen , ) ) commands = [ ] token = next_val_fn ( ) while token [ 0 ] is not EOF : command , token = self . rule_svg_transform ( next_val_fn , token ) commands . append ( command ) return commands | Parse a string of SVG transform = data . |
51,580 | def findElementsWithId ( node , elems = None ) : if elems is None : elems = { } id = node . getAttribute ( 'id' ) if id != '' : elems [ id ] = node if node . hasChildNodes ( ) : for child in node . childNodes : if child . nodeType == Node . ELEMENT_NODE : findElementsWithId ( child , elems ) return elems | Returns all elements with id attributes |
51,581 | def findReferencedElements ( node , ids = None ) : global referencingProps if ids is None : ids = { } if node . nodeName == 'style' and node . namespaceURI == NS [ 'SVG' ] : stylesheet = "" . join ( [ child . nodeValue for child in node . childNodes ] ) if stylesheet != '' : cssRules = parseCssString ( stylesheet ) for... | Returns IDs of all referenced elements - node is the node at which to start the search . - returns a map which has the id as key and each value is is a list of nodes |
51,582 | def shortenIDs ( doc , prefix , unprotectedElements = None ) : num = 0 identifiedElements = findElementsWithId ( doc . documentElement ) if unprotectedElements is None : unprotectedElements = identifiedElements referencedIDs = findReferencedElements ( doc . documentElement ) idList = [ ( len ( referencedIDs [ rid ] ) ,... | Shortens ID names used in the document . ID names referenced the most often are assigned the shortest ID names . If the list unprotectedElements is provided only IDs from this list will be shortened . |
51,583 | def intToID ( idnum , prefix ) : rid = '' while idnum > 0 : idnum -= 1 rid = chr ( ( idnum % 26 ) + ord ( 'a' ) ) + rid idnum = int ( idnum / 26 ) return prefix + rid | Returns the ID name for the given ID number spreadsheet - style i . e . from a to z then from aa to az ba to bz etc . until zz . |
51,584 | def renameID ( doc , idFrom , idTo , identifiedElements , referencedIDs ) : num = 0 definingNode = identifiedElements [ idFrom ] definingNode . setAttribute ( "id" , idTo ) del identifiedElements [ idFrom ] identifiedElements [ idTo ] = definingNode num += len ( idFrom ) - len ( idTo ) referringNodes = referencedIDs . ... | Changes the ID name from idFrom to idTo on the declaring element as well as all references in the document doc . |
51,585 | def unprotected_ids ( doc , options ) : u identifiedElements = findElementsWithId ( doc . documentElement ) if not ( options . protect_ids_noninkscape or options . protect_ids_list or options . protect_ids_prefix ) : return identifiedElements if options . protect_ids_list : protect_ids_list = options . protect_ids_list... | u Returns a list of unprotected IDs within the document doc . |
51,586 | def removeUnreferencedIDs ( referencedIDs , identifiedElements ) : global _num_ids_removed keepTags = [ 'font' ] num = 0 for id in identifiedElements : node = identifiedElements [ id ] if id not in referencedIDs and node . nodeName not in keepTags : node . removeAttribute ( 'id' ) _num_ids_removed += 1 num += 1 return ... | Removes the unreferenced ID attributes . |
51,587 | def moveCommonAttributesToParentGroup ( elem , referencedElements ) : num = 0 childElements = [ ] for child in elem . childNodes : if child . nodeType == Node . ELEMENT_NODE : if not child . getAttribute ( 'id' ) in referencedElements : childElements . append ( child ) num += moveCommonAttributesToParentGroup ( child ,... | This recursively calls this function on all children of the passed in element and then iterates over all child elements and removes common inheritable attributes from the children and places them in the parent group . But only if the parent contains nothing but element children and whitespace . The attributes are only ... |
51,588 | def removeUnusedAttributesOnParent ( elem ) : num = 0 childElements = [ ] for child in elem . childNodes : if child . nodeType == Node . ELEMENT_NODE : childElements . append ( child ) num += removeUnusedAttributesOnParent ( child ) if len ( childElements ) <= 1 : return num attrList = elem . attributes unusedAttrs = {... | This recursively calls this function on all children of the element passed in then removes any unused attributes on this elem if none of the children inherit it |
51,589 | def _getStyle ( node ) : u if node . nodeType == Node . ELEMENT_NODE and len ( node . getAttribute ( 'style' ) ) > 0 : styleMap = { } rawStyles = node . getAttribute ( 'style' ) . split ( ';' ) for style in rawStyles : propval = style . split ( ':' ) if len ( propval ) == 2 : styleMap [ propval [ 0 ] . strip ( ) ] = pr... | u Returns the style attribute of a node as a dictionary . |
51,590 | def _setStyle ( node , styleMap ) : u fixedStyle = ';' . join ( [ prop + ':' + styleMap [ prop ] for prop in styleMap ] ) if fixedStyle != '' : node . setAttribute ( 'style' , fixedStyle ) elif node . getAttribute ( 'style' ) : node . removeAttribute ( 'style' ) return node | u Sets the style attribute of a node to the dictionary styleMap . |
51,591 | def styleInheritedFromParent ( node , style ) : parentNode = node . parentNode if parentNode . nodeType == Node . DOCUMENT_NODE : return None styles = _getStyle ( parentNode ) if style in styles : value = styles [ style ] if not value == 'inherit' : return value value = parentNode . getAttribute ( style ) if value not ... | Returns the value of style that is inherited from the parents of the passed - in node |
51,592 | def styleInheritedByChild ( node , style , nodeIsChild = False ) : if node . nodeType != Node . ELEMENT_NODE : return False if nodeIsChild : if node . getAttribute ( style ) not in [ '' , 'inherit' ] : return False styles = _getStyle ( node ) if ( style in styles ) and not ( styles [ style ] == 'inherit' ) : return Fal... | Returns whether style is inherited by any children of the passed - in node |
51,593 | def mayContainTextNodes ( node ) : try : return node . mayContainTextNodes except AttributeError : pass result = True if node . nodeType != Node . ELEMENT_NODE : result = False elif node . namespaceURI != NS [ 'SVG' ] : result = True elif node . nodeName in [ 'rect' , 'circle' , 'ellipse' , 'line' , 'polygon' , 'polyli... | Returns True if the passed - in node is probably a text element or at least one of its descendants is probably a text element . |
51,594 | def taint ( taintedSet , taintedAttribute ) : u taintedSet . add ( taintedAttribute ) if taintedAttribute == 'marker' : taintedSet |= set ( [ 'marker-start' , 'marker-mid' , 'marker-end' ] ) if taintedAttribute in [ 'marker-start' , 'marker-mid' , 'marker-end' ] : taintedSet . add ( 'marker' ) return taintedSet | u Adds an attribute to a set of attributes . |
51,595 | def removeDefaultAttributeValue ( node , attribute ) : if not node . hasAttribute ( attribute . name ) : return 0 if isinstance ( attribute . value , str ) : if node . getAttribute ( attribute . name ) == attribute . value : if ( attribute . conditions is None ) or attribute . conditions ( node ) : node . removeAttribu... | Removes the DefaultAttribute attribute from node if specified conditions are fulfilled |
51,596 | def removeDefaultAttributeValues ( node , options , tainted = set ( ) ) : u num = 0 if node . nodeType != Node . ELEMENT_NODE : return 0 for attribute in default_attributes_universal : num += removeDefaultAttributeValue ( node , attribute ) if node . nodeName in default_attributes_per_element : for attribute in default... | u tainted keeps a set of attributes defined in parent nodes . |
51,597 | def parseListOfPoints ( s ) : i = 0 ws_nums = re . split ( r"\s*[\s,]\s*" , s . strip ( ) ) nums = [ ] for i in range ( len ( ws_nums ) ) : negcoords = ws_nums [ i ] . split ( "-" ) if len ( negcoords ) == 1 : nums . append ( negcoords [ 0 ] ) else : for j in range ( len ( negcoords ) ) : if j == 0 : if negcoords [ 0 ]... | Parse string into a list of points . |
51,598 | def cleanPolygon ( elem , options ) : global _num_points_removed_from_polygon pts = parseListOfPoints ( elem . getAttribute ( 'points' ) ) N = len ( pts ) / 2 if N >= 2 : ( startx , starty ) = pts [ : 2 ] ( endx , endy ) = pts [ - 2 : ] if startx == endx and starty == endy : del pts [ - 2 : ] _num_points_removed_from_p... | Remove unnecessary closing point of polygon points attribute |
51,599 | def cleanPolyline ( elem , options ) : pts = parseListOfPoints ( elem . getAttribute ( 'points' ) ) elem . setAttribute ( 'points' , scourCoordinates ( pts , options , True ) ) | Scour the polyline points attribute |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.