idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
9,500
def get_textdiff ( text1 , text2 , num_context_lines = 0 , ignore_whitespace = False ) : r 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...
r Uses difflib to return a difference string between two similar texts
9,501
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 ] ) , cond...
Joins a list of words using English conjunction rules
9,502
def bubbletext ( text , font = 'cybermedium' ) : r 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 .
9,503
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
9,504
def chr_range ( * args , ** kw ) : r 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...
r Like range but returns characters
9,505
def highlight_regex ( str_ , pat , reflags = 0 , color = 'red' ) : matches = list ( re . finditer ( pat , str_ , flags = reflags ) ) colored = str_ for match in reversed ( matches ) : start = match . start ( ) end = match . end ( ) colored_part = color_text ( colored [ start : end ] , color ) colored = colored [ : star...
FIXME Use pygments instead
9,506
def highlight_multi_regex ( str_ , pat_to_color , reflags = 0 ) : 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 , c...
FIXME Use pygments instead . must be mututally exclusive
9,507
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_l...
Searches up and down until it finds the endpoints of a block Rectify with find_paragraph_end in pyvim_funcs
9,508
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...
uses ghostscript to write a pdf
9,509
def make_full_document ( text , title = None , preamp_decl = { } , preamb_extra = None ) : r import utool as ut doc_preamb = ut . codeblock ( ) 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 ...
r dummy preamble and document to wrap around latex fragment
9,510
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' ) fname = 'temp_render_latex' pdf_fpath = ut . compile_latex_text ( input_te...
compiles latex and shows the result
9,511
def render_latex ( input_text , dpath = None , fname = None , preamb_extra = None , verbose = 1 , ** kwargs ) : import utool as ut import vtool as vt input_text_ = '\pagenumbering{gobble}\n' + input_text img_fname = ut . ensure_ext ( fname , [ '.jpg' ] + list ( ut . IMG_EXTENSIONS ) ) img_fpath = join ( dpath , img_fna...
Renders latex text into a jpeg .
9,512
def get_latex_figure_str2 ( fpath_list , cmdname , ** kwargs ) : import utool as ut from os . path import relpath 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 ...
hack for candidacy
9,513
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...
Queue a gauge or gauges to be written
9,514
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 namespace , key , block in self . pending_...
Flush all pending gauges
9,515
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
9,516
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
9,517
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 blo...
Clear all data before timestamp for a given key . Note that the timestamp is rounded down to the nearest block boundary
9,518
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 ...
Create counts line in CTfile format .
9,519
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 ...
Create atom block in CTfile format .
9,520
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 ...
Create bond block in CTfile format .
9,521
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_pro...
Create ctab properties block in CTfile format from atom - specific properties .
9,522
def delete_atom ( self , * atom_numbers ) : for atom_number in atom_numbers : deletion_atom = self . atom_by_number ( atom_number = atom_number ) for atom in self . atoms : if int ( atom . atom_number ) > int ( atom_number ) : atom . atom_number = str ( int ( atom . atom_number ) - 1 ) for index , bond in enumerate ( s...
Delete atoms by atom number .
9,523
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 ) ) ) sdfi...
Construct new SDfile object from Molfile object .
9,524
def add_data ( self , id , key , value ) : self [ str ( id ) ] [ 'data' ] . setdefault ( key , [ ] ) self [ str ( id ) ] [ 'data' ] [ key ] . append ( value )
Add new data item .
9,525
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 = lam...
Add Molfile and data to SDfile object .
9,526
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 .
9,527
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 .
9,528
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
9,529
def default ( self , o ) : if isinstance ( o , Atom ) or isinstance ( o , Bond ) : return o . _ctab_data else : return o . __dict__
Default encoder .
9,530
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_configuratio...
Returns ServerConfig instance with configuration given server .
9,531
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
9,532
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 :...
Takes dbfn and connects gets quants for each line in tsvfn sorts them in line by using keys in quantheader list .
9,533
def t_escaped_BACKSPACE_CHAR ( self , t ) : r'\x62' t . lexer . pop_state ( ) t . value = unichr ( 0x0008 ) return t
r \ x62
9,534
def t_escaped_FORM_FEED_CHAR ( self , t ) : r'\x66' t . lexer . pop_state ( ) t . value = unichr ( 0x000c ) return t
r \ x66
9,535
def t_escaped_CARRIAGE_RETURN_CHAR ( self , t ) : r'\x72' t . lexer . pop_state ( ) t . value = unichr ( 0x000d ) return t
r \ x72
9,536
def t_escaped_LINE_FEED_CHAR ( self , t ) : r'\x6E' t . lexer . pop_state ( ) t . value = unichr ( 0x000a ) return t
r \ x6E
9,537
def t_escaped_TAB_CHAR ( self , t ) : r'\x74' t . lexer . pop_state ( ) t . value = unichr ( 0x0009 ) return t
r \ x74
9,538
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
9,539
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...
Loop through SpecIdentificationItem children . Find percolator data by matching to a dict lookup . Return a dict containing percolator data
9,540
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 ...
Search for a path
9,541
def total_purge_developed_repo ( repodir ) : r assert repodir is not None import utool as ut import os repo = ut . util_git . Repo ( dpath = repodir ) user = os . environ [ 'USER' ] fmtdict = dict ( user = user , modname = repo . modname , reponame = repo . reponame , dpath = repo . dpath , global_site_pkgs = ut . get_...
r Outputs commands to help purge a repo
9,542
def add_dict ( self , dyn_dict ) : 'Adds a dictionary to the prefs' if not isinstance ( dyn_dict , dict ) : raise Exception ( 'DynStruct.add_dict expects a dictionary.' + 'Recieved: ' + six . text_type ( type ( dyn_dict ) ) ) for ( key , val ) in six . iteritems ( dyn_dict ) : self [ key ] = val
Adds a dictionary to the prefs
9,543
def to_dict ( self ) : dyn_dict = { } for ( key , val ) in six . iteritems ( self . __dict__ ) : if key not in self . _printable_exclude : dyn_dict [ key ] = val return dyn_dict
Converts dynstruct to a dictionary .
9,544
def execstr ( self , local_name ) : execstr = '' for ( key , val ) in six . iteritems ( self . __dict__ ) : if key not in self . _printable_exclude : execstr += key + ' = ' + local_name + '.' + key + '\n' return execstr
returns a string which when evaluated will add the stored variables to the current namespace
9,545
def get_proteins_for_peptide ( self , psm_id ) : protsql = self . get_sql_select ( [ 'protein_acc' ] , 'protein_psm' ) protsql = '{0} WHERE psm_id=?' . format ( protsql ) cursor = self . get_cursor ( ) proteins = cursor . execute ( protsql , psm_id ) . fetchall ( ) return [ x [ 0 ] for x in proteins ]
Returns list of proteins for a passed psm_id
9,546
def raise_if_error ( frame ) : if "status" not in frame or frame [ "status" ] == b"\x00" : return codes_and_exceptions = { b"\x01" : exceptions . ZigBeeUnknownError , b"\x02" : exceptions . ZigBeeInvalidCommand , b"\x03" : exceptions . ZigBeeInvalidParameter , b"\x04" : exceptions . ZigBeeTxFailure } if frame [ "status...
Checks a frame and raises the relevant exception if required .
9,547
def hex_to_int ( value ) : if version_info . major >= 3 : return int . from_bytes ( value , "big" ) return int ( value . encode ( "hex" ) , 16 )
Convert hex string like \ x0A \ xE3 to 2787 .
9,548
def adc_to_percentage ( value , max_volts , clamp = True ) : percentage = ( 100.0 / const . ADC_MAX_VAL ) * value return max ( min ( 100 , percentage ) , 0 ) if clamp else percentage
Convert the ADC raw value to a percentage .
9,549
def convert_adc ( value , output_type , max_volts ) : return { const . ADC_RAW : lambda x : x , const . ADC_PERCENTAGE : adc_to_percentage , const . ADC_VOLTS : adc_to_volts , const . ADC_MILLIVOLTS : adc_to_millivolts } [ output_type ] ( value , max_volts )
Converts the output from the ADC into the desired type .
9,550
def _frame_received ( self , frame ) : try : self . _rx_frames [ frame [ "frame_id" ] ] = frame except KeyError : pass _LOGGER . debug ( "Frame received: %s" , frame ) for handler in self . _rx_handlers : handler ( frame )
Put the frame into the _rx_frames dict with a key of the frame_id .
9,551
def _send ( self , ** kwargs ) : if kwargs . get ( "dest_addr_long" ) is not None : self . zb . remote_at ( ** kwargs ) else : self . zb . at ( ** kwargs )
Send a frame to either the local ZigBee or a remote device .
9,552
def _send_and_wait ( self , ** kwargs ) : frame_id = self . next_frame_id kwargs . update ( dict ( frame_id = frame_id ) ) self . _send ( ** kwargs ) timeout = datetime . now ( ) + const . RX_TIMEOUT while datetime . now ( ) < timeout : try : frame = self . _rx_frames . pop ( frame_id ) raise_if_error ( frame ) return ...
Send a frame to either the local ZigBee or a remote device and wait for a pre - defined amount of time for its response .
9,553
def _get_parameter ( self , parameter , dest_addr_long = None ) : frame = self . _send_and_wait ( command = parameter , dest_addr_long = dest_addr_long ) return frame [ "parameter" ]
Fetches and returns the value of the specified parameter .
9,554
def get_sample ( self , dest_addr_long = None ) : frame = self . _send_and_wait ( command = b"IS" , dest_addr_long = dest_addr_long ) if "parameter" in frame : return frame [ "parameter" ] [ 0 ] return { }
Initiate a sample and return its data .
9,555
def read_digital_pin ( self , pin_number , dest_addr_long = None ) : sample = self . get_sample ( dest_addr_long = dest_addr_long ) try : return sample [ const . DIGITAL_PINS [ pin_number ] ] except KeyError : raise exceptions . ZigBeePinNotConfigured ( "Pin %s (%s) is not configured as a digital input or output." % ( ...
Fetches a sample and returns the boolean value of the requested digital pin .
9,556
def set_gpio_pin ( self , pin_number , setting , dest_addr_long = None ) : assert setting in const . GPIO_SETTINGS . values ( ) self . _send_and_wait ( command = const . IO_PIN_COMMANDS [ pin_number ] , parameter = setting . value , dest_addr_long = dest_addr_long )
Set a gpio pin setting .
9,557
def get_gpio_pin ( self , pin_number , dest_addr_long = None ) : frame = self . _send_and_wait ( command = const . IO_PIN_COMMANDS [ pin_number ] , dest_addr_long = dest_addr_long ) value = frame [ "parameter" ] return const . GPIO_SETTINGS [ value ]
Get a gpio pin setting .
9,558
def get_supply_voltage ( self , dest_addr_long = None ) : value = self . _get_parameter ( b"%V" , dest_addr_long = dest_addr_long ) return ( hex_to_int ( value ) * ( 1200 / 1024.0 ) ) / 1000
Fetches the value of %V and returns it as volts .
9,559
def add ( self , key ) : if key not in self . _map : self . _map [ key ] = link = _Link ( ) root = self . _root last = root . prev link . prev , link . next , link . key = last , root , key last . next = root . prev = weakref . proxy ( link )
Store new key in a new link at the end of the linked list
9,560
def index ( self , item ) : for count , other in enumerate ( self ) : if item == other : return count raise ValueError ( '%r is not in OrderedSet' % ( item , ) )
Find the index of item in the OrderedSet
9,561
def value ( self , key , timestamp = None , namespace = None ) : return self . make_context ( key = key , end = timestamp , namespace = namespace ) . value ( )
Get the value of a gauge at the specified time
9,562
def aggregate ( self , key , aggregate , start = None , end = None , namespace = None , percentile = None ) : return self . make_context ( key = key , aggregate = aggregate , start = start , end = end , namespace = namespace , percentile = percentile ) . aggregate ( )
Get an aggregate of all gauge data stored in the specified date range
9,563
def value_series ( self , key , start = None , end = None , interval = None , namespace = None , cache = None ) : return self . make_context ( key = key , start = start , end = end , interval = interval , namespace = namespace , cache = cache ) . value_series ( )
Get a time series of gauge values
9,564
def aggregate_series ( self , key , aggregate , start = None , end = None , interval = None , namespace = None , cache = None , percentile = None ) : return self . make_context ( key = key , aggregate = aggregate , start = start , end = end , interval = interval , namespace = namespace , cache = cache , percentile = pe...
Get a time series of gauge aggregates
9,565
def keys ( self , prefix = None , limit = None , offset = None , namespace = None ) : return self . make_context ( prefix = prefix , limit = limit , offset = offset , namespace = namespace ) . keys ( )
Get gauge keys
9,566
def statistics ( self , start = None , end = None , namespace = None ) : return self . make_context ( start = start , end = end , namespace = namespace ) . statistics ( )
Get write statistics for the specified namespace and date range
9,567
def sync ( self ) : self . driver . create_schema ( ) self . driver . set_metadata ( { 'current_version' : Gauged . VERSION , 'initial_version' : Gauged . VERSION , 'block_size' : self . config . block_size , 'resolution' : self . config . resolution , 'created_at' : long ( time ( ) * 1000 ) } , replace = False )
Create the necessary schema
9,568
def make_context ( self , ** kwargs ) : self . check_schema ( ) return Context ( self . driver , self . config , ** kwargs )
Create a new context for reading data
9,569
def check_schema ( self ) : if self . valid_schema : return config = self . config metadata = self . metadata ( ) if 'current_version' not in metadata : raise GaugedSchemaError ( 'Gauged schema not found, ' 'try a gauged.sync()' ) if metadata [ 'current_version' ] != Gauged . VERSION : msg = 'The schema is version %s w...
Check the schema exists and matches configuration
9,570
def nx_dag_node_rank ( graph , nodes = None ) : import utool as ut source = list ( ut . nx_source_nodes ( graph ) ) [ 0 ] longest_paths = dict ( [ ( target , dag_longest_path ( graph , source , target ) ) for target in graph . nodes ( ) ] ) node_to_rank = ut . map_dict_vals ( len , longest_paths ) if nodes is None : re...
Returns rank of nodes that define the level each node is on in a topological sort . This is the same as the Graphviz dot rank .
9,571
def nx_all_nodes_between ( graph , source , target , data = False ) : import utool as ut if source is None : sources = list ( ut . nx_source_nodes ( graph ) ) assert len ( sources ) == 1 , ( 'specify source if there is not only one' ) source = sources [ 0 ] if target is None : sinks = list ( ut . nx_sink_nodes ( graph ...
Find all nodes with on paths between source and target .
9,572
def nx_all_simple_edge_paths ( G , source , target , cutoff = None , keys = False , data = False ) : if cutoff is None : cutoff = len ( G ) - 1 if cutoff < 1 : return import utool as ut import six visited_nodes = [ source ] visited_edges = [ ] if G . is_multigraph ( ) : get_neighbs = ut . partial ( G . edges , keys = k...
Returns each path from source to target as a list of edges .
9,573
def nx_delete_node_attr ( graph , name , nodes = None ) : if nodes is None : nodes = list ( graph . nodes ( ) ) removed = 0 node_dict = nx_node_dict ( graph ) if isinstance ( name , list ) : for node in nodes : for name_ in name : try : del node_dict [ node ] [ name_ ] removed += 1 except KeyError : pass else : for nod...
Removes node attributes
9,574
def nx_delete_edge_attr ( graph , name , edges = None ) : removed = 0 keys = [ name ] if not isinstance ( name , ( list , tuple ) ) else name if edges is None : if graph . is_multigraph ( ) : edges = graph . edges ( keys = True ) else : edges = graph . edges ( ) if graph . is_multigraph ( ) : for u , v , k in edges : f...
Removes an attributes from specific edges in the graph
9,575
def nx_gen_node_values ( G , key , nodes , default = util_const . NoParam ) : node_dict = nx_node_dict ( G ) if default is util_const . NoParam : return ( node_dict [ n ] [ key ] for n in nodes ) else : return ( node_dict [ n ] . get ( key , default ) for n in nodes )
Generates attributes values of specific nodes
9,576
def nx_gen_node_attrs ( G , key , nodes = None , default = util_const . NoParam , on_missing = 'error' , on_keyerr = 'default' ) : if on_missing is None : on_missing = 'error' if default is util_const . NoParam and on_keyerr == 'default' : on_keyerr = 'error' if nodes is None : nodes = G . nodes ( ) node_dict = nx_node...
Improved generator version of nx . get_node_attributes
9,577
def nx_gen_edge_values ( G , key , edges = None , default = util_const . NoParam , on_missing = 'error' , on_keyerr = 'default' ) : if edges is None : edges = G . edges ( ) if on_missing is None : on_missing = 'error' if on_keyerr is None : on_keyerr = 'default' if default is util_const . NoParam and on_keyerr == 'defa...
Generates attributes values of specific edges
9,578
def nx_gen_edge_attrs ( G , key , edges = None , default = util_const . NoParam , on_missing = 'error' , on_keyerr = 'default' ) : if on_missing is None : on_missing = 'error' if default is util_const . NoParam and on_keyerr == 'default' : on_keyerr = 'error' if edges is None : if G . is_multigraph ( ) : raise NotImple...
Improved generator version of nx . get_edge_attributes
9,579
def nx_minimum_weight_component ( graph , weight = 'weight' ) : mwc = nx . minimum_spanning_tree ( graph , weight = weight ) neg_edges = ( e for e , w in nx_gen_edge_attrs ( graph , weight ) if w < 0 ) mwc . add_edges_from ( neg_edges ) return mwc
A minimum weight component is an MST + all negative edges
9,580
def nx_ensure_agraph_color ( graph ) : from plottool import color_funcs import plottool as pt def _fix_agraph_color ( data ) : try : orig_color = data . get ( 'color' , None ) alpha = data . get ( 'alpha' , None ) color = orig_color if color is None and alpha is not None : color = [ 0 , 0 , 0 ] if color is not None : c...
changes colors to hex strings on graph attrs
9,581
def dag_longest_path ( graph , source , target ) : if source == target : return [ source ] allpaths = nx . all_simple_paths ( graph , source , target ) longest_path = [ ] for l in allpaths : if len ( l ) > len ( longest_path ) : longest_path = l return longest_path
Finds the longest path in a dag between two nodes
9,582
def simplify_graph ( graph ) : import utool as ut nodes = sorted ( list ( graph . nodes ( ) ) ) node_lookup = ut . make_index_lookup ( nodes ) if graph . is_multigraph ( ) : edges = list ( graph . edges ( keys = True ) ) else : edges = list ( graph . edges ( ) ) new_nodes = ut . take ( node_lookup , nodes ) if graph . ...
strips out everything but connectivity
9,583
def subgraph_from_edges ( G , edge_list , ref_back = True ) : sub_nodes = list ( { y for x in edge_list for y in x [ 0 : 2 ] } ) multi_edge_list = [ edge [ 0 : 3 ] for edge in edge_list ] if ref_back : G_sub = G . subgraph ( sub_nodes ) for edge in G_sub . edges ( keys = True ) : if edge not in multi_edge_list : G_sub ...
Creates a networkx graph that is a subgraph of G defined by the list of edges in edge_list .
9,584
def all_multi_paths ( graph , source , target , data = False ) : r path_multiedges = list ( nx_all_simple_edge_paths ( graph , source , target , keys = True , data = data ) ) return path_multiedges
r Returns specific paths along multi - edges from the source to this table . Multipaths are identified by edge keys .
9,585
def bfs_conditional ( G , source , reverse = False , keys = True , data = False , yield_nodes = True , yield_if = None , continue_if = None , visited_nodes = None , yield_source = False ) : if reverse and hasattr ( G , 'reverse' ) : G = G . reverse ( ) if isinstance ( G , nx . Graph ) : neighbors = functools . partial ...
Produce edges in a breadth - first - search starting at source but only return nodes that satisfiy a condition and only iterate past a node if it satisfies a different condition .
9,586
def color_nodes ( graph , labelattr = 'label' , brightness = .878 , outof = None , sat_adjust = None ) : import plottool as pt import utool as ut node_to_lbl = nx . get_node_attributes ( graph , labelattr ) unique_lbls = sorted ( set ( node_to_lbl . values ( ) ) ) ncolors = len ( unique_lbls ) if outof is None : if ( n...
Colors edges and nodes by nid
9,587
def approx_min_num_components ( nodes , negative_edges ) : import utool as ut num = 0 g_neg = nx . Graph ( ) g_neg . add_nodes_from ( nodes ) g_neg . add_edges_from ( negative_edges ) if nx . __version__ . startswith ( '2' ) : deg0_nodes = [ n for n , d in g_neg . degree ( ) if d == 0 ] else : deg0_nodes = [ n for n , ...
Find approximate minimum number of connected components possible Each edge represents that two nodes must be separated
9,588
def solve ( self , y , h , t_end ) : ts = [ ] ys = [ ] yi = y ti = 0.0 while ti < t_end : ts . append ( ti ) yi = self . step ( yi , None , ti , h ) ys . append ( yi ) ti += h return ts , ys
Given a function initial conditions step size and end value this will calculate an unforced system . The default start time is t = 0 . 0 but this can be changed .
9,589
def step ( self , y , u , t , h ) : k1 = h * self . func ( t , y , u ) k2 = h * self . func ( t + .5 * h , y + .5 * h * k1 , u ) k3 = h * self . func ( t + .5 * h , y + .5 * h * k2 , u ) k4 = h * self . func ( t + h , y + h * k3 , u ) return y + ( k1 + 2 * k2 + 2 * k3 + k4 ) / 6.0
This is called by solve but can be called by the user who wants to run through an integration with a control force .
9,590
def generate_proteins ( pepfn , proteins , pepheader , scorecol , minlog , higherbetter = True , protcol = False ) : protein_peptides = { } if minlog : higherbetter = False if not protcol : protcol = peptabledata . HEADER_MASTERPROTEINS for psm in reader . generate_tsv_psms ( pepfn , pepheader ) : p_acc = psm [ protcol...
Best peptide for each protein in a table
9,591
def add ( self , child ) : if isinstance ( child , Run ) : self . add_run ( child ) elif isinstance ( child , Record ) : self . add_record ( child ) elif isinstance ( child , EventRecord ) : self . add_event_record ( child ) elif isinstance ( child , DataDisplay ) : self . add_data_display ( child ) elif isinstance ( c...
Adds a typed child object to the simulation spec .
9,592
def fetch ( self , id_ , return_fields = None ) : game_params = { "id" : id_ } if return_fields is not None : self . _validate_return_fields ( return_fields ) field_list = "," . join ( return_fields ) game_params [ "field_list" ] = field_list response = self . _query ( game_params , direct = True ) return response
Wrapper for fetching details of game by ID
9,593
def define_options ( self , names , parser_options = None ) : def copy_option ( options , name ) : return { k : v for k , v in options [ name ] . items ( ) } if parser_options is None : parser_options = { } options = { } for name in names : try : option = copy_option ( parser_options , name ) except KeyError : option =...
Given a list of option names this returns a list of dicts defined in all_options and self . shared_options . These can then be used to populate the argparser with
9,594
def current_memory_usage ( ) : import psutil proc = psutil . Process ( os . getpid ( ) ) meminfo = proc . memory_info ( ) rss = meminfo [ 0 ] vms = meminfo [ 1 ] return rss
Returns this programs current memory usage in bytes
9,595
def num_unused_cpus ( thresh = 10 ) : import psutil cpu_usage = psutil . cpu_percent ( percpu = True ) return sum ( [ p < thresh for p in cpu_usage ] )
Returns the number of cpus with utilization less than thresh percent
9,596
def get_protein_group_content ( pgmap , master ) : pg_content = [ [ 0 , master , protein , len ( peptides ) , len ( [ psm for pgpsms in peptides . values ( ) for psm in pgpsms ] ) , sum ( [ psm [ 1 ] for pgpsms in peptides . values ( ) for psm in pgpsms ] ) , next ( iter ( next ( iter ( peptides . values ( ) ) ) ) ) [ ...
For each master protein we generate the protein group proteins complete with sequences psm_ids and scores . Master proteins are included in this group .
9,597
def get_protein_data ( peptide , pdata , headerfields , accfield ) : report = get_proteins ( peptide , pdata , headerfields ) return get_cov_descriptions ( peptide , pdata , report )
These fields are currently not pool dependent so headerfields is ignored
9,598
def get_num_chunks ( length , chunksize ) : r n_chunks = int ( math . ceil ( length / chunksize ) ) return n_chunks
r Returns the number of chunks that a list will be split into given a chunksize .
9,599
def ProgChunks ( list_ , chunksize , nInput = None , ** kwargs ) : if nInput is None : nInput = len ( list_ ) n_chunks = get_num_chunks ( nInput , chunksize ) kwargs [ 'length' ] = n_chunks if 'freq' not in kwargs : kwargs [ 'freq' ] = 1 chunk_iter = util_iter . ichunks ( list_ , chunksize ) progiter_ = ProgressIter ( ...
Yeilds an iterator in chunks and computes progress Progress version of ut . ichunks