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 ( va... | 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 .... | 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_fil... | 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_i... | 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... | 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 ... | 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 - s... | 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 tm... | 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 . ImportFromWk... | 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 = ras... | 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... | 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 , gd... | 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 ] + ... | 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 . d... | 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 ) ... | 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 ... | 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 ... | 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... | 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_dil... | 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... | 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... | 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 ... | 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 ( ) ... | 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 ) ... | 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 ... | 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 GeoJS... | 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 ( '-'... | 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." # Tak... | 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 '.-' ) ) ... | 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 = N... | 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_na... | 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 }... | 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... | 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_... | 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... | 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 . listtransac... | 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' ... | 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 .... | 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 . v... | 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 ( bu... | 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_... | 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 Pa... | 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_se... | 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 = splitt... | 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' ... | 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_... | 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 ... | 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 ... | 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... | 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... | 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 ( va... | 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 li... | 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' : 'Tkatc... | 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 ... | 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_foun... | 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 ... | 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 =... | 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 Siteca... | 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 SitecatsSecurityExcepti... | 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 [ '... | 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 ) ... | 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.