code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if blockchain_name == 'bitcoin': return get_bitcoin_virtual_transactions(blockchain_opts, first_block_height, last_block_height, tx_filter=tx_filter, **hints) else: raise ValueError("Unknown blockchain {}".format(blockchain_name))
def get_virtual_transactions(blockchain_name, blockchain_opts, first_block_height, last_block_height, tx_filter=None, **hints)
Get the sequence of virtualchain transactions from a particular blockchain over a given range of block heights. Returns a list of tuples in the format of [(block height, [txs])], where each tx in [txs] is the parsed transaction. The parsed transaction will conform to... # TODO write a spec for this Ea...
1.992753
2.429697
0.820165
if blockchain == 'bitcoin': return btc_tx_deserialize(raw_tx, **blockchain_opts) else: raise ValueError("Unknown blockchain {}".format(blockchain))
def tx_parse(raw_tx, blockchain='bitcoin', **blockchain_opts)
Parse a raw transaction, based on the type of blockchain it's from Returns a tx dict on success (see get_virtual_transactions) Raise ValueError for unknown blockchain Raise some other exception for invalid raw_tx (implementation-specific)
3.079449
3.319482
0.92769
if blockchain == 'bitcoin': return btc_tx_output_has_data(output, **blockchain_opts) else: return ValueError('Unknown blockchain "{}"'.format(blockchain))
def tx_output_has_data(output, blockchain='bitcoin', **blockchain_opts)
Give a blockchain name and a tx output, determine whether or not it is a data-bearing script--i.e. one with data for the state engine. Return True if so Return False if not
3.325194
3.951164
0.841573
if blockchain == 'bitcoin': return btc_tx_output_script_has_data(out_script, **blockchain_opts) else: raise ValueError('Unknown blockchain "{}"'.format(blockchain))
def tx_is_data_script(out_script, blockchain='bitcoin', **blockchain_opts)
Given a blockchain name and an output script (tx['outs'][x]['script']), determine whether or not it is a data-bearing script---i.e. one with data for the state engine. Return True if so Reurn False if not
3.417533
4.201661
0.813377
if blockchain == 'bitcoin': return btc_tx_extend(partial_tx_hex, new_inputs, new_outputs, **blockchain_opts) else: raise ValueError('Unknown blockchain "{}"'.format(blockchain))
def tx_extend(partial_tx_hex, new_inputs, new_outputs, blockchain='bitcoin', **blockchain_opts)
Add a set of inputs and outputs to a tx. Return the new tx on success Raise on error
2.059125
2.404537
0.85635
if blockchain == 'bitcoin': return btc_tx_sign_input(tx_hex, idx, prevout_script, prevout_amount, private_key_info, **blockchain_opts) else: raise ValueError('Unknown blockchain "{}"'.format(blockchain))
def tx_sign_input(tx_hex, idx, prevout_script, prevout_amount, private_key_info, blockchain='bitcoin', **blockchain_opts)
Sign a given input in a transaction, given the previous output script and previous output amount. Different blockchains can require additional fields; pass thse in **blockchain_opts. Return the serialized tx with the given input signed on success Raise on error
1.793467
2.219543
0.808034
if blockchain == 'bitcoin': return btc_tx_sign_all_unsigned_inputs(privkey_info, prev_outputs, unsigned_tx_hex, **blockchain_opts) else: raise ValueError('Unknown blockchain "{}"'.format(blockchain))
def tx_sign_all_unsigned_inputs(privkey_info, prev_outputs, unsigned_tx_hex, blockchain='bitcoin', **blockchain_opts)
Sign all unsigned inputs to a given transaction with the given private key. Also, pass in the list of previous outputs to the transaction so they can be paired with the right input (i.e. prev_outputs is a list of tx outputs that are in 1-to-1 correspondance with the inputs in the serialized tx) Different ...
1.925067
2.448577
0.786198
url = 'http://pla.esac.esa.int/pla/aio/product-action?MAP.MAP_ID=HFI_CompMap_ThermalDustModel_2048_R1.20.fits' md5 = '8d804f4e64e709f476a63f0dfed1fd11' fname = os.path.join( data_dir(), 'planck', 'HFI_CompMap_ThermalDustModel_2048_R1.20.fits') fetch_utils.download_and_verify...
def fetch()
Downloads the Planck Collaboration (2013) dust map, placing it in the default ``dustmaps`` data directory.
8.883451
7.657162
1.160149
return self._scale * super(PlanckQuery, self).query(coords, **kwargs)
def query(self, coords, **kwargs)
Returns E(B-V) (or a different Planck dust inference, depending on how the class was intialized) at the specified location(s) on the sky. Args: coords (:obj:`astropy.coordinates.SkyCoord`): The coordinates to query. Returns: A float array of the selected Planck componen...
12.035398
13.711454
0.877762
# when given a string, assume user wants to index raw json if isinstance(data, string_types): return '{"index":{}}', data # make sure we don't alter the action data = data.copy() op_type = data.pop('_op_type', 'index') action = {op_type: {}} for key in ('_index', '_parent', '_p...
def expand_action(data)
From one document or action definition passed in by the user extract the action/data lines needed for elasticsearch's :meth:`~elasticsearch.Elasticsearch.bulk` api.
3.908145
3.713949
1.052288
bulk_actions = [] size, action_count = 0, 0 for action, data in actions: action = serializer.dumps(action) cur_size = len(action) + 1 if data is not None: data = serializer.dumps(data) cur_size += len(data) + 1 # full chunk, send it and start a ...
def _chunk_actions(actions, chunk_size, max_chunk_bytes, serializer)
Split actions into chunks by number or size, serialize them into strings in the process.
2.265346
2.263483
1.000823
# if raise on error is set, we need to collect errors per chunk before raising them errors = [] try: # send the actual request resp = client.bulk('\n'.join(bulk_actions) + '\n', **kwargs) except TransportError as e: # default behavior - just propagate exception if r...
def _process_bulk_chunk(client, bulk_actions, raise_on_exception=True, raise_on_error=True, **kwargs)
Send a bulk request to elasticsearch and process the output.
4.762193
4.738499
1.005
actions = map(expand_action_callback, actions) for bulk_actions in _chunk_actions(actions, chunk_size, max_chunk_bytes, client.transport.serializer): for result in _process_bulk_chunk(client, bulk_actions, raise_on_exception, raise_on_error, **kwargs): yield result
def streaming_bulk(client, actions, chunk_size=500, max_chunk_bytes=100 * 1014 * 1024, raise_on_error=True, expand_action_callback=expand_action, raise_on_exception=True, **kwargs)
Streaming bulk consumes actions from the iterable passed in and yields results per action. For non-streaming usecases use :func:`~elasticsearch.helpers.bulk` which is a wrapper around streaming bulk that returns summary information about the bulk operation once the entire input is consumed and sent. ...
3.032352
4.505491
0.673035
success, failed = 0, 0 # list of errors to be collected is not stats_only errors = [] for ok, item in streaming_bulk(client, actions, **kwargs): # go through request-reponse pairs and detect failures if not ok: if not stats_only: errors.append(item) ...
def bulk(client, actions, stats_only=False, **kwargs)
Helper for the :meth:`~elasticsearch.Elasticsearch.bulk` api that provides a more human friendly interface - it consumes an iterator of actions and sends them to elasticsearch in chunks. It returns a tuple with summary information - number of successfully executed actions and either list of errors or nu...
5.125278
5.369366
0.954541
# Avoid importing multiprocessing unless parallel_bulk is used # to avoid exceptions on restricted environments like App Engine from multiprocessing.dummy import Pool actions = map(expand_action_callback, actions) pool = Pool(thread_count) for result in pool.imap( lambda chunk: li...
def parallel_bulk(client, actions, thread_count=4, chunk_size=500, max_chunk_bytes=100 * 1014 * 1024, expand_action_callback=expand_action, **kwargs)
Parallel version of the bulk helper run in multiple threads at once. :arg client: instance of :class:`~elasticsearch.Elasticsearch` to use :arg actions: iterator containing the actions :arg thread_count: size of the threadpool to use for the bulk requests :arg chunk_size: number of docs in one chunk sen...
4.765863
5.123172
0.930256
if not preserve_order: kwargs['search_type'] = 'scan' # initial search resp = client.search(body=query, scroll=scroll, size=size, **kwargs) scroll_id = resp.get('_scroll_id') if scroll_id is None: return first_run = True while True: # if we didn't set search_ty...
def scan(client, query=None, scroll='5m', raise_on_error=True, preserve_order=False, size=1000, **kwargs)
Simple abstraction on top of the :meth:`~elasticsearch.Elasticsearch.scroll` api - a simple iterator that yields all hits as returned by underlining scroll requests. By default scan does not return results in any pre-determined order. To have a standard order in the returned documents (either by score o...
2.61531
2.599
1.006276
oldcontext = getcontext() _local.__bigfloat_context__ = oldcontext + context
def setcontext(context, _local=local)
Set the current context to that given. Attributes provided by ``context`` override those in the current context. If ``context`` doesn't specify a particular attribute, the attribute from the current context shows through.
16.521933
36.373585
0.454229
rounding = context.rounding bf = mpfr.Mpfr_t.__new__(cls) mpfr.mpfr_init2(bf, context.precision) args = (bf,) + args + (rounding,) ternary = f(*args) with _temporary_exponent_bounds(context.emin, context.emax): ternary = mpfr.mpfr_check_range(bf, ternary, rounding) if contex...
def _apply_function_in_context(cls, f, args, context)
Apply an MPFR function 'f' to the given arguments 'args', rounding to the given context. Returns a new Mpfr object with precision taken from the current context.
5.797838
5.613684
1.032804
if not hasattr(p[1], 'append_predicate'): p[1] = ast.PredicatedExpression(p[1]) p[1].append_predicate(p[2]) p[0] = p[1]
def p_filter_expr_predicate(p)
FilterExpr : FilterExpr Predicate
3.502619
3.395164
1.03165
# FIXME: This production also matches NodeType() or # processing-instruction("foo"), which are technically NodeTest qname = p[1] p[0] = ast.FunctionCall(qname[0], qname[1], p[2])
def p_function_call(p)
FunctionCall : FuncQName FormalArguments
14.948142
13.292274
1.124574
level = logging.CRITICAL if DEBUG: logging.disable(logging.NOTSET) level = logging.DEBUG if name is None: name = "<unknown>" log = logging.getLogger(name=name) log.setLevel( level ) console = logging.StreamHandler() console.setLevel( level ) log_format = (...
def get_logger(name=None)
Get virtualchain's logger
2.605438
2.600687
1.001827
config_filename = impl.get_virtual_chain_name() + ".ini" return os.path.join(working_dir, config_filename)
def get_config_filename(impl, working_dir)
Get the absolute path to the config file.
4.348955
4.199225
1.035657
db_filename = impl.get_virtual_chain_name() + ".db" return os.path.join(working_dir, db_filename)
def get_db_filename(impl, working_dir)
Get the absolute path to the last-block file.
4.065875
3.871171
1.050296
snapshots_filename = impl.get_virtual_chain_name() + ".snapshots" return os.path.join(working_dir, snapshots_filename)
def get_snapshots_filename(impl, working_dir)
Get the absolute path to the chain's consensus snapshots file.
4.245095
3.468546
1.223883
lockfile_name = impl.get_virtual_chain_name() + ".lock" return os.path.join(working_dir, lockfile_name)
def get_lockfile_filename(impl, working_dir)
Get the absolute path to the chain's indexing lockfile
3.971779
3.120363
1.272858
loaded = False bitcoind_server = None bitcoind_port = None bitcoind_user = None bitcoind_passwd = None bitcoind_timeout = None bitcoind_regtest = None bitcoind_p2p_port = None bitcoind_spv_path = None regtest = None if config_file is not None: parser = SafeC...
def get_bitcoind_config(config_file=None, impl=None)
Set bitcoind options globally. Call this before trying to talk to bitcoind.
1.556198
1.558105
0.998777
out = np.full(len(coords.l.deg), np.nan, dtype='f4') for pole in self.poles: m = (coords.b.deg >= 0) if pole == 'ngp' else (coords.b.deg < 0) if np.any(m): data, w = self._data[pole] x, y = w.wcs_world2pix(coords.l.deg[m], coords.b.deg[m...
def query(self, coords, order=1)
Returns the map value at the specified location(s) on the sky. Args: coords (`astropy.coordinates.SkyCoord`): The coordinates to query. order (Optional[int]): Interpolation order to use. Defaults to `1`, for linear interpolation. Returns: A float arr...
3.756741
3.699607
1.015443
return super(SFDQuery, self).query(coords, order=order)
def query(self, coords, order=1)
Returns E(B-V) at the specified location(s) on the sky. See Table 6 of Schlafly & Finkbeiner (2011) for instructions on how to convert this quantity to extinction in various passbands. Args: coords (`astropy.coordinates.SkyCoord`): The coordinates to query. order (Option...
10.388865
11.658273
0.891115
return all(date.is_empty() for date in [self.created, self.issued]) \ and not self.publisher
def is_empty(self)
Returns True if all child date elements present are empty and other nodes are not set. Returns False if any child date elements are not empty or other nodes are set.
12.974763
9.119449
1.422757
non_type_attributes = [attr for attr in self.node.attrib.keys() if attr != 'type'] return len(self.node) == 0 and len(non_type_attributes) == 0 \ and not self.node.text and not self.node.tail
def is_empty(self)
Returns True if the root node contains no child elements, no text, and no attributes other than **type**. Returns False if any are present.
3.842368
2.625401
1.463535
'''Returns True if all titleInfo subfields are not set or empty; returns False if any of the fields are not empty.''' return not bool(self.title or self.subtitle or self.part_number \ or self.part_name or self.non_sort or self.type)
def is_empty(self)
Returns True if all titleInfo subfields are not set or empty; returns False if any of the fields are not empty.
10.285825
3.885626
2.647147
'''Returns True if details, extent, and type are not set or return True for ``is_empty``; returns False if any of the fields are not empty.''' return all(field.is_empty() for field in [self.details, self.extent] if field is not None) \ and not self.ty...
def is_empty(self)
Returns True if details, extent, and type are not set or return True for ``is_empty``; returns False if any of the fields are not empty.
11.442148
3.622874
3.158307
batch_data = [] for rpc_call in rpc_calls: AuthServiceProxy.__id_count += 1 m = rpc_call.pop(0) batch_data.append({"jsonrpc":"2.0", "method":m, "params":rpc_call, "id":AuthServiceProxy.__id_count}) postdata = json.dumps(batch_data, default=EncodeDeci...
def batch_(self, rpc_calls)
Batch RPC call. Pass array of arrays: [ [ "method", params... ], ... ] Returns array of results.
3.143976
3.113253
1.009869
try: old_getinfo = AuthServiceProxy(self.__service_url, 'getinfo', self.__timeout, self.__conn, True) res = old_getinfo() if 'error' not in res: # 0.13 and earlier return res except JSONRPCException: pass ...
def getinfo(self)
Backwards-compatibility for 0.14 and later
2.357489
2.185928
1.078484
coords = ['x', 'y', 'z'] eq_sets = self._metadata['eq']['eq_sets'] sym_ops = self._metadata['eq']['sym_ops'] frame = pd.DataFrame(index=[i for v in eq_sets.values() for i in v], columns=['atom', 'x', 'y', 'z'], dtype='f8') frame['atom'] = pd....
def get_cartesian(self)
Return a :class:`~Cartesian` where all members of a symmetry equivalence class are inserted back in. Args: None Returns: Cartesian: A new cartesian instance.
3.289148
3.42324
0.960829
hex_script = '' parts = script.split(' ') for part in parts: if part[0:3] == 'OP_': value = OPCODE_VALUES.get(part) if not value: raise ValueError("Unrecognized opcode {}".format(part)) hex_script += "%0.2x" % value elif hashing.is_...
def btc_script_to_hex(script)
Parse the string representation of a script and return the hex version. Example: "OP_DUP OP_HASH160 c629...a6db OP_EQUALVERIFY OP_CHECKSIG"
3.982929
4.187996
0.951034
if isinstance(script, str) and re.match('^[0-9a-fA-F]*$', script): script = binascii.unhexlify(script) # output buffer out = [] pos = 0 while pos < len(script): # next script op... code = encoding.from_byte_to_int(script[pos]) if code == 0: # empty...
def btc_script_deserialize(script)
Given a script (hex or bin), decode it into its list of opcodes and data. Return a list of strings and ints. Based on code in pybitcointools (https://github.com/vbuterin/pybitcointools) by Vitalik Buterin
3.736021
3.720987
1.00404
if isinstance(unit, int): # cannot be less than -1, since btc_script_deserialize() never returns such numbers if unit < -1: raise ValueError('Invalid integer: {}'.format(unit)) if unit < 16: if unit == 0: # OP_RESERVED return...
def _btc_script_serialize_unit(unit)
Encode one item of a BTC script Return the encoded item (as a string) Based on code from pybitcointools (https://github.com/vbuterin/pybitcointools) by Vitalik Buterin
2.578419
2.564911
1.005266
script = _script if encoding.json_is_base(_script, 16): # hex-to-bin all hex strings in this script script = encoding.json_changebase(_script, lambda x: binascii.unhexlify(x)) # encode each item and return the concatenated list return encoding.safe_hexlify( ''.join(map(_btc_script_...
def btc_script_serialize(_script)
Given a deserialized script (i.e. an array of Nones, ints, and strings), or an existing script, turn it back into a hex script Based on code from pybitcointools (https://github.com/vbuterin/pybitcointools) by Vitalik Buterin
9.119839
11.480696
0.794363
if segwit is None: segwit = get_features('segwit') # is address bech32-encoded? witver, withash = segwit_addr_decode(address) if witver is not None and withash is not None: # bech32 segwit address if not segwit: raise ValueError("Segwit is disabled") ...
def btc_make_payment_script( address, segwit=None, **ignored )
Make a pay-to-address script.
2.361788
2.335602
1.011212
if len(data) >= MAX_DATA_LEN * 2: raise ValueError("Data hex string is too long") # note: data is a hex string if len(data) % 2 != 0: raise ValueError("Data hex string is not even length") return "6a{:02x}{}".format(len(data)/2, data)
def btc_make_data_script( data, **ignored )
Make a data-bearing transaction output. Data must be a hex string Returns a hex string.
4.335107
3.80726
1.138642
# TODO: make this support more than bitcoin-like scripts if script_hex.startswith("76a914") and script_hex.endswith("88ac") and len(script_hex) == 50: # p2pkh script hash160_bin = binascii.unhexlify(script_hex[6:-4]) return bin_hash160_to_address(hash160_bin, version_byte=version_by...
def btc_script_hex_to_address( script_hex, segwit=None )
Examine a script (hex-encoded) and extract an address. Return the address on success Return None on error
1.926892
1.924209
1.001394
h = hashing.bin_hash160(binascii.unhexlify(script_hex)) addr = bin_hash160_to_address(h, version_byte=multisig_version_byte) return addr
def btc_make_p2sh_address( script_hex )
Make a P2SH address from a hex script
4.587461
4.504119
1.018503
pubkey_hex = keylib.key_formatting.compress(pubkey_hex) hash160_bin = hashing.bin_hash160(pubkey_hex.decode('hex')) return segwit_addr_encode(hash160_bin)
def btc_make_p2wpkh_address( pubkey_hex )
Make a p2wpkh address from a hex pubkey
5.230417
4.830927
1.082694
pubkey_hash = hashing.bin_hash160(pubkey_hex.decode('hex')).encode('hex') redeem_script = btc_script_serialize(['0014' + pubkey_hash]) return redeem_script
def btc_make_p2sh_p2wpkh_redeem_script( pubkey_hex )
Make the redeem script for a p2sh-p2wpkh witness script
3.62752
3.542031
1.024136
witness_script_hash = hashing.bin_sha256(witness_script_hex.decode('hex')).encode('hex') redeem_script = btc_script_serialize(['0020' + witness_script_hash]) return redeem_script
def btc_make_p2sh_p2wsh_redeem_script( witness_script_hex )
Make the redeem script for a p2sh-p2wsh witness script
3.730948
3.616734
1.031579
vb = keylib.b58check.b58check_version_byte( address ) if vb == multisig_version_byte: return True else: return False
def btc_is_p2sh_address( address )
Is the given address a p2sh address?
7.284678
7.039723
1.034796
vb = keylib.b58check.b58check_version_byte( address ) if vb == version_byte: return True else: return False
def btc_is_p2pkh_address( address )
Is the given address a p2pkh address?
7.294965
6.963231
1.047641
wver, whash = segwit_addr_decode(address) if whash is None: return False if len(whash) != 20: return False return True
def btc_is_p2wpkh_address( address )
Is the given address a p2wpkh address?
5.527438
5.194443
1.064106
wver, whash = segwit_addr_decode(address) if whash is None: return False if len(whash) != 32: return False return True
def btc_is_p2wsh_address( address )
Is the given address a p2wsh address?
6.064785
5.646234
1.074129
if script_hex.startswith("a914") and script_hex.endswith("87") and len(script_hex) == 46: return True else: return False
def btc_is_p2sh_script( script_hex )
Is the given scriptpubkey a p2sh script?
2.515039
2.342315
1.073741
# re-encode bitcoin address network = blockchain_opts.get('network', None) opt_version_byte = blockchain_opts.get('version_byte', None) if btc_is_segwit_address(address): # bech32 address hrp = None if network == 'mainnet': hrp = 'bc' elif network == 't...
def btc_address_reencode( address, **blockchain_opts )
Depending on whether or not we're in testnet or mainnet, re-encode an address accordingly.
2.072119
2.070855
1.000611
try: jsonschema.validate(privkey_info, PRIVKEY_MULTISIG_SCHEMA) return not privkey_info.get('segwit', False) except ValidationError as e: return False
def btc_is_multisig(privkey_info, **blockchain_opts)
Does the given private key info represent a multisig bundle? For Bitcoin, this is true for multisig p2sh (not p2sh-p2wsh)
4.873684
4.887942
0.997083
try: jsonschema.validate(privkey_info, PRIVKEY_MULTISIG_SCHEMA) if len(privkey_info['private_keys']) == 1: return False return privkey_info.get('segwit', False) except ValidationError as e: return False
def btc_is_multisig_segwit(privkey_info)
Does the given private key info represent a multisig bundle? For Bitcoin, this is true for multisig p2sh (not p2sh-p2wsh)
3.901628
4.040067
0.965734
try: jsonschema.validate(privkey_info, PRIVKEY_SINGLESIG_SCHEMA) return True except ValidationError as e: return False
def btc_is_singlesig(privkey_info, **blockchain_opts)
Does the given private key info represent a single signature bundle? (i.e. one private key)? i.e. is this key a private key string?
4.781761
4.619706
1.035079
try: jsonschema.validate(privkey_info, PRIVKEY_MULTISIG_SCHEMA) if len(privkey_info['private_keys']) > 1: return False return privkey_info.get('segwit', False) except ValidationError: return False
def btc_is_singlesig_segwit(privkey_info)
Is the given key bundle a p2sh-p2wpkh key bundle?
4.148726
3.72971
1.112346
from .multisig import make_multisig_segwit_address_from_witness_script if btc_is_singlesig(privkey_info): return btc_address_reencode( ecdsalib.ecdsa_private_key(privkey_info).public_key().address() ) if btc_is_multisig(privkey_info) or btc_is_singlesig_segwit(privkey_info): ...
def btc_get_privkey_address(privkey_info, **blockchain_opts)
Get the address for a given private key info bundle (be it multisig or singlesig) Return the address on success Raise exception on error
3.428348
3.366453
1.018386
hrpgot, data = bech32_decode(addr) if hrpgot != hrp: return (None, None) decoded = convertbits(data[1:], 5, 8, False) if decoded is None or len(decoded) < 2 or len(decoded) > 40: return (None, None) if data[0] > 16: return (None, None) if data[0] == 0 and len(decoded...
def segwit_addr_decode(addr, hrp=bech32_prefix)
Decode a segwit address. Returns (version, hash_bin) on success Returns (None, None) on error
2.183099
2.298385
0.94984
witprog_bytes = [ord(c) for c in witprog_bin] ret = bech32_encode(hrp, [int(witver)] + convertbits(witprog_bytes, 8, 5)) assert segwit_addr_decode(hrp, ret) is not (None, None) return ret
def segwit_addr_encode(witprog_bin, hrp=bech32_prefix, witver=bech32_witver)
Encode a segwit script hash to a bech32 address. Returns the bech32-encoded string on success
3.610161
4.360998
0.827829
''' Perform the pure-Python equivalent of in-place `sed` substitution: e.g., `sed -i -e 's/'${pattern}'/'${repl}' "${filename}"`. ''' # For efficiency, precompile the passed regular expression. pattern_compiled = re.compile(pattern) # For portability, NamedTemporaryFile() defaults to mode "...
def sed_inplace(filename, pattern, repl)
Perform the pure-Python equivalent of in-place `sed` substitution: e.g., `sed -i -e 's/'${pattern}'/'${repl}' "${filename}"`.
4.761862
3.791355
1.255979
if git_str is None: return None if "-" not in git_str: # currently at a tag return git_str else: # formatted as version-N-githash # want to convert to version.postN-githash git_str = git_str.replace("-", ".post", 1) if pep440: # does not allow git hash ...
def format_git_describe(git_str, pep440=False)
format the result of calling 'git describe' as a python version
5.279602
5.17713
1.019793
try: with open(VERSION_FILE, "r") as infile: version = str(infile.read().strip()) if len(version) == 0: version = None return version except IOError: return None
def read_release_version()
Read version information from VERSION file
2.924225
2.796242
1.045769
version = get_version(pep440=True) with open(VERSION_FILE, "w") as outfile: outfile.write(version) outfile.write("\n")
def update_release_version()
Update VERSION file
3.267109
3.067858
1.064948
git_version = format_git_describe(call_git_describe(), pep440=pep440) if git_version is None: # not a git repository return read_release_version() return git_version
def get_version(pep440=False)
Tracks the version number. pep440: bool When True, this function returns a version string suitable for a release as defined by PEP 440. When False, the githash (if available) will be appended to the version string. The file VERSION holds the version information. If this is not a git ...
5.432327
5.434866
0.999533
try: with open(devnull, "w") as fnull: arguments = [GIT_COMMAND, 'rev-parse', '--abbrev-ref', 'HEAD'] return check_output(arguments, cwd=CURRENT_DIRECTORY, stderr=fnull).decode("ascii").strip() except (OSError, CalledProcessError): ret...
def call_git_branch()
return the string output of git desribe
3.203961
3.339289
0.959474
try: with open(CC_INIT, "r") as f: found = False while not found: line = f.readline().strip().split() try: found = True if line[0] == '_git_branch' else False except IndexError: pass ...
def read_git_branch()
Read version information from VERSION file
3.346146
3.354473
0.997518
return etree.parse(stream, parser=_get_xmlparser(), base_url=uri)
def parseUri(stream, uri=None)
Read an XML document from a URI, and return a :mod:`lxml.etree` document.
7.722099
8.96704
0.861165
return etree.fromstring(string, parser=_get_xmlparser(), base_url=uri)
def parseString(string, uri=None)
Read an XML document provided as a byte string, and return a :mod:`lxml.etree` document. String cannot be a Unicode string. Base_uri should be provided for the calculation of relative URIs.
5.432651
7.77733
0.698524
# uri to use for reporting errors - include base uri if any if uri in _loaded_schemas: return _loaded_schemas[uri] error_uri = uri if base_uri is not None: error_uri += ' (base URI %s)' % base_uri try: logger.debug('Loading schema %s' % uri) _loaded_schemas[u...
def loadSchema(uri, base_uri=None)
Load an XSD XML document (specified by filename or URL), and return a :class:`lxml.etree.XMLSchema`.
3.852079
3.961683
0.972334
'''Load and compile an XSLT document (specified by filename or string) for repeated use in transforming XML. ''' parser = _get_xmlparser() if filename is not None: xslt_doc = etree.parse(filename, parser=parser) if xsl is not None: xslt_doc = etree.fromstring(xsl, parser=parser) ...
def load_xslt(filename=None, xsl=None)
Load and compile an XSLT document (specified by filename or string) for repeated use in transforming XML.
3.613484
2.430346
1.486819
if validate: if hasattr(xmlclass, 'XSD_SCHEMA') and xmlclass.XSD_SCHEMA is not None: # If the schema has already been loaded, use that. # (since we accessing the *class*, accessing 'xmlschema' returns a property, # not the initialized schema object we actually want)....
def _get_xmlparser(xmlclass=XmlObject, validate=False, resolver=None)
Initialize an instance of :class:`lxml.etree.XMLParser` with appropriate settings for validation. If validation is requested and the specified instance of :class:`XmlObject` has an XSD_SCHEMA defined, that will be used. Otherwise, uses DTD validation. Switched resolver to None to skip validation.
5.837478
5.399409
1.081133
parser = _get_xmlparser(xmlclass=xmlclass, validate=validate, resolver=resolver) element = etree.fromstring(string, parser) return xmlclass(element)
def load_xmlobject_from_string(string, xmlclass=XmlObject, validate=False, resolver=None)
Initialize an XmlObject from a string. If an xmlclass is specified, construct an instance of that class instead of :class:`~eulxml.xmlmap.XmlObject`. It should be a subclass of XmlObject. The constructor will be passed a single node. If validation is requested and the specified subclass of :class:`Xml...
3.077508
4.53406
0.678753
parser = _get_xmlparser(xmlclass=xmlclass, validate=validate, resolver=resolver) tree = etree.parse(filename, parser) return xmlclass(tree.getroot())
def load_xmlobject_from_file(filename, xmlclass=XmlObject, validate=False, resolver=None)
Initialize an XmlObject from a file. See :meth:`load_xmlobject_from_string` for more details; behaves exactly the same, and accepts the same parameters, except that it takes a filename instead of a string. :param filename: name of the file that should be loaded as an xmlobject. :meth:`etree.lx...
3.003606
5.324055
0.564158
out = self._sympy_formatter() out = out._abs_ref_formatter(format_as=format_abs_ref_as) if not upper_triangle: out = out._remove_upper_triangle() content = out._frame.to_string(buf=buf, header=header, index=index, **kwargs) ...
def to_string(self, buf=None, format_abs_ref_as='string', upper_triangle=True, header=True, index=True, **kwargs)
Render a DataFrame to a console-friendly tabular output. Wrapper around the :meth:`pandas.DataFrame.to_string` method.
5.449946
5.785387
0.942019
out = self._sympy_formatter() out = out._abs_ref_formatter(format_as='latex') if not upper_triangle: out = out._remove_upper_triangle() return out._frame.to_latex(buf=buf, **kwargs)
def to_latex(self, buf=None, upper_triangle=True, **kwargs)
Render a DataFrame to a tabular environment table. You can splice this into a LaTeX document. Requires ``\\usepackage{booktabs}``. Wrapper around the :meth:`pandas.DataFrame.to_latex` method.
7.083225
7.120921
0.994706
cols = ['atom', 'b', 'bond', 'a', 'angle', 'd', 'dihedral'] if implicit_index: zmat_frame = pd.read_table(inputfile, comment='#', delim_whitespace=True, names=cols) zmat_frame.index = range(1, ...
def read_zmat(cls, inputfile, implicit_index=True)
Reads a zmat file. Lines beginning with ``#`` are ignored. Args: inputfile (str): implicit_index (bool): If this option is true the first column has to be the element symbols for the atoms. The row number is used to determine the index. Retu...
2.967395
3.088871
0.960673
out = self.copy() if implicit_index: out = out.change_numbering(new_index=range(1, len(self) + 1)) if not upper_triangle: out = out._remove_upper_triangle() output = out.to_string(index=(not implicit_index), float_format=fl...
def to_zmat(self, buf=None, upper_triangle=True, implicit_index=True, float_format='{:.6f}'.format, overwrite=True, header=False)
Write zmat-file Args: buf (str): StringIO-like, optional buffer to write to implicit_index (bool): If implicit_index is set, the zmat indexing is changed to ``range(1, len(self) + 1)``. Using :meth:`~chemcoord.Zmat.change_numbering` Beside...
2.566406
2.729831
0.940134
message = 'Will be removed in the future. Please use to_zmat().' with warnings.catch_warnings(): warnings.simplefilter("always") warnings.warn(message, DeprecationWarning) return self.to_zmat(*args, **kwargs)
def write(self, *args, **kwargs)
Deprecated, use :meth:`~chemcoord.Zmat.to_zmat`
4.142287
2.839043
1.459043
return self._frame.to_latex( buf=buf, columns=columns, col_space=col_space, header=header, index=index, na_rep=na_rep, formatters=formatters, float_format=float_format, sparsify=sparsify, index_names=index_names, bold_rows=bold_rows, column_fo...
def to_latex(self, buf=None, columns=None, col_space=None, header=True, index=True, na_rep='NaN', formatters=None, float_format=None, sparsify=None, index_names=True, bold_rows=True, column_format=None, longtable=None, escape=None, encoding=None, decim...
Render a DataFrame to a tabular environment table. You can splice this into a LaTeX document. Requires ``\\usepackage{booktabs}``. Wrapper around the :meth:`pandas.DataFrame.to_latex` method.
1.249839
1.353482
0.923425
if sort_index: molecule_string = self.sort_index().to_string( header=header, index=index, float_format=float_format) else: molecule_string = self.to_string(header=header, index=index, float_format=float_format)...
def to_xyz(self, buf=None, sort_index=True, index=False, header=False, float_format='{:.6f}'.format, overwrite=True)
Write xyz-file Args: buf (str): StringIO-like, optional buffer to write to sort_index (bool): If sort_index is true, the :class:`~chemcoord.Cartesian` is sorted by the index before writing. float_format (one-parameter function): Formatter func...
3.480811
3.57987
0.972329
message = 'Will be removed in the future. Please use to_xyz().' with warnings.catch_warnings(): warnings.simplefilter("always") warnings.warn(message, DeprecationWarning) return self.to_xyz(*args, **kwargs)
def write_xyz(self, *args, **kwargs)
Deprecated, use :meth:`~chemcoord.Cartesian.to_xyz`
3.424155
2.929996
1.168655
frame = pd.read_table(buf, skiprows=2, comment='#', nrows=nrows, delim_whitespace=True, names=['atom', 'x', 'y', 'z'], engine=engine) remove_digits = partial(re.sub, r'[0-9]+', '') frame['atom'] =...
def read_xyz(cls, buf, start_index=0, get_bonds=True, nrows=None, engine=None)
Read a file of coordinate information. Reads xyz-files. Args: inputfile (str): start_index (int): get_bonds (bool): nrows (int): Number of rows of file to read. Note that the first two rows are implicitly excluded. engine (str...
3.014905
3.723242
0.809753
cjson_dict = {'chemical json': 0} cjson_dict['atoms'] = {} atomic_number = constants.elements['atomic_number'].to_dict() cjson_dict['atoms'] = {'elements': {}} cjson_dict['atoms']['elements']['number'] = [ int(atomic_number[x]) for x in self['atom']] ...
def to_cjson(self, buf=None, **kwargs)
Write a cjson file or return dictionary. The cjson format is specified `here <https://github.com/OpenChemistry/chemicaljson>`_. Args: buf (str): If it is a filepath, the data is written to filepath. If it is None, a dictionary with the cjson informat...
2.918535
3.044219
0.958714
if isinstance(buf, dict): data = buf.copy() else: with open(buf, 'r') as f: data = json.load(f) assert data['chemical json'] == 0 n_atoms = len(data['atoms']['coords']['3d']) metadata = {} _metadata = {} coord...
def read_cjson(cls, buf)
Read a cjson file or a dictionary. The cjson format is specified `here <https://github.com/OpenChemistry/chemicaljson>`_. Args: buf (str, dict): If it is a filepath, the data is read from filepath. If it is a dictionary, the dictionary is interpreted ...
3.304619
3.218893
1.026632
if viewer is None: viewer = settings['defaults']['viewer'] if use_curr_dir: TEMP_DIR = os.path.curdir else: TEMP_DIR = tempfile.gettempdir() def give_filename(i): filename = 'ChemCoord_' + str(i) + '.xyz' return os.pat...
def view(self, viewer=None, use_curr_dir=False)
View your molecule. .. note:: This function writes a temporary file and opens it with an external viewer. If you modify your molecule afterwards you have to recall view in order to see the changes. Args: viewer (str): The external viewer to use. If it is...
2.870138
2.415126
1.188401
from pymatgen import Molecule return Molecule(self['atom'].values, self.loc[:, ['x', 'y', 'z']].values)
def get_pymatgen_molecule(self)
Create a Molecule instance of the pymatgen library .. warning:: The `pymatgen library <http://pymatgen.org>`_ is imported locally in this function and will raise an ``ImportError`` exception, if it is not installed. Args: None Returns: :class:`p...
7.295071
9.911495
0.736021
new = cls(atoms=[el.value for el in molecule.species], coords=molecule.cart_coords) return new._to_numeric()
def from_pymatgen_molecule(cls, molecule)
Create an instance of the own class from a pymatgen molecule Args: molecule (:class:`pymatgen.core.structure.Molecule`): Returns: Cartesian:
10.954415
13.829555
0.792102
return cls(atoms=atoms.get_chemical_symbols(), coords=atoms.positions)
def from_ase_atoms(cls, atoms)
Create an instance of the own class from an ase molecule Args: molecule (:class:`ase.atoms.Atoms`): Returns: Cartesian:
5.131631
9.793657
0.523975
rename = dict(enumerate(self.index)) eq['eq_sets'] = {rename[k]: {rename[x] for x in v} for k, v in eq['eq_sets'].items()} eq['sym_ops'] = {rename[k]: {rename[x]: v[x] for x in v} for k, v in eq['sym_ops'].items()} try: ...
def _convert_eq(self, eq)
WORKS INPLACE on eq
3.69183
3.483896
1.059684
PA = self._get_point_group_analyzer(tolerance=tolerance) return PointGroupOperations(PA.sch_symbol, PA.symmops)
def get_pointgroup(self, tolerance=0.3)
Returns a PointGroup object for the molecule. Args: tolerance (float): Tolerance to generate the full set of symmetry operations. Returns: :class:`~PointGroupOperations`
11.175605
8.609472
1.298059
PA = self._get_point_group_analyzer(tolerance=tolerance) eq = PA.get_equivalent_atoms() self._convert_eq(eq) return eq
def get_equivalent_atoms(self, tolerance=0.3)
Returns sets of equivalent atoms with symmetry operations Args: tolerance (float): Tolerance to generate the full set of symmetry operations. Returns: dict: The returned dictionary has two possible keys: ``eq_sets``: A dictionary of indi...
6.933464
8.869992
0.781676
mg_mol = self.get_pymatgen_molecule() eq = iterative_symmetrize(mg_mol, max_n=max_n, tolerance=tolerance, epsilon=epsilon) self._convert_eq(eq) return eq
def symmetrize(self, max_n=10, tolerance=0.3, epsilon=1e-3)
Returns a symmetrized molecule The equivalent atoms obtained via :meth:`~Cartesian.get_equivalent_atoms` are rotated, mirrored... unto one position. Then the average position is calculated. The average position is rotated, mirrored... back with the inverse of the previou...
5.329105
6.761375
0.788169
_obj = {"ins": [], "outs": [], 'locktime': None} # number of inputs ins = read_var_int(ptr, tx) # all inputs for i in range(ins): _obj["ins"].append({ "outpoint": { "hash": read_bytes(ptr, tx, 32)[::-1], "index": read_as_int(ptr, tx, 4) ...
def read_tx_body(ptr, tx)
Returns {'ins': [...], 'outs': [...]}
1.951345
1.857502
1.050521
witnesses = [] for i in xrange(0, num_witnesses): witness_stack_len = read_var_int(ptr, tx) witness_stack = [] for j in xrange(0, witness_stack_len): stack_item = read_var_string(ptr, tx) witness_stack.append(stack_item) witness_scrip...
def read_tx_witnesses(ptr, tx, num_witnesses)
Returns an array of witness scripts. Each witness will be a bytestring (i.e. encoding the witness script)
2.585252
2.468283
1.047389
s = None if isinstance(string, str) and re.match('^[0-9a-fA-F]*$', string): # convert from hex to bin, safely s = binascii.unhexlify(string) else: s = string[:] buf = encoding.num_to_var_int(len(s)) + s return buf.encode('hex')
def make_var_string(string)
Make a var-string (a var-int with the length, concatenated with the data) Return the hex-encoded string
4.75374
4.260287
1.115826
if isinstance(unit, int): # pass literal return encoding.from_int_to_byte(unit) elif unit is None: # None means OP_0 return b'\x00' else: # return as a varint-prefixed string return make_var_string(unit)
def _btc_witness_serialize_unit(unit)
Encode one item of a BTC witness script Return the encoded item (as a string) Returns a byte string with the encoded unit Based on code from pybitcointools (https://github.com/vbuterin/pybitcointools) by Vitalik Buterin
7.984582
6.970688
1.145451
stack = _stack if encoding.json_is_base(_stack, 16): # hex-to-bin all hex strings stack = encoding.json_changebase(_stack, lambda x: binascii.unhexlify(x)) return encoding.safe_hexlify(_btc_witness_serialize_unit(len(stack)) + ''.join(map(lambda stack_unit: _btc_witness_serialize_unit...
def btc_witness_script_serialize(_stack)
Given a deserialized witness script stack (i.e. the input-specific witness, as an array of Nones, ints, and strings), turn it back into a hex-encoded script
7.844136
8.059385
0.973292
script = None if isinstance(_script, str) and re.match('^[0-9a-fA-F]*$', _script): # convert from hex to bin, safely script = binascii.unhexlify(_script) else: script = _script[:] # pointer to byte offset in _script (as an array due to Python scoping rules) ptr = [0] ...
def btc_witness_script_deserialize(_script)
Given a hex-encoded serialized witness script, turn it into a witness stack (i.e. an array of Nones, ints, and strings)
3.911949
3.744693
1.044665
tx = None if isinstance(_tx, str) and re.match('^[0-9a-fA-F]*$', _tx): # convert from hex to bin, safely tx = binascii.unhexlify(_tx) else: tx = _tx[:] # pointer to byte offset in _tx (as an array due to Python scoping rules) ptr = [0] # top-level tx obj =...
def btc_tx_deserialize(_tx, **blockchain_opts)
Given a hex-encoded transaction, decode it into an object with the following structure: { ins: [ { outpoint: { hash: ..., index: ... }, script: ..., sequence: ..., witness_script: ..., # not included if not segwit ...
3.565996
3.409831
1.045799
# output buffer o = [] txobj = None if encoding.json_is_base(_txobj, 16): # txobj is built from hex strings already. deserialize them txobj = encoding.json_changebase(_txobj, lambda x: binascii.unhexlify(x)) else: txobj = copy.deepcopy(_txobj) # version o...
def btc_tx_serialize(_txobj)
Given a transaction dict returned by btc_tx_deserialize, convert it back into a hex-encoded byte string. Derived from code written by Vitalik Buterin in pybitcointools (https://github.com/vbuterin/pybitcointools)
2.542387
2.583506
0.984084