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,500
def add_dict ( self , dyn_dict ) : 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
83
7
9,501
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 .
58
8
9,502
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
72
16
9,503
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
111
11
9,504
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 .
138
12
9,505
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 .
46
17
9,506
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 .
54
10
9,507
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 .
95
12
9,508
def _frame_received ( self , frame ) : try : self . _rx_frames [ frame [ "frame_id" ] ] = frame except KeyError : # Has no frame_id, ignore? pass _LOGGER . debug ( "Frame received: %s" , frame ) # Give the frame to any interested functions for handler in self . _rx_handlers : handler ( frame )
Put the frame into the _rx_frames dict with a key of the frame_id .
84
19
9,509
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 .
62
14
9,510
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 ) retur...
Send a frame to either the local ZigBee or a remote device and wait for a pre - defined amount of time for its response .
145
27
9,511
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 .
55
12
9,512
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 : # @TODO: Is there always one value? Is it always a list? return frame [ "parameter" ] [ 0 ] return { }
Initiate a sample and return its data .
86
10
9,513
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 .
114
16
9,514
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 .
83
7
9,515
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 .
83
7
9,516
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 .
69
14
9,517
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
74
14
9,518
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
46
10
9,519
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
39
10
9,520
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
61
13
9,521
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
67
7
9,522
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
81
8
9,523
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
49
3
9,524
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
41
10
9,525
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
93
4
9,526
def make_context ( self , * * kwargs ) : self . check_schema ( ) return Context ( self . driver , self . config , * * kwargs )
Create a new context for reading data
39
7
9,527
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
260
7
9,528
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 .
130
30
9,529
def nx_all_nodes_between ( graph , source , target , data = False ) : import utool as ut if source is None : # assume there is a single source 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 : # assume...
Find all nodes with on paths between source and target .
190
11
9,530
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 .
379
13
9,531
def nx_delete_node_attr ( graph , name , nodes = None ) : if nodes is None : nodes = list ( graph . nodes ( ) ) removed = 0 # names = [name] if not isinstance(name, list) else name node_dict = nx_node_dict ( graph ) if isinstance ( name , list ) : for node in nodes : for name_ in name : try : del node_dict [ node ] [ n...
Removes node attributes
137
4
9,532
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
165
10
9,533
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
87
7
9,534
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 ( ) # Generate `node_da...
Improved generator version of nx . get_node_attributes
406
13
9,535
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
330
7
9,536
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
468
13
9,537
def nx_minimum_weight_component ( graph , weight = 'weight' ) : mwc = nx . minimum_spanning_tree ( graph , weight = weight ) # negative edges only reduce the total 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
98
12
9,538
def nx_ensure_agraph_color ( graph ) : from plottool import color_funcs import plottool as pt #import six 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 ...
changes colors to hex strings on graph attrs
348
9
9,539
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
79
11
9,540
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
233
6
9,541
def subgraph_from_edges ( G , edge_list , ref_back = True ) : # TODO: support multi-di-graph sub_nodes = list ( { y for x in edge_list for y in x [ 0 : 2 ] } ) #edge_list_no_data = [edge[0:2] for edge in edge_list] multi_edge_list = [ edge [ 0 : 3 ] for edge in edge_list ] if ref_back : G_sub = G . subgraph ( sub_nodes...
Creates a networkx graph that is a subgraph of G defined by the list of edges in edge_list .
214
24
9,542
def all_multi_paths ( graph , source , target , data = False ) : 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 .
60
24
9,543
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 .
423
36
9,544
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
506
8
9,545
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 ) # Collapse all nodes with degree 0 if nx . __version__ . startswith ( '2' ) : deg0_nodes = [ n for n , d in g_neg . degree ( ) if d == 0...
Find approximate minimum number of connected components possible Each edge represents that two nodes must be separated
582
17
9,546
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 .
77
34
9,547
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 .
131
24
9,548
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
414
9
9,549
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 .
140
10
9,550
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
93
10
9,551
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
140
36
9,552
def current_memory_usage ( ) : import psutil proc = psutil . Process ( os . getpid ( ) ) #meminfo = proc.get_memory_info() meminfo = proc . memory_info ( ) rss = meminfo [ 0 ] # Resident Set Size / Mem Usage vms = meminfo [ 1 ] # Virtual Memory Size / VM Size # NOQA return rss
Returns this programs current memory usage in bytes
85
8
9,553
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
50
13
9,554
def get_protein_group_content ( pgmap , master ) : # first item (0) is only a placeholder so the lookup.INDEX things get the # correct number. Would be nice with a solution, but the INDEXes were # originally made for mzidtsv protein group adding. pg_content = [ [ 0 , master , protein , len ( peptides ) , len ( [ psm fo...
For each master protein we generate the protein group proteins complete with sequences psm_ids and scores . Master proteins are included in this group .
206
28
9,555
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
55
12
9,556
def get_num_chunks ( length , chunksize ) : 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 .
37
18
9,557
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
130
19
9,558
def ensure_newline ( self ) : DECTCEM_SHOW = '\033[?25h' # show cursor AT_END = DECTCEM_SHOW + '\n' if not self . _cursor_at_newline : self . write ( AT_END ) self . _cursor_at_newline = True
use before any custom printing when using the progress iter to ensure your print statement starts on a new line instead of at the end of a progress line
75
29
9,559
def _get_timethresh_heuristics ( self ) : if self . length > 1E5 : time_thresh = 2.5 elif self . length > 1E4 : time_thresh = 2.0 elif self . length > 1E3 : time_thresh = 1.0 else : time_thresh = 0.5 return time_thresh
resonably decent hueristics for how much time to wait before updating progress .
83
17
9,560
def load_code ( name , base_path = None , recurse = False ) : if '/' in name : return load_location ( name , base_path , module = False ) return importer . import_code ( name , base_path , recurse = recurse )
Load executable code from a URL or a path
60
9
9,561
def load ( name , base_path = None ) : if '/' in name : return load_location ( name , base_path , module = True ) return importer . import_symbol ( name , base_path )
Load a module from a URL or a path
48
9
9,562
def extend ( path = None , cache = None ) : if path is None : path = config . PATH try : path = path . split ( ':' ) except : pass sys . path . extend ( [ library . to_path ( p , cache ) for p in path ] )
Extend sys . path by a list of git paths .
59
12
9,563
def extender ( path = None , cache = None ) : old_path = sys . path [ : ] extend ( path , cache = None ) try : yield finally : sys . path = old_path
A context that temporarily extends sys . path and reverts it after the context is complete .
43
18
9,564
def add ( self , child ) : if isinstance ( child , Case ) : self . add_case ( child ) else : raise ModelError ( 'Unsupported child element' )
Adds a typed child object to the conditional derived variable .
38
11
9,565
def add ( self , child ) : if isinstance ( child , Action ) : self . add_action ( child ) else : raise ModelError ( 'Unsupported child element' )
Adds a typed child object to the event handler .
38
10
9,566
def add ( self , child ) : if isinstance ( child , StateVariable ) : self . add_state_variable ( child ) elif isinstance ( child , DerivedVariable ) : self . add_derived_variable ( child ) elif isinstance ( child , ConditionalDerivedVariable ) : self . add_conditional_derived_variable ( child ) elif isinstance ( child ...
Adds a typed child object to the behavioral object .
161
10
9,567
def add ( self , child ) : if isinstance ( child , Regime ) : self . add_regime ( child ) else : Behavioral . add ( self , child )
Adds a typed child object to the dynamics object .
37
10
9,568
def create_bioset_lookup ( lookupdb , spectrafns , set_names ) : unique_setnames = set ( set_names ) lookupdb . store_biosets ( ( ( x , ) for x in unique_setnames ) ) set_id_map = lookupdb . get_setnames ( ) mzmlfiles = ( ( os . path . basename ( fn ) , set_id_map [ setname ] ) for fn , setname in zip ( spectrafns , se...
Fills lookup database with biological set names
143
8
9,569
def get_modpath_from_modname ( modname , prefer_pkg = False , prefer_main = False ) : from os . path import dirname , basename , join , exists initname = '__init__.py' mainname = '__main__.py' if modname in sys . modules : modpath = sys . modules [ modname ] . __file__ . replace ( '.pyc' , '.py' ) else : import pkgutil...
Same as get_modpath but doesnt import directly
247
10
9,570
def check_module_installed ( modname ) : import pkgutil if '.' in modname : # Prevent explicit import if possible parts = modname . split ( '.' ) base = parts [ 0 ] submods = parts [ 1 : ] loader = pkgutil . find_loader ( base ) if loader is not None : # TODO: check to see if path to the submod exists submods return Tr...
Check if a python module is installed without attempting to import it . Note that if modname indicates a child module the parent module is always loaded .
113
29
9,571
def import_module_from_fpath ( module_fpath ) : from os . path import basename , splitext , isdir , join , exists , dirname , split import platform if isdir ( module_fpath ) : module_fpath = join ( module_fpath , '__init__.py' ) print ( 'module_fpath = {!r}' . format ( module_fpath ) ) if not exists ( module_fpath ) : ...
r imports module from a file path
364
7
9,572
def print_locals ( * args , * * kwargs ) : from utool import util_str from utool import util_dbg from utool import util_dict locals_ = util_dbg . get_parent_frame ( ) . f_locals keys = kwargs . get ( 'keys' , None if len ( args ) == 0 else [ ] ) to_print = { } for arg in args : varname = util_dbg . get_varname_from_loc...
Prints local variables in function .
185
7
9,573
def _extract_archive ( archive_fpath , archive_file , archive_namelist , output_dir , force_commonprefix = True , prefix = None , dryrun = False , verbose = not QUIET , overwrite = None ) : # force extracted components into a subdirectory if force_commonprefix is # on return_path = output_diG # FIXMpathE doesn't work r...
archive_fpath = zip_fpath archive_file = zip_file
300
16
9,574
def open_url_in_browser ( url , browsername = None , fallback = False ) : import webbrowser print ( '[utool] Opening url=%r in browser' % ( url , ) ) if browsername is None : browser = webbrowser . open ( url ) else : browser = get_prefered_browser ( pref_list = [ browsername ] , fallback = fallback ) return browser . ...
r Opens a url in the specified or default browser
97
11
9,575
def url_read ( url , verbose = True ) : if url . find ( '://' ) == - 1 : url = 'http://' + url if verbose : print ( 'Reading data from url=%r' % ( url , ) ) try : file_ = _urllib . request . urlopen ( url ) #file_ = _urllib.urlopen(url) except IOError : raise data = file_ . read ( ) file_ . close ( ) return data
r Directly reads data from url
107
7
9,576
def url_read_text ( url , verbose = True ) : data = url_read ( url , verbose ) text = data . decode ( 'utf8' ) return text
r Directly reads text data from url
39
8
9,577
def clean_dropbox_link ( dropbox_url ) : cleaned_url = dropbox_url . replace ( 'www.dropbox' , 'dl.dropbox' ) postfix_list = [ '?dl=0' ] for postfix in postfix_list : if cleaned_url . endswith ( postfix ) : cleaned_url = cleaned_url [ : - 1 * len ( postfix ) ] # cleaned_url = cleaned_url.rstrip('?dl=0') return cleaned_...
Dropbox links should be en - mass downloaed from dl . dropbox
113
17
9,578
def grab_selenium_chromedriver ( redownload = False ) : import utool as ut import os import stat # TODO: use a better download dir (but it must be in the PATh or selenium freaks out) chromedriver_dpath = ut . ensuredir ( ut . truepath ( '~/bin' ) ) chromedriver_fpath = join ( chromedriver_dpath , 'chromedriver' ) if no...
r Automatically download selenium chrome driver if needed
394
11
9,579
def grab_selenium_driver ( driver_name = None ) : from selenium import webdriver if driver_name is None : driver_name = 'firefox' if driver_name . lower ( ) == 'chrome' : grab_selenium_chromedriver ( ) return webdriver . Chrome ( ) elif driver_name . lower ( ) == 'firefox' : # grab_selenium_chromedriver() return webdri...
pip install selenium - U
122
8
9,580
def grab_file_url ( file_url , appname = 'utool' , download_dir = None , delay = None , spoof = False , fname = None , verbose = True , redownload = False , check_hash = False ) : file_url = clean_dropbox_link ( file_url ) if fname is None : fname = basename ( file_url ) # Download zipfile to if download_dir is None : ...
r Downloads a file and returns the local path of the file .
806
13
9,581
def grab_zipped_url ( zipped_url , ensure = True , appname = 'utool' , download_dir = None , force_commonprefix = True , cleanup = False , redownload = False , spoof = False ) : zipped_url = clean_dropbox_link ( zipped_url ) zip_fname = split ( zipped_url ) [ 1 ] data_name = split_archive_ext ( zip_fname ) [ 0 ] # Down...
r downloads and unzips the url
346
8
9,582
def scp_pull ( remote_path , local_path = '.' , remote = 'localhost' , user = None ) : import utool as ut if user is not None : remote_uri = user + '@' + remote + ':' + remote_path else : remote_uri = remote + ':' + remote_path scp_exe = 'scp' scp_args = ( scp_exe , '-r' , remote_uri , local_path ) ut . cmd ( scp_args ...
r wrapper for scp
113
5
9,583
def list_remote ( remote_uri , verbose = False ) : remote_uri1 , remote_dpath = remote_uri . split ( ':' ) if not remote_dpath : remote_dpath = '.' import utool as ut out = ut . cmd ( 'ssh' , remote_uri1 , 'ls -l %s' % ( remote_dpath , ) , verbose = verbose ) import re # Find lines that look like ls output split_lines ...
remote_uri = user
167
5
9,584
def rsync ( src_uri , dst_uri , exclude_dirs = [ ] , port = 22 , dryrun = False ) : from utool import util_cplat rsync_exe = 'rsync' rsync_options = '-avhzP' #rsync_options += ' --port=%d' % (port,) rsync_options += ' -e "ssh -p %d"' % ( port , ) if len ( exclude_dirs ) > 0 : exclude_tup = [ '--exclude ' + dir_ for dir...
r Wrapper for rsync
278
6
9,585
def get_cache ( self , namespace , query_hash , length , start , end ) : query = 'SELECT start, value FROM gauged_cache WHERE namespace = ? ' 'AND hash = ? AND length = ? AND start BETWEEN ? AND ?' cursor = self . cursor cursor . execute ( query , ( namespace , query_hash , length , start , end ) ) return tuple ( curso...
Get a cached value for the specified date range and query
90
11
9,586
def review ( cls , content , log , parent , window_icon ) : # pragma: no cover dlg = DlgReview ( content , log , parent , window_icon ) if dlg . exec_ ( ) : return dlg . ui . edit_main . toPlainText ( ) , dlg . ui . edit_log . toPlainText ( ) return None , None
Reviews the final bug report .
92
7
9,587
def get_version ( ) : version_desc = open ( os . path . join ( os . path . abspath ( APISettings . VERSION_FILE ) ) ) version_file = version_desc . read ( ) try : version = re . search ( r"version=['\"]([^'\"]+)['\"]" , version_file ) . group ( 1 ) return version except FileNotFoundError : Shell . fail ( 'File not foun...
Return version from setup . py
140
6
9,588
def set_version ( old_version , new_version ) : try : if APISettings . DEBUG : Shell . debug ( '* ' + old_version + ' --> ' + new_version ) return True for line in fileinput . input ( os . path . abspath ( APISettings . VERSION_FILE ) , inplace = True ) : print ( line . replace ( old_version , new_version ) , end = '' ...
Write new version into VERSION_FILE
131
8
9,589
def set_major ( self ) : old_version = self . get_version ( ) new_version = str ( int ( old_version . split ( '.' , 5 ) [ 0 ] ) + 1 ) + '.0.0' self . set_version ( old_version , new_version )
Increment the major number of project
65
7
9,590
def set_minor ( self ) : old_version = self . get_version ( ) new_version = str ( int ( old_version . split ( '.' , 5 ) [ 0 ] ) ) + '.' + str ( int ( old_version . split ( '.' , 5 ) [ 1 ] ) + 1 ) + '.0' self . set_version ( old_version , new_version )
Increment the minor number of project
88
7
9,591
def set_patch ( self , pre_release_tag = '' ) : current_version = self . get_version ( ) current_patch = self . get_patch_version ( current_version ) current_pre_release_tag = self . get_current_pre_release_tag ( current_patch ) current_RELEASE_SEPARATOR = self . get_current_RELEASE_SEPARATOR ( current_patch ) new_patc...
Increment the patch number of project
466
7
9,592
def flush ( self ) : ( slice_ , self . __buffer ) = ( self . __buffer , '' ) self . __size = 0 return slice_
Return all buffered data and clear the stack .
33
10
9,593
def __send_hello ( self ) : _logger . debug ( "Saying hello: [%s]" , self ) self . __c . send ( nsq . config . protocol . MAGIC_IDENTIFIER )
Initiate the handshake .
48
6
9,594
def __sender ( self ) : # If we're ignoring the quit, the connections will have to be closed # by the server. while ( self . __ignore_quit is True or self . __nice_quit_ev . is_set ( ) is False ) and self . __force_quit_ev . is_set ( ) is False : # TODO(dustin): The quit-signals aren't being properly set after a produc...
Send - loop .
263
4
9,595
def __receiver ( self ) : # If we're ignoring the quit, the connections will have to be closed # by the server. while ( self . __ignore_quit is True or self . __nice_quit_ev . is_set ( ) is False ) and self . __force_quit_ev . is_set ( ) is False : # TODO(dustin): The quit-signals aren't being properly set after a prod...
Receive - loop .
186
5
9,596
def run ( self ) : while self . __nice_quit_ev . is_set ( ) is False : self . __connect ( ) _logger . info ( "Connection re-connect loop has terminated: %s" , self . __mc )
Connect the server and maintain the connection . This shall not return until a connection has been determined to absolutely not be available .
54
24
9,597
def save ( obj , filename , protocol = 4 ) : with open ( filename , 'wb' ) as f : pickle . dump ( obj , f , protocol = protocol )
Serialize an object to disk using pickle protocol .
37
11
9,598
def load_json ( filename , * * kwargs ) : with open ( filename , 'r' , encoding = 'utf-8' ) as f : return json . load ( f , * * kwargs )
Load a JSON object from the specified file .
47
9
9,599
def save_json ( obj , filename , * * kwargs ) : with open ( filename , 'w' , encoding = 'utf-8' ) as f : json . dump ( obj , f , * * kwargs )
Save an object as a JSON file .
50
8