code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
tx_ins = []
tx_outs = []
try:
for inp in tx['vin']:
next_inp = {
"outpoint": {
"index": int(inp['vout']),
"hash": str(inp['txid'])
}
}
if 'sequence' in inp:
next_i... | def btc_bitcoind_tx_serialize( tx ) | Convert a *Bitcoind*-given transaction into its hex string.
tx format is {'vin': [...], 'vout': [...], 'locktime': ..., 'version': ...},
with the same formatting rules as getrawtransaction.
(in particular, each value in vout is a Decimal, in BTC) | 2.416137 | 2.392386 | 1.009927 |
marker_offset = 4 # 5th byte is the marker byte
flag_offset = 5 # 6th byte is the flag byte
marker_byte_string = tx_serialized[2*marker_offset:2*(marker_offset+1)]
flag_byte_string = tx_serialized[2*flag_offset:2*(flag_offset+1)]
if marker_byte_string == '00' and flag_byte_s... | def btc_tx_is_segwit( tx_serialized ) | Is this serialized (hex-encoded) transaction a segwit transaction? | 3.096483 | 2.985341 | 1.037229 |
if not btc_tx_is_segwit(tx_serialized):
# already strippped
return tx_serialized
tx = btc_tx_deserialize(tx_serialized)
for inp in tx['ins']:
del inp['witness_script']
tx_stripped = btc_tx_serialize(tx)
return tx_stripped | def btc_tx_witness_strip( tx_serialized ) | Strip the witness information from a serialized transaction | 3.60692 | 3.853551 | 0.935999 |
if btc_tx_is_segwit(tx_serialized):
raise ValueError('Segwit transaction: {}'.format(tx_serialized))
tx_bin = binascii.unhexlify(tx_serialized)
if hashcode:
return binascii.hexlify( hashing.bin_double_sha256(tx_bin + encoding.encode(int(hashcode), 256, 4)[::-1]) )
else:
re... | def btc_tx_get_hash( tx_serialized, hashcode=None ) | Make a transaction hash (txid) from a hex tx, optionally along with a sighash.
This DOES NOT WORK for segwit transactions | 3.206351 | 3.054163 | 1.04983 |
if len(script_hex) == 0:
return ""
try:
script_array = btc_script_deserialize(script_hex)
except:
log.error("Failed to convert '%s' to assembler" % script_hex)
raise
script_tokens = []
for token in script_array:
if token is None:
token = 0
... | def btc_tx_script_to_asm( script_hex ) | Decode a script into assembler | 2.778954 | 2.732393 | 1.01704 |
# recover tx
tx = btc_tx_deserialize(partial_tx_hex)
tx_inputs, tx_outputs = tx['ins'], tx['outs']
locktime, version = tx['locktime'], tx['version']
tx_inputs += new_inputs
tx_outputs += new_outputs
new_tx = {
'ins': tx_inputs,
'outs': tx_outputs,
'locktime': ... | def btc_tx_extend(partial_tx_hex, new_inputs, new_outputs, **blockchain_opts) | Given an unsigned serialized transaction, add more inputs and outputs to it.
@new_inputs and @new_outputs will be virtualchain-formatted:
* new_inputs[i] will have {'outpoint': {'index':..., 'hash':...}, 'script':..., 'witness_script': ...}
* new_outputs[i] will have {'script':..., 'value':... (in fundament... | 2.279691 | 2.414477 | 0.944176 |
if l < 0:
raise ValueError("length cannot be negative")
if l < 0x80:
return int2byte(l)
s = ("%x" % l).encode()
if len(s) % 2:
s = b("0") + s
s = binascii.unhexlify(s)
llen = len(s)
return int2byte(0x80 | llen) + s | def btc_tx_der_encode_length(l) | Return a DER-encoded length field
Based on code from python-ecdsa (https://github.com/warner/python-ecdsa)
by Brian Warner. Subject to the MIT license. | 2.662425 | 2.724973 | 0.977046 |
# borrowed from python-ecdsa
total_len = sum([len(p) for p in encoded_pieces])
return b('\x30') + btc_tx_der_encode_length(total_len) + b('').join(encoded_pieces) | def btc_tx_der_encode_sequence(*encoded_pieces) | Return a DER-encoded sequence
Based on code from python-ecdsa (https://github.com/warner/python-ecdsa)
by Brian Warner. Subject to the MIT license. | 4.585433 | 4.166623 | 1.100516 |
txobj = btc_tx_deserialize(tx)
idx = int(idx)
hashcode = int(hashcode)
newtx = copy.deepcopy(txobj)
# remove all scriptsigs in all inputs, except for the ith input's scriptsig.
# the other inputs will be 'partially signed', except for SIGHASH_ANYONECANPAY mode.
for i in xrange(0, len... | def btc_tx_sighash( tx, idx, script, hashcode=SIGHASH_ALL) | Calculate the sighash of a non-segwit transaction.
If it's SIGHASH_NONE, then digest the inputs but no outputs
If it's SIGHASH_SINGLE, then digest all inputs and all outputs up to i (excluding values and scripts), and fully digest the ith input and output
If it's (something) | SIGHASH_ANYONECANPAY, then o... | 3.198267 | 3.074944 | 1.040106 |
if btc_tx_is_segwit(tx):
raise ValueError('tried to use the standard sighash to sign a segwit transaction')
pk = ecdsalib.ecdsa_private_key(str(privkey_str))
priv = pk.to_hex()
# get the parts of the tx we actually need to sign
sighash = btc_tx_sighash(tx, idx, prevout_script, hashcod... | def btc_tx_make_input_signature(tx, idx, prevout_script, privkey_str, hashcode) | Sign a single input of a transaction, given the serialized tx,
the input index, the output's scriptPubkey, and the hashcode.
tx must be a hex-encoded string
privkey_str must be a hex-encoded private key
Return the hex signature.
THIS DOES NOT WORK WITH SEGWIT TRANSACTIONS | 4.17791 | 4.261008 | 0.980498 |
# always compressed
if len(privkey_str) == 64:
privkey_str += '01'
pk = ecdsalib.ecdsa_private_key(str(privkey_str))
pubk = pk.public_key()
priv = pk.to_hex()
# must always be compressed
pub = keylib.key_formatting.compress(pubk.to_hex())
sighash = btc_tx_sighash_segw... | def btc_tx_make_input_signature_segwit(tx, idx, prevout_amount, prevout_script, privkey_str, hashcode) | Sign a single input of a transaction, given the serialized tx,
the input index, the output's scriptPubkey, and the hashcode.
tx must be a hex-encoded string
privkey_str must be a hex-encoded private key
Return the hex signature. | 4.241137 | 4.353878 | 0.974106 |
from .multisig import parse_multisig_redeemscript
# sign in the right order. map all possible public keys to their private key
txobj = btc_tx_deserialize(str(tx))
privs = {}
for pk in private_keys:
pubk = ecdsalib.ecdsa_private_key(pk).public_key().to_hex()
compressed_p... | def btc_tx_sign_multisig(tx, idx, redeem_script, private_keys, hashcode=SIGHASH_ALL) | Sign a p2sh multisig input (not segwit!).
@tx must be a hex-encoded tx
Return the signed transaction | 3.421798 | 3.48355 | 0.982273 |
from .multisig import parse_multisig_redeemscript
if hashcodes is None:
hashcodes = [hashcode] * len(private_keys)
txobj = btc_tx_deserialize(str(tx))
privs = {}
for pk in private_keys:
pubk = ecdsalib.ecdsa_private_key(pk).public_key().to_hex()
compressed_pubkey = k... | def btc_tx_sign_multisig_segwit(tx, idx, prevout_amount, witness_script, private_keys, hashcode=SIGHASH_ALL, hashcodes=None, native=False) | Sign a native p2wsh or p2sh-p2wsh multisig input.
@tx must be a hex-encoded tx
Return the signed transaction | 2.661544 | 2.647489 | 1.005309 |
if scriptpubkey.startswith("76a914") and scriptpubkey.endswith("88ac") and len(scriptpubkey) == 50:
return 'p2pkh'
elif scriptpubkey.startswith("a914") and scriptpubkey.endswith("87") and len(scriptpubkey) == 46:
# maybe p2sh-p2wpkh or p2sh-p2wsh?
if private_key_info:
i... | def btc_script_classify(scriptpubkey, private_key_info=None) | Classify a scriptpubkey, optionally also using the private key info that will generate the corresponding scriptsig/witness
Return None if not known (nonstandard) | 2.030893 | 2.029338 | 1.000766 |
if btc_is_singlesig(private_key_info):
return 'p2pkh'
if btc_is_multisig(private_key_info):
return 'p2sh'
if btc_is_singlesig_segwit(private_key_info):
return 'p2sh-p2wpkh'
if btc_is_multisig_segwit(private_key_info):
return 'p2sh-p2wsh'
return None | def btc_privkey_scriptsig_classify(private_key_info) | What kind of scriptsig can this private key make? | 1.921143 | 1.832637 | 1.048294 |
if segwit is None:
segwit = get_features('segwit')
if scriptsig_type is None:
scriptsig_type = btc_privkey_scriptsig_classify(private_key_info)
if scriptsig_type in ['p2wpkh', 'p2wsh', 'p2sh-p2wpkh', 'p2sh-p2wsh'] and not segwit:
raise ValueError("Segwit is not enabled... | def btc_tx_sign_input(tx, idx, prevout_script, prevout_amount, private_key_info, hashcode=SIGHASH_ALL, hashcodes=None, segwit=None, scriptsig_type=None, redeem_script=None, witness_script=None, **blockchain_opts) | Sign a particular input in the given transaction.
@private_key_info can either be a private key, or it can be a dict with 'redeem_script' and 'private_keys' defined
Returns the tx with the signed input | 2.332717 | 2.414944 | 0.965951 |
if segwit is None:
segwit = get_features('segwit')
txobj = btc_tx_deserialize(unsigned_tx_hex)
inputs = txobj['ins']
if scriptsig_type is None:
scriptsig_type = btc_privkey_scriptsig_classify(private_key_info)
tx_hex = unsigned_tx_hex
prevout_index = 0
# ... | def btc_tx_sign_all_unsigned_inputs(private_key_info, prev_outputs, unsigned_tx_hex, scriptsig_type=None, segwit=None, **blockchain_opts) | Sign all unsigned inputs with a given key.
Use the given outputs to fund them.
@private_key_info: either a hex private key, or a dict with 'private_keys' and 'redeem_script'
defined as keys.
@prev_outputs: a list of {'out_script': xxx, 'value': xxx} that are in 1-to-1 correspondence with the unsigned i... | 2.928675 | 2.958953 | 0.989767 |
# concatenate to form header
o = encoding.encode(inp['version'], 256, 4)[::-1] + \
inp['prevhash'].decode('hex')[::-1] + \
inp['merkle_root'].decode('hex')[::-1] + \
encoding.encode(inp['timestamp'], 256, 4)[::-1] + \
encoding.encode(inp['bits'], 256, 4)[::-1] + \
... | def block_header_serialize( inp ) | Given block header information, serialize it and return the hex hash.
inp has:
* version (int)
* prevhash (str)
* merkle_root (str)
* timestamp (int)
* bits (int)
* nonce (int)
Based on code from pybitcointools (https://github.com/vbuterin/pybitcointools)
by Vitalik Buterin | 2.759671 | 2.586297 | 1.067036 |
header_info = {
"version": block_data['version'],
"prevhash": prev_hash,
"merkle_root": block_data['merkleroot'],
"timestamp": block_data['time'],
"bits": int(block_data['bits'], 16),
"nonce": block_data['nonce'],
"hash": block_data['hash']
}
return blo... | def block_header_to_hex( block_data, prev_hash ) | Calculate the hex form of a block's header, given its getblock information from bitcoind. | 2.102803 | 1.968142 | 1.06842 |
serialized_header = block_header_to_hex( block_data, prev_hash )
candidate_hash_bin_reversed = hashing.bin_double_sha256(binascii.unhexlify(serialized_header))
candidate_hash = binascii.hexlify( candidate_hash_bin_reversed[::-1] )
return block_hash == candidate_hash | def block_header_verify( block_data, prev_hash, block_hash ) | Verify whether or not bitcoind's block header matches the hash we expect. | 3.817013 | 3.768425 | 1.012893 |
# verify block data txs
m = merkle.MerkleTree( block_data['tx'] )
root_hash = str(m.root())
return root_hash == str(block_data['merkleroot']) | def block_verify( block_data ) | Given block data (a dict with 'merkleroot' hex string and 'tx' list of hex strings--i.e.
a block compatible with bitcoind's getblock JSON RPC method), verify that the
transactions are consistent.
Return True on success
Return False if not. | 6.633232 | 5.499815 | 1.206083 |
script_type = None
reqSigs = None
addresses = []
script_type = btc_script_classify(scriptpubkey)
script_tokens = btc_script_deserialize(scriptpubkey)
if script_type in ['p2pkh']:
script_type = "pubkeyhash"
reqSigs = 1
addr = btc_script_hex_to_address(script... | def btc_tx_output_parse_script( scriptpubkey ) | Given the hex representation of a script,
turn it into a nice, easy-to-read dict.
The dict will have:
* asm: the disassembled script as a string
* hex: the raw hex (given as an argument)
* type: the type of script
Optionally, it will have:
* addresses: a list of addresses the script represe... | 2.256255 | 2.127123 | 1.060707 |
if M_c['column_metadata'][cidx]['modeltype'] == 'normal_inverse_gamma':
return float(code)
else:
try:
return M_c['column_metadata'][cidx]['value_to_code'][int(code)]
except KeyError:
return M_c['column_metadata'][cidx]['value_to_code'][str(int(code))] | def convert_code_to_value(M_c, cidx, code) | For a column with categorical data, this function takes the 'code':
the integer used to represent a specific value, and returns the corresponding
raw value (e.g. 'Joe' or 234.23409), which is always encoded as a string.
Note that the underlying store 'value_to_code' is unfortunately named backwards.
TO... | 3.453294 | 3.257224 | 1.060196 |
if M_c['column_metadata'][cidx]['modeltype'] == 'normal_inverse_gamma':
return float(value)
else:
return M_c['column_metadata'][cidx]['code_to_value'][str(value)] | def convert_value_to_code(M_c, cidx, value) | For a column with categorical data, this function takes the raw value
(e.g. 'Joe' or 234.23409), which is always encoded as a string, and returns the
'code': the integer used to represent that value in the underlying representation.
Note that the underlying store 'code_to_value' is unfortunately named back... | 5.903971 | 4.461632 | 1.323276 |
if (not self._success) and (not force):
raise ConfigError((
'The config file appears to be corrupted:\n\n'
' {fname}\n\n'
'Before attempting to save the configuration, please either '
'fix the config file manually, or overwr... | def save(self, force=False) | Saves the configuration to a JSON, in the standard config location.
Args:
force (Optional[:obj:`bool`]): Continue writing, even if the original
config file was not loaded properly. This is dangerous, because
it could cause the previous configuration options to be los... | 4.043251 | 3.77958 | 1.069762 |
self._options = {}
self.save(force=True)
self._success = True | def reset(self) | Resets the configuration, and overwrites the existing configuration
file. | 14.249048 | 11.418364 | 1.247906 |
"Returns system information as a dict"
blob = []
# commit = cc._git_hash
# blob.append(('commit', commit))
try:
(sysname, nodename, release, version,
machine, processor) = platform.uname()
blob.extend([
("python", "%d.%d.%d.%s.%s" % sys.version_info[:]),
... | def get_sys_info() | Returns system information as a dict | 2.883839 | 2.888322 | 0.998448 |
if not self.finished:
raise Exception("Not finished downloading")
ret = []
for (block_hash, block_data) in self.block_info.items():
ret.append( (block_data['height'], block_data['txns']) )
return ret | def get_block_info(self) | Get the retrieved block information.
Return [(height, [txs])] on success, ordered on height
Raise if not finished downloading | 4.617173 | 3.32525 | 1.388519 |
log.debug("Segwit support: {}".format(get_features('segwit')))
self.begin()
try:
self.loop()
except socket.error, se:
if not self.finished:
# unexpected
log.exception(se)
return False
# f... | def run( self ) | Interact with the blockchain peer,
until we get a socket error or we
exit the loop explicitly.
The order of operations is:
* send version
* receive version
* send verack
* send getdata
* receive blocks
* for each block:
* for each transa... | 6.668667 | 5.58639 | 1.193735 |
if not (self.num_blocks_received == self.num_blocks_requested):
log.debug("num blocks received = %s, num requested = %s" % (self.num_blocks_received, self.num_blocks_requested))
return False
return True | def have_all_block_data(self) | Have we received all block data? | 3.266828 | 2.550619 | 1.280798 |
# fetch remaining sender transactions
if len(self.sender_info.keys()) > 0:
sender_txids = self.sender_info.keys()[:]
sender_txid_batches = []
batch_size = 20
for i in xrange(0, len(sender_txids), batch_size ):
sender_txi... | def fetch_sender_txs(self) | Fetch all sender txs via JSON-RPC,
and merge them into our block data.
Try backing off (up to 5 times) if we fail
to fetch transactions via JSONRPC
Return True on success
Raise on error | 2.619365 | 2.546076 | 1.028785 |
assert self.have_all_block_data(), "Still missing block data"
assert self.num_txs_received == len(self.sender_info.keys()), "Num TXs received: %s; num TXs requested: %s" % (self.num_txs_received, len(self.sender_info.keys()))
for (block_hash, block_info) in self.block_info.items():
... | def block_data_sanity_checks(self) | Verify that the data we received makes sense.
Return True on success
Raise on error | 3.096183 | 3.024158 | 1.023816 |
log.debug("handshake (version %s)" % PROTOCOL_VERSION)
version = Version()
version.services = 0 # can't send blocks
log.debug("send Version")
self.send_message(version) | def begin(self) | This method will implement the handshake of the
Bitcoin protocol. It will send the Version message,
and block until it receives a VerAck.
Once we receive the version, we'll send the verack,
and begin downloading. | 10.838639 | 6.953487 | 1.558734 |
log.debug("handle version")
verack = VerAck()
log.debug("send VerAck")
self.send_message(verack)
self.verack = True
start_block_height = sorted(self.blocks.keys())[0]
if start_block_height < 1:
start_block_height = 1
# ask for all bl... | def handle_version(self, message_header, message) | This method will handle the Version message and
will send a VerAck message when it receives the
Version message.
:param message_header: The Version message header
:param message: The Version message | 2.745903 | 2.742408 | 1.001275 |
log.debug("handle inv of %s item(s)" % len(inv_packet.inventory))
reply_inv = []
for inv_info in inv_packet.inventory:
inv_hash = "%064x" % inv_info.inv_hash
if inv_info.inv_type == INVENTORY_TYPE["MSG_BLOCK"]:
# only ask for the block if we nee... | def handle_inv(self, message_header, inv_packet ) | Get the data we just requested.
Shouldn't happen with newer servers, since they use
getheaders/headers followed by getdata/blocks
(older peers use getblocks/inv/getdata/inv exchanges) | 4.091484 | 3.752946 | 1.090206 |
assert sender_txhash in self.sender_info.keys(), "Missing sender info for %s" % sender_txhash
assert nulldata_vin_outpoint in self.sender_info[sender_txhash], "Missing outpoint %s for sender %s" % (nulldata_vin_outpoint, sender_txhash)
block_hash = self.sender_info[sender_txhash][nulld... | def add_sender_info( self, sender_txhash, nulldata_vin_outpoint, sender_out_data ) | Record sender information in our block info.
@sender_txhash: txid of the sender
@nulldata_vin_outpoint: the 'vout' index from the nulldata tx input that this transaction funded | 2.554774 | 2.578713 | 0.990717 |
txn_serializer = TxSerializer()
tx_bin = txn_serializer.serialize(txn)
txdata = {
"version": txn.version,
"locktime": txn.lock_time,
"hex": binascii.hexlify( tx_bin ),
"txid": txn.calculate_hash(),
"size": len( tx_bin ),
... | def parse_tx( self, txn, block_header, block_hash, txindex ) | Given a transaction message and its index in the block,
go and create a "verbose" transaction structure
containing all the information in a nice, easy-to-read
dict (i.e. like what bitcoind would give us).
Does not work on coinbase transactions.
Does not include segwit witnesses | 4.618566 | 4.708587 | 0.980881 |
inp = txn['ins'][i]
ret = {
# to be filled in...
'scriptPubKey': None,
'addresses': None,
# for matching the input and sender funded
"txindex": txn['txindex'],
"relindex": txn['relindex'],
"output_index": inp[... | def make_sender_info( self, block_hash, txn, i, block_height ) | Make sender information bundle for a particular input of
a nulldata transaction.
We'll use it to go find the transaction output that
funded the ith input of the given tx. | 6.853711 | 5.916439 | 1.158418 |
headers = {'content-type': 'application/json'}
reqs = []
ret = {}
for i in xrange(0, len(txids)):
txid = txids[i]
if txid == "0000000000000000000000000000000000000000000000000000000000000000":
# coinbase; we never send these
... | def fetch_txs_rpc( self, bitcoind_opts, txids ) | Fetch the given list of transactions
via the JSON-RPC interface.
Return a dict of parsed transactions on success,
keyed by txid.
Return None on error | 2.87747 | 2.873341 | 1.001437 |
''' Read configuration file, perform sanity check and return configuration
dictionary used by other functions.'''
config = ConfigParser()
config.read_dict(DEFAULT_SETTINGS)
try:
config.readfp(open(config_file))
logger.debug("Using config file at " + config_file)
except:
... | def read_config(config_file=CONFIG_FILE_DEFAULT, override_url=None) | Read configuration file, perform sanity check and return configuration
dictionary used by other functions. | 4.130848 | 3.422544 | 1.206953 |
'''
Check the executor config file for consistency.
'''
# Check server URL
url = config.get("Server", "url")
try:
urlopen(url)
except Exception as e:
logger.error(
"The configured OpenSubmit server URL ({0}) seems to be invalid: {1}".format(url, e))
re... | def check_config(config) | Check the executor config file for consistency. | 4.591111 | 4.18574 | 1.096846 |
'''
Determine if the given config file exists.
'''
config = RawConfigParser()
try:
config.readfp(open(config_fname))
return True
except IOError:
return False | def has_config(config_fname) | Determine if the given config file exists. | 4.050119 | 3.253837 | 1.244721 |
'''
Create the config file from the defaults under the given name.
'''
config_path = os.path.dirname(config_fname)
os.makedirs(config_path, exist_ok=True)
# Consider override URL. Only used by test suite runs
settings = DEFAULT_SETTINGS_FLAT
if override_url:
settings['url'] = ov... | def create_config(config_fname, override_url=None) | Create the config file from the defaults under the given name. | 5.569678 | 4.713814 | 1.181565 |
'''
Makes the given user a student.
'''
tutor_group, owner_group = _get_user_groups()
user.is_staff = False
user.is_superuser = False
user.save()
owner_group.user_set.remove(user)
owner_group.save()
tutor_group.user_set.remove(user)
tutor_group.save() | def make_student(user) | Makes the given user a student. | 3.028386 | 2.600257 | 1.164649 |
'''
Makes the given user a tutor.
'''
tutor_group, owner_group = _get_user_groups()
user.is_staff = True
user.is_superuser = False
user.save()
owner_group.user_set.remove(user)
owner_group.save()
tutor_group.user_set.add(user)
tutor_group.save() | def make_tutor(user) | Makes the given user a tutor. | 2.767425 | 2.408628 | 1.148963 |
'''
Makes the given user a owner and tutor.
'''
tutor_group, owner_group = _get_user_groups()
user.is_staff = True
user.is_superuser = False
user.save()
owner_group.user_set.add(user)
owner_group.save()
tutor_group.user_set.add(user)
tutor_group.save() | def make_owner(user) | Makes the given user a owner and tutor. | 2.958698 | 2.103055 | 1.406857 |
'''
Makes the given user an admin.
'''
tutor_group, owner_group = _get_user_groups()
user.is_staff = True
user.is_superuser = True
user.save()
owner_group.user_set.add(user)
owner_group.save()
tutor_group.user_set.add(user)
tutor_group.save() | def make_admin(user) | Makes the given user an admin. | 2.692654 | 2.459862 | 1.094636 |
'''Best attempt to get username and hostname, returns "na" if problem.'''
user = 'na'
host = 'na'
try:
user = getpass.getuser()
except Exception:
pass
try:
host = socket.gethostname()
except Exception:
pass
return user, host | def _get_username_hostname() | Best attempt to get username and hostname, returns "na" if problem. | 3.412889 | 2.074574 | 1.645104 |
'''Accept a dict of key:values (numerics) returning list of key-value tuples ordered by desc values.
If by_key=True, sorts by dict key.'''
sort_key = lambda x: (-1 * x[1], x[0])
if by_key:
sort_key = lambda x: x[0]
return sorted(key_counts.items(), key=sort_key) | def sort_dict(key_counts, by_key=False) | Accept a dict of key:values (numerics) returning list of key-value tuples ordered by desc values.
If by_key=True, sorts by dict key. | 5.175081 | 2.063405 | 2.508029 |
'''Yields subset of base_collection/generator based on filters.'''
for item in base_collection:
excluded = []
for (name, exclude) in self._filters:
if exclude(item):
excluded.append(name)
if excluded:
filter_value = ... | def filter(self, base_collection) | Yields subset of base_collection/generator based on filters. | 5.149832 | 3.582636 | 1.437442 |
data = {}
# None of them is mandatory
data['id'] = response.get('user_id', None)
data['username'] = response.get('custom_username', None)
if not data['username']:
data['username'] = response.get('ext_user_username', None)
data['last_name'] = response.... | def get_user_details(self, response) | Complete with additional information from original LTI POST data, as available. | 2.590571 | 2.362507 | 1.096535 |
'''
Monkey patch for getting better user name stringification,
user proxies did not make the job.
Django's custom user model feature would have needed to be introduced
before the first syncdb, which does not work for existing installations.
'''
if self.email:
shortened = ... | def user_unicode(self) | Monkey patch for getting better user name stringification,
user proxies did not make the job.
Django's custom user model feature would have needed to be introduced
before the first syncdb, which does not work for existing installations. | 6.226992 | 2.175354 | 2.862518 |
'''
Moves all submissions and other data linked to the secondary user into the primary user.
Nothing is deleted here, we just modify foreign user keys.
'''
# Update all submission authorships of the secondary to the primary
submissions = Submission.objects.filter(authors__id=secondary.pk... | def move_user_data(primary, secondary) | Moves all submissions and other data linked to the secondary user into the primary user.
Nothing is deleted here, we just modify foreign user keys. | 6.104788 | 3.730728 | 1.636353 |
'''
Adds a course for the user after conducting a set of sanity checks.
Return the title of the course or an exception.
'''
course = get_object_or_404(Course, pk=int(id), active=True)
if course not in self.courses.all():
self.courses.add(course)
... | def add_course_safe(self, id) | Adds a course for the user after conducting a set of sanity checks.
Return the title of the course or an exception. | 5.255336 | 2.364751 | 2.222363 |
'''
Returns the list of courses this user is tutor or owner for.
'''
tutoring = self.user.courses_tutoring.all().filter(active__exact=True)
owning = self.user.courses.all().filter(active__exact=True)
result = (tutoring | owning).distinct()
return result | def tutor_courses(self) | Returns the list of courses this user is tutor or owner for. | 4.595461 | 3.251344 | 1.413404 |
'''
Returns the list of courses this user is subscribed for,
or owning, or tutoring.
This leads to the fact that tutors and owners don't need
course membership.
'''
registered = self.courses.filter(active__exact=True).distinct()
return (sel... | def user_courses(self) | Returns the list of courses this user is subscribed for,
or owning, or tutoring.
This leads to the fact that tutors and owners don't need
course membership. | 11.262373 | 2.997716 | 3.756985 |
'''
Returns the list of open assignments from the
viewpoint of this user.
'''
# Include only assignments with future, or no, hard deadline
qs = Assignment.objects.filter(hard_deadline__gt=timezone.now(
)) | Assignment.objects.filter(hard_deadline__isnull=T... | def open_assignments(self) | Returns the list of open assignments from the
viewpoint of this user. | 4.800766 | 4.355837 | 1.102145 |
'''
Returns the list of past assignments the user did not submit for
before the hard deadline.
'''
# Include only assignments with past hard deadline
qs = Assignment.objects.filter(hard_deadline__lt=timezone.now())
# Include only assignments from courses t... | def gone_assignments(self) | Returns the list of past assignments the user did not submit for
before the hard deadline. | 6.00782 | 3.703867 | 1.62204 |
# TODO Maybe file attachments handling through `files` message_model context var.
if subject is None:
subject = u'%s' % _('No Subject')
if mtype == 'html':
msg = self.mime_multipart()
text_part = self.mime_multipart('alternative')
text_p... | def _build_message(self, to, text, subject=None, mtype=None, unsubscribe_url=None) | Constructs a MIME message from message and dispatch models. | 3.191627 | 3.013186 | 1.05922 |
'''
View function that redirects to social auth login,
in case the user is not logged in.
'''
if request.user.is_authenticated():
if not request.user.is_active or not request.user.is_staff:
raise PermissionDenied()
else:
messages.add_message(request, messages.... | def _social_auth_login(self, request, **kwargs) | View function that redirects to social auth login,
in case the user is not logged in. | 3.557133 | 2.463248 | 1.444082 |
''' Restrict the listed courses for the current user.'''
qs = super(CourseAdmin, self).get_queryset(request)
if request.user.is_superuser:
return qs
else:
return qs.filter(Q(tutors__pk=request.user.pk) | Q(owner=request.user)).distinct() | def get_queryset(self, request) | Restrict the listed courses for the current user. | 4.066855 | 2.782539 | 1.461563 |
'''Partition paired aligns into families.
Each read is considered against each ranked tag until all reads are
partitioned into families.'''
tag_aligns = defaultdict(set)
tag_inexact_match_count = defaultdict(int)
for paired_align in tagged_paired_aligns:
(left_umt, right_umt) = paired... | def _build_tag_families(tagged_paired_aligns,
ranked_tags,
hamming_threshold,
consensus_threshold,
family_filter=lambda _: None) | Partition paired aligns into families.
Each read is considered against each ranked tag until all reads are
partitioned into families. | 2.231969 | 1.93715 | 1.152192 |
'''Return the list of tags ranked from most to least popular.'''
tag_count_dict = defaultdict(int)
for paired_align in tagged_paired_aligns:
tag_count_dict[paired_align.umt] += 1
tags_by_count = utils.sort_dict(tag_count_dict)
ranked_tags = [tag_count[0] for tag_count in tags_by_count]
r... | def _rank_tags(tagged_paired_aligns) | Return the list of tags ranked from most to least popular. | 3.033817 | 2.631154 | 1.153037 |
'''Connor entry point. See help for more info'''
log = None
if not command_line_args:
command_line_args = sys.argv
try:
start_time = time.time()
args = parse_command_line_args(command_line_args)
log = utils.Logger(args)
command_validator.preflight(args, log)
... | def main(command_line_args=None) | Connor entry point. See help for more info | 3.767526 | 3.548127 | 1.061835 |
if SHORTCUT_EMAIL_MESSAGE_TYPE:
message_cls = get_registered_message_type(SHORTCUT_EMAIL_MESSAGE_TYPE)
else:
if isinstance(message, dict):
message_cls = EmailHtmlMessage
else:
message_cls = EmailTextMessage
schedule_messages(
message_cls(subje... | def schedule_email(message, to, subject=None, sender=None, priority=None) | Schedules an email message for delivery.
:param dict, str message: str or dict: use str for simple text email;
dict - to compile email from a template (default: `sitemessage/messages/email_html__smtp.html`).
:param list|str|unicode to: recipients addresses or Django User model heir instances
:param... | 4.90703 | 4.628282 | 1.060227 |
schedule_messages(message, recipients('xmppsleek', to), sender=sender, priority=priority) | def schedule_jabber_message(message, to, sender=None, priority=None) | Schedules Jabber XMPP message for delivery.
:param str message: text to send.
:param list|str|unicode to: recipients addresses or Django User model heir instances with `email` attributes.
:param User sender: User model heir instance
:param int priority: number describing message priority. If set overri... | 16.664921 | 29.764517 | 0.559892 |
schedule_messages(message, recipients('twitter', to), sender=sender, priority=priority) | def schedule_tweet(message, to='', sender=None, priority=None) | Schedules a Tweet for delivery.
:param str message: text to send.
:param list|str|unicode to: recipients addresses or Django User model heir instances with `telegram` attributes.
If supplied tweets will be @-replies.
:param User sender: User model heir instance
:param int priority: number descr... | 9.297723 | 24.369097 | 0.381537 |
schedule_messages(message, recipients('telegram', to), sender=sender, priority=priority) | def schedule_telegram_message(message, to, sender=None, priority=None) | Schedules Telegram message for delivery.
:param str message: text to send.
:param list|str|unicode to: recipients addresses or Django User model heir instances with `telegram` attributes.
:param User sender: User model heir instance
:param int priority: number describing message priority. If set overri... | 8.662122 | 19.704586 | 0.439599 |
schedule_messages(message, recipients('fb', ''), sender=sender, priority=priority) | def schedule_facebook_message(message, sender=None, priority=None) | Schedules Facebook wall message for delivery.
:param str message: text or URL to publish.
:param User sender: User model heir instance
:param int priority: number describing message priority. If set overrides priority provided with message type. | 14.312091 | 40.286629 | 0.355257 |
schedule_messages(message, recipients('vk', to), sender=sender, priority=priority) | def schedule_vkontakte_message(message, to, sender=None, priority=None) | Schedules VKontakte message for delivery.
:param str message: text or URL to publish on wall.
:param list|str|unicode to: recipients addresses or Django User model heir instances with `vk` attributes.
:param User sender: User model heir instance
:param int priority: number describing message priority. ... | 9.572035 | 19.316818 | 0.495529 |
if cls.alias is None:
cls.alias = cls.__name__
return cls.alias | def get_alias(cls) | Returns messenger alias.
:return: str
:rtype: str | 3.6601 | 4.416644 | 0.828706 |
self._init_delivery_statuses_dict()
self.before_send()
try:
yield
finally:
self.after_send()
self._update_dispatches() | def before_after_send_handling(self) | Context manager that allows to execute send wrapped
in before_send() and after_send(). | 8.229104 | 7.229958 | 1.138195 |
try: # That's all due Django 1.7 apps loading.
from django.contrib.auth import get_user_model
USER_MODEL = get_user_model()
except ImportError:
# Django 1.4 fallback.
from django.contrib.auth.models import User as USER_MODEL
if not is_it... | def _structure_recipients_data(cls, recipients) | Converts recipients data into a list of Recipient objects.
:param list recipients: list of objects
:return: list of Recipient
:rtype: list | 4.796278 | 4.831507 | 0.992709 |
if message_cls.send_retry_limit is not None and (dispatch.retry_count + 1) >= message_cls.send_retry_limit:
self.mark_failed(dispatch, error_log)
else:
dispatch.error_log = error_log
self._st['error'].append(dispatch) | def mark_error(self, dispatch, error_log, message_cls) | Marks a dispatch as having error or consequently as failed
if send retry limit for that message type is exhausted.
Should be used within send().
:param Dispatch dispatch: a Dispatch
:param str error_log: error message
:param MessageBase message_cls: MessageBase heir | 4.186144 | 3.812272 | 1.098071 |
dispatch.error_log = error_log
self._st['failed'].append(dispatch) | def mark_failed(self, dispatch, error_log) | Marks a dispatch as failed.
Sitemessage won't try to deliver already failed messages.
Should be used within send().
:param Dispatch dispatch: a Dispatch
:param str error_log: str - error message | 11.928361 | 13.369342 | 0.892218 |
with self.before_after_send_handling():
for message_id, message_data in messages.items():
message_model, dispatch_models = message_data
try:
message_cls = get_registered_message_type(message_model.cls)
except UnknownMessage... | def _process_messages(self, messages, ignore_unknown_message_types=False) | Performs message processing.
:param dict messages: indexed by message id dict with messages data
:param bool ignore_unknown_message_types: whether to silence exceptions
:raises UnknownMessageTypeError: | 4.929514 | 4.912818 | 1.003398 |
Dispatch.log_dispatches_errors(self._st['error'] + self._st['failed'])
Dispatch.set_dispatches_statuses(**self._st)
self._init_delivery_statuses_dict() | def _update_dispatches(self) | Updates dispatched data in DB according to information gather by `mark_*` methods, | 15.424309 | 14.084197 | 1.09515 |
'''
Make sure that other installed plugins don't affect the same keyword argument.
'''
for other in app.plugins:
if not isinstance(other, MySQLPlugin):
continue
if other.keyword == self.keyword:
raise PluginError("Found another mysq... | def setup(self, app) | Make sure that other installed plugins don't affect the same keyword argument. | 7.110325 | 4.194376 | 1.695204 |
'''
Part of the Python Social Auth Pipeline.
Checks if the created demo user should be pushed into some group.
'''
if backend.name is 'passthrough' and settings.DEMO is True and 'role' in kwargs['request'].session[passthrough.SESSION_VAR]:
role = kwargs['request'].session[passthrough.SESSION... | def assign_role(backend, user, response, *args, **kwargs) | Part of the Python Social Auth Pipeline.
Checks if the created demo user should be pushed into some group. | 7.234765 | 3.811002 | 1.898389 |
'''
Fetch data from an URL and save it under the given target name.
'''
logger.debug("Fetching %s from %s" % (fullpath, url))
try:
tmpfile, headers = urlretrieve(url)
if os.path.exists(fullpath):
os.remove(fullpath)
shutil.move(tmpfile, fullpath)
except Excep... | def fetch(url, fullpath) | Fetch data from an URL and save it under the given target name. | 3.065555 | 2.505132 | 1.22371 |
'''
Send POST data to an OpenSubmit server url path,
according to the configuration.
'''
server = config.get("Server", "url")
logger.debug("Sending executor payload to " + server)
post_data = urlencode(post_data)
post_data = post_data.encode("utf-8", errors="ignore")
url = server + u... | def send_post(config, urlpath, post_data) | Send POST data to an OpenSubmit server url path,
according to the configuration. | 4.712834 | 3.090049 | 1.525165 |
'''
Register this host on OpenSubmit test machine.
'''
info = all_host_infos()
logger.debug("Sending host information: " + str(info))
post_data = [("Config", json.dumps(info)),
("Action", "get_config"),
("UUID", config.get("Server", "uuid")),
("... | def send_hostinfo(config) | Register this host on OpenSubmit test machine. | 8.727133 | 5.960007 | 1.464282 |
'''
Check if this server API version is compatible to us.
'''
try:
semver = server_version.split('.')
if semver[0] != '1':
logger.error(
'Server API version (%s) is too new for us. Please update the executor installation.' % server_version)
return ... | def compatible_api_version(server_version) | Check if this server API version is compatible to us. | 4.184677 | 3.604709 | 1.160892 |
'''
Fetch any available work from the OpenSubmit server and
return an according job object.
Returns None if no work is available.
Errors are reported by this function directly.
'''
url = "%s/jobs/?Secret=%s&UUID=%s" % (config.get("Server", "url"),
... | def fetch_job(config) | Fetch any available work from the OpenSubmit server and
return an according job object.
Returns None if no work is available.
Errors are reported by this function directly. | 5.250943 | 4.6423 | 1.131108 |
'''
Act like fetch_job, but take the validator file and the student
submission files directly from a directory.
Intended for testing purposes when developing test scripts.
Check also cmdline.py.
'''
logger.debug("Creating fake job from " + src_dir)
from .job import Job
job = Job(co... | def fake_fetch_job(config, src_dir) | Act like fetch_job, but take the validator file and the student
submission files directly from a directory.
Intended for testing purposes when developing test scripts.
Check also cmdline.py. | 4.167276 | 2.84444 | 1.46506 |
if not has_file(self.working_dir, 'configure'):
if mandatory:
raise FileNotFoundError(
"Could not find a configure script for execution.")
else:
return
try:
prog = RunningProgram(self, 'configure')
... | def run_configure(self, mandatory=True) | Runs the 'configure' program in the working directory.
Args:
mandatory (bool): Throw exception if 'configure' fails or a
'configure' file is missing. | 5.53638 | 5.346696 | 1.035477 |
# Let exceptions travel through
prog = RunningProgram(self, *compiler_cmdline(compiler=compiler,
inputs=inputs,
output=output))
prog.expect_exit_status(0) | def run_compiler(self, compiler=GCC, inputs=None, output=None) | Runs a compiler in the working directory.
Args:
compiler (tuple): The compiler program and its command-line arguments,
including placeholders for output and input files.
inputs (tuple): The list of input files for the compiler.
output (str): ... | 12.370612 | 17.579409 | 0.703699 |
logger.info("Running build steps ...")
self.run_configure(mandatory=False)
self.run_make(mandatory=False)
self.run_compiler(compiler=compiler,
inputs=inputs,
output=output) | def run_build(self, compiler=GCC, inputs=None, output=None) | Combined call of 'configure', 'make' and the compiler.
The success of 'configure' and 'make' is optional.
The arguments are the same as for run_compiler. | 4.33015 | 3.648762 | 1.186745 |
logger.debug("Spawning program for interaction ...")
if exclusive:
kill_longrunning(self.config)
return RunningProgram(self, name, arguments, timeout) | def spawn_program(self, name, arguments=[], timeout=30, exclusive=False) | Spawns a program in the working directory.
This method allows the interaction with the running program,
based on the returned RunningProgram object.
Args:
name (str): The name of the program to be executed.
arguments (tuple): Command-line arguments for the progra... | 12.198278 | 15.099785 | 0.807845 |
logger.debug("Running program ...")
if exclusive:
kill_longrunning(self.config)
prog = RunningProgram(self, name, arguments, timeout)
return prog.expect_end() | def run_program(self, name, arguments=[], timeout=30, exclusive=False) | Runs a program in the working directory to completion.
Args:
name (str): The name of the program to be executed.
arguments (tuple): Command-line arguments for the program.
timeout (int): The timeout for execution.
exclusive (bool): Prevent parallel va... | 12.036172 | 14.931494 | 0.806093 |
matches = []
logger.debug("Searching student files for '{0}'".format(regex))
for fname in self.student_files:
if os.path.isfile(self.working_dir + fname):
for line in open(self.working_dir + fname, 'br'):
if re.search(regex.encode(), line)... | def grep(self, regex) | Scans the student files for text patterns.
Args:
regex (str): Regular expression used for scanning inside the files.
Returns:
tuple: Names of the matching files in the working directory. | 3.067882 | 2.879737 | 1.065334 |
logger.debug("Testing {0} for the following files: {1}".format(
self.working_dir, filenames))
dircontent = os.listdir(self.working_dir)
for fname in filenames:
if fname not in dircontent:
return False
return True | def ensure_files(self, filenames) | Checks the student submission for specific files.
Args:
filenames (tuple): The list of file names to be cjecked for.
Returns:
bool: Indicator if all files are found in the student archive. | 3.895874 | 3.80666 | 1.023436 |
context = copy(context)
# Find any upcoming or current live chat. The Chat date must be less than 5
# days away, or currently in progress.
oldchat = LiveChat.chat_finder.get_last_live_chat()
if oldchat:
context['last_live_chat'] = {
'title': oldchat.title,
'ch... | def live_chat_banner(context) | Display any available live chats as advertisements. | 3.760588 | 3.603517 | 1.043588 |
'''
Terminate everything under the current user account
that has run too long. This is a final safeguard if
the subprocess timeout stuff is not working.
You better have no production servers running also
under the current user account ...
'''
import psutil
ourpid ... | def kill_longrunning(config) | Terminate everything under the current user account
that has run too long. This is a final safeguard if
the subprocess timeout stuff is not working.
You better have no production servers running also
under the current user account ... | 6.417103 | 3.155573 | 2.033578 |
logger.debug("Exit status is {0}".format(self._spawn.exitstatus))
return self._spawn.exitstatus | def get_exitstatus(self) | Get the exit status of the program execution.
Returns:
int: Exit status as reported by the operating system,
or None if it is not available. | 5.383218 | 5.647951 | 0.953128 |
logger.debug("Expecting output '{0}' from '{1}'".format(pattern, self.name))
try:
return self._spawn.expect(pattern, timeout)
except pexpect.exceptions.EOF as e:
logger.debug("Raising termination exception.")
raise TerminationException(instance=self, ... | def expect_output(self, pattern, timeout=-1) | Wait until the running program performs some given output, or terminates.
Args:
pattern: The pattern the output should be checked for.
timeout (int): How many seconds should be waited for the output.
The pattern argument may be a string, a compiled regular expression,
... | 2.708987 | 2.446299 | 1.107382 |
logger.debug("Sending input '{0}' to '{1}'".format(text, self.name))
try:
return self._spawn.sendline(text)
except pexpect.exceptions.EOF as e:
logger.debug("Raising termination exception.")
raise TerminationException(instance=self, real_exception=e, ... | def sendline(self, text) | Sends an input line to the running program, including os.linesep.
Args:
text (str): The input text to be send.
Raises:
TerminationException: The program terminated before / while / after sending the input.
NestedException: An internal problem occured while waiting ... | 2.648799 | 2.362903 | 1.120994 |
logger.debug("Waiting for termination of '{0}'".format(self.name))
try:
# Make sure we fetch the last output bytes.
# Recommendation from the pexpect docs.
self._spawn.expect(pexpect.EOF)
self._spawn.wait()
dircontent = str(os.listdir(... | def expect_end(self) | Wait for the running program to finish.
Returns:
A tuple with the exit code, as reported by the operating system, and the output produced. | 4.094617 | 3.895797 | 1.051034 |
self.expect_end()
logger.debug("Checking exit status of '{0}', output so far: {1}".format(
self.name, self.get_output()))
if self._spawn.exitstatus is None:
raise WrongExitStatusException(
instance=self, expected=exit_status, output=self.get_outpu... | def expect_exitstatus(self, exit_status) | Wait for the running program to finish and expect some exit status.
Args:
exit_status (int): The expected exit status.
Raises:
WrongExitStatusException: The produced exit status is not the expected one. | 3.382601 | 3.26309 | 1.036625 |
return _generic_view(
'handle_unsubscribe_request', sig_unsubscribe_failed,
request, message_id, dispatch_id, hashed, redirect_to=redirect_to
) | def unsubscribe(request, message_id, dispatch_id, hashed, redirect_to=None) | Handles unsubscribe request.
:param Request request:
:param int message_id:
:param int dispatch_id:
:param str hashed:
:param str redirect_to:
:return: | 6.058412 | 9.656827 | 0.627371 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.