idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
23,100 | def image_height ( image ) : image_size_cache = _get_cache ( 'image_size_cache' ) if not Image : raise SassMissingDependency ( 'PIL' , 'image manipulation' ) filepath = String . unquoted ( image ) . value path = None try : height = image_size_cache [ filepath ] [ 1 ] except KeyError : height = 0 IMAGES_ROOT = _images_root ( ) if callable ( IMAGES_ROOT ) : try : _file , _storage = list ( IMAGES_ROOT ( filepath ) ) [ 0 ] except IndexError : pass else : path = _storage . open ( _file ) else : _path = os . path . join ( IMAGES_ROOT , filepath . strip ( os . sep ) ) if os . path . exists ( _path ) : path = open ( _path , 'rb' ) if path : image = Image . open ( path ) size = image . size height = size [ 1 ] image_size_cache [ filepath ] = size return Number ( height , 'px' ) | Returns the height of the image found at the path supplied by image relative to your project s images directory . |
23,101 | def path ( self ) : if self . origin : return six . text_type ( self . origin / self . relpath ) else : return six . text_type ( self . relpath ) | Concatenation of origin and relpath as a string . Used in stack traces and other debugging places . |
23,102 | def from_filename ( cls , path_string , origin = MISSING , ** kwargs ) : path = Path ( path_string ) return cls . from_path ( path , origin , ** kwargs ) | Read Sass source from a String specifying the path |
23,103 | def from_file ( cls , f , origin = MISSING , relpath = MISSING , ** kwargs ) : contents = f . read ( ) encoding = determine_encoding ( contents ) if isinstance ( contents , six . binary_type ) : contents = contents . decode ( encoding ) if origin is MISSING or relpath is MISSING : filename = getattr ( f , 'name' , None ) if filename is None : origin = None relpath = repr ( f ) else : origin , relpath = cls . _key_from_path ( Path ( filename ) , origin ) return cls ( origin , relpath , contents , encoding = encoding , ** kwargs ) | Read Sass source from a file or file - like object . |
23,104 | def from_string ( cls , string , relpath = None , encoding = None , is_sass = None ) : if isinstance ( string , six . text_type ) : if encoding is None : encoding = determine_encoding ( string ) byte_contents = string . encode ( encoding ) text_contents = string elif isinstance ( string , six . binary_type ) : encoding = determine_encoding ( string ) byte_contents = string text_contents = string . decode ( encoding ) else : raise TypeError ( "Expected text or bytes, got {0!r}" . format ( string ) ) origin = None if relpath is None : m = hashlib . sha256 ( ) m . update ( byte_contents ) relpath = repr ( "string:{0}:{1}" . format ( m . hexdigest ( ) [ : 16 ] , text_contents [ : 100 ] ) ) return cls ( origin , relpath , text_contents , encoding = encoding , is_sass = is_sass , ) | Read Sass source from the contents of a string . |
23,105 | def hit ( self , rect ) : hits = { tuple ( self . items [ i ] ) for i in rect . collidelistall ( self . items ) } if self . nw and rect . left <= self . cx and rect . top <= self . cy : hits |= self . nw . hit ( rect ) if self . sw and rect . left <= self . cx and rect . bottom >= self . cy : hits |= self . sw . hit ( rect ) if self . ne and rect . right >= self . cx and rect . top <= self . cy : hits |= self . ne . hit ( rect ) if self . se and rect . right >= self . cx and rect . bottom >= self . cy : hits |= self . se . hit ( rect ) return hits | Returns the items that overlap a bounding rectangle . |
23,106 | def scroll ( self , vector ) : self . center ( ( vector [ 0 ] + self . view_rect . centerx , vector [ 1 ] + self . view_rect . centery ) ) | scroll the background in pixels |
23,107 | def center ( self , coords ) : x , y = round ( coords [ 0 ] ) , round ( coords [ 1 ] ) self . view_rect . center = x , y mw , mh = self . data . map_size tw , th = self . data . tile_size vw , vh = self . _tile_view . size if self . clamp_camera : self . _anchored_view = True self . view_rect . clamp_ip ( self . map_rect ) x , y = self . view_rect . center left , self . _x_offset = divmod ( x - self . _half_width , tw ) top , self . _y_offset = divmod ( y - self . _half_height , th ) right = left + vw bottom = top + vh if not self . clamp_camera : self . _anchored_view = True dx = int ( left - self . _tile_view . left ) dy = int ( top - self . _tile_view . top ) if mw < vw or left < 0 : left = 0 self . _x_offset = x - self . _half_width self . _anchored_view = False elif right > mw : left = mw - vw self . _x_offset += dx * tw self . _anchored_view = False if mh < vh or top < 0 : top = 0 self . _y_offset = y - self . _half_height self . _anchored_view = False elif bottom > mh : top = mh - vh self . _y_offset += dy * th self . _anchored_view = False dx = int ( left - self . _tile_view . left ) dy = int ( top - self . _tile_view . top ) view_change = max ( abs ( dx ) , abs ( dy ) ) 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 ( self . _buffer ) elif view_change > self . _redraw_cutoff : logger . info ( 'scrolling too quickly. redraw forced' ) self . _tile_view . move_ip ( dx , dy ) self . redraw_tiles ( self . _buffer ) | center the map on a pixel |
23,108 | def draw ( self , surface , rect , surfaces = None ) : if self . _zoom_level == 1.0 : self . _render_map ( surface , rect , surfaces ) else : self . _render_map ( self . _zoom_buffer , self . _zoom_buffer . get_rect ( ) , surfaces ) self . scaling_function ( self . _zoom_buffer , rect . size , surface ) return self . _previous_blit . copy ( ) | Draw the map onto a surface |
23,109 | 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 |
23,110 | 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 |
23,111 | 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 |
23,112 | 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 ) 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 |
23,113 | 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 |
23,114 | 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 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 ) ) 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 |
23,115 | 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 ) ) self . _clear_surface ( self . _buffer , ( ( rect [ 0 ] - v . left ) * tw , ( rect [ 1 ] - v . top ) * th , rect [ 2 ] * tw , rect [ 3 ] * th ) ) if dx > 0 : append ( ( v . right - 1 , v . top , dx , v . height ) ) elif dx < 0 : append ( ( v . left , v . top , - dx , v . height ) ) if dy > 0 : append ( ( v . left , v . bottom - 1 , v . width , dy ) ) elif dy < 0 : append ( ( v . left , v . top , v . width , - dy ) ) | Queue edge tiles and clear edge areas on buffer if needed |
23,116 | 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 |
23,117 | 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 ) ) positions = set ( ) ani = AnimationToken ( positions , frames , self . _last_time ) self . _animation_map [ gid ] = ani heappush ( self . _animation_queue , ani ) | Reload animation information |
23,118 | def get_tile_image ( self , x , y , l ) : try : return self . _animated_tile [ ( x , y , l ) ] except KeyError : return self . _get_tile_image ( x , y , l ) | Get a tile image respecting current animations |
23,119 | 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 |
23,120 | 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 |
23,121 | def visible_object_layers ( self ) : return ( layer for layer in self . tmx . visible_layers if isinstance ( layer , pytmx . TiledObjectGroup ) ) | This must return layer objects |
23,122 | 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 ] ] : if track and gid in tracked_gids : anim_map [ gid ] . positions . add ( ( x , y , l ) ) try : yield x , y , l , at [ ( x , y , l ) ] except KeyError : yield x , y , l , images [ gid ] | Speed up data access |
23,123 | 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 |
23,124 | 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 elif event . type == VIDEORESIZE : init_screen ( event . w , event . h ) self . map_layer . set_size ( ( event . w , event . h ) ) event = poll ( ) 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 |
23,125 | def update ( self , dt ) : self . group . update ( dt ) 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 |
23,126 | 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 ( ) ) self . handle_input ( ) self . update ( dt ) self . draw ( screen ) pygame . display . flip ( ) except KeyboardInterrupt : self . running = False | Run the game loop |
23,127 | 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 : 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 |
23,128 | 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 ( ) ) self . _x_offset += ( self . _buffer . get_width ( ) - self . view_rect . width ) // 2 self . _y_offset += ( self . _buffer . get_height ( ) - self . view_rect . height ) // 4 dx = int ( left - self . _tile_view . left ) dy = int ( top - self . _tile_view . top ) view_change = max ( abs ( dx ) , abs ( dy ) ) 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 : self . _tile_view . move_ip ( dx , dy ) self . redraw_tiles ( ) | center the map on a map pixel |
23,129 | 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 . |
23,130 | 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 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 |
23,131 | 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 |
23,132 | 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 |
23,133 | 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 |
23,134 | 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 |
23,135 | 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 |
23,136 | 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 |
23,137 | 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 |
23,138 | 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 |
23,139 | 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 |
23,140 | 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 |
23,141 | 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 |
23,142 | 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 |
23,143 | 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 |
23,144 | 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 |
23,145 | 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 |
23,146 | 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 . |
23,147 | 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 . |
23,148 | 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 |
23,149 | 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 |
23,150 | 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 |
23,151 | 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 |
23,152 | 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 |
23,153 | 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 ( ) 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 . |
23,154 | def handle_connection ( stream ) : ws = WSConnection ( ConnectionType . SERVER ) events = ws . events ( ) running = True while running : in_data = stream . recv ( RECEIVE_BYTES ) print ( 'Received {} bytes' . format ( len ( in_data ) ) ) ws . receive_data ( in_data ) try : event = next ( events ) except StopIteration : print ( 'Client connection dropped unexpectedly' ) return if isinstance ( event , Request ) : print ( 'Accepting WebSocket upgrade' ) out_data = ws . send ( AcceptConnection ( ) ) elif isinstance ( event , CloseConnection ) : 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 ) : print ( 'Received request and sending response' ) out_data = ws . send ( Message ( data = event . data [ : : - 1 ] ) ) elif isinstance ( event , Ping ) : print ( 'Received ping and sending pong' ) out_data = ws . send ( event . response ( ) ) else : print ( 'Unknown event: {!r}' . format ( event ) ) print ( 'Sending {} bytes' . format ( len ( out_data ) ) ) stream . send ( out_data ) | Handle a connection . |
23,155 | def receive_data ( self , data ) : if data is None : 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 . |
23,156 | def events ( self ) : 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 . |
23,157 | def server_extensions_handshake ( requested , supported ) : 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 : 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 . |
23,158 | def initiate_upgrade_connection ( self , headers , path ) : 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 . |
23,159 | def send ( self , event ) : 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 . |
23,160 | def receive_data ( self , data ) : 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 . |
23,161 | def net_send ( out_data , conn ) : print ( 'Sending {} bytes' . format ( len ( out_data ) ) ) conn . send ( out_data ) | Write pending data from websocket to network . |
23,162 | def net_recv ( ws , conn ) : in_data = conn . recv ( RECEIVE_BYTES ) if not in_data : 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 . |
23,163 | 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 . |
23,164 | 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 . |
23,165 | def send ( self , packet , recalculate_checksum = True ) : if recalculate_checksum : packet . recalculate_checksums ( ) send_len = c_uint ( 0 ) if 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 . |
23,166 | 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 . |
23,167 | 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 . |
23,168 | 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 . |
23,169 | def _mkprox ( funcname ) : def prox ( * args , ** kwargs ) : _init ( ) return getattr ( _module , funcname ) ( * args , ** kwargs ) return prox | Make lazy - init proxy function . |
23,170 | 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 . |
23,171 | 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 . |
23,172 | 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 . |
23,173 | 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 . |
23,174 | 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 . |
23,175 | 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 . |
23,176 | def _payload ( self ) : return self . tcp or self . udp or self . icmpv4 or self . icmpv6 | header that implements PayloadMixin |
23,177 | 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 . |
23,178 | 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 . |
23,179 | 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 . |
23,180 | 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 |
23,181 | 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 : code_url = "{}/api/v1/download/artifacts/code/{}?is_dir=true&path={}" . format ( floyd . floyd_host , experiment . id , path ) else : 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 |
23,182 | 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 . |
23,183 | def follow_logs ( instance_log_id , sleep_duration = 1 ) : cur_idx = 0 job_terminated = False while not job_terminated : log_file_contents = ResourceClient ( ) . get_content ( instance_log_id ) print_output = log_file_contents [ cur_idx : ] 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 . |
23,184 | 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 . |
23,185 | 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 . |
23,186 | 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 . |
23,187 | 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 . |
23,188 | def version ( ) : import pkg_resources version = pkg_resources . require ( PROJECT_NAME ) [ 0 ] . version floyd_logger . info ( version ) | View the current version of the CLI . |
23,189 | 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 ( ) | Initialize a new dataset at the current dir . |
23,190 | 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 . |
23,191 | 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 . |
23,192 | 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 ) 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 |
23,193 | 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 |
23,194 | 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 : 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 : 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 |
23,195 | 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 ( ) 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 . |
23,196 | 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 . |
23,197 | 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 . |
23,198 | 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 . |
23,199 | 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 . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.