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,600
def load_lines ( filename ) : with open ( filename , 'r' , encoding = 'utf-8' ) as f : return [ line . rstrip ( '\n' ) for line in f . readlines ( ) ]
Load a text file as an array of lines .
50
10
9,601
def save_lines ( lines , filename ) : with open ( filename , 'w' , encoding = 'utf-8' ) as f : f . write ( '\n' . join ( lines ) )
Save an array of lines to a file .
44
9
9,602
def add ( self , child ) : if isinstance ( child , Component ) : self . add_child ( child ) else : raise ModelError ( 'Unsupported child element' )
Adds a typed child object to the component .
38
9
9,603
def write_peps ( self , peps , reverse_seqs ) : if reverse_seqs : peps = [ ( x [ 0 ] [ : : - 1 ] , ) for x in peps ] cursor = self . get_cursor ( ) cursor . executemany ( 'INSERT INTO known_searchspace(seqs) VALUES (?)' , peps ) self . conn . commit ( )
Writes peps to db . We can reverse to be able to look up peptides that have some amino acids missing at the N - terminal . This way we can still use the index .
90
39
9,604
def send_http_request ( self , app : str , service : str , version : str , method : str , entity : str , params : dict ) : host , port , node_id , service_type = self . _registry_client . resolve ( service , version , entity , HTTP ) url = 'http://{}:{}{}' . format ( host , port , params . pop ( 'path' ) ) http_keys = ...
A convenience method that allows you to send a well formatted http request to another service
233
16
9,605
def install_except_hook ( except_hook = _hooks . except_hook ) : if not _backends : raise ValueError ( 'no backends found, you must at least install one ' 'backend before calling this function' ) global _except_hook _except_hook = _hooks . QtExceptHook ( except_hook )
Install an except hook that will show the crash report dialog when an unhandled exception has occured .
75
20
9,606
def show_report_dialog ( window_title = 'Report an issue...' , window_icon = None , traceback = None , issue_title = '' , issue_description = '' , parent = None , modal = None , include_log = True , include_sys_info = True ) : if not _backends : raise ValueError ( 'no backends found, you must at least install one ' 'ba...
Show the issue report dialog manually .
210
7
9,607
def middleware ( self , args ) : if self . url [ ( len ( self . url ) - 1 ) ] == ( self . url_ , self . controller , dict ( method = self . method , request_type = self . request_type , middleware = None ) ) : self . url . pop ( ) self . url . append ( ( self . url_ , self . controller , dict ( method = self . method ,...
Appends a Middleware to the route which is to be executed before the route runs
111
17
9,608
def get ( self , url , controller ) : self . request_type = 'GET' controller_class , controller_method = self . __return_controller__ ( controller ) self . controller = controller_class self . method = controller_method self . url_ = url self . url . append ( ( url , controller_class , dict ( method = controller_method...
Gets the Controller and adds the route controller and method to the url list for GET request
97
18
9,609
def to_bytes ( value ) : if isinstance ( value , unicode ) : return value . encode ( 'utf8' ) elif not isinstance ( value , str ) : return str ( value ) return value
Get a byte array representing the value
46
7
9,610
def table_repr ( columns , rows , data , padding = 2 ) : padding = ' ' * padding column_lengths = [ len ( column ) for column in columns ] for row in rows : for i , column in enumerate ( columns ) : item = str ( data [ row ] [ column ] ) column_lengths [ i ] = max ( len ( item ) , column_lengths [ i ] ) max_row_length ...
Generate a table for cli output
248
8
9,611
def get_proteins_for_db ( fastafn ) : objects = { } for record in parse_fasta ( fastafn ) : objects [ parse_protein_identifier ( record ) ] = record return ( ( ( acc , ) for acc in list ( objects ) ) , ( ( acc , str ( record . seq ) ) for acc , record in objects . items ( ) ) , ( ( acc , get_uniprot_evidence_level ( re...
Runs through fasta file and returns proteins accession nrs sequences and evidence levels for storage in lookup DB . Duplicate accessions in fasta are accepted and removed by keeping only the last one .
117
41
9,612
def get_uniprot_evidence_level ( header ) : header = header . split ( ) for item in header : item = item . split ( '=' ) try : if item [ 0 ] == 'PE' : return 5 - int ( item [ 1 ] ) except IndexError : continue return - 1
Returns uniprot protein existence evidence level for a fasta header . Evidence levels are 1 - 5 but we return 5 - x since sorting still demands that higher is better .
65
35
9,613
def run ( self ) : self . pre_run ( ) first = True while self . runnable : self . pre_call_message ( ) if first : self . pre_first_call_message ( ) message , payload = self . listener . get ( ) getattr ( self , message ) ( payload ) if first : first = False self . post_first_call_message ( ) self . post_call_message ( ...
Run our loop and any defined hooks ...
100
8
9,614
def count_multiplicities ( times , tmax = 20 ) : n = times . shape [ 0 ] mtp = np . ones ( n , dtype = '<i4' ) # multiplicities cid = np . zeros ( n , '<i4' ) # coincidence id idx0 = 0 _mtp = 1 _cid = 0 t0 = times [ idx0 ] for i in range ( 1 , n ) : dt = times [ i ] - t0 if dt > tmax : mtp [ idx0 : i ] = _mtp cid [ idx...
Calculate an array of multiplicities and corresponding coincidence IDs
206
13
9,615
def build_machine ( lines ) : if lines == [ ] : raise SyntaxError ( 'Empty file' ) else : machine = Machine ( lines [ 0 ] . split ( ) ) for line in lines [ 1 : ] : if line . strip ( ) != '' : machine . add_state ( line ) machine . check ( ) return machine
Build machine from list of lines .
72
7
9,616
def add_state ( self , string ) : parsed_string = string . split ( ) if len ( parsed_string ) > 0 : state , rules = parsed_string [ 0 ] , parsed_string [ 1 : ] if len ( rules ) != len ( self . alphabet ) : raise SyntaxError ( 'Wrong count of rules ({cur}/{exp}): {string}' . format ( cur = len ( rules ) , exp = len ( se...
Add state and rules to machine .
184
7
9,617
def check ( self ) : has_term = False if self . START_STATE not in self . states : raise SyntaxError ( 'Undefined start rule' ) for state in self . states : for rule in self . states [ state ] : if rule is not None : if rule [ 2 ] == self . TERM_STATE : has_term = True elif rule [ 2 ] not in self . states : raise Synta...
Check semantic rules .
123
4
9,618
def init_tape ( self , string ) : for char in string : if char not in self . alphabet and not char . isspace ( ) and char != self . EMPTY_SYMBOL : raise RuntimeError ( 'Invalid symbol: "' + char + '"' ) self . check ( ) self . state = self . START_STATE self . head = 0 self . tape = { } for i in range ( len ( string ) ...
Init system values .
128
4
9,619
def get_tape ( self ) : result = '' for i in range ( min ( self . tape ) , max ( self . tape ) + 1 ) : symbol = self . tape [ i ] if self . tape [ i ] != self . EMPTY_SYMBOL else ' ' result += symbol # Remove unnecessary empty symbols on tape return result . strip ( )
Get content of tape .
77
5
9,620
def execute_once ( self ) : symbol = self . tape . get ( self . head , self . EMPTY_SYMBOL ) index = self . alphabet . index ( symbol ) rule = self . states [ self . state ] [ index ] if rule is None : raise RuntimeError ( 'Unexpected symbol: ' + symbol ) self . tape [ self . head ] = rule [ 0 ] if rule [ 1 ] == 'L' : ...
One step of execution .
122
5
9,621
def compile ( self ) : result = TEMPLATE result += 'machine = Machine(' + repr ( self . alphabet ) + ')\n' for state in self . states : repr_state = state [ 0 ] for rule in self . states [ state ] : repr_state += ' ' + ( ',' . join ( rule ) if rule is not None else '-' ) result += ( "machine.add_state({repr_state})\n" ...
Return python code for create and execute machine .
138
9
9,622
def get_missing_services ( self , services ) : required_services = set ( services ) provided_services = set ( self . _services . keys ( ) ) missing_services = required_services . difference ( provided_services ) return sorted ( missing_services )
Check if all required services are provided
56
7
9,623
def _drain ( self , cycles = None ) : log . info ( "Now draining..." ) if not cycles : log . info ( "No cycle count, the pipeline may be drained forever." ) if self . calibration : log . info ( "Setting up the detector calibration." ) for module in self . modules : module . detector = self . calibration . get_detector ...
Activate the pump and let the flow go .
605
10
9,624
def _check_service_requirements ( self ) : missing = self . services . get_missing_services ( self . required_services . keys ( ) ) if missing : self . log . critical ( "Following services are required and missing: {}" . format ( ', ' . join ( missing ) ) ) return False return True
Final comparison of provided and required modules
69
7
9,625
def drain ( self , cycles = None ) : if not self . _check_service_requirements ( ) : self . init_timer . stop ( ) return self . finish ( ) if self . anybar : self . anybar . change ( "orange" ) self . init_timer . stop ( ) log . info ( "Trapping CTRL+C and starting to drain." ) signal . signal ( signal . SIGINT , self ...
Execute _drain while trapping KeyboardInterrupt
116
10
9,626
def _handle_ctrl_c ( self , * args ) : if self . anybar : self . anybar . change ( "exclamation" ) if self . _stop : print ( "\nForced shutdown..." ) raise SystemExit if not self . _stop : hline = 42 * '=' print ( '\n' + hline + "\nGot CTRL+C, waiting for current cycle...\n" "Press CTRL+C again if you're in hurry!\n" +...
Handle the keyboard interrupts .
114
5
9,627
def get ( self , name , default = None ) : value = self . parameters . get ( name ) self . _processed_parameters . append ( name ) if value is None : return default return value
Return the value of the requested parameter or default if None .
44
12
9,628
def require ( self , name ) : value = self . get ( name ) if value is None : raise TypeError ( "{0} requires the parameter '{1}'." . format ( self . __class__ , name ) ) return value
Return the value of the requested parameter or raise an error .
50
12
9,629
def _check_unused_parameters ( self ) : all_params = set ( self . parameters . keys ( ) ) processed_params = set ( self . _processed_parameters ) unused_params = all_params - processed_params - RESERVED_ARGS if unused_params : self . log . warning ( "The following parameters were ignored: {}" . format ( ', ' . join ( s...
Check if any of the parameters passed in are ignored
98
10
9,630
def open_file ( self , filename ) : try : if filename . endswith ( '.gz' ) : self . blob_file = gzip . open ( filename , 'rb' ) else : self . blob_file = open ( filename , 'rb' ) except TypeError : log . error ( "Please specify a valid filename." ) raise SystemExit except IOError as error_message : log . error ( error_...
Open the file with filename
95
5
9,631
def parse ( cls , date_string ) : try : date = dateparser . parse ( date_string ) if date . tzinfo is None : date = dateparser . parse ( date_string , tzinfos = cls . tzd ) return date except Exception : raise ValueError ( "Could not parse date string!" )
Parse any time string . Use a custom timezone matching if the original matching does not pull one out .
73
22
9,632
def epsg_code ( geojson ) : if isinstance ( geojson , dict ) : if 'crs' in geojson : urn = geojson [ 'crs' ] [ 'properties' ] [ 'name' ] . split ( ':' ) if 'EPSG' in urn : try : return int ( urn [ - 1 ] ) except ( TypeError , ValueError ) : return None return None
get the espg code from the crs system
96
10
9,633
def convert_coordinates ( coords , origin , wgs84 , wrapped ) : if isinstance ( coords , list ) or isinstance ( coords , tuple ) : try : if isinstance ( coords [ 0 ] , list ) or isinstance ( coords [ 0 ] , tuple ) : return [ convert_coordinates ( list ( c ) , origin , wgs84 , wrapped ) for c in coords ] elif isinstance...
Convert coordinates from one crs to another
152
9
9,634
def to_latlon ( geojson , origin_espg = None ) : if isinstance ( geojson , dict ) : # get epsg code: if origin_espg : code = origin_espg else : code = epsg_code ( geojson ) if code : origin = Proj ( init = 'epsg:%s' % code ) wgs84 = Proj ( init = 'epsg:4326' ) wrapped = test_wrap_coordinates ( geojson [ 'coordinates' ]...
Convert a given geojson to wgs84 . The original epsg must be included insde the crs tag of geojson
193
30
9,635
def camelcase_underscore ( name ) : s1 = re . sub ( '(.)([A-Z][a-z]+)' , r'\1_\2' , name ) return re . sub ( '([a-z0-9])([A-Z])' , r'\1_\2' , s1 ) . lower ( )
Convert camelcase names to underscore
80
7
9,636
def get_tiles_list ( element ) : tiles = { } for el in element : g = ( el . findall ( './/Granules' ) or el . findall ( './/Granule' ) ) [ 0 ] name = g . attrib [ 'granuleIdentifier' ] name_parts = name . split ( '_' ) mgs = name_parts [ - 2 ] tiles [ mgs ] = name return tiles
Returns the list of all tile names from Product_Organisation element in metadata . xml
97
17
9,637
def metadata_to_dict ( metadata ) : tree = etree . parse ( metadata ) root = tree . getroot ( ) meta = OrderedDict ( ) keys = [ 'SPACECRAFT_NAME' , 'PRODUCT_STOP_TIME' , 'Cloud_Coverage_Assessment' , 'PROCESSING_LEVEL' , 'PRODUCT_TYPE' , 'PROCESSING_BASELINE' , 'SENSING_ORBIT_NUMBER' , 'SENSING_ORBIT_DIRECTION' , 'PROD...
Looks at metadata . xml file of sentinel product and extract useful keys Returns a python dict
490
18
9,638
def get_tile_geometry ( path , origin_espg , tolerance = 500 ) : with rasterio . open ( path ) as src : # Get tile geometry b = src . bounds tile_shape = Polygon ( [ ( b [ 0 ] , b [ 1 ] ) , ( b [ 2 ] , b [ 1 ] ) , ( b [ 2 ] , b [ 3 ] ) , ( b [ 0 ] , b [ 3 ] ) , ( b [ 0 ] , b [ 1 ] ) ] ) tile_geojson = mapping ( tile_sh...
Calculate the data and tile geometry for sentinel - 2 tiles
465
14
9,639
def tile_metadata ( tile , product , geometry_check = None ) : grid = 'T{0}{1}{2}' . format ( pad ( tile [ 'utmZone' ] , 2 ) , tile [ 'latitudeBand' ] , tile [ 'gridSquare' ] ) meta = OrderedDict ( { 'tile_name' : product [ 'tiles' ] [ grid ] } ) logger . info ( '%s Processing tile %s' % ( threading . current_thread ( ...
Generate metadata for a given tile
498
7
9,640
def load_markov ( argv , stdin ) : if len ( argv ) > 3 : with open ( argv [ 3 ] ) as input_file : return Algorithm ( input_file . readlines ( ) ) else : return Algorithm ( stdin . readlines ( ) )
Load and return markov algorithm .
63
7
9,641
def load_turing ( argv , stdin ) : if len ( argv ) > 3 : with open ( argv [ 3 ] ) as input_file : return build_machine ( input_file . readlines ( ) ) else : return build_machine ( stdin . readlines ( ) )
Load and return turing machine .
65
7
9,642
def main ( argv , stdin , stdout ) : if len ( argv ) > 1 and argv [ 1 : 3 ] == [ "compile" , "markov" ] : algo = load_markov ( argv , stdin ) print ( algo . compile ( ) , file = stdout ) elif len ( argv ) == 4 and argv [ 1 : 3 ] == [ "run" , "markov" ] : algo = load_markov ( argv , stdin ) for line in stdin : print ( a...
Execute when user call turingmarkov .
390
10
9,643
def detectors ( regex = None , sep = '\t' , temporary = False ) : db = DBManager ( temporary = temporary ) dt = db . detectors if regex is not None : try : re . compile ( regex ) except re . error : log . error ( "Invalid regex!" ) return dt = dt [ dt [ 'OID' ] . str . contains ( regex ) | dt [ 'CITY' ] . str . contain...
Print the detectors table
117
4
9,644
def get_product_metadata_path ( product_name ) : string_date = product_name . split ( '_' ) [ - 1 ] date = datetime . datetime . strptime ( string_date , '%Y%m%dT%H%M%S' ) path = 'products/{0}/{1}/{2}/{3}' . format ( date . year , date . month , date . day , product_name ) return { product_name : { 'metadata' : '{0}/{1...
gets a single products metadata
173
5
9,645
def get_products_metadata_path ( year , month , day ) : products = { } path = 'products/{0}/{1}/{2}/' . format ( year , month , day ) for key in bucket . objects . filter ( Prefix = path ) : product_path = key . key . replace ( path , '' ) . split ( '/' ) name = product_path [ 0 ] if name not in products : products [ n...
Get paths to multiple products metadata
170
6
9,646
def start ( backdate = None ) : if f . s . cum : raise StartError ( "Already have stamps, can't start again (must reset)." ) if f . t . subdvsn_awaiting or f . t . par_subdvsn_awaiting : raise StartError ( "Already have subdivisions, can't start again (must reset)." ) if f . t . stopped : raise StoppedError ( "Timer al...
Mark the start of timing overwriting the automatic start data written on import or the automatic start at the beginning of a subdivision .
282
26
9,647
def stamp ( name , backdate = None , unique = None , keep_subdivisions = None , quick_print = None , un = None , ks = None , qp = None ) : t = timer ( ) if f . t . stopped : raise StoppedError ( "Cannot stamp stopped timer." ) if f . t . paused : raise PausedError ( "Cannot stamp paused timer." ) if backdate is None : ...
Mark the end of a timing interval .
380
8
9,648
def stop ( name = None , backdate = None , unique = None , keep_subdivisions = None , quick_print = None , un = None , ks = None , qp = None ) : t = timer ( ) if f . t . stopped : raise StoppedError ( "Timer already stopped." ) if backdate is None : t_stop = t else : if f . t is f . root : raise BackdateError ( "Cannot...
Mark the end of timing . Optionally performs a stamp hence accepts the same arguments .
534
17
9,649
def pause ( ) : t = timer ( ) if f . t . stopped : raise StoppedError ( "Cannot pause stopped timer." ) if f . t . paused : raise PausedError ( "Timer already paused." ) f . t . paused = True f . t . tmp_total += t - f . t . start_t f . t . start_t = None f . t . last_t = None return t
Pause the timer preventing subsequent time from accumulating in the total . Renders the timer inactive disabling other timing commands .
92
22
9,650
def resume ( ) : t = timer ( ) if f . t . stopped : raise StoppedError ( "Cannot resume stopped timer." ) if not f . t . paused : raise PausedError ( "Cannot resume timer that is not paused." ) f . t . paused = False f . t . start_t = t f . t . last_t = t return t
Resume a paused timer re - activating it . Subsequent time accumulates in the total .
81
19
9,651
def collapse_times ( ) : orig_ts = f . timer_stack orig_ls = f . loop_stack copy_ts = _copy_timer_stack ( ) copy_ls = copy . deepcopy ( f . loop_stack ) f . timer_stack = copy_ts f . loop_stack = copy_ls f . refresh_shortcuts ( ) while ( len ( f . timer_stack ) > 1 ) or f . t . in_loop : _collapse_subdivision ( ) timer...
Make copies of everything assign to global shortcuts so functions work on them extract the times then restore the running stacks .
163
22
9,652
def create_plate ( self , plate_id , description , meta_data_id , values , complement , parent_plate ) : # Make sure the plate id doesn't already exist with switch_db ( PlateDefinitionModel , db_alias = 'hyperstream' ) : try : p = PlateDefinitionModel . objects . get ( plate_id = plate_id ) if p : logging . info ( "Pla...
Create a new plate and commit it to the database
199
10
9,653
def timed_loop ( name = None , rgstr_stamps = None , save_itrs = SET [ 'SI' ] , loop_end_stamp = None , end_stamp_unique = SET [ 'UN' ] , keep_prev_subdivisions = SET [ 'KS' ] , keep_end_subdivisions = SET [ 'KS' ] , quick_print = SET [ 'QP' ] ) : return TimedLoop ( name = name , rgstr_stamps = rgstr_stamps , save_itrs...
Instantiate a TimedLoop object for measuring loop iteration timing data . Can be used with either for or while loops .
186
24
9,654
def timed_for ( iterable , name = None , rgstr_stamps = None , save_itrs = SET [ 'SI' ] , loop_end_stamp = None , end_stamp_unique = SET [ 'UN' ] , keep_prev_subdivisions = SET [ 'KS' ] , keep_end_subdivisions = SET [ 'KS' ] , quick_print = SET [ 'QP' ] ) : return TimedFor ( iterable , name = name , rgstr_stamps = rgst...
Instantiate a TimedLoop object for measuring for loop iteration timing data . Can be used only on for loops .
192
23
9,655
def write_calibration ( calib , f , loc ) : for i , node in enumerate ( [ p + '_' + s for p in [ 'pos' , 'dir' ] for s in 'xyz' ] ) : h5loc = loc + '/' + node ca = f . get_node ( h5loc ) ca . append ( calib [ : , i ] ) du = f . get_node ( loc + '/du' ) du . append ( calib [ : , 7 ] . astype ( 'u1' ) ) floor = f . get_n...
Write calibration set to file
234
5
9,656
def initialise_arrays ( group , f ) : for node in [ 'pos_x' , 'pos_y' , 'pos_z' , 'dir_x' , 'dir_y' , 'dir_z' , 'du' , 'floor' , 't0' ] : if node in [ 'floor' , 'du' ] : atom = U1_ATOM else : atom = F4_ATOM f . create_earray ( group , node , atom , ( 0 , ) , filters = FILTERS )
Create EArrays for calibrated hits
119
7
9,657
def blob_counter ( self ) : import aa # pylint: disablF0401 # noqa from ROOT import EventFile # pylint: disable F0401 try : event_file = EventFile ( self . filename ) except Exception : raise SystemExit ( "Could not open file" ) num_blobs = 0 for event in event_file : num_blobs += 1 return num_blobs
Create a blob counter .
90
5
9,658
def blob_generator ( self ) : # pylint: disable:F0401,W0612 import aa # pylint: disablF0401 # noqa from ROOT import EventFile # pylint: disable F0401 filename = self . filename log . info ( "Reading from file: {0}" . format ( filename ) ) if not os . path . exists ( filename ) : log . warning ( filename + " not availab...
Create a blob generator .
477
5
9,659
def parse_string ( self , string ) : self . log . info ( "Parsing ASCII data" ) if not string : self . log . warning ( "Empty metadata" ) return lines = string . splitlines ( ) application_data = [ ] application = lines [ 0 ] . split ( ) [ 0 ] self . log . debug ( "Reading meta information for '%s'" % application ) for...
Parse ASCII output of JPrintMeta
168
8
9,660
def _record_app_data ( self , data ) : name , revision = data [ 0 ] . split ( ) root_version = data [ 1 ] . split ( ) [ 1 ] command = b'\n' . join ( data [ 3 : ] ) . split ( b'\n' + name + b' Linux' ) [ 0 ] self . meta . append ( { 'application_name' : np . string_ ( name ) , 'revision' : np . string_ ( revision ) , 'r...
Parse raw metadata output for a single application
138
9
9,661
def get_table ( self , name = 'Meta' , h5loc = '/meta' ) : if not self . meta : return None data = defaultdict ( list ) for entry in self . meta : for key , value in entry . items ( ) : data [ key ] . append ( value ) dtypes = [ ] for key , values in data . items ( ) : max_len = max ( map ( len , values ) ) dtype = 'S{...
Convert metadata to a KM3Pipe Table .
155
11
9,662
def itermovieshash ( self ) : cur = self . _db . firstkey ( ) while cur is not None : yield cur cur = self . _db . nextkey ( cur )
Iterate over movies hash stored in the database .
40
10
9,663
def _max_retries_for_error ( self , error ) : status = error . get ( "status" ) if status == "ABORTED" and get_transactions ( ) > 0 : # Avoids retrying Conflicts when inside a transaction. return None return self . _MAX_RETRIES . get ( status )
Handles Datastore response errors according to their documentation .
72
12
9,664
def anonymous_login ( services ) : if isinstance ( services , str ) : services = [ services ] clients = { } # Initialize valid services for serv in services : try : clients [ serv ] = KNOWN_CLIENTS [ serv ] ( http_timeout = STD_TIMEOUT ) except KeyError : # No known client print ( "Error: No known client for '{}' servi...
Initialize services without authenticating to Globus Auth .
135
11
9,665
def logout ( token_dir = DEFAULT_CRED_PATH ) : for f in os . listdir ( token_dir ) : if f . endswith ( "tokens.json" ) : try : os . remove ( os . path . join ( token_dir , f ) ) except OSError as e : # Eat ENOENT (no such file/dir, tokens already deleted) only, # raise any other issue (bad permissions, etc.) if e . err...
Remove ALL tokens in the token directory . This will force re - authentication to all services .
116
18
9,666
def format_gmeta ( data , acl = None , identifier = None ) : if isinstance ( data , dict ) : if acl is None or identifier is None : raise ValueError ( "acl and identifier are required when formatting a GMetaEntry." ) if isinstance ( acl , str ) : acl = [ acl ] # "Correctly" format ACL entries into URNs prefixed_acl = [...
Format input into GMeta format suitable for ingesting into Globus Search . Formats a dictionary into a GMetaEntry . Formats a list of GMetaEntry into a GMetaList inside a GMetaIngest .
402
45
9,667
def gmeta_pop ( gmeta , info = False ) : if type ( gmeta ) is GlobusHTTPResponse : gmeta = json . loads ( gmeta . text ) elif type ( gmeta ) is str : gmeta = json . loads ( gmeta ) elif type ( gmeta ) is not dict : raise TypeError ( "gmeta must be dict, GlobusHTTPResponse, or JSON string" ) results = [ ] for res in gme...
Remove GMeta wrapping from a Globus Search result . This function can be called on the raw GlobusHTTPResponse that Search returns or a string or dictionary representation of it .
163
38
9,668
def translate_index ( index_name ) : uuid = SEARCH_INDEX_UUIDS . get ( index_name . strip ( ) . lower ( ) ) if not uuid : try : index_info = globus_sdk . SearchClient ( ) . get_index ( index_name ) . data if not isinstance ( index_info , dict ) : raise ValueError ( "Multiple UUIDs possible" ) uuid = index_info . get ( ...
Translate a known Globus Search index into the index UUID . The UUID is the proper way to access indices and will eventually be the only way . This method will return names it cannot disambiguate .
121
44
9,669
def quick_transfer ( transfer_client , source_ep , dest_ep , path_list , interval = None , retries = 10 , notify = True ) : if retries is None : retries = 0 iterations = 0 transfer = custom_transfer ( transfer_client , source_ep , dest_ep , path_list , notify = notify ) res = next ( transfer ) try : # Loop ends on Stop...
Perform a Globus Transfer and monitor for success .
245
11
9,670
def parse_json ( json_file , include_date = False ) : if json_file [ - 2 : ] == 'gz' : fh = gzip . open ( json_file , 'rt' ) else : fh = io . open ( json_file , mode = 'rt' , encoding = 'utf8' ) for line in fh : try : jj = json . loads ( line ) if type ( jj ) is not list : jj = [ jj ] for j in jj : if include_date : yi...
Yield screen_name text tuples from a json file .
259
13
9,671
def extract_tweets ( json_file ) : for screen_name , tweet_iter in groupby ( parse_json ( json_file ) , lambda x : x [ 0 ] ) : tweets = [ t [ 1 ] for t in tweet_iter ] yield screen_name , ' ' . join ( tweets )
Yield screen_name string tuples where the string is the concatenation of all tweets of this user .
68
23
9,672
def vectorize ( json_file , vec , dofit = True ) : ## CountVectorizer, efficiently. screen_names = [ x [ 0 ] for x in extract_tweets ( json_file ) ] if dofit : X = vec . fit_transform ( x [ 1 ] for x in extract_tweets ( json_file ) ) else : X = vec . transform ( x [ 1 ] for x in extract_tweets ( json_file ) ) return sc...
Return a matrix where each row corresponds to a Twitter account and each column corresponds to the number of times a term is used by that account .
108
28
9,673
def read_follower_file ( fname , min_followers = 0 , max_followers = 1e10 , blacklist = set ( ) ) : result = { } with open ( fname , 'rt' ) as f : for line in f : parts = line . split ( ) if len ( parts ) > 3 : if parts [ 1 ] . lower ( ) not in blacklist : followers = set ( int ( x ) for x in parts [ 2 : ] ) if len ( f...
Read a file of follower information and return a dictionary mapping screen_name to a set of follower ids .
157
22
9,674
def jaccard_merge ( brands , exemplars ) : scores = { } exemplar_followers = set ( ) for followers in exemplars . values ( ) : exemplar_followers |= followers for brand , followers in brands : scores [ brand ] = _jaccard ( followers , exemplar_followers ) return scores
Return the average Jaccard similarity between a brand s followers and the followers of each exemplar . We merge all exemplar followers into one big pseudo - account .
72
33
9,675
def cosine ( brands , exemplars , weighted_avg = False , sqrt = False ) : scores = { } for brand , followers in brands : if weighted_avg : scores [ brand ] = np . average ( [ _cosine ( followers , others ) for others in exemplars . values ( ) ] , weights = [ 1. / len ( others ) for others in exemplars . values ( ) ] ) ...
Return the cosine similarity betwee a brand s followers and the exemplars .
159
17
9,676
def suggest_filename ( metadata ) : if 'title' in metadata and 'track_number' in metadata : # Music Manager. suggested_filename = f"{metadata['track_number']:0>2} {metadata['title']}" elif 'title' in metadata and 'trackNumber' in metadata : # Mobile. suggested_filename = f"{metadata['trackNumber']:0>2} {metadata['title...
Generate a filename like Google for a song based on metadata .
221
13
9,677
def template_to_filepath ( template , metadata , template_patterns = None ) : path = Path ( template ) if template_patterns is None : template_patterns = TEMPLATE_PATTERNS suggested_filename = suggest_filename ( metadata ) if ( path == Path . cwd ( ) or path == Path ( '%suggested%' ) ) : filepath = Path ( suggested_fil...
Create directory structure and file name based on metadata template .
440
11
9,678
def _match_field ( field_value , pattern , ignore_case = False , normalize_values = False ) : if normalize_values : ignore_case = True normalize = normalize_value if normalize_values else lambda x : str ( x ) search = functools . partial ( re . search , flags = re . I ) if ignore_case else re . search # audio_metadata ...
Match an item metadata field value by pattern .
140
9
9,679
def _match_item ( item , any_all = any , ignore_case = False , normalize_values = False , * * kwargs ) : it = get_item_tags ( item ) return any_all ( _match_field ( get_field ( it , field ) , pattern , ignore_case = ignore_case , normalize_values = normalize_values ) for field , patterns in kwargs . items ( ) for patte...
Match items by metadata .
100
5
9,680
def exclude_items ( items , any_all = any , ignore_case = False , normalize_values = False , * * kwargs ) : if kwargs : match = functools . partial ( _match_item , any_all = any_all , ignore_case = ignore_case , normalize_values = normalize_values , * * kwargs ) return filterfalse ( match , items ) else : return iter (...
Exclude items by matching metadata .
98
7
9,681
def include_items ( items , any_all = any , ignore_case = False , normalize_values = False , * * kwargs ) : if kwargs : match = functools . partial ( _match_item , any_all = any_all , ignore_case = ignore_case , normalize_values = normalize_values , * * kwargs ) return filter ( match , items ) else : return iter ( item...
Include items by matching metadata .
97
7
9,682
def percentile ( a , q ) : if not a : return None if isinstance ( q , ( float , int ) ) : qq = [ q ] elif isinstance ( q , ( tuple , list ) ) : qq = q else : raise ValueError ( "Quantile type {} not understood" . format ( type ( q ) ) ) if isinstance ( a , ( float , int ) ) : a = [ a ] for i in range ( len ( qq ) ) : i...
Compute the qth percentile of the data along the specified axis . Simpler version than the numpy version that always flattens input arrays .
280
29
9,683
def _filter_closest ( self , lat , lon , stations ) : current_location = ( lat , lon ) closest = None closest_distance = None for station in stations : station_loc = ( station . latitude , station . longitude ) station_distance = distance . distance ( current_location , station_loc ) . km if not closest or station_dist...
Helper to filter the closest station to a given location .
97
11
9,684
async def get ( cls , websession , lat , lon ) : self = Station ( websession ) stations = await self . api . stations ( ) self . station = self . _filter_closest ( lat , lon , stations ) logger . info ( "Using %s as weather station" , self . station . local ) return self
Retrieve the nearest station .
75
6
9,685
def load_channels ( self ) : channels = [ ] # Try to get channels for channel_name in self . channel_names : channel_path = os . path . join ( self . path , "channels" ) sys . path . append ( self . path ) mod = imp . load_module ( channel_name , * imp . find_module ( channel_name , [ channel_path ] ) ) cls = getattr (...
Loads the channels and tools given the plugin path specified
392
11
9,686
def chunk_count ( swatch ) : if type ( swatch ) is dict : if 'data' in swatch : return 1 if 'swatches' in swatch : return 2 + len ( swatch [ 'swatches' ] ) else : return sum ( map ( chunk_count , swatch ) )
return the number of byte - chunks in a swatch object
66
12
9,687
def chunk_for_color ( obj ) : title = obj [ 'name' ] + '\0' title_length = len ( title ) chunk = struct . pack ( '>H' , title_length ) chunk += title . encode ( 'utf-16be' ) mode = obj [ 'data' ] [ 'mode' ] . encode ( ) values = obj [ 'data' ] [ 'values' ] color_type = obj [ 'type' ] fmt = { b'RGB' : '!fff' , b'Gray' :...
builds up a byte - chunk for a color
302
10
9,688
def chunk_for_folder ( obj ) : title = obj [ 'name' ] + '\0' title_length = len ( title ) chunk_body = struct . pack ( '>H' , title_length ) # title length chunk_body += title . encode ( 'utf-16be' ) # title chunk_head = b'\xC0\x01' # folder header chunk_head += struct . pack ( '>I' , len ( chunk_body ) ) # precede ent...
produce a byte - chunk for a folder of colors
194
11
9,689
def iter_lines ( filename ) : with open ( filename , 'rt' ) as idfile : for line in idfile : screen_name = line . strip ( ) if len ( screen_name ) > 0 : yield screen_name . split ( ) [ 0 ]
Iterate over screen names in a file one per line .
57
12
9,690
def fetch_tweets ( account_file , outfile , limit ) : print ( 'fetching tweets for accounts in' , account_file ) outf = io . open ( outfile , 'wt' ) for screen_name in iter_lines ( account_file ) : print ( '\nFetching tweets for %s' % screen_name ) for tweet in twutil . collect . tweets_for_user ( screen_name , limit )...
Fetch up to limit tweets for each account in account_file and write to outfile .
150
19
9,691
def fetch_exemplars ( keyword , outfile , n = 50 ) : list_urls = fetch_lists ( keyword , n ) print ( 'found %d lists for %s' % ( len ( list_urls ) , keyword ) ) counts = Counter ( ) for list_url in list_urls : counts . update ( fetch_list_members ( list_url ) ) # Write to file. outf = io . open ( outfile , 'wt' ) for h...
Fetch top lists matching this keyword then return Twitter screen names along with the number of different lists on which each appers ..
155
25
9,692
def _init_controlhost ( self ) : log . debug ( "Connecting to JLigier" ) self . client = Client ( self . host , self . port ) self . client . _connect ( ) log . debug ( "Subscribing to tags: {0}" . format ( self . tags ) ) for tag in self . tags . split ( ',' ) : self . client . subscribe ( tag . strip ( ) , mode = sel...
Set up the controlhost connection
113
6
9,693
def process ( self , blob ) : # self._add_process_dt() try : log . debug ( "Waiting for queue items." ) prefix , data = self . queue . get ( timeout = self . timeout ) log . debug ( "Got {0} bytes from queue." . format ( len ( data ) ) ) except Empty : log . warning ( "ControlHost timeout ({0}s) reached" . format ( sel...
Wait for the next packet and put it in the blob
133
11
9,694
def finish ( self ) : log . debug ( "Disconnecting from JLigier." ) self . client . socket . shutdown ( socket . SHUT_RDWR ) self . client . _disconnect ( )
Clean up the JLigier controlhost connection
46
10
9,695
def list_variables ( self ) : station_codes = self . _get_station_codes ( ) station_codes = self . _apply_features_filter ( station_codes ) variables = self . _list_variables ( station_codes ) if hasattr ( self , "_variables" ) and self . variables is not None : variables . intersection_update ( set ( self . variables ...
List available variables and applies any filters .
91
8
9,696
def _list_variables ( self , station_codes ) : # sample output from obs retrieval: # # DD9452D0 # HP(SRBM5) # 2013-07-22 19:30 45.97 # HT(SRBM5) # 2013-07-22 19:30 44.29 # PC(SRBM5) # 2013-07-22 19:30 36.19 # rvar = re . compile ( r"\n\s([A-Z]{2}[A-Z0-9]{0,1})\(\w+\)" ) variables = set ( ) resp = requests . post ( self...
Internal helper to list the variables for the given station codes .
234
12
9,697
def _apply_features_filter ( self , station_codes ) : # apply features filter if hasattr ( self , "features" ) and self . features is not None : station_codes = set ( station_codes ) station_codes = list ( station_codes . intersection ( set ( self . features ) ) ) return station_codes
If the features filter is set this will return the intersection of those filter items and the given station codes .
71
21
9,698
def _get_station_codes ( self , force = False ) : if not force and self . station_codes is not None : return self . station_codes state_urls = self . _get_state_urls ( ) # filter by bounding box against a shapefile state_matches = None if self . bbox : with collection ( os . path . join ( "resources" , "ne_50m_admin_1_...
Gets and caches a list of station codes optionally within a bbox .
435
15
9,699
def _monitor_task ( self ) : if self . task . state in states . UNREADY_STATES : reactor . callLater ( self . POLL_PERIOD , self . _monitor_task ) return if self . task . state == 'SUCCESS' : self . callback ( self . task . result ) elif self . task . state == 'FAILURE' : self . errback ( Failure ( self . task . result...
Wrapper that handles the actual asynchronous monitoring of the task state .
176
13