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 = [ 'data' , 'headers' , 'cookies' , 'auth' , 'allow_redirects' , 'compress' , 'chunked' ] kwargs = { k : params [ k ] for k in http_keys if k in params } query_params = params . pop ( 'params' , { } ) if app is not None : query_params [ 'app' ] = app query_params [ 'version' ] = version query_params [ 'service' ] = service response = yield from aiohttp . request ( method , url , params = query_params , * * kwargs ) return response | 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 ' 'backend before calling this function' ) from . _dialogs . report import DlgReport dlg = DlgReport ( _backends , window_title = window_title , window_icon = window_icon , traceback = traceback , issue_title = issue_title , issue_description = issue_description , parent = parent , include_log = include_log , include_sys_info = include_sys_info ) if modal : dlg . show ( ) return dlg else : dlg . exec_ ( ) | 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 , request_type = self . request_type , middleware = args ) ) ) return self | 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 , request_type = self . request_type , middleware = None ) ) ) return self | 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 = max ( len ( row ) for row in rows ) if len ( rows ) else 0 table_row = ' ' * max_row_length for i , column in enumerate ( columns ) : table_row += padding + column . rjust ( column_lengths [ i ] ) table_rows = [ table_row ] for row in rows : table_row = row . rjust ( max_row_length ) for i , column in enumerate ( columns ) : item = str ( data [ row ] [ column ] ) table_row += padding + item . rjust ( column_lengths [ i ] ) table_rows . append ( table_row ) return '\n' . join ( table_rows ) | 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 ( record . description ) ) for acc , record in objects . items ( ) ) ) | 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 ( ) self . post_run ( ) | 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 [ idx0 : i ] = _cid _mtp = 0 _cid += 1 idx0 = i t0 = times [ i ] _mtp += 1 if i == n - 1 : mtp [ idx0 : ] = _mtp cid [ idx0 : ] = _cid break return mtp , cid | 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 ( self . alphabet ) , string = string ) ) if state in self . states or state == self . TERM_STATE : raise SyntaxError ( 'Double definition of state: ' + state ) else : self . states [ state ] = [ ] for rule in rules : try : self . _add_rule ( state , rule ) except SyntaxError as err : self . states . pop ( state ) raise err | 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 SyntaxError ( 'Unexpected state: ' + rule [ 2 ] ) if not has_term : raise SyntaxError ( 'Missed terminate state' ) | 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 ) ) : symbol = string [ i ] if not string [ i ] . isspace ( ) else self . EMPTY_SYMBOL self . tape [ i ] = symbol | 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' : self . head -= 1 elif rule [ 1 ] == 'R' : self . head += 1 self . state = rule [ 2 ] | 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" . format ( repr_state = repr ( repr_state ) ) ) result += "for line in stdin:\n" result += " print(machine.execute(line))" return result | 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 ( ) try : while not self . _stop : cycle_start = timer ( ) cycle_start_cpu = process_time ( ) log . debug ( "Pumping blob #{0}" . format ( self . _cycle_count ) ) self . blob = Blob ( ) for module in self . modules : if self . blob is None : log . debug ( "Skipping {0}, due to empty blob." . format ( module . name ) ) continue if module . only_if and not module . only_if . issubset ( set ( self . blob . keys ( ) ) ) : log . debug ( "Skipping {0}, due to missing required key" "'{1}'." . format ( module . name , module . only_if ) ) continue if ( self . _cycle_count + 1 ) % module . every != 0 : log . debug ( "Skipping {0} (every {1} iterations)." . format ( module . name , module . every ) ) continue if module . blob_keys is not None : blob_to_send = Blob ( { k : self . blob [ k ] for k in module . blob_keys if k in self . blob } ) else : blob_to_send = self . blob log . debug ( "Processing {0} " . format ( module . name ) ) start = timer ( ) start_cpu = process_time ( ) new_blob = module ( blob_to_send ) if self . timeit or module . timeit : self . _timeit [ module ] [ 'process' ] . append ( timer ( ) - start ) self . _timeit [ module ] [ 'process_cpu' ] . append ( process_time ( ) - start_cpu ) if module . blob_keys is not None : if new_blob is not None : for key in new_blob . keys ( ) : self . blob [ key ] = new_blob [ key ] else : self . blob = new_blob self . _timeit [ 'cycles' ] . append ( timer ( ) - cycle_start ) self . _timeit [ 'cycles_cpu' ] . append ( process_time ( ) - cycle_start_cpu ) self . _cycle_count += 1 if cycles and self . _cycle_count >= cycles : raise StopIteration except StopIteration : log . info ( "Nothing left to pump through." ) return self . finish ( ) | 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 . _handle_ctrl_c ) with ignored ( KeyboardInterrupt ) : return self . _drain ( cycles ) | 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" + hline ) self . _stop = True | 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 ( sorted ( unused_params ) ) ) ) | 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_message ) raise SystemExit | 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 ( coords [ 0 ] , float ) : c = list ( transform ( origin , wgs84 , * coords ) ) if wrapped and c [ 0 ] < - 170 : c [ 0 ] = c [ 0 ] + 360 return c except IndexError : pass return None | 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' ] , origin , wgs84 ) new_coords = convert_coordinates ( geojson [ 'coordinates' ] , origin , wgs84 , wrapped ) if new_coords : geojson [ 'coordinates' ] = new_coords try : del geojson [ 'crs' ] except KeyError : pass return geojson | 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' , 'PRODUCT_FORMAT' , ] # grab important keys from the file for key in keys : try : meta [ key . lower ( ) ] = root . findall ( './/' + key ) [ 0 ] . text except IndexError : meta [ key . lower ( ) ] = None meta [ 'product_cloud_coverage_assessment' ] = float ( meta . pop ( 'cloud_coverage_assessment' ) ) meta [ 'sensing_orbit_number' ] = int ( meta [ 'sensing_orbit_number' ] ) # get tile list meta [ 'tiles' ] = get_tiles_list ( root . findall ( './/Product_Organisation' ) [ 0 ] ) # get available bands if root . findall ( './/Band_List' ) : bands = root . findall ( './/Band_List' ) [ 0 ] meta [ 'band_list' ] = [ ] for b in bands : band = b . text . replace ( 'B' , '' ) if len ( band ) == 1 : band = 'B' + pad ( band , 2 ) else : band = b . text meta [ 'band_list' ] . append ( band ) else : bands = root . findall ( './/Spectral_Information_List' ) [ 0 ] meta [ 'band_list' ] = [ ] for b in bands : band = b . attrib [ 'physicalBand' ] . replace ( 'B' , '' ) if len ( band ) == 1 : band = 'B' + pad ( band , 2 ) else : band = b . attrib [ 'physicalBand' ] meta [ 'band_list' ] . append ( band ) return meta | 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_shape ) # read first band of the image image = src . read ( 1 ) # create a mask of zero values mask = image == 0. # generate shapes of the mask novalue_shape = shapes ( image , mask = mask , transform = src . affine ) # generate polygons using shapely novalue_shape = [ Polygon ( s [ 'coordinates' ] [ 0 ] ) for ( s , v ) in novalue_shape ] if novalue_shape : # Make sure polygons are united # also simplify the resulting polygon union = cascaded_union ( novalue_shape ) # generates a geojson data_shape = tile_shape . difference ( union ) # If there are multipolygons, select the largest one if data_shape . geom_type == 'MultiPolygon' : areas = { p . area : i for i , p in enumerate ( data_shape ) } largest = max ( areas . keys ( ) ) data_shape = data_shape [ areas [ largest ] ] # if the polygon has interior rings, remove them if list ( data_shape . interiors ) : data_shape = Polygon ( data_shape . exterior . coords ) data_shape = data_shape . simplify ( tolerance , preserve_topology = False ) data_geojson = mapping ( data_shape ) else : data_geojson = tile_geojson # convert cooridnates to degrees return ( to_latlon ( tile_geojson , origin_espg ) , to_latlon ( data_geojson , origin_espg ) ) | 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 ( ) . name , tile [ 'path' ] ) ) meta [ 'date' ] = tile [ 'timestamp' ] . split ( 'T' ) [ 0 ] meta [ 'thumbnail' ] = '{1}/{0}/preview.jp2' . format ( tile [ 'path' ] , s3_url ) # remove unnecessary keys product . pop ( 'tiles' ) tile . pop ( 'datastrip' ) bands = product . pop ( 'band_list' ) for k , v in iteritems ( tile ) : meta [ camelcase_underscore ( k ) ] = v meta . update ( product ) # construct download links links = [ '{2}/{0}/{1}.jp2' . format ( meta [ 'path' ] , b , s3_url ) for b in bands ] meta [ 'download_links' ] = { 'aws_s3' : links } meta [ 'original_tile_meta' ] = '{0}/{1}/tileInfo.json' . format ( s3_url , meta [ 'path' ] ) def internal_latlon ( meta ) : keys = [ 'tile_origin' , 'tile_geometry' , 'tile_data_geometry' ] for key in keys : if key in meta : meta [ key ] = to_latlon ( meta [ key ] ) return meta # change coordinates to wsg4 degrees if geometry_check : if geometry_check ( meta ) : meta = get_tile_geometry_from_s3 ( meta ) else : meta = internal_latlon ( meta ) else : meta = internal_latlon ( meta ) # rename path key to aws_path meta [ 'aws_path' ] = meta . pop ( 'path' ) return meta | 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 ( algo . execute ( '' . join ( line . split ( ) ) ) , file = stdout ) elif len ( argv ) > 1 and argv [ 1 : 3 ] == [ "compile" , "turing" ] : machine = load_turing ( argv , stdin ) print ( machine . compile ( ) , file = stdout ) elif len ( argv ) == 4 and argv [ 1 : 3 ] == [ "run" , "turing" ] : machine = load_turing ( argv , stdin ) for line in stdin : print ( machine . execute ( line ) , file = stdout ) elif len ( argv ) == 2 and argv [ 1 ] == "test" : path = os . path . abspath ( os . path . dirname ( __file__ ) ) argv [ 1 ] = path pytest . main ( ) elif len ( argv ) == 2 and argv [ 1 ] == "version" : print ( "TuringMarkov" , VERSION , file = stdout ) else : print ( USAGE , file = stdout ) if not ( len ( argv ) == 2 and argv [ 1 ] == "help" ) : exit ( 1 ) | 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 . contains ( regex ) ] dt . to_csv ( sys . stdout , sep = sep ) | 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}' . format ( path , 'metadata.xml' ) , 'tiles' : get_tile_metadata_path ( '{0}/{1}' . format ( path , 'productInfo.json' ) ) } } | 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 [ name ] = { } if product_path [ 1 ] == 'metadata.xml' : products [ name ] [ 'metadata' ] = key . key if product_path [ 1 ] == 'productInfo.json' : products [ name ] [ 'tiles' ] = get_tile_metadata_path ( key . key ) return products | 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 already stopped (must open new or reset)." ) t = timer ( ) if backdate is None : t_start = t else : if f . t is f . root : raise BackdateError ( "Cannot backdate start of root timer." ) if not isinstance ( backdate , float ) : raise TypeError ( "Backdate must be type float." ) if backdate > t : raise BackdateError ( "Cannot backdate to future time." ) if backdate < f . tm1 . last_t : raise BackdateError ( "Cannot backdate start to time previous to latest stamp in parent timer." ) t_start = backdate f . t . paused = False f . t . tmp_total = 0. # (In case previously paused.) f . t . start_t = t_start f . t . last_t = t_start return t | 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 : t_stamp = t else : if not isinstance ( backdate , float ) : raise TypeError ( "Backdate must be type float." ) if backdate > t : raise BackdateError ( "Cannot backdate to future time." ) if backdate < f . t . last_t : raise BackdateError ( "Cannot backdate to time earlier than last stamp." ) t_stamp = backdate elapsed = t_stamp - f . t . last_t # Logic: default unless either arg used. if both args used, 'or' them. unique = SET [ 'UN' ] if ( unique is None and un is None ) else bool ( unique or un ) # bool(None) becomes False keep_subdivisions = SET [ 'KS' ] if ( keep_subdivisions is None and ks is None ) else bool ( keep_subdivisions or ks ) quick_print = SET [ 'QP' ] if ( quick_print is None and qp is None ) else bool ( quick_print or qp ) _stamp ( name , elapsed , unique , keep_subdivisions , quick_print ) tmp_self = timer ( ) - t f . t . self_cut += tmp_self f . t . last_t = t_stamp + tmp_self return t | 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 backdate stop of root timer." ) if not isinstance ( backdate , float ) : raise TypeError ( "Backdate must be type float." ) if backdate > t : raise BackdateError ( "Cannot backdate to future time." ) if backdate < f . t . last_t : raise BackdateError ( "Cannot backdate to time earlier than last stamp." ) t_stop = backdate unique = SET [ 'UN' ] if ( unique is None and un is None ) else bool ( unique or un ) # bool(None) becomes False keep_subdivisions = SET [ 'KS' ] if ( keep_subdivisions is None and ks is None ) else bool ( keep_subdivisions or ks ) quick_print = SET [ 'QP' ] if ( quick_print is None and qp is None ) else bool ( quick_print or qp ) if name is not None : if f . t . paused : raise PausedError ( "Cannot stamp paused timer." ) elapsed = t_stop - f . t . last_t _stamp ( name , elapsed , unique , keep_subdivisions , quick_print ) else : times_priv . assign_subdivisions ( UNASGN , keep_subdivisions ) for s in f . t . rgstr_stamps : if s not in f . s . cum : f . s . cum [ s ] = 0. f . s . order . append ( s ) if not f . t . paused : f . t . tmp_total += t_stop - f . t . start_t f . t . tmp_total -= f . t . self_cut f . t . self_cut += timer ( ) - t # AFTER subtraction from tmp_total, before dump times_priv . dump_times ( ) f . t . stopped = True if quick_print : print ( "({}) Total: {:.4f}" . format ( f . t . name , f . r . total ) ) return t | 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_pub . stop ( ) collapsed_times = f . r f . timer_stack = orig_ts # (loops throw error if not same object!) f . loop_stack = orig_ls f . refresh_shortcuts ( ) return collapsed_times | 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 ( "Plate with id {} already exists" . format ( plate_id ) ) return self . plates [ plate_id ] except DoesNotExist : pass except MultipleObjectsReturned : raise plate_definition = PlateDefinitionModel ( plate_id = plate_id , description = description , meta_data_id = meta_data_id , values = values , complement = complement , parent_plate = parent_plate ) self . add_plate ( plate_definition ) plate_definition . save ( ) return self . plates [ plate_id ] | 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 = save_itrs , loop_end_stamp = loop_end_stamp , end_stamp_unique = end_stamp_unique , keep_prev_subdivisions = keep_prev_subdivisions , keep_end_subdivisions = keep_end_subdivisions ) | 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 = rgstr_stamps , save_itrs = save_itrs , loop_end_stamp = loop_end_stamp , end_stamp_unique = end_stamp_unique , keep_prev_subdivisions = keep_prev_subdivisions , keep_end_subdivisions = keep_end_subdivisions ) | 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_node ( loc + '/floor' ) floor . append ( calib [ : , 8 ] . astype ( 'u1' ) ) t0 = f . get_node ( loc + '/t0' ) t0 . append ( calib [ : , 6 ] ) if loc == "/hits" : time = f . get_node ( loc + "/time" ) offset = len ( time ) chunk_size = len ( calib ) time [ offset - chunk_size : offset ] += calib [ : , 6 ] | 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 available: continue without it" ) try : event_file = EventFile ( filename ) except Exception : raise SystemExit ( "Could not open file" ) log . info ( "Generating blobs through new aanet API..." ) self . print ( "Reading metadata using 'JPrintMeta'" ) meta_parser = MetaParser ( filename = filename ) meta = meta_parser . get_table ( ) if meta is None : self . log . warning ( "No metadata found, this means no data provenance!" ) if self . bare : log . info ( "Skipping data conversion, only passing bare aanet data" ) for event in event_file : yield Blob ( { 'evt' : event , 'event_file' : event_file } ) else : log . info ( "Unpacking aanet header into dictionary..." ) hdr = self . _parse_header ( event_file . header ) if not hdr : log . info ( "Empty header dict found, skipping..." ) self . raw_header = None else : log . info ( "Converting Header dict to Table..." ) self . raw_header = self . _convert_header_dict_to_table ( hdr ) log . info ( "Creating HDF5Header" ) self . header = HDF5Header . from_table ( self . raw_header ) for event in event_file : log . debug ( 'Reading event...' ) blob = self . _read_event ( event , filename ) log . debug ( 'Reading header...' ) blob [ "RawHeader" ] = self . raw_header blob [ "Header" ] = self . header if meta is not None : blob [ 'Meta' ] = meta self . group_id += 1 yield blob del event_file | 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 line in lines : if application is None : self . log . debug ( "Reading meta information for '%s'" % application ) application = line . split ( ) [ 0 ] application_data . append ( line ) if line . startswith ( application + b' Linux' ) : self . _record_app_data ( application_data ) application_data = [ ] application = None | 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 ) , 'root_version' : np . string_ ( root_version ) , 'command' : np . string_ ( command ) } ) | 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{}' . format ( max_len ) dtypes . append ( ( key , dtype ) ) tab = Table ( data , dtype = dtypes , h5loc = h5loc , name = 'Meta' , h5singleton = True ) return tab | 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 '{}' service." . format ( serv ) ) except Exception : # Other issue, probably auth print ( "Error: Unable to create client for '{}' service.\n" "Anonymous access may not be allowed." . format ( serv ) ) return clients | 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 . errno != errno . ENOENT : raise | 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 = [ ] for uuid in acl : # If entry is not special value "public" and is not a URN, make URN # It is not known what the type of UUID is, so use both # This solution is known to be hacky if uuid != "public" and not uuid . lower ( ) . startswith ( "urn:" ) : prefixed_acl . append ( "urn:globus:auth:identity:" + uuid . lower ( ) ) prefixed_acl . append ( "urn:globus:groups:id:" + uuid . lower ( ) ) # Otherwise, no modification else : prefixed_acl . append ( uuid ) return { "@datatype" : "GMetaEntry" , "@version" : "2016-11-09" , "subject" : identifier , "visible_to" : prefixed_acl , "content" : data } elif isinstance ( data , list ) : return { "@datatype" : "GIngest" , "@version" : "2016-11-09" , "ingest_type" : "GMetaList" , "ingest_data" : { "@datatype" : "GMetaList" , "@version" : "2016-11-09" , "gmeta" : data } } else : raise TypeError ( "Cannot format '" + str ( type ( data ) ) + "' into GMeta." ) | 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 gmeta [ "gmeta" ] : for con in res [ "content" ] : results . append ( con ) if info : fyi = { "total_query_matches" : gmeta . get ( "total" ) } return results , fyi else : return results | 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 ( "id" , index_name ) except Exception : uuid = index_name return uuid | 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 StopIteration from generator exhaustion while True : if iterations < retries or retries == - 1 : res = transfer . send ( True ) iterations += 1 else : res = transfer . send ( False ) except StopIteration : pass if res [ "success" ] : error = "No error" else : error = "{}: {}" . format ( res . get ( "fatal_error" , { } ) . get ( "code" , "Error" ) , res . get ( "fatal_error" , { } ) . get ( "description" , "Unknown" ) ) return { "success" : res [ "success" ] , "task_id" : res [ "task_id" ] , "error" : error } | 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 : yield ( j [ 'user' ] [ 'screen_name' ] . lower ( ) , j [ 'text' ] , j [ 'created_at' ] ) else : if 'full_text' in j : # get untruncated text if available. yield ( j [ 'user' ] [ 'screen_name' ] . lower ( ) , j [ 'full_text' ] ) else : yield ( j [ 'user' ] [ 'screen_name' ] . lower ( ) , j [ 'text' ] ) except Exception as e : sys . stderr . write ( 'skipping json error: %s\n' % e ) | 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 screen_names , X | 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 ( followers ) > min_followers and len ( followers ) <= max_followers : result [ parts [ 1 ] . lower ( ) ] = followers else : print ( 'skipping exemplar' , parts [ 1 ] . lower ( ) ) return result | 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 ( ) ] ) else : scores [ brand ] = 1. * sum ( _cosine ( followers , others ) for others in exemplars . values ( ) ) / len ( exemplars ) if sqrt : scores = dict ( [ ( b , math . sqrt ( s ) ) for b , s in scores . items ( ) ] ) return scores | 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']}" elif 'title' in metadata and 'tracknumber' in metadata : # audio-metadata/mutagen. track_number = _split_number_field ( list_to_single_value ( metadata [ 'tracknumber' ] ) ) title = list_to_single_value ( metadata [ 'title' ] ) suggested_filename = f"{track_number:0>2} {title}" else : suggested_filename = f"00 {list_to_single_value(metadata.get('title', ['']))}" return _replace_invalid_characters ( suggested_filename ) | 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_filename ) elif any ( template_pattern in path . parts for template_pattern in template_patterns ) : if template . endswith ( ( '/' , '\\' ) ) : template += suggested_filename path = Path ( template . replace ( '%suggested%' , suggested_filename ) ) parts = [ ] for part in path . parts : if part == path . anchor : parts . append ( part ) else : for key in template_patterns : if ( # pragma: no branch key in part and any ( field in metadata for field in template_patterns [ key ] ) ) : field = more_itertools . first_true ( template_patterns [ key ] , pred = lambda k : k in metadata ) if key . startswith ( ( '%disc' , '%track' ) ) : number = _split_number_field ( str ( list_to_single_value ( metadata [ field ] ) ) ) if key . endswith ( '2%' ) : metadata [ field ] = number . zfill ( 2 ) else : metadata [ field ] = number part = part . replace ( key , list_to_single_value ( metadata [ field ] ) ) parts . append ( _replace_invalid_characters ( part ) ) filepath = Path ( * parts ) elif '%suggested%' in template : filepath = Path ( template . replace ( '%suggested%' , suggested_filename ) ) elif template . endswith ( ( '/' , '\\' ) ) : filepath = path / suggested_filename else : filepath = path return filepath | 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 fields contain a list of values. if isinstance ( field_value , list ) : return any ( search ( pattern , normalize ( value ) ) for value in field_value ) else : return search ( pattern , normalize ( field_value ) ) | 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 pattern in patterns ) | 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 ( items ) | 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 ( items ) | 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 ) ) : if qq [ i ] < 0. or qq [ i ] > 100. : raise ValueError ( "Percentiles must be in the range [0,100]" ) qq [ i ] /= 100. a = sorted ( flatten ( a ) ) r = [ ] for q in qq : k = ( len ( a ) - 1 ) * q f = math . floor ( k ) c = math . ceil ( k ) if f == c : r . append ( float ( a [ int ( k ) ] ) ) continue d0 = a [ int ( f ) ] * ( c - k ) d1 = a [ int ( c ) ] * ( k - f ) r . append ( float ( d0 + d1 ) ) if len ( r ) == 1 : return r [ 0 ] return r | 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_distance < closest_distance : closest = station closest_distance = station_distance return closest | 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 ( mod , channel_name . title ( ) . replace ( "_" , "" ) ) channel_id = channel_name . split ( "_" ) [ 0 ] # TODO: what about up_to_timestamp? try : channels . append ( cls ( channel_id , up_to_timestamp = None ) ) except TypeError : channels . append ( cls ( channel_id ) ) # Try to get tools if self . has_tools : tool_path = os . path . join ( self . path , "tools" ) # Create a tool channel using this path channel_id = self . channel_id_prefix + "_" + "tools" channel = ToolChannel ( channel_id , tool_path , up_to_timestamp = utcnow ( ) ) channels . append ( channel ) if self . has_assets : assset_path = os . path . join ( os . path . abspath ( self . path ) , "assets" ) channel_id = self . channel_id_prefix + "_" + "assets" channel = AssetsFileChannel ( channel_id , assset_path , up_to_timestamp = utcnow ( ) ) channels . append ( channel ) # # from . import TimeInterval # channel.streams.values()[0].window(TimeInterval.up_to_now()).items() return channels | 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' : '!f' , b'CMYK' : '!ffff' , b'LAB' : '!fff' } if mode in fmt : padded_mode = mode . decode ( ) . ljust ( 4 ) . encode ( ) chunk += struct . pack ( '!4s' , padded_mode ) # the color mode chunk += struct . pack ( fmt [ mode ] , * values ) # the color values color_types = [ 'Global' , 'Spot' , 'Process' ] if color_type in color_types : color_int = color_types . index ( color_type ) chunk += struct . pack ( '>h' , color_int ) # append swatch mode chunk = struct . pack ( '>I' , len ( chunk ) ) + chunk # prepend the chunk size return b'\x00\x01' + chunk | 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 entire chunk by folder header and size of folder chunk = chunk_head + chunk_body chunk += b'' . join ( [ chunk_for_color ( c ) for c in obj [ 'swatches' ] ] ) chunk += b'\xC0\x02' # folder terminator chunk chunk += b'\x00\x00\x00\x00' # folder terminator return chunk | 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 ) : tweet [ 'user' ] [ 'screen_name' ] = screen_name outf . write ( '%s\n' % json . dumps ( tweet , ensure_ascii = False ) ) outf . flush ( ) | 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 handle in sorted ( counts ) : outf . write ( '%s\t%d\n' % ( handle , counts [ handle ] ) ) outf . close ( ) print ( 'saved exemplars to' , outfile ) | 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 = self . subscription_mode ) log . debug ( "Controlhost initialisation done." ) | 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 ( self . timeout ) ) raise StopIteration ( "ControlHost timeout reached." ) blob [ self . key_for_prefix ] = prefix blob [ self . key_for_data ] = data return blob | 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 ) ) return list ( 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 . obs_retrieval_url , data = { "state" : "nil" , "hsa" : "nil" , "of" : "3" , "extraids" : " " . join ( station_codes ) , "sinceday" : - 1 , } , ) resp . raise_for_status ( ) list ( map ( variables . add , rvar . findall ( resp . text ) ) ) return variables | 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_states_provinces_lakes_shp.shp" , ) , "r" , ) as c : geom_matches = [ x [ "properties" ] for x in c . filter ( bbox = self . bbox ) ] state_matches = [ x [ "postal" ] if x [ "admin" ] != "Canada" else "CN" for x in geom_matches ] self . station_codes = [ ] for state_url in state_urls : if state_matches is not None : state_abbr = state_url . split ( "/" ) [ - 1 ] . split ( "." ) [ 0 ] if state_abbr not in state_matches : continue self . station_codes . extend ( self . _get_stations_for_state ( state_url ) ) if self . bbox : # retrieve metadata for all stations to properly filter them metadata = self . _get_metadata ( self . station_codes ) parsed_metadata = self . parser . _parse_metadata ( metadata ) def in_bbox ( code ) : lat = parsed_metadata [ code ] [ "latitude" ] lon = parsed_metadata [ code ] [ "longitude" ] return ( lon >= self . bbox [ 0 ] and lon <= self . bbox [ 2 ] and lat >= self . bbox [ 1 ] and lat <= self . bbox [ 3 ] ) self . station_codes = list ( filter ( in_bbox , self . station_codes ) ) return self . station_codes | 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 ) ) elif self . task . state == 'REVOKED' : self . errback ( Failure ( defer . CancelledError ( 'Task {0}' . format ( self . task . id ) ) ) ) else : self . errback ( ValueError ( 'Cannot respond to `{}` state' . format ( self . task . state ) ) ) | Wrapper that handles the actual asynchronous monitoring of the task state . | 176 | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.