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
a9a3bfd72f1dd7efdf9e8c04
train
function
@pytest.fixture(scope="module") def crypto_pool( alice, crypto_project, crypto_math, crypto_lp_token, crypto_views, crypto_coins, crypto_initial_prices, ): # taken from curvefi/curve-crypto-contract keys = [0, 1, 2, 16, 17, 18, "1,#0", "1,#1", "1,#2"] values = ( [crypto_m...
@pytest.fixture(scope="module") def crypto_pool( alice, crypto_project, crypto_math, crypto_lp_token, crypto_views, crypto_coins, crypto_initial_prices, ): # taken from curvefi/curve-crypto-contract
keys = [0, 1, 2, 16, 17, 18, "1,#0", "1,#1", "1,#2"] values = ( [crypto_math.address, crypto_lp_token.address, crypto_views.address] + [coin.address for coin in crypto_coins] + [f"{10 ** (18 - coin.decimals())}," for coin in crypto_coins] ) source = crypto_project.CurveCryptoSwap...
/price?ids=bitcoin,ethereum&vs_currencies=usd" # ).json() # return tuple(int(p[cur]["usd"] * 1e18) for cur in ["bitcoin", "ethereum"]) return (39362000000000003670016, 2493090000000000196608) @pytest.fixture(scope="module") def crypto_pool( alice, crypto_project, crypto_math, crypto_lp_token...
120
120
400
53
67
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
crypto_pool
crypto_pool
351
390
351
361
9886654db054837716f3e13c1e6509846ec7f205
bigcode/the-stack
train
da23a3fdf6e837e4b4051d05
train
function
@pytest.fixture(scope="module") def three_gauges(LiquidityGauge, accounts, mock_lp_token, minter): contracts = [ LiquidityGauge.deploy(mock_lp_token, minter, accounts[0], {"from": accounts[0]}) for _ in range(3) ] yield contracts
@pytest.fixture(scope="module") def three_gauges(LiquidityGauge, accounts, mock_lp_token, minter):
contracts = [ LiquidityGauge.deploy(mock_lp_token, minter, accounts[0], {"from": accounts[0]}) for _ in range(3) ] yield contracts
LiquidityGaugeRewardWrapper.deploy( "Tokenized Reward Gauge", "TG", liquidity_gauge_reward, accounts[0], {"from": accounts[0]}, ) @pytest.fixture(scope="module") def three_gauges(LiquidityGauge, accounts, mock_lp_token, minter):
64
64
67
25
39
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
three_gauges
three_gauges
185
192
185
186
7f0017af17a1b82a3c43f8886a40827e9c9443c8
bigcode/the-stack
train
63b066692d246e636ea9adf9
train
function
@pytest.fixture(scope="module") def vesting(VestingEscrow, accounts, coin_a, start_time, end_time): contract = VestingEscrow.deploy( coin_a, start_time, end_time, True, accounts[1:5], {"from": accounts[0]} ) coin_a._mint_for_testing(accounts[0], 10 ** 21) coin_a.approve(contract, 10 ** 21, {"fro...
@pytest.fixture(scope="module") def vesting(VestingEscrow, accounts, coin_a, start_time, end_time):
contract = VestingEscrow.deploy( coin_a, start_time, end_time, True, accounts[1:5], {"from": accounts[0]} ) coin_a._mint_for_testing(accounts[0], 10 ** 21) coin_a.approve(contract, 10 ** 21, {"from": accounts[0]}) yield contract
yield chain.time() + 1000 + 86400 * 365 @pytest.fixture(scope="module") def end_time(start_time): yield start_time + 100000000 @pytest.fixture(scope="module") def vesting(VestingEscrow, accounts, coin_a, start_time, end_time):
64
64
103
25
38
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
vesting
vesting
208
215
208
209
6c1384b6f4e6980bf9a0e95e18835f2044cb54d3
bigcode/the-stack
train
55ea702c42e63792442e9450
train
function
@pytest.fixture(scope="module") def coin_reward(): yield ERC20("YFIIIIII Funance", "YFIIIIII", 18)
@pytest.fixture(scope="module") def coin_reward():
yield ERC20("YFIIIIII Funance", "YFIIIIII", 18)
Proxy.deploy(accounts[0], accounts[0], accounts[0], {"from": accounts[0]}) @pytest.fixture(scope="module") def gauge_proxy(GaugeProxy, alice, bob): yield GaugeProxy.deploy(alice, bob, {"from": alice}) @pytest.fixture(scope="module") def coin_reward():
64
64
31
10
54
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
coin_reward
coin_reward
121
123
121
122
27fc0e865995b5b47fc10be2152f6d8d3649f285
bigcode/the-stack
train
d91614b830c4ef44edc9f270
train
function
@pytest.fixture(scope="module") def coin_a(): yield ERC20("Coin A", "USDA", 18)
@pytest.fixture(scope="module") def coin_a():
yield ERC20("Coin A", "USDA", 18)
request.param args = (pool_proxy, receiver, receiver, alice, bob, {"from": alice}) idx = len(Burner.deploy.abi["inputs"]) + 1 yield Burner.deploy(*args[-idx:]) # testing contracts @pytest.fixture(scope="module") def coin_a():
64
64
25
10
53
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
coin_a
coin_a
270
272
270
271
3dd4fab225b004a27aa9871b46f9a71a860f4897
bigcode/the-stack
train
942f38ce4bf41c4315d76564
train
function
@pytest.fixture(scope="session") def crypto_initial_prices(): # p = requests.get( # "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,ethereum&vs_currencies=usd" # ).json() # return tuple(int(p[cur]["usd"] * 1e18) for cur in ["bitcoin", "ethereum"]) return (39362000000000003670016, 2493...
@pytest.fixture(scope="session") def crypto_initial_prices(): # p = requests.get( # "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,ethereum&vs_currencies=usd" # ).json() # return tuple(int(p[cur]["usd"] * 1e18) for cur in ["bitcoin", "ethereum"])
return (39362000000000003670016, 2493090000000000196608)
@pytest.fixture(scope="session") def crypto_initial_prices(): # p = requests.get( # "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,ethereum&vs_currencies=usd" # ).json() # return tuple(int(p[cur]["usd"] * 1e18) for cur in ["bitcoin", "ethereum"])
78
64
100
78
0
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
crypto_initial_prices
crypto_initial_prices
342
348
342
347
052c4a232ed1b9460ea0b1581af15f6d3b5b80cb
bigcode/the-stack
train
701a10e10880d55b168566e1
train
function
@pytest.fixture(scope="module") def gauge_v3(LiquidityGaugeV3, alice, mock_lp_token, minter): yield LiquidityGaugeV3.deploy(mock_lp_token, minter, alice, {"from": alice})
@pytest.fixture(scope="module") def gauge_v3(LiquidityGaugeV3, alice, mock_lp_token, minter):
yield LiquidityGaugeV3.deploy(mock_lp_token, minter, alice, {"from": alice})
(LiquidityGaugeV2, alice, mock_lp_token, minter): yield LiquidityGaugeV2.deploy(mock_lp_token, minter, alice, {"from": alice}) @pytest.fixture(scope="module") def gauge_v3(LiquidityGaugeV3, alice, mock_lp_token, minter):
64
64
48
26
38
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
gauge_v3
gauge_v3
143
145
143
144
e46ac1d6ed6f4987998a758ebe7b78cd1786d557
bigcode/the-stack
train
6172062fc485bde2ca7a4644
train
function
@pytest.fixture(scope="module") def liquidity_gauge_reward( LiquidityGaugeReward, accounts, mock_lp_token, minter, reward_contract, coin_reward ): yield LiquidityGaugeReward.deploy( mock_lp_token, minter, reward_contract, coin_reward, accounts[0], {"from": account...
@pytest.fixture(scope="module") def liquidity_gauge_reward( LiquidityGaugeReward, accounts, mock_lp_token, minter, reward_contract, coin_reward ):
yield LiquidityGaugeReward.deploy( mock_lp_token, minter, reward_contract, coin_reward, accounts[0], {"from": accounts[0]}, )
GaugeWrapper.deploy( "Tokenized Gauge", "TG", liquidity_gauge, accounts[0], {"from": accounts[0]} ) @pytest.fixture(scope="module") def liquidity_gauge_reward( LiquidityGaugeReward, accounts, mock_lp_token, minter, reward_contract, coin_reward ):
64
64
74
34
30
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
liquidity_gauge_reward
liquidity_gauge_reward
160
171
160
163
241c8183ac4cc0b9edc822cbff31685cde1abd54
bigcode/the-stack
train
c3ecd1d5f510c9136a96968e
train
function
@pytest.fixture(scope="session") def crypto_project(pm): return pm("curvefi/curve-crypto-contract@1.0.0")
@pytest.fixture(scope="session") def crypto_project(pm):
return pm("curvefi/curve-crypto-contract@1.0.0")
accounts[0], accounts[0], {"from": accounts[0]} ) yield f @pytest.fixture(scope="module") def crypto_coins(coin_a, coin_b, coin_c): return [coin_a, coin_b, coin_c] @pytest.fixture(scope="session") def crypto_project(pm):
64
64
29
11
53
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
crypto_project
crypto_project
317
319
317
318
bd1804be097c9674f1f2118fa08e11254bc4372b
bigcode/the-stack
train
19dfead2085df014f5330dbd
train
function
@pytest.fixture(scope="session") def alice(accounts): yield accounts[0]
@pytest.fixture(scope="session") def alice(accounts):
yield accounts[0]
epoch) / (1 - q)) S += int(YEAR_1_SUPPLY // YEAR * q ** epoch) * ( chain[-1].timestamp - token.start_epoch_time() ) return S yield _fn # account aliases @pytest.fixture(scope="session") def alice(accounts):
64
64
16
10
53
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
alice
alice
61
63
61
62
f5d3ed1cb3d512029e410e725fddc0cf43fb7f59
bigcode/the-stack
train
295072ed939da15c3416af04
train
function
@pytest.fixture(scope="module") def liquidity_gauge(LiquidityGauge, accounts, mock_lp_token, minter): yield LiquidityGauge.deploy(mock_lp_token, minter, accounts[0], {"from": accounts[0]})
@pytest.fixture(scope="module") def liquidity_gauge(LiquidityGauge, accounts, mock_lp_token, minter):
yield LiquidityGauge.deploy(mock_lp_token, minter, accounts[0], {"from": accounts[0]})
= CurveRewards.deploy(mock_lp_token, coin_reward, {"from": accounts[0]}) contract.setRewardDistribution(accounts[0], {"from": accounts[0]}) yield contract @pytest.fixture(scope="module") def liquidity_gauge(LiquidityGauge, accounts, mock_lp_token, minter):
64
64
49
24
39
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
liquidity_gauge
liquidity_gauge
133
135
133
134
ee1d32c776568a2ccd99786b89a21ef0225db57b
bigcode/the-stack
train
447426d2f1d992dd7aff44a6
train
function
def pack_values(values): packed = b"".join(i.to_bytes(1, "big") for i in values) padded = packed + bytes(32 - len(values)) return padded
def pack_values(values):
packed = b"".join(i.to_bytes(1, "big") for i in values) padded = packed + bytes(32 - len(values)) return padded
INITIAL_SUPPLY = 1_303_030_303 def approx(a, b, precision=1e-10): if a == b == 0: return True return 2 * abs(a - b) / (a + b) <= precision def pack_values(values):
64
64
42
5
58
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
pack_values
pack_values
28
31
28
28
5490ca31c463de8dd117fb7519bdc26f30e2dc85
bigcode/the-stack
train
229327186eeb89b66c3ea5c7
train
function
@pytest.fixture(scope="module") def reward_contract(CurveRewards, mock_lp_token, accounts, coin_reward): contract = CurveRewards.deploy(mock_lp_token, coin_reward, {"from": accounts[0]}) contract.setRewardDistribution(accounts[0], {"from": accounts[0]}) yield contract
@pytest.fixture(scope="module") def reward_contract(CurveRewards, mock_lp_token, accounts, coin_reward):
contract = CurveRewards.deploy(mock_lp_token, coin_reward, {"from": accounts[0]}) contract.setRewardDistribution(accounts[0], {"from": accounts[0]}) yield contract
.deploy(alice, bob, {"from": alice}) @pytest.fixture(scope="module") def coin_reward(): yield ERC20("YFIIIIII Funance", "YFIIIIII", 18) @pytest.fixture(scope="module") def reward_contract(CurveRewards, mock_lp_token, accounts, coin_reward):
64
64
64
22
42
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
reward_contract
reward_contract
126
130
126
127
d821a748595ad0dc17dbffbf6e2ddcb534769b7a
bigcode/the-stack
train
e1cff01194ee2fde93f2e78f
train
function
@pytest.fixture(scope="module") def crypto_lp_token(alice, crypto_project): return crypto_project.CurveTokenV4.deploy("Mock Crypto LP Token", "crvMock", {"from": alice})
@pytest.fixture(scope="module") def crypto_lp_token(alice, crypto_project):
return crypto_project.CurveTokenV4.deploy("Mock Crypto LP Token", "crvMock", {"from": alice})
, coin_b, coin_c): return [coin_a, coin_b, coin_c] @pytest.fixture(scope="session") def crypto_project(pm): return pm("curvefi/curve-crypto-contract@1.0.0") @pytest.fixture(scope="module") def crypto_lp_token(alice, crypto_project):
64
64
42
16
48
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
crypto_lp_token
crypto_lp_token
322
324
322
323
c339ac6408e524c2bb152d42ce509fd6b9c0a786
bigcode/the-stack
train
4239a1b41b5d4eec5bedac97
train
function
@pytest.fixture(scope="module") def gauge_v2(LiquidityGaugeV2, alice, mock_lp_token, minter): yield LiquidityGaugeV2.deploy(mock_lp_token, minter, alice, {"from": alice})
@pytest.fixture(scope="module") def gauge_v2(LiquidityGaugeV2, alice, mock_lp_token, minter):
yield LiquidityGaugeV2.deploy(mock_lp_token, minter, alice, {"from": alice})
iquidityGauge, accounts, mock_lp_token, minter): yield LiquidityGauge.deploy(mock_lp_token, minter, accounts[0], {"from": accounts[0]}) @pytest.fixture(scope="module") def gauge_v2(LiquidityGaugeV2, alice, mock_lp_token, minter):
64
64
48
26
38
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
gauge_v2
gauge_v2
138
140
138
139
ae60c66a16d4135f0b3d6c412c6f60a98fd1c837
bigcode/the-stack
train
ad30d6885b047025ca3baeba
train
function
@pytest.fixture(scope="module") def gauge_proxy(GaugeProxy, alice, bob): yield GaugeProxy.deploy(alice, bob, {"from": alice})
@pytest.fixture(scope="module") def gauge_proxy(GaugeProxy, alice, bob):
yield GaugeProxy.deploy(alice, bob, {"from": alice})
alice, {"from": alice}) @pytest.fixture(scope="module") def pool_proxy(PoolProxy, accounts): yield PoolProxy.deploy(accounts[0], accounts[0], accounts[0], {"from": accounts[0]}) @pytest.fixture(scope="module") def gauge_proxy(GaugeProxy, alice, bob):
64
64
32
17
47
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
gauge_proxy
gauge_proxy
116
118
116
117
f6564e9dce21d029633147bd5b2226065759a535
bigcode/the-stack
train
c06b4042d9960794d6c66450
train
function
@pytest.fixture(scope="module") def crypto_coins(coin_a, coin_b, coin_c): return [coin_a, coin_b, coin_c]
@pytest.fixture(scope="module") def crypto_coins(coin_a, coin_b, coin_c):
return [coin_a, coin_b, coin_c]
t = chain.time() return FeeDistributor.deploy( voting_escrow, t, coin_a, accounts[0], accounts[0], {"from": accounts[0]} ) yield f @pytest.fixture(scope="module") def crypto_coins(coin_a, coin_b, coin_c):
64
64
32
20
43
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
crypto_coins
crypto_coins
312
314
312
313
d242a774f54a7d4b96a3f8448eb7db1994c7b9b0
bigcode/the-stack
train
62dafabbc0880110831f106b
train
function
@pytest.fixture(scope="module") def coin_b(): yield ERC20("Coin B", "USDB", 18)
@pytest.fixture(scope="module") def coin_b():
yield ERC20("Coin B", "USDB", 18)
= len(Burner.deploy.abi["inputs"]) + 1 yield Burner.deploy(*args[-idx:]) # testing contracts @pytest.fixture(scope="module") def coin_a(): yield ERC20("Coin A", "USDA", 18) @pytest.fixture(scope="module") def coin_b():
64
64
25
10
54
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
coin_b
coin_b
275
277
275
276
5566d46675b269e938af3cf83e574c4b898d8ce0
bigcode/the-stack
train
ba3784c3ee9fafb1d2d985c9
train
function
@pytest.fixture(scope="module") def pool_proxy(PoolProxy, accounts): yield PoolProxy.deploy(accounts[0], accounts[0], accounts[0], {"from": accounts[0]})
@pytest.fixture(scope="module") def pool_proxy(PoolProxy, accounts):
yield PoolProxy.deploy(accounts[0], accounts[0], accounts[0], {"from": accounts[0]})
.deploy(token, gauge_controller, {"from": accounts[0]}) @pytest.fixture(scope="module") def crypto_pool_proxy(alice, CryptoPoolProxy): return CryptoPoolProxy.deploy(alice, alice, alice, {"from": alice}) @pytest.fixture(scope="module") def pool_proxy(PoolProxy, accounts):
64
64
40
15
49
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
pool_proxy
pool_proxy
111
113
111
112
31d289342a0207fd2c931be58d7caadb711a11b8
bigcode/the-stack
train
97bf47d72d680bb199daf2a3
train
function
@pytest.fixture(scope="module") def rewards_only_gauge(RewardsOnlyGauge, alice, mock_lp_token): yield RewardsOnlyGauge.deploy(alice, mock_lp_token, {"from": alice})
@pytest.fixture(scope="module") def rewards_only_gauge(RewardsOnlyGauge, alice, mock_lp_token):
yield RewardsOnlyGauge.deploy(alice, mock_lp_token, {"from": alice})
def gauge_v3(LiquidityGaugeV3, alice, mock_lp_token, minter): yield LiquidityGaugeV3.deploy(mock_lp_token, minter, alice, {"from": alice}) @pytest.fixture(scope="module") def rewards_only_gauge(RewardsOnlyGauge, alice, mock_lp_token):
64
64
40
22
42
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
rewards_only_gauge
rewards_only_gauge
148
150
148
149
ef43f6f1538f64bad00f57fc2024a06e0fb85ed7
bigcode/the-stack
train
766c41fc96ad53279b224219
train
function
@pytest.fixture(scope="module") def mock_lp_token(ERC20LP, accounts): # Not using the actual Curve contract yield ERC20LP.deploy("Curve LP token", "usdCrv", 18, 10 ** 9, {"from": accounts[0]})
@pytest.fixture(scope="module") def mock_lp_token(ERC20LP, accounts): # Not using the actual Curve contract
yield ERC20LP.deploy("Curve LP token", "usdCrv", 18, 10 ** 9, {"from": accounts[0]})
20("Coin B", "USDB", 18) @pytest.fixture(scope="module") def coin_c(): yield ERC20("Coin C", "mWBTC", 8) @pytest.fixture(scope="module") def mock_lp_token(ERC20LP, accounts): # Not using the actual Curve contract
64
64
59
26
38
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
mock_lp_token
mock_lp_token
285
287
285
286
9307a089dcaf46555ee527053521e34f48ec0f96
bigcode/the-stack
train
95a9581079a3f69d62ae433f
train
function
@pytest.fixture(scope="module") def voting_escrow(VotingEscrow, accounts, token): yield VotingEscrow.deploy( token, "Voting-escrowed CRV", "veCRV", "veCRV_0.99", {"from": accounts[0]} )
@pytest.fixture(scope="module") def voting_escrow(VotingEscrow, accounts, token):
yield VotingEscrow.deploy( token, "Voting-escrowed CRV", "veCRV", "veCRV_0.99", {"from": accounts[0]} )
@pytest.fixture(scope="module") def token(ERC20CRV, accounts): yield ERC20CRV.deploy("Curve DAO Token", "CRV", 18, {"from": accounts[0]}) @pytest.fixture(scope="module") def voting_escrow(VotingEscrow, accounts, token):
64
64
62
20
44
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
voting_escrow
voting_escrow
89
93
89
90
29b53bf1268eb57ee9472e2db0901b54c0d3c563
bigcode/the-stack
train
8175978cc9bb745249e05570
train
function
@pytest.fixture(scope="module") def pool(CurvePool, accounts, mock_lp_token, coin_a, coin_b): curve_pool = CurvePool.deploy( [coin_a, coin_b], mock_lp_token, 100, 4 * 10 ** 6, {"from": accounts[0]} ) mock_lp_token.set_minter(curve_pool, {"from": accounts[0]}) yield curve_pool
@pytest.fixture(scope="module") def pool(CurvePool, accounts, mock_lp_token, coin_a, coin_b):
curve_pool = CurvePool.deploy( [coin_a, coin_b], mock_lp_token, 100, 4 * 10 ** 6, {"from": accounts[0]} ) mock_lp_token.set_minter(curve_pool, {"from": accounts[0]}) yield curve_pool
Not using the actual Curve contract yield ERC20LP.deploy("Curve LP token", "usdCrv", 18, 10 ** 9, {"from": accounts[0]}) @pytest.fixture(scope="module") def pool(CurvePool, accounts, mock_lp_token, coin_a, coin_b):
64
64
89
24
40
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
pool
pool
290
297
290
291
d8a03a497095e153e5d70bd1e946888acd4291dd
bigcode/the-stack
train
c3899b23e2c82d5a2829431d
train
function
@pytest.fixture(scope="session") def charlie(accounts): yield accounts[2]
@pytest.fixture(scope="session") def charlie(accounts):
yield accounts[2]
- token.start_epoch_time() ) return S yield _fn # account aliases @pytest.fixture(scope="session") def alice(accounts): yield accounts[0] @pytest.fixture(scope="session") def bob(accounts): yield accounts[1] @pytest.fixture(scope="session") def charlie(accounts):
64
64
17
11
53
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
charlie
charlie
71
73
71
72
7bb9d260e0b409589fe93628fd8c9a9cd4d1b7ef
bigcode/the-stack
train
111c80ba38369b3252f97ac5
train
function
@pytest.fixture(scope="module") def vesting_simple(VestingEscrowSimple, accounts, vesting_factory, coin_a, start_time): coin_a._mint_for_testing(vesting_factory, 10 ** 21) tx = vesting_factory.deploy_vesting_contract( coin_a, accounts[1], 10 ** 20, True, 100000000, ...
@pytest.fixture(scope="module") def vesting_simple(VestingEscrowSimple, accounts, vesting_factory, coin_a, start_time):
coin_a._mint_for_testing(vesting_factory, 10 ** 21) tx = vesting_factory.deploy_vesting_contract( coin_a, accounts[1], 10 ** 20, True, 100000000, start_time, {"from": accounts[0]}, ) yield VestingEscrowSimple.at(tx.new_contracts[0])
(VestingEscrowFactory, accounts, vesting_target): yield VestingEscrowFactory.deploy(vesting_target, accounts[0], {"from": accounts[0]}) @pytest.fixture(scope="module") def vesting_simple(VestingEscrowSimple, accounts, vesting_factory, coin_a, start_time):
64
64
110
28
36
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
vesting_simple
vesting_simple
228
240
228
229
b170ab452066bbdcd9b5c181de0a88d48a6f481a
bigcode/the-stack
train
dbb533f06612b3e541e88a76
train
function
@pytest.fixture(scope="session") def bob(accounts): yield accounts[1]
@pytest.fixture(scope="session") def bob(accounts):
yield accounts[1]
_SUPPLY // YEAR * q ** epoch) * ( chain[-1].timestamp - token.start_epoch_time() ) return S yield _fn # account aliases @pytest.fixture(scope="session") def alice(accounts): yield accounts[0] @pytest.fixture(scope="session") def bob(accounts):
64
64
16
10
54
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
bob
bob
66
68
66
67
ffbabdb832c460bc6b3b9c7f6cc2891c4fe8fdf5
bigcode/the-stack
train
8211922140467fe27278a35a
train
function
@pytest.fixture( scope="module", params=[ BTCBurner, CBurner, ETHBurner, LPBurner, MetaBurner, UnderlyingBurner, USDNBurner, YBurner, ], ) def burner(alice, bob, receiver, pool_proxy, request): Burner = request.param args = (pool_proxy,...
@pytest.fixture( scope="module", params=[ BTCBurner, CBurner, ETHBurner, LPBurner, MetaBurner, UnderlyingBurner, USDNBurner, YBurner, ], ) def burner(alice, bob, receiver, pool_proxy, request):
Burner = request.param args = (pool_proxy, receiver, receiver, alice, bob, {"from": alice}) idx = len(Burner.deploy.abi["inputs"]) + 1 yield Burner.deploy(*args[-idx:])
@pytest.fixture( scope="module", params=[ BTCBurner, CBurner, ETHBurner, LPBurner, MetaBurner, UnderlyingBurner, USDNBurner, YBurner, ], ) def burner(alice, bob, receiver, pool_proxy, request):
70
64
122
70
0
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
burner
burner
246
264
246
259
e4e6a4d2bc9f5336889de9b41aab342c95fc33c7
bigcode/the-stack
train
26740c7a0ab8055cfbd3f0a6
train
function
@pytest.fixture(scope="module") def gauge_wrapper(LiquidityGaugeWrapper, accounts, liquidity_gauge): yield LiquidityGaugeWrapper.deploy( "Tokenized Gauge", "TG", liquidity_gauge, accounts[0], {"from": accounts[0]} )
@pytest.fixture(scope="module") def gauge_wrapper(LiquidityGaugeWrapper, accounts, liquidity_gauge):
yield LiquidityGaugeWrapper.deploy( "Tokenized Gauge", "TG", liquidity_gauge, accounts[0], {"from": accounts[0]} )
": alice}) @pytest.fixture(scope="module") def rewards_only_gauge(RewardsOnlyGauge, alice, mock_lp_token): yield RewardsOnlyGauge.deploy(alice, mock_lp_token, {"from": alice}) @pytest.fixture(scope="module") def gauge_wrapper(LiquidityGaugeWrapper, accounts, liquidity_gauge):
64
64
55
21
43
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
gauge_wrapper
gauge_wrapper
153
157
153
154
d0b7d7978a1a9e7427e11743c9224c4b7b13b398
bigcode/the-stack
train
62f094b1ead243f57a03cf8e
train
function
@pytest.fixture(scope="module") def coin_c(): yield ERC20("Coin C", "mWBTC", 8)
@pytest.fixture(scope="module") def coin_c():
yield ERC20("Coin C", "mWBTC", 8)
# testing contracts @pytest.fixture(scope="module") def coin_a(): yield ERC20("Coin A", "USDA", 18) @pytest.fixture(scope="module") def coin_b(): yield ERC20("Coin B", "USDB", 18) @pytest.fixture(scope="module") def coin_c():
64
64
26
10
54
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
coin_c
coin_c
280
282
280
281
d0d994dc7ee7540e1439cc943cc241d30560660d
bigcode/the-stack
train
57a92cb5c243b688d7c2badb
train
function
@pytest.fixture(scope="module") def gauge_controller(GaugeController, accounts, token, voting_escrow): yield GaugeController.deploy(token, voting_escrow, {"from": accounts[0]})
@pytest.fixture(scope="module") def gauge_controller(GaugeController, accounts, token, voting_escrow):
yield GaugeController.deploy(token, voting_escrow, {"from": accounts[0]})
yield VotingEscrow.deploy( token, "Voting-escrowed CRV", "veCRV", "veCRV_0.99", {"from": accounts[0]} ) @pytest.fixture(scope="module") def gauge_controller(GaugeController, accounts, token, voting_escrow):
64
64
42
22
42
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
gauge_controller
gauge_controller
96
98
96
97
cd60044acb3870b1361f928db0d5acf2234b99cc
bigcode/the-stack
train
1d210dc9cf3dcb0c559057d3
train
function
@pytest.fixture(scope="module") def vesting_target(VestingEscrowSimple, accounts): yield VestingEscrowSimple.deploy({"from": accounts[0]})
@pytest.fixture(scope="module") def vesting_target(VestingEscrowSimple, accounts):
yield VestingEscrowSimple.deploy({"from": accounts[0]})
0]} ) coin_a._mint_for_testing(accounts[0], 10 ** 21) coin_a.approve(contract, 10 ** 21, {"from": accounts[0]}) yield contract @pytest.fixture(scope="module") def vesting_target(VestingEscrowSimple, accounts):
64
64
34
18
45
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
vesting_target
vesting_target
218
220
218
219
237792fcc355e8b4b1c021a82358cf85cd0bb00f
bigcode/the-stack
train
22bd4a8e2f52f1fef7689fd0
train
function
@pytest.fixture(scope="module") def crypto_math(alice, crypto_project): return crypto_project.CurveCryptoMath3.deploy({"from": alice})
@pytest.fixture(scope="module") def crypto_math(alice, crypto_project):
return crypto_project.CurveCryptoMath3.deploy({"from": alice})
@1.0.0") @pytest.fixture(scope="module") def crypto_lp_token(alice, crypto_project): return crypto_project.CurveTokenV4.deploy("Mock Crypto LP Token", "crvMock", {"from": alice}) @pytest.fixture(scope="module") def crypto_math(alice, crypto_project):
64
64
30
15
49
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
crypto_math
crypto_math
327
329
327
328
89c4c133d508007c18d3e5c332168906d95d114e
bigcode/the-stack
train
0a20fda9c321188000033f80
train
function
@pytest.fixture(scope="module") def start_time(chain): yield chain.time() + 1000 + 86400 * 365
@pytest.fixture(scope="module") def start_time(chain):
yield chain.time() + 1000 + 86400 * 365
, minter): contracts = [ LiquidityGauge.deploy(mock_lp_token, minter, accounts[0], {"from": accounts[0]}) for _ in range(3) ] yield contracts # VestingEscrow fixtures @pytest.fixture(scope="module") def start_time(chain):
64
64
28
11
52
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
start_time
start_time
198
200
198
199
c9d3d63d016d9b6ab28d56a42b0b4287e85be5f5
bigcode/the-stack
train
478058d94cfcab12e468ef38
train
function
@pytest.fixture(scope="module") def reward_gauge_wrapper(LiquidityGaugeRewardWrapper, accounts, liquidity_gauge_reward): yield LiquidityGaugeRewardWrapper.deploy( "Tokenized Reward Gauge", "TG", liquidity_gauge_reward, accounts[0], {"from": accounts[0]}, )
@pytest.fixture(scope="module") def reward_gauge_wrapper(LiquidityGaugeRewardWrapper, accounts, liquidity_gauge_reward):
yield LiquidityGaugeRewardWrapper.deploy( "Tokenized Reward Gauge", "TG", liquidity_gauge_reward, accounts[0], {"from": accounts[0]}, )
yield LiquidityGaugeReward.deploy( mock_lp_token, minter, reward_contract, coin_reward, accounts[0], {"from": accounts[0]}, ) @pytest.fixture(scope="module") def reward_gauge_wrapper(LiquidityGaugeRewardWrapper, accounts, liquidity_gauge_reward):
64
64
66
25
39
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
reward_gauge_wrapper
reward_gauge_wrapper
174
182
174
175
5fe99a65fe9247a92f750c070e20f860f9484a3f
bigcode/the-stack
train
8013c98a0bd7c57f00308d63
train
function
@pytest.fixture(scope="module") def fee_distributor(FeeDistributor, voting_escrow, accounts, coin_a, chain): def f(t=None): if not t: t = chain.time() return FeeDistributor.deploy( voting_escrow, t, coin_a, accounts[0], accounts[0], {"from": accounts[0]} ) yield ...
@pytest.fixture(scope="module") def fee_distributor(FeeDistributor, voting_escrow, accounts, coin_a, chain):
def f(t=None): if not t: t = chain.time() return FeeDistributor.deploy( voting_escrow, t, coin_a, accounts[0], accounts[0], {"from": accounts[0]} ) yield f
10 ** 6, {"from": accounts[0]} ) mock_lp_token.set_minter(curve_pool, {"from": accounts[0]}) yield curve_pool @pytest.fixture(scope="module") def fee_distributor(FeeDistributor, voting_escrow, accounts, coin_a, chain):
64
64
81
26
37
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
fee_distributor
fee_distributor
300
309
300
301
b91b7fb11eb2f5c59ae28e22583d94dd2098abc0
bigcode/the-stack
train
23e96f04d210deeb9e38667b
train
function
@pytest.fixture(scope="session") def receiver(accounts): yield accounts.at("0x0000000000000000000000000000000000031337", True)
@pytest.fixture(scope="session") def receiver(accounts):
yield accounts.at("0x0000000000000000000000000000000000031337", True)
# account aliases @pytest.fixture(scope="session") def alice(accounts): yield accounts[0] @pytest.fixture(scope="session") def bob(accounts): yield accounts[1] @pytest.fixture(scope="session") def charlie(accounts): yield accounts[2] @pytest.fixture(scope="session") def receiver(accounts):
64
64
34
10
54
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
receiver
receiver
76
78
76
77
ca14c3a663eb59ed694302043520769c15bea9ed
bigcode/the-stack
train
e861d05cc5565254c8e1d9f9
train
function
@pytest.fixture(autouse=True) def isolation_setup(fn_isolation): pass
@pytest.fixture(autouse=True) def isolation_setup(fn_isolation):
pass
(a + b) <= precision def pack_values(values): packed = b"".join(i.to_bytes(1, "big") for i in values) padded = packed + bytes(32 - len(values)) return padded @pytest.fixture(autouse=True) def isolation_setup(fn_isolation):
64
64
17
14
49
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
isolation_setup
isolation_setup
34
36
34
35
920629568f8c5e3a9bfe005c01923ee6719b6c36
bigcode/the-stack
train
6c54c051e29af4436ae60b4c
train
function
@pytest.fixture(scope="module") def minter(Minter, accounts, gauge_controller, token): yield Minter.deploy(token, gauge_controller, {"from": accounts[0]})
@pytest.fixture(scope="module") def minter(Minter, accounts, gauge_controller, token):
yield Minter.deploy(token, gauge_controller, {"from": accounts[0]})
]} ) @pytest.fixture(scope="module") def gauge_controller(GaugeController, accounts, token, voting_escrow): yield GaugeController.deploy(token, voting_escrow, {"from": accounts[0]}) @pytest.fixture(scope="module") def minter(Minter, accounts, gauge_controller, token):
64
64
37
19
45
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
minter
minter
101
103
101
102
380f1b61d2569266fb209e129ac436c3f3a638c0
bigcode/the-stack
train
b1557f7133502a2a95c02f22
train
function
@pytest.fixture(scope="module") def token(ERC20CRV, accounts): yield ERC20CRV.deploy("Curve DAO Token", "CRV", 18, {"from": accounts[0]})
@pytest.fixture(scope="module") def token(ERC20CRV, accounts):
yield ERC20CRV.deploy("Curve DAO Token", "CRV", 18, {"from": accounts[0]})
charlie(accounts): yield accounts[2] @pytest.fixture(scope="session") def receiver(accounts): yield accounts.at("0x0000000000000000000000000000000000031337", True) # core contracts @pytest.fixture(scope="module") def token(ERC20CRV, accounts):
64
64
43
16
47
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
token
token
84
86
84
85
4b7b194b822b34aeffff3c61d08110d77bb3d627
bigcode/the-stack
train
d5f8990e24536ad60569774f
train
function
@pytest.fixture(scope="module") def end_time(start_time): yield start_time + 100000000
@pytest.fixture(scope="module") def end_time(start_time):
yield start_time + 100000000
0]}) for _ in range(3) ] yield contracts # VestingEscrow fixtures @pytest.fixture(scope="module") def start_time(chain): yield chain.time() + 1000 + 86400 * 365 @pytest.fixture(scope="module") def end_time(start_time):
64
64
22
12
51
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
end_time
end_time
203
205
203
204
cbb4cfbe8643c9df2c98f596f5ab3b9337d59d9e
bigcode/the-stack
train
1465163eacef9dcf7f984dec
train
function
@pytest.fixture(scope="module") def theoretical_supply(chain, token): def _fn(): epoch = token.mining_epoch() q = 1 / 2 ** 0.25 S = INITIAL_SUPPLY * 10 ** 18 if epoch > 0: S += int(YEAR_1_SUPPLY * (1 - q ** epoch) / (1 - q)) S += int(YEAR_1_SUPPLY // YEAR * q ** e...
@pytest.fixture(scope="module") def theoretical_supply(chain, token):
def _fn(): epoch = token.mining_epoch() q = 1 / 2 ** 0.25 S = INITIAL_SUPPLY * 10 ** 18 if epoch > 0: S += int(YEAR_1_SUPPLY * (1 - q ** epoch) / (1 - q)) S += int(YEAR_1_SUPPLY // YEAR * q ** epoch) * ( chain[-1].timestamp - token.start_epoch_time() ...
_bytes(1, "big") for i in values) padded = packed + bytes(32 - len(values)) return padded @pytest.fixture(autouse=True) def isolation_setup(fn_isolation): pass # helper functions as fixtures @pytest.fixture(scope="module") def theoretical_supply(chain, token):
64
64
126
13
50
AqualisDAO/curve-dao-contracts
tests/conftest.py
Python
theoretical_supply
theoretical_supply
42
55
42
43
f1579b9e5c4758e7de8c1cfd7c2cb03952a23bf0
bigcode/the-stack
train
cff1b135ae63481d6b639d4c
train
function
def add_link(request): if request.method == 'POST': form = LinkCreateForm(request.POST) if form.is_valid(): link_obj = form.save(commit=False) link_obj.timestamp = timezone.now() link_obj.save() return redirect(link_obj.get_absolute_url()) else: ...
def add_link(request):
if request.method == 'POST': form = LinkCreateForm(request.POST) if form.is_valid(): link_obj = form.save(commit=False) link_obj.timestamp = timezone.now() link_obj.save() return redirect(link_obj.get_absolute_url()) else: form = LinkCreate...
from django.shortcuts import render, redirect, get_object_or_404 from django.utils import timezone from links.forms import LinkCreateForm from links.models import Link def add_link(request):
39
64
85
5
33
janokruta/wklej.us
links/views.py
Python
add_link
add_link
8
18
8
8
2528ef0b4f91ece8f3b006114b7ae11819bb52d7
bigcode/the-stack
train
b581ecb98336f1917c29cbdb
train
function
def link_detail(request, slug): link_obj = get_object_or_404(Link, slug=slug) context = { 'text': link_obj.text, 'slug': slug, 'timestamp': link_obj.timestamp } return render(request, 'links/link_detail.html', context)
def link_detail(request, slug):
link_obj = get_object_or_404(Link, slug=slug) context = { 'text': link_obj.text, 'slug': slug, 'timestamp': link_obj.timestamp } return render(request, 'links/link_detail.html', context)
link_obj = form.save(commit=False) link_obj.timestamp = timezone.now() link_obj.save() return redirect(link_obj.get_absolute_url()) else: form = LinkCreateForm() return render(request, 'links/add_link.html', {'form': form}) def link_detail(request, slu...
64
64
63
7
57
janokruta/wklej.us
links/views.py
Python
link_detail
link_detail
21
28
21
21
91dabdcaad78892d0dd2d4e2b3d15fe22960c473
bigcode/the-stack
train
5a0360102df08075bd622f7b
train
function
def test_user_wins_match_by_number(global_store, roulette_queue): # build a user user = UserData("user") user_id = "user" user.roulette_bet = [(5, 10)] # put user into data structures global_store[user_id] = user roulette_queue.add(user_id) # run test service = RouletteQueueManange...
def test_user_wins_match_by_number(global_store, roulette_queue): # build a user
user = UserData("user") user_id = "user" user.roulette_bet = [(5, 10)] # put user into data structures global_store[user_id] = user roulette_queue.add(user_id) # run test service = RouletteQueueManangerService(global_store, roulette_queue) result = service.determine(5, "red") a...
from services.roulette_queue_manager_service import RouletteQueueManangerService from models.user_data import UserData def test_user_wins_match_by_number(global_store, roulette_queue): # build a user
42
64
154
20
21
rhsu/slackjack
test/services_tests/test_roulette_queue_manager_service.py
Python
test_user_wins_match_by_number
test_user_wins_match_by_number
5
20
5
6
caca7e0e6eb37dbaf7d2a8ea96135485d6afa035
bigcode/the-stack
train
6922c3a9d92193a228a40290
train
function
def test_user_wins_match_by_color(global_store, roulette_queue): # build a user user = UserData("user") user_id = "user" # TODO: for consistency. I would like the thing to be (string, int) user.roulette_bet = [("red", 10)] global_store[user_id] = user roulette_queue.add(user_id) # run ...
def test_user_wins_match_by_color(global_store, roulette_queue): # build a user
user = UserData("user") user_id = "user" # TODO: for consistency. I would like the thing to be (string, int) user.roulette_bet = [("red", 10)] global_store[user_id] = user roulette_queue.add(user_id) # run test service = RouletteQueueManangerService(global_store, roulette_queue) re...
is 5 :red_circle:. \n *user* bet on *5*. *user* won. \n" assert user.money == 450 assert len(roulette_queue) == 0 def test_user_wins_match_by_color(global_store, roulette_queue): # build a user
64
64
169
20
43
rhsu/slackjack
test/services_tests/test_roulette_queue_manager_service.py
Python
test_user_wins_match_by_color
test_user_wins_match_by_color
23
38
23
24
e160dd95dd487ba0f7a47ed26c3bdc3e1b8994a2
bigcode/the-stack
train
eb6df6058f7d1d5342211677
train
function
def test_two_users_winer_and_loser(global_store, roulette_queue): # build a winner winner = UserData("winner") winner_id = "winner" winner.roulette_bet = [("red", 10)] # build a loser loser = UserData("loser") loser_id = "loser" loser.roulette_bet = [("black", 10)] # put user into ...
def test_two_users_winer_and_loser(global_store, roulette_queue): # build a winner
winner = UserData("winner") winner_id = "winner" winner.roulette_bet = [("red", 10)] # build a loser loser = UserData("loser") loser_id = "loser" loser.roulette_bet = [("black", 10)] # put user into data structures global_store[winner_id] = winner global_store[loser_id] = loser...
black") assert result == "The result is 2 :black_circle:. \n *user* bet on *:red_circle:*. *user* lost. \n" assert user.money == 90 assert len(roulette_queue) == 0 def test_two_users_winer_and_loser(global_store, roulette_queue): # build a winner
77
77
258
21
55
rhsu/slackjack
test/services_tests/test_roulette_queue_manager_service.py
Python
test_two_users_winer_and_loser
test_two_users_winer_and_loser
59
84
59
60
2a400ab19a1571a82527ee7f82507e5bf2fc8d00
bigcode/the-stack
train
4741e0af15ee984d9ce5419a
train
function
def test_user_loses(global_store, roulette_queue): # build a user user = UserData("user") user_id = "user" user.roulette_bet = [("red", 10)] # put user into data structures global_store[user_id] = user roulette_queue.add(user_id) # run test service = RouletteQueueManangerService(gl...
def test_user_loses(global_store, roulette_queue): # build a user
user = UserData("user") user_id = "user" user.roulette_bet = [("red", 10)] # put user into data structures global_store[user_id] = user roulette_queue.add(user_id) # run test service = RouletteQueueManangerService(global_store, roulette_queue) result = service.determine(2, "black")...
is 5 :red_circle:. \n *user* bet on *:red_circle:*. *user* won. \n" assert user.money == 110 assert len(roulette_queue) == 0 def test_user_loses(global_store, roulette_queue): # build a user
64
64
155
17
46
rhsu/slackjack
test/services_tests/test_roulette_queue_manager_service.py
Python
test_user_loses
test_user_loses
41
56
41
42
72fe95d80b54fab64ed7478eb2f77e0d2bb56ae3
bigcode/the-stack
train
5723bda446b1f9348626a4fb
train
class
class HTTPRequest(BaseHTTPRequestHandler): def __init__(self, request_text): self.rfile = StringIO(request_text) self.raw_requestline = self.rfile.readline() self.error_code = self.error_message = None self.parse_request()
class HTTPRequest(BaseHTTPRequestHandler):
def __init__(self, request_text): self.rfile = StringIO(request_text) self.raw_requestline = self.rfile.readline() self.error_code = self.error_message = None self.parse_request()
import SocketServer import hashlib import base64 import socket import struct import ssl import time import sys import errno import logging from BaseHTTPServer import BaseHTTPRequestHandler from StringIO import StringIO from select import select class HTTPRequest(BaseHTTPRequestHandler):
60
64
54
7
52
Xe/code
irc/duta-server/prototype/src/websocket/handler.py
Python
HTTPRequest
HTTPRequest
16
21
16
16
7795bea7d7f6cfcbf7a70736ec3a5a58ba9a6c22
bigcode/the-stack
train
b875ed699f14b4e570dc1e92
train
class
class SimpleSSLWebSocketServer(SimpleWebSocketServer): def __init__(self, host, port, websocketclass, certfile, keyfile, version = ssl.PROTOCOL_TLSv1): SimpleWebSocketServer.__init__(self, host, port, websocketclass) self.cerfile = certfile self.keyfile = keyfile self.vers...
class SimpleSSLWebSocketServer(SimpleWebSocketServer):
def __init__(self, host, port, websocketclass, certfile, keyfile, version = ssl.PROTOCOL_TLSv1): SimpleWebSocketServer.__init__(self, host, port, websocketclass) self.cerfile = certfile self.keyfile = keyfile self.version = version def close(self): super(Simpl...
else: client = self.connections[failed] fileno = client.client.fileno() try: client.handleClose() except: pass client.close() ...
64
64
203
11
53
Xe/code
irc/duta-server/prototype/src/websocket/handler.py
Python
SimpleSSLWebSocketServer
SimpleSSLWebSocketServer
580
607
580
581
e4111bb7c69d105d33fa7639fda6f6caa2dacc70
bigcode/the-stack
train
80749d93ed67fd6cae8680be
train
class
class SimpleWebSocketServer(object): def __init__(self, host, port, websocketclass): self.websocketclass = websocketclass self.serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.serversock...
class SimpleWebSocketServer(object):
def __init__(self, host, port, websocketclass): self.websocketclass = websocketclass self.serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.serversocket.bind((host, port)) self.se...
LOAD: if self.hasmask is True: self.data.append( byte ^ self.maskarray[self.index % 4] ) else: self.data.append( byte ) # if length exceeds allowable size then we except and remove the connection if len(self.data) >= self.maxpayload...
144
144
482
7
136
Xe/code
irc/duta-server/prototype/src/websocket/handler.py
Python
SimpleWebSocketServer
SimpleWebSocketServer
491
577
491
491
de9c2cd327b8b3382952f53b3524697ace23ad0b
bigcode/the-stack
train
33ee26933ec251febeb411ca
train
class
class WebSocket(object): handshakeStr = ( "HTTP/1.1 101 Switching Protocols\r\n" "Upgrade: WebSocket\r\n" "Connection: Upgrade\r\n" "Sec-WebSocket-Accept: %(acceptstr)s\r\n\r\n" ) hixiehandshakedStr = ( "HTTP/1.1 101 WebSocket Protocol Handshake\r\n" ...
class WebSocket(object):
handshakeStr = ( "HTTP/1.1 101 Switching Protocols\r\n" "Upgrade: WebSocket\r\n" "Connection: Upgrade\r\n" "Sec-WebSocket-Accept: %(acceptstr)s\r\n\r\n" ) hixiehandshakedStr = ( "HTTP/1.1 101 WebSocket Protocol Handshake\r\n" "Upgrade: WebSocket\r\n"...
import SocketServer import hashlib import base64 import socket import struct import ssl import time import sys import errno import logging from BaseHTTPServer import BaseHTTPRequestHandler from StringIO import StringIO from select import select class HTTPRequest(BaseHTTPRequestHandler): def __init...
112
256
3,094
5
107
Xe/code
irc/duta-server/prototype/src/websocket/handler.py
Python
WebSocket
WebSocket
24
488
24
25
d9c7e5b51708b86abf7738504bdc2d182098313c
bigcode/the-stack
train
9683497e25b93482cc5e1142
train
function
@app.route('/task04') def detect_task04(): return flask.render_template('clova_mypet.html', has_result=False)
@app.route('/task04') def detect_task04():
return flask.render_template('clova_mypet.html', has_result=False)
('/task02') def detect_task02(): return flask.render_template('detect_crested_gecko.html', has_result=False) @app.route('/task03') def detect_task03(): return flask.render_template('detect_tt100k.html', has_result=False) @app.route('/task04') def detect_task04():
64
64
28
11
53
asyncbridge/web-ui
src/app.py
Python
detect_task04
detect_task04
232
234
232
233
bb9cec7886446ae2dcc2298088033a40c034e7ff
bigcode/the-stack
train
e1a26af496e3ab6584130f97
train
function
def http_error_response(error_msg, status_code): data = { 'status_code': status_code, 'msg': error_msg } js = json.dumps(data) res = Response(js, status=status_code, mimetype='application/json') logger.error(error_msg) return res
def http_error_response(error_msg, status_code):
data = { 'status_code': status_code, 'msg': error_msg } js = json.dumps(data) res = Response(js, status=status_code, mimetype='application/json') logger.error(error_msg) return res
# data = string_buf.getvalue().encode('base64').replace('\n', '') data = base64.b64encode(stream.getvalue()).decode('utf-8').replace('\n', '') return 'data:image/jpg;base64,' + data def http_error_response(error_msg, status_code):
64
64
64
10
53
asyncbridge/web-ui
src/app.py
Python
http_error_response
http_error_response
191
201
191
191
71aa01f27107a7c40c3a3a228d61514c27c78936
bigcode/the-stack
train
e78756ecb2d238ac26b87bb0
train
function
def showAnnsBBoxTT100K(image, annotations): if len(annotations) == 0 : logging.error("showAnnsBBoxTT100K: there are no items in annotations.") return image text_color = (0, 0, 0) font = cv2.FONT_HERSHEY_SIMPLEX #font_scale = 0.8 * (image.shape[1]/768) font_scale = 0.6 margin...
def showAnnsBBoxTT100K(image, annotations):
if len(annotations) == 0 : logging.error("showAnnsBBoxTT100K: there are no items in annotations.") return image text_color = (0, 0, 0) font = cv2.FONT_HERSHEY_SIMPLEX #font_scale = 0.8 * (image.shape[1]/768) font_scale = 0.6 margin = 5 thickness = 2 for ann in annotation...
TECTED_IMAGE_OUTPUT_WIDTH = 512 HOSTNAME = 'localhost' POST_API_URI_TASK_01 = 'http://'+HOSTNAME+':5001/detect_object?embed_image=false' POST_API_URI_TASK_02 = 'http://'+HOSTNAME+':5002/detect_object?embed_image=false' POST_API_URI_TASK_03 = 'http://'+HOSTNAME+':5003/detect_object?embed_image=false' app = flask.Flask...
123
123
412
13
109
asyncbridge/web-ui
src/app.py
Python
showAnnsBBoxTT100K
showAnnsBBoxTT100K
37
83
37
38
74a994e9713695ab7ff4779d1e03c16f595d132b
bigcode/the-stack
train
c064ea4ec2c262cf63e0908f
train
function
def resize_image_pil(image_pil, width=None, height=None): dim = None w, h = image_pil.size if width is None and height is None: return image if width is None: r = height / float(h) dim = (int(w * r), height) else: r = width / float(w) dim = (width, int(h * r...
def resize_image_pil(image_pil, width=None, height=None):
dim = None w, h = image_pil.size if width is None and height is None: return image if width is None: r = height / float(h) dim = (int(w * r), height) else: r = width / float(w) dim = (width, int(h * r)) resized = image_pil.resize(dim) return resize...
= (int(w * r), height) else: r = width / float(w) dim = (width, int(h * r)) resized = cv2.resize(image, dim, interpolation=inter) return resized def resize_image_pil(image_pil, width=None, height=None):
64
64
104
15
48
asyncbridge/web-ui
src/app.py
Python
resize_image_pil
resize_image_pil
153
169
153
153
dff7108e626cb313a2dba8843129d1c9e8e9751c
bigcode/the-stack
train
f4656626be49d1b2876995b7
train
function
@app.route('/task03_classify_upload', methods=['POST']) def classify_upload_task03(): if not os.path.exists(UPLOAD_FOLDER): os.makedirs(UPLOAD_FOLDER) if flask.request.files['submitImageFile'].filename == '': return http_error_response("There is no image file.", 412) try: imagefile...
@app.route('/task03_classify_upload', methods=['POST']) def classify_upload_task03():
if not os.path.exists(UPLOAD_FOLDER): os.makedirs(UPLOAD_FOLDER) if flask.request.files['submitImageFile'].filename == '': return http_error_response("There is no image file.", 412) try: imagefile = flask.request.files['submitImageFile'] logging.info('imagefile: %s', imagef...
_gecko.html', has_result=True, result=(False, 'Cannot open uploaded image.') ) json_result = json.loads(response.text) detected_result = json_result["result"]["data"][0]["detected_results"] im_arr = exifutil.open_oriented_im(filename) detected_image = showAnnsBBox(im_arr, detected_...
220
220
734
19
201
asyncbridge/web-ui
src/app.py
Python
classify_upload_task03
classify_upload_task03
418
513
418
419
96693b6ce2136e197bdc6fcca1919d59c48afa8f
bigcode/the-stack
train
b770c0f8b19b56c1deffad4e
train
function
def showAnnsBBox(image, annotations): if len(annotations) == 0 : logging.error("showAnnsBBox: there are no items in annotations.") return image text_color = (0, 0, 0) font = cv2.FONT_HERSHEY_SIMPLEX #font_scale = 0.8 * (image.shape[1]/768) font_scale = 0.6 margin = 5 thickne...
def showAnnsBBox(image, annotations):
if len(annotations) == 0 : logging.error("showAnnsBBox: there are no items in annotations.") return image text_color = (0, 0, 0) font = cv2.FONT_HERSHEY_SIMPLEX #font_scale = 0.8 * (image.shape[1]/768) font_scale = 0.6 margin = 5 thickness = 2 for ann in annotations: ...
txt_y = y - 10 if ty < 0: ty = y ty_e = y + 20 + margin txt_y = y + 15 image = cv2.rectangle(image, (x, ty), (x + int(text_width) + margin, ty_e), color, -1) image = cv2.putText(image, class_name, (x + margin, txt_y), font, font_scal...
127
127
426
9
117
asyncbridge/web-ui
src/app.py
Python
showAnnsBBox
showAnnsBBox
86
133
86
87
e46e6c5314c8a06694451cbc00962ee6e7baf864
bigcode/the-stack
train
467e9ae36634a4d418d38dc8
train
function
@app.route('/task01_classify_upload', methods=['POST']) def classify_upload_task01(): if not os.path.exists(UPLOAD_FOLDER): os.makedirs(UPLOAD_FOLDER) if flask.request.files['submitImageFile'].filename == '': return http_error_response("There is no image file.", 412) try: imagefile...
@app.route('/task01_classify_upload', methods=['POST']) def classify_upload_task01():
if not os.path.exists(UPLOAD_FOLDER): os.makedirs(UPLOAD_FOLDER) if flask.request.files['submitImageFile'].filename == '': return http_error_response("There is no image file.", 412) try: imagefile = flask.request.files['submitImageFile'] logging.info('imagefile: %s', imagef...
= { 'status_code': 200, 'msg': message, 'result': result } js = json.dumps(data) res = Response(js, status=200, mimetype='application/json') return res @app.route('/') def index(): return flask.render_template('index.html', has_result=False) @app.route('/task01') def det...
198
198
662
19
179
asyncbridge/web-ui
src/app.py
Python
classify_upload_task01
classify_upload_task01
236
322
236
237
4ce89c692c2ef9cc09d7c6203b2b1541d9276f3b
bigcode/the-stack
train
94a1f9474e029798803db9bc
train
function
def resize_image(image, width=None, height=None, inter=cv2.INTER_AREA): dim = None (h, w) = image.shape[:2] if width is None and height is None: return image if width is None: r = height / float(h) dim = (int(w * r), height) else: r = width / float(w) dim = ...
def resize_image(image, width=None, height=None, inter=cv2.INTER_AREA):
dim = None (h, w) = image.shape[:2] if width is None and height is None: return image if width is None: r = height / float(h) dim = (int(w * r), height) else: r = width / float(w) dim = (width, int(h * r)) resized = cv2.resize(image, dim, interpolation=...
) + margin, ty_e), color, -1) image = cv2.putText(image, class_name, (x + margin, txt_y), font, font_scale, text_color, thickness) return image def resize_image(image, width=None, height=None, inter=cv2.INTER_AREA):
64
64
113
17
46
asyncbridge/web-ui
src/app.py
Python
resize_image
resize_image
135
151
135
135
14aa7553f7775c9ba57fa77a1ccfb04553384bba
bigcode/the-stack
train
ae0cffe1feb4d16704cff783
train
function
@app.route('/task01') def detect_task01(): return flask.render_template('detect_coco.html', has_result=False)
@app.route('/task01') def detect_task01():
return flask.render_template('detect_coco.html', has_result=False)
'result': result } js = json.dumps(data) res = Response(js, status=200, mimetype='application/json') return res @app.route('/') def index(): return flask.render_template('index.html', has_result=False) @app.route('/task01') def detect_task01():
64
64
26
11
53
asyncbridge/web-ui
src/app.py
Python
detect_task01
detect_task01
220
222
220
221
1ca415c46a4a37bafcc4011364322c181c7d6a80
bigcode/the-stack
train
1455a1d5adb2245d319aa448
train
function
@app.route('/task02_classify_upload', methods=['POST']) def classify_upload_task02(): if not os.path.exists(UPLOAD_FOLDER): os.makedirs(UPLOAD_FOLDER) if flask.request.files['submitImageFile'].filename == '': return http_error_response("There is no image file.", 412) try: imagefile...
@app.route('/task02_classify_upload', methods=['POST']) def classify_upload_task02():
if not os.path.exists(UPLOAD_FOLDER): os.makedirs(UPLOAD_FOLDER) if flask.request.files['submitImageFile'].filename == '': return http_error_response("There is no image file.", 412) try: imagefile = flask.request.files['submitImageFile'] logging.info('imagefile: %s', imagef...
.') ) json_result = json.loads(response.text) detected_result = json_result["result"]["data"][0]["detected_results"] im_arr = exifutil.open_oriented_im(filename) detected_image = showAnnsBBox(im_arr, detected_result) embed_detected_image = embed_image_html(detected_image) elapsed_time ...
200
201
673
19
181
asyncbridge/web-ui
src/app.py
Python
classify_upload_task02
classify_upload_task02
329
415
329
330
25c225db6adcbd93de6f32826d301bde742edde5
bigcode/the-stack
train
ce4c3b76b453a5e1770df9dc
train
function
@app.route('/task04_mypet', methods=['POST']) def task04_mypet(): signatureCEK = '' message = '' if 'SignatureCEK' in request.headers: signatureCEK = request.headers['SignatureCEK'] data = request.get_json() requestBody = json.dumps(data) #print("request body: "+requestBody) #print("sign...
@app.route('/task04_mypet', methods=['POST']) def task04_mypet():
signatureCEK = '' message = '' if 'SignatureCEK' in request.headers: signatureCEK = request.headers['SignatureCEK'] data = request.get_json() requestBody = json.dumps(data) #print("request body: "+requestBody) #print("signatureCEK type: ") print(type(signatureCEK)) #print("signatur...
%s', filename) return flask.render_template('detect_tt100k.html', has_result=True, result=(True, num_of_result, detected_result, elapsed_time), imagesrc=embed_detected_image) @app.route('/task04_mypet', methods=['POST']) def task04_mypet():
64
64
178
20
44
asyncbridge/web-ui
src/app.py
Python
task04_mypet
task04_mypet
515
538
515
516
7e028dfb43d1245f1a8f38aa45670d74aeb900c4
bigcode/the-stack
train
5928b39da8e854f86a56486d
train
function
def embed_image_html(image): """Creates an image embedded in HTML base64 format.""" #image_output_width = DETECTED_IMAGE_OUTPUT_WIDTH #if image.shape[1] < image_output_width: # image_output_width = image.shape[1] #image_pil = resize_image(image, width=image_output_width) image_pil = image ...
def embed_image_html(image):
"""Creates an image embedded in HTML base64 format.""" #image_output_width = DETECTED_IMAGE_OUTPUT_WIDTH #if image.shape[1] < image_output_width: # image_output_width = image.shape[1] #image_pil = resize_image(image, width=image_output_width) image_pil = image # image_pil = Image.fromarr...
width is None: r = height / float(h) dim = (int(w * r), height) else: r = width / float(w) dim = (width, int(h * r)) resized = image_pil.resize(dim) return resized def embed_image_html(image):
64
64
203
6
57
asyncbridge/web-ui
src/app.py
Python
embed_image_html
embed_image_html
172
188
172
172
81bc5ecb115ef843bc93fc6fe97ab09d15463df1
bigcode/the-stack
train
66b078ae4309d19614dd9d00
train
function
@app.route('/task03') def detect_task03(): return flask.render_template('detect_tt100k.html', has_result=False)
@app.route('/task03') def detect_task03():
return flask.render_template('detect_tt100k.html', has_result=False)
.route('/task01') def detect_task01(): return flask.render_template('detect_coco.html', has_result=False) @app.route('/task02') def detect_task02(): return flask.render_template('detect_crested_gecko.html', has_result=False) @app.route('/task03') def detect_task03():
64
64
27
11
53
asyncbridge/web-ui
src/app.py
Python
detect_task03
detect_task03
228
230
228
229
a49efd2838a53873434c22e01c7532a777715ae8
bigcode/the-stack
train
e4fb7422ed0245d122fd4c14
train
function
@app.route('/task02') def detect_task02(): return flask.render_template('detect_crested_gecko.html', has_result=False)
@app.route('/task02') def detect_task02():
return flask.render_template('detect_crested_gecko.html', has_result=False)
='application/json') return res @app.route('/') def index(): return flask.render_template('index.html', has_result=False) @app.route('/task01') def detect_task01(): return flask.render_template('detect_coco.html', has_result=False) @app.route('/task02') def detect_task02():
64
64
28
11
53
asyncbridge/web-ui
src/app.py
Python
detect_task02
detect_task02
224
226
224
225
dc6c0e836cf553746fae6358d176911fb27a68e3
bigcode/the-stack
train
5d8f94dab577b8940decb695
train
function
@app.route('/') def index(): return flask.render_template('index.html', has_result=False)
@app.route('/') def index():
return flask.render_template('index.html', has_result=False)
_response(message, result): data = { 'status_code': 200, 'msg': message, 'result': result } js = json.dumps(data) res = Response(js, status=200, mimetype='application/json') return res @app.route('/') def index():
64
64
19
6
57
asyncbridge/web-ui
src/app.py
Python
index
index
216
218
216
217
4428c818e5d95385b80b891af3970a35e971abc9
bigcode/the-stack
train
2af71126623944a5f8e43f42
train
function
def http_success_response(message, result): data = { 'status_code': 200, 'msg': message, 'result': result } js = json.dumps(data) res = Response(js, status=200, mimetype='application/json') return res
def http_success_response(message, result):
data = { 'status_code': 200, 'msg': message, 'result': result } js = json.dumps(data) res = Response(js, status=200, mimetype='application/json') return res
_code): data = { 'status_code': status_code, 'msg': error_msg } js = json.dumps(data) res = Response(js, status=status_code, mimetype='application/json') logger.error(error_msg) return res def http_success_response(message, result):
64
64
61
8
55
asyncbridge/web-ui
src/app.py
Python
http_success_response
http_success_response
204
214
204
204
bcb35d78d3debfc62faead360d3b350a81ba3a77
bigcode/the-stack
train
de9f7e7e6a202e17d9965740
train
function
def G_l1(G, D, opt, training_set, minibatch_size, reals): _ = opt latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:]) labels = training_set.get_random_labels_tf(minibatch_size) rho = np.array([1]) fake_images_out = G.get_output_for(latents, labels, rho, is_training=True) loss = ...
def G_l1(G, D, opt, training_set, minibatch_size, reals):
_ = opt latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:]) labels = training_set.get_random_labels_tf(minibatch_size) rho = np.array([1]) fake_images_out = G.get_output_for(latents, labels, rho, is_training=True) loss = tf.reduce_mean(tf.abs(reals - fake_images_out)) return...
_output_for(fake_images_out, labels, is_training=True)[:,0:1] loss = tf.nn.softplus(-fake_scores_out) # -log(sigmoid(fake_scores_out)) return loss, None def G_l1(G, D, opt, training_set, minibatch_size, reals):
64
64
110
20
43
ak9250/few-shot-gan
training/loss.py
Python
G_l1
G_l1
72
79
72
72
ddeefb0c50bf8ca65fd4b8787b3e714af6bc0142
bigcode/the-stack
train
97f689eae3f89e840ffcfa06
train
function
def D_ns_diffaug_r1(G, D, training_set, minibatch_size, reals, gamma=10, policy='color,translation,cutout', **kwargs): latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:]) labels = training_set.get_random_labels_tf(minibatch_size) rho = np.array([1]) fakes = G.get_output_for(latents, lab...
def D_ns_diffaug_r1(G, D, training_set, minibatch_size, reals, gamma=10, policy='color,translation,cutout', **kwargs):
latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:]) labels = training_set.get_random_labels_tf(minibatch_size) rho = np.array([1]) fakes = G.get_output_for(latents, labels, rho, is_training=True) real_scores = D.get_output_for(DiffAugment(reals, policy=policy, channels_first=True), ...
lib.tflib as tflib from dnnlib.tflib.autosummary import autosummary from DiffAugment_tf import DiffAugment #------------------------------------------- # DiffAugment loss # https://github.com/mit-han-lab/data-efficient-gans def D_ns_diffaug_r1(G, D, training_set, minibatch_size, reals, gamma=10, policy='color,translat...
95
95
319
37
57
ak9250/few-shot-gan
training/loss.py
Python
D_ns_diffaug_r1
D_ns_diffaug_r1
19
35
19
19
cee6bc4a12063e3856e97d128bdcc304f937292c
bigcode/the-stack
train
332cef2c9939941d94baa373
train
function
def D_wgan(G, D, opt, training_set, minibatch_size, reals, labels, wgan_epsilon=0.001): _ = opt, training_set latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:]) fake_images_out = G.get_output_for(latents, labels, is_training=True) real_scores_out = D.get_output_for(reals, labels, is_tr...
def D_wgan(G, D, opt, training_set, minibatch_size, reals, labels, wgan_epsilon=0.001):
_ = opt, training_set latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:]) fake_images_out = G.get_output_for(latents, labels, is_training=True) real_scores_out = D.get_output_for(reals, labels, is_training=True) fake_scores_out = D.get_output_for(fake_images_out, labels, is_training...
D.get_output_for(fake_images_out, labels, is_training=True)[:,0:1] loss = -fake_scores_out return loss, None def D_wgan(G, D, opt, training_set, minibatch_size, reals, labels, wgan_epsilon=0.001):
64
64
211
31
32
ak9250/few-shot-gan
training/loss.py
Python
D_wgan
D_wgan
149
161
149
149
9ec6b5c48696d9683e2ad1ae88b5317a918f4423
bigcode/the-stack
train
abb59d0bda0075bf71c2e633
train
function
def D_logistic(G, D, opt, training_set, minibatch_size, reals, labels): _ = opt, training_set latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:]) fake_images_out = G.get_output_for(latents, labels, is_training=True) real_scores_out = D.get_output_for(reals, labels, is_training=True) ...
def D_logistic(G, D, opt, training_set, minibatch_size, reals, labels):
_ = opt, training_set latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:]) fake_images_out = G.get_output_for(latents, labels, is_training=True) real_scores_out = D.get_output_for(reals, labels, is_training=True) fake_scores_out = D.get_output_for(fake_images_out, labels, is_training...
.abs(reals - fake_images_out)) return loss, None def D_none(G, D, opt, training_set, minibatch_size, reals, labels): return 0, None def D_logistic(G, D, opt, training_set, minibatch_size, reals, labels):
64
64
205
22
41
ak9250/few-shot-gan
training/loss.py
Python
D_logistic
D_logistic
84
94
84
84
a3000d12647d137ed40b8b8e69320ad4c4686f28
bigcode/the-stack
train
fc134bb83b1118d8e7c0182f
train
function
def D_logistic_r1(G, D, opt, training_set, minibatch_size, reals, labels, gamma=10.0): _ = opt, training_set latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:]) rho = np.array([1]) fake_images_out = G.get_output_for(latents, labels, rho, is_training=True) real_scores_out = D.get_out...
def D_logistic_r1(G, D, opt, training_set, minibatch_size, reals, labels, gamma=10.0):
_ = opt, training_set latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:]) rho = np.array([1]) fake_images_out = G.get_output_for(latents, labels, rho, is_training=True) real_scores_out = D.get_output_for(reals, labels, is_training=True) fake_scores_out = D.get_output_for(fake_im...
(sigmoid(real_scores_out)) # pylint: disable=invalid-unary-operand-type return loss, None #---------------------------------------------------------------------------- # R1 and R2 regularizers from the paper # "Which Training Methods for GANs do actually Converge?", Mescheder et al. 2018 def D_logistic_r1(G, D, op...
92
92
308
30
61
ak9250/few-shot-gan
training/loss.py
Python
D_logistic_r1
D_logistic_r1
100
116
100
100
264c4dfed781e5dd99251006b07eb527dc4b3721
bigcode/the-stack
train
d5e2f4047bafa750eb864e84
train
function
def D_none(G, D, opt, training_set, minibatch_size, reals, labels): return 0, None
def D_none(G, D, opt, training_set, minibatch_size, reals, labels):
return 0, None
1]) fake_images_out = G.get_output_for(latents, labels, rho, is_training=True) loss = tf.reduce_mean(tf.abs(reals - fake_images_out)) return loss, None def D_none(G, D, opt, training_set, minibatch_size, reals, labels):
64
64
28
21
42
ak9250/few-shot-gan
training/loss.py
Python
D_none
D_none
81
82
81
81
1bf540204dc24e84eb0c4d8c166367c7f399fa62
bigcode/the-stack
train
bd44fe303cb70477b1811eeb
train
function
def G_ns_diffaug(G, D, training_set, minibatch_size, policy='color,translation,cutout', **kwargs): latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:]) labels = training_set.get_random_labels_tf(minibatch_size) rho = np.array([1]) fakes = G.get_output_for(latents, labels, rho, is_trainin...
def G_ns_diffaug(G, D, training_set, minibatch_size, policy='color,translation,cutout', **kwargs):
latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:]) labels = training_set.get_random_labels_tf(minibatch_size) rho = np.array([1]) fakes = G.get_output_for(latents, labels, rho, is_training=True) fake_scores = D.get_output_for(DiffAugment(fakes, policy=policy, channels_first=True), ...
ummary('Loss/gradient_penalty', gradient_penalty) D_reg = gradient_penalty * (gamma * 0.5) return D_loss, D_reg def G_ns_diffaug(G, D, training_set, minibatch_size, policy='color,translation,cutout', **kwargs):
64
64
169
28
35
ak9250/few-shot-gan
training/loss.py
Python
G_ns_diffaug
G_ns_diffaug
37
46
37
37
05a02081d4efcee4b1035eb89fa95521826605d4
bigcode/the-stack
train
a5f3cb6f942dcbd3c3331738
train
function
def G_logistic_ns_pathreg(G, D, opt, training_set, minibatch_size, pl_minibatch_shrink=2, pl_decay=0.01, pl_weight=2.0): _ = opt latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:]) labels = training_set.get_random_labels_tf(minibatch_size) rho = np.array([1]) fake_images_out, fake_d...
def G_logistic_ns_pathreg(G, D, opt, training_set, minibatch_size, pl_minibatch_shrink=2, pl_decay=0.01, pl_weight=2.0):
_ = opt latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:]) labels = training_set.get_random_labels_tf(minibatch_size) rho = np.array([1]) fake_images_out, fake_dlatents_out = G.get_output_for(latents, labels, rho, is_training=True, return_dlatents=True) fake_scores_out = D.get_...
_out = D.get_output_for(mixed_images_out, labels, is_training=True) mixed_scores_out = autosummary('Loss/scores/mixed', mixed_scores_out) mixed_grads = tf.gradients(tf.reduce_sum(mixed_scores_out), [mixed_images_out])[0] mixed_norms = tf.sqrt(tf.reduce_sum(tf.square(mixed_grads), axis=[1,2,3])) ...
225
225
753
43
181
ak9250/few-shot-gan
training/loss.py
Python
G_logistic_ns_pathreg
G_logistic_ns_pathreg
196
245
196
196
416305667be91b4f8238cc53cd01b9447e3739ca
bigcode/the-stack
train
47f1922c224b9607912f4efc
train
function
def G_logistic(G, D, opt, training_set, minibatch_size): _ = opt latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:]) labels = training_set.get_random_labels_tf(minibatch_size) fake_images_out = G.get_output_for(latents, labels, is_training=True) fake_scores_out = D.get_output_for(fa...
def G_logistic(G, D, opt, training_set, minibatch_size):
_ = opt latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:]) labels = training_set.get_random_labels_tf(minibatch_size) fake_images_out = G.get_output_for(latents, labels, is_training=True) fake_scores_out = D.get_output_for(fake_images_out, labels, is_training=True)[:,0:1] loss ...
_loss = autosummary('Loss/G_loss', G_loss) return G_loss, None #---------------------------------------------------------------------------- # Logistic loss from the paper # "Generative Adversarial Nets", Goodfellow et al. 2014 def G_logistic(G, D, opt, training_set, minibatch_size):
64
64
141
17
46
ak9250/few-shot-gan
training/loss.py
Python
G_logistic
G_logistic
53
60
53
53
0d0297e863342bc90a1b781c4788add7ee65bc5b
bigcode/the-stack
train
2c590a65307a3c62facf39b6
train
function
def G_logistic_ns(G, D, opt, training_set, minibatch_size): _ = opt latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:]) labels = training_set.get_random_labels_tf(minibatch_size) fake_images_out = G.get_output_for(latents, labels, is_training=True) fake_scores_out = D.get_output_for...
def G_logistic_ns(G, D, opt, training_set, minibatch_size):
_ = opt latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:]) labels = training_set.get_random_labels_tf(minibatch_size) fake_images_out = G.get_output_for(latents, labels, is_training=True) fake_scores_out = D.get_output_for(fake_images_out, labels, is_training=True)[:,0:1] loss ...
[:,0:1] loss = -tf.nn.softplus(fake_scores_out) # log(1-sigmoid(fake_scores_out)) # pylint: disable=invalid-unary-operand-type return loss, None def G_logistic_ns(G, D, opt, training_set, minibatch_size):
64
64
128
18
45
ak9250/few-shot-gan
training/loss.py
Python
G_logistic_ns
G_logistic_ns
62
69
62
62
905d12943405020541c305ff24e1d315b47eea2f
bigcode/the-stack
train
54d028b90fa7141ae5cc15cb
train
function
def D_wgan_gp(G, D, opt, training_set, minibatch_size, reals, labels, wgan_lambda=10.0, wgan_epsilon=0.001, wgan_target=1.0): _ = opt, training_set latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:]) fake_images_out = G.get_output_for(latents, labels, is_training=True) real_scores_out =...
def D_wgan_gp(G, D, opt, training_set, minibatch_size, reals, labels, wgan_lambda=10.0, wgan_epsilon=0.001, wgan_target=1.0):
_ = opt, training_set latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:]) fake_images_out = G.get_output_for(latents, labels, is_training=True) real_scores_out = D.get_output_for(reals, labels, is_training=True) fake_scores_out = D.get_output_for(fake_images_out, labels, is_training...
real_scores_out with tf.name_scope('EpsilonPenalty'): epsilon_penalty = autosummary('Loss/epsilon_penalty', tf.square(real_scores_out)) loss += epsilon_penalty * wgan_epsilon return loss, None #---------------------------------------------------------------------------- # WGAN-GP loss from the...
133
133
444
48
84
ak9250/few-shot-gan
training/loss.py
Python
D_wgan_gp
D_wgan_gp
167
190
167
167
d94fec488c5437260e3ee7e2163d14290b585552
bigcode/the-stack
train
0559d489cd1c4262e6f2524a
train
function
def D_logistic_r2(G, D, opt, training_set, minibatch_size, reals, labels, gamma=10.0): _ = opt, training_set latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:]) fake_images_out = G.get_output_for(latents, labels, is_training=True) real_scores_out = D.get_output_for(reals, labels, is_tra...
def D_logistic_r2(G, D, opt, training_set, minibatch_size, reals, labels, gamma=10.0):
_ = opt, training_set latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:]) fake_images_out = G.get_output_for(latents, labels, is_training=True) real_scores_out = D.get_output_for(reals, labels, is_training=True) fake_scores_out = D.get_output_for(fake_images_out, labels, is_training...
_penalty = tf.reduce_sum(tf.square(real_grads), axis=[1,2,3]) gradient_penalty = autosummary('Loss/gradient_penalty', gradient_penalty) reg = gradient_penalty * (gamma * 0.5) return loss, reg def D_logistic_r2(G, D, opt, training_set, minibatch_size, reals, labels, gamma=10.0):
89
89
299
30
58
ak9250/few-shot-gan
training/loss.py
Python
D_logistic_r2
D_logistic_r2
118
134
118
118
17e3dbb2c16cb26f4b100d06884800fc3d04392f
bigcode/the-stack
train
a5dd3609bd93f7a108234284
train
function
def G_wgan(G, D, opt, training_set, minibatch_size): _ = opt latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:]) labels = training_set.get_random_labels_tf(minibatch_size) fake_images_out = G.get_output_for(latents, labels, is_training=True) fake_scores_out = D.get_output_for(fake_i...
def G_wgan(G, D, opt, training_set, minibatch_size):
_ = opt latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:]) labels = training_set.get_random_labels_tf(minibatch_size) fake_images_out = G.get_output_for(latents, labels, is_training=True) fake_scores_out = D.get_output_for(fake_images_out, labels, is_training=True)[:,0:1] loss ...
* (gamma * 0.5) return loss, reg #---------------------------------------------------------------------------- # WGAN loss from the paper # "Wasserstein Generative Adversarial Networks", Arjovsky et al. 2017 def G_wgan(G, D, opt, training_set, minibatch_size):
64
64
114
17
46
ak9250/few-shot-gan
training/loss.py
Python
G_wgan
G_wgan
140
147
140
140
f3088410e4bee296c452265a7630a540fffb1eaf
bigcode/the-stack
train
a028f694a30e7f67c801dba6
train
class
class lstm_model(): """ Using bidirectional LSTM to learn sentence embedding for users' questions """ def __init__(self, FLAGS, initializer= tf.contrib.layers.xavier_initializer()): """ lstm class initialization """ # configurations s...
class lstm_model():
""" Using bidirectional LSTM to learn sentence embedding for users' questions """ def __init__(self, FLAGS, initializer= tf.contrib.layers.xavier_initializer()): """ lstm class initialization """ # configurations self.hidden_size = FL...
import tensorflow as tf import numpy as np from tensorflow.contrib.tensorboard.plugins import projector class lstm_model():
24
256
2,360
5
18
venusafroid/Zero_shot_Capsule_CNN
model.py
Python
lstm_model
lstm_model
5
244
5
5
e835725598b3f879fd373beca7a29c5a9cce0d6c
bigcode/the-stack
train
7195dab138853877fcf61881
train
class
class GallerySeedLogButton( ClientGUICommon.BetterBitmapButton ): def __init__( self, parent, controller, read_only, can_generate_more_pages, gallery_seed_log_get_callable, gallery_seed_log_set_callable = None ): ClientGUICommon.BetterBitmapButton.__init__( self, parent, CC.global_pixmaps().li...
class GallerySeedLogButton( ClientGUICommon.BetterBitmapButton ):
def __init__( self, parent, controller, read_only, can_generate_more_pages, gallery_seed_log_get_callable, gallery_seed_log_set_callable = None ): ClientGUICommon.BetterBitmapButton.__init__( self, parent, CC.global_pixmaps().listctrl, self._ShowGallerySeedLogFrame ) self._controll...
._list_ctrl.HasData( gallery_seed ): gallery_seeds_to_delete.append( gallery_seed ) self._list_ctrl.DeleteDatas( gallery_seeds_to_delete ) if len( gallery_seeds_to_add ) > 0: ...
253
256
2,129
15
238
baibhavvishalpani/hydrus
hydrus/client/gui/ClientGUIGallerySeedLog.py
Python
GallerySeedLogButton
GallerySeedLogButton
284
578
284
285
6cd68a14a2583118c23ea8c182d2aa5a38fb330a
bigcode/the-stack
train
4f8e7fff10eab86f07d26414
train
class
class EditGallerySeedLogPanel( ClientGUIScrolledPanels.EditPanel ): def __init__( self, parent, controller, read_only, can_generate_more_pages, gallery_seed_log ): ClientGUIScrolledPanels.EditPanel.__init__( self, parent ) self._controller = controller self._read_only ...
class EditGallerySeedLogPanel( ClientGUIScrolledPanels.EditPanel ):
def __init__( self, parent, controller, read_only, can_generate_more_pages, gallery_seed_log ): ClientGUIScrolledPanels.EditPanel.__init__( self, parent ) self._controller = controller self._read_only = read_only self._can_generate_more_pages = can_generate_more_pag...
QtCore as QC from qtpy import QtWidgets as QW from qtpy import QtGui as QG from hydrus.core import HydrusData from hydrus.core import HydrusExceptions from hydrus.core import HydrusGlobals as HG from hydrus.core import HydrusText from hydrus.client import ClientConstants as CC from hydrus.client import ClientData fr...
256
256
1,761
17
238
baibhavvishalpani/hydrus
hydrus/client/gui/ClientGUIGallerySeedLog.py
Python
EditGallerySeedLogPanel
EditGallerySeedLogPanel
28
280
28
29
eeeaa7fb74ee7a08eab16ce9154fdf0f6b9acbeb
bigcode/the-stack
train
316f07b5a03b184867b3bd1f
train
class
class GallerySeedLogStatusControl( QW.QFrame ): def __init__( self, parent, controller, read_only, can_generate_more_pages, page_key = None ): QW.QFrame.__init__( self, parent ) self.setFrameStyle( QW.QFrame.Box | QW.QFrame.Raised ) self._controller = controller ...
class GallerySeedLogStatusControl( QW.QFrame ):
def __init__( self, parent, controller, read_only, can_generate_more_pages, page_key = None ): QW.QFrame.__init__( self, parent ) self.setFrameStyle( QW.QFrame.Box | QW.QFrame.Raised ) self._controller = controller self._read_only = read_only self._can_gener...
ClientGUIMenus.AppendMenu( menu, submenu, 'export all urls' ) if not self._read_only: submenu = QW.QMenu( menu ) ClientGUIMenus.AppendMenuItem( submenu, 'from clipboard', 'Import new urls to this list from the clipboard.', self._ImportFromC...
150
152
507
13
137
baibhavvishalpani/hydrus
hydrus/client/gui/ClientGUIGallerySeedLog.py
Python
GallerySeedLogStatusControl
GallerySeedLogStatusControl
581
660
581
582
f2d0cd89befcd9a8964b8e11aba567c72660e1c6
bigcode/the-stack
train
37b65a2e4ec67340746b031a
train
class
class _EditorWindow( GafferUI.Window ) : def __init__( self, parentWindow, editor, **kw ) : GafferUI.Window.__init__( self, borderWidth = 8, **kw ) self.setChild( editor ) self.__titleChangedConnection = editor.titleChangedSignal().connect( Gaffer.WeakMethod( self.__updateTitle ) ) self.__nodeSetMemberR...
class _EditorWindow( GafferUI.Window ) :
def __init__( self, parentWindow, editor, **kw ) : GafferUI.Window.__init__( self, borderWidth = 8, **kw ) self.setChild( editor ) self.__titleChangedConnection = editor.titleChangedSignal().connect( Gaffer.WeakMethod( self.__updateTitle ) ) self.__nodeSetMemberRemovedConnection = editor.getNodeSet().mem...
return QtCore.QTimer.singleShot( 0, self.__updateTimeout ) self.__updateScheduled = True def __updateTimeout( self ) : if self.__updateScheduled : self.__updateScheduled = False self._updateFromSet() class _EditorWindow( GafferUI.Window ) :
70
70
236
11
59
davidsminor/gaffer
python/GafferUI/NodeSetEditor.py
Python
_EditorWindow
_EditorWindow
259
288
259
260
8a6a8dba0d8310bb6597a092a4652ce6459d033c
bigcode/the-stack
train
e1d95ad7a3be7066c4bc46d7
train
class
class NodeSetEditor( GafferUI.EditorWidget ) : def __init__( self, topLevelWidget, scriptNode, **kw ) : self.__nodeSet = Gaffer.StandardSet() self.__nodeSetChangedSignal = GafferUI.WidgetSignal() GafferUI.EditorWidget.__init__( self, topLevelWidget, scriptNode, **kw ) self.__titleFormat = None self...
class NodeSetEditor( GafferUI.EditorWidget ) :
def __init__( self, topLevelWidget, scriptNode, **kw ) : self.__nodeSet = Gaffer.StandardSet() self.__nodeSetChangedSignal = GafferUI.WidgetSignal() GafferUI.EditorWidget.__init__( self, topLevelWidget, scriptNode, **kw ) self.__titleFormat = None self.__updateScheduled = False # allow derived cla...
HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL...
256
256
1,812
12
244
davidsminor/gaffer
python/GafferUI/NodeSetEditor.py
Python
NodeSetEditor
NodeSetEditor
48
257
48
49
5a12ecc0bb606fd4c805299c1ee56cf0e0822daf
bigcode/the-stack
train
22672a0f80ef2a40011b7659
train
class
class RewriterManager: """The rewrite manager that manages some rewriters.""" def __init__(self): self.module_rewriter = ModuleRewriter() self.function_rewriter = FunctionRewriter() self.symbolic_rewriter = SymbolicRewriter()
class RewriterManager:
"""The rewrite manager that manages some rewriters.""" def __init__(self): self.module_rewriter = ModuleRewriter() self.function_rewriter = FunctionRewriter() self.symbolic_rewriter = SymbolicRewriter()
cv import torch.nn as nn from mmdeploy.utils.constants import IR, Backend from .function_rewriter import FunctionRewriter from .module_rewriter import ModuleRewriter from .rewriter_utils import collect_env from .symbolic_rewriter import SymbolicRewriter class RewriterManager:
64
64
55
5
58
xizi/mmdeploy
mmdeploy/core/rewriters/rewriter_manager.py
Python
RewriterManager
RewriterManager
14
20
14
14
7552671459e00711143267acb1b10d2edaae1d17
bigcode/the-stack
train
a5e96c30b0e5f25f687239a9
train
class
class RewriterContext: """The rewrite context. The context is used to manage the rewrite functions and the backend. Args: cfg (Dict): Config dictionary of deployment. backend (str): The inference engine name. ir (IR): The intermeditate representation name. rewrite_manager (...
class RewriterContext:
"""The rewrite context. The context is used to manage the rewrite functions and the backend. Args: cfg (Dict): Config dictionary of deployment. backend (str): The inference engine name. ir (IR): The intermeditate representation name. rewrite_manager (RewriterManager): An Re...
of deployment. backend (str): The inference engine name. ir (IR): The intermeditate representation name. recursive (bool): The flag to enable recursive patching. Returns: nn.Module: THe patched model. Examples: >>> from mmdeploy.core import patch_model >>> patc...
110
110
369
5
105
xizi/mmdeploy
mmdeploy/core/rewriters/rewriter_manager.py
Python
RewriterContext
RewriterContext
57
105
57
57
a2cacc36b48156eb269344a32ea855ce1871e19b
bigcode/the-stack
train
fb070faa1f0f5a24ecc90e3b
train
function
def patch_model(model: nn.Module, cfg: mmcv.Config, backend: str = Backend.DEFAULT.value, ir: IR = IR.DEFAULT, recursive: bool = True, **kwargs) -> nn.Module: """Patch the model, replace the modules that can be rewritten. Note that ...
def patch_model(model: nn.Module, cfg: mmcv.Config, backend: str = Backend.DEFAULT.value, ir: IR = IR.DEFAULT, recursive: bool = True, **kwargs) -> nn.Module:
"""Patch the model, replace the modules that can be rewritten. Note that the original model will be modified permanently. Args: model (torch.nn.Module): The model to patch. cfg (Dict): Config dictionary of deployment. backend (str): The inference engine name. ir (IR): The in...
SYMBOLIC_REWRITER = REWRITER_MANAGER.symbolic_rewriter def patch_model(model: nn.Module, cfg: mmcv.Config, backend: str = Backend.DEFAULT.value, ir: IR = IR.DEFAULT, recursive: bool = True, **kwargs) -> nn.Module:
64
64
200
47
16
xizi/mmdeploy
mmdeploy/core/rewriters/rewriter_manager.py
Python
patch_model
patch_model
30
54
30
35
517f1c9045037e4c16a6cf9e9af65581cd0a037d
bigcode/the-stack
train
ced2691fda07474cc39bad85
train
class
class Statical(Population): """ This implementation of a population algorithm statically assigns the generation of a source in a node of the topology. It is only invoked in the initialization. Extends: :mod: Population """ def initial_allocation(self,sim,app_name): #Assignment of SINK and ...
class Statical(Population):
""" This implementation of a population algorithm statically assigns the generation of a source in a node of the topology. It is only invoked in the initialization. Extends: :mod: Population """ def initial_allocation(self,sim,app_name): #Assignment of SINK and SOURCE pure modules ...
from yafs.population import Population class Statical(Population):
14
64
183
7
6
MarkoRimac/YAFS
src/examples/FogCentrality/CentricityPopulation.py
Python
Statical
Statical
3
24
3
3
f04f0a9c0cfa91421f431f1135fb7a68aba7a4e4
bigcode/the-stack
train
98167353e92aef31330091aa
train
function
def save(): db = clos_db.get_clos_db() def assignedstr(this): return ','.join(f"{k}={v}" for k, v in this.items() if k[0] != '_') def row(item): return [item['ip']['name'], item['collection'], assignedstr(item['assigned'])] ip_info = db.routing_tables.get_interface_members(db.rt_globa...
def save():
db = clos_db.get_clos_db() def assignedstr(this): return ','.join(f"{k}={v}" for k, v in this.items() if k[0] != '_') def row(item): return [item['ip']['name'], item['collection'], assignedstr(item['assigned'])] ip_info = db.routing_tables.get_interface_members(db.rt_global) with...
# distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import csv import fire import clos_db def save():
64
64
141
3
60
imnetdb/example-DC1
ip_addrs.py
Python
save
save
21
36
21
21
d2322dd7f12dbfb1c645935fba08e46246793264
bigcode/the-stack
train
4492327da19a3eb64795eebc
train
class
class state(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-network-instance - based on the path /network-instances/network-instance/protocols/protocol/bgp/peer-groups/peer-group/afi-safis/afi-safi/route-selection-options/state. Each member element ...
class state(PybindBase):
""" This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-network-instance - based on the path /network-instances/network-instance/protocols/protocol/bgp/peer-groups/peer-group/afi-safis/afi-safi/route-selection-options/state. Each member element of the container is rep...
# -*- coding: utf-8 -*- from operator import attrgetter from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType from pyangbind.lib.yangtypes import RestrictedClassType from pyangbind.lib.yangtypes import TypedListType from pyangbind.lib.yangtypes import YANGBool from pyangbind.lib.yangtypes import YANGListTy...
181
256
5,439
6
175
ckishimo/napalm-yang
napalm_yang/models/openconfig/network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/afi_safis/afi_safi/route_selection_options/state/__init__.py
Python
state
state
25
606
25
25
72c15890fc22c11c2ecb11337bceb6edb8f69337
bigcode/the-stack
train
c4ec8d74e74c4674bb88ba6c
train
class
class state(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-network-instance-l2 - based on the path /network-instances/network-instance/protocols/protocol/bgp/peer-groups/peer-group/afi-safis/afi-safi/route-selection-options/state. Each member eleme...
class state(PybindBase):
""" This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-network-instance-l2 - based on the path /network-instances/network-instance/protocols/protocol/bgp/peer-groups/peer-group/afi-safis/afi-safi/route-selection-options/state. Each member element of the container is ...
._extmethods, register_paths=True, namespace="http://openconfig.net/yang/network-instance", defining_module="openconfig-network-instance", yang_type="boolean", is_config=False, ) always_compare_med = __builtin__.property(_get_always_compare_med) ...
256
256
5,441
6
250
ckishimo/napalm-yang
napalm_yang/models/openconfig/network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/afi_safis/afi_safi/route_selection_options/state/__init__.py
Python
state
state
609
1,190
609
609
fba16c33be8ca9cef8efb8d421ca4980139cbc5c
bigcode/the-stack
train
efa4455ed2451d4ca5b4a7ab
train
class
class ModelSeries(ModelTransformer, pd.Series): """ Wrapper for ``pandas.Series`` to support ``sklearn.preprocessing`` """ @property def _constructor(self): return ModelSeries def _call(self, estimator, method_name, *args, **kwargs): method = self._check_attr(estimato...
class ModelSeries(ModelTransformer, pd.Series):
""" Wrapper for ``pandas.Series`` to support ``sklearn.preprocessing`` """ @property def _constructor(self): return ModelSeries def _call(self, estimator, method_name, *args, **kwargs): method = self._check_attr(estimator, method_name) # needed for preproces...
#!/usr/bin/env python import pandas as pd from pandas.util._decorators import Appender, cache_readonly from pandas_ml.core.generic import ModelTransformer, _shared_docs import pandas_ml.skaccessors as skaccessors import pandas_ml.util as util class ModelSeries(ModelTransformer, pd.Series):
65
187
625
9
55
h2oai/pandas-ml
pandas_ml/core/series.py
Python
ModelSeries
ModelSeries
11
89
11
11
a93218a159c4d373edbc718ccd767d22412be1c7
bigcode/the-stack
train
0f17b71a9d41f80af226fb6d
train
class
class Connection: def __init__(self, idx): self.idx = idx self.keys = set() self.nRequests = {} self.nResponses = {} self.rctKey = None def addKey(self, newKey): self.keys.append(newKey) self.nRequests[newKey] = 0 self.nResponses[newKey] = 0
class Connection:
def __init__(self, idx): self.idx = idx self.keys = set() self.nRequests = {} self.nResponses = {} self.rctKey = None def addKey(self, newKey): self.keys.append(newKey) self.nRequests[newKey] = 0 self.nResponses[newKey] = 0
_1 -> 2 hits # user_2 -> 1 hits # listing_1 -> 1 miss # listing_2 -> 1 miss # from collections import defaultdict # decalre dicitonary of list, idx 0 : request, idx 1: response class Connection:
64
64
82
3
60
shawlu95/Algorithm-Toolbox
interview/airbnb/memcache.py
Python
Connection
Connection
28
39
28
28
37df7c4b1a19995e9aeb6544722263328c147f13
bigcode/the-stack
train
745ee4356c66aff24de99b8d
train
function
def simple_sanitize(input): """ This function removes everything from a string except for alphanumeric characters and a few others. """ return re.sub(r'[^a-zA-Z0-9_~\\-\\.\\*]*', '', input)
def simple_sanitize(input):
""" This function removes everything from a string except for alphanumeric characters and a few others. """ return re.sub(r'[^a-zA-Z0-9_~\\-\\.\\*]*', '', input)
.time()) + random.randint(10000000000, 50000000000) s = '' base = len(CODELIST) while ci > 0: s += CODELIST[ci % base] ci /= base return s[::-1] def simple_sanitize(input):
63
64
56
6
57
carsonmcdonald/Python-Flask-neo4j-Heroku-Example
util.py
Python
simple_sanitize
simple_sanitize
32
38
32
32
d66a88e00692e3d5ae7aad0ce311d3cdad533e8f
bigcode/the-stack
train
3aa83e9032c1a77ddac25f6f
train
function
def next_code(): """ This function returns a unique id that contains alphanumeric characters and is only 6 characters long. """ ci = int(time.time()) + random.randint(10000000000, 50000000000) s = '' base = len(CODELIST) while ci > 0: s += CODELIST[ci % base] ci /= base return s[::-1]
def next_code():
""" This function returns a unique id that contains alphanumeric characters and is only 6 characters long. """ ci = int(time.time()) + random.randint(10000000000, 50000000000) s = '' base = len(CODELIST) while ci > 0: s += CODELIST[ci % base] ci /= base return s[::-1]
__copyright__ = "Copyright 2012 Carson McDonald" __license__ = "See LICENSE" import random import time import re CODELIST = list("aceghijlmopqrsuvwxyzACDEHIJKLMNOPQRSTUVWXYZ023456789bdfknFG1tB") def next_code():
64
64
93
4
60
carsonmcdonald/Python-Flask-neo4j-Heroku-Example
util.py
Python
next_code
next_code
17
29
17
17
079ff7297a6a204d23e0398061a8f0b38514c9e9
bigcode/the-stack
train
fddef714b758646509908f30
train
function
def create_attention_mask_from_input_mask(from_tensor, to_mask): """Create 3D attention mask from a 2D tensor mask. Args: from_tensor: 2D or 3D Tensor of shape [batch_size, from_seq_length, ...]. to_mask: int32 Tensor of shape [batch_size, to_seq_length]. Returns: float Tensor of shape [batch_size, ...
def create_attention_mask_from_input_mask(from_tensor, to_mask):
"""Create 3D attention mask from a 2D tensor mask. Args: from_tensor: 2D or 3D Tensor of shape [batch_size, from_seq_length, ...]. to_mask: int32 Tensor of shape [batch_size, to_seq_length]. Returns: float Tensor of shape [batch_size, from_seq_length, to_seq_length]. """ from_shape = get_shape_l...
the batch size. position_broadcast_shape = [] for _ in range(num_dims - 2): position_broadcast_shape.append(1) position_broadcast_shape.extend([seq_length, width]) position_embeddings = tf.reshape(position_embeddings, position_broadcast_shape) ...
93
93
312
13
79
cmacdonald/DeepCT
deepct/modeling.py
Python
create_attention_mask_from_input_mask
create_attention_mask_from_input_mask
526
557
526
526
7b1181d98e98cc7f3aea99c382a648811bef55d5
bigcode/the-stack
train
944531173fc3e3c890f40ca5
train
function
def create_initializer(initializer_range=0.02): """Creates a `truncated_normal_initializer` with the given range.""" return tf.truncated_normal_initializer(stddev=initializer_range)
def create_initializer(initializer_range=0.02):
"""Creates a `truncated_normal_initializer` with the given range.""" return tf.truncated_normal_initializer(stddev=initializer_range)
scope=name) def layer_norm_and_dropout(input_tensor, dropout_prob, name=None): """Runs layer normalization followed by dropout.""" output_tensor = layer_norm(input_tensor, name) output_tensor = dropout(output_tensor, dropout_prob) return output_tensor def create_initializer(initializer_range=0.02):
64
64
39
11
52
cmacdonald/DeepCT
deepct/modeling.py
Python
create_initializer
create_initializer
376
378
376
376
3956b75d9142b716062aba6859e51c11518be31b
bigcode/the-stack
train
28198c805119bfecf0a5299d
train
class
class BertConfig(object): """Configuration for `BertModel`.""" def __init__(self, vocab_size, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act="gelu", hidden_dro...
class BertConfig(object):
"""Configuration for `BertModel`.""" def __init__(self, vocab_size, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act="gelu", hidden_dropout_prob=0.1, ...
8 # Copyright 2018 The Google AI Language Team Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
198
198
662
5
192
cmacdonald/DeepCT
deepct/modeling.py
Python
BertConfig
BertConfig
30
103
30
30
f31d77239402f38837f156ff67e5012c2fa36fe1
bigcode/the-stack
train