uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
fd19a1a8faf0bc8590813a4e
train
class
class msg_reject: __slots__ = ("code", "data", "message", "reason") command = b"reject" REJECT_MALFORMED = 1 def __init__(self): self.message = b"" self.code = 0 self.reason = b"" self.data = 0 def deserialize(self, f): self.message = deser_string(f) ...
class msg_reject:
__slots__ = ("code", "data", "message", "reason") command = b"reject" REJECT_MALFORMED = 1 def __init__(self): self.message = b"" self.code = 0 self.reason = b"" self.data = 0 def deserialize(self, f): self.message = deser_string(f) self.code = struc...
deserialized as blocks blocks = deser_vector(f, CBlock) for x in blocks: self.headers.append(CBlockHeader(x)) def serialize(self): blocks = [CBlock(x) for x in self.headers] return ser_vector(blocks) def __repr__(self): return "msg_headers(headers=%s)" % re...
82
82
274
5
77
minblock/workcoin
test/functional/test_framework/messages.py
Python
msg_reject
msg_reject
1,325
1,355
1,325
1,325
2e6206998d81892288cef4b4e92f0da46509c3dd
bigcode/the-stack
train
41df45e0cee0b14e2437d61e
train
class
class CBlockHeader: __slots__ = ("hash", "hashMerkleRoot", "hashPrevBlock", "nBits", "nNonce", "nTime", "nVersion", "sha256", "scrypt256") def __init__(self, header=None): if header is None: self.set_null() else: self.nVersion = header.nVersion ...
class CBlockHeader:
__slots__ = ("hash", "hashMerkleRoot", "hashPrevBlock", "nBits", "nNonce", "nTime", "nVersion", "sha256", "scrypt256") def __init__(self, header=None): if header is None: self.set_null() else: self.nVersion = header.nVersion self.hashPrevBloc...
to be the txid. def calc_sha256(self, with_witness=False): if with_witness: # Don't cache the result, just return it return uint256_from_str(hash256(self.serialize_with_witness())) if self.sha256 is None: self.sha256 = uint256_from_str(hash256(self.serialize_wit...
212
212
708
5
207
minblock/workcoin
test/functional/test_framework/messages.py
Python
CBlockHeader
CBlockHeader
525
598
525
525
457e3dfe3588ba867d723e708b77ef03a16e7881
bigcode/the-stack
train
e95e3cdb3a166d627ef2b0aa
train
class
class msg_tx: __slots__ = ("tx",) command = b"tx" def __init__(self, tx=CTransaction()): self.tx = tx def deserialize(self, f): self.tx.deserialize(f) def serialize(self): return self.tx.serialize_without_witness() def __repr__(self): return "msg_tx(tx=%s)" % ...
class msg_tx:
__slots__ = ("tx",) command = b"tx" def __init__(self, tx=CTransaction()): self.tx = tx def deserialize(self, f): self.tx.deserialize(f) def serialize(self): return self.tx.serialize_without_witness() def __repr__(self): return "msg_tx(tx=%s)" % (repr(self.tx)...
b"" r += self.locator.serialize() r += ser_uint256(self.hashstop) return r def __repr__(self): return "msg_getblocks(locator=%s hashstop=%064x)" \ % (repr(self.locator), self.hashstop) class msg_tx:
64
64
86
4
60
minblock/workcoin
test/functional/test_framework/messages.py
Python
msg_tx
msg_tx
1,101
1,115
1,101
1,101
8d0529140fab3406908bffb63d4e59d1ed77ab64
bigcode/the-stack
train
b55788210419d598c55e94d1
train
function
def uint256_from_compact(c): nbytes = (c >> 24) & 0xFF v = (c & 0xFFFFFF) << (8 * (nbytes - 3)) return v
def uint256_from_compact(c):
nbytes = (c >> 24) & 0xFF v = (c & 0xFFFFFF) << (8 * (nbytes - 3)) return v
return rs def uint256_from_str(s): r = 0 t = struct.unpack("<IIIIIIII", s[:32]) for i in range(8): r += t[i] << (i * 32) return r def uint256_from_compact(c):
64
64
50
8
55
minblock/workcoin
test/functional/test_framework/messages.py
Python
uint256_from_compact
uint256_from_compact
117
120
117
117
f3af217c76e8624ca574d08e2feea039f3fea516
bigcode/the-stack
train
b2884d8c102a2f426b9fd3cb
train
class
class msg_pong: __slots__ = ("nonce",) command = b"pong" def __init__(self, nonce=0): self.nonce = nonce def deserialize(self, f): self.nonce = struct.unpack("<Q", f.read(8))[0] def serialize(self): r = b"" r += struct.pack("<Q", self.nonce) return r d...
class msg_pong:
__slots__ = ("nonce",) command = b"pong" def __init__(self, nonce=0): self.nonce = nonce def deserialize(self, f): self.nonce = struct.unpack("<Q", f.read(8))[0] def serialize(self): r = b"" r += struct.pack("<Q", self.nonce) return r def __repr__(self...
Q", f.read(8))[0] def serialize(self): r = b"" r += struct.pack("<Q", self.nonce) return r def __repr__(self): return "msg_ping(nonce=%08x)" % self.nonce class msg_pong:
64
64
114
5
58
minblock/workcoin
test/functional/test_framework/messages.py
Python
msg_pong
msg_pong
1,204
1,220
1,204
1,204
ebc96e5628a17acee19306656c409b7c46f4a669
bigcode/the-stack
train
dc237236c0a6beb43d3cbe28
train
class
class msg_generic: __slots__ = ("command", "data") def __init__(self, command, data=None): self.command = command self.data = data def serialize(self): return self.data def __repr__(self): return "msg_generic()"
class msg_generic:
__slots__ = ("command", "data") def __init__(self, command, data=None): self.command = command self.data = data def serialize(self): return self.data def __repr__(self): return "msg_generic()"
_witness=False) def __repr__(self): return "msg_block(block=%s)" % (repr(self.block)) # for cases where a user needs tighter control over what is sent over the wire # note that the user must supply the name of the command, and the data class msg_generic:
64
64
63
4
59
minblock/workcoin
test/functional/test_framework/messages.py
Python
msg_generic
msg_generic
1,147
1,158
1,147
1,147
261203ce8cc3e345ccb27dc115bc876543b276eb
bigcode/the-stack
train
c5c0d45b9f01f5bec264cb5e
train
class
class CTxWitness: __slots__ = ("vtxinwit",) def __init__(self): self.vtxinwit = [] def deserialize(self, f): for i in range(len(self.vtxinwit)): self.vtxinwit[i].deserialize(f) def serialize(self): r = b"" # This is different than the usual vector serializa...
class CTxWitness:
__slots__ = ("vtxinwit",) def __init__(self): self.vtxinwit = [] def deserialize(self, f): for i in range(len(self.vtxinwit)): self.vtxinwit[i].deserialize(f) def serialize(self): r = b"" # This is different than the usual vector serialization -- # ...
deserialize(self, f): self.scriptWitness.stack = deser_string_vector(f) def serialize(self): return ser_string_vector(self.scriptWitness.stack) def __repr__(self): return repr(self.scriptWitness) def is_null(self): return self.scriptWitness.is_null() class CTxWitness:
64
64
199
5
59
minblock/workcoin
test/functional/test_framework/messages.py
Python
CTxWitness
CTxWitness
386
413
386
386
9f3b8fcd6419bba46da06b2e934ab59622d66a39
bigcode/the-stack
train
62456c4b987c825d0314f280
train
function
def deser_vector(f, c): nit = deser_compact_size(f) r = [] for i in range(nit): t = c() t.deserialize(f) r.append(t) return r
def deser_vector(f, c):
nit = deser_compact_size(f) r = [] for i in range(nit): t = c() t.deserialize(f) r.append(t) return r
32) return r def uint256_from_compact(c): nbytes = (c >> 24) & 0xFF v = (c & 0xFFFFFF) << (8 * (nbytes - 3)) return v def deser_vector(f, c):
64
64
47
7
56
minblock/workcoin
test/functional/test_framework/messages.py
Python
deser_vector
deser_vector
123
130
123
123
a51e3e1569ce05487a326e3def5b8bf41332c4b0
bigcode/the-stack
train
0cd0a84b1b1e325e3a333b0c
train
class
class msg_feefilter: __slots__ = ("feerate",) command = b"feefilter" def __init__(self, feerate=0): self.feerate = feerate def deserialize(self, f): self.feerate = struct.unpack("<Q", f.read(8))[0] def serialize(self): r = b"" r += struct.pack("<Q", self.feerate) ...
class msg_feefilter:
__slots__ = ("feerate",) command = b"feefilter" def __init__(self, feerate=0): self.feerate = feerate def deserialize(self, f): self.feerate = struct.unpack("<Q", f.read(8))[0] def serialize(self): r = b"" r += struct.pack("<Q", self.feerate) return r ...
b"tx")): r += ser_uint256(self.data) return r def __repr__(self): return "msg_reject: %s %d %s [%064x]" \ % (self.message, self.code, self.reason, self.data) class msg_feefilter:
64
64
128
6
58
minblock/workcoin
test/functional/test_framework/messages.py
Python
msg_feefilter
msg_feefilter
1,358
1,374
1,358
1,358
fa1d2ec7d6ec41cf84aef70afbf1561c2959b420
bigcode/the-stack
train
788fcf5c3b4db2419cb10fec
train
function
def ToHex(obj): return bytes_to_hex_str(obj.serialize())
def ToHex(obj):
return bytes_to_hex_str(obj.serialize())
v) return r # Deserialize from a hex string representation (eg from RPC) def FromHex(obj, hex_string): obj.deserialize(BytesIO(hex_str_to_bytes(hex_string))) return obj # Convert a binary-serializable object to hex (eg for submission via RPC) def ToHex(obj):
64
64
14
5
59
minblock/workcoin
test/functional/test_framework/messages.py
Python
ToHex
ToHex
184
185
184
184
39524ae7896f4d97fd52c85edc36995245daf181
bigcode/the-stack
train
572bd6dab75cedb81b03f74f
train
function
def hash256(s): return sha256(sha256(s))
def hash256(s):
return sha256(sha256(s))
) MSG_TX = 1 MSG_BLOCK = 2 MSG_WITNESS_FLAG = 1 << 30 MSG_TYPE_MASK = 0xffffffff >> 2 # Serialization/deserialization tools def sha256(s): return hashlib.new('sha256', s).digest() def hash256(s):
64
64
14
5
59
minblock/workcoin
test/functional/test_framework/messages.py
Python
hash256
hash256
61
62
61
61
d53e1d8d5b5d0556060a0efca20f663e01b96916
bigcode/the-stack
train
bea39590c658114292552bde
train
class
class msg_inv: __slots__ = ("inv",) command = b"inv" def __init__(self, inv=None): if inv is None: self.inv = [] else: self.inv = inv def deserialize(self, f): self.inv = deser_vector(f, CInv) def serialize(self): return ser_vector(self.inv)...
class msg_inv:
__slots__ = ("inv",) command = b"inv" def __init__(self, inv=None): if inv is None: self.inv = [] else: self.inv = inv def deserialize(self, f): self.inv = deser_vector(f, CInv) def serialize(self): return ser_vector(self.inv) def __rep...
.addrs = [] def deserialize(self, f): self.addrs = deser_vector(f, CAddress) def serialize(self): return ser_vector(self.addrs) def __repr__(self): return "msg_addr(addrs=%s)" % (repr(self.addrs)) class msg_inv:
64
64
102
4
60
minblock/workcoin
test/functional/test_framework/messages.py
Python
msg_inv
msg_inv
1,040
1,057
1,040
1,040
c000751de29e01338d4d574cd995f595cbec6aee
bigcode/the-stack
train
6549995b978c0ad2af3f936f
train
function
def ser_uint256_vector(l): r = ser_compact_size(len(l)) for i in l: r += ser_uint256(i) return r
def ser_uint256_vector(l):
r = ser_compact_size(len(l)) for i in l: r += ser_uint256(i) return r
else: r += i.serialize() return r def deser_uint256_vector(f): nit = deser_compact_size(f) r = [] for i in range(nit): t = deser_uint256(f) r.append(t) return r def ser_uint256_vector(l):
64
64
35
7
56
minblock/workcoin
test/functional/test_framework/messages.py
Python
ser_uint256_vector
ser_uint256_vector
155
159
155
155
452b4dee118cc6918c1199f2539f7636914db813
bigcode/the-stack
train
11f8c0f36cd40af77e7f0e34
train
class
class P2PHeaderAndShortIDs: __slots__ = ("header", "nonce", "prefilled_txn", "prefilled_txn_length", "shortids", "shortids_length") def __init__(self): self.header = CBlockHeader() self.nonce = 0 self.shortids_length = 0 self.shortids = [] self.prefilled...
class P2PHeaderAndShortIDs:
__slots__ = ("header", "nonce", "prefilled_txn", "prefilled_txn_length", "shortids", "shortids_length") def __init__(self): self.header = CBlockHeader() self.nonce = 0 self.shortids_length = 0 self.shortids = [] self.prefilled_txn_length = 0 self...
): r = b"" r += ser_compact_size(self.index) if with_witness: r += self.tx.serialize_with_witness() else: r += self.tx.serialize_without_witness() return r def serialize_without_witness(self): return self.serialize(with_witness=False) def...
140
140
469
9
131
minblock/workcoin
test/functional/test_framework/messages.py
Python
P2PHeaderAndShortIDs
P2PHeaderAndShortIDs
709
748
709
709
bd2fb639d0750fdde074e2cbfe66c5cb46811b9b
bigcode/the-stack
train
d01278759bc1f83602aff866
train
class
class msg_getheaders: __slots__ = ("hashstop", "locator",) command = b"getheaders" def __init__(self): self.locator = CBlockLocator() self.hashstop = 0 def deserialize(self, f): self.locator = CBlockLocator() self.locator.deserialize(f) self.hashstop = deser_uin...
class msg_getheaders:
__slots__ = ("hashstop", "locator",) command = b"getheaders" def __init__(self): self.locator = CBlockLocator() self.hashstop = 0 def deserialize(self, f): self.locator = CBlockLocator() self.locator.deserialize(f) self.hashstop = deser_uint256(f) def seria...
serialize(self): return b"" def __repr__(self): return "msg_sendheaders()" # getheaders message has # number of entries # vector of hashes # hash_stop (hash of last desired block header, 0 to get as many as possible) class msg_getheaders:
64
64
151
5
59
minblock/workcoin
test/functional/test_framework/messages.py
Python
msg_getheaders
msg_getheaders
1,278
1,299
1,278
1,278
63f768ca1aa684c8428615332711c48cc0020e71
bigcode/the-stack
train
b79e0ec068cc009edcd0654f
train
class
class msg_witness_blocktxn(msg_blocktxn): __slots__ = () def serialize(self): r = b"" r += self.block_transactions.serialize(with_witness=True) return r
class msg_witness_blocktxn(msg_blocktxn):
__slots__ = () def serialize(self): r = b"" r += self.block_transactions.serialize(with_witness=True) return r
(f) def serialize(self): r = b"" r += self.block_transactions.serialize(with_witness=False) return r def __repr__(self): return "msg_blocktxn(block_transactions=%s)" % (repr(self.block_transactions)) class msg_witness_blocktxn(msg_blocktxn):
64
64
43
10
54
minblock/workcoin
test/functional/test_framework/messages.py
Python
msg_witness_blocktxn
msg_witness_blocktxn
1,458
1,464
1,458
1,458
8c31d4ebb8c9b3fce04cc8b5a8a9ef4d0221fa5c
bigcode/the-stack
train
daf3bd31d12cf9f5ec0a42bd
train
class
class msg_version: __slots__ = ("addrFrom", "addrTo", "nNonce", "nRelay", "nServices", "nStartingHeight", "nTime", "nVersion", "strSubVer") command = b"version" def __init__(self): self.nVersion = MY_VERSION self.nServices = NODE_NETWORK | NODE_WITNESS self.nTime = ...
class msg_version:
__slots__ = ("addrFrom", "addrTo", "nNonce", "nRelay", "nServices", "nStartingHeight", "nTime", "nVersion", "strSubVer") command = b"version" def __init__(self): self.nVersion = MY_VERSION self.nServices = NODE_NETWORK | NODE_WITNESS self.nTime = int(time.time()) ...
(nTransactions=%d, vHash=%s, vBits=%s)" % (self.nTransactions, repr(self.vHash), repr(self.vBits)) class CMerkleBlock: __slots__ = ("header", "txn") def __init__(self): self.header = CBlockHeader() self.txn = CPartialMerkleTree() def deserialize(self, f): self.header.deserialize(...
171
171
570
4
166
minblock/workcoin
test/functional/test_framework/messages.py
Python
msg_version
msg_version
947
1,003
947
947
4e5d5f0b43ccb73335202ff3b109dfa1e36df2c0
bigcode/the-stack
train
05e0f4a73431e7df364b8ea4
train
function
def deser_string_vector(f): nit = deser_compact_size(f) r = [] for i in range(nit): t = deser_string(f) r.append(t) return r
def deser_string_vector(f):
nit = deser_compact_size(f) r = [] for i in range(nit): t = deser_string(f) r.append(t) return r
i in range(nit): t = deser_uint256(f) r.append(t) return r def ser_uint256_vector(l): r = ser_compact_size(len(l)) for i in l: r += ser_uint256(i) return r def deser_string_vector(f):
64
64
43
6
57
minblock/workcoin
test/functional/test_framework/messages.py
Python
deser_string_vector
deser_string_vector
162
168
162
162
d6f6b053be9770b4c12e316b6ab3ad3493dc2cb2
bigcode/the-stack
train
88d4153840812bf3855cd4de
train
class
class msg_getdata: __slots__ = ("inv",) command = b"getdata" def __init__(self, inv=None): self.inv = inv if inv is not None else [] def deserialize(self, f): self.inv = deser_vector(f, CInv) def serialize(self): return ser_vector(self.inv) def __repr__(self): ...
class msg_getdata:
__slots__ = ("inv",) command = b"getdata" def __init__(self, inv=None): self.inv = inv if inv is not None else [] def deserialize(self, f): self.inv = deser_vector(f, CInv) def serialize(self): return ser_vector(self.inv) def __repr__(self): return "msg_getdat...
: self.inv = inv def deserialize(self, f): self.inv = deser_vector(f, CInv) def serialize(self): return ser_vector(self.inv) def __repr__(self): return "msg_inv(inv=%s)" % (repr(self.inv)) class msg_getdata:
64
64
97
5
59
minblock/workcoin
test/functional/test_framework/messages.py
Python
msg_getdata
msg_getdata
1,060
1,074
1,060
1,060
e4158e5f3f57bc4a2f56e5ac35156eb289e1d479
bigcode/the-stack
train
96942a4683f065505d9d9435
train
class
class CBlock(CBlockHeader): __slots__ = ("vtx",) def __init__(self, header=None): super(CBlock, self).__init__(header) self.vtx = [] def deserialize(self, f): super(CBlock, self).deserialize(f) self.vtx = deser_vector(f, CTransaction) def serialize(self, with_witness=F...
class CBlock(CBlockHeader):
__slots__ = ("vtx",) def __init__(self, header=None): super(CBlock, self).__init__(header) self.vtx = [] def deserialize(self, f): super(CBlock, self).deserialize(f) self.vtx = deser_vector(f, CTransaction) def serialize(self, with_witness=False): r = b"" ...
self.hash = encode(hash256(r)[::-1], 'hex_codec').decode('ascii') self.scrypt256 = uint256_from_str(workcoin_scrypt.getPoWHash(r)) def rehash(self): self.sha256 = None self.scrypt256 = None self.calc_sha256() return self.sha256 def __repr__(self): return "C...
180
180
601
7
173
minblock/workcoin
test/functional/test_framework/messages.py
Python
CBlock
CBlock
603
674
603
603
5079472521e00d66af227bf005755080a2ca893a
bigcode/the-stack
train
ca97bbbc8cdd7affbdfc061f
train
class
class CTransaction: __slots__ = ("hash", "nLockTime", "nVersion", "sha256", "vin", "vout", "wit") def __init__(self, tx=None): if tx is None: self.nVersion = 1 self.vin = [] self.vout = [] self.wit = CTxWitness() self.nLockTim...
class CTransaction:
__slots__ = ("hash", "nLockTime", "nVersion", "sha256", "vin", "vout", "wit") def __init__(self, tx=None): if tx is None: self.nVersion = 1 self.vin = [] self.vout = [] self.wit = CTxWitness() self.nLockTime = 0 se...
self.scriptWitness.stack = deser_string_vector(f) def serialize(self): return ser_string_vector(self.scriptWitness.stack) def __repr__(self): return repr(self.scriptWitness) def is_null(self): return self.scriptWitness.is_null() class CTxWitness: __slots__ = ("vtxinwit",) ...
256
256
984
4
251
minblock/workcoin
test/functional/test_framework/messages.py
Python
CTransaction
CTransaction
416
522
416
416
6a7d0888f7b474824c5385401a60f53910e23a0c
bigcode/the-stack
train
010db2af2aff0f010ce8bb42
train
class
class CTxIn: __slots__ = ("nSequence", "prevout", "scriptSig") def __init__(self, outpoint=None, scriptSig=b"", nSequence=0): if outpoint is None: self.prevout = COutPoint() else: self.prevout = outpoint self.scriptSig = scriptSig self.nSequence = nSequen...
class CTxIn:
__slots__ = ("nSequence", "prevout", "scriptSig") def __init__(self, outpoint=None, scriptSig=b"", nSequence=0): if outpoint is None: self.prevout = COutPoint() else: self.prevout = outpoint self.scriptSig = scriptSig self.nSequence = nSequence def d...
serialize(self): r = b"" r += ser_uint256(self.hash) r += struct.pack("<I", self.n) return r def __repr__(self): return "COutPoint(hash=%064x n=%i)" % (self.hash, self.n) class CTxIn:
67
67
226
5
62
minblock/workcoin
test/functional/test_framework/messages.py
Python
CTxIn
CTxIn
297
324
297
297
6077a035239d0d0c9d38e1b25db731d0c95ad38d
bigcode/the-stack
train
f7a01abbda42cd27534744f4
train
function
def argument_parser(config): delimiter = "_" parser = argparse.ArgumentParser() for key1 in config: for key2 in config[key1]: argument = "--" + key1 + delimiter + key2 _type = type(config[key1][key2]) if (_type == bool): parser.add_argument(argumen...
def argument_parser(config):
delimiter = "_" parser = argparse.ArgumentParser() for key1 in config: for key2 in config[key1]: argument = "--" + key1 + delimiter + key2 _type = type(config[key1][key2]) if (_type == bool): parser.add_argument(argument, help="Refer config.cfg to ...
('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False else: raise argparse.ArgumentTypeError('Boolean value expected.') def argument_parser(config):
63
64
174
5
58
denisergashbaev/memory-augmented-self-play
SelfPlay/utils/argument_parser.py
Python
argument_parser
argument_parser
14
35
14
14
02c4421923ae6587277e393c12fdaf1355b320a0
bigcode/the-stack
train
d094224be032d398d484e902
train
function
def str2bool(v): # Taken from https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False else: raise argparse.ArgumentTypeError('Boole...
def str2bool(v): # Taken from https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse
if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False else: raise argparse.ArgumentTypeError('Boolean value expected.')
import argparse def str2bool(v): # Taken from https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse
32
64
93
29
2
denisergashbaev/memory-augmented-self-play
SelfPlay/utils/argument_parser.py
Python
str2bool
str2bool
4
11
4
5
3a90f3803e64fa62dd0ef291216ae2432982767c
bigcode/the-stack
train
4b1f03ba03526730aa81debc
train
class
class TestErosion(unittest.TestCase): TEST_PATCH_FILENAME = os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../../example_data', 'TestEOPatch') @classmethod def setUpClass(cls): cls.classes = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] def test_eros...
class TestErosion(unittest.TestCase):
TEST_PATCH_FILENAME = os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../../example_data', 'TestEOPatch') @classmethod def setUpClass(cls): cls.classes = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] def test_erosion_value_error(self): self.ass...
""" Credits: Copyright (c) 2017-2019 Matej Aleksandrov, Matej Batič, Andrej Burja, Eva Erzin (Sinergise) Copyright (c) 2017-2019 Grega Milčinski, Matic Lubej, Devis Peresutti, Jernej Puc, Tomislav Slijepčević (Sinergise) Copyright (c) 2017-2019 Blaž Sovdat, Nejc Vesel, Jovan Višnjić, Anže Zupanc, Lojze Žust (Sinergise)...
192
193
645
8
183
rpitonak/eo-learn
geometry/eolearn/tests/test_morphology.py
Python
TestErosion
TestErosion
20
77
20
21
895bf1b51110bb76f950f794434bf89cf9ac1a8d
bigcode/the-stack
train
c083dbf1646f8af462e1576e
train
function
def test_flush_rewind(): stream = BytesIO() with make_simple(stream, mode='w') as f: x = f.createDimension('x',4) # x is used in createVariable v = f.createVariable('v', 'i2', ['x']) v[:] = 1 f.flush() len_single = len(stream.getvalue()) f.flush() len_dou...
def test_flush_rewind():
stream = BytesIO() with make_simple(stream, mode='w') as f: x = f.createDimension('x',4) # x is used in createVariable v = f.createVariable('v', 'i2', ['x']) v[:] = 1 f.flush() len_single = len(stream.getvalue()) f.flush() len_double = len(stream.getvalue...
.append('uint') with netcdf_file(BytesIO(), 'w') as f: f.createDimension('time', N_EG_ELS) for dt in dtypes: assert_raises(ValueError, f.createVariable, 'time', dt, ('time',)) def test_flush_rewind():
64
64
103
6
58
maxi-marufo/my-scipy
scipy/io/tests/test_netcdf.py
Python
test_flush_rewind
test_flush_rewind
282
293
282
282
9e1cc81d1f1ce39a5f7a3f0d058322aafa4a2eee
bigcode/the-stack
train
e579e4962de14f5a8815a7fe
train
function
def test_zero_dimensional_var(): io = BytesIO() with make_simple(io, 'w') as f: v = f.createVariable('zerodim', 'i2', []) # This is checking that .isrec returns a boolean - don't simplify it # to 'assert not ...' assert v.isrec is False, v.isrec f.flush()
def test_zero_dimensional_var():
io = BytesIO() with make_simple(io, 'w') as f: v = f.createVariable('zerodim', 'i2', []) # This is checking that .isrec returns a boolean - don't simplify it # to 'assert not ...' assert v.isrec is False, v.isrec f.flush()
] # should not crash with suppress_warnings() as sup: sup.filter(RuntimeWarning, "Cannot close a netcdf_file opened with mmap=True, when netcdf_variables or arrays referring to its data still exist") x = doit() x.sum() def test_zero_dimensional_var():
64
64
82
7
57
maxi-marufo/my-scipy
scipy/io/tests/test_netcdf.py
Python
test_zero_dimensional_var
test_zero_dimensional_var
353
360
353
353
74ddae6143c2a4e5977b43b8e3fe32bf8a015d50
bigcode/the-stack
train
47010d47736cb72320fb4af1
train
function
def test_read_withFillValNaN(): fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc') with netcdf_file(fname, maskandscale=True) as f: vardata = f.variables['var5_fillvalNaN'][:] assert_mask_matches(vardata, [False, True, False])
def test_read_withFillValNaN():
fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc') with netcdf_file(fname, maskandscale=True) as f: vardata = f.variables['var5_fillvalNaN'][:] assert_mask_matches(vardata, [False, True, False])
_PATH, 'example_3_maskedvals.nc') with netcdf_file(fname, maskandscale=True) as f: vardata = f.variables['var4_missingValue'][:] assert_mask_matches(vardata, [False, True, False]) def test_read_withFillValNaN():
64
64
73
9
55
maxi-marufo/my-scipy
scipy/io/tests/test_netcdf.py
Python
test_read_withFillValNaN
test_read_withFillValNaN
514
518
514
514
3b97742cb5584aaac3a9ce592833a7d56a91cc66
bigcode/the-stack
train
5ffd839fc29e5d4813c6e152
train
function
def test_read_example_data(): # read any example data files for fname in glob(pjoin(TEST_DATA_PATH, '*.nc')): with netcdf_file(fname, 'r'): pass with netcdf_file(fname, 'r', mmap=False): pass
def test_read_example_data(): # read any example data files
for fname in glob(pjoin(TEST_DATA_PATH, '*.nc')): with netcdf_file(fname, 'r'): pass with netcdf_file(fname, 'r', mmap=False): pass
assert_equal(var._get_encoded_fill_value(), b'\x01') var._FillValue = b'\x00\x00' # invalid, wrong size assert_equal(var._get_encoded_fill_value(), b'\x00') def test_read_example_data(): # read any example data files
64
64
57
14
50
maxi-marufo/my-scipy
scipy/io/tests/test_netcdf.py
Python
test_read_example_data
test_read_example_data
230
236
230
231
e59004e83e6e12cc034a5ba4faa134d1d357be0f
bigcode/the-stack
train
e2e08cde71a920909590264c
train
function
def test_append_recordDimension(): dataSize = 100 with in_tempdir(): # Create file with record time dimension with netcdf_file('withRecordDimension.nc', 'w') as f: f.createDimension('time', None) f.createVariable('time', 'd', ('time',)) f.createDimension('x',...
def test_append_recordDimension():
dataSize = 100 with in_tempdir(): # Create file with record time dimension with netcdf_file('withRecordDimension.nc', 'w') as f: f.createDimension('time', None) f.createVariable('time', 'd', ('time',)) f.createDimension('x', dataSize) x = f.create...
f.close() # open again in 'a', read the att and and a new one f = netcdf_file(filename, 'a') assert_equal(f._attributes['Kilroy'], b'was here') f._attributes['naughty'] = b'Zoot' f.close() # open yet again in 'r' and check both atts f = netcdf_file(filename, 'r...
130
130
435
6
124
maxi-marufo/my-scipy
scipy/io/tests/test_netcdf.py
Python
test_append_recordDimension
test_append_recordDimension
399
437
399
399
5ed62deaa5346aaca51b90ecc779a7c74c7aea4e
bigcode/the-stack
train
00fa806107dccf256d0c4068
train
function
def test_read_withMaskAndScaleFalse(): # If a variable has a _FillValue (or missing_value) attribute, but is read # with maskandscale set to False, the result should be unmasked fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc') # Open file with mmap=False to avoid problems with closing a mmap'ed ...
def test_read_withMaskAndScaleFalse(): # If a variable has a _FillValue (or missing_value) attribute, but is read # with maskandscale set to False, the result should be unmasked
fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc') # Open file with mmap=False to avoid problems with closing a mmap'ed file # when arrays referring to its data still exist: with netcdf_file(fname, maskandscale=False, mmap=False) as f: vardata = f.variables['var3_fillvalAndMissingValue'][:...
ata, [[True, False], [False, False], [False, True]]) def test_read_withMaskAndScaleFalse(): # If a variable has a _FillValue (or missing_value) attribute, but is read # with maskandscale set to False, the result should be unmasked
64
64
159
47
17
maxi-marufo/my-scipy
scipy/io/tests/test_netcdf.py
Python
test_read_withMaskAndScaleFalse
test_read_withMaskAndScaleFalse
532
541
532
534
3459150d589fde55a1f9e794648b8ddb9b921724
bigcode/the-stack
train
5f92d547747b64cee5e857eb
train
function
def assert_mask_matches(arr, expected_mask): ''' Asserts that the mask of arr is effectively the same as expected_mask. In contrast to numpy.ma.testutils.assert_mask_equal, this function allows testing the 'mask' of a standard numpy array (the mask in this case is treated as all False). Parame...
def assert_mask_matches(arr, expected_mask):
''' Asserts that the mask of arr is effectively the same as expected_mask. In contrast to numpy.ma.testutils.assert_mask_equal, this function allows testing the 'mask' of a standard numpy array (the mask in this case is treated as all False). Parameters ---------- arr: ndarray or Maske...
time = ncfileobj.variables['time'] assert_equal(time.units, b'days since 2008-01-01') assert_equal(time.shape, (N_EG_ELS,)) assert_equal(time[-1], N_EG_ELS-1) def assert_mask_matches(arr, expected_mask):
64
64
126
9
55
maxi-marufo/my-scipy
scipy/io/tests/test_netcdf.py
Python
assert_mask_matches
assert_mask_matches
46
63
46
46
af9ca92782561367efd35f1d52373e8bfbba9f86
bigcode/the-stack
train
3480ae6e8b80ecda6fc38b47
train
function
def test_read_with2dVar(): fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc') with netcdf_file(fname, maskandscale=True) as f: vardata = f.variables['var7_2d'][:] assert_mask_matches(vardata, [[True, False], [False, False], [False, True]])
def test_read_with2dVar():
fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc') with netcdf_file(fname, maskandscale=True) as f: vardata = f.variables['var7_2d'][:] assert_mask_matches(vardata, [[True, False], [False, False], [False, True]])
(TEST_DATA_PATH, 'example_3_maskedvals.nc') with netcdf_file(fname, maskandscale=True) as f: vardata = f.variables['var6_char'][:] assert_mask_matches(vardata, [False, True, False]) def test_read_with2dVar():
64
64
79
8
56
maxi-marufo/my-scipy
scipy/io/tests/test_netcdf.py
Python
test_read_with2dVar
test_read_with2dVar
526
530
526
526
fdb6670a0a8d3631c07d6bf9d58ee861ace3fee1
bigcode/the-stack
train
af4b5a1507a106a3c66617ef
train
function
def check_simple(ncfileobj): '''Example fileobj tests ''' assert_equal(ncfileobj.history, b'Created for a test') time = ncfileobj.variables['time'] assert_equal(time.units, b'days since 2008-01-01') assert_equal(time.shape, (N_EG_ELS,)) assert_equal(time[-1], N_EG_ELS-1)
def check_simple(ncfileobj):
'''Example fileobj tests ''' assert_equal(ncfileobj.history, b'Created for a test') time = ncfileobj.variables['time'] assert_equal(time.units, b'days since 2008-01-01') assert_equal(time.shape, (N_EG_ELS,)) assert_equal(time[-1], N_EG_ELS-1)
= f.createVariable('time', VARTYPE_EG, ('time',)) time[:] = np.arange(N_EG_ELS) time.units = 'days since 2008-01-01' f.flush() yield f f.close() def check_simple(ncfileobj):
64
64
87
8
56
maxi-marufo/my-scipy
scipy/io/tests/test_netcdf.py
Python
check_simple
check_simple
38
44
38
38
447311208db4f4c166bc6418bea1c41ebb2b3af1
bigcode/the-stack
train
fd3d1c1ea149927d56f1c8a2
train
function
def test_maskandscale(): t = np.linspace(20, 30, 15) t[3] = 100 tm = np.ma.masked_greater(t, 99) fname = pjoin(TEST_DATA_PATH, 'example_2.nc') with netcdf_file(fname, maskandscale=True) as f: Temp = f.variables['Temperature'] assert_equal(Temp.missing_value, 9999) assert_equa...
def test_maskandscale():
t = np.linspace(20, 30, 15) t[3] = 100 tm = np.ma.masked_greater(t, 99) fname = pjoin(TEST_DATA_PATH, 'example_2.nc') with netcdf_file(fname, maskandscale=True) as f: Temp = f.variables['Temperature'] assert_equal(Temp.missing_value, 9999) assert_equal(Temp.add_offset, 20) ...
assert_equal(f.variables['testData'].data.shape[0], i+1) # Read the file and check that 'data' was not saved as user defined # attribute of testData variable during append operation with netcdf_file('withRecordDimension.nc') as f: with assert_raises(KeyError) as ar: ...
106
106
356
6
100
maxi-marufo/my-scipy
scipy/io/tests/test_netcdf.py
Python
test_maskandscale
test_maskandscale
439
473
439
439
001763add1a39e1008ceca2ca8c093bc6653dcf5
bigcode/the-stack
train
8338d8f634bf739fcddb1604
train
function
def test_byte_gatts(): # Check that global "string" atts work like they did before py3k # unicode and general bytes confusion with in_tempdir(): filename = 'g_byte_atts.nc' f = netcdf_file(filename, 'w') f._attributes['holy'] = b'grail' f._attributes['witch'] = 'floats' ...
def test_byte_gatts(): # Check that global "string" atts work like they did before py3k # unicode and general bytes confusion
with in_tempdir(): filename = 'g_byte_atts.nc' f = netcdf_file(filename, 'w') f._attributes['holy'] = b'grail' f._attributes['witch'] = 'floats' f.close() f = netcdf_file(filename, 'r') assert_equal(f._attributes['holy'], b'grail') assert_equal(f._attr...
a boolean - don't simplify it # to 'assert not ...' assert v.isrec is False, v.isrec f.flush() def test_byte_gatts(): # Check that global "string" atts work like they did before py3k # unicode and general bytes confusion
64
64
132
33
31
maxi-marufo/my-scipy
scipy/io/tests/test_netcdf.py
Python
test_byte_gatts
test_byte_gatts
363
375
363
365
6996a85c377b401b462e034d0949fc84f0ab8371
bigcode/the-stack
train
897383cf39d5fb47ec4469b7
train
function
def test_bytes(): raw_file = BytesIO() f = netcdf_file(raw_file, mode='w') # Dataset only has a single variable, dimension and attribute to avoid # any ambiguity related to order. f.a = 'b' f.createDimension('dim', 1) var = f.createVariable('var', np.int16, ('dim',)) var[0] = -9999 v...
def test_bytes():
raw_file = BytesIO() f = netcdf_file(raw_file, mode='w') # Dataset only has a single variable, dimension and attribute to avoid # any ambiguity related to order. f.a = 'b' f.createDimension('dim', 1) var = f.createVariable('var', np.int16, ('dim',)) var[0] = -9999 var.c = 'd' f.s...
io_64, 'w', version=2) as f_64: str_val = eg_sio_64.getvalue() eg_sio_64 = BytesIO(str_val) with netcdf_file(eg_sio_64) as f_64: check_simple(f_64) assert_equal(f_64.version_byte, 2) # also when version 2 explicitly specified eg_sio_64 = BytesIO(str_val) with netcdf_file(eg_...
142
142
474
4
138
maxi-marufo/my-scipy
scipy/io/tests/test_netcdf.py
Python
test_bytes
test_bytes
170
216
170
170
8672161bfe4a00f0d6bad0d69d5e9d18a7047d89
bigcode/the-stack
train
71c706f265dff92fffd07faf
train
function
def test_read_withNoFillValue(): # For a variable with no fill value, reading data with maskandscale=True # should return unmasked data fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc') with netcdf_file(fname, maskandscale=True) as f: vardata = f.variables['var2_noFillval'][:] ass...
def test_read_withNoFillValue(): # For a variable with no fill value, reading data with maskandscale=True # should return unmasked data
fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc') with netcdf_file(fname, maskandscale=True) as f: vardata = f.variables['var2_noFillval'][:] assert_mask_matches(vardata, [False, False, False]) assert_equal(vardata, [1,2,3])
vardata = f.variables['var1_fillval0'][:] assert_mask_matches(vardata, [False, True, False]) def test_read_withNoFillValue(): # For a variable with no fill value, reading data with maskandscale=True # should return unmasked data
64
64
111
34
30
maxi-marufo/my-scipy
scipy/io/tests/test_netcdf.py
Python
test_read_withNoFillValue
test_read_withNoFillValue
487
494
487
489
92a17b399d92c173b1e7e652108c91184bb4fd88
bigcode/the-stack
train
d63a2ff0c38fa4c28c24fbf2
train
function
def test_read_write_sio(): eg_sio1 = BytesIO() with make_simple(eg_sio1, 'w'): str_val = eg_sio1.getvalue() eg_sio2 = BytesIO(str_val) with netcdf_file(eg_sio2) as f2: check_simple(f2) # Test that error is raised if attempting mmap for sio eg_sio3 = BytesIO(str_val) assert_...
def test_read_write_sio():
eg_sio1 = BytesIO() with make_simple(eg_sio1, 'w'): str_val = eg_sio1.getvalue() eg_sio2 = BytesIO(str_val) with netcdf_file(eg_sio2) as f2: check_simple(f2) # Test that error is raised if attempting mmap for sio eg_sio3 = BytesIO(str_val) assert_raises(ValueError, netcdf_f...
that app_var made it in... with netcdf_file('simple.nc') as f: check_simple(f) assert_equal(f.variables['app_var'][:], 42) except: # noqa: E722 os.chdir(cwd) shutil.rmtree(tmpdir) raise os.chdir(cwd) shutil.rmtree(tmpdir) def test_read_write_sio():
84
84
283
7
77
maxi-marufo/my-scipy
scipy/io/tests/test_netcdf.py
Python
test_read_write_sio
test_read_write_sio
142
167
142
142
b957f2ea8406cee467fad9d8476e1602f22cad1e
bigcode/the-stack
train
08190a91288b9e9c1afd3db9
train
function
def test_appending_issue_gh_8625(): stream = BytesIO() with make_simple(stream, mode='w') as f: f.createDimension('x', 2) f.createVariable('x', float, ('x',)) f.variables['x'][...] = 1 f.flush() contents = stream.getvalue() stream = BytesIO(contents) with netcdf...
def test_appending_issue_gh_8625():
stream = BytesIO() with make_simple(stream, mode='w') as f: f.createDimension('x', 2) f.createVariable('x', float, ('x',)) f.variables['x'][...] = 1 f.flush() contents = stream.getvalue() stream = BytesIO(contents) with netcdf_file(stream, mode='a') as f: ...
'r', mmap=True) as f: time_var = f.variables['time'] # time_var.assignValue(42) should raise a RuntimeError--not seg. fault! assert_raises(RuntimeError, time_var.assignValue, 42) def test_appending_issue_gh_8625():
64
64
107
11
53
maxi-marufo/my-scipy
scipy/io/tests/test_netcdf.py
Python
test_appending_issue_gh_8625
test_appending_issue_gh_8625
254
266
254
254
0fbcf07f63641a969ec2304cf2dd74e8326e28fe
bigcode/the-stack
train
db747b2193ddbf08aeda995c
train
function
def test_read_withMissingValue(): # For a variable with missing_value but not _FillValue, the missing_value # should be used fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc') with netcdf_file(fname, maskandscale=True) as f: vardata = f.variables['var4_missingValue'][:] assert_mask...
def test_read_withMissingValue(): # For a variable with missing_value but not _FillValue, the missing_value # should be used
fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc') with netcdf_file(fname, maskandscale=True) as f: vardata = f.variables['var4_missingValue'][:] assert_mask_matches(vardata, [False, True, False])
_mask_matches(vardata, [True, False, False]) assert_equal(vardata, [IRRELEVANT_VALUE, 2, 3]) def test_read_withMissingValue(): # For a variable with missing_value but not _FillValue, the missing_value # should be used
64
64
93
31
33
maxi-marufo/my-scipy
scipy/io/tests/test_netcdf.py
Python
test_read_withMissingValue
test_read_withMissingValue
506
512
506
508
f146bffc791b18d6631b649fe08b126965f99bbc
bigcode/the-stack
train
047c4c373f72a0e605c06f48
train
function
def test_mmaps_segfault(): filename = pjoin(TEST_DATA_PATH, 'example_1.nc') if not IS_PYPY: with warnings.catch_warnings(): warnings.simplefilter("error") with netcdf_file(filename, mmap=True) as f: x = f.variables['lat'][:] # should not raise war...
def test_mmaps_segfault():
filename = pjoin(TEST_DATA_PATH, 'example_1.nc') if not IS_PYPY: with warnings.catch_warnings(): warnings.simplefilter("error") with netcdf_file(filename, mmap=True) as f: x = f.variables['lat'][:] # should not raise warnings del x...
: assert_equal(f.history, b'Created for a test') float_var = f.variables['float_var'] assert_equal(float_var.units, b'metres') assert_equal(float_var.shape, (10,)) assert_allclose(float_var[:], items) def test_mmaps_segfault():
64
64
161
8
56
maxi-marufo/my-scipy
scipy/io/tests/test_netcdf.py
Python
test_mmaps_segfault
test_mmaps_segfault
330
350
330
330
0e5272dc6a928b39bdd17b35938db2ae486a151e
bigcode/the-stack
train
5c8c1676cc4ceef17730b4ae
train
function
def test_read_withChar(): fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc') with netcdf_file(fname, maskandscale=True) as f: vardata = f.variables['var6_char'][:] assert_mask_matches(vardata, [False, True, False])
def test_read_withChar():
fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc') with netcdf_file(fname, maskandscale=True) as f: vardata = f.variables['var6_char'][:] assert_mask_matches(vardata, [False, True, False])
_DATA_PATH, 'example_3_maskedvals.nc') with netcdf_file(fname, maskandscale=True) as f: vardata = f.variables['var5_fillvalNaN'][:] assert_mask_matches(vardata, [False, True, False]) def test_read_withChar():
64
64
67
6
58
maxi-marufo/my-scipy
scipy/io/tests/test_netcdf.py
Python
test_read_withChar
test_read_withChar
520
524
520
520
822b93839f86f61660537289325db85dbf60172c
bigcode/the-stack
train
2a61095447e30dd569f8e375
train
function
def test_encoded_fill_value(): with netcdf_file(BytesIO(), mode='w') as f: f.createDimension('x', 1) var = f.createVariable('var', 'S1', ('x',)) assert_equal(var._get_encoded_fill_value(), b'\x00') var._FillValue = b'\x01' assert_equal(var._get_encoded_fill_value(), b'\x01') ...
def test_encoded_fill_value():
with netcdf_file(BytesIO(), mode='w') as f: f.createDimension('x', 1) var = f.createVariable('var', 'S1', ('x',)) assert_equal(var._get_encoded_fill_value(), b'\x00') var._FillValue = b'\x01' assert_equal(var._get_encoded_fill_value(), b'\x01') var._FillValue = b'\x00...
\x00' b'\x00\x00\x00\x03' b'\x00\x00\x00\x04' b'\x00\x00\x00\x78' b'\xd8\xf1\x80\x01') assert_equal(actual, expected) def test_encoded_fill_value():
64
64
124
6
58
maxi-marufo/my-scipy
scipy/io/tests/test_netcdf.py
Python
test_encoded_fill_value
test_encoded_fill_value
219
227
219
219
6764b7af54a94f2bf2045789a638097176fc8f8a
bigcode/the-stack
train
d81ef07bb2ee3e13daee4d76
train
function
def test_itemset_no_segfault_on_readonly(): # Regression test for ticket #1202. # Open the test file in read-only mode. filename = pjoin(TEST_DATA_PATH, 'example_1.nc') with suppress_warnings() as sup: sup.filter(RuntimeWarning, "Cannot close a netcdf_file opened with mmap=Tr...
def test_itemset_no_segfault_on_readonly(): # Regression test for ticket #1202. # Open the test file in read-only mode.
filename = pjoin(TEST_DATA_PATH, 'example_1.nc') with suppress_warnings() as sup: sup.filter(RuntimeWarning, "Cannot close a netcdf_file opened with mmap=True, when netcdf_variables or arrays referring to its data still exist") with netcdf_file(filename, 'r', mmap=True) as f: ...
nc')): with netcdf_file(fname, 'r'): pass with netcdf_file(fname, 'r', mmap=False): pass def test_itemset_no_segfault_on_readonly(): # Regression test for ticket #1202. # Open the test file in read-only mode.
64
64
149
33
30
maxi-marufo/my-scipy
scipy/io/tests/test_netcdf.py
Python
test_itemset_no_segfault_on_readonly
test_itemset_no_segfault_on_readonly
239
251
239
242
67932992e8f37ae99b606efa078eebe9251fb469
bigcode/the-stack
train
cc6d0c81d22f23873028e6cc
train
function
def test_ticket_1720(): io = BytesIO() items = [0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9] with netcdf_file(io, 'w') as f: f.history = 'Created for a test' f.createDimension('float_var', 10) float_var = f.createVariable('float_var', 'f', ('float_var',)) float_var[:] = items ...
def test_ticket_1720():
io = BytesIO() items = [0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9] with netcdf_file(io, 'w') as f: f.history = 'Created for a test' f.createDimension('float_var', 10) float_var = f.createVariable('float_var', 'f', ('float_var',)) float_var[:] = items float_var.units = '...
f.createDimension('x',4) f.createVariable('v1', 'i2', ['x']) f.createVariable('v2', np.int16, ['x']) f.createVariable('v3', np.dtype(np.int16), ['x']) def test_ticket_1720():
63
64
210
7
56
maxi-marufo/my-scipy
scipy/io/tests/test_netcdf.py
Python
test_ticket_1720
test_ticket_1720
307
327
307
307
468c64faf1608062b732cac798d8565c91e38429
bigcode/the-stack
train
46f4c5b8099277cbaabe0ad3
train
function
def test_open_append(): # open 'w' put one attr with in_tempdir(): filename = 'append_dat.nc' f = netcdf_file(filename, 'w') f._attributes['Kilroy'] = 'was here' f.close() # open again in 'a', read the att and and a new one f = netcdf_file(filename, 'a') ...
def test_open_append(): # open 'w' put one attr
with in_tempdir(): filename = 'append_dat.nc' f = netcdf_file(filename, 'w') f._attributes['Kilroy'] = 'was here' f.close() # open again in 'a', read the att and and a new one f = netcdf_file(filename, 'a') assert_equal(f._attributes['Kilroy'], b'was here') ...
ats' f.close() f = netcdf_file(filename, 'r') assert_equal(f._attributes['holy'], b'grail') assert_equal(f._attributes['witch'], b'floats') f.close() def test_open_append(): # open 'w' put one attr
64
64
178
15
49
maxi-marufo/my-scipy
scipy/io/tests/test_netcdf.py
Python
test_open_append
test_open_append
378
396
378
379
de73f0ee7b0cc38f6e0d500b3010a8b65f58d848
bigcode/the-stack
train
7504012ff6bd22bbfbab123a
train
function
@contextmanager def make_simple(*args, **kwargs): f = netcdf_file(*args, **kwargs) f.history = 'Created for a test' f.createDimension('time', N_EG_ELS) time = f.createVariable('time', VARTYPE_EG, ('time',)) time[:] = np.arange(N_EG_ELS) time.units = 'days since 2008-01-01' f.flush() yiel...
@contextmanager def make_simple(*args, **kwargs):
f = netcdf_file(*args, **kwargs) f.history = 'Created for a test' f.createDimension('time', N_EG_ELS) time = f.createVariable('time', VARTYPE_EG, ('time',)) time[:] = np.arange(N_EG_ELS) time.units = 'days since 2008-01-01' f.flush() yield f f.close()
in_tempdir TEST_DATA_PATH = pjoin(dirname(__file__), 'data') N_EG_ELS = 11 # number of elements for example variable VARTYPE_EG = 'b' # var type for example variable @contextmanager def make_simple(*args, **kwargs):
64
64
106
13
50
maxi-marufo/my-scipy
scipy/io/tests/test_netcdf.py
Python
make_simple
make_simple
25
35
25
26
5befebe85154c6ba53e185233943103ab9f21faa
bigcode/the-stack
train
47f0e5eb4f939faa284539c2
train
function
def test_write_invalid_dtype(): dtypes = ['int64', 'uint64'] if np.dtype('int').itemsize == 8: # 64-bit machines dtypes.append('int') if np.dtype('uint').itemsize == 8: # 64-bit machines dtypes.append('uint') with netcdf_file(BytesIO(), 'w') as f: f.createDimension('time', N...
def test_write_invalid_dtype():
dtypes = ['int64', 'uint64'] if np.dtype('int').itemsize == 8: # 64-bit machines dtypes.append('int') if np.dtype('uint').itemsize == 8: # 64-bit machines dtypes.append('uint') with netcdf_file(BytesIO(), 'w') as f: f.createDimension('time', N_EG_ELS) for dt in dtype...
('x',)) f.variables['x'][...] = 1 f.flush() contents = stream.getvalue() stream = BytesIO(contents) with netcdf_file(stream, mode='a') as f: f.variables['x'][...] = 2 def test_write_invalid_dtype():
64
64
126
6
57
maxi-marufo/my-scipy
scipy/io/tests/test_netcdf.py
Python
test_write_invalid_dtype
test_write_invalid_dtype
269
279
269
269
ecbb6276b35dd3015f6127adbc61aad012cf9d24
bigcode/the-stack
train
a447536266acc1dc49f67f78
train
function
def test_read_write_files(): # test round trip for example file cwd = os.getcwd() try: tmpdir = tempfile.mkdtemp() os.chdir(tmpdir) with make_simple('simple.nc', 'w') as f: pass # read the file we just created in 'a' mode with netcdf_file('simple.nc', 'a')...
def test_read_write_files(): # test round trip for example file
cwd = os.getcwd() try: tmpdir = tempfile.mkdtemp() os.chdir(tmpdir) with make_simple('simple.nc', 'w') as f: pass # read the file we just created in 'a' mode with netcdf_file('simple.nc', 'a') as f: check_simple(f) # add something ...
.history, b'Created for a test') time = ncfileobj.variables['time'] assert_equal(time.units, b'days since 2008-01-01') assert_equal(time.shape, (N_EG_ELS,)) assert_equal(time[-1], N_EG_ELS-1) def assert_mask_matches(arr, expected_mask): ''' Asserts that the mask of arr is effectively the same a...
206
206
687
15
191
maxi-marufo/my-scipy
scipy/io/tests/test_netcdf.py
Python
test_read_write_files
test_read_write_files
66
139
66
67
737ba4f258681744a5afbc566d925e806e75ac22
bigcode/the-stack
train
94d67329a5ce03a9e2f49c8f
train
function
def test_read_withValuesNearFillValue(): # Regression test for ticket #5626 fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc') with netcdf_file(fname, maskandscale=True) as f: vardata = f.variables['var1_fillval0'][:] assert_mask_matches(vardata, [False, True, False])
def test_read_withValuesNearFillValue(): # Regression test for ticket #5626
fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc') with netcdf_file(fname, maskandscale=True) as f: vardata = f.variables['var1_fillval0'][:] assert_mask_matches(vardata, [False, True, False])
.compressed(), 2) found = Temp[:].compressed() del Temp assert_allclose(found, expected) # ------------------------------------------------------------------------ # Test reading with masked values (_FillValue / missing_value) # -----------------------------------------------------...
64
64
82
19
45
maxi-marufo/my-scipy
scipy/io/tests/test_netcdf.py
Python
test_read_withValuesNearFillValue
test_read_withValuesNearFillValue
480
485
480
481
0afac340ab151f348966dc92ea310dd30dbde872
bigcode/the-stack
train
7130d40dfbc66b4a6e1375d8
train
function
def test_dtype_specifiers(): # Numpy 1.7.0-dev had a bug where 'i2' wouldn't work. # Specifying np.int16 or similar only works from the same commit as this # comment was made. with make_simple(BytesIO(), mode='w') as f: f.createDimension('x',4) f.createVariable('v1', 'i2', ['x']) ...
def test_dtype_specifiers(): # Numpy 1.7.0-dev had a bug where 'i2' wouldn't work. # Specifying np.int16 or similar only works from the same commit as this # comment was made.
with make_simple(BytesIO(), mode='w') as f: f.createDimension('x',4) f.createVariable('v1', 'i2', ['x']) f.createVariable('v2', np.int16, ['x']) f.createVariable('v3', np.dtype(np.int16), ['x'])
.getvalue()) assert_(len_single == len_double) def test_dtype_specifiers(): # Numpy 1.7.0-dev had a bug where 'i2' wouldn't work. # Specifying np.int16 or similar only works from the same commit as this # comment was made.
64
64
122
52
12
maxi-marufo/my-scipy
scipy/io/tests/test_netcdf.py
Python
test_dtype_specifiers
test_dtype_specifiers
296
304
296
299
caecb7d6215c0af29c3b5e8bbd62ce7388d1bc07
bigcode/the-stack
train
b5142c572b2e0cc4ea9e45d9
train
function
def test_read_withFillValueAndMissingValue(): # For a variable with both _FillValue and missing_value, the _FillValue # should be used IRRELEVANT_VALUE = 9999 fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc') with netcdf_file(fname, maskandscale=True) as f: vardata = f.variables['var3...
def test_read_withFillValueAndMissingValue(): # For a variable with both _FillValue and missing_value, the _FillValue # should be used
IRRELEVANT_VALUE = 9999 fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc') with netcdf_file(fname, maskandscale=True) as f: vardata = f.variables['var3_fillvalAndMissingValue'][:] assert_mask_matches(vardata, [True, False, False]) assert_equal(vardata, [IRRELEVANT_VALUE, 2, 3])...
assert_mask_matches(vardata, [False, False, False]) assert_equal(vardata, [1,2,3]) def test_read_withFillValueAndMissingValue(): # For a variable with both _FillValue and missing_value, the _FillValue # should be used
64
64
131
35
29
maxi-marufo/my-scipy
scipy/io/tests/test_netcdf.py
Python
test_read_withFillValueAndMissingValue
test_read_withFillValueAndMissingValue
496
504
496
498
cf635ea0ef3ade58d82b84de41b4b98aa4ce5d3d
bigcode/the-stack
train
d66f3df789250db0e9aa5f23
train
function
def _center_scale_xy(X, Y, scale=True): """ Center X, Y and scale if the scale parameter==True Returns ------- X, Y, x_mean, y_mean, x_std, y_std """ # center x_mean = X.mean(axis=0) X -= x_mean y_mean = Y.mean(axis=0) Y -= y_mean # scale if scale: x_std = X....
def _center_scale_xy(X, Y, scale=True):
""" Center X, Y and scale if the scale parameter==True Returns ------- X, Y, x_mean, y_mean, x_std, y_std """ # center x_mean = X.mean(axis=0) X -= x_mean y_mean = Y.mean(axis=0) Y -= y_mean # scale if scale: x_std = X.std(axis=0, ddof=1) x_std[x_std ...
): C = np.dot(X.T, Y) U, s, Vh = svd(C, full_matrices=False) u = U[:, [0]] v = Vh.T[:, [0]] return u, v def _center_scale_xy(X, Y, scale=True):
64
64
214
12
51
haniamatera/cds-visual_new
Assignment4/mypython/lib/python2.7/site-packages/sklearn/cross_decomposition/pls_.py
Python
_center_scale_xy
_center_scale_xy
94
117
94
94
d71fed56f9e0eda386d7646cff008608ab2eb250
bigcode/the-stack
train
3a1f2f7f93317b49b37035a9
train
class
class PLSRegression(_PLS): """PLS regression PLSRegression implements the PLS 2 blocks regression known as PLS2 or PLS1 in case of one dimensional response. This class inherits from _PLS with mode="A", deflation_mode="regression", norm_y_weights=False and algorithm="nipals". Read more in the :...
class PLSRegression(_PLS):
"""PLS regression PLSRegression implements the PLS 2 blocks regression known as PLS2 or PLS1 in case of one dimensional response. This class inherits from _PLS with mode="A", deflation_mode="regression", norm_y_weights=False and algorithm="nipals". Read more in the :ref:`User Guide <cross_deco...
-place normalization. Notes ----- This call requires the estimation of a p x q matrix, which may be an issue in high dimensional space. """ check_is_fitted(self, 'x_mean_') X = check_array(X, copy=copy, dtype=FLOAT_DTYPES) # Normalize X -= self.x_...
256
256
1,195
8
248
haniamatera/cds-visual_new
Assignment4/mypython/lib/python2.7/site-packages/sklearn/cross_decomposition/pls_.py
Python
PLSRegression
PLSRegression
464
601
464
464
33d976bf9155c43c70240d940c5688179579b7d1
bigcode/the-stack
train
6bed8104be0f946c0679c9b0
train
class
class PLSCanonical(_PLS): """ PLSCanonical implements the 2 blocks canonical PLS of the original Wold algorithm [Tenenhaus 1998] p.204, referred as PLS-C2A in [Wegelin 2000]. This class inherits from PLS with mode="A" and deflation_mode="canonical", norm_y_weights=True and algorithm="nipals", but svd s...
class PLSCanonical(_PLS):
""" PLSCanonical implements the 2 blocks canonical PLS of the original Wold algorithm [Tenenhaus 1998] p.204, referred as PLS-C2A in [Wegelin 2000]. This class inherits from PLS with mode="A" and deflation_mode="canonical", norm_y_weights=True and algorithm="nipals", but svd should provide similar ...
pls2 = PLSRegression(n_components=2) >>> pls2.fit(X, Y) ... # doctest: +NORMALIZE_WHITESPACE PLSRegression(copy=True, max_iter=500, n_components=2, scale=True, tol=1e-06) >>> Y_pred = pls2.predict(X) References ---------- Jacob A. Wegelin. A survey of Partial Least Squares (PL...
256
256
1,326
8
248
haniamatera/cds-visual_new
Assignment4/mypython/lib/python2.7/site-packages/sklearn/cross_decomposition/pls_.py
Python
PLSCanonical
PLSCanonical
604
747
604
604
c8d01f2703be0a7862e8a7d9581c8fc86164b014
bigcode/the-stack
train
31e1923b2e8e0c4c2b666313
train
class
class _PLS(six.with_metaclass(ABCMeta), BaseEstimator, TransformerMixin, RegressorMixin): """Partial Least Squares (PLS) This class implements the generic PLS algorithm, constructors' parameters allow to obtain a specific implementation such as: - PLS2 regression, i.e., PLS 2 blocks, mode A...
class _PLS(six.with_metaclass(ABCMeta), BaseEstimator, TransformerMixin, RegressorMixin):
"""Partial Least Squares (PLS) This class implements the generic PLS algorithm, constructors' parameters allow to obtain a specific implementation such as: - PLS2 regression, i.e., PLS 2 blocks, mode A, with asymmetric deflation and unnormalized y weights such as defined by [Tenenhaus 1998] p. 1...
]] v = Vh.T[:, [0]] return u, v def _center_scale_xy(X, Y, scale=True): """ Center X, Y and scale if the scale parameter==True Returns ------- X, Y, x_mean, y_mean, x_std, y_std """ # center x_mean = X.mean(axis=0) X -= x_mean y_mean = Y.mean(axis=0) Y -= y_mean ...
256
256
3,294
25
230
haniamatera/cds-visual_new
Assignment4/mypython/lib/python2.7/site-packages/sklearn/cross_decomposition/pls_.py
Python
_PLS
_PLS
120
461
120
121
06b304a91d207fe062d869e16fce6f7c783b8b27
bigcode/the-stack
train
9300b822fd68a458611b5e5a
train
function
def _svd_cross_product(X, Y): C = np.dot(X.T, Y) U, s, Vh = svd(C, full_matrices=False) u = U[:, [0]] v = Vh.T[:, [0]] return u, v
def _svd_cross_product(X, Y):
C = np.dot(X.T, Y) U, s, Vh = svd(C, full_matrices=False) u = U[:, [0]] v = Vh.T[:, [0]] return u, v
1: break if ite == max_iter: warnings.warn('Maximum number of iterations reached', ConvergenceWarning) break x_weights_old = x_weights ite += 1 return x_weights, y_weights, ite def _svd_cross_product(X, Y):
64
64
61
10
53
haniamatera/cds-visual_new
Assignment4/mypython/lib/python2.7/site-packages/sklearn/cross_decomposition/pls_.py
Python
_svd_cross_product
_svd_cross_product
86
91
86
86
e345be3cfa2d05ea6eafa2b7e5efd463c8eb9193
bigcode/the-stack
train
7fb743a67865796179e3567c
train
function
def _nipals_twoblocks_inner_loop(X, Y, mode="A", max_iter=500, tol=1e-06, norm_y_weights=False): """Inner loop of the iterative NIPALS algorithm. Provides an alternative to the svd(X'Y); returns the first left and right singular vectors of X'Y. See PLS for the meaning of t...
def _nipals_twoblocks_inner_loop(X, Y, mode="A", max_iter=500, tol=1e-06, norm_y_weights=False):
"""Inner loop of the iterative NIPALS algorithm. Provides an alternative to the svd(X'Y); returns the first left and right singular vectors of X'Y. See PLS for the meaning of the parameters. It is similar to the Power method for determining the eigenvectors and eigenvalues of a X'Y. """ y...
""" The :mod:`sklearn.pls` module implements Partial Least Squares (PLS). """ # Author: Edouard Duchesnay <edouard.duchesnay@cea.fr> # License: BSD 3 clause import warnings from abc import ABCMeta, abstractmethod import numpy as np from scipy.linalg import pinv2, svd from scipy.sparse.linalg import svds from ..base...
205
206
687
35
170
haniamatera/cds-visual_new
Assignment4/mypython/lib/python2.7/site-packages/sklearn/cross_decomposition/pls_.py
Python
_nipals_twoblocks_inner_loop
_nipals_twoblocks_inner_loop
25
83
25
26
a455e37efcbbedacde812e7e7bc9272a96398ef9
bigcode/the-stack
train
7de108de7a162bead72e181e
train
class
class PLSSVD(BaseEstimator, TransformerMixin): """Partial Least Square SVD Simply perform a svd on the crosscovariance matrix: X'Y There are no iterative deflation here. Read more in the :ref:`User Guide <cross_decomposition>`. Parameters ---------- n_components : int, default 2 N...
class PLSSVD(BaseEstimator, TransformerMixin):
"""Partial Least Square SVD Simply perform a svd on the crosscovariance matrix: X'Y There are no iterative deflation here. Read more in the :ref:`User Guide <cross_decomposition>`. Parameters ---------- n_components : int, default 2 Number of components to keep. scale : boole...
_WHITESPACE PLSCanonical(algorithm='nipals', copy=True, max_iter=500, n_components=2, scale=True, tol=1e-06) >>> X_c, Y_c = plsca.transform(X, Y) References ---------- Jacob A. Wegelin. A survey of Partial Least Squares (PLS) methods, with emphasis on the two-block case. Techn...
256
256
1,322
10
246
haniamatera/cds-visual_new
Assignment4/mypython/lib/python2.7/site-packages/sklearn/cross_decomposition/pls_.py
Python
PLSSVD
PLSSVD
750
905
750
750
e3b4b202c2c13b1b0a7841e06a9754330281f5d5
bigcode/the-stack
train
e78cc7dd2fd311c77a1f91ab
train
class
class Reporter(object): """Report results of deployments to pipeline""" def __init__(self, config, session): self._environment = config.environment self._infrastructure = config.infrastructure self._session = session self._callback_urls = {} self._logger = logging.getLogg...
class Reporter(object):
"""Report results of deployments to pipeline""" def __init__(self, config, session): self._environment = config.environment self._infrastructure = config.infrastructure self._session = session self._callback_urls = {} self._logger = logging.getLogger(__name__) sig...
with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or i...
152
152
508
4
147
ariadnarouco/fiaas-deploy-daemon
fiaas_deploy_daemon/pipeline/reporter.py
Python
Reporter
Reporter
29
70
29
29
255f8c035fda4cc52d6720fe3ac4dcf1ad06b86c
bigcode/the-stack
train
1fbca1e94a9a63d74da12a34
train
function
def letterAsASCII(digits) -> int: res = 0 for i in range(len(digits)): res = res + digits[i] * 10 ** (len(digits) - i - 1) return res
def letterAsASCII(digits) -> int:
res = 0 for i in range(len(digits)): res = res + digits[i] * 10 ** (len(digits) - i - 1) return res
3)) print(sorted(lines_4)) print(len(lines_2)) print(len(lines_3)) print(len(lines_4)) print(len(lines)) print(len(lines_2) + len(lines_3) + len(lines_4)) def letterAsASCII(digits) -> int:
64
64
52
10
54
fly2plan/FPL-baseline
server/baseline/privacy/circuits/validation/nationality_codes.py
Python
letterAsASCII
letterAsASCII
20
24
20
20
933cbfaa8cf636ecc72f4a31331cd0003962cc06
bigcode/the-stack
train
dbafdf3855a2320d40ebea16
train
function
def p_sel_tourn(p): return p["selection"] == "tournament"
def p_sel_tourn(p):
return p["selection"] == "tournament"
ational(p): return p["evolutionMode"] == "generational" def p_steadyState(p): return p["evolutionMode"] == "steadyState" def p_sel_lexicase(p): return p["selection"] == "lexicase" def p_sel_tourn(p):
64
64
18
7
57
iwob/evoplotter
app/gpem19/gpem19_processor_expA.py
Python
p_sel_tourn
p_sel_tourn
82
83
82
82
fe0ea2b8f3e9a193802b3f99c398667d20f78ce9
bigcode/the-stack
train
18ae2766b0dfd036a69cdc0b
train
function
def create_single_table_bundle(props, dim_rows, dim_cols, cellLambda, headerRowNames, cv0, cv1, cv2, vb=1, tableVariants=None, onlyNonemptyRows=True, tablePostprocessor=post, printTextTable=False, middle_col_align="c"): if tableVariants is None: ...
def create_single_table_bundle(props, dim_rows, dim_cols, cellLambda, headerRowNames, cv0, cv1, cv2, vb=1, tableVariants=None, onlyNonemptyRows=True, tablePostprocessor=post, printTextTable=False, middle_col_align="c"):
if tableVariants is None: tableVariants = [p_true] assert isinstance(tableVariants, list) text = "" for variant in tableVariants: # each variant is some predicate on data props_variant = [p for p in props if variant(p)] if onlyNonemptyRows: dim_rows_variant = Dim([c...
(reporting.FloatFigure(f)) section.add(reporting.BlockLatex(r"\vspace{1cm}" + "\n")) return section def create_single_table_bundle(props, dim_rows, dim_cols, cellLambda, headerRowNames, cv0, cv1, cv2, vb=1, tableVariants=None, onlyNonemptyRows=True, tablePostprocessor=post, ...
92
92
309
62
29
iwob/evoplotter
app/gpem19/gpem19_processor_expA.py
Python
create_single_table_bundle
create_single_table_bundle
178
205
178
180
47a67deeeeaf58eb08f41849a93cf8e2588b749a
bigcode/the-stack
train
91da567831ecf0a551a7ad02
train
function
def p_testsRatio_equalTo(ratio): return lambda p, ratio=ratio: p["testsRatio"] == ratio
def p_testsRatio_equalTo(ratio):
return lambda p, ratio=ratio: p["testsRatio"] == ratio
State(p): return p["evolutionMode"] == "steadyState" def p_sel_lexicase(p): return p["selection"] == "lexicase" def p_sel_tourn(p): return p["selection"] == "tournament" def p_testsRatio_equalTo(ratio):
64
64
26
9
55
iwob/evoplotter
app/gpem19/gpem19_processor_expA.py
Python
p_testsRatio_equalTo
p_testsRatio_equalTo
84
85
84
84
60f59e3c41ba06deabd0b99de4b062b33d571db5
bigcode/the-stack
train
b9460d9bdd54d1411613944b
train
function
def create_subsection_aggregation_tests(props, dim_rows, dim_cols, headerRowNames): vb = 1 # vertical border variants = None dim_rows_v2 = get_benchmarks_from_props(props, ignoreNumTests=True) dim_rows_v2 += dim_true # By default: dim_cols = (dim_methodGP * dim_empty + dim_methodCDGP * dim_testsRa...
def create_subsection_aggregation_tests(props, dim_rows, dim_cols, headerRowNames):
vb = 1 # vertical border variants = None dim_rows_v2 = get_benchmarks_from_props(props, ignoreNumTests=True) dim_rows_v2 += dim_true # By default: dim_cols = (dim_methodGP * dim_empty + dim_methodCDGP * dim_testsRatio) * dim_optThreshold tables = [ # TableGenerator(fun_successRateMseO...
= [p_true] assert isinstance(tableVariants, list) text = "" for variant in tableVariants: # each variant is some predicate on data props_variant = [p for p in props if variant(p)] if onlyNonemptyRows: dim_rows_variant = Dim([c for c in dim_rows.configs if len(c.filter_props(pr...
256
256
1,088
19
236
iwob/evoplotter
app/gpem19/gpem19_processor_expA.py
Python
create_subsection_aggregation_tests
create_subsection_aggregation_tests
209
309
209
209
a660815fe729d60d0a5250c83c26871aa0bfaacf
bigcode/the-stack
train
e52a2d3f493703e3d3f840f4
train
function
def p_dict_matcher(d): assert isinstance(d, dict) d = d.copy() return lambda p, d=d: p_matches_dict(p, d)
def p_dict_matcher(d):
assert isinstance(d, dict) d = d.copy() return lambda p, d=d: p_matches_dict(p, d)
_matches_dict(p, d): for k, v in d.items(): if k not in p: return False # throw here an exception if you know that p should always contain k if p[k] != v: return False return True def p_dict_matcher(d):
64
64
35
7
56
iwob/evoplotter
app/gpem19/gpem19_processor_expA.py
Python
p_dict_matcher
p_dict_matcher
72
75
72
72
55c461447d29e51357874f6dd6a356118c5858ce
bigcode/the-stack
train
af1372e56f792c1a89002555
train
function
def simplify_benchmark_name(name): """Shortens or modifies the path of the benchmark in order to make the table more readable.""" i = name.rfind("/") name = name.replace("resistance_par", "res") name = name if i == -1 else name[i+1:] name = name[:name.rfind(".")] # cut off '.sl' name = name[:na...
def simplify_benchmark_name(name):
"""Shortens or modifies the path of the benchmark in order to make the table more readable.""" i = name.rfind("/") name = name.replace("resistance_par", "res") name = name if i == -1 else name[i+1:] name = name[:name.rfind(".")] # cut off '.sl' name = name[:name.rfind("_")] # cut off number of...
oplotter import utils from evoplotter import plotter from evoplotter import printer from evoplotter import templates from evoplotter import reporting from evoplotter.dims import * from evoplotter.templates import * def simplify_benchmark_name(name):
63
64
121
7
56
iwob/evoplotter
app/gpem19/gpem19_processor_expA.py
Python
simplify_benchmark_name
simplify_benchmark_name
13
21
13
13
b8fa77b2e5aba27eb7eb3aae7837128b70acc0bc
bigcode/the-stack
train
b508d74c99e0b4633355a38d
train
function
def get_content_of_subsections(subsects): content = [] vspace = reporting.BlockLatex(r"\vspace{0.75cm}"+"\n") for title, table, cs in subsects: if isinstance(cs, reporting.ColorScheme3): cs = cs.toBlockLatex() sub = reporting.SectionRelative(title, contents=[cs, reporting.BlockLa...
def get_content_of_subsections(subsects):
content = [] vspace = reporting.BlockLatex(r"\vspace{0.75cm}"+"\n") for title, table, cs in subsects: if isinstance(cs, reporting.ColorScheme3): cs = cs.toBlockLatex() sub = reporting.SectionRelative(title, contents=[cs, reporting.BlockLatex(table + "\n"), vspace]) conten...
p_dict_matcher({"partialConstraintsWeight": "5"}), benchmarkNumTests="5"), ]) # variants_benchmarkNumTests = [p_dict_matcher({"sizeTrainSet": "10"}), p_dict_matcher({"sizeTrainSet": "100"})] def get_content_of_subsections(subsects):
63
64
97
9
54
iwob/evoplotter
app/gpem19/gpem19_processor_expA.py
Python
get_content_of_subsections
get_content_of_subsections
141
149
141
141
6ef9241c0f8397cde59da5e7b3a463dc5df7f699
bigcode/the-stack
train
6e1a441b2c247b6313e5074a
train
function
def create_section(title, desc, props, subsects, figures_list, exp_prefix): assert isinstance(title, str) assert isinstance(desc, str) assert isinstance(props, list) assert isinstance(figures_list, list) section = reporting.Section(title, []) section.add(reporting.BlockLatex(desc + "\n")) f...
def create_section(title, desc, props, subsects, figures_list, exp_prefix):
assert isinstance(title, str) assert isinstance(desc, str) assert isinstance(props, list) assert isinstance(figures_list, list) section = reporting.Section(title, []) section.add(reporting.BlockLatex(desc + "\n")) for s in subsects: section.add(s) # Create figures in the approp...
")\ .replace(r"\_{lex}", "_{lex}").replace(r"\_{", "_{").replace("resistance_par", "res")\ .replace("gravity", "gr") return s def create_section(title, desc, props, subsects, figures_list, exp_prefix):
64
64
130
18
45
iwob/evoplotter
app/gpem19/gpem19_processor_expA.py
Python
create_section
create_section
159
174
159
159
705d8579636c18c555b6b6cbce946c8edcdb8506
bigcode/the-stack
train
ea74c95d83278210aed622fe
train
function
def p_method_for(name): return lambda p, name=name: p["method"] == name
def p_method_for(name):
return lambda p, name=name: p["method"] == name
] dim_benchmarks = Dim(configs) dim_benchmarks.sort() return sort_benchmark_dim(dim_benchmarks) def standardize_benchmark_names(props): for p in props: p["benchmark"] = simplify_benchmark_name(p["benchmark"]) def p_method_for(name):
63
64
21
6
57
iwob/evoplotter
app/gpem19/gpem19_processor_expA.py
Python
p_method_for
p_method_for
63
64
63
63
a591fe759359398e4637e2c364c32b61f7a98f67
bigcode/the-stack
train
e12b57577a2cc15c3a2a2ad6
train
function
def p_matches_dict(p, d): for k, v in d.items(): if k not in p: return False # throw here an exception if you know that p should always contain k if p[k] != v: return False return True
def p_matches_dict(p, d):
for k, v in d.items(): if k not in p: return False # throw here an exception if you know that p should always contain k if p[k] != v: return False return True
_dim(dim_benchmarks) def standardize_benchmark_names(props): for p in props: p["benchmark"] = simplify_benchmark_name(p["benchmark"]) def p_method_for(name): return lambda p, name=name: p["method"] == name def p_matches_dict(p, d):
64
64
59
8
55
iwob/evoplotter
app/gpem19/gpem19_processor_expA.py
Python
p_matches_dict
p_matches_dict
65
71
65
65
0364d153cdb9f4a649a2b68d08d36debc3832126
bigcode/the-stack
train
c836a8596439f096b5bdaeb3
train
function
def create_subsection_shared_stats(props, title, dim_rows, dim_cols, numRuns, headerRowNames): vb = 1 # vertical border variants = None # variants_benchmarkNumTests dim_rows_v2 = get_benchmarks_from_props(props, ignoreNumTests=True) # dim_rows_v2 += dim_true #TODO: within dict # ----------------...
def create_subsection_shared_stats(props, title, dim_rows, dim_cols, numRuns, headerRowNames):
vb = 1 # vertical border variants = None # variants_benchmarkNumTests dim_rows_v2 = get_benchmarks_from_props(props, ignoreNumTests=True) # dim_rows_v2 += dim_true #TODO: within dict # ---------------------------------------------------- # Cleaning experiment here, because dimension can be e...
predicate, xs=xs, xticks=xticks, show_plot=False, title="Ratio of solutions with MSE under the certain level", xlabel="MSE", series_dim=dim_method, ...
256
256
1,785
23
232
iwob/evoplotter
app/gpem19/gpem19_processor_expA.py
Python
create_subsection_shared_stats
create_subsection_shared_stats
350
475
350
350
9e973a9456a996ae701bba8bfa813036f26af5e9
bigcode/the-stack
train
ef6ba165309b4f1578614388
train
function
def create_subsection_figures(props, dim_rows, dim_cols, exp_prefix): if len(props) == 0: print("No props: plots were not generated.") return section = reporting.Section("Figures", []) getter_mse = lambda p: float(p["result.best.trainMSE"]) predicate = lambda v, v_xaxis: v <= v_xaxis ...
def create_subsection_figures(props, dim_rows, dim_cols, exp_prefix):
if len(props) == 0: print("No props: plots were not generated.") return section = reporting.Section("Figures", []) getter_mse = lambda p: float(p["result.best.trainMSE"]) predicate = lambda v, v_xaxis: v <= v_xaxis N = 50 # number of points per plot line r = (0.0, 1e0) xs ...
reporting.color_scheme_green, default_color_thresholds=(0.0, 0.5, 1.0), vertical_border=vb, table_postprocessor=post, variants=variants, ), ] subsects_main = [] for t in tables: tup = (t.title, t.apply(props), t.color_scheme) ...
121
122
409
17
104
iwob/evoplotter
app/gpem19/gpem19_processor_expA.py
Python
create_subsection_figures
create_subsection_figures
313
346
313
313
df6ecbaf6f94b6a77636d04a5599e36c5acc7a04
bigcode/the-stack
train
09da770f7770842fcb728744
train
function
def sort_benchmark_dim(d): assert isinstance(d, Dim) def s(config1): return config1.get_caption() # sort benchmarks by their names return Dim(sorted(d.configs, key=s))
def sort_benchmark_dim(d):
assert isinstance(d, Dim) def s(config1): return config1.get_caption() # sort benchmarks by their names return Dim(sorted(d.configs, key=s))
(".") i_us = name.rfind("_") return name[i_us+1:i_dot] def benchmark_shorter(name): name = simplify_benchmark_name(name) i_us = name.rfind("_") x = name[:i_us] return x def sort_benchmark_dim(d):
64
64
46
7
56
iwob/evoplotter
app/gpem19/gpem19_processor_expA.py
Python
sort_benchmark_dim
sort_benchmark_dim
37
41
37
37
5286070340cfb48fa1b4fdf8f7f89404ca37eed3
bigcode/the-stack
train
18ba10da78db079f6e7be89e
train
function
def p_true(p): return True
def p_true(p):
return True
ase(p): return p["selection"] == "lexicase" def p_sel_tourn(p): return p["selection"] == "tournament" def p_testsRatio_equalTo(ratio): return lambda p, ratio=ratio: p["testsRatio"] == ratio def p_true(p):
64
64
9
5
58
iwob/evoplotter
app/gpem19/gpem19_processor_expA.py
Python
p_true
p_true
86
87
86
86
740f0565ecd66b42891f5359843ca72eb9d81c9c
bigcode/the-stack
train
407e255fd66e4f98d9745679
train
function
def benchmark_get_num_tests(name): i_dot = name.rfind(".") i_us = name.rfind("_") return name[i_us+1:i_dot]
def benchmark_get_num_tests(name):
i_dot = name.rfind(".") i_us = name.rfind("_") return name[i_us+1:i_dot]
= name[:name.rfind(".")] # cut off '.sl' name = name[:name.rfind("_")] # cut off number of tests # return name.replace("resistance_par", "res").replace("gravity", "gr") return name def benchmark_get_num_tests(name):
64
64
35
7
56
iwob/evoplotter
app/gpem19/gpem19_processor_expA.py
Python
benchmark_get_num_tests
benchmark_get_num_tests
24
27
24
24
c1a169ca0c9d3c27b8e116b2f84ab1e84001cc7f
bigcode/the-stack
train
1e411fe6776c4913fbbed3aa
train
function
def standardize_benchmark_names(props): for p in props: p["benchmark"] = simplify_benchmark_name(p["benchmark"])
def standardize_benchmark_names(props):
for p in props: p["benchmark"] = simplify_benchmark_name(p["benchmark"])
_name(c.get_caption()), c.filters[0][1], benchmark=c.get_caption()) for c in dim_benchmarks.configs] dim_benchmarks = Dim(configs) dim_benchmarks.sort() return sort_benchmark_dim(dim_benchmarks) def standardize_benchmark_names(props):
64
64
28
8
56
iwob/evoplotter
app/gpem19/gpem19_processor_expA.py
Python
standardize_benchmark_names
standardize_benchmark_names
57
59
57
57
c3f54342532f68d2d1981a862e969a193ce138be
bigcode/the-stack
train
b45ed975d9b2df359003c6c5
train
function
def post(s): s = s.replace("{ccccccccccccc}", "{rrrrrrrrrrrrr}").replace("{rrr", "{lrr")\ .replace(r"\_{lex}", "_{lex}").replace(r"\_{", "_{").replace("resistance_par", "res")\ .replace("gravity", "gr") return s
def post(s):
s = s.replace("{ccccccccccccc}", "{rrrrrrrrrrrrr}").replace("{rrr", "{lrr")\ .replace(r"\_{lex}", "_{lex}").replace(r"\_{", "_{").replace("resistance_par", "res")\ .replace("gravity", "gr") return s
, table, cs in subsects: if isinstance(cs, reporting.ColorScheme3): cs = cs.toBlockLatex() sub = reporting.SectionRelative(title, contents=[cs, reporting.BlockLatex(table + "\n"), vspace]) content.append(sub) return content def post(s):
64
64
76
4
59
iwob/evoplotter
app/gpem19/gpem19_processor_expA.py
Python
post
post
151
155
151
151
4838515d47c1a31a0a8850703c665b01c5049e3c
bigcode/the-stack
train
2909634aade0fbfcaf81f006
train
function
def create_subsection_cdgp_specific(props, title, dim_rows, dim_cols, headerRowNames): vb = 1 # vertical border # variants = variants_benchmarkNumTests variants = None # props = [p for p in props if p["method"] in {"CDGP", "CDGPprops"}] print("AVG TOTAL TESTS") latex_avgTotalTests = create_si...
def create_subsection_cdgp_specific(props, title, dim_rows, dim_cols, headerRowNames):
vb = 1 # vertical border # variants = variants_benchmarkNumTests variants = None # props = [p for p in props if p["method"] in {"CDGP", "CDGPprops"}] print("AVG TOTAL TESTS") latex_avgTotalTests = create_single_table_bundle(props, dim_rows, dim_cols, get_avg_totalTests, headerRowNames, ...
# TableGenerator(get_avg_evaluatedSuccessful, dim_rows, dim_cols, headerRowNames=headerRowNames, # title="Average number of evaluated solutions", # color_scheme=reporting.color_scheme_brown, # default_color_thresholds=(500.0, 25000.0, 100000.0), ...
255
256
1,182
21
234
iwob/evoplotter
app/gpem19/gpem19_processor_expA.py
Python
create_subsection_cdgp_specific
create_subsection_cdgp_specific
541
608
541
541
b22642fa5de3fb34054bcb47dfd196b92a6fd2d2
bigcode/the-stack
train
e250f701815cf2a4ae1206ee
train
function
def p_steadyState(p): return p["evolutionMode"] == "steadyState"
def p_steadyState(p):
return p["evolutionMode"] == "steadyState"
return True def p_dict_matcher(d): assert isinstance(d, dict) d = d.copy() return lambda p, d=d: p_matches_dict(p, d) def p_generational(p): return p["evolutionMode"] == "generational" def p_steadyState(p):
64
64
20
7
57
iwob/evoplotter
app/gpem19/gpem19_processor_expA.py
Python
p_steadyState
p_steadyState
78
79
78
78
2ec9136a9577f2fea4985208ea40b5888aec0eb2
bigcode/the-stack
train
9a980a4456f8bd92bc7d611a
train
function
def p_generational(p): return p["evolutionMode"] == "generational"
def p_generational(p):
return p["evolutionMode"] == "generational"
that p should always contain k if p[k] != v: return False return True def p_dict_matcher(d): assert isinstance(d, dict) d = d.copy() return lambda p, d=d: p_matches_dict(p, d) def p_generational(p):
64
64
19
6
58
iwob/evoplotter
app/gpem19/gpem19_processor_expA.py
Python
p_generational
p_generational
76
77
76
76
279f0a03ab47be887aabd8fb10e0513faef48487
bigcode/the-stack
train
7081123d6782db5a22fd5660
train
function
def benchmark_shorter(name): name = simplify_benchmark_name(name) i_us = name.rfind("_") x = name[:i_us] return x
def benchmark_shorter(name):
name = simplify_benchmark_name(name) i_us = name.rfind("_") x = name[:i_us] return x
# return name.replace("resistance_par", "res").replace("gravity", "gr") return name def benchmark_get_num_tests(name): i_dot = name.rfind(".") i_us = name.rfind("_") return name[i_us+1:i_dot] def benchmark_shorter(name):
64
64
36
6
58
iwob/evoplotter
app/gpem19/gpem19_processor_expA.py
Python
benchmark_shorter
benchmark_shorter
30
34
30
30
30cd49127a486a9e2ad538d6b846bfa27358a536
bigcode/the-stack
train
b9d734cd55ec62266e90a452
train
function
def reports_expA01(): title = "Experiments for regression CDGP and baseline regressors from Scikit. A01 - with noise." desc = r""" \parbox{30cm}{ Training set: 300\\ Validation set (GP/CDGP only): 75\\ Test set: 125\\ Sets were shuffled randomly from the 500 cases present in each generated benchmark. In this ...
def reports_expA01():
title = "Experiments for regression CDGP and baseline regressors from Scikit. A01 - with noise." desc = r""" \parbox{30cm}{ Training set: 300\\ Validation set (GP/CDGP only): 75\\ Test set: 125\\ Sets were shuffled randomly from the 500 cases present in each generated benchmark. In this experiment, A01, noise...
Tests, reporting.color_scheme_blue), # ("Average generation (all)", latex_avgGeneration, reporting.color_scheme_teal), #("Average generation (only successful)", latex_avgGenerationSuccessful, reporting.color_scheme_teal), # ("Average evaluated solutions", latex_avgEvaluated, reporting.color_sche...
255
256
2,000
6
249
iwob/evoplotter
app/gpem19/gpem19_processor_expA.py
Python
reports_expA01
reports_expA01
612
679
612
612
f465051703109cedea2189343292f081c1d7e7a4
bigcode/the-stack
train
6f687739f4882426fede30c1
train
function
def p_sel_lexicase(p): return p["selection"] == "lexicase"
def p_sel_lexicase(p):
return p["selection"] == "lexicase"
() return lambda p, d=d: p_matches_dict(p, d) def p_generational(p): return p["evolutionMode"] == "generational" def p_steadyState(p): return p["evolutionMode"] == "steadyState" def p_sel_lexicase(p):
64
64
21
9
55
iwob/evoplotter
app/gpem19/gpem19_processor_expA.py
Python
p_sel_lexicase
p_sel_lexicase
80
81
80
80
d750d6cc24bf9609ffcdf254f0efe8db5666ca7b
bigcode/the-stack
train
b8d3415bc6dd0c6b752b0178
train
function
def get_benchmarks_from_props(props, simplify_names=False, ignoreNumTests=False): if ignoreNumTests: dim_benchmarks = Dim.from_dict_postprocess(props, "benchmark", fun=benchmark_shorter) else: dim_benchmarks = Dim.from_dict(props, "benchmark") if simplify_names: configs = [Co...
def get_benchmarks_from_props(props, simplify_names=False, ignoreNumTests=False):
if ignoreNumTests: dim_benchmarks = Dim.from_dict_postprocess(props, "benchmark", fun=benchmark_shorter) else: dim_benchmarks = Dim.from_dict(props, "benchmark") if simplify_names: configs = [Config(simplify_benchmark_name(c.get_caption()), c.filters[0][1], ...
def sort_benchmark_dim(d): assert isinstance(d, Dim) def s(config1): return config1.get_caption() # sort benchmarks by their names return Dim(sorted(d.configs, key=s)) def get_benchmarks_from_props(props, simplify_names=False, ignoreNumTests=False):
64
64
134
18
46
iwob/evoplotter
app/gpem19/gpem19_processor_expA.py
Python
get_benchmarks_from_props
get_benchmarks_from_props
44
54
44
44
ddfa7a232ff62c67fd4ddf714f8b3a4794ddb5ca
bigcode/the-stack
train
a5dcc3f1a7329ab8306a90f0
train
function
def create_subsection_ea_stats(props, title, dim_rows, dim_cols, headerRowNames): vb = 1 # vertical border variants = None # variants_benchmarkNumTests dim_rows_v2 = get_benchmarks_from_props(props, ignoreNumTests=True) # dim_rows_v2 += dim_true # TODO: within dict tables = [ TableGenera...
def create_subsection_ea_stats(props, title, dim_rows, dim_cols, headerRowNames):
vb = 1 # vertical border variants = None # variants_benchmarkNumTests dim_rows_v2 = get_benchmarks_from_props(props, ignoreNumTests=True) # dim_rows_v2 += dim_true # TODO: within dict tables = [ TableGenerator(get_rankingOfBestSolutionsCDSR(ONLY_VISIBLE_SOLS=True, NUM_SHOWN=15), ...
, headerRowNames=headerRowNames, title="Average runtime [s]", color_scheme=reporting.color_scheme_violet, default_color_thresholds=(0.0, 900.0, 1800.0), vertical_border=vb, table_postprocessor=post, variants=variants, ...
239
240
800
21
218
iwob/evoplotter
app/gpem19/gpem19_processor_expA.py
Python
create_subsection_ea_stats
create_subsection_ea_stats
479
537
479
479
c4ce5d5b297a9e16dd6928e26dc84be0845752f7
bigcode/the-stack
train
ba8be01a8abbaf7372092331
train
function
def reports_expA02(): title = "Experiments for regression CDGP and baseline regressors from Scikit. A02 - no noise." desc = r""" \parbox{30cm}{ Training set: 300\\ Validation set (GP/CDGP only): 75\\ Test set: 125\\ Sets were shuffled randomly from the 500 cases present in each generated benchmark. In this ex...
def reports_expA02():
title = "Experiments for regression CDGP and baseline regressors from Scikit. A02 - no noise." desc = r""" \parbox{30cm}{ Training set: 300\\ Validation set (GP/CDGP only): 75\\ Test set: 125\\ Sets were shuffled randomly from the 500 cases present in each generated benchmark. In this experiment, A02, there i...
_cdgp_specific, [props, "CDGP Statistics", dim_rows, dim_cols_cdgp, headerRowNames]), # (create_subsection_aggregation_tests, [dim_rows, dim_cols, headerRowNames]), # (create_subsection_figures, [dim_rows, dim_cols, exp_prefix]), ] sects = [(title, desc, subs, [])] save_listings(props, dim...
255
256
1,902
6
249
iwob/evoplotter
app/gpem19/gpem19_processor_expA.py
Python
reports_expA02
reports_expA02
686
751
686
686
13b37e09b0c13c3f2e52fb7c48055a2788970029
bigcode/the-stack
train
3842d4aa666e4739d07a3189
train
function
def set_up_cube(data, name, units, realizations=np.array([0, 1, 2], dtype=np.float32), timesteps=1, y_dimension_length=3, x_dimension_length=3): """Create a cube containing multiple realizations.""" try: cube = Cube(data, standard_name=name, units=units) except ValueE...
def set_up_cube(data, name, units, realizations=np.array([0, 1, 2], dtype=np.float32), timesteps=1, y_dimension_length=3, x_dimension_length=3):
"""Create a cube containing multiple realizations.""" try: cube = Cube(data, standard_name=name, units=units) except ValueError: cube = Cube(data, long_name=name, units=units) cube.add_dim_coord(DimCoord(realizations, 'realization', units='1'), 0) tim...
0.0, 0.1, 0.0, 0.0, 0.0]]], dtype=np.float32) return ( set_up_probability_above_threshold_spot_cube( data, "air_temperature", "degreesC")) def set_up_cube(data, name, units, realizations=np.array([0, 1, 2], dtype=np.float32), timesteps=1, y...
104
105
350
47
57
TomekTrzeciak/improver
lib/improver/tests/ensemble_calibration/ensemble_calibration/helper_functions.py
Python
set_up_cube
set_up_cube
267
294
267
269
fbe5661af26cb55e5e3b67c4c4ca4f8ca9d1589f
bigcode/the-stack
train
f101087d7be1837d7b88a537
train
function
def _create_truth(data, time_dt, number_of_days=5, **kwargs): """ Function to create truth cubes, based on the input cube, and assuming that there will be one forecast per day at the same hour of the day. Please see improver.tests.set_up_test_cubes.set_up_variable_cube for the other supported keywo...
def _create_truth(data, time_dt, number_of_days=5, **kwargs):
""" Function to create truth cubes, based on the input cube, and assuming that there will be one forecast per day at the same hour of the day. Please see improver.tests.set_up_test_cubes.set_up_variable_cube for the other supported keyword arguments. Args: data (numpy.ndarray): ...
= frt_dt + datetime.timedelta(days=day) new_time_dt = time_dt + datetime.timedelta(days=day) historic_forecasts.append( set_up_variable_cube( data - 2, time=new_time_dt, frt=new_frt_dt, standard_grid_metadata=standard_grid_metadata, **kwargs)) return hist...
91
91
306
18
72
TomekTrzeciak/improver
lib/improver/tests/ensemble_calibration/ensemble_calibration/helper_functions.py
Python
_create_truth
_create_truth
414
443
414
414
39cdb680a0358756cd602a98ad44a1e97aebb8d4
bigcode/the-stack
train
46c854316db664253c994538
train
function
def add_forecast_reference_time_and_forecast_period( cube, time_point=402295.0, fp_point=4.0): """ Function to add forecast_reference_time and forecast_period coordinates to the input cube. """ cube.coord("time").points = time_point coord_position = cube.coord_dims("time") if not isi...
def add_forecast_reference_time_and_forecast_period( cube, time_point=402295.0, fp_point=4.0):
""" Function to add forecast_reference_time and forecast_period coordinates to the input cube. """ cube.coord("time").points = time_point coord_position = cube.coord_dims("time") if not isinstance(fp_point, list): fp_point = [fp_point] fp_points = fp_point frt_points = cube.c...
] += 2 data[2] += 4 return set_up_cube(data.astype(np.float32), "wind_speed", "m s^-1") def add_forecast_reference_time_and_forecast_period( cube, time_point=402295.0, fp_point=4.0):
64
64
208
29
35
TomekTrzeciak/improver
lib/improver/tests/ensemble_calibration/ensemble_calibration/helper_functions.py
Python
add_forecast_reference_time_and_forecast_period
add_forecast_reference_time_and_forecast_period
347
367
347
348
7e78d25a399ffb9fda6dca0a282d27acc55ce6f8
bigcode/the-stack
train
0c1807abbcc9333fb045dd57
train
function
def set_up_spot_temperature_cube(): """Create a cube with metadata and values suitable for air temperature.""" data = (np.tile(np.linspace(-45.0, 45.0, 9), 3).reshape(3, 1, 9) + 273.15) data[0] -= 2 data[1] += 2 data[2] += 4 return set_up_spot_cube(data.astype(np.float32), "air_tempe...
def set_up_spot_temperature_cube():
"""Create a cube with metadata and values suitable for air temperature.""" data = (np.tile(np.linspace(-45.0, 45.0, 9), 3).reshape(3, 1, 9) + 273.15) data[0] -= 2 data[1] += 2 data[2] += 4 return set_up_spot_cube(data.astype(np.float32), "air_temperature", "K")
32), 'latitude', units='degrees'), data_dims=2) cube.add_aux_coord(AuxCoord(np.linspace(120, 180, 9, dtype=np.float32), 'longitude', units='degrees'), data_dims=2) return cube def set_up_spot_temperature_cube():
64
64
110
8
55
TomekTrzeciak/improver
lib/improver/tests/ensemble_calibration/ensemble_calibration/helper_functions.py
Python
set_up_spot_temperature_cube
set_up_spot_temperature_cube
328
335
328
328
c9c5aaa8746b508ad54120143a81176b47ef5835
bigcode/the-stack
train
6a316fbb371a2038e4a9f4b0
train
function
def set_up_spot_cube(data, phenomenon_standard_name, phenomenon_units): """Create a cube containing multiple realizations.""" cube = Cube(data, standard_name=phenomenon_standard_name, units=phenomenon_units) cube.add_dim_coord(DimCoord([0, 1, 2], 'realization', ...
def set_up_spot_cube(data, phenomenon_standard_name, phenomenon_units):
"""Create a cube containing multiple realizations.""" cube = Cube(data, standard_name=phenomenon_standard_name, units=phenomenon_units) cube.add_dim_coord(DimCoord([0, 1, 2], 'realization', units='1'), 0) time_origin = "hours since 1970-01-01 00:00:00" ...
reshape(3, 1, 3, 3) + 273.15) data[0] -= 2 data[1] += 2 data[2] += 4 return set_up_cube(data.astype(dtype), "air_temperature", "K") def set_up_spot_cube(data, phenomenon_standard_name, phenomenon_units):
78
78
260
15
63
TomekTrzeciak/improver
lib/improver/tests/ensemble_calibration/ensemble_calibration/helper_functions.py
Python
set_up_spot_cube
set_up_spot_cube
307
325
307
307
31ca8d9546ed8a5a4f12970cad75204069b6c182
bigcode/the-stack
train
ca638f312018af91cde2f421
train
class
class SetupCubes(IrisTest): """Set up cubes for testing.""" @ManageWarnings( ignored_messages=IGNORED_MESSAGES, warning_types=WARNING_TYPES) def setUp(self): """Set up temperature and wind speed cubes for testing.""" super().setUp() frt_dt = datetime.datetime(2017, 11, 10, ...
class SetupCubes(IrisTest):
"""Set up cubes for testing.""" @ManageWarnings( ignored_messages=IGNORED_MESSAGES, warning_types=WARNING_TYPES) def setUp(self): """Set up temperature and wind speed cubes for testing.""" super().setUp() frt_dt = datetime.datetime(2017, 11, 10, 0, 0) time_dt = datet...
4) def assertCalibratedVariablesAlmostEqual(self, first, second): """Overriding of the assertArrayAlmostEqual method to check whether array are matching to 4 decimal places. This is specifically for use in assertions following applying the EMOS coefficients, in order to calibrate th...
171
171
571
8
163
TomekTrzeciak/improver
lib/improver/tests/ensemble_calibration/ensemble_calibration/helper_functions.py
Python
SetupCubes
SetupCubes
90
139
90
91
c5844b950e08ae11474e37b5ad928c6ae7ac984c
bigcode/the-stack
train
39cc0b17e00b12d5ce76d189
train
function
def set_up_probability_threshold_cube( data, phenomenon_standard_name, phenomenon_units, forecast_thresholds=np.array([8, 10, 12]), timesteps=1, y_dimension_length=3, x_dimension_length=3, spp__relative_to_threshold='above'): """ Create a cube containing multiple probability_abov...
def set_up_probability_threshold_cube( data, phenomenon_standard_name, phenomenon_units, forecast_thresholds=np.array([8, 10, 12]), timesteps=1, y_dimension_length=3, x_dimension_length=3, spp__relative_to_threshold='above'):
""" Create a cube containing multiple probability_above/below_threshold values for the coordinate. """ cube_long_name = ( "probability_of_{}_{}_threshold".format( phenomenon_standard_name, spp__relative_to_threshold)) cube = Cube(data, long_name=cube_long_name, ...
, frt_dt, realizations=[0, 1, 2], name="wind_speed", units="m s-1").merge_cube() self.wind_speed_truth_cube = _create_truth( base_data, time_dt, name="wind_speed", units="m s-1").merge_cube() def set_up_probability_threshold_cube( data, phenomenon_standard_name, phenomenon_units...
124
124
414
59
65
TomekTrzeciak/improver
lib/improver/tests/ensemble_calibration/ensemble_calibration/helper_functions.py
Python
set_up_probability_threshold_cube
set_up_probability_threshold_cube
142
182
142
146
ae68a0051d30d330580f2be5063d6d8fad75b177
bigcode/the-stack
train
a00b3ddec7352663978b3c4b
train
function
def set_up_wind_speed_cube(): """Create a cube with metadata and values suitable for wind speed.""" data = np.tile(np.linspace(0, 60, 9), 3).reshape(3, 1, 3, 3) data[0] += 0 data[1] += 2 data[2] += 4 return set_up_cube(data.astype(np.float32), "wind_speed", "m s^-1")
def set_up_wind_speed_cube():
"""Create a cube with metadata and values suitable for wind speed.""" data = np.tile(np.linspace(0, 60, 9), 3).reshape(3, 1, 3, 3) data[0] += 0 data[1] += 2 data[2] += 4 return set_up_cube(data.astype(np.float32), "wind_speed", "m s^-1")
9) + 273.15) data[0] -= 2 data[1] += 2 data[2] += 4 return set_up_spot_cube(data.astype(np.float32), "air_temperature", "K") def set_up_wind_speed_cube():
64
64
102
8
56
TomekTrzeciak/improver
lib/improver/tests/ensemble_calibration/ensemble_calibration/helper_functions.py
Python
set_up_wind_speed_cube
set_up_wind_speed_cube
338
344
338
338
0b3f5fc2a937498324f4a87bfd769445c366606c
bigcode/the-stack
train
20e8e62e941e71c118b475e9
train
function
def set_up_probability_above_threshold_spot_temperature_cube(): """ Create a cube with metadata and values suitable for air temperature for spot forecasts. """ data = np.array([[[1.0, 0.9, 1.0, 0.8, 0.9, 0.5, 0.5, 0.2, 0.0]], [[1.0, ...
def set_up_probability_above_threshold_spot_temperature_cube():
""" Create a cube with metadata and values suitable for air temperature for spot forecasts. """ data = np.array([[[1.0, 0.9, 1.0, 0.8, 0.9, 0.5, 0.5, 0.2, 0.0]], [[1.0, 0.5, 1.0, 0.5, 0.5, 0.3, ...
x_dimension_length, dtype=np.float32), 'longitude', units='degrees'), data_dims=2) cube.coord( var_name="threshold").attributes[ "spp__relative_to_threshold"] = "above" return cube def set_up_probability_above_thres...
64
64
214
12
51
TomekTrzeciak/improver
lib/improver/tests/ensemble_calibration/ensemble_calibration/helper_functions.py
Python
set_up_probability_above_threshold_spot_temperature_cube
set_up_probability_above_threshold_spot_temperature_cube
248
264
248
248
f4163d85799b523690c8bbcd39417a4a146ac082
bigcode/the-stack
train
6aee597494f5b6fe2f2870b4
train
function
def set_up_temperature_cube(dtype=np.float32): """Create a cube with metadata and values suitable for air temperature.""" data = (np.tile(np.linspace(-45.0, 45.0, 9), 3).reshape(3, 1, 3, 3) + 273.15) data[0] -= 2 data[1] += 2 data[2] += 4 return set_up_cube(data.astype(dtype), "air_t...
def set_up_temperature_cube(dtype=np.float32):
"""Create a cube with metadata and values suitable for air temperature.""" data = (np.tile(np.linspace(-45.0, 45.0, 9), 3).reshape(3, 1, 3, 3) + 273.15) data[0] -= 2 data[1] += 2 data[2] += 4 return set_up_cube(data.astype(dtype), "air_temperature", "K")
32), 'latitude', units='degrees'), 2) cube.add_dim_coord(DimCoord(np.linspace(120, 180, x_dimension_length, dtype=np.float32), 'longitude', units='degrees'), 3) return cube def set_up_temperature_cube(dty...
64
64
111
10
53
TomekTrzeciak/improver
lib/improver/tests/ensemble_calibration/ensemble_calibration/helper_functions.py
Python
set_up_temperature_cube
set_up_temperature_cube
297
304
297
297
e2168441029ad631f71cc1fd27edc62e346ce756
bigcode/the-stack
train
d0d4b5f7580458d0ebcbee7a
train
function
def set_up_probability_above_threshold_spot_cube( data, phenomenon_standard_name, phenomenon_units, forecast_thresholds=np.array([8, 10, 12]), y_dimension_length=9, x_dimension_length=9): """ Create a cube containing multiple realizations, where one of the dimensions is an index used...
def set_up_probability_above_threshold_spot_cube( data, phenomenon_standard_name, phenomenon_units, forecast_thresholds=np.array([8, 10, 12]), y_dimension_length=9, x_dimension_length=9):
""" Create a cube containing multiple realizations, where one of the dimensions is an index used for spot forecasts. """ cube_long_name = ( "probability_of_{}_above_threshold".format(phenomenon_standard_name)) cube = Cube(data, long_name=cube_long_name, units=1) try:...
2, 0.5], [0.2, 0.0, 0.1], [0.0, 0.0, 0.0]]]], dtype=np.float32) return ( set_up_probability_threshold_cube( data, "air_temperature", "degreesC", spp__relative_to_threshold='above')) def set_up_probability_above_threshold_spot_cube( ...
124
125
417
49
75
TomekTrzeciak/improver
lib/improver/tests/ensemble_calibration/ensemble_calibration/helper_functions.py
Python
set_up_probability_above_threshold_spot_cube
set_up_probability_above_threshold_spot_cube
204
245
204
207
0efacad7c94f3445b8511a70f5643a6b957db531
bigcode/the-stack
train
b6f0d40886c8dc8e638c6d31
train
function
def _create_historic_forecasts(data, time_dt, frt_dt, standard_grid_metadata="uk_ens", number_of_days=5, **kwargs): """ Function to create a set of pseudo historic forecast cubes, based on the input cube, and assuming that there will be one forec...
def _create_historic_forecasts(data, time_dt, frt_dt, standard_grid_metadata="uk_ens", number_of_days=5, **kwargs):
""" Function to create a set of pseudo historic forecast cubes, based on the input cube, and assuming that there will be one forecast per day at the same hour of the day. Please see improver.tests.set_up_test_cubes.set_up_variable_cube for the supported keyword arguments. Args: dat...
hours since 1970-01-01 00:00:00" calendar = "gregorian" tunit = Unit(time_origin, calendar) cube.add_aux_coord( DimCoord([frt_points], "forecast_reference_time", units=tunit)) cube.add_aux_coord( DimCoord(fp_points, "forecast_period", units="hours"), data_dims=coord_position) ...
123
123
412
36
86
TomekTrzeciak/improver
lib/improver/tests/ensemble_calibration/ensemble_calibration/helper_functions.py
Python
_create_historic_forecasts
_create_historic_forecasts
370
411
370
372
31db89969d20d4d0122a6e76679bc1b68c6fea5f
bigcode/the-stack
train