idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
19,900
def rabin_karp_factor ( s , t , k ) : last_pos = pow ( DOMAIN , k - 1 ) % PRIME pos = { } assert k > 0 if len ( s ) < k or len ( t ) < k : return None hash_t = 0 for j in range ( k ) : hash_t = ( DOMAIN * hash_t + ord ( t [ j ] ) ) % PRIME for j in range ( len ( t ) - k + 1 ) : if hash_t in pos : pos [ hash_t ] . appen...
Find a common factor by Rabin - Karp
19,901
def rectangles_from_histogram ( H ) : best = ( float ( '-inf' ) , 0 , 0 , 0 ) S = [ ] H2 = H + [ float ( '-inf' ) ] for right in range ( len ( H2 ) ) : x = H2 [ right ] left = right while len ( S ) > 0 and S [ - 1 ] [ 1 ] >= x : left , height = S . pop ( ) rect = ( height * ( right - left ) , left , height , right ) if...
Largest Rectangular Area in a Histogram
19,902
def topological_order_dfs ( graph ) : n = len ( graph ) order = [ ] times_seen = [ - 1 ] * n for start in range ( n ) : if times_seen [ start ] == - 1 : times_seen [ start ] = 0 to_visit = [ start ] while to_visit : node = to_visit [ - 1 ] children = graph [ node ] if times_seen [ node ] == len ( children ) : to_visit ...
Topological sorting by depth first search
19,903
def topological_order ( graph ) : V = range ( len ( graph ) ) indeg = [ 0 for _ in V ] for node in V : for neighbor in graph [ node ] : indeg [ neighbor ] += 1 Q = [ node for node in V if indeg [ node ] == 0 ] order = [ ] while Q : node = Q . pop ( ) order . append ( node ) for neighbor in graph [ node ] : indeg [ neig...
Topological sorting by maintaining indegree
19,904
def getkth ( self , k ) : "starts from 0" if k >= len ( self ) : raise IndexError k += 1 h = len ( self . next ) - 1 x = self while k : while x . next [ h ] is None or x . count [ h ] > k : h -= 1 k -= x . count [ h ] x = x . next [ h ] return x . key
starts from 0
19,905
def pop ( self ) : try : x = next ( iter ( self ) ) self . remove ( x ) return x except StopIteration : raise KeyError ( 'pop from an empty set' )
Pops the first element
19,906
def merge ( x , y ) : z = [ ] i = 0 j = 0 while i < len ( x ) or j < len ( y ) : if j == len ( y ) or i < len ( x ) and x [ i ] <= y [ j ] : z . append ( x [ i ] ) i += 1 else : z . append ( y [ j ] ) j += 1 return z
Merge two ordered lists
19,907
def consecutive_ones_property ( sets , universe = None ) : if universe is None : universe = set ( ) for S in sets : universe |= set ( S ) tree = PQ_tree ( universe ) try : for S in sets : tree . reduce ( S ) return tree . border ( ) except IsNotC1P : return None
Check the consecutive ones property .
19,908
def add ( self , node ) : self . sons . append ( node ) node . parent = self
Add one node as descendant
19,909
def add_group ( self , L ) : if len ( L ) == 1 : self . add ( L [ 0 ] ) elif len ( L ) >= 2 : x = PQ_node ( P_shape ) x . add_all ( L ) self . add ( x )
Add elements of L as descendants of the node . If there are several elements in L group them in a P - node first
19,910
def border ( self , L ) : if self . shape == L_shape : L . append ( self . value ) else : for x in self . sons : x . border ( L )
Append to L the border of the subtree .
19,911
def maximum_border_length ( w ) : n = len ( w ) f = [ 0 ] * n k = 0 for i in range ( 1 , n ) : while w [ k ] != w [ i ] and k > 0 : k = f [ k - 1 ] if w [ k ] == w [ i ] : k += 1 f [ i ] = k return f
Maximum string borders by Knuth - Morris - Pratt
19,912
def knuth_morris_pratt ( s , t ) : sep = '\x00' assert sep not in t and sep not in s f = maximum_border_length ( t + sep + s ) n = len ( t ) for i , fi in enumerate ( f ) : if fi == n : return i - 2 * n return - 1
Find a substring by Knuth - Morris - Pratt
19,913
def powerstring_by_border ( u ) : f = maximum_border_length ( u ) n = len ( u ) if n % ( n - f [ - 1 ] ) == 0 : return n // ( n - f [ - 1 ] ) return 1
Power string by Knuth - Morris - Pratt
19,914
def matrix_mult_opt_order ( M ) : n = len ( M ) r = [ len ( Mi ) for Mi in M ] c = [ len ( Mi [ 0 ] ) for Mi in M ] opt = [ [ 0 for j in range ( n ) ] for i in range ( n ) ] arg = [ [ None for j in range ( n ) ] for i in range ( n ) ] for j_i in range ( 1 , n ) : for i in range ( n - j_i ) : j = i + j_i opt [ i ] [ j ]...
Matrix chain multiplication optimal order
19,915
def matrix_chain_mult ( M ) : opt , arg = matrix_mult_opt_order ( M ) return _apply_order ( M , arg , 0 , len ( M ) - 1 )
Matrix chain multiplication
19,916
def levenshtein ( x , y ) : n = len ( x ) m = len ( y ) A = [ [ i + j for j in range ( m + 1 ) ] for i in range ( n + 1 ) ] for i in range ( n ) : for j in range ( m ) : A [ i + 1 ] [ j + 1 ] = min ( A [ i ] [ j + 1 ] + 1 , A [ i + 1 ] [ j ] + 1 , A [ i ] [ j ] + int ( x [ i ] != y [ j ] ) ) return A [ n ] [ m ]
Levenshtein edit distance
19,917
def gale_shapley ( men , women ) : n = len ( men ) assert n == len ( women ) current_suitor = [ 0 ] * n spouse = [ None ] * n rank = [ [ 0 ] * n for j in range ( n ) ] for j in range ( n ) : for r in range ( n ) : rank [ j ] [ women [ j ] [ r ] ] = r singles = deque ( range ( n ) ) while singles : i = singles . popleft...
Stable matching by Gale - Shapley
19,918
def eulerian_tour_directed ( graph ) : P = [ ] Q = [ 0 ] R = [ ] succ = [ 0 ] * len ( graph ) while Q : node = Q . pop ( ) P . append ( node ) while succ [ node ] < len ( graph [ node ] ) : neighbor = graph [ node ] [ succ [ node ] ] succ [ node ] += 1 R . append ( neighbor ) node = neighbor while R : Q . append ( R . ...
Eulerian tour on a directed graph
19,919
def write_cycle ( filename , graph , cycle , directed ) : n = len ( graph ) weight = [ [ float ( 'inf' ) ] * n for _ in range ( n ) ] for r in range ( 1 , len ( cycle ) ) : weight [ cycle [ r - 1 ] ] [ cycle [ r ] ] = r if not directed : weight [ cycle [ r ] ] [ cycle [ r - 1 ] ] = r write_graph ( filename , graph , ar...
Write an eulerian tour in DOT format
19,920
def random_eulerien_graph ( n ) : graphe = [ [ ] for _ in range ( n ) ] for v in range ( n - 1 ) : noeuds = random . sample ( range ( v + 1 , n ) , random . choice ( range ( 0 if len ( graphe [ v ] ) % 2 == 0 else 1 , ( n - v ) , 2 ) ) ) graphe [ v ] . extend ( noeuds ) for w in graphe [ v ] : if w > v : graphe [ w ] ....
Generates some random eulerian graph
19,921
def longest_common_subsequence ( x , y ) : n = len ( x ) m = len ( y ) A = [ [ 0 for j in range ( m + 1 ) ] for i in range ( n + 1 ) ] for i in range ( n ) : for j in range ( m ) : if x [ i ] == y [ j ] : A [ i + 1 ] [ j + 1 ] = A [ i ] [ j ] + 1 else : A [ i + 1 ] [ j + 1 ] = max ( A [ i ] [ j + 1 ] , A [ i + 1 ] [ j ...
Longest common subsequence
19,922
def kuhn_munkres ( G ) : assert len ( G ) == len ( G [ 0 ] ) n = len ( G ) mu = [ None ] * n mv = [ None ] * n lu = [ max ( row ) for row in G ] lv = [ 0 ] * n for u0 in range ( n ) : if mu [ u0 ] is None : while True : au = [ False ] * n av = [ False ] * n if improve_matching ( G , u0 , mu , mv , au , av , lu , lv ) :...
Maximum profit perfect matching
19,923
def kuhn_munkres ( G , TOLERANCE = 1e-6 ) : nU = len ( G ) U = range ( nU ) nV = len ( G [ 0 ] ) V = range ( nV ) assert nU <= nV mu = [ None ] * nU mv = [ None ] * nV lu = [ max ( row ) for row in G ] lv = [ 0 ] * nV for root in U : au = [ False ] * nU au [ root ] = True Av = [ None ] * nV slack = [ ( lu [ root ] + lv...
Maximum profit bipartite matching by Kuhn - Munkres
19,924
def interval_cover ( I ) : S = [ ] for start , end in sorted ( I , key = lambda v : v [ 1 ] ) : if not S or S [ - 1 ] < start : S . append ( end ) return S
Minimum interval cover
19,925
def dist01 ( graph , weight , source = 0 , target = None ) : n = len ( graph ) dist = [ float ( 'inf' ) ] * n prec = [ None ] * n black = [ False ] * n dist [ source ] = 0 gray = deque ( [ source ] ) while gray : node = gray . pop ( ) if black [ node ] : continue black [ node ] = True if node == target : break for neig...
Shortest path in a 0 1 weighted graph
19,926
def max_interval_intersec ( S ) : B = ( [ ( left , + 1 ) for left , right in S ] + [ ( right , - 1 ) for left , right in S ] ) B . sort ( ) c = 0 best = ( c , None ) for x , d in B : c += d if best [ 0 ] < c : best = ( c , x ) return best
determine a value that is contained in a largest number of given intervals
19,927
def dist_grid ( grid , source , target = None ) : rows = len ( grid ) cols = len ( grid [ 0 ] ) dirs = [ ( 0 , + 1 , '>' ) , ( 0 , - 1 , '<' ) , ( + 1 , 0 , 'v' ) , ( - 1 , 0 , '^' ) ] i , j = source grid [ i ] [ j ] = 's' Q = deque ( ) Q . append ( source ) while Q : i1 , j1 = Q . popleft ( ) for di , dj , symbol in d...
Distances in a grid by BFS
19,928
def _range_min ( self , p , start , span , i , k ) : if start + span <= i or k <= start : return self . INF if i <= start and start + span <= k : return self . s [ p ] left = self . _range_min ( 2 * p , start , span // 2 , i , k ) right = self . _range_min ( 2 * p + 1 , start + span // 2 , span // 2 , i , k ) return mi...
returns the minimum in t in the indexes [ i k ) intersected with [ start start + span ) . p is the node associated to the later interval .
19,929
def _clear ( self , node , left , right ) : if self . lazyset [ node ] is not None : val = self . lazyset [ node ] self . minval [ node ] = val self . maxval [ node ] = val self . sumval [ node ] = val * ( right - left ) self . lazyset [ node ] = None if left < right - 1 : self . lazyset [ 2 * node ] = val self . lazya...
propagates the lazy updates for this node to the subtrees . as a result the maxval minval sumval values for the node are up to date .
19,930
def left_right_inversions ( tab ) : n = len ( tab ) left = [ 0 ] * n right = [ 0 ] * n tmp = [ None ] * n rank = list ( range ( n ) ) _merge_sort ( tab , tmp , rank , left , right , 0 , n ) return left , right
Compute left and right inversions of each element of a table .
19,931
def interval_tree ( intervals ) : if intervals == [ ] : return None center = intervals [ len ( intervals ) // 2 ] [ 0 ] L = [ ] R = [ ] C = [ ] for I in intervals : if I [ 1 ] <= center : L . append ( I ) elif center < I [ 0 ] : R . append ( I ) else : C . append ( I ) by_low = sorted ( ( I [ 0 ] , I ) for I in C ) by_...
Construct an interval tree
19,932
def intervals_containing ( t , p ) : INF = float ( 'inf' ) if t is None : return [ ] if p < t . center : retval = intervals_containing ( t . left , p ) j = bisect_right ( t . by_low , ( p , ( INF , INF ) ) ) for i in range ( j ) : retval . append ( t . by_low [ i ] [ 1 ] ) else : retval = intervals_containing ( t . rig...
Query the interval tree
19,933
def andrew ( S ) : S . sort ( ) top = [ ] bot = [ ] for p in S : while len ( top ) >= 2 and not left_turn ( p , top [ - 1 ] , top [ - 2 ] ) : top . pop ( ) top . append ( p ) while len ( bot ) >= 2 and not left_turn ( bot [ - 2 ] , bot [ - 1 ] , p ) : bot . pop ( ) bot . append ( p ) return bot [ : - 1 ] + top [ : 0 : ...
Convex hull by Andrew
19,934
def discrete_binary_search ( tab , lo , hi ) : while lo < hi : mid = lo + ( hi - lo ) // 2 if tab [ mid ] : hi = mid else : lo = mid + 1 return lo
Binary search in a table
19,935
def continuous_binary_search ( f , lo , hi , gap = 1e-4 ) : while hi - lo > gap : mid = ( lo + hi ) / 2. if f ( mid ) : hi = mid else : lo = mid return lo
Binary search for a function
19,936
def ternary_search ( f , lo , hi , gap = 1e-10 ) : while hi - lo > gap : step = ( hi - lo ) / 3. if f ( lo + step ) < f ( lo + 2 * step ) : lo += step else : hi -= step return lo
Ternary maximum search for a bitonic function
19,937
def anagrams ( w ) : w = list ( set ( w ) ) d = { } for i in range ( len ( w ) ) : s = '' . join ( sorted ( w [ i ] ) ) if s in d : d [ s ] . append ( i ) else : d [ s ] = [ i ] answer = [ ] for s in d : if len ( d [ s ] ) > 1 : answer . append ( [ w [ i ] for i in d [ s ] ] ) return answer
group a list of words into anagrams
19,938
def subset_sum ( x , R ) : k = len ( x ) // 2 Y = [ v for v in part_sum ( x [ : k ] ) ] Z = [ R - v for v in part_sum ( x [ k : ] ) ] Y . sort ( ) Z . sort ( ) i = 0 j = 0 while i < len ( Y ) and j < len ( Z ) : if Y [ i ] == Z [ j ] : return True elif Y [ i ] < Z [ j ] : i += 1 else : j += 1 return False
Subsetsum by splitting
19,939
def tarjan_recursif ( graph ) : global sccp , waiting , dfs_time , dfs_num sccp = [ ] waiting = [ ] waits = [ False ] * len ( graph ) dfs_time = 0 dfs_num = [ None ] * len ( graph ) def dfs ( node ) : global sccp , waiting , dfs_time , dfs_num waiting . append ( node ) waits [ node ] = True dfs_num [ node ] = dfs_time ...
Strongly connected components by Tarjan recursive implementation
19,940
def tarjan ( graph ) : n = len ( graph ) dfs_num = [ None ] * n dfs_min = [ n ] * n waiting = [ ] waits = [ False ] * n sccp = [ ] dfs_time = 0 times_seen = [ - 1 ] * n for start in range ( n ) : if times_seen [ start ] == - 1 : times_seen [ start ] = 0 to_visit = [ start ] while to_visit : node = to_visit [ - 1 ] if t...
Strongly connected components by Tarjan iterative implementation
19,941
def kosaraju ( graph ) : n = len ( graph ) order = [ ] sccp = [ ] kosaraju_dfs ( graph , range ( n ) , order , [ ] ) kosaraju_dfs ( reverse ( graph ) , order [ : : - 1 ] , [ ] , sccp ) return sccp [ : : - 1 ]
Strongly connected components by Kosaraju
19,942
def get_template_dirs ( ) : temp_glob = rel_to_cwd ( 'templates' , '**' , 'templates' , 'config.yaml' ) temp_groups = glob ( temp_glob ) temp_groups = [ get_parent_dir ( path , 2 ) for path in temp_groups ] return set ( temp_groups )
Return a set of all template directories .
19,943
def get_scheme_dirs ( ) : scheme_glob = rel_to_cwd ( 'schemes' , '**' , '*.yaml' ) scheme_groups = glob ( scheme_glob ) scheme_groups = [ get_parent_dir ( path ) for path in scheme_groups ] return set ( scheme_groups )
Return a set of all scheme directories .
19,944
def build ( templates = None , schemes = None , base_output_dir = None ) : template_dirs = templates or get_template_dirs ( ) scheme_files = get_scheme_files ( schemes ) base_output_dir = base_output_dir or rel_to_cwd ( 'output' ) if not template_dirs or not scheme_files : raise LookupError try : os . makedirs ( base_o...
Main build function to initiate building process .
19,945
def write_sources_file ( ) : file_content = ( 'schemes: ' 'https://github.com/chriskempson/base16-schemes-source.git\n' 'templates: ' 'https://github.com/chriskempson/base16-templates-source.git' ) file_path = rel_to_cwd ( 'sources.yaml' ) with open ( file_path , 'w' ) as file_ : file_ . write ( file_content )
Write a sources . yaml file to current working dir .
19,946
def get_yaml_dict ( yaml_file ) : try : with open ( yaml_file , 'r' ) as file_ : yaml_dict = yaml . safe_load ( file_ . read ( ) ) or { } return yaml_dict except FileNotFoundError : return { }
Return a yaml_dict from reading yaml_file . If yaml_file is empty or doesn t exist return an empty dict instead .
19,947
def _get_temp ( self , content ) : temp = None for line in content . splitlines ( ) : if not temp : match = TEMP_NEEDLE . match ( line ) if match : temp = match . group ( 1 ) . strip ( ) continue else : match = TEMP_END_NEEDLE . match ( line ) if match : return temp raise IndexError ( self . path )
Get the string that points to a specific base16 scheme .
19,948
def get_colorscheme ( self , scheme_file ) : scheme = get_yaml_dict ( scheme_file ) scheme_slug = builder . slugify ( scheme_file ) builder . format_scheme ( scheme , scheme_slug ) try : temp_base , temp_sub = self . temp . split ( '##' ) except ValueError : temp_base , temp_sub = ( self . temp . strip ( '##' ) , 'defa...
Return a string object with the colorscheme that is to be inserted .
19,949
def write ( self ) : with open ( self . path , 'w' ) as file_ : file_ . write ( self . content )
Write content back to file .
19,950
def update_mode ( arg_namespace ) : try : updater . update ( custom_sources = arg_namespace . custom ) except ( PermissionError , FileNotFoundError ) as exception : if isinstance ( exception , PermissionError ) : print ( 'No write permission for current working directory.' ) if isinstance ( exception , FileNotFoundErro...
Check command line arguments and run update function .
19,951
def get_address_details ( address , coin_symbol = 'btc' , txn_limit = None , api_key = None , before_bh = None , after_bh = None , unspent_only = False , show_confidence = False , confirmations = 0 , include_script = False ) : assert is_valid_address_for_coinsymbol ( b58_address = address , coin_symbol = coin_symbol ) ...
Takes an address and coin_symbol and returns the address details
19,952
def get_addresses_details ( address_list , coin_symbol = 'btc' , txn_limit = None , api_key = None , before_bh = None , after_bh = None , unspent_only = False , show_confidence = False , confirmations = 0 , include_script = False ) : for address in address_list : assert is_valid_address_for_coinsymbol ( b58_address = a...
Batch version of get_address_details method
19,953
def get_wallet_transactions ( wallet_name , api_key , coin_symbol = 'btc' , before_bh = None , after_bh = None , txn_limit = None , omit_addresses = False , unspent_only = False , show_confidence = False , confirmations = 0 ) : assert len ( wallet_name ) <= 25 , wallet_name assert api_key assert is_valid_coin_symbol ( ...
Takes a wallet api_key coin_symbol and returns the wallet s details
19,954
def get_address_overview ( address , coin_symbol = 'btc' , api_key = None ) : assert is_valid_address_for_coinsymbol ( b58_address = address , coin_symbol = coin_symbol ) url = make_url ( coin_symbol , 'addrs' , ** { address : 'balance' } ) params = { } if api_key : params [ 'token' ] = api_key r = requests . get ( url...
Takes an address and coin_symbol and return the address details
19,955
def generate_new_address ( coin_symbol = 'btc' , api_key = None ) : assert api_key , 'api_key required' assert is_valid_coin_symbol ( coin_symbol ) if coin_symbol not in ( 'btc-testnet' , 'bcy' ) : WARNING_MSG = [ 'Generating private key details server-side.' , 'You really should do this client-side.' , 'See https://gi...
Takes a coin_symbol and returns a new address with it s public and private keys .
19,956
def get_transaction_details ( tx_hash , coin_symbol = 'btc' , limit = None , tx_input_offset = None , tx_output_offset = None , include_hex = False , show_confidence = False , confidence_only = False , api_key = None ) : assert is_valid_hash ( tx_hash ) , tx_hash assert is_valid_coin_symbol ( coin_symbol ) , coin_symbo...
Takes a tx_hash coin_symbol and limit and returns the transaction details
19,957
def get_transactions_details ( tx_hash_list , coin_symbol = 'btc' , limit = None , api_key = None ) : for tx_hash in tx_hash_list : assert is_valid_hash ( tx_hash ) assert is_valid_coin_symbol ( coin_symbol ) if len ( tx_hash_list ) == 0 : return [ ] elif len ( tx_hash_list ) == 1 : return [ get_transaction_details ( t...
Takes a list of tx_hashes coin_symbol and limit and returns the transaction details
19,958
def get_num_confirmations ( tx_hash , coin_symbol = 'btc' , api_key = None ) : return get_transaction_details ( tx_hash = tx_hash , coin_symbol = coin_symbol , limit = 1 , api_key = api_key ) . get ( 'confirmations' )
Given a tx_hash return the number of confirmations that transactions has .
19,959
def get_broadcast_transactions ( coin_symbol = 'btc' , limit = 10 , api_key = None ) : url = make_url ( coin_symbol , 'txs' ) params = { } if api_key : params [ 'token' ] = api_key if limit : params [ 'limit' ] = limit r = requests . get ( url , params = params , verify = True , timeout = TIMEOUT_IN_SECONDS ) response_...
Get a list of broadcast but unconfirmed transactions Similar to bitcoind s getrawmempool method
19,960
def get_block_overview ( block_representation , coin_symbol = 'btc' , txn_limit = None , txn_offset = None , api_key = None ) : assert is_valid_coin_symbol ( coin_symbol ) assert is_valid_block_representation ( block_representation = block_representation , coin_symbol = coin_symbol ) url = make_url ( coin_symbol , ** d...
Takes a block_representation coin_symbol and txn_limit and gets an overview of that block including up to X transaction ids . Note that block_representation may be the block number or block hash
19,961
def get_blocks_overview ( block_representation_list , coin_symbol = 'btc' , txn_limit = None , api_key = None ) : for block_representation in block_representation_list : assert is_valid_block_representation ( block_representation = block_representation , coin_symbol = coin_symbol ) assert is_valid_coin_symbol ( coin_sy...
Batch request version of get_blocks_overview
19,962
def get_merkle_root ( block_representation , coin_symbol = 'btc' , api_key = None ) : return get_block_overview ( block_representation = block_representation , coin_symbol = coin_symbol , txn_limit = 1 , api_key = api_key ) [ 'mrkl_root' ]
Takes a block_representation and returns the merkle root
19,963
def get_bits ( block_representation , coin_symbol = 'btc' , api_key = None ) : return get_block_overview ( block_representation = block_representation , coin_symbol = coin_symbol , txn_limit = 1 , api_key = api_key ) [ 'bits' ]
Takes a block_representation and returns the number of bits
19,964
def get_nonce ( block_representation , coin_symbol = 'btc' , api_key = None ) : return get_block_overview ( block_representation = block_representation , coin_symbol = coin_symbol , txn_limit = 1 , api_key = api_key ) [ 'bits' ]
Takes a block_representation and returns the nonce
19,965
def get_prev_block_hash ( block_representation , coin_symbol = 'btc' , api_key = None ) : return get_block_overview ( block_representation = block_representation , coin_symbol = coin_symbol , txn_limit = 1 , api_key = api_key ) [ 'prev_block' ]
Takes a block_representation and returns the previous block hash
19,966
def get_block_hash ( block_height , coin_symbol = 'btc' , api_key = None ) : return get_block_overview ( block_representation = block_height , coin_symbol = coin_symbol , txn_limit = 1 , api_key = api_key ) [ 'hash' ]
Takes a block_height and returns the block_hash
19,967
def get_block_height ( block_hash , coin_symbol = 'btc' , api_key = None ) : return get_block_overview ( block_representation = block_hash , coin_symbol = coin_symbol , txn_limit = 1 , api_key = api_key ) [ 'height' ]
Takes a block_hash and returns the block_height
19,968
def get_block_details ( block_representation , coin_symbol = 'btc' , txn_limit = None , txn_offset = None , in_out_limit = None , api_key = None ) : assert is_valid_coin_symbol ( coin_symbol ) block_overview = get_block_overview ( block_representation = block_representation , coin_symbol = coin_symbol , txn_limit = txn...
Takes a block_representation coin_symbol and txn_limit and 1 ) Gets the block overview 2 ) Makes a separate API call to get specific data on txn_limit transactions
19,969
def get_blockchain_fee_estimates ( coin_symbol = 'btc' , api_key = None ) : overview = get_blockchain_overview ( coin_symbol = coin_symbol , api_key = api_key ) return { 'high_fee_per_kb' : overview [ 'high_fee_per_kb' ] , 'medium_fee_per_kb' : overview [ 'medium_fee_per_kb' ] , 'low_fee_per_kb' : overview [ 'low_fee_p...
Returns high medium and low fee estimates for a given blockchain .
19,970
def get_forwarding_address_details ( destination_address , api_key , callback_url = None , coin_symbol = 'btc' ) : assert is_valid_coin_symbol ( coin_symbol ) assert api_key , 'api_key required' url = make_url ( coin_symbol , 'payments' ) logger . info ( url ) params = { 'token' : api_key } data = { 'destination' : des...
Give a destination address and return the details of the input address that will automatically forward to the destination address
19,971
def get_forwarding_address ( destination_address , api_key , callback_url = None , coin_symbol = 'btc' ) : assert api_key , 'api_key required' resp_dict = get_forwarding_address_details ( destination_address = destination_address , api_key = api_key , callback_url = callback_url , coin_symbol = coin_symbol ) return res...
Give a destination address and return an input address that will automatically forward to the destination address . See get_forwarding_address_details if you also need the forwarding address ID .
19,972
def delete_forwarding_address ( payment_id , coin_symbol = 'btc' , api_key = None ) : assert payment_id , 'payment_id required' assert is_valid_coin_symbol ( coin_symbol ) assert api_key , 'api_key required' params = { 'token' : api_key } url = make_url ( ** dict ( payments = payment_id ) ) r = requests . delete ( url ...
Delete a forwarding address on a specific blockchain using its payment id
19,973
def send_faucet_coins ( address_to_fund , satoshis , api_key , coin_symbol = 'bcy' ) : assert coin_symbol in ( 'bcy' , 'btc-testnet' ) assert is_valid_address_for_coinsymbol ( b58_address = address_to_fund , coin_symbol = coin_symbol ) assert satoshis > 0 assert api_key , 'api_key required' url = make_url ( coin_symbol...
Send yourself test coins on the bitcoin or blockcypher testnet
19,974
def list_wallet_names ( api_key , is_hd_wallet = False , coin_symbol = 'btc' ) : assert is_valid_coin_symbol ( coin_symbol ) , coin_symbol assert api_key params = { 'token' : api_key } kwargs = dict ( wallets = 'hd' if is_hd_wallet else '' ) url = make_url ( coin_symbol , ** kwargs ) r = requests . get ( url , params =...
Get all the wallets belonging to an API key
19,975
def create_wallet_from_address ( wallet_name , address , api_key , coin_symbol = 'btc' ) : assert is_valid_address_for_coinsymbol ( address , coin_symbol ) assert api_key assert is_valid_wallet_name ( wallet_name ) , wallet_name data = { 'name' : wallet_name , 'addresses' : [ address , ] , } params = { 'token' : api_ke...
Create a new wallet with one address
19,976
def get_wallet_addresses ( wallet_name , api_key , is_hd_wallet = False , zero_balance = None , used = None , omit_addresses = False , coin_symbol = 'btc' ) : assert is_valid_coin_symbol ( coin_symbol ) assert api_key assert len ( wallet_name ) <= 25 , wallet_name assert zero_balance in ( None , True , False ) assert u...
Returns a list of wallet addresses as well as some meta - data
19,977
def make_tx_signatures ( txs_to_sign , privkey_list , pubkey_list ) : assert len ( privkey_list ) == len ( pubkey_list ) == len ( txs_to_sign ) signatures = [ ] for cnt , tx_to_sign in enumerate ( txs_to_sign ) : sig = der_encode_sig ( * ecdsa_raw_sign ( tx_to_sign . rstrip ( ' \t\r\n\0' ) , privkey_list [ cnt ] ) ) er...
Loops through txs_to_sign and makes signatures using privkey_list and pubkey_list
19,978
def broadcast_signed_transaction ( unsigned_tx , signatures , pubkeys , coin_symbol = 'btc' , api_key = None ) : assert 'errors' not in unsigned_tx , unsigned_tx assert api_key , 'api_key required' url = make_url ( coin_symbol , ** dict ( txs = 'send' ) ) data = unsigned_tx . copy ( ) data [ 'signatures' ] = signatures...
Broadcasts the transaction from create_unsigned_tx
19,979
def simple_spend ( from_privkey , to_address , to_satoshis , change_address = None , privkey_is_compressed = True , min_confirmations = 0 , api_key = None , coin_symbol = 'btc' ) : assert is_valid_coin_symbol ( coin_symbol ) , coin_symbol assert isinstance ( to_satoshis , int ) , to_satoshis assert api_key , 'api_key r...
Simple method to spend from one single - key address to another .
19,980
def get_metadata ( address = None , tx_hash = None , block_hash = None , api_key = None , private = True , coin_symbol = 'btc' ) : assert is_valid_coin_symbol ( coin_symbol ) , coin_symbol assert api_key or not private , 'Cannot see private metadata without an API key' kwarg = get_valid_metadata_identifier ( coin_symbo...
Get metadata using blockcypher s API .
19,981
def put_metadata ( metadata_dict , address = None , tx_hash = None , block_hash = None , api_key = None , private = True , coin_symbol = 'btc' ) : assert is_valid_coin_symbol ( coin_symbol ) , coin_symbol assert api_key assert metadata_dict and isinstance ( metadata_dict , dict ) , metadata_dict kwarg = get_valid_metad...
Embed metadata using blockcypher s API .
19,982
def delete_metadata ( address = None , tx_hash = None , block_hash = None , api_key = None , coin_symbol = 'btc' ) : assert is_valid_coin_symbol ( coin_symbol ) , coin_symbol assert api_key , 'api_key required' kwarg = get_valid_metadata_identifier ( coin_symbol = coin_symbol , address = address , tx_hash = tx_hash , b...
Only available for metadata that was embedded privately .
19,983
def to_satoshis ( input_quantity , input_type ) : assert input_type in UNIT_CHOICES , input_type if input_type in ( 'btc' , 'mbtc' , 'bit' ) : satoshis = float ( input_quantity ) * float ( UNIT_MAPPINGS [ input_type ] [ 'satoshis_per' ] ) elif input_type == 'satoshi' : satoshis = input_quantity else : raise Exception (...
convert to satoshis no rounding
19,984
def get_txn_outputs ( raw_tx_hex , output_addr_list , coin_symbol ) : err_msg = 'Library not able to parse %s transactions' % coin_symbol assert lib_can_deserialize_cs ( coin_symbol ) , err_msg assert isinstance ( output_addr_list , ( list , tuple ) ) for output_addr in output_addr_list : assert is_valid_address ( outp...
Used to verify a transaction hex does what s expected of it .
19,985
def get_blockcypher_walletname_from_mpub ( mpub , subchain_indices = [ ] ) : mpub = mpub . encode ( 'utf-8' ) if subchain_indices : mpub += ',' . join ( [ str ( x ) for x in subchain_indices ] ) . encode ( 'utf-8' ) return 'X%s' % sha256 ( mpub ) . hexdigest ( ) [ : 24 ]
Blockcypher limits wallet names to 25 chars .
19,986
def crl ( self ) : revoked_certs = self . get_revoked_certs ( ) crl = crypto . CRL ( ) now_str = timezone . now ( ) . strftime ( generalized_time ) for cert in revoked_certs : revoked = crypto . Revoked ( ) revoked . set_serial ( bytes_compat ( cert . serial_number ) ) revoked . set_reason ( b'unspecified' ) revoked . ...
Returns up to date CRL of this CA
19,987
def crl ( request , pk ) : authenticated = request . user . is_authenticated authenticated = authenticated ( ) if callable ( authenticated ) else authenticated if app_settings . CRL_PROTECTED and not authenticated : return HttpResponse ( _ ( 'Forbidden' ) , status = 403 , content_type = 'text/plain' ) ca = crl . ca_mod...
returns CRL of a CA
19,988
def font_list ( text = "test" , test = False ) : fonts = set ( FONT_MAP . keys ( ) ) if test : fonts = fonts - set ( TEST_FILTERED_FONTS ) for item in sorted ( list ( fonts ) ) : print ( str ( item ) + " : " ) text_temp = text try : tprint ( text_temp , str ( item ) ) except Exception : print ( FONT_ENVIRONMENT_WARNING...
Print all fonts .
19,989
def art_list ( test = False ) : for i in sorted ( list ( art_dic . keys ( ) ) ) : try : if test : raise Exception print ( i ) aprint ( i ) line ( ) except Exception : print ( ART_ENVIRONMENT_WARNING ) line ( ) if test : break
Print all 1 - Line arts .
19,990
def help_func ( ) : tprint ( "art" ) tprint ( "v" + VERSION ) print ( DESCRIPTION + "\n" ) print ( "Webpage : http://art.shaghighi.ir\n" ) print ( "Help : \n" ) print ( " - list ) print ( " - fonts ) print ( " - test ) print ( " - text 'yourtext' 'font(optional)' ) print ( " - shape 'shapename' ...
Print help page .
19,991
def aprint ( artname , number = 1 , text = "" ) : print ( art ( artname = artname , number = number , text = text ) )
Print 1 - line art .
19,992
def art ( artname , number = 1 , text = "" ) : if isinstance ( artname , str ) is False : raise artError ( ART_TYPE_ERROR ) artname = artname . lower ( ) arts = sorted ( art_dic . keys ( ) ) if artname == "random" or artname == "rand" or artname == "rnd" : filtered_arts = list ( set ( arts ) - set ( RANDOM_FILTERED_ART...
Return 1 - line art .
19,993
def distance_calc ( s1 , s2 ) : if len ( s1 ) > len ( s2 ) : s1 , s2 = s2 , s1 distances = range ( len ( s1 ) + 1 ) for i2 , c2 in enumerate ( s2 ) : distances_ = [ i2 + 1 ] for i1 , c1 in enumerate ( s1 ) : if c1 == c2 : distances_ . append ( distances [ i1 ] ) else : distances_ . append ( 1 + min ( ( distances [ i1 ]...
Calculate Levenshtein distance between two words .
19,994
def wizard_font ( text ) : text_length = len ( text ) if text_length <= TEXT_XLARGE_THRESHOLD : font = random . choice ( XLARGE_WIZARD_FONT ) elif text_length > TEXT_XLARGE_THRESHOLD and text_length <= TEXT_LARGE_THRESHOLD : font = random . choice ( LARGE_WIZARD_FONT ) elif text_length > TEXT_LARGE_THRESHOLD and text_l...
Check input text length for wizard mode .
19,995
def indirect_font ( font , fonts , text ) : if font == "rnd-small" or font == "random-small" or font == "rand-small" : font = random . choice ( RND_SIZE_DICT [ "small_list" ] ) return font if font == "rnd-medium" or font == "random-medium" or font == "rand-medium" : font = random . choice ( RND_SIZE_DICT [ "medium_list...
Check input font for indirect modes .
19,996
def __word2art ( word , font , chr_ignore , letters ) : split_list = [ ] result_list = [ ] splitter = "\n" for i in word : if ( ord ( i ) == 9 ) or ( ord ( i ) == 32 and font == "block" ) : continue if ( i not in letters . keys ( ) ) : if ( chr_ignore ) : continue else : raise artError ( str ( i ) + " is invalid." ) if...
Return art word .
19,997
def set_default ( font = DEFAULT_FONT , chr_ignore = True , filename = "art" , print_status = True ) : if isinstance ( font , str ) is False : raise artError ( FONT_TYPE_ERROR ) if isinstance ( chr_ignore , bool ) is False : raise artError ( CHR_IGNORE_TYPE_ERROR ) if isinstance ( filename , str ) is False : raise artE...
Change text2art tprint and tsave default values .
19,998
def objectgetter ( model , attr_name = 'pk' , field_name = 'pk' ) : def _getter ( request , * view_args , ** view_kwargs ) : if attr_name not in view_kwargs : raise ImproperlyConfigured ( 'Argument {0} is not available. Given arguments: [{1}]' . format ( attr_name , ', ' . join ( view_kwargs . keys ( ) ) ) ) try : retu...
Helper that returns a function suitable for use as the fn argument to the permission_required decorator . Internally uses get_object_or_404 so keep in mind that this may raise Http404 .
19,999
def set_base_dir ( self , base_dir ) : self . _base_dir = base_dir self . icon_cache . set_base_dir ( base_dir )
Set the base directory to be used for all relative filenames .