idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
4,800 | def _writeOptionalXsecCards ( self , fileObject , xSec , replaceParamFile ) : if xSec . erode : fileObject . write ( 'ERODE\n' ) if xSec . maxErosion != None : fileObject . write ( 'MAX_EROSION %.6f\n' % xSec . maxErosion ) if xSec . subsurface : fileObject . write ( 'SUBSURFACE\n' ) if xSec . mRiver != None : mRiver = vwp ( xSec . mRiver , replaceParamFile ) try : fileObject . write ( 'M_RIVER %.6f\n' % mRiver ) except : fileObject . write ( 'M_RIVER %s\n' % mRiver ) if xSec . kRiver != None : kRiver = vwp ( xSec . kRiver , replaceParamFile ) try : fileObject . write ( 'K_RIVER %.6f\n' % kRiver ) except : fileObject . write ( 'K_RIVER %s\n' % kRiver ) | Write Optional Cross Section Cards to File Method | 239 | 8 |
4,801 | def replace_file ( from_file , to_file ) : try : os . remove ( to_file ) except OSError : pass copy ( from_file , to_file ) | Replaces to_file with from_file | 41 | 9 |
4,802 | def _prepare_lsm_gag ( self ) : lsm_required_vars = ( self . lsm_precip_data_var , self . lsm_precip_type ) return self . lsm_input_valid and ( None not in lsm_required_vars ) | Determines whether to prepare gage data from LSM | 69 | 12 |
4,803 | def _update_card_file_location ( self , card_name , new_directory ) : with tmp_chdir ( self . gssha_directory ) : file_card = self . project_manager . getCard ( card_name ) if file_card : if file_card . value : original_location = file_card . value . strip ( "'" ) . strip ( '"' ) new_location = os . path . join ( new_directory , os . path . basename ( original_location ) ) file_card . value = '"{0}"' . format ( os . path . basename ( original_location ) ) try : move ( original_location , new_location ) except OSError as ex : log . warning ( ex ) pass | Moves card to new gssha working directory | 166 | 10 |
4,804 | def download_spt_forecast ( self , extract_directory ) : needed_vars = ( self . spt_watershed_name , self . spt_subbasin_name , self . spt_forecast_date_string , self . ckan_engine_url , self . ckan_api_key , self . ckan_owner_organization ) if None not in needed_vars : er_manager = ECMWFRAPIDDatasetManager ( self . ckan_engine_url , self . ckan_api_key , self . ckan_owner_organization ) # TODO: Modify to only download one of the forecasts in the ensemble er_manager . download_prediction_dataset ( watershed = self . spt_watershed_name , subbasin = self . spt_subbasin_name , date_string = self . spt_forecast_date_string , # '20160711.1200' extract_directory = extract_directory ) return glob ( os . path . join ( extract_directory , self . spt_forecast_date_string , "Qout*52.nc" ) ) [ 0 ] elif needed_vars . count ( None ) == len ( needed_vars ) : log . info ( "Skipping streamflow forecast download ..." ) return None else : raise ValueError ( "To download the forecasts, you need to set: \n" "spt_watershed_name, spt_subbasin_name, spt_forecast_date_string \n" "ckan_engine_url, ckan_api_key, and ckan_owner_organization." ) | Downloads Streamflow Prediction Tool forecast data | 371 | 8 |
4,805 | def prepare_hmet ( self ) : if self . _prepare_lsm_hmet : netcdf_file_path = None hmet_ascii_output_folder = None if self . output_netcdf : netcdf_file_path = '{0}_hmet.nc' . format ( self . project_manager . name ) if self . hotstart_minimal_mode : netcdf_file_path = '{0}_hmet_hotstart.nc' . format ( self . project_manager . name ) else : hmet_ascii_output_folder = 'hmet_data_{0}to{1}' if self . hotstart_minimal_mode : hmet_ascii_output_folder += "_hotstart" self . event_manager . prepare_hmet_lsm ( self . lsm_data_var_map_array , hmet_ascii_output_folder , netcdf_file_path ) self . simulation_modified_input_cards += [ "HMET_NETCDF" , "HMET_ASCII" ] else : log . info ( "HMET preparation skipped due to missing parameters ..." ) | Prepare HMET data for simulation | 267 | 7 |
4,806 | def prepare_gag ( self ) : if self . _prepare_lsm_gag : self . event_manager . prepare_gag_lsm ( self . lsm_precip_data_var , self . lsm_precip_type , self . precip_interpolation_type ) self . simulation_modified_input_cards . append ( "PRECIP_FILE" ) else : log . info ( "Gage file preparation skipped due to missing parameters ..." ) | Prepare gage data for simulation | 108 | 7 |
4,807 | def rapid_to_gssha ( self ) : # if no streamflow given, download forecast if self . path_to_rapid_qout is None and self . connection_list_file : rapid_qout_directory = os . path . join ( self . gssha_directory , 'rapid_streamflow' ) try : os . mkdir ( rapid_qout_directory ) except OSError : pass self . path_to_rapid_qout = self . download_spt_forecast ( rapid_qout_directory ) # prepare input for GSSHA if user wants if self . path_to_rapid_qout is not None and self . connection_list_file : self . event_manager . prepare_rapid_streamflow ( self . path_to_rapid_qout , self . connection_list_file ) self . simulation_modified_input_cards . append ( 'CHAN_POINT_INPUT' ) | Prepare RAPID data for simulation | 214 | 8 |
4,808 | def run_forecast ( self ) : # ---------------------------------------------------------------------- # LSM to GSSHA # ---------------------------------------------------------------------- self . prepare_hmet ( ) self . prepare_gag ( ) # ---------------------------------------------------------------------- # RAPID to GSSHA # ---------------------------------------------------------------------- self . rapid_to_gssha ( ) # ---------------------------------------------------------------------- # HOTSTART # ---------------------------------------------------------------------- self . hotstart ( ) # ---------------------------------------------------------------------- # Run GSSHA # ---------------------------------------------------------------------- return self . run ( ) | Updates card & runs for RAPID to GSSHA & LSM to GSSHA | 96 | 20 |
4,809 | def get_cache_key ( request , page , lang , site_id , title ) : from cms . cache import _get_cache_key from cms . templatetags . cms_tags import _get_page_by_untyped_arg from cms . models import Page if not isinstance ( page , Page ) : page = _get_page_by_untyped_arg ( page , request , site_id ) if not site_id : try : site_id = page . node . site_id except AttributeError : # CMS_3_4 site_id = page . site_id if not title : return _get_cache_key ( 'page_tags' , page , '' , site_id ) + '_type:tags_list' else : return _get_cache_key ( 'title_tags' , page , lang , site_id ) + '_type:tags_list' | Create the cache key for the current page and tag type | 206 | 11 |
4,810 | def get_page_tags ( page ) : from . models import PageTags try : return page . pagetags . tags . all ( ) except PageTags . DoesNotExist : return [ ] | Retrieves all the tags for a Page instance . | 42 | 11 |
4,811 | def page_has_tag ( page , tag ) : from . models import PageTags if hasattr ( tag , 'slug' ) : slug = tag . slug else : slug = tag try : return page . pagetags . tags . filter ( slug = slug ) . exists ( ) except PageTags . DoesNotExist : return False | Check if a Page object is associated with the given tag . | 72 | 12 |
4,812 | def title_has_tag ( page , lang , tag ) : from . models import TitleTags if hasattr ( tag , 'slug' ) : slug = tag . slug else : slug = tag try : return page . get_title_obj ( language = lang , fallback = False ) . titletags . tags . filter ( slug = slug ) . exists ( ) except TitleTags . DoesNotExist : return False | Check if a Title object is associated with the given tag . This function does not use fallbacks to retrieve title object . | 90 | 24 |
4,813 | def get_page_tags_from_request ( request , page_lookup , lang , site , title = False ) : from cms . templatetags . cms_tags import _get_page_by_untyped_arg from cms . utils import get_language_from_request , get_site_id from django . core . cache import cache try : from cms . utils import get_cms_setting except ImportError : from cms . utils . conf import get_cms_setting site_id = get_site_id ( site ) if lang is None : lang = get_language_from_request ( request ) cache_key = get_cache_key ( request , page_lookup , lang , site , title ) tags_list = cache . get ( cache_key ) if not tags_list : page = _get_page_by_untyped_arg ( page_lookup , request , site_id ) if page : if title : tags_list = get_title_tags ( page , lang ) else : tags_list = get_page_tags ( page ) cache . set ( cache_key , tags_list , timeout = get_cms_setting ( 'CACHE_DURATIONS' ) [ 'content' ] ) if not tags_list : tags_list = ( ) return tags_list | Get the list of tags attached to a Page or a Title from a request from usual page_lookup parameters . | 297 | 23 |
4,814 | def get_title_tags_from_request ( request , page_lookup , lang , site ) : return get_page_tags_from_request ( request , page_lookup , lang , site , True ) | Get the list of tags attached to a Title from a request from usual page_lookup parameters . | 47 | 20 |
4,815 | def generateFromWatershedShapefile ( self , shapefile_path , cell_size , out_raster_path = None , load_raster_to_db = True ) : if not self . projectFile : raise ValueError ( "Must be connected to project file ..." ) # match elevation grid if exists match_grid = None try : match_grid = self . projectFile . getGrid ( use_mask = False ) except ValueError : pass # match projection if exists wkt_projection = None try : wkt_projection = self . projectFile . getWkt ( ) except ValueError : pass if out_raster_path is None : out_raster_path = '{0}.{1}' . format ( self . projectFile . name , self . extension ) # make sure paths are absolute as the working directory changes shapefile_path = os . path . abspath ( shapefile_path ) # make sure the polygon is valid check_watershed_boundary_geometry ( shapefile_path ) gr = rasterize_shapefile ( shapefile_path , x_cell_size = cell_size , y_cell_size = cell_size , match_grid = match_grid , raster_nodata = 0 , as_gdal_grid = True , raster_wkt_proj = wkt_projection , convert_to_utm = True ) with tmp_chdir ( self . projectFile . project_directory ) : gr . to_grass_ascii ( out_raster_path , print_nodata = False ) self . filename = out_raster_path # update project file cards self . projectFile . setCard ( 'WATERSHED_MASK' , out_raster_path , add_quotes = True ) self . projectFile . setCard ( 'GRIDSIZE' , str ( ( gr . geotransform [ 1 ] - gr . geotransform [ - 1 ] ) / 2.0 ) ) self . projectFile . setCard ( 'ROWS' , str ( gr . y_size ) ) self . projectFile . setCard ( 'COLS' , str ( gr . x_size ) ) # write projection file if does not exist if wkt_projection is None : proj_file = ProjectionFile ( ) proj_file . projection = gr . wkt proj_file . projectFile = self . projectFile proj_path = "{0}_prj.pro" . format ( os . path . splitext ( out_raster_path ) [ 0 ] ) gr . write_prj ( proj_path ) self . projectFile . setCard ( '#PROJECTION_FILE' , proj_path , add_quotes = True ) # read raster into object if load_raster_to_db : self . _load_raster_text ( out_raster_path ) | Generates a mask from a watershed_shapefile | 643 | 10 |
4,816 | def tmp_chdir ( new_path ) : prev_cwd = os . getcwd ( ) os . chdir ( new_path ) try : yield finally : os . chdir ( prev_cwd ) | Change directory temporarily and return when done . | 47 | 8 |
4,817 | def _download ( self ) : # reproject GSSHA grid and get bounds min_x , max_x , min_y , max_y = self . gssha_grid . bounds ( as_geographic = True ) if self . era_download_data == 'era5' : log . info ( "Downloading ERA5 data ..." ) download_era5_for_gssha ( self . lsm_input_folder_path , self . download_start_datetime , self . download_end_datetime , leftlon = min_x - 0.5 , rightlon = max_x + 0.5 , toplat = max_y + 0.5 , bottomlat = min_y - 0.5 ) else : log . info ( "Downloading ERA Interim data ..." ) download_interim_for_gssha ( self . lsm_input_folder_path , self . download_start_datetime , self . download_end_datetime , leftlon = min_x - 1 , rightlon = max_x + 1 , toplat = max_y + 1 , bottomlat = min_y - 1 ) | download ERA5 data for GSSHA domain | 253 | 9 |
4,818 | def dispatch_request ( self , * args , * * kwargs ) : if request . method in ( 'POST' , 'PUT' ) : return_url , context = self . post ( * args , * * kwargs ) if return_url is not None : return redirect ( return_url ) elif request . method in ( 'GET' , 'HEAD' ) : context = self . get ( * args , * * kwargs ) return self . render_response ( self . context ( context ) ) | Dispatch the request . Its the actual view flask will use . | 111 | 12 |
4,819 | def _run_cmd_get_output ( cmd ) : process = subprocess . Popen ( cmd . split ( ) , stdout = subprocess . PIPE ) out , err = process . communicate ( ) return out or err | Runs a shell command returns console output . | 50 | 9 |
4,820 | def _remote_github_url_to_string ( remote_url ) : # TODO: make this work with https URLs match = re . search ( 'git@github\.com:(.*)\.git' , remote_url ) if not match : raise EnvironmentError ( 'Remote is not a valid github URL' ) identifier = match . group ( 1 ) return re . sub ( '\W' , ':' , identifier ) | Parse out the repository identifier from a github URL . | 91 | 11 |
4,821 | def _get_args ( args ) : parser = argparse . ArgumentParser ( description = 'A tool to extract features into a simple format.' , formatter_class = argparse . ArgumentDefaultsHelpFormatter , ) parser . add_argument ( '--no-cache' , action = 'store_true' ) parser . add_argument ( '--deploy' , action = 'store_true' ) parser . add_argument ( '--cache-path' , type = str , default = 'fex-cache.pckl' , help = 'Path for cache file' ) parser . add_argument ( '--path' , type = str , default = 'features.csv' , help = 'Path to write the dataset to' ) args = parser . parse_args ( args ) if args . no_cache : args . cache_path = None return args | Argparse logic lives here . | 187 | 6 |
4,822 | def run ( * extractor_list , * * kwargs ) : args = _get_args ( kwargs . get ( 'args' ) ) n_extractors = len ( extractor_list ) log . info ( 'Going to run list of {} FeatureExtractors' . format ( n_extractors ) ) collection = fex . Collection ( cache_path = args . cache_path ) for extractor in extractor_list : collection . add_feature_extractor ( extractor ) out_path = args . path if args . deploy : out_path = _prefix_git_hash ( out_path ) collection . run ( out_path ) | Parse arguments provided on the commandline and execute extractors . | 146 | 13 |
4,823 | def _delete_existing ( self , project_file , session ) : # remove existing grid if exists existing_elev = session . query ( RasterMapFile ) . filter ( RasterMapFile . projectFile == project_file ) . filter ( RasterMapFile . fileExtension == self . fileExtension ) . all ( ) if existing_elev : session . delete ( existing_elev ) session . commit ( ) | This will delete existing instances with the same extension | 92 | 9 |
4,824 | def _load_raster_text ( self , raster_path ) : # Open file and read plain text into text field with open ( raster_path , 'r' ) as f : self . rasterText = f . read ( ) # Retrieve metadata from header lines = self . rasterText . split ( '\n' ) for line in lines [ 0 : 6 ] : spline = line . split ( ) if 'north' in spline [ 0 ] . lower ( ) : self . north = float ( spline [ 1 ] ) elif 'south' in spline [ 0 ] . lower ( ) : self . south = float ( spline [ 1 ] ) elif 'east' in spline [ 0 ] . lower ( ) : self . east = float ( spline [ 1 ] ) elif 'west' in spline [ 0 ] . lower ( ) : self . west = float ( spline [ 1 ] ) elif 'rows' in spline [ 0 ] . lower ( ) : self . rows = int ( spline [ 1 ] ) elif 'cols' in spline [ 0 ] . lower ( ) : self . columns = int ( spline [ 1 ] ) | Loads grass ASCII to object | 260 | 6 |
4,825 | def _read ( self , directory , filename , session , path , name , extension , spatial , spatialReferenceID , replaceParamFile ) : # Assign file extension attribute to file object self . fileExtension = extension self . filename = filename self . _load_raster_text ( path ) if spatial : # Get well known binary from the raster file using the MapKit RasterLoader wkbRaster = RasterLoader . grassAsciiRasterToWKB ( session = session , grassRasterPath = path , srid = str ( spatialReferenceID ) , noData = '0' ) self . raster = wkbRaster | Raster Map File Read from File Method | 138 | 8 |
4,826 | def _write ( self , session , openFile , replaceParamFile ) : # If the raster field is not empty, write from this field if self . raster is not None : # Configure RasterConverter converter = RasterConverter ( session ) # Use MapKit RasterConverter to retrieve the raster as a GRASS ASCII Grid grassAsciiGrid = converter . getAsGrassAsciiRaster ( rasterFieldName = 'raster' , tableName = self . __tablename__ , rasterIdFieldName = 'id' , rasterId = self . id ) # Write to file openFile . write ( grassAsciiGrid ) elif self . rasterText is not None : # Write file openFile . write ( self . rasterText ) | Raster Map File Write to File Method | 174 | 8 |
4,827 | def write ( self , session , directory , name , replaceParamFile = None , * * kwargs ) : if self . raster is not None or self . rasterText is not None : super ( RasterMapFile , self ) . write ( session , directory , name , replaceParamFile , * * kwargs ) | Wrapper for GsshaPyFileObjectBase write method | 70 | 12 |
4,828 | def slugify ( value ) : s1 = first_cap_re . sub ( r'\1_\2' , value ) s2 = all_cap_re . sub ( r'\1_\2' , s1 ) return s2 . lower ( ) . replace ( ' _' , '_' ) . replace ( ' ' , '_' ) | Simple Slugify . | 80 | 4 |
4,829 | def entrypoint ( cls ) : if not isinstance ( cls , type ) or not issubclass ( cls , Command ) : raise TypeError ( f"inappropriate entrypoint instance of type {cls.__class__}" ) cls . _argcmdr_entrypoint_ = True return cls | Mark the decorated command as the intended entrypoint of the command module . | 68 | 14 |
4,830 | def store_env_override ( option_strings , dest , envvar , nargs = None , default = None , type = None , choices = None , description = None , help = None , metavar = None ) : if envvar == '' : raise ValueError ( "unsupported environment variable name" , envvar ) envvalue = os . getenv ( envvar ) if callable ( default ) : default_value = default ( envvalue ) elif envvalue : default_value = envvalue else : default_value = default if description and help : raise ValueError ( "only specify help to override its optional generation from " "description -- not both" ) elif description : if default_value : help = '{} (default {} envvar {}: {})' . format ( description , 'provided by' if default is None else 'derived from' , envvar , default_value , ) else : help = ( f'{description} (required because ' f'envvar {envvar} is empty)' ) return argparse . _StoreAction ( option_strings = option_strings , dest = dest , nargs = nargs , const = None , default = default_value , type = type , choices = choices , required = ( not default_value ) , help = help , metavar = metavar , ) | Construct an argparse action which stores the value of a command line option to override a corresponding value in the process environment . | 284 | 24 |
4,831 | def individual_dict ( self , ind_ids ) : ind_dict = { ind . ind_id : ind for ind in self . individuals ( ind_ids = ind_ids ) } return ind_dict | Return a dict with ind_id as key and Individual as values . | 44 | 14 |
4,832 | def clean ( ) : run ( 'rm -rf build/' ) run ( 'rm -rf dist/' ) run ( 'rm -rf puzzle.egg-info' ) run ( 'find . -name __pycache__ -delete' ) run ( 'find . -name *.pyc -delete' ) run ( 'find . -name *.pyo -delete' ) run ( 'find . -name *~ -delete' ) log . info ( 'cleaned up' ) | clean - remove build artifacts . | 104 | 6 |
4,833 | def zmq_sub ( bind , tables , forwarder = False , green = False ) : logger = logging . getLogger ( "meepo.sub.zmq_sub" ) if not isinstance ( tables , ( list , set ) ) : raise ValueError ( "tables should be list or set" ) if not green : import zmq else : import zmq . green as zmq ctx = zmq . Context ( ) socket = ctx . socket ( zmq . PUB ) if forwarder : socket . connect ( bind ) else : socket . bind ( bind ) events = ( "%s_%s" % ( tb , action ) for tb , action in itertools . product ( * [ tables , [ "write" , "update" , "delete" ] ] ) ) for event in events : def _sub ( pk , event = event ) : msg = "%s %s" % ( event , pk ) socket . send_string ( msg ) logger . debug ( "pub msg: %s" % msg ) signal ( event ) . connect ( _sub , weak = False ) return socket | 0mq fanout sub . | 250 | 7 |
4,834 | def add_case ( self , case_obj , vtype = 'snv' , mode = 'vcf' , ped_svg = None ) : new_case = Case ( case_id = case_obj . case_id , name = case_obj . name , variant_source = case_obj . variant_source , variant_type = vtype , variant_mode = mode , pedigree = ped_svg , compressed = case_obj . compressed , tabix_index = case_obj . tabix_index ) # build individuals inds = [ Individual ( ind_id = ind . ind_id , name = ind . name , mother = ind . mother , father = ind . father , sex = ind . sex , phenotype = ind . phenotype , ind_index = ind . ind_index , variant_source = ind . variant_source , bam_path = ind . bam_path , ) for ind in case_obj . individuals ] new_case . individuals = inds if self . case ( new_case . case_id ) : logger . warning ( "Case already exists in database!" ) else : self . session . add ( new_case ) self . save ( ) return new_case | Load a case with individuals . | 260 | 6 |
4,835 | def individuals ( self , ind_ids = None ) : query = self . query ( Individual ) if ind_ids : query = query . filter ( Individual . ind_id . in_ ( ind_ids ) ) return query | Fetch all individuals from the database . | 47 | 8 |
4,836 | def case_comments ( self ) : comments = ( comment for comment in self . comments if comment . variant_id is None ) return comments | Return only comments made on the case . | 29 | 8 |
4,837 | def put ( self , url , body = None , * * kwargs ) : return self . request ( 'put' , url , body = body , * * kwargs ) | Send a PUT request . | 39 | 6 |
4,838 | def event ( self , * topics , * * kwargs ) : workers = kwargs . pop ( "workers" , 1 ) multi = kwargs . pop ( "multi" , False ) queue_limit = kwargs . pop ( "queue_limit" , 10000 ) def wrapper ( func ) : for topic in topics : queues = [ Queue ( ) for _ in range ( workers ) ] hash_ring = ketama . Continuum ( ) for q in queues : hash_ring [ str ( hash ( q ) ) ] = q self . worker_queues [ topic ] = hash_ring self . workers [ topic ] = WorkerPool ( queues , topic , func , multi = multi , queue_limit = queue_limit , logger_name = "%s.%s" % ( self . name , topic ) ) self . socket . setsockopt ( zmq . SUBSCRIBE , asbytes ( topic ) ) return func return wrapper | Topic callback registry . | 205 | 4 |
4,839 | def run ( self ) : for worker_pool in self . workers . values ( ) : worker_pool . start ( ) if isinstance ( self . listen , list ) : for i in self . listen : self . socket . connect ( i ) else : self . socket . connect ( self . listen ) try : while True : msg = self . socket . recv_string ( ) lst = msg . split ( ) if len ( lst ) == 2 : topic , pks = lst [ 0 ] , [ lst [ 1 ] , ] elif len ( lst ) > 2 : topic , pks = lst [ 0 ] , lst [ 1 : ] else : self . logger . error ( "msg corrupt -> %s" % msg ) continue self . logger . debug ( "replicator: {0} -> {1}" . format ( topic , pks ) ) for pk in pks : self . worker_queues [ topic ] [ str ( hash ( pk ) ) ] . put ( pk ) except Exception as e : self . logger . exception ( e ) finally : for worker_pool in self . workers . values ( ) : worker_pool . terminate ( ) | Run the replicator . | 256 | 5 |
4,840 | def _pk ( self , obj ) : pk_values = tuple ( getattr ( obj , c . name ) for c in obj . __mapper__ . primary_key ) if len ( pk_values ) == 1 : return pk_values [ 0 ] return pk_values | Get pk values from object | 64 | 6 |
4,841 | def session_update ( self , session , * _ ) : self . _session_init ( session ) session . pending_write |= set ( session . new ) session . pending_update |= set ( session . dirty ) session . pending_delete |= set ( session . deleted ) self . logger . debug ( "%s - session_update" % session . meepo_unique_id ) | Record the sqlalchemy object states in the middle of session prepare the events for the final pub in session_commit . | 85 | 24 |
4,842 | def session_commit ( self , session ) : # this may happen when there's nothing to commit if not hasattr ( session , 'meepo_unique_id' ) : self . logger . debug ( "skipped - session_commit" ) return self . _session_pub ( session ) self . _session_del ( session ) | Pub the events after the session committed . | 72 | 8 |
4,843 | def add_basic_auth ( dolt , username , password ) : return dolt . with_headers ( Authorization = 'Basic %s' % base64 . b64encode ( '%s:%s' % ( username , password ) ) . strip ( ) ) | Send basic auth username and password . | 58 | 7 |
4,844 | def _add_genotypes ( self , variant_obj , gemini_variant , case_id , individual_objs ) : for ind in individual_objs : index = ind . ind_index variant_obj . add_individual ( Genotype ( sample_id = ind . ind_id , genotype = gemini_variant [ 'gts' ] [ index ] , case_id = case_id , phenotype = ind . phenotype , ref_depth = gemini_variant [ 'gt_ref_depths' ] [ index ] , alt_depth = gemini_variant [ 'gt_alt_depths' ] [ index ] , depth = gemini_variant [ 'gt_depths' ] [ index ] , genotype_quality = gemini_variant [ 'gt_quals' ] [ index ] ) ) | Add the genotypes for a variant for all individuals | 185 | 10 |
4,845 | def process_frames_argument ( frames ) : result = None if np . iterable ( frames ) : try : frames_arr = np . array ( frames ) except : raise TypeError ( "'frames' should be convertable to numpy.array" ) for idx in range ( len ( frames_arr ) ) : frame_idx = frames_arr [ idx ] assert is_real_number ( frame_idx ) assert int ( frame_idx ) == frame_idx frames_arr [ idx ] = int ( frame_idx ) #self.frames = frames_arr result = frames_arr elif is_real_number ( frames ) : assert int ( frames ) == frames frames = int ( frames ) #self.frames = range(frames) result = range ( frames ) return result | Check and process frames argument into a proper iterable for an animation object | 174 | 14 |
4,846 | def init ( ctx , reset , root , phenomizer ) : configs = { } if root is None : root = ctx . obj . get ( 'root' ) or os . path . expanduser ( "~/.puzzle" ) configs [ 'root' ] = root if os . path . isfile ( root ) : logger . error ( "'root' can't be a file" ) ctx . abort ( ) logger . info ( "Root directory is: {}" . format ( root ) ) db_path = os . path . join ( root , 'puzzle_db.sqlite3' ) logger . info ( "db path is: {}" . format ( db_path ) ) resource_dir = os . path . join ( root , 'resources' ) logger . info ( "resource dir is: {}" . format ( resource_dir ) ) if os . path . exists ( resource_dir ) : logger . debug ( "Found puzzle directory: {0}" . format ( root ) ) if os . path . exists ( resource_dir ) and not reset : logger . warning ( "Puzzle db already in place" ) ctx . abort ( ) else : logger . info ( "Create directory: {0}" . format ( resource_dir ) ) os . makedirs ( resource_dir ) logger . debug ( 'Directory created' ) logger . debug ( 'Connect to database and create tables' ) store = SqlStore ( db_path ) store . set_up ( reset = reset ) if phenomizer : phenomizer = [ str ( term ) for term in phenomizer ] configs [ 'phenomizer_auth' ] = phenomizer if not ctx . obj . get ( 'config_path' ) : logger . info ( "Creating puzzle config file in {0}" . format ( PUZZLE_CONFIG_PATH ) ) with codecs . open ( PUZZLE_CONFIG_PATH , 'w' , encoding = 'utf-8' ) as f : f . write ( yaml . dump ( configs ) ) logger . debug ( "Config created" ) | Initialize a database that store metadata | 454 | 7 |
4,847 | def encode ( value , encoding = 'utf-8' , encoding_errors = 'strict' ) : if isinstance ( value , bytes ) : return value if not isinstance ( value , basestring ) : value = str ( value ) if isinstance ( value , unicode ) : value = value . encode ( encoding , encoding_errors ) return value | Return a bytestring representation of the value . | 76 | 10 |
4,848 | def share_secret ( threshold , nshares , secret , identifier , hash_id = Hash . SHA256 ) : if identifier is None : raise TSSError ( 'an identifier must be provided' ) if not Hash . is_valid ( hash_id ) : raise TSSError ( 'invalid hash algorithm %s' % hash_id ) secret = encode ( secret ) identifier = encode ( identifier ) if hash_id != Hash . NONE : secret += Hash . to_func ( hash_id ) ( secret ) . digest ( ) shares = generate_shares ( threshold , nshares , secret ) header = format_header ( identifier , hash_id , threshold , len ( secret ) + 1 ) return [ format_share ( header , share ) for share in shares ] | Create nshares of the secret . threshold specifies the number of shares needed for reconstructing the secret value . A 0 - 16 bytes identifier must be provided . Optionally the secret is hashed with the algorithm specified by hash_id a class attribute of Hash . This function must return a list of formatted shares or raises a TSSError exception if anything went wrong . | 168 | 75 |
4,849 | def get_gene_symbols ( chrom , start , stop ) : gene_symbols = query_gene_symbol ( chrom , start , stop ) logger . debug ( "Found gene symbols: {0}" . format ( ', ' . join ( gene_symbols ) ) ) return gene_symbols | Get the gene symbols that a interval overlaps | 71 | 9 |
4,850 | def get_gene_info ( ensembl_ids = None , hgnc_symbols = None ) : uniq_ensembl_ids = set ( ensembl_id for ensembl_id in ( ensembl_ids or [ ] ) ) uniq_hgnc_symbols = set ( hgnc_symbol for hgnc_symbol in ( hgnc_symbols or [ ] ) ) genes = [ ] gene_data = [ ] if uniq_ensembl_ids : for ensembl_id in uniq_ensembl_ids : for res in query_gene ( ensembl_id = ensembl_id ) : gene_data . append ( res ) elif uniq_hgnc_symbols : for hgnc_symbol in uniq_hgnc_symbols : query_res = query_gene ( hgnc_symbol = hgnc_symbol ) if query_res : for res in query_res : gene_data . append ( res ) else : # If no result we add just the symbol gene_data . append ( { 'hgnc_symbol' : hgnc_symbol , 'hgnc_id' : None , 'ensembl_id' : None , 'description' : None , 'chrom' : 'unknown' , 'start' : 0 , 'stop' : 0 , 'hi_score' : None , 'constraint_score' : None , } ) for gene in gene_data : genes . append ( Gene ( symbol = gene [ 'hgnc_symbol' ] , hgnc_id = gene [ 'hgnc_id' ] , ensembl_id = gene [ 'ensembl_id' ] , description = gene [ 'description' ] , chrom = gene [ 'chrom' ] , start = gene [ 'start' ] , stop = gene [ 'stop' ] , location = get_cytoband_coord ( gene [ 'chrom' ] , gene [ 'start' ] ) , hi_score = gene [ 'hi_score' ] , constraint_score = gene [ 'constraint_score' ] , omim_number = get_omim_number ( gene [ 'hgnc_symbol' ] ) ) ) return genes | Return the genes info based on the transcripts found | 520 | 9 |
4,851 | def get_most_severe_consequence ( transcripts ) : most_severe_consequence = None most_severe_score = None for transcript in transcripts : for consequence in transcript [ 'consequence' ] . split ( '&' ) : logger . debug ( "Checking severity score for consequence: {0}" . format ( consequence ) ) severity_score = SEVERITY_DICT . get ( consequence ) logger . debug ( "Severity score found: {0}" . format ( severity_score ) ) if severity_score != None : if most_severe_score : if severity_score < most_severe_score : most_severe_consequence = consequence most_severe_score = severity_score else : most_severe_consequence = consequence most_severe_score = severity_score return most_severe_consequence | Get the most severe consequence | 177 | 5 |
4,852 | def get_cytoband_coord ( chrom , pos ) : chrom = chrom . strip ( 'chr' ) pos = int ( pos ) result = None logger . debug ( "Finding Cytoband for chrom:{0} pos:{1}" . format ( chrom , pos ) ) if chrom in CYTOBANDS : for interval in CYTOBANDS [ chrom ] [ pos ] : result = "{0}{1}" . format ( chrom , interval . data ) return result | Get the cytoband coordinate for a position | 104 | 9 |
4,853 | def parse_mapping ( self , map_path , source = None , dotfiles = None ) : include_re = r"""^\s*#include\s+(".+"|'.+')""" include_re = re . compile ( include_re , re . I ) mapping_re = r"""^("[^"]+"|\'[^\']+\'|[^\'":]+)\s*(?::\s*(.*)\s*)?$""" mapping_re = re . compile ( mapping_re ) filename = None map_path = path . realpath ( path . expanduser ( map_path ) ) if path . isfile ( map_path ) : filename = map_path elif path . isdir ( map_path ) : # try finding a mapping in the target directory for map_name in '.dotfiles' , 'dotfiles' : candidate = path . join ( map_path , map_name ) if path . isfile ( candidate ) : filename = candidate break if filename is None : raise ValueError ( 'No dotfile mapping found in %s' % map_path ) if source is None : source = path . dirname ( map_path ) if dotfiles is None : dotfiles = OrderedDict ( ) lineno = 0 with open ( filename ) as fh : for line in fh : lineno += 1 content = line . strip ( ) match = include_re . match ( content ) if match : include_path = match . group ( 1 ) . strip ( '\'"' ) if ( include_path . startswith ( '/' ) or include_path . startswith ( '~' ) ) : include_path = path . realpath ( path . expanduser ( include_path ) ) else : include_path = path . join ( path . dirname ( filename ) , include_path ) if path . exists ( include_path ) : self . log . debug ( 'Recursively parsing mapping in %s' , include_path ) dotfiles = self . parse_mapping ( include_path , dotfiles = dotfiles ) else : self . log . warning ( 'Include command points to file or ' 'directory that does not exist, "%s",' ' on line %d' , include_path , lineno ) if not content or content . startswith ( '#' ) : # comment line or empty line continue match = mapping_re . match ( content ) if match : source_path , target_path = match . groups ( ) source_path = path . join ( source , source_path . strip ( '\'"' ) ) if source_path in dotfiles : self . log . warning ( 'Duplicate dotfile source "%s" ' 'on line #%d' , lineno ) continue if target_path is None : target_path = source_path dotfiles [ source_path ] = target_path else : self . log . warning ( 'Dotfile mapping regex failed on line ' '#%d' , lineno ) return dotfiles | Do a simple parse of the dotfile mapping using semicolons to separate source file name from the target file paths . | 658 | 24 |
4,854 | def sh ( self , * command , * * kwargs ) : self . log . debug ( 'shell: %s' , ' ' . join ( command ) ) return subprocess . check_call ( ' ' . join ( command ) , stdout = sys . stdout , stderr = sys . stderr , stdin = sys . stdin , shell = True , * * kwargs ) | Run a shell command with the given arguments . | 88 | 9 |
4,855 | def scp ( self , local_file , remote_path = '' ) : if self . args . user : upload_spec = '{0}@{1}:{2}' . format ( self . args . user , self . args . server , remote_path ) else : upload_spec = '{0}:{1}' . format ( self . args . server , remote_path ) return self . sh ( 'scp' , local_file , upload_spec ) | Copy a local file to the given remote path . | 104 | 10 |
4,856 | def run ( self ) : script = path . realpath ( __file__ ) self . log . debug ( 'Running from %s with arguments: %s' , script , self . args ) if self . args . source : self . source = self . args . source else : # hardcoding as the parent-parent of the script for now self . source = path . dirname ( path . dirname ( script ) ) self . log . debug ( 'Sourcing dotfiles from %s' , self . source ) try : if self . args . repo : self . clone_repo ( ) self . deploy_dotfiles ( self . load_dotfiles ( ) ) except : self . log . exception ( 'Profile deploy failed' ) finally : if self . args . repo : self . cleanup_repo ( ) | Start the dotfile deployment process . | 174 | 7 |
4,857 | def load_dotfiles ( self ) : if self . args . map and path . exists ( self . args . map ) : dotfiles_path = self . args . map else : dotfiles_path = self . source self . log . debug ( 'Loading dotfile mapping from %s' , dotfiles_path ) return self . parse_mapping ( dotfiles_path , source = self . source ) | Read in the dotfile mapping as a dictionary . | 87 | 10 |
4,858 | def clone_repo ( self ) : tempdir_path = tempfile . mkdtemp ( ) if self . args . git : self . log . debug ( 'Cloning git source repository from %s to %s' , self . source , tempdir_path ) self . sh ( 'git clone' , self . source , tempdir_path ) else : raise NotImplementedError ( 'Unknown repo type' ) self . source = tempdir_path | Clone a repository containing the dotfiles source . | 99 | 10 |
4,859 | def cleanup_repo ( self ) : if self . source and path . isdir ( self . source ) : self . log . debug ( 'Cleaning up source repo from %s' , self . source ) shutil . rmtree ( self . source ) | Cleanup the temporary directory containing the dotfiles repo . | 56 | 11 |
4,860 | def deploy_dotfiles ( self , dotfiles ) : if self . args . server : return self . deploy_remote ( dotfiles ) else : return self . deploy_local ( dotfiles ) | Deploy dotfiles using the appropriate method . | 41 | 8 |
4,861 | def deploy_remote ( self , dotfiles ) : tempfile_path = None tempdir_path = None try : tempdir_path = tempfile . mkdtemp ( ) self . log . debug ( 'Deploying to temp dir %s' , tempdir_path ) self . deploy_local ( dotfiles , target_root = tempdir_path ) if self . args . rsync : local_spec = tempdir_path . rstrip ( '/' ) + '/' remote_spec = self . args . path . rstrip ( '/' ) + '/' if self . args . user : remote_spec = "{0}@{1}:{2}" . format ( self . args . user , self . args . server , remote_spec ) else : remote_spec = "{0}:{1}" . format ( self . args . server , remote_spec ) self . log . debug ( 'Using rsync to sync dotfiles to %s' , remote_spec ) self . sh ( 'rsync' , '-az' , local_spec , remote_spec ) else : fh , tempfile_path = tempfile . mkstemp ( suffix = '.tar.gz' ) os . close ( fh ) self . log . debug ( 'Creating tar file %s' , tempfile_path ) shutil . make_archive ( tempfile_path . replace ( '.tar.gz' , '' ) , 'gztar' , tempdir_path ) upload_path = '_profile_upload.tgz' self . log . debug ( 'Uploading tarball to %s' , upload_path ) self . scp ( tempfile_path , upload_path ) if self . args . path : ssh_command = "'mkdir -p {0} && " "tar xf _profile_upload.tgz -C {0}; " "rm -f _profile_upload.tgz'" "" . format ( self . args . path ) else : ssh_command = "tar xf _profile_upload.tgz; " "rm -f _profile_upload.tgz" self . log . debug ( 'Using ssh to unpack tarball and clean up' ) self . ssh ( ssh_command ) finally : if tempdir_path and path . isdir ( tempdir_path ) : self . log . debug ( 'Removing temp dir %s' , tempdir_path ) shutil . rmtree ( tempdir_path ) if tempfile_path and path . isfile ( tempfile_path ) : self . log . debug ( 'Removing temp file %s' , tempfile_path ) os . unlink ( tempfile_path ) | Deploy dotfiles to a remote server . | 579 | 8 |
4,862 | def deploy_local ( self , dotfiles , target_root = None ) : if target_root is None : target_root = self . args . path for source_path , target_path in dotfiles . items ( ) : source_path = path . join ( self . source , source_path ) target_path = path . join ( target_root , target_path ) if path . isfile ( target_path ) or path . islink ( target_path ) : self . log . debug ( 'Removing existing file at %s' , target_path ) os . unlink ( target_path ) elif path . isdir ( target_path ) : self . log . debug ( 'Removing existing dir at %s' , target_path ) shutil . rmtree ( target_path ) parent_dir = path . dirname ( target_path ) if not path . isdir ( parent_dir ) : self . log . debug ( 'Creating parent dir %s' , parent_dir ) os . makedirs ( parent_dir ) if self . args . copy : if path . isdir ( source_path ) : self . log . debug ( 'Copying file %s to %s' , source_path , target_path ) shutil . copytree ( source_path , target_path ) else : self . log . debug ( 'Copying dir %s to %s' , source_path , target_path ) shutil . copy ( source_path , target_path ) else : self . log . debug ( 'Symlinking %s -> %s' , target_path , source_path ) os . symlink ( source_path , target_path ) | Deploy dotfiles to a local path . | 365 | 8 |
4,863 | def dedupe_list ( l ) : result = [ ] for el in l : if el not in result : result . append ( el ) return result | Remove duplicates from a list preserving the order . | 32 | 10 |
4,864 | def plot_amino_diagrams ( self ) : for res in self . topology_data . dict_of_plotted_res : try : color = [ self . colors_amino_acids [ self . amino_acids [ res [ 0 ] ] ] , 'white' ] except KeyError : color = [ "pink" , 'white' ] plt . figure ( figsize = ( 2.5 , 2.5 ) ) ring1 , _ = plt . pie ( [ 1 ] , radius = 1 , startangle = 90 , colors = color , counterclock = False ) plt . axis ( 'equal' ) plt . setp ( ring1 , width = 1 , edgecolor = color [ 0 ] ) if len ( self . topology_data . universe . protein . segments ) <= 1 : #Parameters for amino diagrams without segids plt . text ( 0 , - 0.45 , res [ 0 ] + "\n" + res [ 1 ] , ha = 'center' , size = 36 , fontweight = "bold" ) else : #Parameters for amino diagrams with segids plt . text ( 0 , - 0.37 , res [ 0 ] + "\n" + res [ 1 ] + " " + res [ 2 ] , ha = 'center' , size = 30 , fontweight = "bold" ) #play with the dpi pylab . savefig ( str ( res [ 1 ] ) + res [ 2 ] + ".svg" , dpi = 300 , transparent = True ) | Plotting of amino diagrams - circles with residue name and id colored according to the residue type . If the protein has more than one chain chain identity is also included in the plot . The plot is saved as svg file with residue id and chain id as filename for more certain identification . | 334 | 57 |
4,865 | def get_cases ( variant_source , case_lines = None , case_type = 'ped' , variant_type = 'snv' , variant_mode = 'vcf' ) : individuals = get_individuals ( variant_source = variant_source , case_lines = case_lines , case_type = case_type , variant_mode = variant_mode ) case_objs = [ ] case_ids = set ( ) compressed = False tabix_index = False #If no individuals we still need to have a case id if variant_source . endswith ( '.gz' ) : logger . debug ( "Found compressed variant source" ) compressed = True tabix_file = '.' . join ( [ variant_source , 'tbi' ] ) if os . path . exists ( tabix_file ) : logger . debug ( "Found index file" ) tabix_index = True if len ( individuals ) > 0 : for individual in individuals : case_ids . add ( individual . case_id ) else : case_ids = [ os . path . basename ( variant_source ) ] for case_id in case_ids : logger . info ( "Found case {0}" . format ( case_id ) ) case = Case ( case_id = case_id , name = case_id , variant_source = variant_source , variant_type = variant_type , variant_mode = variant_mode , compressed = compressed , tabix_index = tabix_index ) # Add the individuals to the correct case for individual in individuals : if individual . case_id == case_id : logger . info ( "Adding ind {0} to case {1}" . format ( individual . name , individual . case_id ) ) case . add_individual ( individual ) case_objs . append ( case ) return case_objs | Create a cases and populate it with individuals | 396 | 8 |
4,866 | def handle_message ( self , message ) : if self . _yamaha : if 'power' in message : _LOGGER . debug ( "Power: %s" , message . get ( 'power' ) ) self . _yamaha . power = ( STATE_ON if message . get ( 'power' ) == "on" else STATE_OFF ) if 'input' in message : _LOGGER . debug ( "Input: %s" , message . get ( 'input' ) ) self . _yamaha . _source = message . get ( 'input' ) if 'volume' in message : volume = message . get ( 'volume' ) if 'max_volume' in message : volume_max = message . get ( 'max_volume' ) else : volume_max = self . _yamaha . volume_max _LOGGER . debug ( "Volume: %d / Max: %d" , volume , volume_max ) self . _yamaha . volume = volume / volume_max self . _yamaha . volume_max = volume_max if 'mute' in message : _LOGGER . debug ( "Mute: %s" , message . get ( 'mute' ) ) self . _yamaha . mute = message . get ( 'mute' , False ) else : _LOGGER . debug ( "No yamaha-obj found" ) | Process UDP messages | 303 | 3 |
4,867 | def update_status ( self , new_status = None ) : _LOGGER . debug ( "update_status: Zone %s" , self . zone_id ) if self . status and new_status is None : _LOGGER . debug ( "Zone: healthy." ) else : old_status = self . status or { } if new_status : # merge new_status with existing for comparison _LOGGER . debug ( "Set status: provided" ) # make a copy of the old_status status = old_status . copy ( ) # merge updated items into status status . update ( new_status ) # promote merged_status to new_status new_status = status else : _LOGGER . debug ( "Set status: own" ) new_status = self . get_status ( ) _LOGGER . debug ( "old_status: %s" , old_status ) _LOGGER . debug ( "new_status: %s" , new_status ) _LOGGER . debug ( "is_equal: %s" , old_status == new_status ) if new_status != old_status : self . handle_message ( new_status ) self . _status_sent = False self . status = new_status if not self . _status_sent : self . _status_sent = self . update_hass ( ) | Updates the zone status . | 289 | 6 |
4,868 | def set_power ( self , power ) : req_url = ENDPOINTS [ "setPower" ] . format ( self . ip_address , self . zone_id ) params = { "power" : "on" if power else "standby" } return request ( req_url , params = params ) | Send Power command . | 69 | 4 |
4,869 | def set_mute ( self , mute ) : req_url = ENDPOINTS [ "setMute" ] . format ( self . ip_address , self . zone_id ) params = { "enable" : "true" if mute else "false" } return request ( req_url , params = params ) | Send mute command . | 70 | 4 |
4,870 | def set_volume ( self , volume ) : req_url = ENDPOINTS [ "setVolume" ] . format ( self . ip_address , self . zone_id ) params = { "volume" : int ( volume ) } return request ( req_url , params = params ) | Send Volume command . | 63 | 4 |
4,871 | def set_input ( self , input_id ) : req_url = ENDPOINTS [ "setInput" ] . format ( self . ip_address , self . zone_id ) params = { "input" : input_id } return request ( req_url , params = params ) | Send Input command . | 64 | 4 |
4,872 | def _add_compounds ( self , variant_obj , info_dict ) : compound_list = [ ] compound_entry = info_dict . get ( 'Compounds' ) if compound_entry : for family_annotation in compound_entry . split ( ',' ) : compounds = family_annotation . split ( ':' ) [ - 1 ] . split ( '|' ) for compound in compounds : splitted_compound = compound . split ( '>' ) compound_score = None if len ( splitted_compound ) > 1 : compound_id = splitted_compound [ 0 ] compound_score = int ( splitted_compound [ - 1 ] ) compound_list . append ( Compound ( variant_id = compound_id , combined_score = compound_score ) ) #Sort the compounds based on rank score compound_list . sort ( key = operator . attrgetter ( 'combined_score' ) , reverse = True ) for compound in compound_list : variant_obj . add_compound ( compound ) | Check if there are any compounds and add them to the variant The compounds that are added should be sorted on rank score | 226 | 23 |
4,873 | def load_xml ( fp , object_pairs_hook = dict ) : tree = ET . parse ( fp ) return object_pairs_hook ( _fromXML ( tree . getroot ( ) ) ) | r Parse the contents of the file - like object fp as an XML properties file and return a dict of the key - value pairs . | 48 | 29 |
4,874 | def loads_xml ( s , object_pairs_hook = dict ) : elem = ET . fromstring ( s ) return object_pairs_hook ( _fromXML ( elem ) ) | r Parse the contents of the string s as an XML properties document and return a dict of the key - value pairs . | 44 | 25 |
4,875 | def dump_xml ( props , fp , comment = None , encoding = 'UTF-8' , sort_keys = False ) : fp = codecs . lookup ( encoding ) . streamwriter ( fp , errors = 'xmlcharrefreplace' ) print ( '<?xml version="1.0" encoding={0} standalone="no"?>' . format ( quoteattr ( encoding ) ) , file = fp ) for s in _stream_xml ( props , comment , sort_keys ) : print ( s , file = fp ) | Write a series props of key - value pairs to a binary filehandle fp in the format of an XML properties file . The file will include both an XML declaration and a doctype declaration . | 117 | 39 |
4,876 | def dumps_xml ( props , comment = None , sort_keys = False ) : return '' . join ( s + '\n' for s in _stream_xml ( props , comment , sort_keys ) ) | Convert a series props of key - value pairs to a text string containing an XML properties document . The document will include a doctype declaration but not an XML declaration . | 46 | 34 |
4,877 | def connect ( self , db_uri , debug = False ) : kwargs = { 'echo' : debug , 'convert_unicode' : True } # connect to the SQL database if 'mysql' in db_uri : kwargs [ 'pool_recycle' ] = 3600 elif '://' not in db_uri : logger . debug ( "detected sqlite path URI: {}" . format ( db_uri ) ) db_path = os . path . abspath ( os . path . expanduser ( db_uri ) ) db_uri = "sqlite:///{}" . format ( db_path ) self . engine = create_engine ( db_uri , * * kwargs ) logger . debug ( 'connection established successfully' ) # make sure the same engine is propagated to the BASE classes BASE . metadata . bind = self . engine # start a session self . session = scoped_session ( sessionmaker ( bind = self . engine ) ) # shortcut to query method self . query = self . session . query return self | Configure connection to a SQL database . | 228 | 8 |
4,878 | def select_plugin ( self , case_obj ) : if case_obj . variant_mode == 'vcf' : logger . debug ( "Using vcf plugin" ) plugin = VcfPlugin ( case_obj . variant_type ) elif case_obj . variant_mode == 'gemini' : logger . debug ( "Using gemini plugin" ) plugin = GeminiPlugin ( case_obj . variant_type ) #Add case to plugin plugin . add_case ( case_obj ) self . variant_type = case_obj . variant_type case_id = case_obj . case_id return plugin , case_id | Select and initialize the correct plugin for the case . | 135 | 10 |
4,879 | def index ( ) : gene_lists = app . db . gene_lists ( ) if app . config [ 'STORE_ENABLED' ] else [ ] queries = app . db . gemini_queries ( ) if app . config [ 'STORE_ENABLED' ] else [ ] case_groups = { } for case in app . db . cases ( ) : key = ( case . variant_source , case . variant_type , case . variant_mode ) if key not in case_groups : case_groups [ key ] = [ ] case_groups [ key ] . append ( case ) return render_template ( 'index.html' , case_groups = case_groups , gene_lists = gene_lists , queries = queries ) | Show the landing page . | 162 | 5 |
4,880 | def case ( case_id ) : case_obj = app . db . case ( case_id ) return render_template ( 'case.html' , case = case_obj , case_id = case_id ) | Show the overview for a case . | 47 | 7 |
4,881 | def delete_phenotype ( phenotype_id ) : ind_id = request . form [ 'ind_id' ] ind_obj = app . db . individual ( ind_id ) try : app . db . remove_phenotype ( ind_obj , phenotype_id ) except RuntimeError as error : return abort ( 500 , error . message ) return redirect ( request . referrer ) | Delete phenotype from an individual . | 81 | 6 |
4,882 | def gene_list ( list_id = None ) : all_case_ids = [ case . case_id for case in app . db . cases ( ) ] if list_id : genelist_obj = app . db . gene_list ( list_id ) case_ids = [ case . case_id for case in app . db . cases ( ) if case not in genelist_obj . cases ] if genelist_obj is None : return abort ( 404 , "gene list not found: {}" . format ( list_id ) ) if 'download' in request . args : response = make_response ( '\n' . join ( genelist_obj . gene_ids ) ) filename = secure_filename ( "{}.txt" . format ( genelist_obj . list_id ) ) header = "attachment; filename={}" . format ( filename ) response . headers [ 'Content-Disposition' ] = header return response if request . method == 'POST' : if list_id : # link a case to the gene list case_ids = request . form . getlist ( 'case_id' ) for case_id in case_ids : case_obj = app . db . case ( case_id ) if case_obj not in genelist_obj . cases : genelist_obj . cases . append ( case_obj ) app . db . save ( ) else : # upload a new gene list req_file = request . files [ 'file' ] new_listid = ( request . form [ 'list_id' ] or secure_filename ( req_file . filename ) ) if app . db . gene_list ( new_listid ) : return abort ( 500 , 'Please provide a unique list name' ) if not req_file : return abort ( 500 , 'Please provide a file for upload' ) gene_ids = [ line for line in req_file . stream if not line . startswith ( '#' ) ] genelist_obj = app . db . add_genelist ( new_listid , gene_ids ) case_ids = all_case_ids return render_template ( 'gene_list.html' , gene_list = genelist_obj , case_ids = case_ids ) | Display or add a gene list . | 484 | 7 |
4,883 | def delete_genelist ( list_id , case_id = None ) : if case_id : # unlink a case from a gene list case_obj = app . db . case ( case_id ) app . db . remove_genelist ( list_id , case_obj = case_obj ) return redirect ( request . referrer ) else : # remove the whole gene list app . db . remove_genelist ( list_id ) return redirect ( url_for ( '.index' ) ) | Delete a whole gene list with links to cases or a link . | 107 | 13 |
4,884 | def resources ( ) : ind_id = request . form [ 'ind_id' ] upload_dir = os . path . abspath ( app . config [ 'UPLOAD_DIR' ] ) req_file = request . files [ 'file' ] filename = secure_filename ( req_file . filename ) file_path = os . path . join ( upload_dir , filename ) name = request . form [ 'name' ] or filename req_file . save ( file_path ) ind_obj = app . db . individual ( ind_id ) app . db . add_resource ( name , file_path , ind_obj ) return redirect ( request . referrer ) | Upload a new resource for an individual . | 145 | 8 |
4,885 | def resource ( resource_id ) : resource_obj = app . db . resource ( resource_id ) if 'raw' in request . args : return send_from_directory ( os . path . dirname ( resource_obj . path ) , os . path . basename ( resource_obj . path ) ) return render_template ( 'resource.html' , resource = resource_obj ) | Show a resource . | 83 | 4 |
4,886 | def comments ( case_id ) : text = request . form [ 'text' ] variant_id = request . form . get ( 'variant_id' ) username = request . form . get ( 'username' ) case_obj = app . db . case ( case_id ) app . db . add_comment ( case_obj , text , variant_id = variant_id , username = username ) return redirect ( request . referrer ) | Upload a new comment . | 95 | 5 |
4,887 | def individual ( ind_id ) : individual_obj = app . db . individual ( ind_id ) return render_template ( 'individual.html' , individual = individual_obj ) | Show details for a specific individual . | 39 | 7 |
4,888 | def synopsis ( case_id ) : text = request . form [ 'text' ] case_obj = app . db . case ( case_id ) app . db . update_synopsis ( case_obj , text ) return redirect ( request . referrer ) | Update the case synopsis . | 55 | 5 |
4,889 | def add_case ( ) : ind_ids = request . form . getlist ( 'ind_id' ) case_id = request . form [ 'case_id' ] source = request . form [ 'source' ] variant_type = request . form [ 'type' ] if len ( ind_ids ) == 0 : return abort ( 400 , "must add at least one member of case" ) # only GEMINI supported new_case = Case ( case_id = case_id , name = case_id , variant_source = source , variant_type = variant_type , variant_mode = 'gemini' ) # Add individuals to the correct case for ind_id in ind_ids : ind_obj = app . db . individual ( ind_id ) new_case . individuals . append ( ind_obj ) app . db . session . add ( new_case ) app . db . save ( ) return redirect ( url_for ( '.case' , case_id = new_case . name ) ) | Make a new case out of a list of individuals . | 219 | 11 |
4,890 | def print_sub ( tables ) : logger = logging . getLogger ( "meepo.sub.print_sub" ) logger . info ( "print_sub tables: %s" % ", " . join ( tables ) ) if not isinstance ( tables , ( list , set ) ) : raise ValueError ( "tables should be list or set" ) events = ( "%s_%s" % ( tb , action ) for tb , action in itertools . product ( * [ tables , [ "write" , "update" , "delete" ] ] ) ) for event in events : signal ( event ) . connect ( lambda pk : logger . info ( "%s -> %s" % event , pk ) , weak = False ) | Dummy print sub . | 163 | 5 |
4,891 | def binary_to_term ( data ) : if not isinstance ( data , bytes ) : raise ParseException ( 'not bytes input' ) size = len ( data ) if size <= 1 : raise ParseException ( 'null input' ) if b_ord ( data [ 0 ] ) != _TAG_VERSION : raise ParseException ( 'invalid version' ) try : i , term = _binary_to_term ( 1 , data ) if i != size : raise ParseException ( 'unparsed data' ) return term except struct . error : raise ParseException ( 'missing data' ) except IndexError : raise ParseException ( 'missing data' ) | Decode Erlang terms within binary data into Python types | 145 | 11 |
4,892 | def term_to_binary ( term , compressed = False ) : data_uncompressed = _term_to_binary ( term ) if compressed is False : return b_chr ( _TAG_VERSION ) + data_uncompressed else : if compressed is True : compressed = 6 if compressed < 0 or compressed > 9 : raise InputException ( 'compressed in [0..9]' ) data_compressed = zlib . compress ( data_uncompressed , compressed ) size_uncompressed = len ( data_uncompressed ) if size_uncompressed > 4294967295 : raise OutputException ( 'uint32 overflow' ) return ( b_chr ( _TAG_VERSION ) + b_chr ( _TAG_COMPRESSED_ZLIB ) + struct . pack ( b'>I' , size_uncompressed ) + data_compressed ) | Encode Python types into Erlang terms in binary data | 188 | 11 |
4,893 | def _parseLine ( cls , line ) : r = cls . _PROG . match ( line ) if not r : raise ValueError ( "Error: parsing '%s'. Correct: \"<number> <number> [<text>]\"" % line ) d = r . groupdict ( ) if len ( d [ 'begin' ] ) == 0 or len ( d [ 'end' ] ) == 0 : raise ValueError ( "Error: parsing '%s'. Correct: \"<number> <number> [<text>]\"" % line ) return AudioClipSpec ( d [ 'begin' ] , d [ 'end' ] , d [ 'text' ] . strip ( ) ) | Parsers a single line of text and returns an AudioClipSpec | 152 | 15 |
4,894 | def mode_name ( self ) : for name , id in self . MODES . iteritems ( ) : if id == self . mode : return name | Returns the tunnel mode s name for printing purpose . | 32 | 10 |
4,895 | def open ( self ) : if self . fd is not None : raise self . AlreadyOpened ( ) logger . debug ( "Opening %s..." % ( TUN_KO_PATH , ) ) self . fd = os . open ( TUN_KO_PATH , os . O_RDWR ) logger . debug ( "Opening %s tunnel '%s'..." % ( self . mode_name . upper ( ) , self . pattern , ) ) try : ret = fcntl . ioctl ( self . fd , self . TUNSETIFF , struct . pack ( "16sH" , self . pattern , self . mode | self . no_pi ) ) except IOError , e : if e . errno == 1 : logger . error ( "Cannot open a %s tunnel because the operation is not permitted." % ( self . mode_name . upper ( ) , ) ) raise self . NotPermitted ( ) raise self . name = ret [ : 16 ] . strip ( "\x00" ) logger . info ( "Tunnel '%s' opened." % ( self . name , ) ) | Create the tunnel . If the tunnel is already opened the function will raised an AlreadyOpened exception . | 242 | 20 |
4,896 | def close ( self ) : if self . fd is None : return logger . debug ( "Closing tunnel '%s'..." % ( self . name or "" , ) ) # Close tun.ko file os . close ( self . fd ) self . fd = None logger . info ( "Tunnel '%s' closed." % ( self . name or "" , ) ) | Close the tunnel . If the tunnel is already closed or never opened do nothing . | 83 | 16 |
4,897 | def recv ( self , size = None ) : size = size if size is not None else 1500 return os . read ( self . fd , size ) | Receive a buffer . The default size is 1500 the classical MTU . | 33 | 15 |
4,898 | def download ( self ) : p = Pool ( ) p . map ( self . _download , self . days ) | MLBAM dataset download | 24 | 5 |
4,899 | def count_by_type ( self ) : saltbridges = defaultdict ( int ) for contact in self . timeseries : #count by residue name not by proteinring pkey = ( contact . ligandatomid , contact . ligandatomname , contact . resid , contact . resname , contact . segid ) saltbridges [ pkey ] += 1 dtype = [ ( "ligand_atom_id" , int ) , ( "ligand_atom_name" , "|U4" ) , ( "resid" , int ) , ( "resname" , "|U4" ) , ( "segid" , "|U8" ) , ( "frequency" , float ) ] out = np . empty ( ( len ( saltbridges ) , ) , dtype = dtype ) tsteps = float ( len ( self . timesteps ) ) for cursor , ( key , count ) in enumerate ( saltbridges . iteritems ( ) ) : out [ cursor ] = key + ( count / tsteps , ) return out . view ( np . recarray ) | Count how many times each individual salt bridge occured throughout the simulation . Returns numpy array . | 238 | 19 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.