idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
9,400
def inject_colored_exceptions ( ) : #COLORED_INJECTS = '--nocolorex' not in sys.argv #COLORED_INJECTS = '--colorex' in sys.argv # Ignore colored exceptions on win32 if VERBOSE : print ( '[inject] injecting colored exceptions' ) if not sys . platform . startswith ( 'win32' ) : if VERYVERBOSE : print ( '[inject] injecting colored exceptions' ) if '--noinject-color' in sys . argv : print ( 'Not injecting color' ) else : sys . excepthook = colored_pygments_excepthook else : if VERYVERBOSE : print ( '[inject] cannot inject colored exceptions' )
Causes exceptions to be colored if not already
170
9
9,401
def inject_print_functions ( module_name = None , module_prefix = '[???]' , DEBUG = False , module = None ) : module = _get_module ( module_name , module ) if SILENT : def print ( * args ) : """ silent builtins.print """ pass def printDBG ( * args ) : """ silent debug print """ pass def print_ ( * args ) : """ silent stdout.write """ pass else : if DEBUG_PRINT : # Turns on printing where a message came from def print ( * args ) : """ debugging logging builtins.print """ from utool . _internal . meta_util_dbg import get_caller_name calltag = '' . join ( ( '[caller:' , get_caller_name ( N = DEBUG_PRINT_N ) , ']' ) ) util_logging . _utool_print ( ) ( calltag , * args ) else : def print ( * args ) : """ logging builtins.print """ util_logging . _utool_print ( ) ( * args ) if __AGGROFLUSH__ : def print_ ( * args ) : """ aggressive logging stdout.write """ util_logging . _utool_write ( ) ( * args ) util_logging . _utool_flush ( ) ( ) else : def print_ ( * args ) : """ logging stdout.write """ util_logging . _utool_write ( ) ( * args ) # turn on module debugging with command line flags dotpos = module . __name__ . rfind ( '.' ) if dotpos == - 1 : module_name = module . __name__ else : module_name = module . __name__ [ dotpos + 1 : ] def _replchars ( str_ ) : return str_ . replace ( '_' , '-' ) . replace ( ']' , '' ) . replace ( '[' , '' ) flag1 = '--debug-%s' % _replchars ( module_name ) flag2 = '--debug-%s' % _replchars ( module_prefix ) DEBUG_FLAG = any ( [ flag in sys . argv for flag in [ flag1 , flag2 ] ] ) for curflag in ARGV_DEBUG_FLAGS : if curflag in module_prefix : DEBUG_FLAG = True if __DEBUG_ALL__ or DEBUG or DEBUG_FLAG : print ( 'INJECT_PRINT: %r == %r' % ( module_name , module_prefix ) ) def printDBG ( * args ) : """ debug logging print """ msg = ', ' . join ( map ( str , args ) ) util_logging . __UTOOL_PRINTDBG__ ( module_prefix + ' DEBUG ' + msg ) else : def printDBG ( * args ) : """ silent debug logging print """ pass #_inject_funcs(module, print, print_, printDBG) print_funcs = ( print , print_ , printDBG ) return print_funcs
makes print functions to be injected into the module
656
9
9,402
def make_module_reload_func ( module_name = None , module_prefix = '[???]' , module = None ) : module = _get_module ( module_name , module , register = False ) if module_name is None : module_name = str ( module . __name__ ) def rrr ( verbose = True ) : """ Dynamic module reloading """ if not __RELOAD_OK__ : raise Exception ( 'Reloading has been forced off' ) try : import imp if verbose and not QUIET : builtins . print ( 'RELOAD: ' + str ( module_prefix ) + ' __name__=' + module_name ) imp . reload ( module ) except Exception as ex : print ( ex ) print ( '%s Failed to reload' % module_prefix ) raise # this doesn't seem to set anything on import * #_inject_funcs(module, rrr) return rrr
Injects dynamic module reloading
202
7
9,403
def noinject ( module_name = None , module_prefix = '[???]' , DEBUG = False , module = None , N = 0 , via = None ) : if PRINT_INJECT_ORDER : from utool . _internal import meta_util_dbg callername = meta_util_dbg . get_caller_name ( N = N + 1 , strict = False ) lineno = meta_util_dbg . get_caller_lineno ( N = N + 1 , strict = False ) suff = ' via %s' % ( via , ) if via else '' fmtdict = dict ( N = N , lineno = lineno , callername = callername , modname = module_name , suff = suff ) msg = '[util_inject] N={N} {modname} is imported by {callername} at lineno={lineno}{suff}' . format ( * * fmtdict ) if DEBUG_SLOW_IMPORT : global PREV_MODNAME seconds = tt . toc ( ) import_times [ ( PREV_MODNAME , module_name ) ] = seconds PREV_MODNAME = module_name builtins . print ( msg ) if DEBUG_SLOW_IMPORT : tt . tic ( ) # builtins.print(elapsed) if EXIT_ON_INJECT_MODNAME == module_name : builtins . print ( '...exiting' ) assert False , 'exit in inject requested'
Use in modules that do not have inject in them
327
10
9,404
def inject ( module_name = None , module_prefix = '[???]' , DEBUG = False , module = None , N = 1 ) : #noinject(module_name, module_prefix, DEBUG, module, N=1) noinject ( module_name , module_prefix , DEBUG , module , N = N ) module = _get_module ( module_name , module ) rrr = make_module_reload_func ( None , module_prefix , module ) profile_ = make_module_profile_func ( None , module_prefix , module ) print_funcs = inject_print_functions ( None , module_prefix , DEBUG , module ) ( print , print_ , printDBG ) = print_funcs return ( print , print_ , printDBG , rrr , profile_ )
Injects your module with utool magic
178
9
9,405
def inject2 ( module_name = None , module_prefix = None , DEBUG = False , module = None , N = 1 ) : if module_prefix is None : module_prefix = '[%s]' % ( module_name , ) noinject ( module_name , module_prefix , DEBUG , module , N = N ) module = _get_module ( module_name , module ) rrr = make_module_reload_func ( None , module_prefix , module ) profile_ = make_module_profile_func ( None , module_prefix , module ) print = make_module_print_func ( module ) return print , rrr , profile_
wrapper that depricates print_ and printDBG
143
11
9,406
def inject_python_code2 ( fpath , patch_code , tag ) : import utool as ut text = ut . readfrom ( fpath ) start_tag = '# <%s>' % tag end_tag = '# </%s>' % tag new_text = ut . replace_between_tags ( text , patch_code , start_tag , end_tag ) ut . writeto ( fpath , new_text )
Does autogeneration stuff
97
6
9,407
def inject_python_code ( fpath , patch_code , tag = None , inject_location = 'after_imports' ) : import utool as ut assert tag is not None , 'TAG MUST BE SPECIFIED IN INJECTED CODETEXT' text = ut . read_from ( fpath ) comment_start_tag = '# <util_inject:%s>' % tag comment_end_tag = '# </util_inject:%s>' % tag tagstart_txtpos = text . find ( comment_start_tag ) tagend_txtpos = text . find ( comment_end_tag ) text_lines = ut . split_python_text_into_lines ( text ) # split the file into two parts and inject code between them if tagstart_txtpos != - 1 or tagend_txtpos != - 1 : assert tagstart_txtpos != - 1 , 'both tags must not be found' assert tagend_txtpos != - 1 , 'both tags must not be found' for pos , line in enumerate ( text_lines ) : if line . startswith ( comment_start_tag ) : tagstart_pos = pos if line . startswith ( comment_end_tag ) : tagend_pos = pos part1 = text_lines [ 0 : tagstart_pos ] part2 = text_lines [ tagend_pos + 1 : ] else : if inject_location == 'after_imports' : first_nonimport_pos = 0 for line in text_lines : list_ = [ 'import ' , 'from ' , '#' , ' ' ] isvalid = ( len ( line ) == 0 or any ( line . startswith ( str_ ) for str_ in list_ ) ) if not isvalid : break first_nonimport_pos += 1 part1 = text_lines [ 0 : first_nonimport_pos ] part2 = text_lines [ first_nonimport_pos : ] else : raise AssertionError ( 'Unknown inject location' ) newtext = ( '\n' . join ( part1 + [ comment_start_tag ] ) + '\n' + patch_code + '\n' + '\n' . join ( [ comment_end_tag ] + part2 ) ) text_backup_fname = fpath + '.' + ut . get_timestamp ( ) + '.bak' ut . write_to ( text_backup_fname , text ) ut . write_to ( fpath , newtext )
DEPRICATE puts code into files on disk
554
10
9,408
def printableType ( val , name = None , parent = None ) : import numpy as np if parent is not None and hasattr ( parent , 'customPrintableType' ) : # Hack for non - trivial preference types _typestr = parent . customPrintableType ( name ) if _typestr is not None : return _typestr if isinstance ( val , np . ndarray ) : info = npArrInfo ( val ) _typestr = info . dtypestr elif isinstance ( val , object ) : _typestr = val . __class__ . __name__ else : _typestr = str ( type ( val ) ) _typestr = _typestr . replace ( 'type' , '' ) _typestr = re . sub ( '[\'><]' , '' , _typestr ) _typestr = re . sub ( ' *' , ' ' , _typestr ) _typestr = _typestr . strip ( ) return _typestr
Tries to make a nice type string for a value . Can also pass in a Printable parent object
225
21
9,409
def printableVal ( val , type_bit = True , justlength = False ) : from utool import util_dev # Move to util_dev # NUMPY ARRAY import numpy as np if type ( val ) is np . ndarray : info = npArrInfo ( val ) if info . dtypestr . startswith ( 'bool' ) : _valstr = '{ shape:' + info . shapestr + ' bittotal: ' + info . bittotal + '}' # + '\n |_____' elif info . dtypestr . startswith ( 'float' ) : _valstr = util_dev . get_stats_str ( val ) else : _valstr = '{ shape:' + info . shapestr + ' mM:' + info . minmaxstr + ' }' # + '\n |_____' # String elif isinstance ( val , ( str , unicode ) ) : # NOQA _valstr = '\'%s\'' % val # List elif isinstance ( val , list ) : if justlength or len ( val ) > 30 : _valstr = 'len=' + str ( len ( val ) ) else : _valstr = '[ ' + ( ', \n ' . join ( [ str ( v ) for v in val ] ) ) + ' ]' # ??? isinstance(val, AbstractPrintable): elif hasattr ( val , 'get_printable' ) and type ( val ) != type : _valstr = val . get_printable ( type_bit = type_bit ) elif isinstance ( val , dict ) : _valstr = '{\n' for val_key in val . keys ( ) : val_val = val [ val_key ] _valstr += ' ' + str ( val_key ) + ' : ' + str ( val_val ) + '\n' _valstr += '}' else : _valstr = str ( val ) if _valstr . find ( '\n' ) > 0 : # Indent if necessary _valstr = _valstr . replace ( '\n' , '\n ' ) _valstr = '\n ' + _valstr _valstr = re . sub ( '\n *$' , '' , _valstr ) # Replace empty lines return _valstr
Very old way of doing pretty printing . Need to update and refactor . DEPRICATE
514
19
9,410
def npArrInfo ( arr ) : from utool . DynamicStruct import DynStruct info = DynStruct ( ) info . shapestr = '[' + ' x ' . join ( [ str ( x ) for x in arr . shape ] ) + ']' info . dtypestr = str ( arr . dtype ) if info . dtypestr == 'bool' : info . bittotal = 'T=%d, F=%d' % ( sum ( arr ) , sum ( 1 - arr ) ) elif info . dtypestr == 'object' : info . minmaxstr = 'NA' elif info . dtypestr [ 0 ] == '|' : info . minmaxstr = 'NA' else : if arr . size > 0 : info . minmaxstr = '(%r, %r)' % ( arr . min ( ) , arr . max ( ) ) else : info . minmaxstr = '(None)' return info
OLD update and refactor
208
5
9,411
def get_isobaric_ratios ( psmfn , psmheader , channels , denom_channels , min_int , targetfn , accessioncol , normalize , normratiofn ) : psm_or_feat_ratios = get_psmratios ( psmfn , psmheader , channels , denom_channels , min_int , accessioncol ) if normalize and normratiofn : normheader = reader . get_tsv_header ( normratiofn ) normratios = get_ratios_from_fn ( normratiofn , normheader , channels ) ch_medians = get_medians ( channels , normratios , report = True ) outratios = calculate_normalized_ratios ( psm_or_feat_ratios , ch_medians , channels ) elif normalize : flatratios = [ [ feat [ ch ] for ch in channels ] for feat in psm_or_feat_ratios ] ch_medians = get_medians ( channels , flatratios , report = True ) outratios = calculate_normalized_ratios ( psm_or_feat_ratios , ch_medians , channels ) else : outratios = psm_or_feat_ratios # at this point, outratios look like: # [{ch1: 123, ch2: 456, ISOQUANTRATIO_FEAT_ACC: ENSG1244}, ] if accessioncol and targetfn : outratios = { x [ ISOQUANTRATIO_FEAT_ACC ] : x for x in outratios } return output_to_target_accession_table ( targetfn , outratios , channels ) elif not accessioncol and not targetfn : return paste_to_psmtable ( psmfn , psmheader , outratios ) elif accessioncol and not targetfn : # generate new table with accessions return ( { ( k if not k == ISOQUANTRATIO_FEAT_ACC else prottabledata . HEADER_ACCESSION ) : v for k , v in ratio . items ( ) } for ratio in outratios )
Main function to calculate ratios for PSMs peptides proteins genes . Can do simple ratios median - of - ratios and median - centering normalization .
484
30
9,412
def sanitize ( value ) : value = unicodedata . normalize ( 'NFKD' , value ) value = value . strip ( ) value = re . sub ( '[^./\w\s-]' , '' , value ) value = re . sub ( '[-\s]+' , '-' , value ) return value
Strips all undesirable characters out of potential file paths .
72
12
9,413
def remove_on_exception ( dirname , remove = True ) : os . makedirs ( dirname ) try : yield except : if remove : shutil . rmtree ( dirname , ignore_errors = True ) raise
Creates a directory yields to the caller and removes that directory if an exception is thrown .
50
18
9,414
def add_percolator_to_mzidtsv ( mzidfn , tsvfn , multipsm , oldheader ) : namespace = readers . get_mzid_namespace ( mzidfn ) try : xmlns = '{%s}' % namespace [ 'xmlns' ] except TypeError : xmlns = '' specfnids = readers . get_mzid_specfile_ids ( mzidfn , namespace ) mzidpepmap = { } for peptide in readers . generate_mzid_peptides ( mzidfn , namespace ) : pep_id , seq = readers . get_mzid_peptidedata ( peptide , xmlns ) mzidpepmap [ pep_id ] = seq mzidpercomap = { } for specid_data in readers . generate_mzid_spec_id_items ( mzidfn , namespace , xmlns , specfnids ) : scan , fn , pepid , spec_id = specid_data percodata = readers . get_specidentitem_percolator_data ( spec_id , xmlns ) try : mzidpercomap [ fn ] [ scan ] [ mzidpepmap [ pepid ] ] = percodata except KeyError : try : mzidpercomap [ fn ] [ scan ] = { mzidpepmap [ pepid ] : percodata } except KeyError : mzidpercomap [ fn ] = { scan : { mzidpepmap [ pepid ] : percodata } } for line in tsvreader . generate_tsv_psms ( tsvfn , oldheader ) : outline = { k : v for k , v in line . items ( ) } fn = line [ mzidtsvdata . HEADER_SPECFILE ] scan = line [ mzidtsvdata . HEADER_SCANNR ] seq = line [ mzidtsvdata . HEADER_PEPTIDE ] outline . update ( mzidpercomap [ fn ] [ scan ] [ seq ] ) yield outline
Takes a MSGF + tsv and corresponding mzId adds percolatordata to tsv lines . Generator yields the lines . Multiple PSMs per scan can be delivered in which case rank is also reported .
477
45
9,415
def parse_rawprofile_blocks ( text ) : # The total time reported in the raw output is from pystone not kernprof # The pystone total time is actually the average time spent in the function delim = 'Total time: ' delim2 = 'Pystone time: ' #delim = 'File: ' profile_block_list = ut . regex_split ( '^' + delim , text ) for ix in range ( 1 , len ( profile_block_list ) ) : profile_block_list [ ix ] = delim2 + profile_block_list [ ix ] return profile_block_list
Split the file into blocks along delimters and and put delimeters back in the list
133
17
9,416
def parse_timemap_from_blocks ( profile_block_list ) : prefix_list = [ ] timemap = ut . ddict ( list ) for ix in range ( len ( profile_block_list ) ) : block = profile_block_list [ ix ] total_time = get_block_totaltime ( block ) # Blocks without time go at the front of sorted output if total_time is None : prefix_list . append ( block ) # Blocks that are not run are not appended to output elif total_time != 0 : timemap [ total_time ] . append ( block ) return prefix_list , timemap
Build a map from times to line_profile blocks
142
10
9,417
def clean_line_profile_text ( text ) : # profile_block_list = parse_rawprofile_blocks ( text ) #profile_block_list = fix_rawprofile_blocks(profile_block_list) #--- # FIXME can be written much nicer prefix_list , timemap = parse_timemap_from_blocks ( profile_block_list ) # Sort the blocks by time sorted_lists = sorted ( six . iteritems ( timemap ) , key = operator . itemgetter ( 0 ) ) newlist = prefix_list [ : ] for key , val in sorted_lists : newlist . extend ( val ) # Rejoin output text output_text = '\n' . join ( newlist ) #--- # Hack in a profile summary summary_text = get_summary ( profile_block_list ) output_text = output_text return output_text , summary_text
Sorts the output from line profile by execution time Removes entries which were not run
196
17
9,418
def clean_lprof_file ( input_fname , output_fname = None ) : # Read the raw .lprof text dump text = ut . read_from ( input_fname ) # Sort and clean the text output_text = clean_line_profile_text ( text ) return output_text
Reads a . lprof file and cleans it
67
10
9,419
def get_class_weights ( y , smooth_factor = 0 ) : from collections import Counter counter = Counter ( y ) if smooth_factor > 0 : p = max ( counter . values ( ) ) * smooth_factor for k in counter . keys ( ) : counter [ k ] += p majority = max ( counter . values ( ) ) return { cls : float ( majority / count ) for cls , count in counter . items ( ) }
Returns the weights for each class based on the frequencies of the samples .
95
14
9,420
def plot_loss_history ( history , figsize = ( 15 , 8 ) ) : plt . figure ( figsize = figsize ) plt . plot ( history . history [ "loss" ] ) plt . plot ( history . history [ "val_loss" ] ) plt . xlabel ( "# Epochs" ) plt . ylabel ( "Loss" ) plt . legend ( [ "Training" , "Validation" ] ) plt . title ( "Loss over time" ) plt . show ( )
Plots the learning history for a Keras model assuming the validation data was provided to the fit function .
117
21
9,421
def iter_window ( iterable , size = 2 , step = 1 , wrap = False ) : # it.tee may be slow, but works on all iterables iter_list = it . tee ( iterable , size ) if wrap : # Secondary iterables need to be cycled for wraparound iter_list = [ iter_list [ 0 ] ] + list ( map ( it . cycle , iter_list [ 1 : ] ) ) # Step each iterator the approprate number of times try : for count , iter_ in enumerate ( iter_list [ 1 : ] , start = 1 ) : for _ in range ( count ) : six . next ( iter_ ) except StopIteration : return iter ( ( ) ) else : _window_iter = zip ( * iter_list ) # Account for the step size window_iter = it . islice ( _window_iter , 0 , None , step ) return window_iter
r iterates through iterable with a window size generalizeation of itertwo
201
17
9,422
def iter_compress ( item_iter , flag_iter ) : # TODO: Just use it.compress true_items = ( item for ( item , flag ) in zip ( item_iter , flag_iter ) if flag ) return true_items
iter_compress - like numpy compress
55
9
9,423
def ichunks ( iterable , chunksize , bordermode = None ) : if bordermode is None : return ichunks_noborder ( iterable , chunksize ) elif bordermode == 'cycle' : return ichunks_cycle ( iterable , chunksize ) elif bordermode == 'replicate' : return ichunks_replicate ( iterable , chunksize ) else : raise ValueError ( 'unknown bordermode=%r' % ( bordermode , ) )
r generates successive n - sized chunks from iterable .
104
11
9,424
def ichunks_list ( list_ , chunksize ) : return ( list_ [ ix : ix + chunksize ] for ix in range ( 0 , len ( list_ ) , chunksize ) )
input must be a list .
46
6
9,425
def interleave ( args ) : arg_iters = list ( map ( iter , args ) ) cycle_iter = it . cycle ( arg_iters ) for iter_ in cycle_iter : yield six . next ( iter_ )
r zip followed by flatten
50
6
9,426
def random_product ( items , num = None , rng = None ) : import utool as ut rng = ut . ensure_rng ( rng , 'python' ) seen = set ( ) items = [ list ( g ) for g in items ] max_num = ut . prod ( map ( len , items ) ) if num is None : num = max_num if num > max_num : raise ValueError ( 'num exceedes maximum number of products' ) # TODO: make this more efficient when num is large if num > max_num // 2 : for prod in ut . shuffle ( list ( it . product ( * items ) ) , rng = rng ) : yield prod else : while len ( seen ) < num : # combo = tuple(sorted(rng.choice(items, size, replace=False))) idxs = tuple ( rng . randint ( 0 , len ( g ) - 1 ) for g in items ) if idxs not in seen : seen . add ( idxs ) prod = tuple ( g [ x ] for g , x in zip ( items , idxs ) ) yield prod
Yields num items from the cartesian product of items in a random order .
243
17
9,427
def random_combinations ( items , size , num = None , rng = None ) : import scipy . misc import numpy as np import utool as ut rng = ut . ensure_rng ( rng , impl = 'python' ) num_ = np . inf if num is None else num # Ensure we dont request more than is possible n_max = int ( scipy . misc . comb ( len ( items ) , size ) ) num_ = min ( n_max , num_ ) if num is not None and num_ > n_max // 2 : # If num is too big just generate all combinations and shuffle them combos = list ( it . combinations ( items , size ) ) rng . shuffle ( combos ) for combo in combos [ : num ] : yield combo else : # Otherwise yield randomly until we get something we havent seen items = list ( items ) combos = set ( ) while len ( combos ) < num_ : # combo = tuple(sorted(rng.choice(items, size, replace=False))) combo = tuple ( sorted ( rng . sample ( items , size ) ) ) if combo not in combos : # TODO: store indices instead of combo values combos . add ( combo ) yield combo
Yields num combinations of length size from items in random order
265
13
9,428
def parse_dsn ( dsn_string ) : dsn = urlparse ( dsn_string ) scheme = dsn . scheme . split ( '+' ) [ 0 ] username = password = host = port = None host = dsn . netloc if '@' in host : username , host = host . split ( '@' ) if ':' in username : username , password = username . split ( ':' ) password = unquote ( password ) username = unquote ( username ) if ':' in host : host , port = host . split ( ':' ) port = int ( port ) database = dsn . path . split ( '?' ) [ 0 ] [ 1 : ] query = dsn . path . split ( '?' ) [ 1 ] if '?' in dsn . path else dsn . query kwargs = dict ( parse_qsl ( query , True ) ) if scheme == 'sqlite' : return SQLiteDriver , [ dsn . path ] , { } elif scheme == 'mysql' : kwargs [ 'user' ] = username or 'root' kwargs [ 'db' ] = database if port : kwargs [ 'port' ] = port if host : kwargs [ 'host' ] = host if password : kwargs [ 'passwd' ] = password return MySQLDriver , [ ] , kwargs elif scheme == 'postgresql' : kwargs [ 'user' ] = username or 'postgres' kwargs [ 'database' ] = database if port : kwargs [ 'port' ] = port if 'unix_socket' in kwargs : kwargs [ 'host' ] = kwargs . pop ( 'unix_socket' ) elif host : kwargs [ 'host' ] = host if password : kwargs [ 'password' ] = password return PostgreSQLDriver , [ ] , kwargs else : raise ValueError ( 'Unknown driver %s' % dsn_string )
Parse a connection string and return the associated driver
434
10
9,429
def db_for_write ( self , model , * * hints ) : try : if model . sf_access == READ_ONLY : raise WriteNotSupportedError ( "%r is a read-only model." % model ) except AttributeError : pass return None
Prevent write actions on read - only tables .
57
10
9,430
def run_hook ( self , hook , * args , * * kwargs ) : for plugin in self . raw_plugins : if hasattr ( plugin , hook ) : self . logger . debug ( 'Calling hook {0} in plugin {1}' . format ( hook , plugin . __name__ ) ) getattr ( plugin , hook ) ( * args , * * kwargs )
Loop over all plugins and invoke function hook with args and kwargs in each of them . If the plugin does not have the function it is skipped .
84
31
9,431
def write_tsv ( headerfields , features , outfn ) : with open ( outfn , 'w' ) as fp : write_tsv_line_from_list ( headerfields , fp ) for line in features : write_tsv_line_from_list ( [ str ( line [ field ] ) for field in headerfields ] , fp )
Writes header and generator of lines to tab separated file .
80
12
9,432
def write_tsv_line_from_list ( linelist , outfp ) : line = '\t' . join ( linelist ) outfp . write ( line ) outfp . write ( '\n' )
Utility method to convert list to tsv line with carriage return
48
13
9,433
def replace_between_tags ( text , repl_ , start_tag , end_tag = None ) : new_lines = [ ] editing = False lines = text . split ( '\n' ) for line in lines : if not editing : new_lines . append ( line ) if line . strip ( ) . startswith ( start_tag ) : new_lines . append ( repl_ ) editing = True if end_tag is not None and line . strip ( ) . startswith ( end_tag ) : editing = False new_lines . append ( line ) new_text = '\n' . join ( new_lines ) return new_text
r Replaces text between sentinal lines in a block of text .
141
14
9,434
def theta_str ( theta , taustr = TAUSTR , fmtstr = '{coeff:,.1f}{taustr}' ) : coeff = theta / TAU theta_str = fmtstr . format ( coeff = coeff , taustr = taustr ) return theta_str
r Format theta so it is interpretable in base 10
73
12
9,435
def bbox_str ( bbox , pad = 4 , sep = ', ' ) : if bbox is None : return 'None' fmtstr = sep . join ( [ '%' + six . text_type ( pad ) + 'd' ] * 4 ) return '(' + fmtstr % tuple ( bbox ) + ')'
r makes a string from an integer bounding box
72
10
9,436
def verts_str ( verts , pad = 1 ) : if verts is None : return 'None' fmtstr = ', ' . join ( [ '%' + six . text_type ( pad ) + 'd' + ', %' + six . text_type ( pad ) + 'd' ] * 1 ) return ', ' . join ( [ '(' + fmtstr % vert + ')' for vert in verts ] )
r makes a string from a list of integer verticies
94
12
9,437
def remove_chars ( str_ , char_list ) : outstr = str_ [ : ] for char in char_list : outstr = outstr . replace ( char , '' ) return outstr
removes all chars in char_list from str_
44
11
9,438
def get_minimum_indentation ( text ) : lines = text . split ( '\n' ) indentations = [ get_indentation ( line_ ) for line_ in lines if len ( line_ . strip ( ) ) > 0 ] if len ( indentations ) == 0 : return 0 return min ( indentations )
r returns the number of preceding spaces
71
7
9,439
def indentjoin ( strlist , indent = '\n ' , suffix = '' ) : indent_ = indent strlist = list ( strlist ) if len ( strlist ) == 0 : return '' return indent_ + indent_ . join ( [ six . text_type ( str_ ) + suffix for str_ in strlist ] )
r Convineince indentjoin
71
6
9,440
def truncate_str ( str_ , maxlen = 110 , truncmsg = ' ~~~TRUNCATED~~~ ' ) : if NO_TRUNCATE : return str_ if maxlen is None or maxlen == - 1 or len ( str_ ) < maxlen : return str_ else : maxlen_ = maxlen - len ( truncmsg ) lowerb = int ( maxlen_ * .8 ) upperb = maxlen_ - lowerb tup = ( str_ [ : lowerb ] , truncmsg , str_ [ - upperb : ] ) return '' . join ( tup )
Removes the middle part of any string over maxlen characters .
132
13
9,441
def packstr ( instr , textwidth = 160 , breakchars = ' ' , break_words = True , newline_prefix = '' , indentation = '' , nlprefix = None , wordsep = ' ' , remove_newlines = True ) : if not isinstance ( instr , six . string_types ) : instr = repr ( instr ) if nlprefix is not None : newline_prefix = nlprefix str_ = pack_into ( instr , textwidth , breakchars , break_words , newline_prefix , wordsep , remove_newlines ) if indentation != '' : str_ = indent ( str_ , indentation ) return str_
alias for pack_into . has more up to date kwargs
147
14
9,442
def byte_str ( nBytes , unit = 'bytes' , precision = 2 ) : #return (nBytes * ureg.byte).to(unit.upper()) if unit . lower ( ) . startswith ( 'b' ) : nUnit = nBytes elif unit . lower ( ) . startswith ( 'k' ) : nUnit = nBytes / ( 2.0 ** 10 ) elif unit . lower ( ) . startswith ( 'm' ) : nUnit = nBytes / ( 2.0 ** 20 ) elif unit . lower ( ) . startswith ( 'g' ) : nUnit = nBytes / ( 2.0 ** 30 ) elif unit . lower ( ) . startswith ( 't' ) : nUnit = nBytes / ( 2.0 ** 40 ) else : raise NotImplementedError ( 'unknown nBytes=%r unit=%r' % ( nBytes , unit ) ) return repr2 ( nUnit , precision = precision ) + ' ' + unit
representing the number of bytes with the chosen unit
222
10
9,443
def func_str ( func , args = [ ] , kwargs = { } , type_aliases = [ ] , packed = False , packkw = None , truncate = False ) : import utool as ut # if truncate: # truncatekw = {'maxlen': 20} # else: truncatekw = { } argrepr_list = ( [ ] if args is None else ut . get_itemstr_list ( args , nl = False , truncate = truncate , truncatekw = truncatekw ) ) kwrepr_list = ( [ ] if kwargs is None else ut . dict_itemstr_list ( kwargs , explicit = True , nl = False , truncate = truncate , truncatekw = truncatekw ) ) repr_list = argrepr_list + kwrepr_list argskwargs_str = ', ' . join ( repr_list ) _str = '%s(%s)' % ( meta_util_six . get_funcname ( func ) , argskwargs_str ) if packed : packkw_ = dict ( textwidth = 80 , nlprefix = ' ' , break_words = False ) if packkw is not None : packkw_ . update ( packkw_ ) _str = packstr ( _str , * * packkw_ ) return _str
string representation of function definition
299
5
9,444
def func_defsig ( func , with_name = True ) : import inspect argspec = inspect . getargspec ( func ) ( args , varargs , varkw , defaults ) = argspec defsig = inspect . formatargspec ( * argspec ) if with_name : defsig = get_callable_name ( func ) + defsig return defsig
String of function definition signature
84
5
9,445
def func_callsig ( func , with_name = True ) : import inspect argspec = inspect . getargspec ( func ) ( args , varargs , varkw , defaults ) = argspec callsig = inspect . formatargspec ( * argspec [ 0 : 3 ] ) if with_name : callsig = get_callable_name ( func ) + callsig return callsig
String of function call signature
85
5
9,446
def numpy_str ( arr , strvals = False , precision = None , pr = None , force_dtype = False , with_dtype = None , suppress_small = None , max_line_width = None , threshold = None , * * kwargs ) : # strvals = kwargs.get('strvals', False) itemsep = kwargs . get ( 'itemsep' , ' ' ) # precision = kwargs.get('precision', None) # suppress_small = kwargs.get('supress_small', None) # max_line_width = kwargs.get('max_line_width', None) # with_dtype = kwargs.get('with_dtype', False) newlines = kwargs . pop ( 'nl' , kwargs . pop ( 'newlines' , 1 ) ) data = arr # if with_dtype and strvals: # raise ValueError('cannot format with strvals and dtype') separator = ',' + itemsep if strvals : prefix = '' suffix = '' else : modname = type ( data ) . __module__ # substitute shorthand for numpy module names np_nice = 'np' modname = re . sub ( '\\bnumpy\\b' , np_nice , modname ) modname = re . sub ( '\\bma.core\\b' , 'ma' , modname ) class_name = type ( data ) . __name__ if class_name == 'ndarray' : class_name = 'array' prefix = modname + '.' + class_name + '(' if with_dtype : dtype_repr = data . dtype . name # dtype_repr = np.core.arrayprint.dtype_short_repr(data.dtype) suffix = ',{}dtype={}.{})' . format ( itemsep , np_nice , dtype_repr ) else : suffix = ')' if not strvals and data . size == 0 and data . shape != ( 0 , ) : # Special case for displaying empty data prefix = modname + '.empty(' body = repr ( tuple ( map ( int , data . shape ) ) ) else : body = np . array2string ( data , precision = precision , separator = separator , suppress_small = suppress_small , prefix = prefix , max_line_width = max_line_width ) if not newlines : # remove newlines if we need to body = re . sub ( '\n *' , '' , body ) formatted = prefix + body + suffix return formatted
suppress_small = False turns off scientific representation
572
10
9,447
def list_str_summarized ( list_ , list_name , maxlen = 5 ) : if len ( list_ ) > maxlen : return 'len(%s)=%d' % ( list_name , len ( list_ ) ) else : return '%s=%r' % ( list_name , list_ )
prints the list members when the list is small and the length when it is large
73
16
9,448
def _rectify_countdown_or_bool ( count_or_bool ) : if count_or_bool is True or count_or_bool is False : count_or_bool_ = count_or_bool elif isinstance ( count_or_bool , int ) : if count_or_bool == 0 : return 0 sign_ = math . copysign ( 1 , count_or_bool ) count_or_bool_ = int ( count_or_bool - sign_ ) #if count_or_bool_ == 0: # return sign_ == 1 else : count_or_bool_ = False return count_or_bool_
used by recrusive functions to specify which level to turn a bool on in counting down yeilds True True ... False conting up yeilds False False False ... True
142
35
9,449
def repr2 ( obj_ , * * kwargs ) : kwargs [ 'nl' ] = kwargs . pop ( 'nl' , kwargs . pop ( 'newlines' , False ) ) val_str = _make_valstr ( * * kwargs ) return val_str ( obj_ )
Attempt to replace repr more configurable pretty version that works the same in both 2 and 3
71
18
9,450
def repr2_json ( obj_ , * * kwargs ) : import utool as ut kwargs [ 'trailing_sep' ] = False json_str = ut . repr2 ( obj_ , * * kwargs ) json_str = str ( json_str . replace ( '\'' , '"' ) ) json_str = json_str . replace ( '(' , '[' ) json_str = json_str . replace ( ')' , ']' ) json_str = json_str . replace ( 'None' , 'null' ) return json_str
hack for json reprs
127
5
9,451
def list_str ( list_ , * * listkw ) : import utool as ut newlines = listkw . pop ( 'nl' , listkw . pop ( 'newlines' , 1 ) ) packed = listkw . pop ( 'packed' , False ) truncate = listkw . pop ( 'truncate' , False ) listkw [ 'nl' ] = _rectify_countdown_or_bool ( newlines ) listkw [ 'truncate' ] = _rectify_countdown_or_bool ( truncate ) listkw [ 'packed' ] = _rectify_countdown_or_bool ( packed ) nobraces = listkw . pop ( 'nobr' , listkw . pop ( 'nobraces' , False ) ) itemsep = listkw . get ( 'itemsep' , ' ' ) # Doesn't actually put in trailing comma if on same line trailing_sep = listkw . get ( 'trailing_sep' , True ) with_comma = True itemstr_list = get_itemstr_list ( list_ , * * listkw ) is_tuple = isinstance ( list_ , tuple ) is_set = isinstance ( list_ , ( set , frozenset , ut . oset ) ) is_onetup = isinstance ( list_ , ( tuple ) ) and len ( list_ ) <= 1 if nobraces : lbr , rbr = '' , '' elif is_tuple : lbr , rbr = '(' , ')' elif is_set : lbr , rbr = '{' , '}' else : lbr , rbr = '[' , ']' if len ( itemstr_list ) == 0 : newlines = False if newlines is not False and ( newlines is True or newlines > 0 ) : sep = ',\n' if with_comma else '\n' if nobraces : body_str = sep . join ( itemstr_list ) if trailing_sep : body_str += ',' retstr = body_str else : if packed : # DEPRICATE? joinstr = sep + itemsep * len ( lbr ) body_str = joinstr . join ( [ itemstr for itemstr in itemstr_list ] ) if trailing_sep : body_str += ',' braced_body_str = ( lbr + '' + body_str + '' + rbr ) else : body_str = sep . join ( [ ut . indent ( itemstr ) for itemstr in itemstr_list ] ) if trailing_sep : body_str += ',' braced_body_str = ( lbr + '\n' + body_str + '\n' + rbr ) retstr = braced_body_str else : sep = ',' + itemsep if with_comma else itemsep body_str = sep . join ( itemstr_list ) if is_onetup : body_str += ',' retstr = ( lbr + body_str + rbr ) # TODO: rectify with dict_truncate do_truncate = truncate is not False and ( truncate is True or truncate == 0 ) if do_truncate : truncatekw = listkw . get ( 'truncatekw' , { } ) retstr = truncate_str ( retstr , * * truncatekw ) return retstr
r Makes a pretty list string
750
6
9,452
def horiz_string ( * args , * * kwargs ) : import unicodedata precision = kwargs . get ( 'precision' , None ) sep = kwargs . get ( 'sep' , '' ) if len ( args ) == 1 and not isinstance ( args [ 0 ] , six . string_types ) : val_list = args [ 0 ] else : val_list = args val_list = [ unicodedata . normalize ( 'NFC' , ensure_unicode ( val ) ) for val in val_list ] all_lines = [ ] hpos = 0 # for each value in the list or args for sx in range ( len ( val_list ) ) : # Ensure value is a string val = val_list [ sx ] str_ = None if precision is not None : # Hack in numpy precision if util_type . HAVE_NUMPY : try : if isinstance ( val , np . ndarray ) : str_ = np . array_str ( val , precision = precision , suppress_small = True ) except ImportError : pass if str_ is None : str_ = six . text_type ( val_list [ sx ] ) # continue with formating lines = str_ . split ( '\n' ) line_diff = len ( lines ) - len ( all_lines ) # Vertical padding if line_diff > 0 : all_lines += [ ' ' * hpos ] * line_diff # Add strings for lx , line in enumerate ( lines ) : all_lines [ lx ] += line hpos = max ( hpos , len ( all_lines [ lx ] ) ) # Horizontal padding for lx in range ( len ( all_lines ) ) : hpos_diff = hpos - len ( all_lines [ lx ] ) all_lines [ lx ] += ' ' * hpos_diff + sep all_lines = [ line . rstrip ( ' ' ) for line in all_lines ] ret = '\n' . join ( all_lines ) return ret
Horizontally concatenates strings reprs preserving indentation
448
12
9,453
def str_between ( str_ , startstr , endstr ) : if startstr is None : startpos = 0 else : startpos = str_ . find ( startstr ) + len ( startstr ) if endstr is None : endpos = None else : endpos = str_ . find ( endstr ) if endpos == - 1 : endpos = None newstr = str_ [ startpos : endpos ] return newstr
r gets substring between two sentianl strings
93
10
9,454
def get_callable_name ( func ) : try : return meta_util_six . get_funcname ( func ) except AttributeError : if isinstance ( func , type ) : return repr ( func ) . replace ( '<type \'' , '' ) . replace ( '\'>' , '' ) elif hasattr ( func , '__name__' ) : return func . __name__ else : raise NotImplementedError ( ( 'cannot get func_name of func=%r' 'type(func)=%r' ) % ( func , type ( func ) ) )
Works on must functionlike objects including str which has no func_name
129
14
9,455
def multi_replace ( str_ , search_list , repl_list ) : if isinstance ( repl_list , six . string_types ) : repl_list_ = [ repl_list ] * len ( search_list ) else : repl_list_ = repl_list newstr = str_ assert len ( search_list ) == len ( repl_list_ ) , 'bad lens' for search , repl in zip ( search_list , repl_list_ ) : newstr = newstr . replace ( search , repl ) return newstr
r Performs multiple replace functions foreach item in search_list and repl_list .
116
18
9,456
def pluralize ( wordtext , num = 2 , plural_suffix = 's' ) : if num == 1 : return wordtext else : if wordtext . endswith ( '\'s' ) : return wordtext [ : - 2 ] + 's\'' else : return wordtext + plural_suffix return ( wordtext + plural_suffix ) if num != 1 else wordtext
r Heuristically changes a word to its plural form if num is not 1
85
16
9,457
def quantstr ( typestr , num , plural_suffix = 's' ) : return six . text_type ( num ) + ' ' + pluralize ( typestr , num , plural_suffix )
r Heuristically generates an english phrase relating to the quantity of something . This is useful for writing user messages .
47
23
9,458
def msgblock ( key , text , side = '|' ) : blocked_text = '' . join ( [ ' + --- ' , key , ' ---\n' ] + [ ' ' + side + ' ' + line + '\n' for line in text . split ( '\n' ) ] + [ ' L ___ ' , key , ' ___\n' ] ) return blocked_text
puts text inside a visual ascii block
86
10
9,459
def get_textdiff ( text1 , text2 , num_context_lines = 0 , ignore_whitespace = False ) : import difflib text1 = ensure_unicode ( text1 ) text2 = ensure_unicode ( text2 ) text1_lines = text1 . splitlines ( ) text2_lines = text2 . splitlines ( ) if ignore_whitespace : text1_lines = [ t . rstrip ( ) for t in text1_lines ] text2_lines = [ t . rstrip ( ) for t in text2_lines ] ndiff_kw = dict ( linejunk = difflib . IS_LINE_JUNK , charjunk = difflib . IS_CHARACTER_JUNK ) else : ndiff_kw = { } all_diff_lines = list ( difflib . ndiff ( text1_lines , text2_lines , * * ndiff_kw ) ) if num_context_lines is None : diff_lines = all_diff_lines else : from utool import util_list # boolean for every line if it is marked or not ismarked_list = [ len ( line ) > 0 and line [ 0 ] in '+-?' for line in all_diff_lines ] # flag lines that are within num_context_lines away from a diff line isvalid_list = ismarked_list [ : ] for i in range ( 1 , num_context_lines + 1 ) : isvalid_list [ : - i ] = util_list . or_lists ( isvalid_list [ : - i ] , ismarked_list [ i : ] ) isvalid_list [ i : ] = util_list . or_lists ( isvalid_list [ i : ] , ismarked_list [ : - i ] ) USE_BREAK_LINE = True if USE_BREAK_LINE : # insert a visual break when there is a break in context diff_lines = [ ] prev = False visual_break = '\n <... FILTERED CONTEXT ...> \n' #print(isvalid_list) for line , valid in zip ( all_diff_lines , isvalid_list ) : if valid : diff_lines . append ( line ) elif prev : if False : diff_lines . append ( visual_break ) prev = valid else : diff_lines = util_list . compress ( all_diff_lines , isvalid_list ) return '\n' . join ( diff_lines )
r Uses difflib to return a difference string between two similar texts
540
13
9,460
def conj_phrase ( list_ , cond = 'or' ) : if len ( list_ ) == 0 : return '' elif len ( list_ ) == 1 : return list_ [ 0 ] elif len ( list_ ) == 2 : return ' ' . join ( ( list_ [ 0 ] , cond , list_ [ 1 ] ) ) else : condstr = '' . join ( ( ', ' + cond , ' ' ) ) return ', ' . join ( ( ', ' . join ( list_ [ : - 2 ] ) , condstr . join ( list_ [ - 2 : ] ) ) )
Joins a list of words using English conjunction rules
129
10
9,461
def bubbletext ( text , font = 'cybermedium' ) : import utool as ut pyfiglet = ut . tryimport ( 'pyfiglet' , 'git+https://github.com/pwaller/pyfiglet' ) if pyfiglet is None : return text else : bubble_text = pyfiglet . figlet_format ( text , font = font ) return bubble_text
r Uses pyfiglet to create bubble text .
87
10
9,462
def is_url ( str_ ) : return any ( [ str_ . startswith ( 'http://' ) , str_ . startswith ( 'https://' ) , str_ . startswith ( 'www.' ) , '.org/' in str_ , '.com/' in str_ , ] )
heuristic check if str is url formatted
69
8
9,463
def chr_range ( * args , * * kw ) : if len ( args ) == 1 : stop , = args start , step = 0 , 1 elif len ( args ) == 2 : start , stop = args step = 1 elif len ( args ) == 3 : start , stop , step = args else : raise ValueError ( 'incorrect args' ) chr_ = six . unichr base = ord ( kw . get ( 'base' , 'a' ) ) if isinstance ( start , int ) : start = base + start if isinstance ( stop , int ) : stop = base + stop if isinstance ( start , six . string_types ) : start = ord ( start ) if isinstance ( stop , six . string_types ) : stop = ord ( stop ) if step is None : step = 1 list_ = list ( map ( six . text_type , map ( chr_ , range ( start , stop , step ) ) ) ) return list_
r Like range but returns characters
213
6
9,464
def highlight_regex ( str_ , pat , reflags = 0 , color = 'red' ) : #import colorama # from colorama import Fore, Style #color = Fore.MAGENTA # color = Fore.RED #match = re.search(pat, str_, flags=reflags) matches = list ( re . finditer ( pat , str_ , flags = reflags ) ) colored = str_ for match in reversed ( matches ) : #pass #if match is None: # return str_ #else: start = match . start ( ) end = match . end ( ) #colorama.init() colored_part = color_text ( colored [ start : end ] , color ) colored = colored [ : start ] + colored_part + colored [ end : ] # colored = (colored[:start] + color + colored[start:end] + # Style.RESET_ALL + colored[end:]) #colorama.deinit() return colored
FIXME Use pygments instead
210
6
9,465
def highlight_multi_regex ( str_ , pat_to_color , reflags = 0 ) : #import colorama # from colorama import Fore, Style #color = Fore.MAGENTA # color = Fore.RED #match = re.search(pat, str_, flags=reflags) colored = str_ to_replace = [ ] for pat , color in pat_to_color . items ( ) : matches = list ( re . finditer ( pat , str_ , flags = reflags ) ) for match in matches : start = match . start ( ) end = match . end ( ) to_replace . append ( ( end , start , color ) ) for tup in reversed ( sorted ( to_replace ) ) : end , start , color = tup colored_part = color_text ( colored [ start : end ] , color ) colored = colored [ : start ] + colored_part + colored [ end : ] return colored
FIXME Use pygments instead . must be mututally exclusive
204
13
9,466
def find_block_end ( row , line_list , sentinal , direction = 1 ) : import re row_ = row line_ = line_list [ row_ ] flag1 = row_ == 0 or row_ == len ( line_list ) - 1 flag2 = re . match ( sentinal , line_ ) if not ( flag1 or flag2 ) : while True : if ( row_ == 0 or row_ == len ( line_list ) - 1 ) : break line_ = line_list [ row_ ] if re . match ( sentinal , line_ ) : break row_ += direction return row_
Searches up and down until it finds the endpoints of a block Rectify with find_paragraph_end in pyvim_funcs
133
29
9,467
def compress_pdf ( pdf_fpath , output_fname = None ) : import utool as ut ut . assertpath ( pdf_fpath ) suffix = '_' + ut . get_datestamp ( False ) + '_compressed' print ( 'pdf_fpath = %r' % ( pdf_fpath , ) ) output_pdf_fpath = ut . augpath ( pdf_fpath , suffix , newfname = output_fname ) print ( 'output_pdf_fpath = %r' % ( output_pdf_fpath , ) ) gs_exe = find_ghostscript_exe ( ) cmd_list = ( gs_exe , '-sDEVICE=pdfwrite' , '-dCompatibilityLevel=1.4' , '-dNOPAUSE' , '-dQUIET' , '-dBATCH' , '-sOutputFile=' + output_pdf_fpath , pdf_fpath ) ut . cmd ( * cmd_list ) return output_pdf_fpath
uses ghostscript to write a pdf
227
7
9,468
def make_full_document ( text , title = None , preamp_decl = { } , preamb_extra = None ) : import utool as ut doc_preamb = ut . codeblock ( ''' %\\documentclass{article} \\documentclass[10pt,twocolumn,letterpaper]{article} % \\usepackage[utf8]{inputenc} \\usepackage[T1]{fontenc} \\usepackage{times} \\usepackage{epsfig} \\usepackage{graphicx} \\usepackage{amsmath,amsthm,amssymb} \\usepackage[usenames,dvipsnames,svgnames,table]{xcolor} \\usepackage{multirow} \\usepackage{subcaption} \\usepackage{booktabs} %\\pagenumbering{gobble} ''' ) if preamb_extra is not None : if isinstance ( preamb_extra , ( list , tuple ) ) : preamb_extra = '\n' . join ( preamb_extra ) doc_preamb += '\n' + preamb_extra + '\n' if title is not None : preamp_decl [ 'title' ] = title decl_lines = [ r'\{key}{{{val}}}' . format ( key = key , val = val ) for key , val in preamp_decl . items ( ) ] doc_decllines = '\n' . join ( decl_lines ) doc_header = ut . codeblock ( r''' \begin{document} ''' ) if preamp_decl . get ( 'title' ) is not None : doc_header += r'\maketitle' doc_footer = ut . codeblock ( r''' \end{document} ''' ) text_ = '\n' . join ( ( doc_preamb , doc_decllines , doc_header , text , doc_footer ) ) return text_
r dummy preamble and document to wrap around latex fragment
433
12
9,469
def render_latex_text ( input_text , nest_in_doc = False , preamb_extra = None , appname = 'utool' , verbose = None ) : import utool as ut if verbose is None : verbose = ut . VERBOSE dpath = ut . ensure_app_resource_dir ( appname , 'latex_tmp' ) # put a latex framgent in a full document # print(input_text) fname = 'temp_render_latex' pdf_fpath = ut . compile_latex_text ( input_text , dpath = dpath , fname = fname , preamb_extra = preamb_extra , verbose = verbose ) ut . startfile ( pdf_fpath ) return pdf_fpath
compiles latex and shows the result
172
7
9,470
def render_latex ( input_text , dpath = None , fname = None , preamb_extra = None , verbose = 1 , * * kwargs ) : import utool as ut import vtool as vt # turn off page numbers input_text_ = '\pagenumbering{gobble}\n' + input_text # fname, _ = splitext(fname) img_fname = ut . ensure_ext ( fname , [ '.jpg' ] + list ( ut . IMG_EXTENSIONS ) ) img_fpath = join ( dpath , img_fname ) pdf_fpath = ut . compile_latex_text ( input_text_ , fname = fname , dpath = dpath , preamb_extra = preamb_extra , verbose = verbose , move = False ) ext = splitext ( img_fname ) [ 1 ] fpath_in = ut . convert_pdf_to_image ( pdf_fpath , ext = ext , verbose = verbose ) # Clip of boundaries of the pdf imag vt . clipwhite_ondisk ( fpath_in , fpath_out = img_fpath , verbose = verbose > 1 ) return img_fpath
Renders latex text into a jpeg .
276
9
9,471
def get_latex_figure_str2 ( fpath_list , cmdname , * * kwargs ) : import utool as ut from os . path import relpath # Make relative paths if kwargs . pop ( 'relpath' , True ) : start = ut . truepath ( '~/latex/crall-candidacy-2015' ) fpath_list = [ relpath ( fpath , start ) for fpath in fpath_list ] cmdname = ut . latex_sanitize_command_name ( cmdname ) kwargs [ 'caption_str' ] = kwargs . get ( 'caption_str' , cmdname ) figure_str = ut . get_latex_figure_str ( fpath_list , * * kwargs ) latex_block = ut . latex_newcommand ( cmdname , figure_str ) return latex_block
hack for candidacy
197
3
9,472
def add ( self , data , value = None , timestamp = None , namespace = None , debug = False ) : if value is not None : return self . add ( ( ( data , value ) , ) , timestamp = timestamp , namespace = namespace , debug = debug ) writer = self . writer if writer is None : raise GaugedUseAfterFreeError if timestamp is None : timestamp = long ( time ( ) * 1000 ) config = self . config block_size = config . block_size this_block = timestamp // block_size this_array = ( timestamp % block_size ) // config . resolution if namespace is None : namespace = config . namespace if this_block < self . current_block or ( this_block == self . current_block and this_array < self . current_array ) : if config . append_only_violation == Writer . ERROR : msg = 'Gauged is append-only; timestamps must be increasing' raise GaugedAppendOnlyError ( msg ) elif config . append_only_violation == Writer . REWRITE : this_block = self . current_block this_array = self . current_array else : return if isinstance ( data , unicode ) : data = data . encode ( 'utf8' ) if debug : return self . debug ( timestamp , namespace , data ) if this_block > self . current_block : self . flush_blocks ( ) self . current_block = this_block self . current_array = this_array elif this_array > self . current_array : if not Gauged . writer_flush_arrays ( writer , self . current_array ) : raise MemoryError self . current_array = this_array data_points = 0 namespace_statistics = self . statistics [ namespace ] whitelist = config . key_whitelist skip_long_keys = config . key_overflow == Writer . IGNORE skip_gauge_nan = config . gauge_nan == Writer . IGNORE if isinstance ( data , str ) and skip_gauge_nan and skip_long_keys and whitelist is None : # fast path data_points = c_uint32 ( 0 ) if not Gauged . writer_emit_pairs ( writer , namespace , data , byref ( data_points ) ) : raise MemoryError data_points = data_points . value else : if isinstance ( data , dict ) : data = data . iteritems ( ) elif isinstance ( data , str ) : data = self . parse_query ( data ) emit = Gauged . writer_emit for key , value in data : key = to_bytes ( key ) if whitelist is not None and key not in whitelist : continue try : value = float ( value ) except ValueError : value = float ( 'nan' ) if value != value : # => NaN? if skip_gauge_nan : continue raise GaugedNaNError success = emit ( writer , namespace , key , c_float ( value ) ) if success != 1 : if not success : raise MemoryError elif success == Writer . KEY_OVERFLOW and not skip_long_keys : msg = 'Key is larger than the driver allows ' msg += '(%s)' % key raise GaugedKeyOverflowError ( msg ) data_points += 1 namespace_statistics . data_points += data_points if self . flush_now : self . flush ( )
Queue a gauge or gauges to be written
737
9
9,473
def flush ( self ) : writer = self . writer if writer is None : raise GaugedUseAfterFreeError self . flush_writer_position ( ) keys = self . translate_keys ( ) blocks = [ ] current_block = self . current_block statistics = self . statistics driver = self . driver flags = 0 # for future extensions, e.g. block compression for namespace , key , block in self . pending_blocks ( ) : length = block . byte_length ( ) if not length : continue key_id = keys [ ( namespace , key ) ] statistics [ namespace ] . byte_count += length blocks . append ( ( namespace , current_block , key_id , block . buffer ( ) , flags ) ) if self . config . overwrite_blocks : driver . replace_blocks ( blocks ) else : driver . insert_or_append_blocks ( blocks ) if not Gauged . writer_flush_maps ( writer , True ) : raise MemoryError update_namespace = driver . add_namespace_statistics for namespace , stats in statistics . iteritems ( ) : update_namespace ( namespace , self . current_block , stats . data_points , stats . byte_count ) statistics . clear ( ) driver . commit ( ) self . flush_now = False
Flush all pending gauges
271
6
9,474
def resume_from ( self ) : position = self . driver . get_writer_position ( self . config . writer_name ) return position + self . config . resolution if position else 0
Get a timestamp representing the position just after the last written gauge
40
12
9,475
def clear_from ( self , timestamp ) : block_size = self . config . block_size offset , remainder = timestamp // block_size , timestamp % block_size if remainder : raise ValueError ( 'Timestamp must be on a block boundary' ) self . driver . clear_from ( offset , timestamp )
Clear all data from timestamp onwards . Note that the timestamp is rounded down to the nearest block boundary
66
19
9,476
def clear_key_before ( self , key , namespace = None , timestamp = None ) : block_size = self . config . block_size if namespace is None : namespace = self . config . namespace if timestamp is not None : offset , remainder = divmod ( timestamp , block_size ) if remainder : raise ValueError ( 'timestamp must be on a block boundary' ) if offset == 0 : raise ValueError ( 'cannot delete before offset zero' ) offset -= 1 self . driver . clear_key_before ( key , namespace , offset , timestamp ) else : self . driver . clear_key_before ( key , namespace )
Clear all data before timestamp for a given key . Note that the timestamp is rounded down to the nearest block boundary
135
22
9,477
def _to_ctfile_counts_line ( self , key ) : counter = OrderedCounter ( self . counts_line_format ) self [ key ] [ 'number_of_atoms' ] = str ( len ( self . atoms ) ) self [ key ] [ 'number_of_bonds' ] = str ( len ( self . bonds ) ) counts_line = '' . join ( [ str ( value ) . rjust ( spacing ) for value , spacing in zip ( self [ key ] . values ( ) , counter . values ( ) ) ] ) return '{}\n' . format ( counts_line )
Create counts line in CTfile format .
135
8
9,478
def _to_ctfile_atom_block ( self , key ) : counter = OrderedCounter ( Atom . atom_block_format ) ctab_atom_block = '\n' . join ( [ '' . join ( [ str ( value ) . rjust ( spacing ) for value , spacing in zip ( atom . _ctab_data . values ( ) , counter . values ( ) ) ] ) for atom in self [ key ] ] ) return '{}\n' . format ( ctab_atom_block )
Create atom block in CTfile format .
112
8
9,479
def _to_ctfile_bond_block ( self , key ) : counter = OrderedCounter ( Bond . bond_block_format ) ctab_bond_block = '\n' . join ( [ '' . join ( [ str ( value ) . rjust ( spacing ) for value , spacing in zip ( bond . _ctab_data . values ( ) , counter . values ( ) ) ] ) for bond in self [ key ] ] ) return '{}\n' . format ( ctab_bond_block )
Create bond block in CTfile format .
115
8
9,480
def _to_ctfile_property_block ( self ) : ctab_properties_data = defaultdict ( list ) for atom in self . atoms : for ctab_property_key , ctab_property_value in atom . _ctab_property_data . items ( ) : ctab_properties_data [ ctab_property_key ] . append ( OrderedDict ( zip ( self . ctab_conf [ self . version ] [ ctab_property_key ] [ 'values' ] , [ atom . atom_number , ctab_property_value ] ) ) ) ctab_property_lines = [ ] for ctab_property_key , ctab_property_value in ctab_properties_data . items ( ) : for entry in ctab_property_value : ctab_property_line = '{} {}{}' . format ( self . ctab_conf [ self . version ] [ ctab_property_key ] [ 'fmt' ] , 1 , '' . join ( [ str ( value ) . rjust ( 4 ) for value in entry . values ( ) ] ) ) ctab_property_lines . append ( ctab_property_line ) if ctab_property_lines : return '{}\n' . format ( '\n' . join ( ctab_property_lines ) ) return ''
Create ctab properties block in CTfile format from atom - specific properties .
294
15
9,481
def delete_atom ( self , * atom_numbers ) : for atom_number in atom_numbers : deletion_atom = self . atom_by_number ( atom_number = atom_number ) # update atom numbers for atom in self . atoms : if int ( atom . atom_number ) > int ( atom_number ) : atom . atom_number = str ( int ( atom . atom_number ) - 1 ) # find index of a bond to remove and update ctab data dict with new atom numbers for index , bond in enumerate ( self . bonds ) : bond . update_atom_numbers ( ) if atom_number in { bond . first_atom_number , bond . second_atom_number } : self . bonds . remove ( bond ) # remove atom from neighbors list for atom in self . atoms : if deletion_atom in atom . neighbors : atom . neighbors . remove ( deletion_atom ) self . atoms . remove ( deletion_atom )
Delete atoms by atom number .
205
6
9,482
def from_molfile ( cls , molfile , data = None ) : if not data : data = OrderedDict ( ) if not isinstance ( molfile , Molfile ) : raise ValueError ( 'Not a Molfile type: "{}"' . format ( type ( molfile ) ) ) if not isinstance ( data , dict ) : raise ValueError ( 'Not a dict type: "{}"' . format ( type ( data ) ) ) sdfile = cls ( ) sdfile [ '1' ] = OrderedDict ( ) sdfile [ '1' ] [ 'molfile' ] = molfile sdfile [ '1' ] [ 'data' ] = data return sdfile
Construct new SDfile object from Molfile object .
164
11
9,483
def add_data ( self , id , key , value ) : self [ str ( id ) ] [ 'data' ] . setdefault ( key , [ ] ) self [ str ( id ) ] [ 'data' ] [ key ] . append ( value )
Add new data item .
55
5
9,484
def add_molfile ( self , molfile , data ) : if not isinstance ( molfile , Molfile ) : raise ValueError ( 'Not a Molfile type: "{}"' . format ( type ( molfile ) ) ) if not isinstance ( data , dict ) : raise ValueError ( 'Not a dict type: "{}"' . format ( type ( data ) ) ) entry_ids = sorted ( self . keys ( ) , key = lambda x : int ( x ) ) if entry_ids : last_entry_id = str ( entry_ids [ - 1 ] ) else : last_entry_id = '0' new_entry_id = str ( int ( last_entry_id ) + 1 ) self [ new_entry_id ] = OrderedDict ( ) self [ new_entry_id ] [ 'molfile' ] = molfile self [ new_entry_id ] [ 'data' ] = data
Add Molfile and data to SDfile object .
210
11
9,485
def add_sdfile ( self , sdfile ) : if not isinstance ( sdfile , SDfile ) : raise ValueError ( 'Not a SDfile type: "{}"' . format ( type ( sdfile ) ) ) for entry_id in sdfile : self . add_molfile ( molfile = sdfile [ entry_id ] [ 'molfile' ] , data = sdfile [ entry_id ] [ 'data' ] )
Add new SDfile to current SDfile .
105
9
9,486
def neighbor_atoms ( self , atom_symbol = None ) : if not atom_symbol : return self . neighbors else : return [ atom for atom in self . neighbors if atom [ 'atom_symbol' ] == atom_symbol ]
Access neighbor atoms .
54
4
9,487
def update_atom_numbers ( self ) : self . _ctab_data [ 'first_atom_number' ] = self . first_atom . atom_number self . _ctab_data [ 'second_atom_number' ] = self . second_atom . atom_number
Update links first_atom_number - > second_atom_number
63
14
9,488
def default ( self , o ) : if isinstance ( o , Atom ) or isinstance ( o , Bond ) : return o . _ctab_data else : return o . __dict__
Default encoder .
41
4
9,489
def get ( self , server ) : server_config = self . config . get ( server ) try : while server_config is None : new_config = self . _read_next_config ( ) server_config = new_config . get ( server ) new_config . update ( self . config ) self . config = new_config except StopIteration : return _default_server_configuration ( server ) if CONFIG_URL_KEY_NAME not in server_config : message = "'%s' must be specified in configuration for '%s'" % ( CONFIG_URL_KEY_NAME , server ) raise ServerConfigMissingUrlError ( message ) return ServerConfig ( server_config )
Returns ServerConfig instance with configuration given server .
147
9
9,490
def free ( self ) : if self . _ptr is None : return Gauged . array_free ( self . ptr ) FloatArray . ALLOCATIONS -= 1 self . _ptr = None
Free the underlying C array
40
5
9,491
def generate_psms_quanted ( quantdb , tsvfn , isob_header , oldheader , isobaric = False , precursor = False ) : allquants , sqlfields = quantdb . select_all_psm_quants ( isobaric , precursor ) quant = next ( allquants ) for rownr , psm in enumerate ( readers . generate_tsv_psms ( tsvfn , oldheader ) ) : outpsm = { x : y for x , y in psm . items ( ) } if precursor : pquant = quant [ sqlfields [ 'precursor' ] ] if pquant is None : pquant = 'NA' outpsm . update ( { mzidtsvdata . HEADER_PRECURSOR_QUANT : str ( pquant ) } ) if isobaric : isoquants = { } while quant [ 0 ] == rownr : isoquants . update ( { quant [ sqlfields [ 'isochan' ] ] : str ( quant [ sqlfields [ 'isoquant' ] ] ) } ) try : quant = next ( allquants ) except StopIteration : # last PSM, break from while loop or it is not yielded at all break outpsm . update ( get_quant_NAs ( isoquants , isob_header ) ) else : try : quant = next ( allquants ) except StopIteration : # last PSM, needs explicit yield/break or it will not be yielded yield outpsm break yield outpsm
Takes dbfn and connects gets quants for each line in tsvfn sorts them in line by using keys in quantheader list .
344
29
9,492
def t_escaped_BACKSPACE_CHAR ( self , t ) : # 'b' t . lexer . pop_state ( ) t . value = unichr ( 0x0008 ) return t
r \ x62
46
4
9,493
def t_escaped_FORM_FEED_CHAR ( self , t ) : # 'f' t . lexer . pop_state ( ) t . value = unichr ( 0x000c ) return t
r \ x66
47
4
9,494
def t_escaped_CARRIAGE_RETURN_CHAR ( self , t ) : # 'r' t . lexer . pop_state ( ) t . value = unichr ( 0x000d ) return t
r \ x72
50
4
9,495
def t_escaped_LINE_FEED_CHAR ( self , t ) : # 'n' t . lexer . pop_state ( ) t . value = unichr ( 0x000a ) return t
r \ x6E
47
5
9,496
def t_escaped_TAB_CHAR ( self , t ) : # 't' t . lexer . pop_state ( ) t . value = unichr ( 0x0009 ) return t
r \ x74
45
4
9,497
def get_mzid_specfile_ids ( mzidfn , namespace ) : sid_fn = { } for specdata in mzid_specdata_generator ( mzidfn , namespace ) : sid_fn [ specdata . attrib [ 'id' ] ] = specdata . attrib [ 'name' ] return sid_fn
Returns mzid spectra data filenames and their IDs used in the mzIdentML file as a dict . Keys == IDs values == fns
78
32
9,498
def get_specidentitem_percolator_data ( item , xmlns ) : percomap = { '{0}userParam' . format ( xmlns ) : PERCO_HEADERMAP , } percodata = { } for child in item : try : percoscore = percomap [ child . tag ] [ child . attrib [ 'name' ] ] except KeyError : continue else : percodata [ percoscore ] = child . attrib [ 'value' ] outkeys = [ y for x in list ( percomap . values ( ) ) for y in list ( x . values ( ) ) ] for key in outkeys : try : percodata [ key ] except KeyError : percodata [ key ] = 'NA' return percodata
Loop through SpecIdentificationItem children . Find percolator data by matching to a dict lookup . Return a dict containing percolator data
169
28
9,499
def locate_path ( dname , recurse_down = True ) : tried_fpaths = [ ] root_dir = os . getcwd ( ) while root_dir is not None : dpath = join ( root_dir , dname ) if exists ( dpath ) : return dpath else : tried_fpaths . append ( dpath ) _new_root = dirname ( root_dir ) if _new_root == root_dir : root_dir = None break else : root_dir = _new_root if not recurse_down : break msg = 'Cannot locate dname=%r' % ( dname , ) msg = ( '\n[sysreq!] Checked: ' . join ( tried_fpaths ) ) print ( msg ) raise ImportError ( msg )
Search for a path
176
4