idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
5,900 | def stage ( obj , parent = None , member = None ) : obj = Staged ( obj , parent , member ) if isinstance ( obj , Mapping ) : for key , value in obj . items ( ) : stage ( value , obj , key ) elif isinstance ( obj , Sequence ) and not isinstance ( obj , string_types ) : for index , value in enumerate ( obj ) : stage ( value , obj , index ) elif isinstance ( obj , Set ) : for value in obj : stage ( value , obj , None ) return obj | Prepare obj to be staged . | 119 | 7 |
5,901 | def rotate ( key_prefix , key_ext , bucket_name , daily_backups = 7 , weekly_backups = 4 , aws_key = None , aws_secret = None ) : session = boto3 . Session ( aws_access_key_id = aws_key , aws_secret_access_key = aws_secret ) s3 = session . resource ( 's3' ) bucket = s3 . Bucket ( bucket_name ) keys = bucket . objects . filter ( Prefix = key_prefix ) regex = '{0}-(?P<year>[\d]+?)-(?P<month>[\d]+?)-(?P<day>[\d]+?){1}' . format ( key_prefix , key_ext ) backups = [ ] for key in keys : match = re . match ( regex , str ( key . key ) ) if not match : continue year = int ( match . group ( 'year' ) ) month = int ( match . group ( 'month' ) ) day = int ( match . group ( 'day' ) ) key_date = datetime ( year , month , day ) backups [ : 0 ] = [ key_date ] backups = sorted ( backups , reverse = True ) if len ( backups ) > daily_backups + 1 and backups [ daily_backups ] - backups [ daily_backups + 1 ] < timedelta ( days = 7 ) : key = bucket . Object ( "{0}{1}{2}" . format ( key_prefix , backups [ daily_backups ] . strftime ( "-%Y-%m-%d" ) , key_ext ) ) logger . debug ( "deleting {0}" . format ( key ) ) key . delete ( ) del backups [ daily_backups ] month_offset = daily_backups + weekly_backups if len ( backups ) > month_offset + 1 and backups [ month_offset ] - backups [ month_offset + 1 ] < timedelta ( days = 30 ) : key = bucket . Object ( "{0}{1}{2}" . format ( key_prefix , backups [ month_offset ] . strftime ( "-%Y-%m-%d" ) , key_ext ) ) logger . debug ( "deleting {0}" . format ( key ) ) key . delete ( ) del backups [ month_offset ] | Delete old files we ve uploaded to S3 according to grandfather father sun strategy | 513 | 15 |
5,902 | def splitext ( filename ) : index = filename . find ( '.' ) if index == 0 : index = 1 + filename [ 1 : ] . find ( '.' ) if index == - 1 : return filename , '' return filename [ : index ] , filename [ index : ] return os . path . splitext ( filename ) | Return the filename and extension according to the first dot in the filename . This helps date stamping . tar . bz2 or . ext . gz files properly . | 70 | 34 |
5,903 | def start_fitting ( self ) : self . queue = queue . Queue ( ) self . peak_vals = [ ] self . fit_thread = QThread ( ) #must be assigned as an instance variable, not local, as otherwise thread is garbage #collected immediately at the end of the function before it runs self . fitobj = self . do_fit ( str ( self . data_filepath . text ( ) ) , self . matplotlibwidget , self . queue , self . peak_vals , self . peak_locs ) self . fitobj . moveToThread ( self . fit_thread ) self . fit_thread . started . connect ( self . fitobj . run ) self . fitobj . finished . connect ( self . fit_thread . quit ) # clean up. quit thread after script is finished self . fitobj . status . connect ( self . update_status ) self . fit_thread . start ( ) | Launches the fitting routine on another thread | 198 | 8 |
5,904 | def _get_bandgap_from_bands ( energies , nelec ) : nelec = int ( nelec ) valence = [ x [ nelec - 1 ] for x in energies ] conduction = [ x [ nelec ] for x in energies ] return max ( min ( conduction ) - max ( valence ) , 0.0 ) | Compute difference in conduction band min and valence band max | 79 | 13 |
5,905 | def _get_bandgap_eigenval ( eigenval_fname , outcar_fname ) : with open ( outcar_fname , "r" ) as f : parser = OutcarParser ( ) nelec = next ( iter ( filter ( lambda x : "number of electrons" in x , parser . parse ( f . readlines ( ) ) ) ) ) [ "number of electrons" ] with open ( eigenval_fname , "r" ) as f : eigenval_info = list ( EigenvalParser ( ) . parse ( f . readlines ( ) ) ) # spin_polarized = (2 == len(next(filter(lambda x: "kpoint" in x, eigenval_info))["occupancies"][0])) # if spin_polarized: all_energies = [ zip ( * x [ "energies" ] ) for x in eigenval_info if "energies" in x ] spin_energies = zip ( * all_energies ) gaps = [ VaspParser . _get_bandgap_from_bands ( x , nelec / 2.0 ) for x in spin_energies ] return min ( gaps ) | Get the bandgap from the EIGENVAL file | 272 | 11 |
5,906 | def _get_bandgap_doscar ( filename ) : with open ( filename ) as fp : for i in range ( 6 ) : l = fp . readline ( ) efermi = float ( l . split ( ) [ 3 ] ) step1 = fp . readline ( ) . split ( ) [ 0 ] step2 = fp . readline ( ) . split ( ) [ 0 ] step_size = float ( step2 ) - float ( step1 ) not_found = True while not_found : l = fp . readline ( ) . split ( ) e = float ( l . pop ( 0 ) ) dens = 0.0 for i in range ( int ( len ( l ) / 2 ) ) : dens += float ( l [ i ] ) if e < efermi and dens > 1e-3 : bot = e elif e > efermi and dens > 1e-3 : top = e not_found = False if top - bot < step_size * 2 : bandgap = 0.0 else : bandgap = float ( top - bot ) return bandgap | Get the bandgap from the DOSCAR file | 238 | 9 |
5,907 | def get_band_gap ( self ) : if self . outcar is not None and self . eignval is not None : bandgap = VaspParser . _get_bandgap_eigenval ( self . eignval , self . outcar ) elif self . doscar is not None : bandgap = VaspParser . _get_bandgap_doscar ( self . doscar ) else : return None return Property ( scalars = [ Scalar ( value = round ( bandgap , 3 ) ) ] , units = 'eV' ) | Get the bandgap either from the EIGENVAL or DOSCAR files | 120 | 15 |
5,908 | def get_value_by_xy ( self , x , y ) : if x < self . xMin or x > self . xMax or y < self . yMin or y > self . yMax : return None # raise ValueError("The x or y value must be within the Min and Max!") else : row = self . nRows - int ( numpy . ceil ( ( y - self . yMin ) / self . dx ) ) col = int ( numpy . floor ( ( x - self . xMin ) / self . dx ) ) value = self . data [ row ] [ col ] if value == self . noDataValue : return None else : return value | Get raster value by xy coordinates . | 147 | 9 |
5,909 | def get_central_coors ( self , row , col ) : if row < 0 or row >= self . nRows or col < 0 or col >= self . nCols : raise ValueError ( "The row (%d) or col (%d) must be >=0 and less than " "nRows (%d) or nCols (%d)!" % ( row , col , self . nRows , self . nCols ) ) else : tmpx = self . xMin + ( col + 0.5 ) * self . dx tmpy = self . yMax - ( row + 0.5 ) * self . dx return tmpx , tmpy | Get the coordinates of central grid . | 143 | 7 |
5,910 | def read_raster ( raster_file ) : ds = gdal_Open ( raster_file ) band = ds . GetRasterBand ( 1 ) data = band . ReadAsArray ( ) xsize = band . XSize ysize = band . YSize nodata_value = band . GetNoDataValue ( ) geotrans = ds . GetGeoTransform ( ) dttype = band . DataType srs = osr_SpatialReference ( ) srs . ImportFromWkt ( ds . GetProjection ( ) ) # print(srs.ExportToProj4()) if nodata_value is None : nodata_value = DEFAULT_NODATA band = None ds = None return Raster ( ysize , xsize , data , nodata_value , geotrans , srs , dttype ) | Read raster by GDAL . | 188 | 7 |
5,911 | def get_mask_from_raster ( rasterfile , outmaskfile , keep_nodata = False ) : raster_r = RasterUtilClass . read_raster ( rasterfile ) xsize = raster_r . nCols ysize = raster_r . nRows nodata_value = raster_r . noDataValue srs = raster_r . srs x_min = raster_r . xMin y_max = raster_r . yMax dx = raster_r . dx data = raster_r . data if not keep_nodata : i_min = ysize - 1 i_max = 0 j_min = xsize - 1 j_max = 0 for i in range ( ysize ) : for j in range ( xsize ) : if abs ( data [ i ] [ j ] - nodata_value ) > DELTA : i_min = min ( i , i_min ) i_max = max ( i , i_max ) j_min = min ( j , j_min ) j_max = max ( j , j_max ) # print(i_min, i_max, j_min, j_max) y_size_mask = i_max - i_min + 1 x_size_mask = j_max - j_min + 1 x_min_mask = x_min + j_min * dx y_max_mask = y_max - i_min * dx else : y_size_mask = ysize x_size_mask = xsize x_min_mask = x_min y_max_mask = y_max i_min = 0 j_min = 0 print ( '%dx%d -> %dx%d' % ( xsize , ysize , x_size_mask , y_size_mask ) ) mask = numpy . zeros ( ( y_size_mask , x_size_mask ) ) for i in range ( y_size_mask ) : for j in range ( x_size_mask ) : if abs ( data [ i + i_min ] [ j + j_min ] - nodata_value ) > DELTA : mask [ i ] [ j ] = 1 else : mask [ i ] [ j ] = DEFAULT_NODATA mask_geotrans = [ x_min_mask , dx , 0 , y_max_mask , 0 , - dx ] RasterUtilClass . write_gtiff_file ( outmaskfile , y_size_mask , x_size_mask , mask , mask_geotrans , srs , DEFAULT_NODATA , GDT_Int32 ) return Raster ( y_size_mask , x_size_mask , mask , DEFAULT_NODATA , mask_geotrans , srs ) | Generate mask data from a given raster data . | 623 | 11 |
5,912 | def raster_reclassify ( srcfile , v_dict , dstfile , gdaltype = GDT_Float32 ) : src_r = RasterUtilClass . read_raster ( srcfile ) src_data = src_r . data dst_data = numpy . copy ( src_data ) if gdaltype == GDT_Float32 and src_r . dataType != GDT_Float32 : gdaltype = src_r . dataType no_data = src_r . noDataValue new_no_data = DEFAULT_NODATA if gdaltype in [ GDT_Unknown , GDT_Byte , GDT_UInt16 , GDT_UInt32 ] : new_no_data = 0 if not MathClass . floatequal ( new_no_data , src_r . noDataValue ) : if src_r . noDataValue not in v_dict : v_dict [ src_r . noDataValue ] = new_no_data no_data = new_no_data for ( k , v ) in iteritems ( v_dict ) : dst_data [ src_data == k ] = v RasterUtilClass . write_gtiff_file ( dstfile , src_r . nRows , src_r . nCols , dst_data , src_r . geotrans , src_r . srs , no_data , gdaltype ) | Reclassify raster by given classifier dict . | 315 | 11 |
5,913 | def write_gtiff_file ( f_name , n_rows , n_cols , data , geotransform , srs , nodata_value , gdal_type = GDT_Float32 ) : UtilClass . mkdir ( os . path . dirname ( FileClass . get_file_fullpath ( f_name ) ) ) driver = gdal_GetDriverByName ( str ( 'GTiff' ) ) try : ds = driver . Create ( f_name , n_cols , n_rows , 1 , gdal_type ) except Exception : print ( 'Cannot create output file %s' % f_name ) return ds . SetGeoTransform ( geotransform ) try : ds . SetProjection ( srs . ExportToWkt ( ) ) except AttributeError or Exception : ds . SetProjection ( srs ) ds . GetRasterBand ( 1 ) . SetNoDataValue ( nodata_value ) # if data contains numpy.nan, then replaced by nodata_value if isinstance ( data , numpy . ndarray ) and data . dtype in [ numpy . dtype ( 'int' ) , numpy . dtype ( 'float' ) ] : data = numpy . where ( numpy . isnan ( data ) , nodata_value , data ) ds . GetRasterBand ( 1 ) . WriteArray ( data ) ds = None | Output Raster to GeoTiff format file . | 317 | 10 |
5,914 | def write_asc_file ( filename , data , xsize , ysize , geotransform , nodata_value ) : UtilClass . mkdir ( os . path . dirname ( FileClass . get_file_fullpath ( filename ) ) ) header = 'NCOLS %d\n' 'NROWS %d\n' 'XLLCENTER %f\n' 'YLLCENTER %f\n' 'CELLSIZE %f\n' 'NODATA_VALUE %f' % ( xsize , ysize , geotransform [ 0 ] + 0.5 * geotransform [ 1 ] , geotransform [ 3 ] - ( ysize - 0.5 ) * geotransform [ 1 ] , geotransform [ 1 ] , nodata_value ) with open ( filename , 'w' , encoding = 'utf-8' ) as f : f . write ( header ) for i in range ( 0 , ysize ) : for j in range ( 0 , xsize ) : f . write ( '%s\t' % repr ( data [ i ] [ j ] ) ) f . write ( '\n' ) f . close ( ) | Output Raster to ASCII file . | 263 | 7 |
5,915 | def raster_to_gtiff ( tif , geotif , change_nodata = False , change_gdal_type = False ) : rst_file = RasterUtilClass . read_raster ( tif ) nodata = rst_file . noDataValue if change_nodata : if not MathClass . floatequal ( rst_file . noDataValue , DEFAULT_NODATA ) : nodata = DEFAULT_NODATA rst_file . data [ rst_file . data == rst_file . noDataValue ] = DEFAULT_NODATA gdal_type = rst_file . dataType if change_gdal_type : gdal_type = GDT_Float32 RasterUtilClass . write_gtiff_file ( geotif , rst_file . nRows , rst_file . nCols , rst_file . data , rst_file . geotrans , rst_file . srs , nodata , gdal_type ) | Converting Raster format to GeoTIFF . | 233 | 10 |
5,916 | def raster_to_asc ( raster_f , asc_f ) : raster_r = RasterUtilClass . read_raster ( raster_f ) RasterUtilClass . write_asc_file ( asc_f , raster_r . data , raster_r . nCols , raster_r . nRows , raster_r . geotrans , raster_r . noDataValue ) | Converting Raster format to ASCII raster . | 98 | 10 |
5,917 | def raster_statistics ( raster_file ) : ds = gdal_Open ( raster_file ) band = ds . GetRasterBand ( 1 ) minv , maxv , meanv , std = band . ComputeStatistics ( False ) return minv , maxv , meanv , std | Get basic statistics of raster data . | 68 | 8 |
5,918 | def split_raster ( rs , split_shp , field_name , temp_dir ) : UtilClass . rmmkdir ( temp_dir ) ds = ogr_Open ( split_shp ) lyr = ds . GetLayer ( 0 ) lyr . ResetReading ( ) ft = lyr . GetNextFeature ( ) while ft : cur_field_name = ft . GetFieldAsString ( field_name ) for r in rs : cur_file_name = r . split ( os . sep ) [ - 1 ] outraster = temp_dir + os . sep + cur_file_name . replace ( '.tif' , '_%s.tif' % cur_field_name . replace ( ' ' , '_' ) ) subprocess . call ( [ 'gdalwarp' , r , outraster , '-cutline' , split_shp , '-crop_to_cutline' , '-cwhere' , "'%s'='%s'" % ( field_name , cur_field_name ) , '-dstnodata' , '-9999' ] ) ft = lyr . GetNextFeature ( ) ds = None | Split raster by given shapefile and field name . | 259 | 11 |
5,919 | def get_negative_dem ( raw_dem , neg_dem ) : origin = RasterUtilClass . read_raster ( raw_dem ) max_v = numpy . max ( origin . data ) temp = origin . data < 0 neg = numpy . where ( temp , origin . noDataValue , max_v - origin . data ) RasterUtilClass . write_gtiff_file ( neg_dem , origin . nRows , origin . nCols , neg , origin . geotrans , origin . srs , origin . noDataValue , origin . dataType ) | Get negative DEM data . | 129 | 5 |
5,920 | def raster_binarization ( given_value , rasterfilename ) : origin_raster = RasterUtilClass . read_raster ( rasterfilename ) binary_raster = numpy . where ( origin_raster . data == given_value , 1 , 0 ) return binary_raster | Make the raster into binarization . | 67 | 9 |
5,921 | def raster_erosion ( rasterfile ) : if is_string ( rasterfile ) : origin_raster = RasterUtilClass . read_raster ( str ( rasterfile ) ) elif isinstance ( rasterfile , Raster ) : origin_raster = rasterfile . data elif isinstance ( rasterfile , numpy . ndarray ) : origin_raster = rasterfile else : return "Your rasterfile has a wrong type. Type must be string or " "numpy.array or class Raster in pygeoc." max_value_raster = origin_raster . max ( ) erosion_raster = numpy . zeros ( ( origin_raster . shape [ 0 ] , origin_raster . shape [ 1 ] ) ) # In order to compute the raster edges, we need to expand the original # raster's rows and cols. We need to add the edges whose pixels' value is # the max pixel's value in raster. add_row = numpy . full ( ( 1 , origin_raster . shape [ 1 ] ) , max_value_raster ) temp_origin_raster = numpy . vstack ( ( numpy . vstack ( ( add_row , origin_raster ) ) , add_row ) ) add_col = numpy . full ( ( origin_raster . shape [ 0 ] + 2 , 1 ) , max_value_raster ) expand_origin_raster = numpy . hstack ( ( numpy . hstack ( ( add_col , temp_origin_raster ) ) , add_col ) ) # Erode the raster. for i in range ( origin_raster . shape [ 0 ] ) : for j in range ( origin_raster . shape [ 1 ] ) : min_pixel_value = max_value_raster # Find the min pixel value in the 8-neighborhood. for k in range ( 3 ) : for l in range ( 3 ) : if expand_origin_raster [ i + k , j + l ] <= min_pixel_value : min_pixel_value = expand_origin_raster [ i + k , j + l ] # After this loop, we get the min pixel's value of the # 8-neighborhood. Then we change the compute pixel's value into # the min pixel's value. erosion_raster [ i , j ] = min_pixel_value # Return the result. return erosion_raster | Erode the raster image . | 548 | 8 |
5,922 | def raster_dilation ( rasterfile ) : if is_string ( rasterfile ) : origin_raster = RasterUtilClass . read_raster ( str ( rasterfile ) ) elif isinstance ( rasterfile , Raster ) : origin_raster = rasterfile . data elif isinstance ( rasterfile , numpy . ndarray ) : origin_raster = rasterfile else : return 'Your rasterfile has a wrong type. Type must be string or ' 'numpy.array or class Raster in pygeoc.' min_value_raster = origin_raster . min ( ) dilation_raster = numpy . zeros ( ( origin_raster . shape [ 0 ] , origin_raster . shape [ 1 ] ) ) # In order to compute the raster edges, we need to expand the original # raster's rows and cols. We need to add the edges whose pixels' value is # the max pixel's value in raster. add_row = numpy . full ( ( 1 , origin_raster . shape [ 1 ] ) , min_value_raster ) temp_origin_raster = numpy . vstack ( ( numpy . vstack ( ( add_row , origin_raster ) ) , add_row ) ) add_col = numpy . full ( ( origin_raster . shape [ 0 ] + 2 , 1 ) , min_value_raster ) expand_origin_raster = numpy . hstack ( ( numpy . hstack ( ( add_col , temp_origin_raster ) ) , add_col ) ) # Dilate the raster. for i in range ( origin_raster . shape [ 0 ] ) : for j in range ( origin_raster . shape [ 1 ] ) : max_pixel_value = min_value_raster # Find the max pixel value in the 8-neighborhood. for k in range ( 3 ) : for l in range ( 3 ) : if expand_origin_raster [ i + k , j + l ] >= max_pixel_value : max_pixel_value = expand_origin_raster [ i + k , j + l ] # After this loop, we get the max pixel's value of the # 8-neighborhood. Then we change the compute pixel's value into # the max pixel's value. dilation_raster [ i , j ] = max_pixel_value # Return the result. return dilation_raster | Dilate the raster image . | 550 | 8 |
5,923 | def openning ( input_rasterfilename , times ) : input_raster = RasterUtilClass . read_raster ( input_rasterfilename ) openning_raster = input_raster for i in range ( times ) : openning_raster = RasterUtilClass . raster_erosion ( openning_raster ) for i in range ( times ) : openning_raster = RasterUtilClass . raster_dilation ( openning_raster ) return openning_raster | Do openning . | 115 | 4 |
5,924 | def closing ( input_rasterfilename , times ) : input_raster = RasterUtilClass . read_raster ( input_rasterfilename ) closing_raster = input_raster for i in range ( times ) : closing_raster = RasterUtilClass . raster_dilation ( closing_raster ) for i in range ( times ) : closing_raster = RasterUtilClass . raster_erosion ( closing_raster ) return closing_raster | Do closing . | 108 | 3 |
5,925 | def calculate_tx_fee ( tx_size : int ) -> Decimal : per_kb_cost = 0.01 min_fee = Decimal ( 0.001 ) fee = Decimal ( ( tx_size / 1000 ) * per_kb_cost ) if fee <= min_fee : return min_fee else : return fee | return tx fee from tx size in bytes | 71 | 8 |
5,926 | def p2sh_p2pkh_script ( network : str , address : str ) -> P2shScript : network_params = net_query ( network ) addr = Address . from_string ( network = network_params , string = address ) p2pkh = P2pkhScript ( addr ) return P2shScript ( p2pkh ) | p2sh embedding p2pkh | 78 | 9 |
5,927 | def tx_output ( network : str , value : Decimal , n : int , script : ScriptSig ) -> TxOut : network_params = net_query ( network ) return TxOut ( network = network_params , value = int ( value * network_params . to_unit ) , n = n , script_pubkey = script ) | create TxOut object | 76 | 5 |
5,928 | def make_raw_transaction ( network : str , inputs : list , outputs : list , locktime : Locktime , timestamp : int = int ( time ( ) ) , version : int = 1 , ) -> MutableTransaction : network_params = net_query ( network ) if network_params . name . startswith ( "peercoin" ) : return MutableTransaction ( version = version , ins = inputs , outs = outputs , locktime = locktime , network = network_params , timestamp = timestamp , ) return MutableTransaction ( version = version , ins = inputs , outs = outputs , locktime = locktime , network = network_params , ) | create raw transaction | 140 | 3 |
5,929 | def find_parent_outputs ( provider : Provider , utxo : TxIn ) -> TxOut : network_params = net_query ( provider . network ) index = utxo . txout # utxo index return TxOut . from_json ( provider . getrawtransaction ( utxo . txid , 1 ) [ 'vout' ] [ index ] , network = network_params ) | due to design of the btcpy library TxIn object must be converted to TxOut object before signing | 91 | 23 |
5,930 | def sign_transaction ( provider : Provider , unsigned : MutableTransaction , key : Kutil ) -> Transaction : parent_outputs = [ find_parent_outputs ( provider , i ) for i in unsigned . ins ] return key . sign_transaction ( parent_outputs , unsigned ) | sign transaction with Kutil | 63 | 5 |
5,931 | def set_style ( style = 'basic' , * * kwargs ) : style = _read_style ( style ) # Add basic style as the first style if style [ 0 ] != 'basic' : style = [ 'basic' ] + style # Apply all styles for s in style : _set_style ( s , * * kwargs ) | Changes Matplotlib basic style to produce high quality graphs . Call this function at the beginning of your script . You can even further improve graphs with a call to fix_style at the end of your script . | 76 | 42 |
5,932 | def fix_style ( style = 'basic' , ax = None , * * kwargs ) : style = _read_style ( style ) # Apply all styles for s in style : if not s in style_params . keys ( ) : avail = [ f . replace ( '.mplstyle' , '' ) for f in os . listdir ( _get_lib ( ) ) if f . endswith ( '.mplstyle' ) ] raise ValueError ( '{0} is not a valid style. ' . format ( s ) + 'Please pick a style from the list available in ' + '{0}: {1}' . format ( _get_lib ( ) , avail ) ) _fix_style ( style , ax , * * kwargs ) | Add an extra formatting layer to an axe that couldn t be changed directly in matplotlib . rcParams or with styles . Apply this function to every axe you created . | 165 | 35 |
5,933 | def _get_label ( self ) : if self . _label is None : foundfiles = False for f in self . _files : if ".files" in f : foundfiles = True self . _label = f . split ( "." ) [ 0 ] with open ( self . _label + '.files' , 'r' ) as fp : line = fp . readline ( ) . split ( ) [ 0 ] if line != self . _label + ".in" : fp . close ( ) raise Exception ( 'first line must be label.in' ) line = fp . readline ( ) . split ( ) [ 0 ] if line != self . _label + ".txt" : fp . close ( ) raise Exception ( 'second line must be label.txt' ) line = fp . readline ( ) . split ( ) [ 0 ] if line != self . _label + "i" : fp . close ( ) raise Exception ( 'third line must be labeli' ) line = fp . readline ( ) . split ( ) [ 0 ] if line != self . _label + "o" : fp . close ( ) raise Exception ( 'fourth line must be labelo' ) fp . close ( ) if foundfiles : return self . _label else : raise Exception ( 'label.files not found' ) #ASE format # (self.prefix + '.in') # input # (self.prefix + '.txt')# output # (self.prefix + 'i') # input # (self.prefix + 'o') # output else : return self . _label | Find the label for the output files for this calculation | 343 | 10 |
5,934 | def next_player ( self ) : logging . warning ( 'turn={}, players={}' . format ( self . game . _cur_turn , self . game . players ) ) return self . game . players [ ( self . game . _cur_turn + 1 ) % len ( self . game . players ) ] | Returns the player whose turn it will be next . | 68 | 10 |
5,935 | def plot ( self , figure_list ) : #TODO: be smarter about how we plot ScriptIterator if self . _current_subscript_stage is not None : if self . _current_subscript_stage [ 'current_subscript' ] is not None : self . _current_subscript_stage [ 'current_subscript' ] . plot ( figure_list ) if ( self . is_running is False ) and not ( self . data == { } or self . data is None ) : script_names = list ( self . settings [ 'script_order' ] . keys ( ) ) script_indices = [ self . settings [ 'script_order' ] [ name ] for name in script_names ] _ , sorted_script_names = list ( zip ( * sorted ( zip ( script_indices , script_names ) ) ) ) last_script = self . scripts [ sorted_script_names [ - 1 ] ] last_script . force_update ( ) # since we use the last script plot function we force it to refresh axes_list = last_script . get_axes_layout ( figure_list ) # catch error is _plot function doens't take optional data argument try : last_script . _plot ( axes_list , self . data ) except TypeError as err : print ( ( warnings . warn ( 'can\'t plot average script data because script.plot function doens\'t take data as optional argument. Plotting last data set instead' ) ) ) print ( ( err . message ) ) last_script . plot ( figure_list ) | When each subscript is called uses its standard plotting | 341 | 9 |
5,936 | def raster2shp ( rasterfile , vectorshp , layername = None , fieldname = None , band_num = 1 , mask = 'default' ) : FileClass . remove_files ( vectorshp ) FileClass . check_file_exists ( rasterfile ) # this allows GDAL to throw Python Exceptions gdal . UseExceptions ( ) src_ds = gdal . Open ( rasterfile ) if src_ds is None : print ( 'Unable to open %s' % rasterfile ) sys . exit ( 1 ) try : srcband = src_ds . GetRasterBand ( band_num ) except RuntimeError as e : # for example, try GetRasterBand(10) print ( 'Band ( %i ) not found, %s' % ( band_num , e ) ) sys . exit ( 1 ) if mask == 'default' : maskband = srcband . GetMaskBand ( ) elif mask is None or mask . upper ( ) == 'NONE' : maskband = None else : mask_ds = gdal . Open ( mask ) maskband = mask_ds . GetRasterBand ( 1 ) # create output datasource if layername is None : layername = FileClass . get_core_name_without_suffix ( rasterfile ) drv = ogr_GetDriverByName ( str ( 'ESRI Shapefile' ) ) dst_ds = drv . CreateDataSource ( vectorshp ) srs = None if src_ds . GetProjection ( ) != '' : srs = osr_SpatialReference ( ) srs . ImportFromWkt ( src_ds . GetProjection ( ) ) dst_layer = dst_ds . CreateLayer ( str ( layername ) , srs = srs ) if fieldname is None : fieldname = layername . upper ( ) fd = ogr_FieldDefn ( str ( fieldname ) , OFTInteger ) dst_layer . CreateField ( fd ) dst_field = 0 result = gdal . Polygonize ( srcband , maskband , dst_layer , dst_field , [ '8CONNECTED=8' ] , callback = None ) return result | Convert raster to ESRI shapefile | 477 | 9 |
5,937 | def convert2geojson ( jsonfile , src_srs , dst_srs , src_file ) : if os . path . exists ( jsonfile ) : os . remove ( jsonfile ) if sysstr == 'Windows' : exepath = '"%s/Lib/site-packages/osgeo/ogr2ogr"' % sys . exec_prefix else : exepath = FileClass . get_executable_fullpath ( 'ogr2ogr' ) # os.system(s) s = '%s -f GeoJSON -s_srs "%s" -t_srs %s %s %s' % ( exepath , src_srs , dst_srs , jsonfile , src_file ) UtilClass . run_command ( s ) | convert shapefile to geojson file | 176 | 9 |
5,938 | def consensus ( aln , weights = None , gap_threshold = 0.5 , simple = False , trim_ends = True ) : # Choose your algorithms! if simple : # Use the simple, unweighted algorithm col_consensus = make_simple_col_consensus ( alnutils . aa_frequencies ( aln ) ) def is_majority_gap ( col ) : return ( float ( col . count ( '-' ) ) / len ( col ) >= gap_threshold ) # ENH (alternatively/additionally): does any aa occur more than once? # ENH: choose gap-decisionmaking separately from col_consensus else : # Use the entropy-based, weighted algorithm if weights is None : seq_weights = alnutils . sequence_weights ( aln , 'avg1' ) else : seq_weights = weights aa_frequencies = alnutils . aa_frequencies ( aln , weights = seq_weights ) col_consensus = make_entropy_col_consensus ( aa_frequencies ) def is_majority_gap ( col ) : gap_count = 0.0 for wt , char in zip ( seq_weights , col ) : if char == '-' : gap_count += wt return ( gap_count / sum ( seq_weights ) >= gap_threshold ) # Traverse the alignment, handling gaps etc. def col_wise_consensus ( columns ) : """Calculate the consensus chars for an iterable of columns.""" if not trim_ends : # Track if we're in the N-term or C-term end of the sequence in_left_end = True maybe_right_tail = [ ] # prev_col = None # prev_char = None for col in columns : # Lowercase cols mean explicitly, "don't include in consensus" if all ( c . islower ( ) for c in col if c not in '.-' ) : yield '-' continue if any ( c . islower ( ) for c in col ) : logging . warn ( 'Mixed lowercase and uppercase letters in a ' 'column: ' + '' . join ( col ) ) col = map ( str . upper , col ) # Gap chars is_gap = is_majority_gap ( col ) if not trim_ends : # Avoid N-terminal gaps in the consensus sequence if in_left_end : if not is_gap : # Match -- we're no longer in the left end in_left_end = False is_gap = False # When to yield a gap here: # ----------- --------- ------ ---------- # in_left_end trim_ends is_gap yield gap? # ----------- --------- ------ ---------- # True True (True) yes # True False (False) (no -- def. char) # False True T/F yes, if is_gap # False False (T/F) NO! use maybe_right_tail # ----------- --------- ------ ---------- if is_gap and trim_ends : yield '-' continue # Get the consensus character, using the chosen algorithm cons_char = col_consensus ( col ) if trim_ends : yield cons_char else : # Avoid C-terminal gaps in the consensus sequence if is_gap : maybe_right_tail . append ( cons_char ) else : # Match -> gaps weren't the right tail; emit all gaps for char in maybe_right_tail : yield '-' maybe_right_tail = [ ] yield cons_char # prev_col = col # prev_char = cons_char # Finally, if we were keeping a right (C-term) tail, emit it if not trim_ends : for char in maybe_right_tail : yield char return '' . join ( col_wise_consensus ( zip ( * aln ) ) ) | Get the consensus of an alignment as a string . | 827 | 10 |
5,939 | def make_simple_col_consensus ( bg_freqs ) : # Hack: use default kwargs to persist across iterations def col_consensus ( col , prev_col = [ ] , prev_char = [ ] ) : # Count the amino acid types in this column aa_counts = sequtils . aa_frequencies ( col ) assert aa_counts , "Column is all gaps! That's not allowed." # Take the most common residue(s) best_char , best_score = max ( aa_counts . iteritems ( ) , key = lambda kv : kv [ 1 ] ) # Resolve ties ties = [ aa for aa in aa_counts if aa_counts [ aa ] == best_score ] if len ( ties ) > 1 : # Breaker #1: most common after the prev. consensus char # Resolve a tied col by restricting to rows where the preceding # char is the consensus type for that (preceding) col if prev_char and prev_col : mc_next = Counter ( [ b for a , b in zip ( prev_col , col ) if a == prev_char [ 0 ] and b in ties ] ) . most_common ( ) ties_next = [ x [ 0 ] for x in mc_next if x [ 1 ] == mc_next [ 0 ] [ 1 ] ] if ties_next : ties = ties_next if len ( ties ) > 1 : # Breaker #2: lowest overall residue frequency ties . sort ( key = lambda aa : bg_freqs [ aa ] ) best_char = ties [ 0 ] else : assert best_char == ties [ 0 ] , 'WTF %s != %s[0]' % ( best_char , ties ) # Save values for tie-breaker #1 prev_col [ : ] = col prev_char [ : ] = best_char return best_char return col_consensus | Consensus by simple plurality unweighted . | 424 | 9 |
5,940 | def supported ( aln ) : def col_consensus ( columns ) : """Calculate the consensus chars for an iterable of columns.""" for col in columns : if ( # Majority gap chars ( col . count ( '-' ) >= len ( col ) / 2 ) or # Lowercase cols mean "don't include in consensus" all ( c . islower ( ) for c in col if c not in '.-' ) ) : yield '-' continue # Validation - copied from consensus() above if any ( c . islower ( ) for c in col ) : logging . warn ( 'Mixed lowercase and uppercase letters in a ' 'column: ' + '' . join ( col ) ) col = map ( str . upper , col ) # Calculate the consensus character most_common = Counter ( [ c for c in col if c not in '-' ] ) . most_common ( ) if not most_common : # XXX ever reached? logging . warn ( "Column is all gaps! How did that happen?" ) if most_common [ 0 ] [ 1 ] == 1 : # No char has frequency > 1; no consensus char yield '-' elif ( len ( most_common ) > 1 and most_common [ 0 ] [ 1 ] == most_common [ 1 ] [ 1 ] ) : # Tie for most-common residue type ties = [ x [ 0 ] for x in most_common if x [ 1 ] == most_common [ 0 ] [ 1 ] ] yield '' . join ( ties ) else : yield most_common [ 0 ] [ 0 ] return list ( col_consensus ( zip ( * aln ) ) ) | Get only the supported consensus residues in each column . | 352 | 10 |
5,941 | def detect_clause ( parser , clause_name , tokens , as_filter_expr = True ) : if clause_name in tokens : t_index = tokens . index ( clause_name ) clause_value = tokens [ t_index + 1 ] if as_filter_expr : clause_value = parser . compile_filter ( clause_value ) del tokens [ t_index : t_index + 2 ] else : clause_value = None return clause_value | Helper function detects a certain clause in tag tokens list . Returns its value . | 99 | 15 |
5,942 | def install_kernel_spec ( self , app , dir_name , display_name , settings_module , ipython_arguments ) : ksm = app . kernel_spec_manager try_spec_names = [ 'python3' if six . PY3 else 'python2' , 'python' ] if isinstance ( try_spec_names , six . string_types ) : try_spec_names = [ try_spec_names ] ks = None for spec_name in try_spec_names : try : ks = ksm . get_kernel_spec ( spec_name ) break except Exception : continue if not ks : self . parser . error ( "No notebook (Python) kernel specs found" ) ks . display_name = display_name ks . env [ "CORRAL_SETTINGS_MODULE" ] = settings_module ks . argv . extend ( ipython_arguments ) in_corral_dir , in_corral = os . path . split ( os . path . realpath ( sys . argv [ 0 ] ) ) pythonpath = ks . env . get ( 'PYTHONPATH' , os . environ . get ( 'PYTHONPATH' , '' ) ) pythonpath = pythonpath . split ( ':' ) if in_corral_dir not in pythonpath : pythonpath . append ( in_corral_dir ) ks . env [ 'PYTHONPATH' ] = ':' . join ( filter ( None , pythonpath ) ) kernel_dir = os . path . join ( ksm . user_kernel_dir , conf . PACKAGE ) if not os . path . exists ( kernel_dir ) : os . makedirs ( kernel_dir ) shutil . copy ( res . fullpath ( "logo-64x64.png" ) , kernel_dir ) with open ( os . path . join ( kernel_dir , 'kernel.json' ) , 'w' ) as f : f . write ( ks . to_json ( ) ) | install an IPython > = 3 . 0 kernelspec that loads corral env | 447 | 16 |
5,943 | def _cache_init ( self ) : cache_ = cache . get ( self . CACHE_ENTRY_NAME ) if cache_ is None : categories = get_category_model ( ) . objects . order_by ( 'sort_order' ) ids = { category . id : category for category in categories } aliases = { category . alias : category for category in categories if category . alias } parent_to_children = OrderedDict ( ) # Preserve aliases order. for category in categories : parent_category = ids . get ( category . parent_id , False ) parent_alias = None if parent_category : parent_alias = parent_category . alias if parent_alias not in parent_to_children : parent_to_children [ parent_alias ] = [ ] parent_to_children [ parent_alias ] . append ( category . id ) cache_ = { self . CACHE_NAME_IDS : ids , self . CACHE_NAME_PARENTS : parent_to_children , self . CACHE_NAME_ALIASES : aliases } cache . set ( self . CACHE_ENTRY_NAME , cache_ , self . CACHE_TIMEOUT ) self . _cache = cache_ | Initializes local cache from Django cache if required . | 269 | 10 |
5,944 | def _cache_get_entry ( self , entry_name , key = ENTIRE_ENTRY_KEY , default = False ) : if key is self . ENTIRE_ENTRY_KEY : return self . _cache [ entry_name ] return self . _cache [ entry_name ] . get ( key , default ) | Returns cache entry parameter value by its name . | 69 | 9 |
5,945 | def sort_aliases ( self , aliases ) : self . _cache_init ( ) if not aliases : return aliases parent_aliases = self . _cache_get_entry ( self . CACHE_NAME_PARENTS ) . keys ( ) return [ parent_alias for parent_alias in parent_aliases if parent_alias in aliases ] | Sorts the given aliases list returns a sorted list . | 75 | 11 |
5,946 | def get_parents_for ( self , child_ids ) : self . _cache_init ( ) parent_candidates = [ ] for parent , children in self . _cache_get_entry ( self . CACHE_NAME_PARENTS ) . items ( ) : if set ( children ) . intersection ( child_ids ) : parent_candidates . append ( parent ) return set ( parent_candidates ) | Returns parent aliases for a list of child IDs . | 89 | 10 |
5,947 | def get_children_for ( self , parent_alias = None , only_with_aliases = False ) : self . _cache_init ( ) child_ids = self . get_child_ids ( parent_alias ) if only_with_aliases : children = [ ] for cid in child_ids : category = self . get_category_by_id ( cid ) if category . alias : children . append ( category ) return children return [ self . get_category_by_id ( cid ) for cid in child_ids ] | Returns a list with with categories under the given parent . | 120 | 11 |
5,948 | def get_child_ids ( self , parent_alias ) : self . _cache_init ( ) return self . _cache_get_entry ( self . CACHE_NAME_PARENTS , parent_alias , [ ] ) | Returns child IDs of the given parent category | 50 | 8 |
5,949 | def get_category_by_alias ( self , alias ) : self . _cache_init ( ) return self . _cache_get_entry ( self . CACHE_NAME_ALIASES , alias , None ) | Returns Category object by its alias . | 48 | 7 |
5,950 | def get_category_by_id ( self , cid ) : self . _cache_init ( ) return self . _cache_get_entry ( self . CACHE_NAME_IDS , cid ) | Returns Category object by its id . | 46 | 7 |
5,951 | def get_ties_stats ( self , categories , target_model = None ) : filter_kwargs = { 'category_id__in' : categories } if target_model is not None : is_cls = hasattr ( target_model , '__name__' ) if is_cls : concrete = False else : concrete = True filter_kwargs [ 'object_id' ] = target_model . id filter_kwargs [ 'content_type' ] = ContentType . objects . get_for_model ( target_model , for_concrete_model = concrete ) return { item [ 'category_id' ] : item [ 'ties_num' ] for item in get_tie_model ( ) . objects . filter ( * * filter_kwargs ) . values ( 'category_id' ) . annotate ( ties_num = Count ( 'category' ) ) } | Returns a dict with categories popularity stats . | 193 | 8 |
5,952 | def load_p2th_privkey_into_local_node ( provider : RpcNode , prod : bool = True ) -> None : assert isinstance ( provider , RpcNode ) , { "error" : "Import only works with local node." } error = { "error" : "Loading P2TH privkey failed." } pa_params = param_query ( provider . network ) if prod : provider . importprivkey ( pa_params . P2TH_wif , "PAPROD" ) # now verify if ismine == True if not provider . validateaddress ( pa_params . P2TH_addr ) [ 'ismine' ] : raise P2THImportFailed ( error ) else : provider . importprivkey ( pa_params . test_P2TH_wif , "PATEST" ) if not provider . validateaddress ( pa_params . test_P2TH_addr ) [ 'ismine' ] : raise P2THImportFailed ( error ) | Load PeerAssets P2TH privkey into the local node . | 217 | 14 |
5,953 | def find_deck_spawns ( provider : Provider , prod : bool = True ) -> Iterable [ str ] : pa_params = param_query ( provider . network ) if isinstance ( provider , RpcNode ) : if prod : decks = ( i [ "txid" ] for i in provider . listtransactions ( "PAPROD" ) ) else : decks = ( i [ "txid" ] for i in provider . listtransactions ( "PATEST" ) ) if isinstance ( provider , Cryptoid ) or isinstance ( provider , Explorer ) : if prod : decks = ( i for i in provider . listtransactions ( pa_params . P2TH_addr ) ) else : decks = ( i for i in provider . listtransactions ( pa_params . test_P2TH_addr ) ) return decks | find deck spawn transactions via Provider it requires that Deck spawn P2TH were imported in local node or that remote API knows about P2TH address . | 181 | 30 |
5,954 | def deck_parser ( args : Tuple [ Provider , dict , int , str ] , prod : bool = True ) -> Optional [ Deck ] : provider = args [ 0 ] raw_tx = args [ 1 ] deck_version = args [ 2 ] p2th = args [ 3 ] try : validate_deckspawn_p2th ( provider , raw_tx , p2th ) d = parse_deckspawn_metainfo ( read_tx_opreturn ( raw_tx [ 'vout' ] [ 1 ] ) , deck_version ) if d : d [ "id" ] = raw_tx [ "txid" ] try : d [ "issue_time" ] = raw_tx [ "blocktime" ] except KeyError : d [ "time" ] = 0 d [ "issuer" ] = find_tx_sender ( provider , raw_tx ) d [ "network" ] = provider . network d [ "production" ] = prod d [ "tx_confirmations" ] = raw_tx [ "confirmations" ] return Deck ( * * d ) except ( InvalidDeckSpawn , InvalidDeckMetainfo , InvalidDeckVersion , InvalidNulldataOutput ) as err : pass return None | deck parser function | 270 | 3 |
5,955 | def tx_serialization_order ( provider : Provider , blockhash : str , txid : str ) -> int : return provider . getblock ( blockhash ) [ "tx" ] . index ( txid ) | find index of this tx in the blockid | 45 | 9 |
5,956 | def deck_issue_mode ( proto : DeckSpawnProto ) -> Iterable [ str ] : if proto . issue_mode == 0 : yield "NONE" return for mode , value in proto . MODE . items ( ) : if value > proto . issue_mode : continue if value & proto . issue_mode : yield mode | interpret issue mode bitfeg | 71 | 6 |
5,957 | def parse_deckspawn_metainfo ( protobuf : bytes , version : int ) -> dict : deck = DeckSpawnProto ( ) deck . ParseFromString ( protobuf ) error = { "error" : "Deck ({deck}) metainfo incomplete, deck must have a name." . format ( deck = deck . name ) } if deck . name == "" : raise InvalidDeckMetainfo ( error ) if deck . version != version : raise InvalidDeckVersion ( { "error" , "Deck version mismatch." } ) return { "version" : deck . version , "name" : deck . name , "issue_mode" : deck . issue_mode , "number_of_decimals" : deck . number_of_decimals , "asset_specific_data" : deck . asset_specific_data } | Decode deck_spawn tx op_return protobuf message and validate it Raise error if deck_spawn metainfo incomplete or version mistmatch . | 188 | 31 |
5,958 | def load_deck_p2th_into_local_node ( provider : RpcNode , deck : Deck ) -> None : assert isinstance ( provider , RpcNode ) , { "error" : "You can load privkeys only into local node." } error = { "error" : "Deck P2TH import went wrong." } provider . importprivkey ( deck . p2th_wif , deck . id ) check_addr = provider . validateaddress ( deck . p2th_address ) if not check_addr [ "isvalid" ] and not check_addr [ "ismine" ] : raise DeckP2THImportError ( error ) | load deck p2th into local node via importprivke this allows building of proof - of - timeline for this deck | 143 | 24 |
5,959 | def card_bundle_parser ( bundle : CardBundle , debug = False ) -> Iterator : try : # first vout of the bundle must pay to deck.p2th validate_card_transfer_p2th ( bundle . deck , bundle . vouts [ 0 ] ) # second vout must be OP_RETURN with card_metainfo card_metainfo = parse_card_transfer_metainfo ( read_tx_opreturn ( bundle . vouts [ 1 ] ) , bundle . deck . version ) # if any of this exceptions is raised, return None except ( InvalidCardTransferP2TH , CardVersionMismatch , CardNumberOfDecimalsMismatch , RecieverAmountMismatch , DecodeError , TypeError , InvalidNulldataOutput ) as e : if debug : print ( e ) # re-do as logging later on return yield # check for decimals if not card_metainfo [ "number_of_decimals" ] == bundle . deck . number_of_decimals : raise CardNumberOfDecimalsMismatch ( { "error" : "Number of decimals does not match." } ) # deduce the individual cards in the bundle cards = card_postprocess ( card_metainfo , bundle . vouts ) # drop the vouts property del bundle . __dict__ [ 'vouts' ] for c in cards : d = { * * c , * * bundle . __dict__ } try : yield CardTransfer ( * * d ) # issuing cards to issuing address is forbidden, # this will except the error except InvalidCardIssue as e : if debug : print ( e ) | this function wraps all the card transfer parsing | 359 | 8 |
5,960 | def param_query ( name : str ) -> PAParams : for pa_params in params : if name in ( pa_params . network_name , pa_params . network_shortname , ) : return pa_params raise UnsupportedNetwork | Find the PAParams for a network by its long or short name . Raises UnsupportedNetwork if no PAParams is found . | 53 | 30 |
5,961 | def load_scripts ( self ) : # update scripts so that current settings do not get lost for index in range ( self . tree_scripts . topLevelItemCount ( ) ) : script_item = self . tree_scripts . topLevelItem ( index ) self . update_script_from_item ( script_item ) dialog = LoadDialog ( elements_type = "scripts" , elements_old = self . scripts , filename = self . gui_settings [ 'scripts_folder' ] ) if dialog . exec_ ( ) : self . gui_settings [ 'scripts_folder' ] = str ( dialog . txt_probe_log_path . text ( ) ) scripts = dialog . get_values ( ) added_scripts = set ( scripts . keys ( ) ) - set ( self . scripts . keys ( ) ) removed_scripts = set ( self . scripts . keys ( ) ) - set ( scripts . keys ( ) ) if 'data_folder' in list ( self . gui_settings . keys ( ) ) and os . path . exists ( self . gui_settings [ 'data_folder' ] ) : data_folder_name = self . gui_settings [ 'data_folder' ] else : data_folder_name = None # create instances of new instruments/scripts self . scripts , loaded_failed , self . instruments = Script . load_and_append ( script_dict = { name : scripts [ name ] for name in added_scripts } , scripts = self . scripts , instruments = self . instruments , log_function = self . log , data_path = data_folder_name ) # delete instances of new instruments/scripts that have been deselected for name in removed_scripts : del self . scripts [ name ] | opens file dialog to load scripts into gui | 369 | 8 |
5,962 | def getblockhash ( self , index : int ) -> str : return cast ( str , self . api_fetch ( 'getblockhash?index=' + str ( index ) ) ) | Returns the hash of the block at ; index 0 is the genesis block . | 40 | 15 |
5,963 | def getblock ( self , hash : str ) -> dict : return cast ( dict , self . api_fetch ( 'getblock?hash=' + hash ) ) | Returns information about the block with the given hash . | 35 | 10 |
5,964 | def getaddress ( self , address : str ) -> dict : return cast ( dict , self . ext_fetch ( 'getaddress/' + address ) ) | Returns information for given address . | 34 | 6 |
5,965 | def listunspent ( self , address : str ) -> list : try : return cast ( dict , self . ext_fetch ( 'listunspent/' + address ) ) [ 'unspent_outputs' ] except KeyError : raise InsufficientFunds ( 'Insufficient funds.' ) | Returns unspent transactions for given address . | 66 | 9 |
5,966 | def txinfo ( self , txid : str ) -> dict : return cast ( dict , self . ext_fetch ( 'txinfo/' + txid ) ) | Returns information about given transaction . | 36 | 6 |
5,967 | def getbalance ( self , address : str ) -> Decimal : try : return Decimal ( cast ( float , self . ext_fetch ( 'getbalance/' + address ) ) ) except TypeError : return Decimal ( 0 ) | Returns current balance of given address . | 51 | 7 |
5,968 | def extract ( self , obj , bypass_ref = False ) : return self . pointer . extract ( obj , bypass_ref ) | Extract subelement from obj according to pointer . It assums that document is the object . | 27 | 19 |
5,969 | def parse ( self , pointer ) : if isinstance ( pointer , Pointer ) : return pointer . tokens [ : ] elif pointer == '' : return [ ] tokens = [ ] staged , _ , children = pointer . partition ( '/' ) if staged : try : token = StagesToken ( staged ) token . last = False tokens . append ( token ) except ValueError : raise ParseError ( 'pointer must start with / or int' , pointer ) if _ : for part in children . split ( '/' ) : part = part . replace ( '~1' , '/' ) part = part . replace ( '~0' , '~' ) token = ChildToken ( part ) token . last = False tokens . append ( token ) return tokens | parse pointer into tokens | 159 | 4 |
5,970 | def extract ( self , obj , bypass_ref = False ) : for token in self . tokens : obj = token . extract ( obj , bypass_ref ) return obj | Extract subelement from obj according to tokens . | 35 | 10 |
5,971 | def extract ( self , obj , bypass_ref = False ) : for i in range ( 0 , self . stages ) : try : obj = obj . parent_obj except AttributeError : raise UnstagedError ( obj , '{!r} must be staged before ' 'exploring its parents' . format ( obj ) ) if self . member : return obj . parent_member return obj | Extract parent of obj according to current token . | 83 | 10 |
5,972 | def extract ( self , obj , bypass_ref = False ) : try : if isinstance ( obj , Mapping ) : if not bypass_ref and '$ref' in obj : raise RefError ( obj , 'presence of a $ref member' ) obj = self . extract_mapping ( obj ) elif isinstance ( obj , Sequence ) and not isinstance ( obj , string_types ) : obj = self . extract_sequence ( obj ) else : raise WrongType ( obj , '{!r} does not apply ' 'for {!r}' . format ( str ( self ) , obj ) ) if isinstance ( obj , Mapping ) : if not bypass_ref and '$ref' in obj : raise RefError ( obj , 'presence of a $ref member' ) return obj except ExtractError as error : logger . exception ( error ) raise except Exception as error : logger . exception ( error ) args = [ arg for arg in error . args if arg not in ( self , obj ) ] raise ExtractError ( obj , * args ) | Extract subelement from obj according to current token . | 226 | 11 |
5,973 | def digester ( data ) : if not isinstance ( data , six . binary_type ) : data = data . encode ( 'utf_8' ) hashof = hashlib . sha1 ( data ) . digest ( ) encoded_hash = base64 . b64encode ( hashof ) if not isinstance ( encoded_hash , six . string_types ) : encoded_hash = encoded_hash . decode ( 'utf_8' ) chunked = splitter ( encoded_hash , chunksize = 60 ) lines = '\n' . join ( chunked ) return lines | Create SHA - 1 hash get digest b64 encode split every 60 char . | 125 | 15 |
5,974 | def splitter ( iterable , chunksize = 60 ) : return ( iterable [ 0 + i : chunksize + i ] for i in range ( 0 , len ( iterable ) , chunksize ) ) | Split an iterable that supports indexing into chunks of chunksize . | 44 | 14 |
5,975 | def canonical_request ( self , method , path , content , timestamp ) : request = collections . OrderedDict ( [ ( 'Method' , method . upper ( ) ) , ( 'Hashed Path' , path ) , ( 'X-Ops-Content-Hash' , content ) , ( 'X-Ops-Timestamp' , timestamp ) , ( 'X-Ops-UserId' , self . user_id ) , ] ) return '\n' . join ( [ '%s:%s' % ( key , value ) for key , value in request . items ( ) ] ) | Return the canonical request string . | 128 | 6 |
5,976 | def load_pem ( cls , private_key , password = None ) : # TODO(sam): try to break this in tests maybe_path = normpath ( private_key ) if os . path . isfile ( maybe_path ) : with open ( maybe_path , 'rb' ) as pkf : private_key = pkf . read ( ) if not isinstance ( private_key , six . binary_type ) : private_key = private_key . encode ( 'utf-8' ) pkey = serialization . load_pem_private_key ( private_key , password = password , backend = crypto_backends . default_backend ( ) ) return cls ( pkey ) | Return a PrivateKey instance . | 157 | 6 |
5,977 | def sign ( self , data , b64 = True ) : padder = padding . PKCS1v15 ( ) signer = self . private_key . signer ( padder , None ) if not isinstance ( data , six . binary_type ) : data = data . encode ( 'utf_8' ) signer . update ( data ) signed = signer . finalize ( ) if b64 : signed = base64 . b64encode ( signed ) return signed | Sign data with the private key and return the signed data . | 102 | 12 |
5,978 | def dump ( obj , fp , * * kw ) : xml = dumps ( obj , * * kw ) if isinstance ( fp , basestring ) : with open ( fp , 'w' ) as fobj : fobj . write ( xml ) else : fp . write ( xml ) | r Dump python object to file . | 67 | 8 |
5,979 | def value ( self ) : value = getattr ( self . instrument , self . probe_name ) self . buffer . append ( value ) return value | reads the value from the instrument | 31 | 6 |
5,980 | def load_and_append ( probe_dict , probes , instruments = { } ) : loaded_failed = { } updated_probes = { } updated_probes . update ( probes ) updated_instruments = { } updated_instruments . update ( instruments ) # ===== load new instruments ======= new_instruments = list ( set ( probe_dict . keys ( ) ) - set ( probes . keys ( ) ) ) if new_instruments != [ ] : updated_instruments , failed = Instrument . load_and_append ( { instrument_name : instrument_name for instrument_name in new_instruments } , instruments ) if failed != [ ] : # if loading an instrument fails all the probes that depend on that instrument also fail # ignore the failed instrument that did exist already because they failed because they did exist for failed_instrument in set ( failed ) - set ( instruments . keys ( ) ) : for probe_name in probe_dict [ failed_instrument ] : loaded_failed [ probe_name ] = ValueError ( 'failed to load instrument {:s} already exists. Did not load!' . format ( failed_instrument ) ) del probe_dict [ failed_instrument ] # ===== now we are sure that all the instruments that we need for the probes already exist for instrument_name , probe_names in probe_dict . items ( ) : if not instrument_name in updated_probes : updated_probes . update ( { instrument_name : { } } ) for probe_name in probe_names . split ( ',' ) : if probe_name in updated_probes [ instrument_name ] : loaded_failed [ probe_name ] = ValueError ( 'failed to load probe {:s} already exists. Did not load!' . format ( probe_name ) ) else : probe_instance = Probe ( updated_instruments [ instrument_name ] , probe_name ) updated_probes [ instrument_name ] . update ( { probe_name : probe_instance } ) return updated_probes , loaded_failed , updated_instruments | load probes from probe_dict and append to probes if additional instruments are required create them and add them to instruments | 448 | 22 |
5,981 | def get ( self , key ) : try : return self [ self . id_lookup . get ( key ) ] except TypeError : raise KeyError | Returns an address by user controlled input ID | 32 | 8 |
5,982 | def get_index ( self , key ) : try : return self [ self . index_lookup . get ( key ) ] except TypeError : raise KeyError | Returns an address by input index a value that matches the list index of the provided lookup value not necessarily the result . | 34 | 23 |
5,983 | def _igamc ( a , x ) : # Compute x**a * exp(-x) / Gamma(a) ax = math . exp ( a * math . log ( x ) - x - math . lgamma ( a ) ) # Continued fraction y = 1.0 - a z = x + y + 1.0 c = 0.0 pkm2 = 1.0 qkm2 = x pkm1 = x + 1.0 qkm1 = z * x ans = pkm1 / qkm1 while True : c += 1.0 y += 1.0 z += 2.0 yc = y * c pk = pkm1 * z - pkm2 * yc qk = qkm1 * z - qkm2 * yc if qk != 0 : r = pk / qk t = abs ( ( ans - r ) / r ) ans = r else : t = 1.0 pkm2 = pkm1 pkm1 = pk qkm2 = qkm1 qkm1 = qk if abs ( pk ) > BIG : pkm2 *= BIGINV pkm1 *= BIGINV qkm2 *= BIGINV qkm1 *= BIGINV if t <= MACHEP : return ans * ax | Complemented incomplete Gamma integral . | 281 | 7 |
5,984 | def main ( ) : dem = '../tests/data/Jamaica_dem.tif' num_proc = 2 wp = '../tests/data/tmp_results/wtsd_delineation' TauDEMWorkflow . watershed_delineation ( num_proc , dem , workingdir = wp ) | The simplest usage of watershed delineation based on TauDEM . | 70 | 12 |
5,985 | def _get_line ( self , search_string , search_file , return_string = True , case_sens = True ) : if os . path . isfile ( search_file ) : # if single search string if type ( search_string ) == type ( '' ) : search_string = [ search_string ] # if case insensitive, convert everything to lowercase if not case_sens : search_string = [ i . lower ( ) for i in search_string ] with open ( search_file ) as fp : # search for the strings line by line for line in fp : query_line = line if case_sens else line . lower ( ) if all ( [ i in query_line for i in search_string ] ) : return line if return_string else True if return_string : raise Exception ( '%s not found in %s' % ( ' & ' . join ( search_string ) , search_file ) ) else : return False else : raise Exception ( '%s file does not exist' % search_file ) | Return the first line containing a set of strings in a file . | 228 | 13 |
5,986 | def get_cutoff_energy ( self ) : return Value ( scalars = [ Scalar ( value = self . settings [ "kinetic-energy cutoff" ] ) ] , units = self . settings [ 'kinetic-energy cutoff units' ] ) | Determine the cutoff energy from the output | 54 | 9 |
5,987 | def get_pp_name ( self ) : ppnames = [ ] # Find the number of atom types natomtypes = int ( self . _get_line ( 'number of atomic types' , self . outputf ) . split ( ) [ 5 ] ) # Find the pseudopotential names with open ( self . outputf ) as fp : for line in fp : if "PseudoPot. #" in line : ppnames . append ( Scalar ( value = next ( fp ) . split ( '/' ) [ - 1 ] . rstrip ( ) ) ) if len ( ppnames ) == natomtypes : return Value ( scalars = ppnames ) raise Exception ( 'Could not find %i pseudopotential names' % natomtypes ) | Determine the pseudopotential names from the output | 163 | 11 |
5,988 | def get_U_settings ( self ) : with open ( self . outputf ) as fp : for line in fp : if "LDA+U calculation" in line : U_param = { } U_param [ 'Type' ] = line . split ( ) [ 0 ] U_param [ 'Values' ] = { } # look through next several lines for nl in range ( 15 ) : line2 = next ( fp ) . split ( ) if len ( line2 ) > 1 and line2 [ 0 ] == "atomic" : pass # column titles elif len ( line2 ) == 6 : U_param [ 'Values' ] [ line2 [ 0 ] ] = { } U_param [ 'Values' ] [ line2 [ 0 ] ] [ 'L' ] = float ( line2 [ 1 ] ) U_param [ 'Values' ] [ line2 [ 0 ] ] [ 'U' ] = float ( line2 [ 2 ] ) U_param [ 'Values' ] [ line2 [ 0 ] ] [ 'J' ] = float ( line2 [ 4 ] ) else : break # end of data block return Value ( * * U_param ) return None | Determine the DFT + U type and parameters from the output | 257 | 14 |
5,989 | def get_vdW_settings ( self ) : xc = self . get_xc_functional ( ) . scalars [ 0 ] . value if 'vdw' in xc . lower ( ) : # vdW xc functional return Value ( scalars = [ Scalar ( value = xc ) ] ) else : # look for vdw_corr in input vdW_dict = { 'xdm' : 'Becke-Johnson XDM' , 'ts' : 'Tkatchenko-Scheffler' , 'ts-vdw' : 'Tkatchenko-Scheffler' , 'tkatchenko-scheffler' : 'Tkatchenko-Scheffler' , 'grimme-d2' : 'Grimme D2' , 'dft-d' : 'Grimme D2' } if self . _get_line ( 'vdw_corr' , self . inputf , return_string = False , case_sens = False ) : line = self . _get_line ( 'vdw_corr' , self . inputf , return_string = True , case_sens = False ) vdwkey = str ( line . split ( '=' ) [ - 1 ] . replace ( "'" , "" ) . replace ( ',' , '' ) . lower ( ) . rstrip ( ) ) return Value ( scalars = [ Scalar ( value = vdW_dict [ vdwkey ] ) ] ) return None | Determine the vdW type if using vdW xc functional or correction scheme from the input otherwise | 326 | 23 |
5,990 | def get_stresses ( self ) : if "stress" not in self . settings : return None wrapped = [ [ Scalar ( value = x ) for x in y ] for y in self . settings [ "stress" ] ] return Property ( matrices = [ wrapped ] , units = self . settings [ "stress units" ] ) | Determine the stress tensor from the output | 71 | 10 |
5,991 | def get_dos ( self ) : # find the dos file fildos = '' for f in self . _files : with open ( f , 'r' ) as fp : first_line = next ( fp ) if "E (eV)" in first_line and "Int dos(E)" in first_line : fildos = f ndoscol = len ( next ( fp ) . split ( ) ) - 2 # number of spin channels fp . close ( ) break fp . close ( ) if not fildos : return None # cannot find DOS # get the Fermi energy line = self . _get_line ( 'the Fermi energy is' , self . outputf ) efermi = float ( line . split ( 'is' ) [ - 1 ] . split ( ) [ 0 ] ) # grab the DOS energy = [ ] dos = [ ] fp = open ( fildos , 'r' ) next ( fp ) # comment line for line in fp : ls = line . split ( ) energy . append ( Scalar ( value = float ( ls [ 0 ] ) - efermi ) ) dos . append ( Scalar ( value = sum ( [ float ( i ) for i in ls [ 1 : 1 + ndoscol ] ] ) ) ) return Property ( scalars = dos , units = 'number of states per unit cell' , conditions = Value ( name = 'energy' , scalars = energy , units = 'eV' ) ) | Find the total DOS shifted by the Fermi energy | 323 | 11 |
5,992 | def get_band_gap ( self ) : dosdata = self . get_dos ( ) if type ( dosdata ) == type ( None ) : return None # cannot find DOS else : energy = dosdata . conditions . scalars dos = dosdata . scalars step_size = energy [ 1 ] . value - energy [ 0 ] . value not_found = True l = 0 bot = 10 ** 3 top = - 10 ** 3 while not_found and l < len ( dos ) : # iterate through the data e = float ( energy [ l ] . value ) dens = float ( dos [ l ] . value ) # note: dos already shifted by efermi if e < 0 and dens > 1e-3 : bot = e elif e > 0 and dens > 1e-3 : top = e not_found = False l += 1 if top < bot : raise Exception ( 'Algorithm failed to find the band gap' ) elif top - bot < step_size * 2 : return Property ( scalars = [ Scalar ( value = 0 ) ] , units = 'eV' ) else : bandgap = float ( top - bot ) return Property ( scalars = [ Scalar ( value = round ( bandgap , 3 ) ) ] , units = 'eV' ) | Compute the band gap from the DOS | 275 | 8 |
5,993 | def get_category_aliases_under ( parent_alias = None ) : return [ ch . alias for ch in get_cache ( ) . get_children_for ( parent_alias , only_with_aliases = True ) ] | Returns a list of category aliases under the given parent . | 51 | 11 |
5,994 | def get_category_lists ( init_kwargs = None , additional_parents_aliases = None , obj = None ) : init_kwargs = init_kwargs or { } additional_parents_aliases = additional_parents_aliases or [ ] parent_aliases = additional_parents_aliases if obj is not None : ctype = ContentType . objects . get_for_model ( obj ) cat_ids = [ item [ 0 ] for item in get_tie_model ( ) . objects . filter ( content_type = ctype , object_id = obj . id ) . values_list ( 'category_id' ) . all ( ) ] parent_aliases = list ( get_cache ( ) . get_parents_for ( cat_ids ) . union ( additional_parents_aliases ) ) lists = [ ] aliases = get_cache ( ) . sort_aliases ( parent_aliases ) categories_cache = get_cache ( ) . get_categories ( aliases , obj ) for parent_alias in aliases : catlist = CategoryList ( parent_alias , * * init_kwargs ) # TODO Burned in class name. Make more customizable. if obj is not None : catlist . set_obj ( obj ) # Optimization. To get DB hits down. cache = [ ] try : cache = categories_cache [ parent_alias ] except KeyError : pass catlist . set_get_categories_cache ( cache ) lists . append ( catlist ) return lists | Returns a list of CategoryList objects optionally associated with a given model instance . | 325 | 15 |
5,995 | def register_lists ( self , category_lists , lists_init_kwargs = None , editor_init_kwargs = None ) : lists_init_kwargs = lists_init_kwargs or { } editor_init_kwargs = editor_init_kwargs or { } for lst in category_lists : if isinstance ( lst , string_types ) : # Spawn CategoryList object from base category alias. lst = self . list_cls ( lst , * * lists_init_kwargs ) elif not isinstance ( lst , CategoryList ) : raise SitecatsConfigurationError ( '`CategoryRequestHandler.register_lists()` accepts only ' '`CategoryList` objects or category aliases.' ) if self . _obj : lst . set_obj ( self . _obj ) for name , val in lists_init_kwargs . items ( ) : # Setting CategoryList attributes from kwargs. setattr ( lst , name , val ) lst . enable_editor ( * * editor_init_kwargs ) self . _lists [ lst . get_id ( ) ] = lst | Registers CategoryList objects to handle their requests . | 245 | 10 |
5,996 | def action_remove ( cls , request , category_list ) : if not category_list . editor . allow_remove : raise SitecatsSecurityException ( '`action_remove()` is not supported by parent `%s`category.' % category_list . alias ) category_id = int ( request . POST . get ( 'category_id' , 0 ) ) if not category_id : raise SitecatsSecurityException ( 'Unsupported `category_id` value - `%s` - is passed to `action_remove()`.' % category_id ) category = get_cache ( ) . get_category_by_id ( category_id ) if not category : raise SitecatsSecurityException ( 'Unable to get `%s` category in `action_remove()`.' % category_id ) cat_ident = category . alias or category . id if category . is_locked : raise SitecatsSecurityException ( '`action_remove()` is not supported by `%s` category.' % cat_ident ) if category . parent_id != category_list . get_id ( ) : raise SitecatsSecurityException ( '`action_remove()` is unable to remove `%s`: ' 'not a child of parent `%s` category.' % ( cat_ident , category_list . alias ) ) min_num = category_list . editor . min_num def check_min_num ( num ) : if min_num is not None and num - 1 < min_num : subcats_str = ungettext_lazy ( 'subcategory' , 'subcategories' , min_num ) error_msg = _ ( 'Unable to remove "%(target_category)s" category from "%(parent_category)s": ' 'parent category requires at least %(num)s %(subcats_str)s.' ) % { 'target_category' : category . title , 'parent_category' : category_list . get_title ( ) , 'num' : min_num , 'subcats_str' : subcats_str } raise SitecatsValidationError ( error_msg ) child_ids = get_cache ( ) . get_child_ids ( category_list . alias ) check_min_num ( len ( child_ids ) ) if category_list . obj is None : # Remove category itself and children. category . delete ( ) else : # Remove just a category-to-object tie. # TODO filter user/status check_min_num ( category_list . obj . get_ties_for_categories_qs ( child_ids ) . count ( ) ) category_list . obj . remove_from_category ( category ) return True | Handles remove action from CategoryList editor . | 585 | 9 |
5,997 | def action_add ( cls , request , category_list ) : if not category_list . editor . allow_add : raise SitecatsSecurityException ( '`action_add()` is not supported by `%s` category.' % category_list . alias ) titles = request . POST . get ( 'category_title' , '' ) . strip ( ) if not titles : raise SitecatsSecurityException ( 'Unsupported `category_title` value - `%s` - is passed to `action_add()`.' % titles ) if category_list . editor . category_separator is None : titles = [ titles ] else : titles = [ title . strip ( ) for title in titles . split ( category_list . editor . category_separator ) if title . strip ( ) ] def check_max_num ( num , max_num , category_title ) : if max_num is not None and num + 1 > max_num : subcats_str = ungettext_lazy ( 'subcategory' , 'subcategories' , max_num ) error_msg = _ ( 'Unable to add "%(target_category)s" category into "%(parent_category)s": ' 'parent category can have at most %(num)s %(subcats_str)s.' ) % { 'target_category' : category_title , 'parent_category' : category_list . get_title ( ) , 'num' : max_num , 'subcats_str' : subcats_str } raise SitecatsValidationError ( error_msg ) target_category = None for category_title in titles : exists = get_cache ( ) . find_category ( category_list . alias , category_title ) if exists and category_list . obj is None : # Already exists. return exists if not exists and not category_list . editor . allow_new : error_msg = _ ( 'Unable to create a new "%(new_category)s" category inside of "%(parent_category)s": ' 'parent category does not support this action.' ) % { 'new_category' : category_title , 'parent_category' : category_list . get_title ( ) } raise SitecatsNewCategoryException ( error_msg ) max_num = category_list . editor . max_num child_ids = get_cache ( ) . get_child_ids ( category_list . alias ) if not exists : # Add new category. if category_list . obj is None : check_max_num ( len ( child_ids ) , max_num , category_title ) # TODO status target_category = get_category_model ( ) . add ( category_title , request . user , parent = category_list . get_category_model ( ) ) else : target_category = exists # Use existing one for a tie. if category_list . obj is not None : # TODO status check_max_num ( category_list . obj . get_ties_for_categories_qs ( child_ids ) . count ( ) , max_num , category_title ) category_list . obj . add_to_category ( target_category , request . user ) return target_category | Handles add action from CategoryList editor . | 696 | 9 |
5,998 | def shrink ( image , apikey ) : def _handle_response ( response ) : body = json . loads ( response . read ( ) ) if response . code == TinyPNGResponse . SUCCESS_CODE : body [ 'location' ] = response . headers . getheader ( "Location" ) try : body [ 'bytes' ] = urlopen ( body [ 'location' ] ) . read ( ) except : body [ 'bytes' ] = None return response . code , body auth = b64encode ( bytes ( "api:" + apikey ) ) . decode ( "ascii" ) request = Request ( TINYPNG_SHRINK_URL , image ) request . add_header ( "Authorization" , "Basic %s" % auth ) try : response = urlopen ( request ) ( code , response_dict ) = _handle_response ( response ) except HTTPError as e : ( code , response_dict ) = _handle_response ( e ) return TinyPNGResponse ( code , * * response_dict ) | To shrink a PNG image post the data to the API service . The response is a JSON message . The initial request must be authorized with HTTP Basic authorization . | 227 | 31 |
5,999 | def download_and_install_dependencies ( ) : try : import requests except ImportError : raise ValueError ( "Python 3.6+ is required." ) dependencies = { "hmm_databases" : HMM_URL } if sys . platform . startswith ( "linux" ) or "bsd" in sys . platform : dependencies [ "prodigal" ] = "{}.linux" . format ( BASE_PRODIGAL ) dependencies [ "louvain" ] = ( "https://lip6.github.io/Louvain-BinaryBuild/" "louvain_linux.tar.gz" ) elif sys . platform == "darwin" : dependencies [ "prodigal" ] = "{}.osx.10.9.5" . format ( BASE_PRODIGAL ) dependencies [ "louvain" ] = ( "https://github.com/lip6/Louvain-BinaryBuilds/raw/osx/" "louvain_osx.tar.gz" ) elif sys . platform . startswith ( "win" ) or sys . platform == "cygwin" : dependencies [ "prodigal" ] = "{}.windows.exe" dependencies [ "louvain" ] = ( "https://ci.appveyor.com/api/projects/yanntm/" "Louvain-BinaryBuild/artifacts/website/" "louvain_windows.tar.gz" ) else : raise NotImplementedError ( "Your platform is not supported: {}" . format ( sys . platform ) ) cache_dir = pathlib . Path . cwd ( ) / pathlib . Path ( "cache" ) try : print ( "Downloading dependencies..." ) cache_dir . mkdir ( ) for dependency_name , url in dependencies . items ( ) : print ( "Downloading {} at {}" . format ( dependency_name , url ) ) request = requests . get ( url ) basename = url . split ( "/" ) [ - 1 ] with open ( cache_dir / basename , "wb" ) as handle : print ( dependency_name , basename , cache_dir / basename ) handle . write ( request . content ) except FileExistsError : print ( "Using cached dependencies..." ) share_dir = pathlib . Path . cwd ( ) tools_dir = share_dir / "tools" louvain_dir = tools_dir / "louvain" louvain_dir . mkdir ( parents = True , exist_ok = True ) louvain_basename = dependencies [ "louvain" ] . split ( "/" ) [ - 1 ] louvain_path = louvain_dir / louvain_basename ( cache_dir / louvain_basename ) . replace ( louvain_path ) with tarfile . open ( louvain_path , "r:gz" ) as tar : tar . extractall ( ) hmm_basename = dependencies [ "hmm_databases" ] . split ( "/" ) [ - 1 ] hmm_path = share_dir / hmm_basename ( cache_dir / hmm_basename ) . replace ( hmm_path ) prodigal_basename = dependencies [ "prodigal" ] . split ( "/" ) [ - 1 ] prodigal_path = tools_dir / "prodigal" ( cache_dir / prodigal_basename ) . replace ( prodigal_path ) | Setup URLS and download dependencies for Python 3 . 6 + | 772 | 12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.