idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
62,900
def bound_symbols ( self ) : if self . _bound_symbols is None : res = set . union ( set ( [ ] ) , * [ _bound_symbols ( val ) for val in self . kwargs . values ( ) ] ) res . update ( set ( [ ] ) , * [ _bound_symbols ( arg ) for arg in self . args ] ) self . _bound_symbols = res return self . _bound_symbols
Set of bound SymPy symbols in the expression
62,901
def download ( url , dest ) : u = urllib . FancyURLopener ( ) logger . info ( "Downloading %s..." % url ) u . retrieve ( url , dest ) logger . info ( 'Done, see %s' % dest ) return dest
Platform - agnostic downloader .
62,902
def logged_command ( cmds ) : "helper function to log a command and then run it" logger . info ( ' ' . join ( cmds ) ) os . system ( ' ' . join ( cmds ) )
helper function to log a command and then run it
62,903
def get_cufflinks ( ) : "Download cufflinks GTF files" for size , md5 , url in cufflinks : cuff_gtf = os . path . join ( args . data_dir , os . path . basename ( url ) ) if not _up_to_date ( md5 , cuff_gtf ) : download ( url , cuff_gtf )
Download cufflinks GTF files
62,904
def get_bams ( ) : for size , md5 , url in bams : bam = os . path . join ( args . data_dir , os . path . basename ( url ) . replace ( '.bam' , '_%s.bam' % CHROM ) ) if not _up_to_date ( md5 , bam ) : logger . info ( 'Downloading reads on chromosome %s from %s to %s' % ( CHROM , url , bam ) ) cmds = [ 'samtools' , 'view' , '-b' , url , COORD , '>' , bam ] logged_command ( cmds ) bai = bam + '.bai' if not os . path . exists ( bai ) : logger . info ( 'indexing %s' % bam ) logger . info ( ' ' . join ( cmds ) ) cmds = [ 'samtools' , 'index' , bam ] logged_command ( cmds ) if os . path . exists ( os . path . basename ( url ) + '.bai' ) : os . unlink ( os . path . basename ( url ) + '.bai' ) for size , md5 , fn in bais : if not _up_to_date ( md5 , fn ) : cmds = [ 'samtools' , 'index' , bai . replace ( '.bai' , '' ) ] logged_command ( cmds )
Download BAM files if needed extract only chr17 reads and regenerate . bai
62,905
def get_gtf ( ) : size , md5 , url = GTF full_gtf = os . path . join ( args . data_dir , os . path . basename ( url ) ) subset_gtf = os . path . join ( args . data_dir , os . path . basename ( url ) . replace ( '.gtf.gz' , '_%s.gtf' % CHROM ) ) if not _up_to_date ( md5 , subset_gtf ) : download ( url , full_gtf ) cmds = [ 'zcat' , '<' , full_gtf , '|' , 'awk -F "\\t" \'{if ($1 == "%s") print $0}\'' % CHROM . replace ( 'chr' , '' ) , '|' , 'awk \'{print "chr"$0}\'' , '>' , subset_gtf ] logged_command ( cmds )
Download GTF file from Ensembl only keeping the chr17 entries .
62,906
def make_db ( ) : size , md5 , fn = DB if not _up_to_date ( md5 , fn ) : gffutils . create_db ( fn . replace ( '.db' , '' ) , fn , verbose = True , force = True )
Create gffutils database
62,907
def cufflinks_conversion ( ) : for size , md5 , fn in cufflinks_tables : fn = os . path . join ( args . data_dir , fn ) table = fn . replace ( '.gtf.gz' , '.table' ) if not _up_to_date ( md5 , table ) : logger . info ( "Converting Cufflinks GTF %s to table" % fn ) fout = open ( table , 'w' ) fout . write ( 'id\tscore\tfpkm\n' ) x = pybedtools . BedTool ( fn ) seen = set ( ) for i in x : accession = i [ 'transcript_id' ] . split ( '.' ) [ 0 ] if accession not in seen : seen . update ( [ accession ] ) fout . write ( '\t' . join ( [ accession , i . score , i [ 'FPKM' ] ] ) + '\n' ) fout . close ( )
convert Cufflinks output GTF files into tables of score and FPKM .
62,908
def plot ( self , feature ) : if isinstance ( feature , gffutils . Feature ) : feature = asinterval ( feature ) self . make_fig ( ) axes = [ ] for ax , method in self . panels ( ) : feature = method ( ax , feature ) axes . append ( ax ) return axes
Spawns a new figure showing data for feature .
62,909
def example_panel ( self , ax , feature ) : txt = '%s:%s-%s' % ( feature . chrom , feature . start , feature . stop ) ax . text ( 0.5 , 0.5 , txt , transform = ax . transAxes ) return feature
A example panel that just prints the text of the feature .
62,910
def signal_panel ( self , ax , feature ) : for gs , kwargs in zip ( self . genomic_signal_objs , self . plotting_kwargs ) : x , y = gs . local_coverage ( feature , ** self . local_coverage_kwargs ) ax . plot ( x , y , ** kwargs ) ax . axis ( 'tight' ) return feature
Plots each genomic signal as a line using the corresponding plotting_kwargs
62,911
def panels ( self ) : ax1 = self . fig . add_subplot ( 211 ) ax2 = self . fig . add_subplot ( 212 , sharex = ax1 ) return ( ax2 , self . gene_panel ) , ( ax1 , self . signal_panel )
Add 2 panels to the figure top for signal and bottom for gene models
62,912
def simple ( ) : MAX_VALUE = 100 bar = Bar ( max_value = MAX_VALUE , fallback = True ) bar . cursor . clear_lines ( 2 ) bar . cursor . save ( ) for i in range ( MAX_VALUE + 1 ) : sleep ( 0.1 * random . random ( ) ) bar . cursor . restore ( ) bar . draw ( value = i )
Simple example using just the Bar class
62,913
def tree ( ) : leaf_values = [ Value ( 0 ) for i in range ( 6 ) ] bd_defaults = dict ( type = Bar , kwargs = dict ( max_value = 10 ) ) test_d = { "Warp Jump" : { "1) Prepare fuel" : { "Load Tanks" : { "Tank 1" : BarDescriptor ( value = leaf_values [ 0 ] , ** bd_defaults ) , "Tank 2" : BarDescriptor ( value = leaf_values [ 1 ] , ** bd_defaults ) , } , "Refine tylium ore" : BarDescriptor ( value = leaf_values [ 2 ] , ** bd_defaults ) , } , "2) Calculate jump co-ordinates" : { "Resolve common name to co-ordinates" : { "Querying resolution from baseship" : BarDescriptor ( value = leaf_values [ 3 ] , ** bd_defaults ) , } , } , "3) Perform jump" : { "Check FTL drive readiness" : BarDescriptor ( value = leaf_values [ 4 ] , ** bd_defaults ) , "Juuuuuump!" : BarDescriptor ( value = leaf_values [ 5 ] , ** bd_defaults ) } } } def incr_value ( obj ) : for val in leaf_values : if val . value < 10 : val . value += 1 break def are_we_done ( obj ) : return all ( val . value == 10 for val in leaf_values ) t = Terminal ( ) n = ProgressTree ( term = t ) n . make_room ( test_d ) while not are_we_done ( test_d ) : sleep ( 0.2 * random . random ( ) ) n . cursor . restore ( ) incr_value ( test_d ) n . draw ( test_d , BarDescriptor ( bd_defaults ) )
Example showing tree progress view
62,914
def ci_plot ( x , arr , conf = 0.95 , ax = None , line_kwargs = None , fill_kwargs = None ) : if ax is None : fig = plt . figure ( ) ax = fig . add_subplot ( 111 ) line_kwargs = line_kwargs or { } fill_kwargs = fill_kwargs or { } m , lo , hi = ci ( arr , conf ) ax . plot ( x , m , ** line_kwargs ) ax . fill_between ( x , lo , hi , ** fill_kwargs ) return ax
Plots the mean and 95% ci for the given array on the given axes
62,915
def add_labels_to_subsets ( ax , subset_by , subset_order , text_kwargs = None , add_hlines = True , hline_kwargs = None ) : _text_kwargs = dict ( transform = ax . get_yaxis_transform ( ) ) if text_kwargs : _text_kwargs . update ( text_kwargs ) _hline_kwargs = dict ( color = 'k' ) if hline_kwargs : _hline_kwargs . update ( hline_kwargs ) pos = 0 for label in subset_order : ind = subset_by == label last_pos = pos pos += sum ( ind ) if add_hlines : ax . axhline ( pos , ** _hline_kwargs ) ax . text ( 1.1 , last_pos + ( pos - last_pos ) / 2.0 , label , ** _text_kwargs )
Helper function for adding labels to subsets within a heatmap .
62,916
def calculate_limits ( array_dict , method = 'global' , percentiles = None , limit = ( ) ) : if percentiles is not None : for percentile in percentiles : if not 0 <= percentile <= 100 : raise ValueError ( "percentile (%s) not between [0, 100]" ) if method == 'global' : all_arrays = np . concatenate ( [ i . ravel ( ) for i in array_dict . itervalues ( ) ] ) if percentiles : vmin = mlab . prctile ( all_arrays , percentiles [ 0 ] ) vmax = mlab . prctile ( all_arrays , percentiles [ 1 ] ) else : vmin = all_arrays . min ( ) vmax = all_arrays . max ( ) d = dict ( [ ( i , ( vmin , vmax ) ) for i in array_dict . keys ( ) ] ) elif method == 'independent' : d = { } for k , v in array_dict . iteritems ( ) : d [ k ] = ( v . min ( ) , v . max ( ) ) elif hasattr ( method , '__call__' ) : d = { } sorted_keys = sorted ( array_dict . keys ( ) , key = method ) for group , keys in itertools . groupby ( sorted_keys , method ) : keys = list ( keys ) all_arrays = np . concatenate ( [ array_dict [ i ] for i in keys ] ) if percentiles : vmin = mlab . prctile ( all_arrays , percentiles [ 0 ] ) vmax = mlab . prctile ( all_arrays , percentiles [ 1 ] ) else : vmin = all_arrays . min ( ) vmax = all_arrays . max ( ) for key in keys : d [ key ] = ( vmin , vmax ) return d
Calculate limits for a group of arrays in a flexible manner .
62,917
def ci ( arr , conf = 0.95 ) : m = arr . mean ( axis = 0 ) n = len ( arr ) se = arr . std ( axis = 0 ) / np . sqrt ( n ) h = se * stats . t . _ppf ( ( 1 + conf ) / 2. , n - 1 ) return m , m - h , m + h
Column - wise confidence interval .
62,918
def nice_log ( x ) : neg = x < 0 xi = np . log2 ( np . abs ( x ) + 1 ) xi [ neg ] = - xi [ neg ] return xi
Uses a log scale but with negative numbers .
62,919
def tip_fdr ( a , alpha = 0.05 ) : zscores = tip_zscores ( a ) pvals = stats . norm . pdf ( zscores ) rejected , fdrs = fdrcorrection ( pvals ) return fdrs
Returns adjusted TIP p - values for a particular alpha .
62,920
def prepare_logged ( x , y ) : xi = np . log2 ( x ) yi = np . log2 ( y ) xv = np . isfinite ( xi ) yv = np . isfinite ( yi ) global_min = min ( xi [ xv ] . min ( ) , yi [ yv ] . min ( ) ) global_max = max ( xi [ xv ] . max ( ) , yi [ yv ] . max ( ) ) xi [ ~ xv ] = global_min yi [ ~ yv ] = global_min return xi , yi
Transform x and y to a log scale while dealing with zeros .
62,921
def _updatecopy ( orig , update_with , keys = None , override = False ) : d = orig . copy ( ) if keys is None : keys = update_with . keys ( ) for k in keys : if k in update_with : if k in d and not override : continue d [ k ] = update_with [ k ] return d
Update a copy of dest with source . If keys is a list then only update with those keys .
62,922
def append ( self , x , y , scatter_kwargs , hist_kwargs = None , xhist_kwargs = None , yhist_kwargs = None , num_ticks = 3 , labels = None , hist_share = False , marginal_histograms = True ) : scatter_kwargs = scatter_kwargs or { } hist_kwargs = hist_kwargs or { } xhist_kwargs = xhist_kwargs or { } yhist_kwargs = yhist_kwargs or { } yhist_kwargs . update ( dict ( orientation = 'horizontal' ) ) coll = self . scatter_ax . scatter ( x , y , ** scatter_kwargs ) coll . labels = labels if not marginal_histograms : return xhk = _updatecopy ( hist_kwargs , xhist_kwargs ) yhk = _updatecopy ( hist_kwargs , yhist_kwargs ) axhistx = self . divider . append_axes ( 'top' , size = self . hist_size , pad = self . pad , sharex = self . scatter_ax , sharey = self . xfirst_ax ) axhisty = self . divider . append_axes ( 'right' , size = self . hist_size , pad = self . pad , sharey = self . scatter_ax , sharex = self . yfirst_ax ) axhistx . yaxis . set_major_locator ( MaxNLocator ( nbins = num_ticks , prune = 'both' ) ) axhisty . xaxis . set_major_locator ( MaxNLocator ( nbins = num_ticks , prune = 'both' ) ) if not self . xfirst_ax and hist_share : self . xfirst_ax = axhistx if not self . yfirst_ax and hist_share : self . yfirst_ax = axhisty self . top_hists . append ( axhistx ) self . right_hists . append ( axhisty ) hx = _clean ( x ) hy = _clean ( y ) self . hxs . append ( hx ) self . hys . append ( hy ) if len ( hx ) > 0 : if len ( hx ) == 1 : _xhk = _updatecopy ( orig = xhk , update_with = dict ( bins = [ hx [ 0 ] , hx [ 0 ] ] ) , keys = [ 'bins' ] ) axhistx . hist ( hx , ** _xhk ) else : axhistx . hist ( hx , ** xhk ) if len ( hy ) > 0 : if len ( hy ) == 1 : _yhk = _updatecopy ( orig = yhk , update_with = dict ( bins = [ hy [ 0 ] , hy [ 0 ] ] ) , keys = [ 'bins' ] ) axhisty . hist ( hy , ** _yhk ) else : axhisty . hist ( hy , ** yhk ) for txt in axhisty . get_yticklabels ( ) + axhistx . get_xticklabels ( ) : txt . set_visible ( False ) for txt in axhisty . get_xticklabels ( ) : txt . set_rotation ( - 90 )
Adds a new scatter to self . scatter_ax as well as marginal histograms for the same data borrowing addtional room from the axes .
62,923
def add_legends ( self , xhists = True , yhists = False , scatter = True , ** kwargs ) : axs = [ ] if xhists : axs . extend ( self . hxs ) if yhists : axs . extend ( self . hys ) if scatter : axs . extend ( self . ax ) for ax in axs : ax . legend ( ** kwargs )
Add legends to axes .
62,924
def genomic_signal ( fn , kind ) : try : klass = _registry [ kind . lower ( ) ] except KeyError : raise ValueError ( 'No support for %s format, choices are %s' % ( kind , _registry . keys ( ) ) ) m = klass ( fn ) m . kind = kind return m
Factory function that makes the right class for the file format .
62,925
def genome ( self ) : f = self . adapter . fileobj d = { } for ref , length in zip ( f . references , f . lengths ) : d [ ref ] = ( 0 , length ) return d
genome dictionary ready for pybedtools based on the BAM header .
62,926
def mapped_read_count ( self , force = False ) : if self . _readcount and not force : return self . _readcount if os . path . exists ( self . fn + '.mmr' ) and not force : for line in open ( self . fn + '.mmr' ) : if line . startswith ( '#' ) : continue self . _readcount = float ( line . strip ( ) ) return self . _readcount cmds = [ 'samtools' , 'view' , '-c' , '-F' , '0x4' , self . fn ] p = subprocess . Popen ( cmds , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) stdout , stderr = p . communicate ( ) if stderr : sys . stderr . write ( 'samtools says: %s' % stderr ) return None mapped_reads = int ( stdout ) if not os . path . exists ( self . fn + '.mmr' ) : fout = open ( self . fn + '.mmr' , 'w' ) fout . write ( str ( mapped_reads ) + '\n' ) fout . close ( ) self . _readcount = mapped_reads return self . _readcount
Counts total reads in a BAM file .
62,927
def print_2x2_table ( table , row_labels , col_labels , fmt = "%d" ) : grand = sum ( table ) t11 , t12 , t21 , t22 = table r1 = t11 + t12 r2 = t21 + t22 c1 = t11 + t21 c2 = t12 + t22 t11 , t12 , t21 , t22 , c1 , c2 , r1 , r2 , grand = [ fmt % i for i in [ t11 , t12 , t21 , t22 , c1 , c2 , r1 , r2 , grand ] ] rows = [ [ "" ] + col_labels + [ 'total' ] , [ row_labels [ 0 ] , t11 , t12 , r1 ] , [ row_labels [ 1 ] , t21 , t22 , r2 ] , [ 'total' , c1 , c2 , grand ] , ] cols = [ [ row [ 0 ] for row in rows ] , [ col_labels [ 0 ] , t11 , t21 , c1 ] , [ col_labels [ 1 ] , t12 , t22 , c2 ] , [ 'total' , r1 , r2 , grand ] , ] widths = [ ] for col in cols : widths . append ( max ( len ( i ) for i in col ) ) sep = [ '=' * i for i in widths ] s = [ ] s . append ( ' ' . join ( sep ) ) s . append ( ' ' . join ( i . ljust ( j ) for i , j in zip ( rows [ 0 ] , widths ) ) ) s . append ( ' ' . join ( sep ) ) for row in rows [ 1 : ] : s . append ( ' ' . join ( i . ljust ( j ) for i , j in zip ( row , widths ) ) ) s . append ( ' ' . join ( sep ) + '\n' ) return "\n" . join ( s )
Prints a table used for Fisher s exact test . Adds row column and grand totals .
62,928
def print_row_perc_table ( table , row_labels , col_labels ) : r1c1 , r1c2 , r2c1 , r2c2 = map ( float , table ) row1 = r1c1 + r1c2 row2 = r2c1 + r2c2 blocks = [ ( r1c1 , row1 ) , ( r1c2 , row1 ) , ( r2c1 , row2 ) , ( r2c2 , row2 ) ] new_table = [ ] for cell , row in blocks : try : x = cell / row except ZeroDivisionError : x = 0 new_table . append ( x ) s = print_2x2_table ( new_table , row_labels , col_labels , fmt = "%.2f" ) s = s . splitlines ( True ) del s [ 5 ] return '' . join ( s )
given a table print the percentages rather than the totals
62,929
def print_col_perc_table ( table , row_labels , col_labels ) : r1c1 , r1c2 , r2c1 , r2c2 = map ( float , table ) col1 = r1c1 + r2c1 col2 = r1c2 + r2c2 blocks = [ ( r1c1 , col1 ) , ( r1c2 , col2 ) , ( r2c1 , col1 ) , ( r2c2 , col2 ) ] new_table = [ ] for cell , row in blocks : try : x = cell / row except ZeroDivisionError : x = 0 new_table . append ( x ) s = print_2x2_table ( new_table , row_labels , col_labels , fmt = "%.2f" ) s = s . splitlines ( False ) last_space = s [ 0 ] . rindex ( " " ) new_s = [ i [ : last_space ] for i in s ] return '\n' . join ( new_s )
given a table print the cols as percentages
62,930
def draw ( self , tree , bar_desc = None , save_cursor = True , flush = True ) : if save_cursor : self . cursor . save ( ) tree = deepcopy ( tree ) lines_required = self . lines_required ( tree ) ensure ( lines_required <= self . cursor . term . height , LengthOverflowError , "Terminal is not long ({} rows) enough to fit all bars " "({} rows)." . format ( self . cursor . term . height , lines_required ) ) bar_desc = BarDescriptor ( type = Bar ) if not bar_desc else bar_desc self . _calculate_values ( tree , bar_desc ) self . _draw ( tree ) if flush : self . cursor . flush ( )
Draw tree to the terminal
62,931
def make_room ( self , tree ) : lines_req = self . lines_required ( tree ) self . cursor . clear_lines ( lines_req )
Clear lines in terminal below current cursor position as required
62,932
def lines_required ( self , tree , count = 0 ) : if all ( [ isinstance ( tree , dict ) , type ( tree ) != BarDescriptor ] ) : return sum ( self . lines_required ( v , count = count ) for v in tree . values ( ) ) + 2 elif isinstance ( tree , BarDescriptor ) : if tree . get ( "kwargs" , { } ) . get ( "title_pos" ) in [ "left" , "right" ] : return 1 else : return 2
Calculate number of lines required to draw tree
62,933
def _calculate_values ( self , tree , bar_d ) : if all ( [ isinstance ( tree , dict ) , type ( tree ) != BarDescriptor ] ) : max_val = 0 value = 0 for k in tree : bar_desc = self . _calculate_values ( tree [ k ] , bar_d ) tree [ k ] = ( bar_desc , tree [ k ] ) value += bar_desc [ "value" ] . value max_val += bar_desc . get ( "kwargs" , { } ) . get ( "max_value" , 100 ) kwargs = merge_dicts ( [ bar_d . get ( "kwargs" , { } ) , dict ( max_value = max_val ) ] , deepcopy = True ) ret_d = merge_dicts ( [ bar_d , dict ( value = Value ( floor ( value ) ) , kwargs = kwargs ) ] , deepcopy = True ) return BarDescriptor ( ret_d ) elif isinstance ( tree , BarDescriptor ) : return tree else : raise TypeError ( "Unexpected type {}" . format ( type ( tree ) ) )
Calculate values for drawing bars of non - leafs in tree
62,934
def _draw ( self , tree , indent = 0 ) : if all ( [ isinstance ( tree , dict ) , type ( tree ) != BarDescriptor ] ) : for k , v in sorted ( tree . items ( ) ) : bar_desc , subdict = v [ 0 ] , v [ 1 ] args = [ self . cursor . term ] + bar_desc . get ( "args" , [ ] ) kwargs = dict ( title_pos = "above" , indent = indent , title = k ) kwargs . update ( bar_desc . get ( "kwargs" , { } ) ) b = Bar ( * args , ** kwargs ) b . draw ( value = bar_desc [ "value" ] . value , flush = False ) self . _draw ( subdict , indent = indent + self . indent )
Recurse through tree and draw all nodes
62,935
def load_features_and_arrays ( prefix , mmap_mode = 'r' ) : features = pybedtools . BedTool ( prefix + '.features' ) arrays = np . load ( prefix + '.npz' , mmap_mode = mmap_mode ) return features , arrays
Returns the features and NumPy arrays that were saved with save_features_and_arrays .
62,936
def save_features_and_arrays ( features , arrays , prefix , compressed = False , link_features = False , overwrite = False ) : if link_features : if isinstance ( features , pybedtools . BedTool ) : assert isinstance ( features . fn , basestring ) features_filename = features . fn else : assert isinstance ( features , basestring ) features_filename = features if overwrite : force_flag = '-f' else : force_flag = '' cmds = [ 'ln' , '-s' , force_flag , os . path . abspath ( features_filename ) , prefix + '.features' ] os . system ( ' ' . join ( cmds ) ) else : pybedtools . BedTool ( features ) . saveas ( prefix + '.features' ) if compressed : np . savez_compressed ( prefix , ** arrays ) else : np . savez ( prefix , ** arrays )
Saves NumPy arrays of processed data along with the features that correspond to each row to files for later use .
62,937
def list_all ( fritz , args ) : devices = fritz . get_devices ( ) for device in devices : print ( '#' * 30 ) print ( 'name=%s' % device . name ) print ( ' ain=%s' % device . ain ) print ( ' id=%s' % device . identifier ) print ( ' productname=%s' % device . productname ) print ( ' manufacturer=%s' % device . manufacturer ) print ( " present=%s" % device . present ) print ( " lock=%s" % device . lock ) print ( " devicelock=%s" % device . device_lock ) if device . present is False : continue if device . has_switch : print ( " Switch:" ) print ( " switch_state=%s" % device . switch_state ) if device . has_switch : print ( " Powermeter:" ) print ( " power=%s" % device . power ) print ( " energy=%s" % device . energy ) print ( " voltage=%s" % device . voltage ) if device . has_temperature_sensor : print ( " Temperature:" ) print ( " temperature=%s" % device . temperature ) print ( " offset=%s" % device . offset ) if device . has_thermostat : print ( " Thermostat:" ) print ( " battery_low=%s" % device . battery_low ) print ( " battery_level=%s" % device . battery_level ) print ( " actual=%s" % device . actual_temperature ) print ( " target=%s" % device . target_temperature ) print ( " comfort=%s" % device . comfort_temperature ) print ( " eco=%s" % device . eco_temperature ) print ( " window=%s" % device . window_open ) print ( " summer=%s" % device . summer_active ) print ( " holiday=%s" % device . holiday_active ) if device . has_alarm : print ( " Alert:" ) print ( " alert=%s" % device . alert_state )
Command that prints all device information .
62,938
def device_statistics ( fritz , args ) : stats = fritz . get_device_statistics ( args . ain ) print ( stats )
Command that prints the device statistics .
62,939
def chunker ( f , n ) : f = iter ( f ) x = [ ] while 1 : if len ( x ) < n : try : x . append ( f . next ( ) ) except StopIteration : if len ( x ) > 0 : yield tuple ( x ) break else : yield tuple ( x ) x = [ ]
Utility function to split iterable f into n chunks
62,940
def split_feature ( f , n ) : if not isinstance ( n , int ) : raise ValueError ( 'n must be an integer' ) orig_feature = copy ( f ) step = ( f . stop - f . start ) / n for i in range ( f . start , f . stop , step ) : f = copy ( orig_feature ) start = i stop = min ( i + step , orig_feature . stop ) f . start = start f . stop = stop yield f if stop == orig_feature . stop : break
Split an interval into n roughly equal portions
62,941
def tointerval ( s ) : if isinstance ( s , basestring ) : m = coord_re . search ( s ) if m . group ( 'strand' ) : return pybedtools . create_interval_from_list ( [ m . group ( 'chrom' ) , m . group ( 'start' ) , m . group ( 'stop' ) , '.' , '0' , m . group ( 'strand' ) ] ) else : return pybedtools . create_interval_from_list ( [ m . group ( 'chrom' ) , m . group ( 'start' ) , m . group ( 'stop' ) , ] ) return s
If string then convert to an interval ; otherwise just return the input
62,942
def max_width ( self ) : value , unit = float ( self . _width_str [ : - 1 ] ) , self . _width_str [ - 1 ] ensure ( unit in [ "c" , "%" ] , ValueError , "Width unit must be either 'c' or '%'" ) if unit == "c" : ensure ( value <= self . columns , ValueError , "Terminal only has {} columns, cannot draw " "bar of size {}." . format ( self . columns , value ) ) retval = value else : ensure ( 0 < value <= 100 , ValueError , "value=={} does not satisfy 0 < value <= 100" . format ( value ) ) dec = value / 100 retval = dec * self . columns return floor ( retval )
Get maximum width of progress bar
62,943
def full_line_width ( self ) : bar_str_len = sum ( [ self . _indent , ( ( len ( self . title ) + 1 ) if self . _title_pos in [ "left" , "right" ] else 0 ) , len ( self . start_char ) , self . max_width , len ( self . end_char ) , 1 , len ( str ( self . max_value ) ) * 2 + 1 ] ) return bar_str_len
Find actual length of bar_str
62,944
def _supports_colors ( term , raise_err , colors ) : for color in colors : try : if isinstance ( color , str ) : req_colors = 16 if "bright" in color else 8 ensure ( term . number_of_colors >= req_colors , ColorUnsupportedError , "{} is unsupported by your terminal." . format ( color ) ) elif isinstance ( color , int ) : ensure ( term . number_of_colors >= color , ColorUnsupportedError , "{} is unsupported by your terminal." . format ( color ) ) except ColorUnsupportedError as e : if raise_err : raise e else : return False else : return True
Check if term supports colors
62,945
def _get_format_callable ( term , color , back_color ) : if isinstance ( color , str ) : ensure ( any ( isinstance ( back_color , t ) for t in [ str , type ( None ) ] ) , TypeError , "back_color must be a str or NoneType" ) if back_color : return getattr ( term , "_" . join ( [ color , "on" , back_color ] ) ) elif back_color is None : return getattr ( term , color ) elif isinstance ( color , int ) : return term . on_color ( color ) else : raise TypeError ( "Invalid type {} for color" . format ( type ( color ) ) )
Get string - coloring callable
62,946
def draw ( self , value , newline = True , flush = True ) : self . _measure_terminal ( ) amount_complete = 1.0 if self . max_value == 0 else value / self . max_value fill_amount = int ( floor ( amount_complete * self . max_width ) ) empty_amount = self . max_width - fill_amount amount_complete_str = ( u"{}/{}" . format ( value , self . max_value ) if self . _num_rep == "fraction" else u"{}%" . format ( int ( floor ( amount_complete * 100 ) ) ) ) if self . _title_pos == "above" : title_str = u"{}{}\n" . format ( " " * self . _indent , self . title , ) self . _write ( title_str , ignore_overflow = True ) bar_str = u'' . join ( [ u ( self . filled ( self . _filled_char * fill_amount ) ) , u ( self . empty ( self . _empty_char * empty_amount ) ) , ] ) bar_str = u"{}{}{}" . format ( self . start_char , bar_str , self . end_char ) if self . _title_pos == "left" : bar_str = u"{} {}" . format ( self . title , bar_str ) elif self . _title_pos == "right" : bar_str = u"{} {}" . format ( bar_str , self . title ) bar_str = u'' . join ( [ " " * self . _indent , bar_str ] ) bar_str = u"{} {}" . format ( bar_str , amount_complete_str ) bar_str = u"{}{}" . format ( bar_str , self . term . normal ) self . _write ( bar_str , s_length = self . full_line_width ) if self . _title_pos == "below" : title_str = u"\n{}{}" . format ( " " * self . _indent , self . title , ) self . _write ( title_str , ignore_overflow = True ) if newline : self . cursor . newline ( ) if flush : self . cursor . flush ( )
Draw the progress bar
62,947
def get_text ( nodelist ) : value = [ ] for node in nodelist : if node . nodeType == node . TEXT_NODE : value . append ( node . data ) return '' . join ( value )
Get the value from a text node .
62,948
def _request ( self , url , params = None , timeout = 10 ) : rsp = self . _session . get ( url , params = params , timeout = timeout ) rsp . raise_for_status ( ) return rsp . text . strip ( )
Send a request with parameters .
62,949
def _login_request ( self , username = None , secret = None ) : url = 'http://' + self . _host + '/login_sid.lua' params = { } if username : params [ 'username' ] = username if secret : params [ 'response' ] = secret plain = self . _request ( url , params ) dom = xml . dom . minidom . parseString ( plain ) sid = get_text ( dom . getElementsByTagName ( 'SID' ) [ 0 ] . childNodes ) challenge = get_text ( dom . getElementsByTagName ( 'Challenge' ) [ 0 ] . childNodes ) return ( sid , challenge )
Send a login request with paramerters .
62,950
def _logout_request ( self ) : _LOGGER . debug ( 'logout' ) url = 'http://' + self . _host + '/login_sid.lua' params = { 'security:command/logout' : '1' , 'sid' : self . _sid } self . _request ( url , params )
Send a logout request .
62,951
def _create_login_secret ( challenge , password ) : to_hash = ( challenge + '-' + password ) . encode ( 'UTF-16LE' ) hashed = hashlib . md5 ( to_hash ) . hexdigest ( ) return '{0}-{1}' . format ( challenge , hashed )
Create a login secret .
62,952
def _aha_request ( self , cmd , ain = None , param = None , rf = str ) : url = 'http://' + self . _host + '/webservices/homeautoswitch.lua' params = { 'switchcmd' : cmd , 'sid' : self . _sid } if param : params [ 'param' ] = param if ain : params [ 'ain' ] = ain plain = self . _request ( url , params ) if plain == 'inval' : raise InvalidError if rf == bool : return bool ( int ( plain ) ) return rf ( plain )
Send an AHA request .
62,953
def login ( self ) : try : ( sid , challenge ) = self . _login_request ( ) if sid == '0000000000000000' : secret = self . _create_login_secret ( challenge , self . _password ) ( sid2 , challenge ) = self . _login_request ( username = self . _user , secret = secret ) if sid2 == '0000000000000000' : _LOGGER . warning ( "login failed %s" , sid2 ) raise LoginError ( self . _user ) self . _sid = sid2 except xml . parsers . expat . ExpatError : raise LoginError ( self . _user )
Login and get a valid session ID .
62,954
def get_device_elements ( self ) : plain = self . _aha_request ( 'getdevicelistinfos' ) dom = xml . dom . minidom . parseString ( plain ) _LOGGER . debug ( dom ) return dom . getElementsByTagName ( "device" )
Get the DOM elements for the device list .