idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
23,000 | def set_size ( self , size ) : buffer_size = self . _calculate_zoom_buffer_size ( size , self . _zoom_level ) self . _size = size self . _initialize_buffers ( buffer_size ) | Set the size of the map in pixels | 57 | 8 |
23,001 | def translate_point ( self , point ) : mx , my = self . get_center_offset ( ) if self . _zoom_level == 1.0 : return point [ 0 ] + mx , point [ 1 ] + my else : return int ( round ( ( point [ 0 ] + mx ) ) * self . _real_ratio_x ) , int ( round ( ( point [ 1 ] + my ) * self . _real_ratio_y ) ) | Translate world coordinates and return screen coordinates . Respects zoom level | 105 | 13 |
23,002 | def translate_points ( self , points ) : retval = list ( ) append = retval . append sx , sy = self . get_center_offset ( ) if self . _zoom_level == 1.0 : for c in points : append ( ( c [ 0 ] + sx , c [ 1 ] + sy ) ) else : rx = self . _real_ratio_x ry = self . _real_ratio_y for c in points : append ( ( int ( round ( ( c [ 0 ] + sx ) * rx ) ) , int ( round ( ( c [ 1 ] + sy ) * ry ) ) ) ) return retval | Translate coordinates and return screen coordinates | 148 | 7 |
23,003 | def _render_map ( self , surface , rect , surfaces ) : self . _tile_queue = self . data . process_animation_queue ( self . _tile_view ) self . _tile_queue and self . _flush_tile_queue ( self . _buffer ) # TODO: could maybe optimize to remove just the edges, ideally by drawing lines # if not self.anchored_view: # surface.fill(self._clear_color, self._previous_blit) if not self . _anchored_view : self . _clear_surface ( surface , self . _previous_blit ) offset = - self . _x_offset + rect . left , - self . _y_offset + rect . top with surface_clipping_context ( surface , rect ) : self . _previous_blit = surface . blit ( self . _buffer , offset ) if surfaces : surfaces_offset = - offset [ 0 ] , - offset [ 1 ] self . _draw_surfaces ( surface , surfaces_offset , surfaces ) | Render the map and optional surfaces to destination surface | 228 | 9 |
23,004 | def _clear_surface ( self , surface , rect = None ) : clear_color = self . _rgb_clear_color if self . _clear_color is None else self . _clear_color surface . fill ( clear_color , rect ) | Clear the buffer taking in account colorkey or alpha | 54 | 10 |
23,005 | def _draw_surfaces ( self , surface , offset , surfaces ) : surface_blit = surface . blit ox , oy = offset left , top = self . _tile_view . topleft hit = self . _layer_quadtree . hit get_tile = self . data . get_tile_image tile_layers = tuple ( self . data . visible_tile_layers ) dirty = list ( ) dirty_append = dirty . append # TODO: check to avoid sorting overhead # sort layers, then the y value def sprite_sort ( i ) : return i [ 2 ] , i [ 1 ] [ 1 ] + i [ 0 ] . get_height ( ) surfaces . sort ( key = sprite_sort ) layer_getter = itemgetter ( 2 ) for layer , group in groupby ( surfaces , layer_getter ) : del dirty [ : ] for i in group : try : flags = i [ 3 ] except IndexError : dirty_append ( surface_blit ( i [ 0 ] , i [ 1 ] ) ) else : dirty_append ( surface_blit ( i [ 0 ] , i [ 1 ] , None , flags ) ) # TODO: make set of covered tiles, in the case where a cluster # of sprite surfaces causes excessive over tile overdrawing for dirty_rect in dirty : for r in hit ( dirty_rect . move ( ox , oy ) ) : x , y , tw , th = r for l in [ i for i in tile_layers if gt ( i , layer ) ] : if self . tall_sprites and l == layer + 1 : if y - oy + th <= dirty_rect . bottom - self . tall_sprites : continue tile = get_tile ( x // tw + left , y // th + top , l ) tile and surface_blit ( tile , ( x - ox , y - oy ) ) | Draw surfaces onto buffer then redraw tiles that cover them | 408 | 11 |
23,006 | def _queue_edge_tiles ( self , dx , dy ) : v = self . _tile_view tw , th = self . data . tile_size self . _tile_queue = iter ( [ ] ) def append ( rect ) : self . _tile_queue = chain ( self . _tile_queue , self . data . get_tile_images_by_rect ( rect ) ) # TODO: optimize so fill is only used when map is smaller than buffer self . _clear_surface ( self . _buffer , ( ( rect [ 0 ] - v . left ) * tw , ( rect [ 1 ] - v . top ) * th , rect [ 2 ] * tw , rect [ 3 ] * th ) ) if dx > 0 : # right side append ( ( v . right - 1 , v . top , dx , v . height ) ) elif dx < 0 : # left side append ( ( v . left , v . top , - dx , v . height ) ) if dy > 0 : # bottom side append ( ( v . left , v . bottom - 1 , v . width , dy ) ) elif dy < 0 : # top side append ( ( v . left , v . top , v . width , - dy ) ) | Queue edge tiles and clear edge areas on buffer if needed | 268 | 11 |
23,007 | def _create_buffers ( self , view_size , buffer_size ) : requires_zoom_buffer = not view_size == buffer_size self . _zoom_buffer = None if self . _clear_color is None : if requires_zoom_buffer : self . _zoom_buffer = Surface ( view_size ) self . _buffer = Surface ( buffer_size ) elif self . _clear_color == self . _rgba_clear_color : if requires_zoom_buffer : self . _zoom_buffer = Surface ( view_size , flags = pygame . SRCALPHA ) self . _buffer = Surface ( buffer_size , flags = pygame . SRCALPHA ) self . data . convert_surfaces ( self . _buffer , True ) elif self . _clear_color is not self . _rgb_clear_color : if requires_zoom_buffer : self . _zoom_buffer = Surface ( view_size , flags = pygame . RLEACCEL ) self . _zoom_buffer . set_colorkey ( self . _clear_color ) self . _buffer = Surface ( buffer_size , flags = pygame . RLEACCEL ) self . _buffer . set_colorkey ( self . _clear_color ) self . _buffer . fill ( self . _clear_color ) | Create the buffers taking in account pixel alpha or colorkey | 299 | 11 |
23,008 | def reload_animations ( self ) : self . _update_time ( ) self . _animation_queue = list ( ) self . _tracked_gids = set ( ) self . _animation_map = dict ( ) for gid , frame_data in self . get_animations ( ) : self . _tracked_gids . add ( gid ) frames = list ( ) for frame_gid , frame_duration in frame_data : image = self . _get_tile_image_by_id ( frame_gid ) frames . append ( AnimationFrame ( image , frame_duration ) ) # the following line is slow when loading maps, but avoids overhead when rendering # positions = set(self.tmx.get_tile_locations_by_gid(gid)) # ideally, positions would be populated with all the known # locations of an animation, but searching for their locations # is slow. so it will be updated as the map is drawn. positions = set ( ) ani = AnimationToken ( positions , frames , self . _last_time ) self . _animation_map [ gid ] = ani heappush ( self . _animation_queue , ani ) | Reload animation information | 263 | 4 |
23,009 | def get_tile_image ( self , x , y , l ) : # disabled for now, re-enable when support for generic maps is restored # # since the tile has been queried, assume it wants to be checked # # for animations sometime in the future # if self._animation_queue: # self._tracked_tiles.add((x, y, l)) try : # animated, so return the correct frame return self . _animated_tile [ ( x , y , l ) ] except KeyError : # not animated, so return surface from data, if any return self . _get_tile_image ( x , y , l ) | Get a tile image respecting current animations | 140 | 7 |
23,010 | def get_tile_images_by_rect ( self , rect ) : x1 , y1 , x2 , y2 = rect_to_bb ( rect ) for layer in self . visible_tile_layers : for y , x in product ( range ( y1 , y2 + 1 ) , range ( x1 , x2 + 1 ) ) : tile = self . get_tile_image ( x , y , layer ) if tile : yield x , y , layer , tile | Given a 2d area return generator of tile images inside | 105 | 11 |
23,011 | def convert_surfaces ( self , parent , alpha = False ) : images = list ( ) for i in self . tmx . images : try : if alpha : images . append ( i . convert_alpha ( parent ) ) else : images . append ( i . convert ( parent ) ) except AttributeError : images . append ( None ) self . tmx . images = images | Convert all images in the data to match the parent | 80 | 11 |
23,012 | def visible_object_layers ( self ) : return ( layer for layer in self . tmx . visible_layers if isinstance ( layer , pytmx . TiledObjectGroup ) ) | This must return layer objects | 42 | 5 |
23,013 | def get_tile_images_by_rect ( self , rect ) : def rev ( seq , start , stop ) : if start < 0 : start = 0 return enumerate ( seq [ start : stop + 1 ] , start ) x1 , y1 , x2 , y2 = rect_to_bb ( rect ) images = self . tmx . images layers = self . tmx . layers at = self . _animated_tile tracked_gids = self . _tracked_gids anim_map = self . _animation_map track = bool ( self . _animation_queue ) for l in self . tmx . visible_tile_layers : for y , row in rev ( layers [ l ] . data , y1 , y2 ) : for x , gid in [ i for i in rev ( row , x1 , x2 ) if i [ 1 ] ] : # since the tile has been queried, assume it wants to be checked # for animations sometime in the future if track and gid in tracked_gids : anim_map [ gid ] . positions . add ( ( x , y , l ) ) try : # animated, so return the correct frame yield x , y , l , at [ ( x , y , l ) ] except KeyError : # not animated, so return surface from data, if any yield x , y , l , images [ gid ] | Speed up data access | 302 | 4 |
23,014 | def move_back ( self , dt ) : self . _position = self . _old_position self . rect . topleft = self . _position self . feet . midbottom = self . rect . midbottom | If called after an update the sprite can move back | 47 | 10 |
23,015 | def handle_input ( self ) : poll = pygame . event . poll event = poll ( ) while event : if event . type == QUIT : self . running = False break elif event . type == KEYDOWN : if event . key == K_ESCAPE : self . running = False break elif event . key == K_EQUALS : self . map_layer . zoom += .25 elif event . key == K_MINUS : value = self . map_layer . zoom - .25 if value > 0 : self . map_layer . zoom = value # this will be handled if the window is resized elif event . type == VIDEORESIZE : init_screen ( event . w , event . h ) self . map_layer . set_size ( ( event . w , event . h ) ) event = poll ( ) # using get_pressed is slightly less accurate than testing for events # but is much easier to use. pressed = pygame . key . get_pressed ( ) if pressed [ K_UP ] : self . hero . velocity [ 1 ] = - HERO_MOVE_SPEED elif pressed [ K_DOWN ] : self . hero . velocity [ 1 ] = HERO_MOVE_SPEED else : self . hero . velocity [ 1 ] = 0 if pressed [ K_LEFT ] : self . hero . velocity [ 0 ] = - HERO_MOVE_SPEED elif pressed [ K_RIGHT ] : self . hero . velocity [ 0 ] = HERO_MOVE_SPEED else : self . hero . velocity [ 0 ] = 0 | Handle pygame input events | 341 | 5 |
23,016 | def update ( self , dt ) : self . group . update ( dt ) # check if the sprite's feet are colliding with wall # sprite must have a rect called feet, and move_back method, # otherwise this will fail for sprite in self . group . sprites ( ) : if sprite . feet . collidelist ( self . walls ) > - 1 : sprite . move_back ( dt ) | Tasks that occur over time should be handled here | 87 | 10 |
23,017 | def run ( self ) : clock = pygame . time . Clock ( ) self . running = True from collections import deque times = deque ( maxlen = 30 ) try : while self . running : dt = clock . tick ( ) / 1000. times . append ( clock . get_fps ( ) ) # print(sum(times)/len(times)) self . handle_input ( ) self . update ( dt ) self . draw ( screen ) pygame . display . flip ( ) except KeyboardInterrupt : self . running = False | Run the game loop | 115 | 4 |
23,018 | def draw ( self , surface ) : ox , oy = self . _map_layer . get_center_offset ( ) new_surfaces = list ( ) spritedict = self . spritedict gl = self . get_layer_of_sprite new_surfaces_append = new_surfaces . append for spr in self . sprites ( ) : new_rect = spr . rect . move ( ox , oy ) try : new_surfaces_append ( ( spr . image , new_rect , gl ( spr ) , spr . blendmode ) ) except AttributeError : # generally should only fail when no blendmode available new_surfaces_append ( ( spr . image , new_rect , gl ( spr ) ) ) spritedict [ spr ] = new_rect self . lostsprites = [ ] return self . _map_layer . draw ( surface , surface . get_rect ( ) , new_surfaces ) | Draw all sprites and map onto the surface | 203 | 8 |
23,019 | def center ( self , coords ) : x , y = [ round ( i , 0 ) for i in coords ] self . view_rect . center = x , y tw , th = self . data . tile_size left , ox = divmod ( x , tw ) top , oy = divmod ( y , th ) vec = int ( ox / 2 ) , int ( oy ) iso = vector2_to_iso ( vec ) self . _x_offset = iso [ 0 ] self . _y_offset = iso [ 1 ] print ( self . _tile_view . size ) print ( self . _buffer . get_size ( ) ) # center the buffer on the screen self . _x_offset += ( self . _buffer . get_width ( ) - self . view_rect . width ) // 2 self . _y_offset += ( self . _buffer . get_height ( ) - self . view_rect . height ) // 4 # adjust the view if the view has changed without a redraw dx = int ( left - self . _tile_view . left ) dy = int ( top - self . _tile_view . top ) view_change = max ( abs ( dx ) , abs ( dy ) ) # force redraw every time: edge queuing not supported yet self . _redraw_cutoff = 0 if view_change and ( view_change <= self . _redraw_cutoff ) : self . _buffer . scroll ( - dx * tw , - dy * th ) self . _tile_view . move_ip ( dx , dy ) self . _queue_edge_tiles ( dx , dy ) self . _flush_tile_queue ( ) elif view_change > self . _redraw_cutoff : # logger.info('scrolling too quickly. redraw forced') self . _tile_view . move_ip ( dx , dy ) self . redraw_tiles ( ) | center the map on a map pixel | 416 | 7 |
23,020 | def get_odoo_args ( self , ctx ) : config = ctx . params . get ( "config" ) addons_path = ctx . params . get ( "addons_path" ) database = ctx . params . get ( "database" ) log_level = ctx . params . get ( "log_level" ) logfile = ctx . params . get ( "logfile" ) odoo_args = [ ] if config : odoo_args . extend ( [ "--config" , config ] ) if addons_path : odoo_args . extend ( [ "--addons-path" , addons_path ] ) if database : odoo_args . extend ( [ "--database" , database ] ) if log_level : odoo_args . extend ( [ "--log-level" , log_level ] ) if logfile : odoo_args . extend ( [ "--logfile" , logfile ] ) return odoo_args | Return a list of Odoo command line arguments from the Click context . | 214 | 14 |
23,021 | def make_query ( search_term , querytype = 'AdvancedKeywordQuery' ) : assert querytype in { 'HoldingsQuery' , 'ExpTypeQuery' , 'AdvancedKeywordQuery' , 'StructureIdQuery' , 'ModifiedStructuresQuery' , 'AdvancedAuthorQuery' , 'MotifQuery' , 'NoLigandQuery' , 'PubmedIdQuery' } , 'Query type %s not supported yet' % querytype query_params = dict ( ) query_params [ 'queryType' ] = querytype if querytype == 'AdvancedKeywordQuery' : query_params [ 'description' ] = 'Text Search for: ' + search_term query_params [ 'keywords' ] = search_term elif querytype == 'NoLigandQuery' : query_params [ 'haveLigands' ] = 'yes' elif querytype == 'AdvancedAuthorQuery' : query_params [ 'description' ] = 'Author Name: ' + search_term query_params [ 'searchType' ] = 'All Authors' query_params [ 'audit_author.name' ] = search_term query_params [ 'exactMatch' ] = 'false' elif querytype == 'MotifQuery' : query_params [ 'description' ] = 'Motif Query For: ' + search_term query_params [ 'motif' ] = search_term # search for a specific structure elif querytype in [ 'StructureIdQuery' , 'ModifiedStructuresQuery' ] : query_params [ 'structureIdList' ] = search_term elif querytype == 'ExpTypeQuery' : query_params [ 'experimentalMethod' ] = search_term query_params [ 'description' ] = 'Experimental Method Search : Experimental Method=' + search_term query_params [ 'mvStructure.expMethod.value' ] = search_term elif querytype == 'PubmedIdQuery' : query_params [ 'description' ] = 'Pubmed Id Search for Pubmed Id ' + search_term query_params [ 'pubMedIdList' ] = search_term scan_params = dict ( ) scan_params [ 'orgPdbQuery' ] = query_params return scan_params | Repackage strings into a search dictionary | 493 | 8 |
23,022 | def do_protsym_search ( point_group , min_rmsd = 0.0 , max_rmsd = 7.0 ) : query_params = dict ( ) query_params [ 'queryType' ] = 'PointGroupQuery' query_params [ 'rMSDComparator' ] = 'between' query_params [ 'pointGroup' ] = point_group query_params [ 'rMSDMin' ] = min_rmsd query_params [ 'rMSDMax' ] = max_rmsd scan_params = dict ( ) scan_params [ 'orgPdbQuery' ] = query_params idlist = do_search ( scan_params ) return idlist | Performs a protein symmetry search of the PDB | 155 | 10 |
23,023 | def get_all ( ) : url = 'http://www.rcsb.org/pdb/rest/getCurrent' req = urllib . request . Request ( url ) f = urllib . request . urlopen ( req ) result = f . read ( ) assert result kk = str ( result ) p = re . compile ( 'structureId=\"...."' ) matches = p . findall ( str ( result ) ) out = list ( ) for item in matches : out . append ( item [ - 5 : - 1 ] ) return out | Return a list of all PDB entries currently in the RCSB Protein Data Bank | 119 | 17 |
23,024 | def get_info ( pdb_id , url_root = 'http://www.rcsb.org/pdb/rest/describeMol?structureId=' ) : url = url_root + pdb_id req = urllib . request . Request ( url ) f = urllib . request . urlopen ( req ) result = f . read ( ) assert result out = xmltodict . parse ( result , process_namespaces = True ) return out | Look up all information about a given PDB ID | 105 | 10 |
23,025 | def get_pdb_file ( pdb_id , filetype = 'pdb' , compression = False ) : full_url = "https://files.rcsb.org/download/" full_url += pdb_id if ( filetype == 'structfact' ) : full_url += "-sf.cif" else : full_url += "." + filetype if compression : full_url += ".gz" else : pass req = urllib . request . Request ( full_url ) f = urllib . request . urlopen ( req ) result = f . read ( ) if not compression : result = result . decode ( 'ascii' ) else : pass return result | Get the full PDB file associated with a PDB_ID | 150 | 13 |
23,026 | def get_all_info ( pdb_id ) : out = to_dict ( get_info ( pdb_id ) ) [ 'molDescription' ] [ 'structureId' ] out = remove_at_sign ( out ) return out | A wrapper for get_info that cleans up the output slighly | 54 | 14 |
23,027 | def get_raw_blast ( pdb_id , output_form = 'HTML' , chain_id = 'A' ) : url_root = 'http://www.rcsb.org/pdb/rest/getBlastPDB2?structureId=' url = url_root + pdb_id + '&chainId=' + chain_id + '&outputFormat=' + output_form req = urllib . request . Request ( url ) f = urllib . request . urlopen ( req ) result = f . read ( ) result = result . decode ( 'unicode_escape' ) assert result return result | Look up full BLAST page for a given PDB ID | 138 | 12 |
23,028 | def parse_blast ( blast_string ) : soup = BeautifulSoup ( str ( blast_string ) , "html.parser" ) all_blasts = list ( ) all_blast_ids = list ( ) pattern = '></a>....:' prog = re . compile ( pattern ) for item in soup . find_all ( 'pre' ) : if len ( item . find_all ( 'a' ) ) == 1 : all_blasts . append ( item ) blast_id = re . findall ( pattern , str ( item ) ) [ 0 ] [ - 5 : - 1 ] all_blast_ids . append ( blast_id ) out = ( all_blast_ids , all_blasts ) return out | Clean up HTML BLAST results | 156 | 6 |
23,029 | def get_blast2 ( pdb_id , chain_id = 'A' , output_form = 'HTML' ) : raw_results = get_raw_blast ( pdb_id , chain_id = chain_id , output_form = output_form ) out = parse_blast ( raw_results ) return out | Alternative way to look up BLAST for a given PDB ID . This function is a wrapper for get_raw_blast and parse_blast | 71 | 29 |
23,030 | def describe_pdb ( pdb_id ) : out = get_info ( pdb_id , url_root = 'http://www.rcsb.org/pdb/rest/describePDB?structureId=' ) out = to_dict ( out ) out = remove_at_sign ( out [ 'PDBdescription' ] [ 'PDB' ] ) return out | Get description and metadata of a PDB entry | 85 | 9 |
23,031 | def get_entity_info ( pdb_id ) : out = get_info ( pdb_id , url_root = 'http://www.rcsb.org/pdb/rest/getEntityInfo?structureId=' ) out = to_dict ( out ) return remove_at_sign ( out [ 'entityInfo' ] [ 'PDB' ] ) | Return pdb id information | 81 | 5 |
23,032 | def get_ligands ( pdb_id ) : out = get_info ( pdb_id , url_root = 'http://www.rcsb.org/pdb/rest/ligandInfo?structureId=' ) out = to_dict ( out ) return remove_at_sign ( out [ 'structureId' ] ) | Return ligands of given PDB ID | 75 | 8 |
23,033 | def get_gene_onto ( pdb_id ) : out = get_info ( pdb_id , url_root = 'http://www.rcsb.org/pdb/rest/goTerms?structureId=' ) out = to_dict ( out ) if not out [ 'goTerms' ] : return None out = remove_at_sign ( out [ 'goTerms' ] ) return out | Return ligands of given PDB_ID | 93 | 9 |
23,034 | def get_seq_cluster ( pdb_id_chain ) : url_root = 'http://www.rcsb.org/pdb/rest/sequenceCluster?structureId=' out = get_info ( pdb_id_chain , url_root = url_root ) out = to_dict ( out ) return remove_at_sign ( out [ 'sequenceCluster' ] ) | Get the sequence cluster of a PDB ID plus a pdb_id plus a chain | 88 | 18 |
23,035 | def get_pfam ( pdb_id ) : out = get_info ( pdb_id , url_root = 'http://www.rcsb.org/pdb/rest/hmmer?structureId=' ) out = to_dict ( out ) if not out [ 'hmmer3' ] : return dict ( ) return remove_at_sign ( out [ 'hmmer3' ] ) | Return PFAM annotations of given PDB_ID | 89 | 10 |
23,036 | def get_clusters ( pdb_id ) : out = get_info ( pdb_id , url_root = 'http://www.rcsb.org/pdb/rest/representatives?structureId=' ) out = to_dict ( out ) return remove_at_sign ( out [ 'representatives' ] ) | Return cluster related web services of given PDB_ID | 73 | 11 |
23,037 | def find_results_gen ( search_term , field = 'title' ) : scan_params = make_query ( search_term , querytype = 'AdvancedKeywordQuery' ) search_result_ids = do_search ( scan_params ) all_titles = [ ] for pdb_result in search_result_ids : result = describe_pdb ( pdb_result ) if field in result . keys ( ) : yield result [ field ] | Return a generator of the results returned by a search of the protein data bank . This generator is used internally . | 99 | 22 |
23,038 | def parse_results_gen ( search_term , field = 'title' , max_results = 100 , sleep_time = .1 ) : if max_results * sleep_time > 30 : warnings . warn ( "Because of API limitations, this function\ will take at least " + str ( max_results * sleep_time ) + " seconds to return results.\ If you need greater speed, try modifying the optional argument sleep_time=.1, (although \ this may cause the search to time out)" ) all_data_raw = find_results_gen ( search_term , field = field ) all_data = list ( ) while len ( all_data ) < max_results : all_data . append ( all_data_raw . send ( None ) ) time . sleep ( sleep_time ) return all_data | Query the PDB with a search term and field while respecting the query frequency limitations of the API . | 178 | 20 |
23,039 | def find_papers ( search_term , * * kwargs ) : all_papers = parse_results_gen ( search_term , field = 'title' , * * kwargs ) return remove_dupes ( all_papers ) | Return an ordered list of the top papers returned by a keyword search of the RCSB PDB | 52 | 20 |
23,040 | def find_authors ( search_term , * * kwargs ) : all_individuals = parse_results_gen ( search_term , field = 'citation_authors' , * * kwargs ) full_author_list = [ ] for individual in all_individuals : individual = individual . replace ( '.,' , '.;' ) author_list_clean = [ x . strip ( ) for x in individual . split ( ';' ) ] full_author_list += author_list_clean out = list ( chain . from_iterable ( repeat ( ii , c ) for ii , c in Counter ( full_author_list ) . most_common ( ) ) ) return remove_dupes ( out ) | Return an ordered list of the top authors returned by a keyword search of the RCSB PDB | 157 | 20 |
23,041 | def list_taxa ( pdb_list , sleep_time = .1 ) : if len ( pdb_list ) * sleep_time > 30 : warnings . warn ( "Because of API limitations, this function\ will take at least " + str ( len ( pdb_list ) * sleep_time ) + " seconds to return results.\ If you need greater speed, try modifying the optional argument sleep_time=.1, (although \ this may cause the search to time out)" ) taxa = [ ] for pdb_id in pdb_list : all_info = get_all_info ( pdb_id ) species_results = walk_nested_dict ( all_info , 'Taxonomy' , maxdepth = 25 , outputs = [ ] ) first_result = walk_nested_dict ( species_results , '@name' , outputs = [ ] ) if first_result : taxa . append ( first_result [ - 1 ] ) else : taxa . append ( 'Unknown' ) time . sleep ( sleep_time ) return taxa | Given a list of PDB IDs look up their associated species | 232 | 12 |
23,042 | def list_types ( pdb_list , sleep_time = .1 ) : if len ( pdb_list ) * sleep_time > 30 : warnings . warn ( "Because of API limitations, this function\ will take at least " + str ( len ( pdb_list ) * sleep_time ) + " seconds to return results.\ If you need greater speed, try modifying the optional argument sleep_time=.1, (although \ this may cause the search to time out)" ) infotypes = [ ] for pdb_id in pdb_list : all_info = get_all_info ( pdb_id ) type_results = walk_nested_dict ( all_info , '@type' , maxdepth = 25 , outputs = [ ] ) if type_results : infotypes . append ( type_results [ - 1 ] ) else : infotypes . append ( 'Unknown' ) time . sleep ( sleep_time ) return infotypes | Given a list of PDB IDs look up their associated structure type | 206 | 13 |
23,043 | def remove_dupes ( list_with_dupes ) : visited = set ( ) visited_add = visited . add out = [ entry for entry in list_with_dupes if not ( entry in visited or visited_add ( entry ) ) ] return out | Remove duplicate entries from a list while preserving order | 56 | 9 |
23,044 | def download_file_from_google_drive ( file_id , dest_path , overwrite = False , unzip = False , showsize = False ) : destination_directory = dirname ( dest_path ) if not exists ( destination_directory ) : makedirs ( destination_directory ) if not exists ( dest_path ) or overwrite : session = requests . Session ( ) print ( 'Downloading {} into {}... ' . format ( file_id , dest_path ) , end = '' ) stdout . flush ( ) response = session . get ( GoogleDriveDownloader . DOWNLOAD_URL , params = { 'id' : file_id } , stream = True ) token = GoogleDriveDownloader . _get_confirm_token ( response ) if token : params = { 'id' : file_id , 'confirm' : token } response = session . get ( GoogleDriveDownloader . DOWNLOAD_URL , params = params , stream = True ) if showsize : print ( ) # Skip to the next line current_download_size = [ 0 ] GoogleDriveDownloader . _save_response_content ( response , dest_path , showsize , current_download_size ) print ( 'Done.' ) if unzip : try : print ( 'Unzipping...' , end = '' ) stdout . flush ( ) with zipfile . ZipFile ( dest_path , 'r' ) as z : z . extractall ( destination_directory ) print ( 'Done.' ) except zipfile . BadZipfile : warnings . warn ( 'Ignoring `unzip` since "{}" does not look like a valid zip file' . format ( file_id ) ) | Downloads a shared file from google drive into a given folder . Optionally unzips it . | 358 | 20 |
23,045 | def handle_connection ( stream ) : ws = WSConnection ( ConnectionType . SERVER ) # events is a generator that yields websocket event objects. Usually you # would say `for event in ws.events()`, but the synchronous nature of this # server requires us to use next(event) instead so that we can interleave # the network I/O. events = ws . events ( ) running = True while running : # 1) Read data from network in_data = stream . recv ( RECEIVE_BYTES ) print ( 'Received {} bytes' . format ( len ( in_data ) ) ) ws . receive_data ( in_data ) # 2) Get next wsproto event try : event = next ( events ) except StopIteration : print ( 'Client connection dropped unexpectedly' ) return # 3) Handle event if isinstance ( event , Request ) : # Negotiate new WebSocket connection print ( 'Accepting WebSocket upgrade' ) out_data = ws . send ( AcceptConnection ( ) ) elif isinstance ( event , CloseConnection ) : # Print log message and break out print ( 'Connection closed: code={}/{} reason={}' . format ( event . code . value , event . code . name , event . reason ) ) out_data = ws . send ( event . response ( ) ) running = False elif isinstance ( event , TextMessage ) : # Reverse text and send it back to wsproto print ( 'Received request and sending response' ) out_data = ws . send ( Message ( data = event . data [ : : - 1 ] ) ) elif isinstance ( event , Ping ) : # wsproto handles ping events for you by placing a pong frame in # the outgoing buffer. You should not call pong() unless you want to # send an unsolicited pong frame. print ( 'Received ping and sending pong' ) out_data = ws . send ( event . response ( ) ) else : print ( 'Unknown event: {!r}' . format ( event ) ) # 4) Send data from wsproto to network print ( 'Sending {} bytes' . format ( len ( out_data ) ) ) stream . send ( out_data ) | Handle a connection . | 492 | 4 |
23,046 | def receive_data ( self , data ) : # type: (bytes) -> None if data is None : # "If _The WebSocket Connection is Closed_ and no Close control # frame was received by the endpoint (such as could occur if the # underlying transport connection is lost), _The WebSocket # Connection Close Code_ is considered to be 1006." self . _events . append ( CloseConnection ( code = CloseReason . ABNORMAL_CLOSURE ) ) self . _state = ConnectionState . CLOSED return if self . state in ( ConnectionState . OPEN , ConnectionState . LOCAL_CLOSING ) : self . _proto . receive_bytes ( data ) elif self . state is ConnectionState . CLOSED : raise LocalProtocolError ( "Connection already closed." ) | Pass some received data to the connection for handling . | 168 | 10 |
23,047 | def events ( self ) : # type: () -> Generator[Event, None, None] while self . _events : yield self . _events . popleft ( ) try : for frame in self . _proto . received_frames ( ) : if frame . opcode is Opcode . PING : assert frame . frame_finished and frame . message_finished yield Ping ( payload = frame . payload ) elif frame . opcode is Opcode . PONG : assert frame . frame_finished and frame . message_finished yield Pong ( payload = frame . payload ) elif frame . opcode is Opcode . CLOSE : code , reason = frame . payload if self . state is ConnectionState . LOCAL_CLOSING : self . _state = ConnectionState . CLOSED else : self . _state = ConnectionState . REMOTE_CLOSING yield CloseConnection ( code = code , reason = reason ) elif frame . opcode is Opcode . TEXT : yield TextMessage ( data = frame . payload , frame_finished = frame . frame_finished , message_finished = frame . message_finished , ) elif frame . opcode is Opcode . BINARY : yield BytesMessage ( data = frame . payload , frame_finished = frame . frame_finished , message_finished = frame . message_finished , ) except ParseFailed as exc : yield CloseConnection ( code = exc . code , reason = str ( exc ) ) | Return a generator that provides any events that have been generated by protocol activity . | 308 | 15 |
23,048 | def server_extensions_handshake ( requested , supported ) : # type: (List[str], List[Extension]) -> Optional[bytes] accepts = { } for offer in requested : name = offer . split ( ";" , 1 ) [ 0 ] . strip ( ) for extension in supported : if extension . name == name : accept = extension . accept ( offer ) if accept is True : accepts [ extension . name ] = True elif accept is not False and accept is not None : accepts [ extension . name ] = accept . encode ( "ascii" ) if accepts : extensions = [ ] for name , params in accepts . items ( ) : if params is True : extensions . append ( name . encode ( "ascii" ) ) else : # py34 annoyance: doesn't support bytestring formatting params = params . decode ( "ascii" ) if params == "" : extensions . append ( ( "%s" % ( name ) ) . encode ( "ascii" ) ) else : extensions . append ( ( "%s; %s" % ( name , params ) ) . encode ( "ascii" ) ) return b", " . join ( extensions ) return None | Agree on the extensions to use returning an appropriate header value . | 254 | 13 |
23,049 | def initiate_upgrade_connection ( self , headers , path ) : # type: (List[Tuple[bytes, bytes]], str) -> None if self . client : raise LocalProtocolError ( "Cannot initiate an upgrade connection when acting as the client" ) upgrade_request = h11 . Request ( method = b"GET" , target = path , headers = headers ) h11_client = h11 . Connection ( h11 . CLIENT ) self . receive_data ( h11_client . send ( upgrade_request ) ) | Initiate an upgrade connection . | 115 | 7 |
23,050 | def send ( self , event ) : # type(Event) -> bytes data = b"" if isinstance ( event , Request ) : data += self . _initiate_connection ( event ) elif isinstance ( event , AcceptConnection ) : data += self . _accept ( event ) elif isinstance ( event , RejectConnection ) : data += self . _reject ( event ) elif isinstance ( event , RejectData ) : data += self . _send_reject_data ( event ) else : raise LocalProtocolError ( "Event {} cannot be sent during the handshake" . format ( event ) ) return data | Send an event to the remote . | 135 | 7 |
23,051 | def receive_data ( self , data ) : # type: (bytes) -> None self . _h11_connection . receive_data ( data ) while True : try : event = self . _h11_connection . next_event ( ) except h11 . RemoteProtocolError : raise RemoteProtocolError ( "Bad HTTP message" , event_hint = RejectConnection ( ) ) if ( isinstance ( event , h11 . ConnectionClosed ) or event is h11 . NEED_DATA or event is h11 . PAUSED ) : break if self . client : if isinstance ( event , h11 . InformationalResponse ) : if event . status_code == 101 : self . _events . append ( self . _establish_client_connection ( event ) ) else : self . _events . append ( RejectConnection ( headers = event . headers , status_code = event . status_code , has_body = False , ) ) self . _state = ConnectionState . CLOSED elif isinstance ( event , h11 . Response ) : self . _state = ConnectionState . REJECTING self . _events . append ( RejectConnection ( headers = event . headers , status_code = event . status_code , has_body = True , ) ) elif isinstance ( event , h11 . Data ) : self . _events . append ( RejectData ( data = event . data , body_finished = False ) ) elif isinstance ( event , h11 . EndOfMessage ) : self . _events . append ( RejectData ( data = b"" , body_finished = True ) ) self . _state = ConnectionState . CLOSED else : if isinstance ( event , h11 . Request ) : self . _events . append ( self . _process_connection_request ( event ) ) | Receive data from the remote . | 390 | 7 |
23,052 | def net_send ( out_data , conn ) : print ( 'Sending {} bytes' . format ( len ( out_data ) ) ) conn . send ( out_data ) | Write pending data from websocket to network . | 39 | 9 |
23,053 | def net_recv ( ws , conn ) : in_data = conn . recv ( RECEIVE_BYTES ) if not in_data : # A receive of zero bytes indicates the TCP socket has been closed. We # need to pass None to wsproto to update its internal state. print ( 'Received 0 bytes (connection closed)' ) ws . receive_data ( None ) else : print ( 'Received {} bytes' . format ( len ( in_data ) ) ) ws . receive_data ( in_data ) | Read pending data from network into websocket . | 119 | 9 |
23,054 | def check_filter ( filter , layer = Layer . NETWORK ) : res , pos , msg = False , c_uint ( ) , c_char_p ( ) try : res = windivert_dll . WinDivertHelperCheckFilter ( filter . encode ( ) , layer , byref ( msg ) , byref ( pos ) ) except OSError : pass return res , pos . value , msg . value . decode ( ) | Checks if the given packet filter string is valid with respect to the filter language . | 94 | 17 |
23,055 | def recv ( self , bufsize = DEFAULT_PACKET_BUFFER_SIZE ) : if self . _handle is None : raise RuntimeError ( "WinDivert handle is not open" ) packet = bytearray ( bufsize ) packet_ = ( c_char * bufsize ) . from_buffer ( packet ) address = windivert_dll . WinDivertAddress ( ) recv_len = c_uint ( 0 ) windivert_dll . WinDivertRecv ( self . _handle , packet_ , bufsize , byref ( address ) , byref ( recv_len ) ) return Packet ( memoryview ( packet ) [ : recv_len . value ] , ( address . IfIdx , address . SubIfIdx ) , Direction ( address . Direction ) ) | Receives a diverted packet that matched the filter . | 179 | 11 |
23,056 | def send ( self , packet , recalculate_checksum = True ) : if recalculate_checksum : packet . recalculate_checksums ( ) send_len = c_uint ( 0 ) if PY2 : # .from_buffer(memoryview) does not work on PY2 buff = bytearray ( packet . raw ) else : buff = packet . raw buff = ( c_char * len ( packet . raw ) ) . from_buffer ( buff ) windivert_dll . WinDivertSend ( self . _handle , buff , len ( packet . raw ) , byref ( packet . wd_addr ) , byref ( send_len ) ) return send_len | Injects a packet into the network stack . Recalculates the checksum before sending unless recalculate_checksum = False is passed . | 154 | 31 |
23,057 | def get_param ( self , name ) : value = c_uint64 ( 0 ) windivert_dll . WinDivertGetParam ( self . _handle , name , byref ( value ) ) return value . value | Get a WinDivert parameter . See pydivert . Param for the list of parameters . | 49 | 21 |
23,058 | def set_param ( self , name , value ) : return windivert_dll . WinDivertSetParam ( self . _handle , name , value ) | Set a WinDivert parameter . See pydivert . Param for the list of parameters . | 35 | 21 |
23,059 | def _init ( ) : i = instance ( ) for funcname in WINDIVERT_FUNCTIONS : func = getattr ( i , funcname ) func = raise_on_error ( func ) setattr ( _module , funcname , func ) | Lazy - load DLL replace proxy functions with actual ones . | 55 | 13 |
23,060 | def _mkprox ( funcname ) : def prox ( * args , * * kwargs ) : _init ( ) return getattr ( _module , funcname ) ( * args , * * kwargs ) return prox | Make lazy - init proxy function . | 49 | 7 |
23,061 | def src_addr ( self ) : try : return socket . inet_ntop ( self . _af , self . raw [ self . _src_addr ] . tobytes ( ) ) except ( ValueError , socket . error ) : pass | The packet source address . | 52 | 5 |
23,062 | def dst_addr ( self ) : try : return socket . inet_ntop ( self . _af , self . raw [ self . _dst_addr ] . tobytes ( ) ) except ( ValueError , socket . error ) : pass | The packet destination address . | 53 | 5 |
23,063 | def icmpv4 ( self ) : ipproto , proto_start = self . protocol if ipproto == Protocol . ICMP : return ICMPv4Header ( self , proto_start ) | - An ICMPv4Header instance if the packet is valid ICMPv4 . - None otherwise . | 45 | 22 |
23,064 | def icmpv6 ( self ) : ipproto , proto_start = self . protocol if ipproto == Protocol . ICMPV6 : return ICMPv6Header ( self , proto_start ) | - An ICMPv6Header instance if the packet is valid ICMPv6 . - None otherwise . | 47 | 22 |
23,065 | def tcp ( self ) : ipproto , proto_start = self . protocol if ipproto == Protocol . TCP : return TCPHeader ( self , proto_start ) | - An TCPHeader instance if the packet is valid TCP . - None otherwise . | 38 | 16 |
23,066 | def udp ( self ) : ipproto , proto_start = self . protocol if ipproto == Protocol . UDP : return UDPHeader ( self , proto_start ) | - An TCPHeader instance if the packet is valid UDP . - None otherwise . | 39 | 16 |
23,067 | def _payload ( self ) : return self . tcp or self . udp or self . icmpv4 or self . icmpv6 | header that implements PayloadMixin | 31 | 7 |
23,068 | def matches ( self , filter , layer = Layer . NETWORK ) : buff , buff_ = self . __to_buffers ( ) return windivert_dll . WinDivertHelperEvalFilter ( filter . encode ( ) , layer , ctypes . byref ( buff_ ) , len ( self . raw ) , ctypes . byref ( self . wd_addr ) ) | Evaluates the packet against the given packet filter string . | 83 | 12 |
23,069 | def init ( project_name ) : project_obj = ProjectClient ( ) . get_by_name ( project_name ) if not project_obj : namespace , name = get_namespace_from_name ( project_name ) create_project_base_url = "{}/projects/create" . format ( floyd . floyd_web_host ) create_project_url = "{}?name={}&namespace={}" . format ( create_project_base_url , name , namespace ) floyd_logger . info ( ( 'Project name does not yet exist on floydhub.com. ' 'Create your new project on floydhub.com:\n\t%s' ) , create_project_base_url ) webbrowser . open ( create_project_url ) name = click . prompt ( 'Press ENTER to use project name "%s" or enter a different name' % project_name , default = project_name , show_default = False ) project_name = name . strip ( ) or project_name project_obj = ProjectClient ( ) . get_by_name ( project_name ) if not project_obj : raise FloydException ( 'Project "%s" does not exist on floydhub.com. Ensure it exists before continuing.' % project_name ) namespace , name = get_namespace_from_name ( project_name ) experiment_config = ExperimentConfig ( name = name , namespace = namespace , family_id = project_obj . id ) ExperimentConfigManager . set_config ( experiment_config ) FloydIgnoreManager . init ( ) yaml_config = read_yaml_config ( ) if not yaml_config : copyfile ( os . path . join ( os . path . dirname ( __file__ ) , 'default_floyd.yml' ) , 'floyd.yml' ) floyd_logger . info ( "Project \"%s\" initialized in current directory" , project_name ) | Initialize new project at the current path . | 426 | 9 |
23,070 | def status ( id ) : if id : try : experiment = ExperimentClient ( ) . get ( normalize_job_name ( id ) ) except FloydException : experiment = ExperimentClient ( ) . get ( id ) print_experiments ( [ experiment ] ) else : experiments = ExperimentClient ( ) . get_all ( ) print_experiments ( experiments ) | View status of all jobs in a project . | 75 | 9 |
23,071 | def print_experiments ( experiments ) : headers = [ "JOB NAME" , "CREATED" , "STATUS" , "DURATION(s)" , "INSTANCE" , "DESCRIPTION" , "METRICS" ] expt_list = [ ] for experiment in experiments : expt_list . append ( [ normalize_job_name ( experiment . name ) , experiment . created_pretty , experiment . state , experiment . duration_rounded , experiment . instance_type_trimmed , experiment . description , format_metrics ( experiment . latest_metrics ) ] ) floyd_logger . info ( tabulate ( expt_list , headers = headers ) ) | Prints job details in a table . Includes urls and mode parameters | 149 | 14 |
23,072 | def clone ( id , path ) : try : experiment = ExperimentClient ( ) . get ( normalize_job_name ( id , use_config = False ) ) except FloydException : experiment = ExperimentClient ( ) . get ( id ) task_instance_id = get_module_task_instance_id ( experiment . task_instances ) task_instance = TaskInstanceClient ( ) . get ( task_instance_id ) if task_instance_id else None if not task_instance : sys . exit ( "Cannot clone this version of the job. Try a different version." ) module = ModuleClient ( ) . get ( task_instance . module_id ) if task_instance else None if path : # Download a directory from Code code_url = "{}/api/v1/download/artifacts/code/{}?is_dir=true&path={}" . format ( floyd . floyd_host , experiment . id , path ) else : # Download the full Code code_url = "{}/api/v1/resources/{}?content=true&download=true" . format ( floyd . floyd_host , module . resource_id ) ExperimentClient ( ) . download_tar ( url = code_url , untar = True , delete_after_untar = True ) | - Download all files from a job | 282 | 7 |
23,073 | def info ( job_name_or_id ) : try : experiment = ExperimentClient ( ) . get ( normalize_job_name ( job_name_or_id ) ) except FloydException : experiment = ExperimentClient ( ) . get ( job_name_or_id ) task_instance_id = get_module_task_instance_id ( experiment . task_instances ) task_instance = TaskInstanceClient ( ) . get ( task_instance_id ) if task_instance_id else None normalized_job_name = normalize_job_name ( experiment . name ) table = [ [ "Job name" , normalized_job_name ] , [ "Created" , experiment . created_pretty ] , [ "Status" , experiment . state ] , [ "Duration(s)" , experiment . duration_rounded ] , [ "Instance" , experiment . instance_type_trimmed ] , [ "Description" , experiment . description ] , [ "Metrics" , format_metrics ( experiment . latest_metrics ) ] ] if task_instance and task_instance . mode in [ 'jupyter' , 'serving' ] : table . append ( [ "Mode" , task_instance . mode ] ) table . append ( [ "Url" , experiment . service_url ] ) if experiment . tensorboard_url : table . append ( [ "TensorBoard" , experiment . tensorboard_url ] ) floyd_logger . info ( tabulate ( table ) ) | View detailed information of a job . | 323 | 7 |
23,074 | def follow_logs ( instance_log_id , sleep_duration = 1 ) : cur_idx = 0 job_terminated = False while not job_terminated : # Get the logs in a loop and log the new lines log_file_contents = ResourceClient ( ) . get_content ( instance_log_id ) print_output = log_file_contents [ cur_idx : ] # Get the status of the Job from the current log line job_terminated = any ( terminal_output in print_output for terminal_output in TERMINATION_OUTPUT_LIST ) cur_idx += len ( print_output ) sys . stdout . write ( print_output ) sleep ( sleep_duration ) | Follow the logs until Job termination . | 158 | 7 |
23,075 | def logs ( id , url , follow , sleep_duration = 1 ) : instance_log_id = get_log_id ( id ) if url : log_url = "{}/api/v1/resources/{}?content=true" . format ( floyd . floyd_host , instance_log_id ) floyd_logger . info ( log_url ) return if follow : floyd_logger . info ( "Launching job ..." ) follow_logs ( instance_log_id , sleep_duration ) else : log_file_contents = ResourceClient ( ) . get_content ( instance_log_id ) if len ( log_file_contents . strip ( ) ) : floyd_logger . info ( log_file_contents . rstrip ( ) ) else : floyd_logger . info ( "Launching job now. Try after a few seconds." ) | View the logs of a job . | 198 | 7 |
23,076 | def output ( id , url ) : try : experiment = ExperimentClient ( ) . get ( normalize_job_name ( id ) ) except FloydException : experiment = ExperimentClient ( ) . get ( id ) output_dir_url = "%s/%s/files" % ( floyd . floyd_web_host , experiment . name ) if url : floyd_logger . info ( output_dir_url ) else : floyd_logger . info ( "Opening output path in your browser ..." ) webbrowser . open ( output_dir_url ) | View the files from a job . | 121 | 7 |
23,077 | def stop ( id ) : try : experiment = ExperimentClient ( ) . get ( normalize_job_name ( id ) ) except FloydException : experiment = ExperimentClient ( ) . get ( id ) if experiment . state not in [ "queued" , "queue_scheduled" , "running" ] : floyd_logger . info ( "Job in {} state cannot be stopped" . format ( experiment . state ) ) sys . exit ( 1 ) if not ExperimentClient ( ) . stop ( experiment . id ) : floyd_logger . error ( "Failed to stop job" ) sys . exit ( 1 ) floyd_logger . info ( "Experiment shutdown request submitted. Check status to confirm shutdown" ) | Stop a running job . | 156 | 5 |
23,078 | def delete ( names , yes ) : failures = False for name in names : try : experiment = ExperimentClient ( ) . get ( normalize_job_name ( name ) ) except FloydException : experiment = ExperimentClient ( ) . get ( name ) if not experiment : failures = True continue if not yes and not click . confirm ( "Delete Job: {}?" . format ( experiment . name ) , abort = False , default = False ) : floyd_logger . info ( "Job {}: Skipped." . format ( experiment . name ) ) continue if not ExperimentClient ( ) . delete ( experiment . id ) : failures = True else : floyd_logger . info ( "Job %s Deleted" , experiment . name ) if failures : sys . exit ( 1 ) | Delete a training job . | 164 | 5 |
23,079 | def version ( ) : import pkg_resources version = pkg_resources . require ( PROJECT_NAME ) [ 0 ] . version floyd_logger . info ( version ) | View the current version of the CLI . | 39 | 8 |
23,080 | def init ( dataset_name ) : dataset_obj = DatasetClient ( ) . get_by_name ( dataset_name ) if not dataset_obj : namespace , name = get_namespace_from_name ( dataset_name ) create_dataset_base_url = "{}/datasets/create" . format ( floyd . floyd_web_host ) create_dataset_url = "{}?name={}&namespace={}" . format ( create_dataset_base_url , name , namespace ) floyd_logger . info ( ( "Dataset name does not match your list of datasets. " "Create your new dataset in the web dashboard:\n\t%s" ) , create_dataset_base_url ) webbrowser . open ( create_dataset_url ) name = click . prompt ( 'Press ENTER to use dataset name "%s" or enter a different name' % dataset_name , default = dataset_name , show_default = False ) dataset_name = name . strip ( ) or dataset_name dataset_obj = DatasetClient ( ) . get_by_name ( dataset_name ) if not dataset_obj : raise FloydException ( 'Dataset "%s" does not exist on floydhub.com. Ensure it exists before continuing.' % dataset_name ) namespace , name = get_namespace_from_name ( dataset_name ) data_config = DataConfig ( name = name , namespace = namespace , family_id = dataset_obj . id ) DataConfigManager . set_config ( data_config ) floyd_logger . info ( "Data source \"{}\" initialized in current directory" . format ( dataset_name ) ) floyd_logger . info ( """ You can now upload your data to Floyd by: floyd data upload """ ) | Initialize a new dataset at the current dir . | 402 | 10 |
23,081 | def upload ( resume , message ) : data_config = DataConfigManager . get_config ( ) if not upload_is_resumable ( data_config ) or not opt_to_resume ( resume ) : abort_previous_upload ( data_config ) access_token = AuthConfigManager . get_access_token ( ) initialize_new_upload ( data_config , access_token , message ) complete_upload ( data_config ) | Upload files in the current dir to FloydHub . | 97 | 10 |
23,082 | def status ( id ) : if id : data_source = get_data_object ( id , use_data_config = False ) print_data ( [ data_source ] if data_source else [ ] ) else : data_sources = DataClient ( ) . get_all ( ) print_data ( data_sources ) | View status of all versions in a dataset . | 72 | 9 |
23,083 | def get_data_object ( data_id , use_data_config = True ) : normalized_data_reference = normalize_data_name ( data_id , use_data_config = use_data_config ) client = DataClient ( ) data_obj = client . get ( normalized_data_reference ) # Try with the raw ID if not data_obj and data_id != normalized_data_reference : data_obj = client . get ( data_id ) return data_obj | Normalize the data_id and query the server . If that is unavailable try the raw ID | 107 | 19 |
23,084 | def print_data ( data_sources ) : if not data_sources : return headers = [ "DATA NAME" , "CREATED" , "STATUS" , "DISK USAGE" ] data_list = [ ] for data_source in data_sources : data_list . append ( [ data_source . name , data_source . created_pretty , data_source . state , data_source . size ] ) floyd_logger . info ( tabulate ( data_list , headers = headers ) ) | Print dataset information in tabular form | 114 | 7 |
23,085 | def clone ( id , path ) : data_source = get_data_object ( id , use_data_config = False ) if not data_source : if 'output' in id : floyd_logger . info ( "Note: You cannot clone the output of a running job. You need to wait for it to finish." ) sys . exit ( ) if path : # Download a directory from Dataset or Files # Get the type of data resource from the id (foo/projects/bar/ or foo/datasets/bar/) if '/datasets/' in id : resource_type = 'data' resource_id = data_source . id else : resource_type = 'files' try : experiment = ExperimentClient ( ) . get ( normalize_job_name ( id , use_config = False ) ) except FloydException : experiment = ExperimentClient ( ) . get ( id ) resource_id = experiment . id data_url = "{}/api/v1/download/artifacts/{}/{}?is_dir=true&path={}" . format ( floyd . floyd_host , resource_type , resource_id , path ) else : # Download the full Dataset data_url = "{}/api/v1/resources/{}?content=true&download=true" . format ( floyd . floyd_host , data_source . resource_id ) DataClient ( ) . download_tar ( url = data_url , untar = True , delete_after_untar = True ) | - Download all files in a dataset or from a Job output | 334 | 12 |
23,086 | def listfiles ( data_name ) : data_source = get_data_object ( data_name , use_data_config = False ) if not data_source : if 'output' in data_name : floyd_logger . info ( "Note: You cannot clone the output of a running job. You need to wait for it to finish." ) sys . exit ( ) # Depth-first search dirs = [ '' ] paths = [ ] while dirs : cur_dir = dirs . pop ( ) url = "/resources/{}/{}?content=true" . format ( data_source . resource_id , cur_dir ) response = DataClient ( ) . request ( "GET" , url ) . json ( ) if response [ 'skipped_files' ] > 0 : floyd_logger . info ( "Warning: in directory '%s', %s/%s files skipped (too many files)" , cur_dir , response [ 'skipped_files' ] , response [ 'total_files' ] ) files = response [ 'files' ] files . sort ( key = lambda f : f [ 'name' ] ) for f in files : path = os . path . join ( cur_dir , f [ 'name' ] ) if f [ 'type' ] == 'directory' : path += os . sep paths . append ( path ) if f [ 'type' ] == 'directory' : dirs . append ( os . path . join ( cur_dir , f [ 'name' ] ) ) for path in paths : floyd_logger . info ( path ) | List files in a dataset . | 347 | 6 |
23,087 | def getfile ( data_name , path ) : data_source = get_data_object ( data_name , use_data_config = False ) if not data_source : if 'output' in data_name : floyd_logger . info ( "Note: You cannot clone the output of a running job. You need to wait for it to finish." ) sys . exit ( ) url = "{}/api/v1/resources/{}/{}?content=true" . format ( floyd . floyd_host , data_source . resource_id , path ) fname = os . path . basename ( path ) DataClient ( ) . download ( url , filename = fname ) floyd_logger . info ( "Download finished" ) | Download a specific file from a dataset . | 166 | 8 |
23,088 | def output ( id , url ) : data_source = get_data_object ( id , use_data_config = False ) if not data_source : sys . exit ( ) data_url = "%s/%s" % ( floyd . floyd_web_host , data_source . name ) if url : floyd_logger . info ( data_url ) else : floyd_logger . info ( "Opening output directory in your browser ..." ) webbrowser . open ( data_url ) | View the files from a dataset . | 110 | 7 |
23,089 | def delete ( ids , yes ) : failures = False for id in ids : data_source = get_data_object ( id , use_data_config = True ) if not data_source : failures = True continue data_name = normalize_data_name ( data_source . name ) suffix = data_name . split ( '/' ) [ - 1 ] if not suffix . isdigit ( ) : failures = True floyd_logger . error ( '%s is not a dataset, skipped.' , id ) if suffix == 'output' : floyd_logger . error ( 'To delete job output, please delete the job itself.' ) continue if not yes and not click . confirm ( "Delete Data: {}?" . format ( data_name ) , abort = False , default = False ) : floyd_logger . info ( "Data %s: Skipped" , data_name ) continue if not DataClient ( ) . delete ( data_source . id ) : failures = True else : floyd_logger . info ( "Data %s: Deleted" , data_name ) if failures : sys . exit ( 1 ) | Delete datasets . | 247 | 3 |
23,090 | def add ( source ) : new_data = DatasetClient ( ) . add_data ( source ) print_data ( [ DataClient ( ) . get ( new_data [ 'data_id' ] ) ] ) | Create a new dataset version from the contents of a job . | 48 | 12 |
23,091 | def login ( token , apikey , username , password ) : if manual_login_success ( token , username , password ) : return if not apikey : if has_browser ( ) : apikey = wait_for_apikey ( ) else : floyd_logger . error ( "No browser found, please login manually by creating login key at %s/settings/apikey." , floyd . floyd_web_host ) sys . exit ( 1 ) if apikey : user = AuthClient ( ) . get_user ( apikey , is_apikey = True ) AuthConfigManager . set_apikey ( username = user . username , apikey = apikey ) floyd_logger . info ( "Login Successful as %s" , user . username ) else : floyd_logger . error ( "Login failed, please see --help for other login options." ) | Login to FloydHub . | 201 | 5 |
23,092 | def check_cli_version ( ) : should_exit = False server_version = VersionClient ( ) . get_cli_version ( ) current_version = get_cli_version ( ) if LooseVersion ( current_version ) < LooseVersion ( server_version . min_version ) : print ( "\nYour version of CLI (%s) is no longer compatible with server." % current_version ) should_exit = True elif LooseVersion ( current_version ) < LooseVersion ( server_version . latest_version ) : print ( "\nNew version of CLI (%s) is now available." % server_version . latest_version ) else : return # new version is ready if should_exit and click . confirm ( '\nDo you want to upgrade to version %s now?' % server_version . latest_version ) : auto_upgrade ( ) sys . exit ( 0 ) else : msg_parts = [ ] msg_parts . append ( "\nTo manually upgrade run:" ) msg_parts . append ( " pip install -U floyd-cli" ) if is_conda_env ( ) : msg_parts . append ( "Or if you prefer to use conda:" ) msg_parts . append ( " conda install -y -c conda-forge -c floydhub floyd-cli" ) print ( "\n" . join ( msg_parts ) ) print ( "" ) if should_exit : sys . exit ( 0 ) | Check if the current cli version satisfies the server requirements | 316 | 11 |
23,093 | def request ( self , method , url , params = None , data = None , files = None , json = None , timeout = 5 , headers = None , skip_auth = False ) : request_url = self . base_url + url floyd_logger . debug ( "Starting request to url: %s with params: %s, data: %s" , request_url , params , data ) request_headers = { 'x-floydhub-cli-version' : get_cli_version ( ) } # Auth headers if present if self . auth_header : request_headers [ "Authorization" ] = self . auth_header # Add any additional headers if headers : request_headers . update ( headers ) try : response = requests . request ( method , request_url , params = params , data = data , json = json , headers = request_headers , files = files , timeout = timeout ) except requests . exceptions . ConnectionError as exception : floyd_logger . debug ( "Exception: %s" , exception , exc_info = True ) sys . exit ( "Cannot connect to the Floyd server. Check your internet connection." ) except requests . exceptions . Timeout as exception : floyd_logger . debug ( "Exception: %s" , exception , exc_info = True ) sys . exit ( "Connection to FloydHub server timed out. Please retry or check your internet connection." ) floyd_logger . debug ( "Response Content: %s, Headers: %s" % ( response . content , response . headers ) ) self . check_response_status ( response ) return response | Execute the request using requests library | 347 | 7 |
23,094 | def download ( self , url , filename , relative = False , headers = None , timeout = 5 ) : request_url = self . base_url + url if relative else url floyd_logger . debug ( "Downloading file from url: {}" . format ( request_url ) ) # Auth headers if present request_headers = { } if self . auth_header : request_headers [ "Authorization" ] = self . auth_header # Add any additional headers if headers : request_headers . update ( headers ) try : response = requests . get ( request_url , headers = request_headers , timeout = timeout , stream = True ) self . check_response_status ( response ) with open ( filename , 'wb' ) as f : # chunk mode response doesn't have content-length so we are # using a custom header here content_length = response . headers . get ( 'x-floydhub-content-length' ) if not content_length : content_length = response . headers . get ( 'content-length' ) if content_length : for chunk in progress . bar ( response . iter_content ( chunk_size = 1024 ) , expected_size = ( int ( content_length ) / 1024 ) + 1 ) : if chunk : f . write ( chunk ) else : for chunk in response . iter_content ( chunk_size = 1024 ) : if chunk : f . write ( chunk ) return filename except requests . exceptions . ConnectionError as exception : floyd_logger . debug ( "Exception: {}" . format ( exception ) ) sys . exit ( "Cannot connect to the Floyd server. Check your internet connection." ) | Download the file from the given url at the current path | 351 | 11 |
23,095 | def download_tar ( self , url , untar = True , delete_after_untar = False , destination_dir = '.' ) : try : floyd_logger . info ( "Downloading the tar file to the current directory ..." ) filename = self . download ( url = url , filename = 'output.tar' ) if filename and untar : floyd_logger . info ( "Untarring the contents of the file ..." ) tar = tarfile . open ( filename ) tar . extractall ( path = destination_dir ) tar . close ( ) if delete_after_untar : floyd_logger . info ( "Cleaning up the tar file ..." ) os . remove ( filename ) return filename except FloydException as e : floyd_logger . info ( "Download URL ERROR! {}" . format ( e . message ) ) return False | Download and optionally untar the tar file from the given url | 185 | 12 |
23,096 | def check_response_status ( self , response ) : if not ( 200 <= response . status_code < 300 ) : try : message = response . json ( ) [ "errors" ] except Exception : message = None floyd_logger . debug ( "Error received : status_code: {}, message: {}" . format ( response . status_code , message or response . content ) ) if response . status_code == 400 : raise BadRequestException ( response ) elif response . status_code == 401 : raise AuthenticationException ( ) elif response . status_code == 403 : raise AuthorizationException ( response ) elif response . status_code == 404 : raise NotFoundException ( ) elif response . status_code == 429 : raise OverLimitException ( response . json ( ) . get ( "message" ) ) elif response . status_code == 502 : raise BadGatewayException ( ) elif response . status_code == 504 : raise GatewayTimeoutException ( ) elif response . status_code == 423 : raise LockedException ( ) elif 500 <= response . status_code < 600 : if 'Server under maintenance' in response . content . decode ( ) : raise ServerException ( 'Server under maintenance, please try again later.' ) else : raise ServerException ( ) else : msg = "An error occurred. Server response: {}" . format ( response . status_code ) raise FloydException ( message = msg ) | Check if response is successful . Else raise Exception . | 303 | 10 |
23,097 | def cli ( verbose ) : floyd . floyd_host = floyd . floyd_web_host = "https://dev.floydhub.com" floyd . tus_server_endpoint = "https://upload-v2-dev.floydhub.com/api/v1/upload/" configure_logger ( verbose ) check_cli_version ( ) | Floyd CLI interacts with FloydHub server and executes your commands . More help is available under each command listed below . | 86 | 23 |
23,098 | def get_unignored_file_paths ( ignore_list = None , whitelist = None ) : unignored_files = [ ] if ignore_list is None : ignore_list = [ ] if whitelist is None : whitelist = [ ] for root , dirs , files in os . walk ( "." ) : floyd_logger . debug ( "Root:%s, Dirs:%s" , root , dirs ) if ignore_path ( unix_style_path ( root ) , ignore_list , whitelist ) : # Reset dirs to avoid going further down this directory. # Then continue to the next iteration of os.walk, which causes # everything in this directory to be ignored. # # Note that whitelisted files that are within directories that are # ignored will not be whitelisted. This follows the expected # behavior established by .gitignore logic: # "It is not possible to re-include a file if a parent directory of # that file is excluded." # https://git-scm.com/docs/gitignore#_pattern_format dirs [ : ] = [ ] floyd_logger . debug ( "Ignoring directory : %s" , root ) continue for file_name in files : file_path = unix_style_path ( os . path . join ( root , file_name ) ) if ignore_path ( file_path , ignore_list , whitelist ) : floyd_logger . debug ( "Ignoring file : %s" , file_name ) continue unignored_files . append ( os . path . join ( root , file_name ) ) return unignored_files | Given an ignore_list and a whitelist of glob patterns returns the list of unignored file paths in the current directory and its subdirectories | 359 | 30 |
23,099 | def ignore_path ( path , ignore_list = None , whitelist = None ) : if ignore_list is None : return True should_ignore = matches_glob_list ( path , ignore_list ) if whitelist is None : return should_ignore return should_ignore and not matches_glob_list ( path , whitelist ) | Returns a boolean indicating if a path should be ignored given an ignore_list and a whitelist of glob patterns . | 73 | 23 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.