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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cb14191c504453092a5a7bb5 | train | class | class DefaultTargetInfo(object):
def __init__(self, full_config):
self.full_config = full_config
def platform(self):
return sys.platform.lower().strip()
def add_locale_features(self, features):
self.full_config.lit_config.warning(
"No locales entry for target_system: %s... | class DefaultTargetInfo(object):
| def __init__(self, full_config):
self.full_config = full_config
def platform(self):
return sys.platform.lower().strip()
def add_locale_features(self, features):
self.full_config.lit_config.warning(
"No locales entry for target_system: %s" % self.platform())
def add... |
#
# This file is dual licensed under the MIT and the University of Illinois Open
# Source Licenses. See LICENSE.TXT for details.
#
#===----------------------------------------------------------------------===//
import importlib
import locale
import os
import platform
import re
import subprocess
import sys
class Defau... | 64 | 64 | 147 | 6 | 57 | vlaza/openenclave | 3rdparty/libcxx/libcxx/utils/libcxx/test/target_info.py | Python | DefaultTargetInfo | DefaultTargetInfo | 18 | 34 | 18 | 18 | 24a1599605cdf679493e190f75c0358ccfe44186 | bigcode/the-stack | train |
db539b4fe3a239d1074dc791 | train | class | class WindowsLocalTI(DefaultTargetInfo):
def __init__(self, full_config):
super(WindowsLocalTI, self).__init__(full_config)
def add_locale_features(self, features):
add_common_locales(features, self.full_config.lit_config,
is_windows=True)
def use_lit_shell_defau... | class WindowsLocalTI(DefaultTargetInfo):
| def __init__(self, full_config):
super(WindowsLocalTI, self).__init__(full_config)
def add_locale_features(self, features):
add_common_locales(features, self.full_config.lit_config,
is_windows=True)
def use_lit_shell_default(self):
# Default to the intern... | ()
if san:
# The libraries and their order are taken from the
# linkSanitizerRuntimeDeps function in
# clang/lib/Driver/Tools.cpp
flags += ['-lpthread', '-lrt', '-lm', '-ldl']
class WindowsLocalTI(DefaultTargetInfo):
| 64 | 64 | 95 | 8 | 56 | vlaza/openenclave | 3rdparty/libcxx/libcxx/utils/libcxx/test/target_info.py | Python | WindowsLocalTI | WindowsLocalTI | 256 | 267 | 256 | 256 | 5f01a4781ad6c38a73e91eb4508f04e67112352a | bigcode/the-stack | train |
c2accab7edf1b466e0012695 | train | class | class Resurrection(Player):
"""
A player starts by cooperating and defects if the number of rounds
played by the player is greater than five and the last five rounds
are defections.
Otherwise, the strategy plays like Tit-for-tat.
Names:
- Resurrection: [Eckhart2015]_
"""
# These ... | class Resurrection(Player):
| """
A player starts by cooperating and defects if the number of rounds
played by the player is greater than five and the last five rounds
are defections.
Otherwise, the strategy plays like Tit-for-tat.
Names:
- Resurrection: [Eckhart2015]_
"""
# These are various properties for t... | from axelrod.action import Action
from axelrod.player import Player
C, D = Action.C, Action.D
class Resurrection(Player):
| 30 | 64 | 216 | 4 | 25 | danilobellini/Axelrod | axelrod/strategies/resurrection.py | Python | Resurrection | Resurrection | 7 | 38 | 7 | 7 | b69ae5cfd08d755030169c8e101f7aa358515d5d | bigcode/the-stack | train |
e03d412b682c47be029bbd58 | train | class | class DoubleResurrection(Player):
"""
A player starts by cooperating and defects if the number of rounds
played by the player is greater than five and the last five rounds
are cooperations.
If the last five rounds were defections, the player cooperates.
Names:
- DoubleResurrection: [Eckha... | class DoubleResurrection(Player):
| """
A player starts by cooperating and defects if the number of rounds
played by the player is greater than five and the last five rounds
are cooperations.
If the last five rounds were defections, the player cooperates.
Names:
- DoubleResurrection: [Eckhart2015]_
"""
name = "Doub... | def strategy(self, opponent: Player) -> Action:
if len(self.history) == 0:
return C
if len(self.history) >= 5 and self.history[-5:] == [D, D, D, D, D]:
return D
else:
return opponent.history[-1]
class DoubleResurrection(Player):
| 73 | 73 | 245 | 6 | 67 | danilobellini/Axelrod | axelrod/strategies/resurrection.py | Python | DoubleResurrection | DoubleResurrection | 41 | 73 | 41 | 41 | f8590892971a1a0f2d7f2741799f039ec1d819bd | bigcode/the-stack | train |
a3be9bdd2aaca9b15d621f57 | train | function | def path_to_date(path):
return os.path.getmtime(str(path))
| def path_to_date(path):
| return os.path.getmtime(str(path))
| ImportError:
import pathlib2 as pathlib
import sys
import os
import datetime
import glob
#functions
def text_to_bool(text):
return False \
if not str(text) \
else str(text).lower() in '1,yes,y,true,t'
def path_to_date(path):
| 64 | 64 | 15 | 6 | 58 | labsyspharm/mcmicro-old | bin/illumination.py | Python | path_to_date | path_to_date | 23 | 24 | 23 | 23 | 669806f86a741309c8815d361d6c95b99b626ea1 | bigcode/the-stack | train |
bd48f37d04a701a9d5d49217 | train | function | def text_to_bool(text):
return False \
if not str(text) \
else str(text).lower() in '1,yes,y,true,t'
| def text_to_bool(text):
| return False \
if not str(text) \
else str(text).lower() in '1,yes,y,true,t'
| : python illumination ./example_data/image_1
#library
from __future__ import print_function
from subprocess import call
try:
import pathlib
except ImportError:
import pathlib2 as pathlib
import sys
import os
import datetime
import glob
#functions
def text_to_bool(text):
| 64 | 64 | 33 | 6 | 57 | labsyspharm/mcmicro-old | bin/illumination.py | Python | text_to_bool | text_to_bool | 18 | 21 | 18 | 18 | f6b9b354f413358fd4510a93fb7dbc240a32fcbb | bigcode/the-stack | train |
1bbbfe5e7a0aae8bf9989b20 | train | function | def microscope_check(current_sample):
if len(glob.glob(str(current_sample) + '/raw_files/*.ome.tiff')) != 0:
print('Exemplar Dataset Used')
output = '.ome.tiff'
return(output)
if len(glob.glob(str(current_sample) + '/raw_images/*.ome.tiff')) != 0:
print('Exemplar Dataset Used')
... | def microscope_check(current_sample):
| if len(glob.glob(str(current_sample) + '/raw_files/*.ome.tiff')) != 0:
print('Exemplar Dataset Used')
output = '.ome.tiff'
return(output)
if len(glob.glob(str(current_sample) + '/raw_images/*.ome.tiff')) != 0:
print('Exemplar Dataset Used')
output = '.ome.tiff'
re... | _to_bool(text):
return False \
if not str(text) \
else str(text).lower() in '1,yes,y,true,t'
def path_to_date(path):
return os.path.getmtime(str(path))
#expand the number of microscope raw files types searched for
def microscope_check(current_sample):
| 64 | 64 | 207 | 6 | 57 | labsyspharm/mcmicro-old | bin/illumination.py | Python | microscope_check | microscope_check | 27 | 46 | 27 | 27 | ba327646f60d6ee00ca03f97fadb9a62c649c966 | bigcode/the-stack | train |
2ed2728d35d7e61bd978e954 | train | class | class TestPageRank:
def setUp(self):
G=networkx.DiGraph()
edges=[(1,2),(1,3),\
(3,1),(3,2),(3,5),\
(4,5),(4,6),\
(5,4),(5,6),\
(6,4)]
G.add_edges_from(edges)
self.G=G
self.G.pagerank=dict(zip(G,
... | class TestPageRank:
| def setUp(self):
G=networkx.DiGraph()
edges=[(1,2),(1,3),\
(3,1),(3,2),(3,5),\
(4,5),(4,6),\
(5,4),(5,6),\
(6,4)]
G.add_edges_from(edges)
self.G=G
self.G.pagerank=dict(zip(G,
[0.03721197,... | #!/usr/bin/env python
from nose.tools import *
from nose import SkipTest
from nose.plugins.attrib import attr
import networkx
# Example from
# A. Langville and C. Meyer, "A survey of eigenvector methods of web
# information retrieval." http://citeseer.ist.psu.edu/713792.html
class TestPageRank:
| 77 | 177 | 590 | 5 | 71 | CSE512-15S/a3-haynesb-Pending | appengine/networkx/algorithms/link_analysis/tests/test_pagerank.py | Python | TestPageRank | TestPageRank | 12 | 76 | 12 | 13 | fd9b7751e229bb91f7f52280819d3a70ba7680a0 | bigcode/the-stack | train |
871dba5aefb7c6e5a6f0b497 | train | function | @app.route('/migration/status')
@jwt_required
async def migration_status():
if request.method == 'GET':
project = request.args.get('project')
con = create_db_con()
machines = [dict(x) for x in BluePrint.objects(project=project).allow_filtering()]
con.shutdown()
return jsonify... | @app.route('/migration/status')
@jwt_required
async def migration_status():
| if request.method == 'GET':
project = request.args.get('project')
con = create_db_con()
machines = [dict(x) for x in BluePrint.objects(project=project).allow_filtering()]
con.shutdown()
return jsonify(machines)
else:
return jsonify({"status":500, "msg": "method no... | from __main__ import app
from utils.dbconn import *
from model.blueprint import *
import json
from quart import jsonify,request
from quart_jwt_extended import jwt_required, get_jwt_identity
@app.route('/migration/status')
@jwt_required
async def migration_status():
| 58 | 64 | 89 | 15 | 42 | iamvishnuks/Xmigrate | routes/status.py | Python | migration_status | migration_status | 8 | 18 | 8 | 10 | 56ed5cc179346998befa03b2b630942513025a18 | bigcode/the-stack | train |
dbd9ef95d4c607c864f2ba22 | train | function | def test_grad_sum_bacward(get_clients) -> None:
parties = get_clients(4)
grad = torch.tensor(420)
grad_mpc = grad.share(parties=parties)
shape = (2, 3)
ctx = {"x_shape": shape}
res_mpc = GradSum.backward(ctx, grad_mpc)
res = res_mpc.reconstruct()
expected = torch.ones(size=shape) * g... | def test_grad_sum_bacward(get_clients) -> None:
| parties = get_clients(4)
grad = torch.tensor(420)
grad_mpc = grad.share(parties=parties)
shape = (2, 3)
ctx = {"x_shape": shape}
res_mpc = GradSum.backward(ctx, grad_mpc)
res = res_mpc.reconstruct()
expected = torch.ones(size=shape) * grad
assert (res == expected).all()
| res_mpc = GradSum.forward(ctx, x_mpc)
assert ctx["x_shape"] == (2, 3)
res = res_mpc.reconstruct()
expected = x.sum()
assert (res == expected).all()
def test_grad_sum_bacward(get_clients) -> None:
| 64 | 64 | 104 | 13 | 51 | libratiger/SyMPC | tests/sympc/tensor/grad/grad_functions_test.py | Python | test_grad_sum_bacward | test_grad_sum_bacward | 131 | 145 | 131 | 131 | 3a00e9694d80bcc4531b3af1eea569cf5ed79366 | bigcode/the-stack | train |
67be73ec34ab4042852eaa30 | train | function | def test_grad_add_different_dims_backward(get_clients) -> None:
parties = get_clients(4)
grad = torch.Tensor([[[2, 4, 6], [5, 7, 9]]])
grad_x = grad
grad_y = torch.Tensor([[7, 11, 15]])
grad_mpc = grad.share(parties=parties)
ctx = {"x_shape": (2, 3), "y_shape": (1, 3)}
res_mpc_x, res_mpc_y... | def test_grad_add_different_dims_backward(get_clients) -> None:
| parties = get_clients(4)
grad = torch.Tensor([[[2, 4, 6], [5, 7, 9]]])
grad_x = grad
grad_y = torch.Tensor([[7, 11, 15]])
grad_mpc = grad.share(parties=parties)
ctx = {"x_shape": (2, 3), "y_shape": (1, 3)}
res_mpc_x, res_mpc_y = GradAdd.backward(ctx, grad_mpc)
assert (res_mpc_x.recons... | parties)
ctx = {}
res_mpc = GradAdd.forward(ctx, x_mpc, y_mpc)
res = res_mpc.reconstruct()
expected = x + y
assert (res == expected).all()
def test_grad_add_different_dims_backward(get_clients) -> None:
| 64 | 64 | 156 | 14 | 50 | libratiger/SyMPC | tests/sympc/tensor/grad/grad_functions_test.py | Python | test_grad_add_different_dims_backward | test_grad_add_different_dims_backward | 69 | 81 | 69 | 69 | cdaa123b5e876bcb577387f9b5967358ab381533 | bigcode/the-stack | train |
c792e221ce62a40b2630c7b5 | train | function | def test_grad_sigmoid_bacward(get_clients) -> None:
parties = get_clients(4)
grad = torch.tensor([0.3, 0.4, 0.7])
grad_mpc = grad.share(parties=parties)
ctx = {"probabilities": grad}
res_mpc = GradSigmoid.backward(ctx, grad_mpc)
res = res_mpc.reconstruct()
expected = grad * grad * (1 - g... | def test_grad_sigmoid_bacward(get_clients) -> None:
| parties = get_clients(4)
grad = torch.tensor([0.3, 0.4, 0.7])
grad_mpc = grad.share(parties=parties)
ctx = {"probabilities": grad}
res_mpc = GradSigmoid.backward(ctx, grad_mpc)
res = res_mpc.reconstruct()
expected = grad * grad * (1 - grad)
assert np.allclose(res, expected, rtol=1e-... | moid.forward(ctx, x_mpc)
assert "probabilities" in ctx
res = res_mpc.reconstruct()
expected = x.sigmoid()
assert np.allclose(res, expected, rtol=1e-2)
def test_grad_sigmoid_bacward(get_clients) -> None:
| 64 | 64 | 117 | 14 | 50 | libratiger/SyMPC | tests/sympc/tensor/grad/grad_functions_test.py | Python | test_grad_sigmoid_bacward | test_grad_sigmoid_bacward | 229 | 242 | 229 | 229 | 428ad8666458d89aba5a10e631e23a14d735c2f4 | bigcode/the-stack | train |
a367ab8c9ca17ae21f2f8d3f | train | function | def test_grad_add_forward(get_clients) -> None:
parties = get_clients(4)
x = torch.Tensor([[1, 2, 3], [4, 5, 6]])
y = torch.Tensor([[1, 4, 6], [8, 10, 12]])
x_mpc = x.share(parties=parties)
y_mpc = y.share(parties=parties)
ctx = {}
res_mpc = GradAdd.forward(ctx, x_mpc, y_mpc)
res = re... | def test_grad_add_forward(get_clients) -> None:
| parties = get_clients(4)
x = torch.Tensor([[1, 2, 3], [4, 5, 6]])
y = torch.Tensor([[1, 4, 6], [8, 10, 12]])
x_mpc = x.share(parties=parties)
y_mpc = y.share(parties=parties)
ctx = {}
res_mpc = GradAdd.forward(ctx, x_mpc, y_mpc)
res = res_mpc.reconstruct()
expected = x + y
as... | )}
res_mpc_x, res_mpc_y = GradAdd.backward(ctx, grad_mpc)
assert (res_mpc_x.reconstruct() == grad_x).all()
assert (res_mpc_y.reconstruct() == grad_y).all()
def test_grad_add_forward(get_clients) -> None:
| 64 | 64 | 138 | 11 | 53 | libratiger/SyMPC | tests/sympc/tensor/grad/grad_functions_test.py | Python | test_grad_add_forward | test_grad_add_forward | 84 | 98 | 84 | 84 | 0abeaead4dfb9f9028c934b4cb5c6aa37bb93d23 | bigcode/the-stack | train |
5424a8b85050ebf866e9682b | train | function | def test_grad_sub_backward(get_clients) -> None:
parties = get_clients(4)
grad = torch.Tensor([1, 2, 3, 4])
grad_mpc = grad.share(parties=parties)
ctx = {"x_shape": (4,), "y_shape": (4,)}
res_mpc_x, res_mpc_y = GradSub.backward(ctx, grad_mpc)
assert (res_mpc_x.reconstruct() == grad).all()
... | def test_grad_sub_backward(get_clients) -> None:
| parties = get_clients(4)
grad = torch.Tensor([1, 2, 3, 4])
grad_mpc = grad.share(parties=parties)
ctx = {"x_shape": (4,), "y_shape": (4,)}
res_mpc_x, res_mpc_y = GradSub.backward(ctx, grad_mpc)
assert (res_mpc_x.reconstruct() == grad).all()
assert (res_mpc_y.reconstruct() == -grad).all()
| (parties=parties)
ctx = {}
res_mpc = GradSub.forward(ctx, x_mpc, y_mpc)
res = res_mpc.reconstruct()
expected = x - y
assert (res == expected).all()
def test_grad_sub_backward(get_clients) -> None:
| 64 | 64 | 118 | 11 | 53 | libratiger/SyMPC | tests/sympc/tensor/grad/grad_functions_test.py | Python | test_grad_sub_backward | test_grad_sub_backward | 165 | 175 | 165 | 165 | 87343ec7c668b84f52d06dd6666a3e7465c2ce83 | bigcode/the-stack | train |
c14169ad94900d295e00a30f | train | function | def test_grad_sum_forward(get_clients) -> None:
parties = get_clients(4)
x = torch.Tensor([[1, 2, 3], [4, 5, 6]])
x_mpc = x.share(parties=parties)
ctx = {}
res_mpc = GradSum.forward(ctx, x_mpc)
assert ctx["x_shape"] == (2, 3)
res = res_mpc.reconstruct()
expected = x.sum()
assert... | def test_grad_sum_forward(get_clients) -> None:
| parties = get_clients(4)
x = torch.Tensor([[1, 2, 3], [4, 5, 6]])
x_mpc = x.share(parties=parties)
ctx = {}
res_mpc = GradSum.forward(ctx, x_mpc)
assert ctx["x_shape"] == (2, 3)
res = res_mpc.reconstruct()
expected = x.sum()
assert (res == expected).all()
| 4,)}
res_mpc_x, res_mpc_y = GradAdd.backward(ctx, grad_mpc)
assert (res_mpc_x.reconstruct() == grad).all()
assert (res_mpc_y.reconstruct() == grad).all()
def test_grad_sum_forward(get_clients) -> None:
| 64 | 64 | 111 | 11 | 53 | libratiger/SyMPC | tests/sympc/tensor/grad/grad_functions_test.py | Python | test_grad_sum_forward | test_grad_sum_forward | 114 | 128 | 114 | 114 | 9cce7d73d2bc02f9c1544784bc0552547df15eee | bigcode/the-stack | train |
d1565650dc873293734b3f26 | train | function | def test_grad_func_abstract_backward_exception() -> None:
with pytest.raises(NotImplementedError):
GradFunc.backward({})
| def test_grad_func_abstract_backward_exception() -> None:
| with pytest.raises(NotImplementedError):
GradFunc.backward({})
| Sub
from sympc.tensor.grads.grad_functions import GradSum
from sympc.tensor.grads.grad_functions import GradT
def test_grad_func_abstract_forward_exception() -> None:
with pytest.raises(NotImplementedError):
GradFunc.forward({})
def test_grad_func_abstract_backward_exception() -> None:
| 63 | 64 | 25 | 12 | 52 | libratiger/SyMPC | tests/sympc/tensor/grad/grad_functions_test.py | Python | test_grad_func_abstract_backward_exception | test_grad_func_abstract_backward_exception | 20 | 22 | 20 | 20 | f6e241a007c3a98bc1c7381d20086f94b49ff30c | bigcode/the-stack | train |
45808cefc6a3989168b9a1a8 | train | function | def test_grad_mul_forward(get_clients) -> None:
parties = get_clients(4)
x = torch.Tensor([[1, 2], [3, -4]])
y = torch.Tensor([[1, -4], [8, 9]])
x_mpc = x.share(parties=parties)
y_mpc = y.share(parties=parties)
ctx = {}
res_mpc = GradMul.forward(ctx, x_mpc, y_mpc)
assert "x" in ctx
... | def test_grad_mul_forward(get_clients) -> None:
| parties = get_clients(4)
x = torch.Tensor([[1, 2], [3, -4]])
y = torch.Tensor([[1, -4], [8, 9]])
x_mpc = x.share(parties=parties)
y_mpc = y.share(parties=parties)
ctx = {}
res_mpc = GradMul.forward(ctx, x_mpc, y_mpc)
assert "x" in ctx
assert "y" in ctx
res = res_mpc.reconstru... | res_mpc = GradSigmoid.backward(ctx, grad_mpc)
res = res_mpc.reconstruct()
expected = grad * grad * (1 - grad)
assert np.allclose(res, expected, rtol=1e-2)
def test_grad_mul_forward(get_clients) -> None:
| 64 | 64 | 150 | 11 | 53 | libratiger/SyMPC | tests/sympc/tensor/grad/grad_functions_test.py | Python | test_grad_mul_forward | test_grad_mul_forward | 245 | 262 | 245 | 245 | d0a5549e37d7f45b6420c4255a23c7c854066532 | bigcode/the-stack | train |
5ac7e5aabe383823d17b0597 | train | function | def test_grad_sub_different_dims_backward(get_clients) -> None:
parties = get_clients(4)
grad = torch.Tensor([[[2, 4, 6], [5, 7, 9]]])
grad_x = grad
grad_y = -torch.Tensor([[7, 11, 15]])
grad_mpc = grad.share(parties=parties)
ctx = {"x_shape": (2, 3), "y_shape": (1, 3)}
res_mpc_x, res_mpc_... | def test_grad_sub_different_dims_backward(get_clients) -> None:
| parties = get_clients(4)
grad = torch.Tensor([[[2, 4, 6], [5, 7, 9]]])
grad_x = grad
grad_y = -torch.Tensor([[7, 11, 15]])
grad_mpc = grad.share(parties=parties)
ctx = {"x_shape": (2, 3), "y_shape": (1, 3)}
res_mpc_x, res_mpc_y = GradSub.backward(ctx, grad_mpc)
assert (res_mpc_x.recon... | parties)
ctx = {}
res_mpc = GradSub.forward(ctx, x_mpc, y_mpc)
res = res_mpc.reconstruct()
expected = x - y
assert (res == expected).all()
def test_grad_sub_different_dims_backward(get_clients) -> None:
| 64 | 64 | 157 | 14 | 50 | libratiger/SyMPC | tests/sympc/tensor/grad/grad_functions_test.py | Python | test_grad_sub_different_dims_backward | test_grad_sub_different_dims_backward | 195 | 207 | 195 | 195 | 2dbfcabb9c3f62be14df13b82d89f42962340ac9 | bigcode/the-stack | train |
60635d3582659d84af10a291 | train | function | def test_grad_transpose_backward(get_clients) -> None:
parties = get_clients(4)
grad = torch.Tensor([[1, 2, 3], [4, 5, 6]])
grad_mpc = grad.t().share(parties=parties)
ctx = {}
res_mpc = GradT.backward(ctx, grad_mpc)
res = res_mpc.reconstruct()
expected = grad
assert (res == expected).... | def test_grad_transpose_backward(get_clients) -> None:
| parties = get_clients(4)
grad = torch.Tensor([[1, 2, 3], [4, 5, 6]])
grad_mpc = grad.t().share(parties=parties)
ctx = {}
res_mpc = GradT.backward(ctx, grad_mpc)
res = res_mpc.reconstruct()
expected = grad
assert (res == expected).all()
| = secret.share(parties=get_clients(4))
ctx = {}
res_mpc = GradT.forward(ctx, mpc_tensor)
res = res_mpc.reconstruct()
expected = secret.t()
assert (res == expected).all()
def test_grad_transpose_backward(get_clients) -> None:
| 64 | 64 | 99 | 12 | 52 | libratiger/SyMPC | tests/sympc/tensor/grad/grad_functions_test.py | Python | test_grad_transpose_backward | test_grad_transpose_backward | 38 | 49 | 38 | 38 | 6bd587cb80eeee55c44cbe405dc7733fafcbd133 | bigcode/the-stack | train |
c1d3594aca9c35375025472a | train | function | def test_grad_sub_different_dims_forward(get_clients) -> None:
parties = get_clients(4)
x = torch.Tensor([[1, 2, 3], [4, 5, 6]])
y = torch.Tensor([1, 2, 3])
x_mpc = x.share(parties=parties)
y_mpc = y.share(parties=parties)
ctx = {}
res_mpc = GradSub.forward(ctx, x_mpc, y_mpc)
res = re... | def test_grad_sub_different_dims_forward(get_clients) -> None:
| parties = get_clients(4)
x = torch.Tensor([[1, 2, 3], [4, 5, 6]])
y = torch.Tensor([1, 2, 3])
x_mpc = x.share(parties=parties)
y_mpc = y.share(parties=parties)
ctx = {}
res_mpc = GradSub.forward(ctx, x_mpc, y_mpc)
res = res_mpc.reconstruct()
expected = x - y
assert (res == ex... | res_mpc_x, res_mpc_y = GradSub.backward(ctx, grad_mpc)
assert (res_mpc_x.reconstruct() == grad).all()
assert (res_mpc_y.reconstruct() == -grad).all()
def test_grad_sub_different_dims_forward(get_clients) -> None:
| 64 | 64 | 132 | 14 | 50 | libratiger/SyMPC | tests/sympc/tensor/grad/grad_functions_test.py | Python | test_grad_sub_different_dims_forward | test_grad_sub_different_dims_forward | 178 | 192 | 178 | 178 | e3ee25bdacb50e811bce96e0c6b427452f2fd9e2 | bigcode/the-stack | train |
14467898a2fa5106dcb7be6a | train | function | def test_grad_sub_forward(get_clients) -> None:
parties = get_clients(4)
x = torch.Tensor([[1, 2, 3], [4, 5, 6]])
y = torch.Tensor([[1, 4, 6], [8, 10, 12]])
x_mpc = x.share(parties=parties)
y_mpc = y.share(parties=parties)
ctx = {}
res_mpc = GradSub.forward(ctx, x_mpc, y_mpc)
res = re... | def test_grad_sub_forward(get_clients) -> None:
| parties = get_clients(4)
x = torch.Tensor([[1, 2, 3], [4, 5, 6]])
y = torch.Tensor([[1, 4, 6], [8, 10, 12]])
x_mpc = x.share(parties=parties)
y_mpc = y.share(parties=parties)
ctx = {}
res_mpc = GradSub.forward(ctx, x_mpc, y_mpc)
res = res_mpc.reconstruct()
expected = x - y
as... | ctx = {"x_shape": shape}
res_mpc = GradSum.backward(ctx, grad_mpc)
res = res_mpc.reconstruct()
expected = torch.ones(size=shape) * grad
assert (res == expected).all()
def test_grad_sub_forward(get_clients) -> None:
| 64 | 64 | 138 | 11 | 53 | libratiger/SyMPC | tests/sympc/tensor/grad/grad_functions_test.py | Python | test_grad_sub_forward | test_grad_sub_forward | 148 | 162 | 148 | 148 | fb003e2793dd29e9321a7e7a090f66fa2fb413f5 | bigcode/the-stack | train |
15c7746d617d579ef35dd8a1 | train | function | def test_grad_transpose_forward(get_clients) -> None:
secret = torch.Tensor([[1, 2, 3], [4, 5, 6]])
mpc_tensor = secret.share(parties=get_clients(4))
ctx = {}
res_mpc = GradT.forward(ctx, mpc_tensor)
res = res_mpc.reconstruct()
expected = secret.t()
assert (res == expected).all()
| def test_grad_transpose_forward(get_clients) -> None:
| secret = torch.Tensor([[1, 2, 3], [4, 5, 6]])
mpc_tensor = secret.share(parties=get_clients(4))
ctx = {}
res_mpc = GradT.forward(ctx, mpc_tensor)
res = res_mpc.reconstruct()
expected = secret.t()
assert (res == expected).all()
| def test_grad_func_abstract_forward_exception() -> None:
with pytest.raises(NotImplementedError):
GradFunc.forward({})
def test_grad_func_abstract_backward_exception() -> None:
with pytest.raises(NotImplementedError):
GradFunc.backward({})
def test_grad_transpose_forward(get_clients) -> None:
| 63 | 64 | 91 | 12 | 52 | libratiger/SyMPC | tests/sympc/tensor/grad/grad_functions_test.py | Python | test_grad_transpose_forward | test_grad_transpose_forward | 25 | 35 | 25 | 25 | 15d2effe91a89f130d39c5443c2d54673537c670 | bigcode/the-stack | train |
002e5f98c139a689e0e40e13 | train | function | def test_grad_mul_backward(get_clients) -> None:
parties = get_clients(4)
grad = torch.Tensor([[1, 2], [3, 4]])
x = torch.Tensor([[1, 2], [3, -4]])
y = torch.Tensor([[1, -4], [8, 9]])
x_mpc = x.share(parties=parties)
y_mpc = y.share(parties=parties)
grad_mpc = grad.share(parties=parties)
... | def test_grad_mul_backward(get_clients) -> None:
| parties = get_clients(4)
grad = torch.Tensor([[1, 2], [3, 4]])
x = torch.Tensor([[1, 2], [3, -4]])
y = torch.Tensor([[1, -4], [8, 9]])
x_mpc = x.share(parties=parties)
y_mpc = y.share(parties=parties)
grad_mpc = grad.share(parties=parties)
ctx = {"x": x_mpc, "y": y_mpc}
res_mpc_x... | y_mpc)
assert "x" in ctx
assert "y" in ctx
res = res_mpc.reconstruct()
expected = x * y
assert np.allclose(res, expected, rtol=1e-3)
def test_grad_mul_backward(get_clients) -> None:
| 64 | 64 | 194 | 11 | 53 | libratiger/SyMPC | tests/sympc/tensor/grad/grad_functions_test.py | Python | test_grad_mul_backward | test_grad_mul_backward | 265 | 281 | 265 | 265 | d64ed0c7c6832bc56ed82cd5e951845a265545a0 | bigcode/the-stack | train |
0a3ad553980d46f9c322885d | train | function | def test_grad_add_different_dims_forward(get_clients) -> None:
parties = get_clients(4)
x = torch.Tensor([[1, 2, 3], [4, 5, 6]])
y = torch.Tensor([1, 2, 3])
x_mpc = x.share(parties=parties)
y_mpc = y.share(parties=parties)
ctx = {}
res_mpc = GradAdd.forward(ctx, x_mpc, y_mpc)
res = re... | def test_grad_add_different_dims_forward(get_clients) -> None:
| parties = get_clients(4)
x = torch.Tensor([[1, 2, 3], [4, 5, 6]])
y = torch.Tensor([1, 2, 3])
x_mpc = x.share(parties=parties)
y_mpc = y.share(parties=parties)
ctx = {}
res_mpc = GradAdd.forward(ctx, x_mpc, y_mpc)
res = res_mpc.reconstruct()
expected = x + y
assert (res == ex... | .t().share(parties=parties)
ctx = {}
res_mpc = GradT.backward(ctx, grad_mpc)
res = res_mpc.reconstruct()
expected = grad
assert (res == expected).all()
def test_grad_add_different_dims_forward(get_clients) -> None:
| 64 | 64 | 132 | 14 | 50 | libratiger/SyMPC | tests/sympc/tensor/grad/grad_functions_test.py | Python | test_grad_add_different_dims_forward | test_grad_add_different_dims_forward | 52 | 66 | 52 | 52 | 6bb397d07a289f85b088c18ab709dd11f33afc45 | bigcode/the-stack | train |
fa268518460879bf549b66ae | train | function | def test_grad_func_abstract_forward_exception() -> None:
with pytest.raises(NotImplementedError):
GradFunc.forward({})
| def test_grad_func_abstract_forward_exception() -> None:
| with pytest.raises(NotImplementedError):
GradFunc.forward({})
| GradMul
from sympc.tensor.grads.grad_functions import GradSigmoid
from sympc.tensor.grads.grad_functions import GradSub
from sympc.tensor.grads.grad_functions import GradSum
from sympc.tensor.grads.grad_functions import GradT
def test_grad_func_abstract_forward_exception() -> None:
| 64 | 64 | 25 | 12 | 51 | libratiger/SyMPC | tests/sympc/tensor/grad/grad_functions_test.py | Python | test_grad_func_abstract_forward_exception | test_grad_func_abstract_forward_exception | 15 | 17 | 15 | 15 | 651d5c068ec6f30b0cd624da36b22fdfb7f142d7 | bigcode/the-stack | train |
33240db81b606088286eb6ee | train | function | def test_grad_sigmoid_forward(get_clients) -> None:
# We need Function Secret Sharing (only for 2 parties) for
# comparing
parties = get_clients(2)
x = torch.Tensor([7, 10, 12])
x_mpc = x.share(parties=parties)
ctx = {}
res_mpc = GradSigmoid.forward(ctx, x_mpc)
assert "probabilities" ... | def test_grad_sigmoid_forward(get_clients) -> None:
# We need Function Secret Sharing (only for 2 parties) for
# comparing
| parties = get_clients(2)
x = torch.Tensor([7, 10, 12])
x_mpc = x.share(parties=parties)
ctx = {}
res_mpc = GradSigmoid.forward(ctx, x_mpc)
assert "probabilities" in ctx
res = res_mpc.reconstruct()
expected = x.sigmoid()
assert np.allclose(res, expected, rtol=1e-2)
| assert (res_mpc_x.reconstruct() == grad_x).all()
assert (res_mpc_y.reconstruct() == grad_y).all()
def test_grad_sigmoid_forward(get_clients) -> None:
# We need Function Secret Sharing (only for 2 parties) for
# comparing
| 64 | 64 | 128 | 32 | 32 | libratiger/SyMPC | tests/sympc/tensor/grad/grad_functions_test.py | Python | test_grad_sigmoid_forward | test_grad_sigmoid_forward | 210 | 226 | 210 | 212 | 91eaefefeaf51ad5dd5a138186365418ece04577 | bigcode/the-stack | train |
fde72c403bd4f27597e6f314 | train | function | def test_grad_add_backward(get_clients) -> None:
parties = get_clients(4)
grad = torch.Tensor([1, 2, 3, 4])
grad_mpc = grad.share(parties=parties)
ctx = {"x_shape": (4,), "y_shape": (4,)}
res_mpc_x, res_mpc_y = GradAdd.backward(ctx, grad_mpc)
assert (res_mpc_x.reconstruct() == grad).all()
... | def test_grad_add_backward(get_clients) -> None:
| parties = get_clients(4)
grad = torch.Tensor([1, 2, 3, 4])
grad_mpc = grad.share(parties=parties)
ctx = {"x_shape": (4,), "y_shape": (4,)}
res_mpc_x, res_mpc_y = GradAdd.backward(ctx, grad_mpc)
assert (res_mpc_x.reconstruct() == grad).all()
assert (res_mpc_y.reconstruct() == grad).all()
| (parties=parties)
ctx = {}
res_mpc = GradAdd.forward(ctx, x_mpc, y_mpc)
res = res_mpc.reconstruct()
expected = x + y
assert (res == expected).all()
def test_grad_add_backward(get_clients) -> None:
| 64 | 64 | 117 | 11 | 53 | libratiger/SyMPC | tests/sympc/tensor/grad/grad_functions_test.py | Python | test_grad_add_backward | test_grad_add_backward | 101 | 111 | 101 | 101 | 35a2a233721c403ee830ef126484d63af49dccb5 | bigcode/the-stack | train |
752d58700211145db187d043 | train | class | class BoolSerialiser(Serialiser[bool]):
"""
Serialiser which serialises a boolean value to a single byte,
with 0x00 representing False and 0x01 representing True.
"""
def __init__(self,
true_byte: bytes = b'\x01',
false_byte: bytes = b'\x00'):
# Make sure th... | class BoolSerialiser(Serialiser[bool]):
| """
Serialiser which serialises a boolean value to a single byte,
with 0x00 representing False and 0x01 representing True.
"""
def __init__(self,
true_byte: bytes = b'\x01',
false_byte: bytes = b'\x00'):
# Make sure the true and false bytes are 1-byte long
... | from typing import IO
from .._Serialiser import Serialiser
class BoolSerialiser(Serialiser[bool]):
| 24 | 98 | 329 | 10 | 13 | waikato-datamining/wai-spectral-io | src/wai/spectralio/serialisation/serialisers/_BoolSerialiser.py | Python | BoolSerialiser | BoolSerialiser | 6 | 41 | 6 | 6 | 208c08e7108b9ae73f083f0ecb35b4e71fd48903 | bigcode/the-stack | train |
fe4c004545ed12dc9613c909 | train | function | def test_missing_args():
"""Nothing to check: uname accepts any number of arguments."""
pass
| def test_missing_args():
| """Nothing to check: uname accepts any number of arguments."""
pass
| pubs.opengroup.org/onlinepubs/9699919799/utilities/uname.html
"""
import os
from helpers import check, check_fail, check_version, run
def test_version():
"""Check that we're using Boreutil's implementation."""
assert check_version("uname")
def test_missing_args():
| 64 | 64 | 21 | 5 | 59 | duckinator/boreutils | test/test_uname.py | Python | test_missing_args | test_missing_args | 16 | 18 | 16 | 16 | b06751bcc8fb4f985d00235f451b419a4b2eff2f | bigcode/the-stack | train |
8e3300049a1f5037046b06de | train | function | def test_main():
"""Test that uname returns the correct values, and errors when appropriate."""
uname = os.uname()
uname_smr = f"{uname.sysname} {uname.release} {uname.machine}\n"
uname_a = f"{uname.sysname} {uname.nodename} {uname.release} {uname.version} {uname.machine}\n"
assert check(["uname"]).... | def test_main():
| """Test that uname returns the correct values, and errors when appropriate."""
uname = os.uname()
uname_smr = f"{uname.sysname} {uname.release} {uname.machine}\n"
uname_a = f"{uname.sysname} {uname.nodename} {uname.release} {uname.version} {uname.machine}\n"
assert check(["uname"]).stdout == uname.s... | print help text."""
assert run(["uname", "-h"]).stdout.split(' ')[0] == 'Usage:'
assert run(["uname", "--help"]).stdout.split(' ')[0] == 'Usage:'
assert run(["uname", "-h"]).returncode > 0
assert run(["uname", "--help"]).returncode > 0
def test_main():
| 78 | 78 | 260 | 4 | 73 | duckinator/boreutils | test/test_uname.py | Python | test_main | test_main | 34 | 49 | 34 | 34 | e2f487ead4cd58f369706b3eaf0cc16ef8d7cae2 | bigcode/the-stack | train |
33d7c198f91e19144503dd4a | train | function | def test_extra_args():
"""Nothing to check: uname accepts any number of arguments."""
pass
| def test_extra_args():
| """Nothing to check: uname accepts any number of arguments."""
pass
| import os
from helpers import check, check_fail, check_version, run
def test_version():
"""Check that we're using Boreutil's implementation."""
assert check_version("uname")
def test_missing_args():
"""Nothing to check: uname accepts any number of arguments."""
pass
def test_extra_args():
| 64 | 64 | 21 | 5 | 58 | duckinator/boreutils | test/test_uname.py | Python | test_extra_args | test_extra_args | 21 | 23 | 21 | 21 | 79cb7b50f95fc945db95d522cbc56d5bffb9d583 | bigcode/the-stack | train |
996b775f24f9e458da258364 | train | function | def test_help():
"""Passing -h or --help => print help text."""
assert run(["uname", "-h"]).stdout.split(' ')[0] == 'Usage:'
assert run(["uname", "--help"]).stdout.split(' ')[0] == 'Usage:'
assert run(["uname", "-h"]).returncode > 0
assert run(["uname", "--help"]).returncode > 0
| def test_help():
| """Passing -h or --help => print help text."""
assert run(["uname", "-h"]).stdout.split(' ')[0] == 'Usage:'
assert run(["uname", "--help"]).stdout.split(' ')[0] == 'Usage:'
assert run(["uname", "-h"]).returncode > 0
assert run(["uname", "--help"]).returncode > 0
| """Check that we're using Boreutil's implementation."""
assert check_version("uname")
def test_missing_args():
"""Nothing to check: uname accepts any number of arguments."""
pass
def test_extra_args():
"""Nothing to check: uname accepts any number of arguments."""
pass
def test_help():
| 64 | 64 | 87 | 4 | 59 | duckinator/boreutils | test/test_uname.py | Python | test_help | test_help | 26 | 31 | 26 | 26 | 7d6dbca561684c0931e21dcecb7bf055db4c97a4 | bigcode/the-stack | train |
892365a21494f95f47abebac | train | function | def test_version():
"""Check that we're using Boreutil's implementation."""
assert check_version("uname")
| def test_version():
| """Check that we're using Boreutil's implementation."""
assert check_version("uname")
| """
Tests for POSIX-compatible `uname`.
https://pubs.opengroup.org/onlinepubs/9699919799/utilities/uname.html
"""
import os
from helpers import check, check_fail, check_version, run
def test_version():
| 52 | 64 | 22 | 4 | 47 | duckinator/boreutils | test/test_uname.py | Python | test_version | test_version | 11 | 13 | 11 | 11 | 59a45fc653bcf030d207f17f53b93b34981f5b14 | bigcode/the-stack | train |
b73527a766797c2f2d1bbff6 | train | function | def lev_dist(source, target):
if source == target:
return 0
#words = open(test_file.txt,'r').read().split();
# Prepare matrix
slen, tlen = len(source), len(target)
dist = [[0 for i in range(tlen+1)] for x in range(slen+1)]
for i in range(slen+1):
dist[i][0] = i
for j in range(t... | def lev_dist(source, target):
| if source == target:
return 0
#words = open(test_file.txt,'r').read().split();
# Prepare matrix
slen, tlen = len(source), len(target)
dist = [[0 for i in range(tlen+1)] for x in range(slen+1)]
for i in range(slen+1):
dist[i][0] = i
for j in range(tlen+1):
dist[0][j] = j... | #!/usr/bin/env python
# -*- coding=utf-8 -*-
def lev_dist(source, target):
| 20 | 65 | 217 | 7 | 13 | DmitryPMI/pgups_hack | requests/lev_distance.py | Python | lev_dist | lev_dist | 4 | 27 | 4 | 4 | 920e7e349b22e36abd8078ad09286c6c583f6314 | bigcode/the-stack | train |
8c7f1df04ff62f0dac6094d6 | train | function | def req_distance(request_words, word):
for i in request_words:
if lev_dist(word, i) <= 2:
return True
return False | def req_distance(request_words, word):
| for i in request_words:
if lev_dist(word, i) <= 2:
return True
return False |
dist[i+1][j] + 1, # insertion
dist[i][j] + cost # substitution
)
return dist[-1][-1]
#print(lev_dist("расписание", "расписанье"))
def req_distance(request_words, word):
| 64 | 64 | 34 | 8 | 56 | DmitryPMI/pgups_hack | requests/lev_distance.py | Python | req_distance | req_distance | 31 | 38 | 31 | 32 | 6d5bc8c762880741a42ddf791414a9f7d83778b9 | bigcode/the-stack | train |
cab806a32fd8310f29df8f1f | train | class | class AbstractUrlsModuleParams(AbstractModuleParams):
def __init__(self):
AbstractModuleParams.__init__(self)
self.add_options(
[
'msymbol',
'not-found-re',
'found-re',
'not-found-ex',
'not-found-size',
... | class AbstractUrlsModuleParams(AbstractModuleParams):
| def __init__(self):
AbstractModuleParams.__init__(self)
self.add_options(
[
'msymbol',
'not-found-re',
'found-re',
'not-found-ex',
'not-found-size',
'not-found-codes',
'ignore-... | /WebScout
License: MIT
Copyright (c) Anton Kuzmin <http://anton-kuzmin.ru> (ru) <http://anton-kuzmin.pro> (en)
Module params class
"""
from classes.modules.params.AbstractModuleParams import AbstractModuleParams
class AbstractUrlsModuleParams(AbstractModuleParams):
| 64 | 64 | 132 | 9 | 54 | AntonKuzminRussia/web-scout | classes/modules/params/AbstractUrlsModuleParams.py | Python | AbstractUrlsModuleParams | AbstractUrlsModuleParams | 15 | 38 | 15 | 15 | 001039ce9a77ce85e729e4b8b351304b2196be7e | bigcode/the-stack | train |
76210f62b5c99d8809bf8953 | train | class | class RegistryJob(core.job.Job):
def create(self):
if self.session_id == -1:
self.error("0", "This job is not yet compatible with ONESHOT stagers.", "ONESHOT job error", "")
return False
if self.session.elevated != 1 and self.options.get("IGNOREADMIN") == "false":
... | class RegistryJob(core.job.Job):
| def create(self):
if self.session_id == -1:
self.error("0", "This job is not yet compatible with ONESHOT stagers.", "ONESHOT job error", "")
return False
if self.session.elevated != 1 and self.options.get("IGNOREADMIN") == "false":
self.script = self.script.replac... | import core.job
import core.implant
import uuid
class RegistryJob(core.job.Job):
| 19 | 95 | 317 | 7 | 11 | beenjaminmb/koadic | modules/implant/persist/registry.py | Python | RegistryJob | RegistryJob | 5 | 48 | 5 | 6 | 64f214f6058b07a7a523a37c45f8c42368a85756 | bigcode/the-stack | train |
6e71450fd7ff4fce7d8edd6b | train | class | class RegistryImplant(core.implant.Implant):
NAME = "Add Registry Payload"
DESCRIPTION = "Adds a Koadic stager payload in the registry."
AUTHORS = ["TheNaterz"]
def load(self):
self.options.register("PAYLOAD", "", "payload to stage")
self.options.register("CMD", "", "command", hidden=T... | class RegistryImplant(core.implant.Implant):
| NAME = "Add Registry Payload"
DESCRIPTION = "Adds a Koadic stager payload in the registry."
AUTHORS = ["TheNaterz"]
def load(self):
self.options.register("PAYLOAD", "", "payload to stage")
self.options.register("CMD", "", "command", hidden=True)
self.options.register("CLEANUP", ... | be removed.")
return
if data == "Complete":
super(RegistryJob, self).report(handler, data)
handler.reply(200)
def done(self):
self.results = "Completed"
self.display()
def display(self):
# self.shell.print_plain(self.data)
pass
class R... | 76 | 76 | 255 | 11 | 64 | beenjaminmb/koadic | modules/implant/persist/registry.py | Python | RegistryImplant | RegistryImplant | 50 | 80 | 50 | 51 | d18252b04f8f9887c0f07ad8d250b837065de122 | bigcode/the-stack | train |
f9a5dae6a00598b695dfbe93 | train | function | def gen_train_data(dataset, split, time_step, nb_nodes, nhood, global_att, batch_size, reverse, PG_type):
def get_data(dimension, fr):
if reverse == '1':
used_data = 'target'
else:
used_data = 'source'
input_data = np.load(
'Datasets/' + frames_ps + dataset + '_train_npy_data/' + used_data + '_' + dimen... | def gen_train_data(dataset, split, time_step, nb_nodes, nhood, global_att, batch_size, reverse, PG_type):
| def get_data(dimension, fr):
if reverse == '1':
used_data = 'target'
else:
used_data = 'source'
input_data = np.load(
'Datasets/' + frames_ps + dataset + '_train_npy_data/' + used_data + '_' + dimension + '_' + dataset + '_' + str(
fr) + '.npy')
input_data = input_data.reshape([-1, time_step, nb_n... | import numpy as np
import pickle as pkl
import networkx as nx
import scipy.sparse as sp
import copy
from scipy.sparse.linalg.eigen.arpack import eigsh
import sys
from sklearn.preprocessing import label_binarize
from sklearn.metrics import roc_curve, auc
"""
Generate training data for each dataset.
"""
def gen_train_d... | 98 | 256 | 3,804 | 28 | 70 | Anonymous-926/SM-SGE | utils/process_cme.py | Python | gen_train_data | gen_train_data | 15 | 223 | 15 | 15 | 7fc3450b5db9d32be25bf53862575f25efa4aa17 | bigcode/the-stack | train |
a8a12c5d271810d7921fbc4c | train | function | def cal_nAUC(scores, labels):
scores = np.array(scores)
labels = np.array(labels)
# Compute micro-average ROC curve and ROC area
fpr, tpr, thresholds = roc_curve(labels.ravel(), scores.ravel())
roc_auc = auc(fpr, tpr)
return roc_auc
| def cal_nAUC(scores, labels):
| scores = np.array(scores)
labels = np.array(labels)
# Compute micro-average ROC curve and ROC area
fpr, tpr, thresholds = roc_curve(labels.ravel(), scores.ravel())
roc_auc = auc(fpr, tpr)
return roc_auc
| )
X_interp = np.reshape(X_interp, [X.shape[0], X.shape[1], node_num-1, 3])
X_interp = np.concatenate((X, X_interp), axis=-2)
return X_interp
"""
Calculate normalized area under curves.
"""
def cal_nAUC(scores, labels):
| 64 | 64 | 67 | 9 | 55 | Anonymous-926/SM-SGE | utils/process_cme.py | Python | cal_nAUC | cal_nAUC | 478 | 484 | 478 | 478 | 58aaae3fea92662b6c48e894ec2a835198786f90 | bigcode/the-stack | train |
9e65268ed477c7dabb380360 | train | function | def load_random_data(size):
adj = sp.random(size, size, density=0.002) # density similar to cora
features = sp.random(size, 1000, density=0.015)
int_labels = np.random.randint(7, size=(size))
labels = np.zeros((size, 7)) # Nx7
labels[np.arange(size), int_labels] = 1
train_mask = np.zeros((size,)).astype(bool)
... | def load_random_data(size):
| adj = sp.random(size, size, density=0.002) # density similar to cora
features = sp.random(size, 1000, density=0.015)
int_labels = np.random.randint(7, size=(size))
labels = np.zeros((size, 7)) # Nx7
labels[np.arange(size), int_labels] = 1
train_mask = np.zeros((size,)).astype(bool)
train_mask[np.arange(size)[... | np.zeros(labels.shape)
y_train[train_mask, :] = labels[train_mask, :]
y_val[val_mask, :] = labels[val_mask, :]
y_test[test_mask, :] = labels[test_mask, :]
# print(adj.shape)
# print(features.shape)
return adj, features, y_train, y_val, y_test, train_mask, val_mask, test_mask
def load_random_data(size):
| 85 | 85 | 284 | 6 | 78 | Anonymous-926/SM-SGE | utils/process_cme.py | Python | load_random_data | load_random_data | 622 | 646 | 622 | 622 | 508052c97bf11b0e7b3f611ded92d244837b9a42 | bigcode/the-stack | train |
c04e01f1d42ed465e608085f | train | function | def adj_to_bias(adj, sizes, nhood=1):
nb_graphs = adj.shape[0]
mt = np.empty(adj.shape)
for g in range(nb_graphs):
mt[g] = np.eye(adj.shape[1])
for _ in range(nhood):
mt[g] = np.matmul(mt[g], (adj[g] + np.eye(adj.shape[1])))
for i in range(sizes[g]):
for j in range(sizes[g]):
if mt[g][i][j] > 0.0:
... | def adj_to_bias(adj, sizes, nhood=1):
| nb_graphs = adj.shape[0]
mt = np.empty(adj.shape)
for g in range(nb_graphs):
mt[g] = np.eye(adj.shape[1])
for _ in range(nhood):
mt[g] = np.matmul(mt[g], (adj[g] + np.eye(adj.shape[1])))
for i in range(sizes[g]):
for j in range(sizes[g]):
if mt[g][i][j] > 0.0:
mt[g][i][j] = 1.0
return -1e9 * (1... | _batch_y)
return X_train, y_train
"""
Prepare adjacency matrix by expanding up to a given neighbourhood.
This will insert loops on every node.
Finally, the matrix is converted to bias vectors.
Expected shape: [graph, nodes, nodes]
"""
def adj_to_bias(adj, sizes, nhood=1):
| 64 | 64 | 139 | 13 | 51 | Anonymous-926/SM-SGE | utils/process_cme.py | Python | adj_to_bias | adj_to_bias | 535 | 546 | 535 | 535 | 34347f519951520cf04c32766d01abb34d386c61 | bigcode/the-stack | train |
77a213cd5e7461c248ff895a | train | function | def generate_denser_graph_data(X, adj, joint_num=20):
adj_temp = copy.deepcopy(adj)
adj_temp = adj_temp.tolist()
node_num = len(adj_temp)
cnt = node_num
for i in range(node_num):
for j in range(node_num):
if adj_temp[i][j] == 1:
adj_temp[i][j] = adj_temp[j][i] = 0
new_node = np.mean(X[:, :, [i, j], :]... | def generate_denser_graph_data(X, adj, joint_num=20):
| adj_temp = copy.deepcopy(adj)
adj_temp = adj_temp.tolist()
node_num = len(adj_temp)
cnt = node_num
for i in range(node_num):
for j in range(node_num):
if adj_temp[i][j] == 1:
adj_temp[i][j] = adj_temp[j][i] = 0
new_node = np.mean(X[:, :, [i, j], :], axis=2)
# print(new_node.shape)
if cnt == no... | 2), axis=-1) \
.reshape([X.shape[0], X.shape[1], 19, 3])
# 25+24
X_interp = np.concatenate((X, X_part), axis=-2)
return X_interp
def generate_denser_graph_data(X, adj, joint_num=20):
| 70 | 70 | 236 | 15 | 54 | Anonymous-926/SM-SGE | utils/process_cme.py | Python | generate_denser_graph_data | generate_denser_graph_data | 451 | 473 | 451 | 451 | 10126ac0629e3dca879f95de9a06e70003fcf628 | bigcode/the-stack | train |
ba5294eb822213ec57ba2ea7 | train | function | def sparse_to_tuple(sparse_mx):
"""Convert sparse matrix to tuple representation."""
def to_tuple(mx):
if not sp.isspmatrix_coo(mx):
mx = mx.tocoo()
coords = np.vstack((mx.row, mx.col)).transpose()
values = mx.data
shape = mx.shape
return coords, values, shape
if isinstance(sparse_mx, list):
for i i... | def sparse_to_tuple(sparse_mx):
| """Convert sparse matrix to tuple representation."""
def to_tuple(mx):
if not sp.isspmatrix_coo(mx):
mx = mx.tocoo()
coords = np.vstack((mx.row, mx.col)).transpose()
values = mx.data
shape = mx.shape
return coords, values, shape
if isinstance(sparse_mx, list):
for i in range(len(sparse_mx)):
spar... | _test[test_mask, :] = labels[test_mask, :]
# sparse NxN, sparse NxF, norm NxC, ..., norm Nx1, ...
return adj, features, y_train, y_val, y_test, train_mask, val_mask, test_mask
def sparse_to_tuple(sparse_mx):
| 64 | 64 | 136 | 9 | 54 | Anonymous-926/SM-SGE | utils/process_cme.py | Python | sparse_to_tuple | sparse_to_tuple | 649 | 666 | 649 | 649 | 4b4e0f911849caa4e81c6c869a8aa17cabcc6a6c | bigcode/the-stack | train |
c5e2daefe008e610a32e72c0 | train | function | def parse_index_file(filename):
"""Parse index file."""
index = []
for line in open(filename):
index.append(int(line.strip()))
return index
| def parse_index_file(filename):
| """Parse index file."""
index = []
for line in open(filename):
index.append(int(line.strip()))
return index
| [g][i][j] > 0.0:
mt[g][i][j] = 1.0
return -1e9 * (1.0 - mt)
###############################################
# This section of code adapted from tkipf/gcn #
###############################################
def parse_index_file(filename):
| 64 | 64 | 31 | 6 | 58 | Anonymous-926/SM-SGE | utils/process_cme.py | Python | parse_index_file | parse_index_file | 553 | 558 | 553 | 553 | 5831091f0b5eaf151e26ede0a5ea0c36515c2304 | bigcode/the-stack | train |
3e49f8a9afddfdc85806d17c | train | function | def sample_mask(idx, l):
"""Create mask."""
mask = np.zeros(l)
mask[idx] = 1
return np.array(mask, dtype=np.bool)
| def sample_mask(idx, l):
| """Create mask."""
mask = np.zeros(l)
mask[idx] = 1
return np.array(mask, dtype=np.bool)
| (1.0 - mt)
###############################################
# This section of code adapted from tkipf/gcn #
###############################################
def parse_index_file(filename):
"""Parse index file."""
index = []
for line in open(filename):
index.append(int(line.strip()))
return index
def sample_mask... | 64 | 64 | 34 | 7 | 56 | Anonymous-926/SM-SGE | utils/process_cme.py | Python | sample_mask | sample_mask | 561 | 565 | 561 | 561 | e515f878188bdc7f6766110c088fbaff8549f5e8 | bigcode/the-stack | train |
8dd057473cb42531212ce387 | train | function | def class_samp_gen(X, y, ids_, batch_size):
class_num = len(ids_.keys())
ids_ = sorted(ids_.items(), key=lambda item: item[0])
cnt = 0
all_batch_X = []
all_batch_y = []
total = y.shape[0]
batch_num = total // batch_size * 2
batch_num = total // batch_size * 2
class_in_bacth = class_num
batch_per_class = batch... | def class_samp_gen(X, y, ids_, batch_size):
| class_num = len(ids_.keys())
ids_ = sorted(ids_.items(), key=lambda item: item[0])
cnt = 0
all_batch_X = []
all_batch_y = []
total = y.shape[0]
batch_num = total // batch_size * 2
batch_num = total // batch_size * 2
class_in_bacth = class_num
batch_per_class = batch_size // class_in_bacth
class_cnt = class_i... | np.concatenate((X, X_interp), axis=-2)
return X_interp
"""
Calculate normalized area under curves.
"""
def cal_nAUC(scores, labels):
scores = np.array(scores)
labels = np.array(labels)
# Compute micro-average ROC curve and ROC area
fpr, tpr, thresholds = roc_curve(labels.ravel(), scores.ravel())
roc_auc = auc(... | 115 | 115 | 385 | 14 | 101 | Anonymous-926/SM-SGE | utils/process_cme.py | Python | class_samp_gen | class_samp_gen | 489 | 525 | 489 | 489 | 11efed3cf61808e14c808967530b243de80be9b4 | bigcode/the-stack | train |
89c40953b7cd5eac033f9e15 | train | function | def preprocess_features(features):
"""Row-normalize feature matrix and convert to tuple representation"""
rowsum = np.array(features.sum(1))
r_inv = np.power(rowsum, -1).flatten()
r_inv[np.isinf(r_inv)] = 0.
r_mat_inv = sp.diags(r_inv)
features = r_mat_inv.dot(features)
return features.todense(), sparse_to_tuple... | def preprocess_features(features):
| """Row-normalize feature matrix and convert to tuple representation"""
rowsum = np.array(features.sum(1))
r_inv = np.power(rowsum, -1).flatten()
r_inv[np.isinf(r_inv)] = 0.
r_mat_inv = sp.diags(r_inv)
features = r_mat_inv.dot(features)
return features.todense(), sparse_to_tuple(features)
| f[:, np.squeeze(np.array(sigma > 0))]
mu = f[train_mask == True, :].mean(axis=0)
sigma = f[train_mask == True, :].std(axis=0)
f = (f - mu) / sigma
return f
def preprocess_features(features):
| 64 | 64 | 83 | 5 | 58 | Anonymous-926/SM-SGE | utils/process_cme.py | Python | preprocess_features | preprocess_features | 682 | 689 | 682 | 682 | e194878ea8821040a8be4f64f33f30743bec3e56 | bigcode/the-stack | train |
1fad2e1e15c403cfeb3f0cf2 | train | function | def standardize_data(f, train_mask):
"""Standardize feature matrix and convert to tuple representation"""
# standardize data
f = f.todense()
mu = f[train_mask == True, :].mean(axis=0)
sigma = f[train_mask == True, :].std(axis=0)
f = f[:, np.squeeze(np.array(sigma > 0))]
mu = f[train_mask == True, :].mean(axis=0)... | def standardize_data(f, train_mask):
| """Standardize feature matrix and convert to tuple representation"""
# standardize data
f = f.todense()
mu = f[train_mask == True, :].mean(axis=0)
sigma = f[train_mask == True, :].std(axis=0)
f = f[:, np.squeeze(np.array(sigma > 0))]
mu = f[train_mask == True, :].mean(axis=0)
sigma = f[train_mask == True, :].st... | isinstance(sparse_mx, list):
for i in range(len(sparse_mx)):
sparse_mx[i] = to_tuple(sparse_mx[i])
else:
sparse_mx = to_tuple(sparse_mx)
return sparse_mx
def standardize_data(f, train_mask):
| 64 | 64 | 129 | 9 | 54 | Anonymous-926/SM-SGE | utils/process_cme.py | Python | standardize_data | standardize_data | 669 | 679 | 669 | 669 | 41bcab4cb867934d22875b6bde2ba5aa39e1e8c0 | bigcode/the-stack | train |
efc86d2f86153352d2d86b67 | train | function | def preprocess_adj(adj):
"""Preprocessing of adjacency matrix for simple GCN model and conversion to tuple representation."""
adj_normalized = normalize_adj(adj + sp.eye(adj.shape[0]))
return sparse_to_tuple(adj_normalized)
| def preprocess_adj(adj):
| """Preprocessing of adjacency matrix for simple GCN model and conversion to tuple representation."""
adj_normalized = normalize_adj(adj + sp.eye(adj.shape[0]))
return sparse_to_tuple(adj_normalized)
| , -0.5).flatten()
d_inv_sqrt[np.isinf(d_inv_sqrt)] = 0.
d_mat_inv_sqrt = sp.diags(d_inv_sqrt)
return adj.dot(d_mat_inv_sqrt).transpose().dot(d_mat_inv_sqrt).tocoo()
def preprocess_adj(adj):
| 64 | 64 | 47 | 5 | 59 | Anonymous-926/SM-SGE | utils/process_cme.py | Python | preprocess_adj | preprocess_adj | 702 | 705 | 702 | 702 | b9006b8d2f205229f9f9669d96d93b1ab44702b5 | bigcode/the-stack | train |
e556bcc3d4da832f6ace072c | train | function | def preprocess_adj_bias(adj):
num_nodes = adj.shape[0]
adj = adj + sp.eye(num_nodes) # self-loop
adj[adj > 0.0] = 1.0
if not sp.isspmatrix_coo(adj):
adj = adj.tocoo()
adj = adj.astype(np.float32)
indices = np.vstack(
(adj.col, adj.row)).transpose() # This is where I made a mistake, I used (adj.row, adj.col)... | def preprocess_adj_bias(adj):
| num_nodes = adj.shape[0]
adj = adj + sp.eye(num_nodes) # self-loop
adj[adj > 0.0] = 1.0
if not sp.isspmatrix_coo(adj):
adj = adj.tocoo()
adj = adj.astype(np.float32)
indices = np.vstack(
(adj.col, adj.row)).transpose() # This is where I made a mistake, I used (adj.row, adj.col) instead
# return tf.SparseTe... | ().dot(d_mat_inv_sqrt).tocoo()
def preprocess_adj(adj):
"""Preprocessing of adjacency matrix for simple GCN model and conversion to tuple representation."""
adj_normalized = normalize_adj(adj + sp.eye(adj.shape[0]))
return sparse_to_tuple(adj_normalized)
def preprocess_adj_bias(adj):
| 64 | 64 | 142 | 6 | 58 | Anonymous-926/SM-SGE | utils/process_cme.py | Python | preprocess_adj_bias | preprocess_adj_bias | 708 | 718 | 708 | 708 | 29a87d1cdf789ee9ad5db03cf56a7ac67963e48d | bigcode/the-stack | train |
b2ca791bbd973db28784ad37 | train | function | def load_data(dataset_str): # {'pubmed', 'citeseer', 'cora'}
"""Load data."""
names = ['x', 'y', 'tx', 'ty', 'allx', 'ally', 'graph']
objects = []
for i in range(len(names)):
with open("data/ind.{}.{}".format(dataset_str, names[i]), 'rb') as f:
if sys.version_info > (3, 0):
objects.append(pkl.load(f, enco... | def load_data(dataset_str): # {'pubmed', 'citeseer', 'cora'}
| """Load data."""
names = ['x', 'y', 'tx', 'ty', 'allx', 'ally', 'graph']
objects = []
for i in range(len(names)):
with open("data/ind.{}.{}".format(dataset_str, names[i]), 'rb') as f:
if sys.version_info > (3, 0):
objects.append(pkl.load(f, encoding='latin1'))
else:
objects.append(pkl.load(f))
x, ... | [1])))
for i in range(sizes[g]):
for j in range(sizes[g]):
if mt[g][i][j] > 0.0:
mt[g][i][j] = 1.0
return -1e9 * (1.0 - mt)
###############################################
# This section of code adapted from tkipf/gcn #
###############################################
def parse_index_file(filename):
"... | 168 | 168 | 563 | 21 | 147 | Anonymous-926/SM-SGE | utils/process_cme.py | Python | load_data | load_data | 568 | 619 | 568 | 568 | a8ba9d586cd5068061f699e6576d837aa5cc2c5b | bigcode/the-stack | train |
d02424a2ff1c6d68b099d189 | train | function | def reduce2part(X, joint_num=20):
if joint_num == 25:
left_leg_up = [12, 13]
left_leg_down = [14, 15]
right_leg_up = [16, 17]
right_leg_down = [18, 19]
torso = [0, 1]
head = [2, 3, 20]
left_arm_up = [4, 5]
left_arm_down = [6, 7, 21, 22]
right_arm_up = [8, 9]
right_arm_down = [10, 11, 23, 24]
elif ... | def reduce2part(X, joint_num=20):
| if joint_num == 25:
left_leg_up = [12, 13]
left_leg_down = [14, 15]
right_leg_up = [16, 17]
right_leg_down = [18, 19]
torso = [0, 1]
head = [2, 3, 20]
left_arm_up = [4, 5]
left_arm_down = [6, 7, 21, 22]
right_arm_up = [8, 9]
right_arm_down = [10, 11, 23, 24]
elif joint_num == 20:
left_leg_up = [... | _joint, [nb_nodes], nhood=nhood)
adj_part = adj_part[np.newaxis]
biases_part = adj_to_bias(adj_part, [10], nhood=1)
adj_body = adj_body[np.newaxis]
biases_body = adj_to_bias(adj_body, [5], nhood=1)
adj_interp = adj_interp[np.newaxis]
biases_interp = adj_to_bias(adj_interp, [nb_nodes*2-1], nhood=1)
return X_t... | 191 | 191 | 638 | 11 | 180 | Anonymous-926/SM-SGE | utils/process_cme.py | Python | reduce2part | reduce2part | 229 | 277 | 229 | 229 | 19640afbd1b50a94600ac1742a4c226b99f42935 | bigcode/the-stack | train |
7c58fec50137cea32f931aca | train | function | def normalize_adj(adj):
"""Symmetrically normalize adjacency matrix."""
adj = sp.coo_matrix(adj)
rowsum = np.array(adj.sum(1))
d_inv_sqrt = np.power(rowsum, -0.5).flatten()
d_inv_sqrt[np.isinf(d_inv_sqrt)] = 0.
d_mat_inv_sqrt = sp.diags(d_inv_sqrt)
return adj.dot(d_mat_inv_sqrt).transpose().dot(d_mat_inv_sqrt).t... | def normalize_adj(adj):
| """Symmetrically normalize adjacency matrix."""
adj = sp.coo_matrix(adj)
rowsum = np.array(adj.sum(1))
d_inv_sqrt = np.power(rowsum, -0.5).flatten()
d_inv_sqrt[np.isinf(d_inv_sqrt)] = 0.
d_mat_inv_sqrt = sp.diags(d_inv_sqrt)
return adj.dot(d_mat_inv_sqrt).transpose().dot(d_mat_inv_sqrt).tocoo()
| .sum(1))
r_inv = np.power(rowsum, -1).flatten()
r_inv[np.isinf(r_inv)] = 0.
r_mat_inv = sp.diags(r_inv)
features = r_mat_inv.dot(features)
return features.todense(), sparse_to_tuple(features)
def normalize_adj(adj):
| 64 | 64 | 101 | 5 | 59 | Anonymous-926/SM-SGE | utils/process_cme.py | Python | normalize_adj | normalize_adj | 692 | 699 | 692 | 692 | a908f84cffec6ca6e5160754477b51e58de70cf9 | bigcode/the-stack | train |
9925bd643353f5c98bf4c013 | train | function | def interpolation(X, joint_num=20):
if joint_num == 25:
left_leg_up = [12, 13]
left_leg_down = [14, 15]
right_leg_up = [16, 17]
right_leg_down = [18, 19]
torso = [0, 1]
head_1 = [2, 3]
head_2 = [2, 20]
left_arm_up = [4, 5]
left_arm_down_1 = [6, 7]
left_arm_down_2 = [7, 21]
left_arm_down_3 = [6, 2... | def interpolation(X, joint_num=20):
| if joint_num == 25:
left_leg_up = [12, 13]
left_leg_down = [14, 15]
right_leg_up = [16, 17]
right_leg_down = [18, 19]
torso = [0, 1]
head_1 = [2, 3]
head_2 = [2, 20]
left_arm_up = [4, 5]
left_arm_down_1 = [6, 7]
left_arm_down_2 = [7, 21]
left_arm_down_3 = [6, 22]
right_arm_up = [8, 9]
right_a... | 7]
right_arm = [8, 9, 10, 11]
elif joint_num == 14:
left_leg = [11, 12, 13]
right_leg = [8, 9, 10]
torso = [0, 1]
left_arm = [5, 6, 7]
right_arm = [2, 3, 4]
x_torso = np.mean(X[:, :, torso, :], axis=2) # [N * T, V=1]
x_leftleg = np.mean(X[:, :, left_leg, :], axis=2)
x_rightleg = np.mean(X[:, :, right... | 256 | 256 | 2,201 | 9 | 247 | Anonymous-926/SM-SGE | utils/process_cme.py | Python | interpolation | interpolation | 316 | 449 | 316 | 316 | 9606441641a8ee230392c378779c63531a1c114d | bigcode/the-stack | train |
8ff7944360d77e1385b1f48e | train | function | def reduce2body(X, joint_num=20):
if joint_num == 25:
left_leg = [12, 13, 14, 15]
right_leg = [16, 17, 18, 19]
torso = [0, 1, 2, 3, 20]
left_arm = [4, 5, 6, 7, 21, 22]
right_arm = [8, 9, 10, 11, 23, 24]
elif joint_num == 20:
left_leg = [12, 13, 14, 15]
right_leg = [16, 17, 18, 19]
torso = [0, 1, 2, 3]... | def reduce2body(X, joint_num=20):
| if joint_num == 25:
left_leg = [12, 13, 14, 15]
right_leg = [16, 17, 18, 19]
torso = [0, 1, 2, 3, 20]
left_arm = [4, 5, 6, 7, 21, 22]
right_arm = [8, 9, 10, 11, 23, 24]
elif joint_num == 20:
left_leg = [12, 13, 14, 15]
right_leg = [16, 17, 18, 19]
torso = [0, 1, 2, 3]
left_arm = [4, 5, 6, 7]
right... | 2)
x_rightarmdown = np.mean(X[:, :, right_arm_down, :], axis=2)
X_part = np.concatenate((x_leftlegup, x_leftlegdown, x_rightlegup, x_rightlegdown, x_torso, x_head, x_leftarmup,
x_leftarmdown, x_rightarmup, x_rightarmdown), axis=-1) \
.reshape([X.shape[0], X.shape[1], 10, 3])
return X_part... | 126 | 126 | 423 | 11 | 115 | Anonymous-926/SM-SGE | utils/process_cme.py | Python | reduce2body | reduce2body | 283 | 310 | 283 | 283 | cac57dbf3421f563ef0f90e3180aa9c34ccabdbb | bigcode/the-stack | train |
efd9f762910acc6be15da516 | train | class | class L3NatExtensionTestCase(test_extensions_base.ExtensionTestCase):
fmt = 'json'
def setUp(self):
super(L3NatExtensionTestCase, self).setUp()
self._setUpExtension(
'neutron.services.l3_router.l3_router_plugin.L3RouterPlugin',
plugin_constants.L3, l3.RESOURCE_ATTRIBUTE_... | class L3NatExtensionTestCase(test_extensions_base.ExtensionTestCase):
| fmt = 'json'
def setUp(self):
super(L3NatExtensionTestCase, self).setUp()
self._setUpExtension(
'neutron.services.l3_router.l3_router_plugin.L3RouterPlugin',
plugin_constants.L3, l3.RESOURCE_ATTRIBUTE_MAP,
l3.L3, '', allow_pagination=True, allow_sorting=True,... |
from neutron.services.revisions import revision_plugin
from neutron.tests import base
from neutron.tests.common import helpers
from neutron.tests import fake_notifier
from neutron.tests.unit.api import test_extensions
from neutron.tests.unit.api.v2 import test_base
from neutron.tests.unit.db import test_db_base_plugin... | 255 | 256 | 1,291 | 14 | 241 | mail2nsrajesh/neutron | neutron/tests/unit/extensions/test_l3.py | Python | L3NatExtensionTestCase | L3NatExtensionTestCase | 97 | 245 | 97 | 97 | 05668cbe9c6d18b3cc752312ece61df9b3e86fac | bigcode/the-stack | train |
e1e46fb16b11d4163b0b7ca3 | train | class | class L3BaseForIntTests(test_db_base_plugin_v2.NeutronDbPluginV2TestCase):
mock_rescheduling = True
def setUp(self, plugin=None, ext_mgr=None, service_plugins=None):
if not plugin:
plugin = 'neutron.tests.unit.extensions.test_l3.TestL3NatIntPlugin'
# for these tests we need to enab... | class L3BaseForIntTests(test_db_base_plugin_v2.NeutronDbPluginV2TestCase):
| mock_rescheduling = True
def setUp(self, plugin=None, ext_mgr=None, service_plugins=None):
if not plugin:
plugin = 'neutron.tests.unit.extensions.test_l3.TestL3NatIntPlugin'
# for these tests we need to enable overlapping ips
cfg.CONF.set_default('allow_overlapping_ips', Tru... | routers', r['router']['id'],
expected_code=exc.HTTPConflict.code)
# ensure it stopped the commit
self.assertTrue(self._show('routers', r['router']['id']))
class L3BaseForIntTests(test_db_base_plugin_v2.NeutronDbPluginV2TestCase):
| 63 | 64 | 178 | 22 | 41 | mail2nsrajesh/neutron | neutron/tests/unit/extensions/test_l3.py | Python | L3BaseForIntTests | L3BaseForIntTests | 3,647 | 3,665 | 3,647 | 3,648 | c38fec7dadb07c47115f6d92407312b11b224a3b | bigcode/the-stack | train |
aeb022dba2392c97c07af7d8 | train | class | class TestL3NatAgentSchedulingServicePlugin(TestL3NatServicePlugin,
l3_dvrscheduler_db.
L3_DVRsch_db_mixin,
l3_hamode_db.L3_HA_NAT_db_mixin):
supported_extension_aliases = ["router", ... | class TestL3NatAgentSchedulingServicePlugin(TestL3NatServicePlugin,
l3_dvrscheduler_db.
L3_DVRsch_db_mixin,
l3_hamode_db.L3_HA_NAT_db_mixin):
| supported_extension_aliases = ["router", "l3_agent_scheduler"]
def __init__(self):
super(TestL3NatAgentSchedulingServicePlugin, self).__init__()
self.router_scheduler = importutils.import_object(
cfg.CONF.router_scheduler_driver)
self.agent_notifiers.update(
{lib... | with
# plugins that delegate away L3 routing functionality
class TestL3NatAgentSchedulingServicePlugin(TestL3NatServicePlugin,
l3_dvrscheduler_db.
L3_DVRsch_db_mixin,
l3_hamode_db.L3_HA_N... | 64 | 64 | 136 | 52 | 11 | mail2nsrajesh/neutron | neutron/tests/unit/extensions/test_l3.py | Python | TestL3NatAgentSchedulingServicePlugin | TestL3NatAgentSchedulingServicePlugin | 334 | 346 | 334 | 338 | 3ccb0ade1413f6beac554f4b1bf13a8e6030943f | bigcode/the-stack | train |
29c3d3617e3417ce289ba6ad | train | class | class L3NatTestCaseBase(L3NatTestCaseMixin):
def test_router_create(self):
name = 'router1'
tenant_id = _uuid()
expected_value = [('name', name), ('tenant_id', tenant_id),
('admin_state_up', True), ('status', 'ACTIVE'),
('external_gateway_... | class L3NatTestCaseBase(L3NatTestCaseMixin):
| def test_router_create(self):
name = 'router1'
tenant_id = _uuid()
expected_value = [('name', name), ('tenant_id', tenant_id),
('admin_state_up', True), ('status', 'ACTIVE'),
('external_gateway_info', None)]
with self.router(name='r... | def test__extend_extra_router_dict_defaults(self):
rdict = {}
self.mixin._extend_extra_router_dict(rdict, self.router)
self.assertEqual(self._get_default_api_values(), rdict)
def test_set_attrs_and_extend(self):
self.mixin.set_extra_attr_value(self.ctx, self.router, 'ha_vr_id', 99)... | 256 | 256 | 28,590 | 14 | 242 | mail2nsrajesh/neutron | neutron/tests/unit/extensions/test_l3.py | Python | L3NatTestCaseBase | L3NatTestCaseBase | 614 | 3,417 | 614 | 615 | 34addf2bddf234725395dd762a44b69a4f47bb36 | bigcode/the-stack | train |
871397a0451bb94779152171 | train | class | class L3NatDBIntTestCase(L3BaseForIntTests, L3NatTestCaseBase,
L3NatDBTestCaseMixin):
"""Unit tests for core plugin with L3 routing integrated."""
pass
| class L3NatDBIntTestCase(L3BaseForIntTests, L3NatTestCaseBase,
L3NatDBTestCaseMixin):
| """Unit tests for core plugin with L3 routing integrated."""
pass
| ctx, data)
# Verify router doesn't persist on failure
routers = plugin.get_routers(ctx)
self.assertEqual(0, len(routers))
class L3NatDBIntTestCase(L3BaseForIntTests, L3NatTestCaseBase,
L3NatDBTestCaseMixin):
| 64 | 64 | 47 | 31 | 33 | mail2nsrajesh/neutron | neutron/tests/unit/extensions/test_l3.py | Python | L3NatDBIntTestCase | L3NatDBIntTestCase | 3,940 | 3,944 | 3,940 | 3,942 | 5c1625d70892dad49a14d418900bd79eb804bfe8 | bigcode/the-stack | train |
f93201ef6940c745faf843f6 | train | class | class L3TestExtensionManager(object):
def get_resources(self):
# Add the resources to the global attribute map
# This is done here as the setup process won't
# initialize the main API router which extends
# the global attribute map
attributes.RESOURCE_ATTRIBUTE_MAP.update(
... | class L3TestExtensionManager(object):
| def get_resources(self):
# Add the resources to the global attribute map
# This is done here as the setup process won't
# initialize the main API router which extends
# the global attribute map
attributes.RESOURCE_ATTRIBUTE_MAP.update(
l3.RESOURCE_ATTRIBUTE_MAP)
... | .tests.unit.plugins.ml2 import base as ml2_base
from neutron.tests.unit import testlib_api
_uuid = uuidutils.generate_uuid
_get_path = test_base._get_path
DEVICE_OWNER_COMPUTE = lib_constants.DEVICE_OWNER_COMPUTE_PREFIX + 'fake'
class L3TestExtensionManager(object):
| 64 | 64 | 98 | 8 | 56 | mail2nsrajesh/neutron | neutron/tests/unit/extensions/test_l3.py | Python | L3TestExtensionManager | L3TestExtensionManager | 79 | 94 | 79 | 80 | c064e830bb0e2e663379c6d4302310b977929245 | bigcode/the-stack | train |
2c8f8b3209eb2287de328f22 | train | class | class TestNoL3NatPlugin(TestL3NatBasePlugin):
__native_pagination_support = True
__native_sorting_support = True
supported_extension_aliases = ["external-net"]
| class TestNoL3NatPlugin(TestL3NatBasePlugin):
| __native_pagination_support = True
__native_sorting_support = True
supported_extension_aliases = ["external-net"]
| supported_extension_aliases = ["external-net", "router",
"l3_agent_scheduler"]
router_scheduler = importutils.import_object(
cfg.CONF.router_scheduler_driver)
# This plugin class is for tests with plugin not supporting L3.
class TestNoL3NatPlugin(TestL3NatBasePlugin):
| 64 | 64 | 42 | 14 | 50 | mail2nsrajesh/neutron | neutron/tests/unit/extensions/test_l3.py | Python | TestNoL3NatPlugin | TestNoL3NatPlugin | 305 | 310 | 305 | 306 | 795db898be03f23ce56a6bbed475983da3bb79f3 | bigcode/the-stack | train |
ae907bec2e1de7d0edfdc946 | train | class | class L3NatDBTestCaseMixin(object):
"""L3_NAT_dbonly_mixin specific test cases."""
def setUp(self):
super(L3NatDBTestCaseMixin, self).setUp()
plugin = directory.get_plugin(plugin_constants.L3)
if not isinstance(plugin, l3_db.L3_NAT_dbonly_mixin):
self.skipTest("Plugin is not... | class L3NatDBTestCaseMixin(object):
| """L3_NAT_dbonly_mixin specific test cases."""
def setUp(self):
super(L3NatDBTestCaseMixin, self).setUp()
plugin = directory.get_plugin(plugin_constants.L3)
if not isinstance(plugin, l3_db.L3_NAT_dbonly_mixin):
self.skipTest("Plugin is not L3_NAT_dbonly_mixin")
def test... | ._make_floatingip(
self.fmt, flip['floatingip']['floating_network_id'],
port_id=port['port']['id'],
**self.kwargs)
self._assert_object_list_queries_constant(float_maker,
'floatingips')
class ... | 83 | 83 | 278 | 10 | 72 | mail2nsrajesh/neutron | neutron/tests/unit/extensions/test_l3.py | Python | L3NatDBTestCaseMixin | L3NatDBTestCaseMixin | 3,906 | 3,937 | 3,906 | 3,906 | 79824b54a20ccf40af96f7df04c58d5117edc834 | bigcode/the-stack | train |
ab7f3d450e91d563384b2b29 | train | class | class TestL3DbOperationBoundsTenant(TestL3DbOperationBounds):
admin = False
| class TestL3DbOperationBoundsTenant(TestL3DbOperationBounds):
| admin = False
| ip(
self.fmt, flip['floatingip']['floating_network_id'],
port_id=port['port']['id'],
**self.kwargs)
self._assert_object_list_queries_constant(float_maker,
'floatingips')
class TestL3DbOperation... | 64 | 64 | 20 | 15 | 49 | mail2nsrajesh/neutron | neutron/tests/unit/extensions/test_l3.py | Python | TestL3DbOperationBoundsTenant | TestL3DbOperationBoundsTenant | 3,902 | 3,903 | 3,902 | 3,902 | 436160466fcd7de3373cd063fbf0d4d9a6640c6b | bigcode/the-stack | train |
0f2772d510d46ad1093c0e93 | train | class | class L3NatDBIntAgentSchedulingTestCase(L3BaseForIntTests,
L3NatTestCaseMixin,
test_agent.
AgentDBTestMixIn):
"""Unit tests for core plugin with L3 routing and scheduling integrated."""
def ... | class L3NatDBIntAgentSchedulingTestCase(L3BaseForIntTests,
L3NatTestCaseMixin,
test_agent.
AgentDBTestMixIn):
| """Unit tests for core plugin with L3 routing and scheduling integrated."""
def setUp(self, plugin='neutron.tests.unit.extensions.test_l3.'
'TestL3NatIntAgentSchedulingPlugin',
ext_mgr=None, service_plugins=None):
self.mock_rescheduling = False
super(L3N... | , self).setUp(plugin=plugin, ext_mgr=ext_mgr,
service_plugins=service_plugins)
self.setup_notification_driver()
class L3BaseForSepTests(test_db_base_plugin_v2.NeutronDbPluginV2TestCase):
def setUp(self, plugin=None, ext_mgr=None):
# the plugin without... | 256 | 256 | 977 | 36 | 220 | mail2nsrajesh/neutron | neutron/tests/unit/extensions/test_l3.py | Python | L3NatDBIntAgentSchedulingTestCase | L3NatDBIntAgentSchedulingTestCase | 3,689 | 3,786 | 3,689 | 3,693 | b2c4859004f7b984ec6f5879b8a2e346cf62003d | bigcode/the-stack | train |
6dd58d1b6808ab65f066d1c5 | train | class | class L3NatDBSepTestCase(L3BaseForSepTests, L3NatTestCaseBase,
L3NatDBTestCaseMixin):
"""Unit tests for a separate L3 routing service plugin."""
def test_port_deletion_prevention_handles_missing_port(self):
pl = directory.get_plugin(plugin_constants.L3)
self.assertIsNo... | class L3NatDBSepTestCase(L3BaseForSepTests, L3NatTestCaseBase,
L3NatDBTestCaseMixin):
| """Unit tests for a separate L3 routing service plugin."""
def test_port_deletion_prevention_handles_missing_port(self):
pl = directory.get_plugin(plugin_constants.L3)
self.assertIsNone(
pl.prevent_l3_port_deletion(context.get_admin_context(), 'fakeid')
)
| , L3NatTestCaseBase,
L3NatDBTestCaseMixin):
"""Unit tests for core plugin with L3 routing integrated."""
pass
class L3NatDBSepTestCase(L3BaseForSepTests, L3NatTestCaseBase,
L3NatDBTestCaseMixin):
| 64 | 64 | 93 | 31 | 32 | mail2nsrajesh/neutron | neutron/tests/unit/extensions/test_l3.py | Python | L3NatDBSepTestCase | L3NatDBSepTestCase | 3,947 | 3,956 | 3,947 | 3,949 | b475a3e177d3affe6311f507fd3f11f47a5ecec9 | bigcode/the-stack | train |
a6636fb94e63b2b6d8da028d | train | class | class L3RpcCallbackTestCase(base.BaseTestCase):
def setUp(self):
super(L3RpcCallbackTestCase, self).setUp()
self.mock_plugin = mock.patch.object(
l3_rpc.L3RpcCallback,
'plugin', new_callable=mock.PropertyMock).start()
self.mock_l3plugin = mock.patch.object(
... | class L3RpcCallbackTestCase(base.BaseTestCase):
| def setUp(self):
super(L3RpcCallbackTestCase, self).setUp()
self.mock_plugin = mock.patch.object(
l3_rpc.L3RpcCallback,
'plugin', new_callable=mock.PropertyMock).start()
self.mock_l3plugin = mock.patch.object(
l3_rpc.L3RpcCallback,
'l3plugin', ... | networks since no scheduling decision needs
# to be made
self._add_external_gateway_to_router(
r['router']['id'],
s1['subnet']['network_id'])
def test_router_update_gateway_no_eligible_l3_agent(self):
with self.router(... | 159 | 159 | 530 | 12 | 147 | mail2nsrajesh/neutron | neutron/tests/unit/extensions/test_l3.py | Python | L3RpcCallbackTestCase | L3RpcCallbackTestCase | 3,789 | 3,834 | 3,789 | 3,790 | faee8cf85728403103fac5233a9f9ca6ddf20a50 | bigcode/the-stack | train |
cb661c9f62d15bc4b78657b9 | train | class | class TestL3NatIntPlugin(TestL3NatBasePlugin,
l3_db.L3_NAT_db_mixin, dns_db.DNSDbMixin):
__native_pagination_support = True
__native_sorting_support = True
supported_extension_aliases = ["external-net", "router", "dns-integration"]
| class TestL3NatIntPlugin(TestL3NatBasePlugin,
l3_db.L3_NAT_db_mixin, dns_db.DNSDbMixin):
| __native_pagination_support = True
__native_sorting_support = True
supported_extension_aliases = ["external-net", "router", "dns-integration"]
| return super(TestL3NatBasePlugin, self).delete_port(context, id)
# This plugin class is for tests with plugin that integrates L3.
class TestL3NatIntPlugin(TestL3NatBasePlugin,
l3_db.L3_NAT_db_mixin, dns_db.DNSDbMixin):
| 64 | 64 | 69 | 33 | 31 | mail2nsrajesh/neutron | neutron/tests/unit/extensions/test_l3.py | Python | TestL3NatIntPlugin | TestL3NatIntPlugin | 282 | 288 | 282 | 284 | a3419434458447c448b1334b31a0f45f0c76e251 | bigcode/the-stack | train |
eb41db3ad100896f05cb2039 | train | class | class TestL3NatServicePlugin(common_db_mixin.CommonDbMixin,
l3_dvr_db.L3_NAT_with_dvr_db_mixin,
l3_db.L3_NAT_db_mixin, dns_db.DNSDbMixin):
__native_pagination_support = True
__native_sorting_support = True
supported_extension_aliases = ["router", "... | class TestL3NatServicePlugin(common_db_mixin.CommonDbMixin,
l3_dvr_db.L3_NAT_with_dvr_db_mixin,
l3_db.L3_NAT_db_mixin, dns_db.DNSDbMixin):
| __native_pagination_support = True
__native_sorting_support = True
supported_extension_aliases = ["router", "dns-integration"]
@classmethod
def get_plugin_type(cls):
return plugin_constants.L3
def get_plugin_description(self):
return "L3 Routing Service Plugin for testing"
| tests with plugins that
# delegate away L3 routing functionality
class TestL3NatServicePlugin(common_db_mixin.CommonDbMixin,
l3_dvr_db.L3_NAT_with_dvr_db_mixin,
l3_db.L3_NAT_db_mixin, dns_db.DNSDbMixin):
| 64 | 64 | 119 | 51 | 12 | mail2nsrajesh/neutron | neutron/tests/unit/extensions/test_l3.py | Python | TestL3NatServicePlugin | TestL3NatServicePlugin | 315 | 329 | 315 | 318 | 2dae9141b5728addf5ae84cd0e6121802cc69508 | bigcode/the-stack | train |
7324cf0a6309d5d9157e883c | train | class | class ExtraAttributesMixinTestCase(testlib_api.SqlTestCase):
def setUp(self):
super(ExtraAttributesMixinTestCase, self).setUp()
self.mixin = l3_attrs_db.ExtraAttributesMixin()
directory.add_plugin(plugin_constants.L3, self.mixin)
self.ctx = context.get_admin_context()
self.r... | class ExtraAttributesMixinTestCase(testlib_api.SqlTestCase):
| def setUp(self):
super(ExtraAttributesMixinTestCase, self).setUp()
self.mixin = l3_attrs_db.ExtraAttributesMixin()
directory.add_plugin(plugin_constants.L3, self.mixin)
self.ctx = context.get_admin_context()
self.router = l3_models.Router()
with self.ctx.session.begin... | ._delete('floatingips',
floatingip['floatingip']['id'])
@contextlib.contextmanager
def floatingip_no_assoc(self, private_sub, fmt=None,
set_context=False, **kwargs):
with self.subnet(cidr='12.0.0.0/24') as public_sub:
with self.floati... | 126 | 126 | 420 | 13 | 112 | mail2nsrajesh/neutron | neutron/tests/unit/extensions/test_l3.py | Python | ExtraAttributesMixinTestCase | ExtraAttributesMixinTestCase | 570 | 611 | 570 | 571 | 5926e87b326e1fb126c32bf44f9fd222831a3356 | bigcode/the-stack | train |
41e0a89a73940e515b1a3d98 | train | class | class TestL3DbOperationBounds(test_db_base_plugin_v2.DbOperationBoundMixin,
L3NatTestCaseMixin,
ml2_base.ML2TestFramework):
def setUp(self):
super(TestL3DbOperationBounds, self).setUp()
ext_mgr = L3TestExtensionManager()
self.ext_ap... | class TestL3DbOperationBounds(test_db_base_plugin_v2.DbOperationBoundMixin,
L3NatTestCaseMixin,
ml2_base.ML2TestFramework):
| def setUp(self):
super(TestL3DbOperationBounds, self).setUp()
ext_mgr = L3TestExtensionManager()
self.ext_api = test_extensions.setup_extensions_middleware(ext_mgr)
self.kwargs = self.get_api_kwargs()
def test_router_list_queries_constant(self):
with self.subnet(**self.k... | tests for methods called by the L3 agent for the
case where separate service plugin implements L3 routing.
"""
def setUp(self):
super(L3AgentDbSepTestCase, self).setUp()
self.core_plugin = TestNoL3NatPlugin()
self.plugin = TestL3NatServicePlugin()
class TestL3DbOperationBounds(test... | 105 | 105 | 351 | 36 | 69 | mail2nsrajesh/neutron | neutron/tests/unit/extensions/test_l3.py | Python | TestL3DbOperationBounds | TestL3DbOperationBounds | 3,861 | 3,899 | 3,861 | 3,863 | b39aadf15c328082af5092b9b4e4145195ecdc5c | bigcode/the-stack | train |
e1e938c8a94b05b2d7dcf56b | train | class | class TestL3NatBasePlugin(db_base_plugin_v2.NeutronDbPluginV2,
external_net_db.External_net_db_mixin):
__native_pagination_support = True
__native_sorting_support = True
def create_network(self, context, network):
session = context.session
with session.begin(subtr... | class TestL3NatBasePlugin(db_base_plugin_v2.NeutronDbPluginV2,
external_net_db.External_net_db_mixin):
| __native_pagination_support = True
__native_sorting_support = True
def create_network(self, context, network):
session = context.session
with session.begin(subtransactions=True):
net = super(TestL3NatBasePlugin, self).create_network(context,
... | res = self.api.put(path)
self.assertEqual(exc.HTTPOk.code, res.status_int)
instance.add_router_interface.assert_called_with(mock.ANY, router_id)
# This base plugin class is for tests.
class TestL3NatBasePlugin(db_base_plugin_v2.NeutronDbPluginV2,
external_net_db.External_net... | 76 | 76 | 256 | 29 | 47 | mail2nsrajesh/neutron | neutron/tests/unit/extensions/test_l3.py | Python | TestL3NatBasePlugin | TestL3NatBasePlugin | 249 | 278 | 249 | 251 | 3546dbd28e315df46034949feeee386b10268fe0 | bigcode/the-stack | train |
a1e827589a91eb29f66b85a5 | train | class | class L3NatDBFloatingIpTestCaseWithDNS(L3BaseForSepTests, L3NatTestCaseMixin):
"""Unit tests for floating ip with external DNS integration"""
fmt = 'json'
DNS_NAME = 'test'
DNS_DOMAIN = 'test-domain.org.'
PUBLIC_CIDR = '11.0.0.0/24'
PRIVATE_CIDR = '10.0.0.0/24'
mock_client = mock.MagicMock(... | class L3NatDBFloatingIpTestCaseWithDNS(L3BaseForSepTests, L3NatTestCaseMixin):
| """Unit tests for floating ip with external DNS integration"""
fmt = 'json'
DNS_NAME = 'test'
DNS_DOMAIN = 'test-domain.org.'
PUBLIC_CIDR = '11.0.0.0/24'
PRIVATE_CIDR = '10.0.0.0/24'
mock_client = mock.MagicMock()
mock_admin_client = mock.MagicMock()
MOCK_PATH = ('neutron.services.e... | 3NatDBTestCaseMixin):
"""Unit tests for core plugin with L3 routing integrated."""
pass
class L3NatDBSepTestCase(L3BaseForSepTests, L3NatTestCaseBase,
L3NatDBTestCaseMixin):
"""Unit tests for a separate L3 routing service plugin."""
def test_port_deletion_prevention_handles... | 256 | 256 | 3,004 | 25 | 231 | mail2nsrajesh/neutron | neutron/tests/unit/extensions/test_l3.py | Python | L3NatDBFloatingIpTestCaseWithDNS | L3NatDBFloatingIpTestCaseWithDNS | 3,973 | 4,246 | 3,973 | 3,973 | 2d3fe257d56a825ccb7381a50e0b8810e5b0f74f | bigcode/the-stack | train |
6ce89c6ca32d2b3a1103eaf5 | train | class | class L3AgentDbIntTestCase(L3BaseForIntTests, L3AgentDbTestCaseBase):
"""Unit tests for methods called by the L3 agent for
the case where core plugin implements L3 routing.
"""
def setUp(self):
super(L3AgentDbIntTestCase, self).setUp()
self.core_plugin = TestL3NatIntPlugin()
se... | class L3AgentDbIntTestCase(L3BaseForIntTests, L3AgentDbTestCaseBase):
| """Unit tests for methods called by the L3 agent for
the case where core plugin implements L3 routing.
"""
def setUp(self):
super(L3AgentDbIntTestCase, self).setUp()
self.core_plugin = TestL3NatIntPlugin()
self.plugin = self.core_plugin
| agent binding for router foo_router_id.')
actual_message = mock_log.call_args[0][0] % mock_log.call_args[0][1]
self.assertEqual(expected_message, actual_message)
class L3AgentDbIntTestCase(L3BaseForIntTests, L3AgentDbTestCaseBase):
| 64 | 64 | 91 | 23 | 41 | mail2nsrajesh/neutron | neutron/tests/unit/extensions/test_l3.py | Python | L3AgentDbIntTestCase | L3AgentDbIntTestCase | 3,837 | 3,846 | 3,837 | 3,838 | a924cdcdf4156998c863f017a5dd33acdd7eeb06 | bigcode/the-stack | train |
30782192ad8ee8e97c12992d | train | class | class L3AgentDbSepTestCase(L3BaseForSepTests, L3AgentDbTestCaseBase):
"""Unit tests for methods called by the L3 agent for the
case where separate service plugin implements L3 routing.
"""
def setUp(self):
super(L3AgentDbSepTestCase, self).setUp()
self.core_plugin = TestNoL3NatPlugin()... | class L3AgentDbSepTestCase(L3BaseForSepTests, L3AgentDbTestCaseBase):
| """Unit tests for methods called by the L3 agent for the
case where separate service plugin implements L3 routing.
"""
def setUp(self):
super(L3AgentDbSepTestCase, self).setUp()
self.core_plugin = TestNoL3NatPlugin()
self.plugin = TestL3NatServicePlugin()
| def setUp(self):
super(L3AgentDbIntTestCase, self).setUp()
self.core_plugin = TestL3NatIntPlugin()
self.plugin = self.core_plugin
class L3AgentDbSepTestCase(L3BaseForSepTests, L3AgentDbTestCaseBase):
| 64 | 64 | 95 | 23 | 40 | mail2nsrajesh/neutron | neutron/tests/unit/extensions/test_l3.py | Python | L3AgentDbSepTestCase | L3AgentDbSepTestCase | 3,849 | 3,858 | 3,849 | 3,850 | 015f1170fe932ef344914a5d25cbf54f1496b9bf | bigcode/the-stack | train |
ddbbfbfdb68e945ad921c181 | train | class | class L3NatTestCaseMixin(object):
def _create_router(self, fmt, tenant_id, name=None,
admin_state_up=None, set_context=False,
arg_list=None, **kwargs):
tenant_id = tenant_id or _uuid()
data = {'router': {'tenant_id': tenant_id}}
if name:
... | class L3NatTestCaseMixin(object):
| def _create_router(self, fmt, tenant_id, name=None,
admin_state_up=None, set_context=False,
arg_list=None, **kwargs):
tenant_id = tenant_id or _uuid()
data = {'router': {'tenant_id': tenant_id}}
if name:
data['router']['name'] = name
... | _db.L3_NAT_db_mixin, dns_db.DNSDbMixin):
__native_pagination_support = True
__native_sorting_support = True
supported_extension_aliases = ["router", "dns-integration"]
@classmethod
def get_plugin_type(cls):
return plugin_constants.L3
def get_plugin_description(self):
return "... | 256 | 256 | 1,908 | 9 | 247 | mail2nsrajesh/neutron | neutron/tests/unit/extensions/test_l3.py | Python | L3NatTestCaseMixin | L3NatTestCaseMixin | 349 | 567 | 349 | 350 | d36c28a58fad30cd3f6977bf8404b5d6c3b2ee67 | bigcode/the-stack | train |
a22f3d0c5b1fade00af09fce | train | class | class L3TestExtensionManagerWithDNS(L3TestExtensionManager):
def get_resources(self):
# Add the resources to the global attribute map
# This is done here as the setup process won't
# initialize the main API router which extends
# the global attribute map
attributes.RESOURCE_... | class L3TestExtensionManagerWithDNS(L3TestExtensionManager):
| def get_resources(self):
# Add the resources to the global attribute map
# This is done here as the setup process won't
# initialize the main API router which extends
# the global attribute map
attributes.RESOURCE_ATTRIBUTE_MAP.update(
l3.RESOURCE_ATTRIBUTE_MAP)
... | ."""
def test_port_deletion_prevention_handles_missing_port(self):
pl = directory.get_plugin(plugin_constants.L3)
self.assertIsNone(
pl.prevent_l3_port_deletion(context.get_admin_context(), 'fakeid')
)
class L3TestExtensionManagerWithDNS(L3TestExtensionManager):
| 64 | 64 | 115 | 14 | 50 | mail2nsrajesh/neutron | neutron/tests/unit/extensions/test_l3.py | Python | L3TestExtensionManagerWithDNS | L3TestExtensionManagerWithDNS | 3,959 | 3,970 | 3,959 | 3,960 | 6c3da14f55ee1307ae2c3766e550b4a42a9ed1d9 | bigcode/the-stack | train |
ee50e3fbd3c103177321eedf | train | class | class L3BaseForSepTests(test_db_base_plugin_v2.NeutronDbPluginV2TestCase):
def setUp(self, plugin=None, ext_mgr=None):
# the plugin without L3 support
if not plugin:
plugin = 'neutron.tests.unit.extensions.test_l3.TestNoL3NatPlugin'
# the L3 service plugin
l3_plugin = ('... | class L3BaseForSepTests(test_db_base_plugin_v2.NeutronDbPluginV2TestCase):
| def setUp(self, plugin=None, ext_mgr=None):
# the plugin without L3 support
if not plugin:
plugin = 'neutron.tests.unit.extensions.test_l3.TestNoL3NatPlugin'
# the L3 service plugin
l3_plugin = ('neutron.tests.unit.extensions.test_l3.'
'TestL3NatServi... | a: False).start()
super(L3BaseForIntTests, self).setUp(plugin=plugin, ext_mgr=ext_mgr,
service_plugins=service_plugins)
self.setup_notification_driver()
class L3BaseForSepTests(test_db_base_plugin_v2.NeutronDbPluginV2TestCase):
| 64 | 64 | 192 | 22 | 42 | mail2nsrajesh/neutron | neutron/tests/unit/extensions/test_l3.py | Python | L3BaseForSepTests | L3BaseForSepTests | 3,668 | 3,686 | 3,668 | 3,669 | 650ffa02777666ecc9b60c44e1cc8ea18f3f8de1 | bigcode/the-stack | train |
8b90ad139b068e9dea430117 | train | class | class L3AgentDbTestCaseBase(L3NatTestCaseMixin):
"""Unit tests for methods called by the L3 agent."""
def test_l3_agent_routers_query_interfaces(self):
with self.router() as r:
with self.port() as p:
self._router_interface_action('add',
... | class L3AgentDbTestCaseBase(L3NatTestCaseMixin):
| """Unit tests for methods called by the L3 agent."""
def test_l3_agent_routers_query_interfaces(self):
with self.router() as r:
with self.port() as p:
self._router_interface_action('add',
r['router']['id'],
... | _delete_if_fixed_in_interim(self):
# here we ensure that the janitor doesn't delete the port on the second
# call if the conditions have been fixed
plugin = directory.get_plugin(plugin_constants.L3)
with self.network() as n:
port_res = self._create_port(
self.... | 255 | 256 | 2,257 | 15 | 240 | mail2nsrajesh/neutron | neutron/tests/unit/extensions/test_l3.py | Python | L3AgentDbTestCaseBase | L3AgentDbTestCaseBase | 3,420 | 3,644 | 3,420 | 3,421 | 3c52e0cc7db295c0f0506d8f06a824ac388bef49 | bigcode/the-stack | train |
515a80ff5699dfd11a8ca6a6 | train | class | class TestL3NatIntAgentSchedulingPlugin(TestL3NatIntPlugin,
l3_agentschedulers_db.
L3AgentSchedulerDbMixin,
l3_hamode_db.L3_HA_NAT_db_mixin):
supported_extension_aliases = ["external-net", "route... | class TestL3NatIntAgentSchedulingPlugin(TestL3NatIntPlugin,
l3_agentschedulers_db.
L3AgentSchedulerDbMixin,
l3_hamode_db.L3_HA_NAT_db_mixin):
| supported_extension_aliases = ["external-net", "router",
"l3_agent_scheduler"]
router_scheduler = importutils.import_object(
cfg.CONF.router_scheduler_driver)
| for tests with plugin that integrates L3 and L3 agent
# scheduling.
class TestL3NatIntAgentSchedulingPlugin(TestL3NatIntPlugin,
l3_agentschedulers_db.
L3AgentSchedulerDbMixin,
l3_hamode_db.L3_HA_NAT_... | 64 | 64 | 85 | 48 | 16 | mail2nsrajesh/neutron | neutron/tests/unit/extensions/test_l3.py | Python | TestL3NatIntAgentSchedulingPlugin | TestL3NatIntAgentSchedulingPlugin | 293 | 301 | 293 | 297 | 32e4d6208b37044182813b2316c80641c0b046b4 | bigcode/the-stack | train |
1b0463e7eb7bb28675a948ad | train | class | class ProjectAdd(UserEndPoint):
name = "api-v1-project-add"
description = _("New application")
@extend_schema_with_envcheck(
request=_ProjectsAddBodyArgsSerializer,
tags=[_('Project')],
summary=_('Projects Add'),
description=_(
"""Create a new project according t... | class ProjectAdd(UserEndPoint):
| name = "api-v1-project-add"
description = _("New application")
@extend_schema_with_envcheck(
request=_ProjectsAddBodyArgsSerializer,
tags=[_('Project')],
summary=_('Projects Add'),
description=_(
"""Create a new project according to the given conditions;
... | iast.utils import extend_schema_with_envcheck, get_response_serializer
from rest_framework import serializers
logger = logging.getLogger("django")
class _ProjectsAddBodyArgsSerializer(serializers.Serializer):
name = serializers.CharField(help_text=_('The name of project'))
agent_ids = serializers.CharField(... | 246 | 246 | 822 | 7 | 239 | zu1kbackup/DongTai-webapi | iast/views/project_add.py | Python | ProjectAdd | ProjectAdd | 48 | 144 | 48 | 48 | d347f889dec6e063ebe1ffe69304e6a3eec9a54e | bigcode/the-stack | train |
9b4f75301318a3e7657f651d | train | class | class _ProjectsAddBodyArgsSerializer(serializers.Serializer):
name = serializers.CharField(help_text=_('The name of project'))
agent_ids = serializers.CharField(help_text=_(
'The id corresponding to the agent, use, for segmentation.'))
mode = serializers.ChoiceField(['插桩模式'],
... | class _ProjectsAddBodyArgsSerializer(serializers.Serializer):
| name = serializers.CharField(help_text=_('The name of project'))
agent_ids = serializers.CharField(help_text=_(
'The id corresponding to the agent, use, for segmentation.'))
mode = serializers.ChoiceField(['插桩模式'],
help_text=_('The mode of project'))
scan_id = ... |
from iast.base.project_version import version_modify, ProjectsVersionDataSerializer
from django.utils.translation import gettext_lazy as _
from iast.utils import extend_schema_with_envcheck, get_response_serializer
from rest_framework import serializers
logger = logging.getLogger("django")
class _ProjectsAddBodyArgsS... | 64 | 64 | 149 | 10 | 54 | zu1kbackup/DongTai-webapi | iast/views/project_add.py | Python | _ProjectsAddBodyArgsSerializer | _ProjectsAddBodyArgsSerializer | 25 | 37 | 25 | 25 | 2d07c6ca3201fbf98bc73fe342dd5d5114ab7971 | bigcode/the-stack | train |
87bb32fd9e8c6d799bc45eb0 | train | function | @app.route('/')
def index():
return render_template('index.html')
| @app.route('/')
def index():
| return render_template('index.html')
| .abspath('static/')
@app.errorhandler(403)
def forbbiden(e):
return render_template('error.html', error=str(e)), 403
@app.errorhandler(500)
def internal_error(e):
return render_template('error.html', error=str(e)), 500
@app.route('/')
def index():
| 64 | 64 | 14 | 6 | 57 | leewalter/xss-challenge | vulnapp/app.py | Python | index | index | 18 | 20 | 18 | 19 | daee9230b51e47d50a8935306eb965b51672a3a3 | bigcode/the-stack | train |
13e06ef63a4e34beee8cb5c2 | train | function | @app.errorhandler(500)
def internal_error(e):
return render_template('error.html', error=str(e)), 500
| @app.errorhandler(500)
def internal_error(e):
| return render_template('error.html', error=str(e)), 500
| environ
DEADLINE = 6
app = Flask(__name__)
app._static_folder = path.abspath('static/')
@app.errorhandler(403)
def forbbiden(e):
return render_template('error.html', error=str(e)), 403
@app.errorhandler(500)
def internal_error(e):
| 64 | 64 | 26 | 11 | 52 | leewalter/xss-challenge | vulnapp/app.py | Python | internal_error | internal_error | 14 | 16 | 14 | 15 | 48e468c2ad1f9383517b90c1a9ae14dc629b625d | bigcode/the-stack | train |
40257d79467ad7e1ddbac9e7 | train | function | @app.errorhandler(403)
def forbbiden(e):
return render_template('error.html', error=str(e)), 403
| @app.errorhandler(403)
def forbbiden(e):
| return render_template('error.html', error=str(e)), 403
| from flask import Flask, abort, render_template, redirect, request, url_for
import requests
from os import path, environ
DEADLINE = 6
app = Flask(__name__)
app._static_folder = path.abspath('static/')
@app.errorhandler(403)
def forbbiden(e):
| 62 | 64 | 27 | 12 | 50 | leewalter/xss-challenge | vulnapp/app.py | Python | forbbiden | forbbiden | 10 | 12 | 10 | 11 | 61e0afbf423829032a72f0018bc780a455ab7166 | bigcode/the-stack | train |
830cbba59717d785a15a0d68 | train | class | class OffSiteBackupForList:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list ... | class OffSiteBackupForList:
| """
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
... | # coding: utf-8
import pprint
import re
import six
class OffSiteBackupForList:
| 23 | 256 | 2,267 | 7 | 15 | wuchen-huawei/huaweicloud-sdk-python-v3 | huaweicloud-sdk-rds/huaweicloudsdkrds/v3/model/off_site_backup_for_list.py | Python | OffSiteBackupForList | OffSiteBackupForList | 12 | 342 | 12 | 14 | de5cbcc633c79c2e1e27372fafefef2c7fdff9bb | bigcode/the-stack | train |
ab79387f369c81db7d2cd5b4 | train | class | class CustomCacheKeyValidationTests(unittest.TestCase):
"""
Tests for the ability to mixin a custom ``validate_key`` method to
a custom cache backend that otherwise inherits from a builtin
backend, and override the default key validation. Refs #6447.
"""
def test_custom_key_validation(self):
... | class CustomCacheKeyValidationTests(unittest.TestCase):
| """
Tests for the ability to mixin a custom ``validate_key`` method to
a custom cache backend that otherwise inherits from a builtin
backend, and override the default key validation. Refs #6447.
"""
def test_custom_key_validation(self):
cache = get_cache('regressiontests.cache.liberal_b... | ):
self.perform_cull_test(50, 29)
def test_old_initialization(self):
self.cache = get_cache('file://%s?max_entries=30' % self.dirname)
self.perform_cull_test(50, 29)
class CustomCacheKeyValidationTests(unittest.TestCase):
| 64 | 64 | 135 | 10 | 54 | wnyc/django | tests/regressiontests/cache/tests.py | Python | CustomCacheKeyValidationTests | CustomCacheKeyValidationTests | 1,022 | 1,036 | 1,022 | 1,022 | 4190be4910857b341714d2217fa4b1c039b5a341 | bigcode/the-stack | train |
0b9bae6563de8a4bca85f030 | train | class | @override_settings(
CACHE_MIDDLEWARE_KEY_PREFIX='settingsprefix',
CACHE_MIDDLEWARE_SECONDS=1,
CACHES={
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
},
},
USE_I18N=False,
)
class CacheUtils(TestCase):
"""TestC... | @override_settings(
CACHE_MIDDLEWARE_KEY_PREFIX='settingsprefix',
CACHE_MIDDLEWARE_SECONDS=1,
CACHES={
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
},
},
USE_I18N=False,
)
class CacheUtils(TestCase):
| """TestCase for django.utils.cache functions."""
def setUp(self):
self.path = '/cache/test/'
self.cache = get_cache('default')
def tearDown(self):
self.cache.clear()
def _get_request(self, path, method='GET'):
request = HttpRequest()
request.META = {
... | (cache.get(key), val)
class GetCacheTests(unittest.TestCase):
def test_simple(self):
cache = get_cache('locmem://')
from django.core.cache.backends.locmem import LocMemCache
self.assertTrue(isinstance(cache, LocMemCache))
from django.core.cache import cache
self.assertTru... | 256 | 256 | 1,220 | 69 | 187 | wnyc/django | tests/regressiontests/cache/tests.py | Python | CacheUtils | CacheUtils | 1,063 | 1,167 | 1,063 | 1,073 | 77ebd17a2669dcff7462c0447fde498bb8df26e4 | bigcode/the-stack | train |
bceb061f1fe5c82db3ece463 | train | class | @override_settings(USE_TZ=True)
class DBCacheWithTimeZoneTests(DBCacheTests):
pass
| @override_settings(USE_TZ=True)
class DBCacheWithTimeZoneTests(DBCacheTests):
| pass
| ,
"Cache table 'test cache table' could not be created"):
management.call_command(
'createcachetable',
self._table_name,
verbosity=0,
interactive=False
)
@override_settings(USE_TZ=True)
class DBCacheWithTimeZoneTests(... | 64 | 64 | 24 | 21 | 43 | wnyc/django | tests/regressiontests/cache/tests.py | Python | DBCacheWithTimeZoneTests | DBCacheWithTimeZoneTests | 833 | 835 | 833 | 834 | c2793611f27c11ae9a3cb691986228921ae78076 | bigcode/the-stack | train |
a1d71be13191899005b1799f | train | class | @override_settings(
CACHE_MIDDLEWARE_SECONDS=60,
CACHE_MIDDLEWARE_KEY_PREFIX='test',
CACHES={
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
},
},
)
class CacheHEADTest(TestCase):
def setUp(self):
self.path = ... | @override_settings(
CACHE_MIDDLEWARE_SECONDS=60,
CACHE_MIDDLEWARE_KEY_PREFIX='test',
CACHES={
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
},
},
)
class CacheHEADTest(TestCase):
| def setUp(self):
self.path = '/cache/test/'
self.cache = get_cache('default')
def tearDown(self):
self.cache.clear()
def _get_request(self, method):
request = HttpRequest()
request.META = {
'SERVER_NAME': 'testserver',
'SERVER_PORT': 80,
... | )
@override_settings(
CACHES={
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'KEY_PREFIX': 'cacheprefix',
},
},
)
class PrefixedCacheUtils(CacheUtils):
pass
@override_settings(
CACHE_MIDDLEWARE_SECONDS=60,
... | 119 | 119 | 397 | 62 | 56 | wnyc/django | tests/regressiontests/cache/tests.py | Python | CacheHEADTest | CacheHEADTest | 1,182 | 1,240 | 1,182 | 1,192 | 6f34367e806ae4abcb0aecddf07f7e4610bc428e | bigcode/the-stack | train |
2af6c37b75fdbc073f0ca32b | train | class | class DBCacheRouter(object):
"""A router that puts the cache table on the 'other' database."""
def db_for_read(self, model, **hints):
if model._meta.app_label == 'django_cache':
return 'other'
def db_for_write(self, model, **hints):
if model._meta.app_label == 'django_cache':
... | class DBCacheRouter(object):
| """A router that puts the cache table on the 'other' database."""
def db_for_read(self, model, **hints):
if model._meta.app_label == 'django_cache':
return 'other'
def db_for_write(self, model, **hints):
if model._meta.app_label == 'django_cache':
return 'other'
... | could not be created"):
management.call_command(
'createcachetable',
self._table_name,
verbosity=0,
interactive=False
)
@override_settings(USE_TZ=True)
class DBCacheWithTimeZoneTests(DBCacheTests):
pass
class DBCacheRouter(obj... | 64 | 64 | 113 | 7 | 56 | wnyc/django | tests/regressiontests/cache/tests.py | Python | DBCacheRouter | DBCacheRouter | 838 | 851 | 838 | 838 | 6e1a1b857512c72bdcaf96cab24e17295c143f00 | bigcode/the-stack | train |
4ce4dd9ef5a5d4bcc8c0e18a | train | function | def f():
return 42
| def f():
| return 42
| .cache import (patch_vary_headers, get_cache_key,
learn_cache_key, patch_cache_control, patch_response_headers)
from django.utils.encoding import force_text
from django.views.decorators.cache import cache_page
from .models import Poll, expensive_calculation
# functions/classes for complex data type tests
def f():... | 64 | 64 | 8 | 3 | 60 | wnyc/django | tests/regressiontests/cache/tests.py | Python | f | f | 38 | 39 | 38 | 38 | 1622a4e9915aa374175e24f3d853e8c1f1178b57 | bigcode/the-stack | train |
8a1dfbbdfb85d5bae89682ae | train | function | def custom_key_func(key, key_prefix, version):
"A customized cache key function"
return 'CUSTOM-' + '-'.join([key_prefix, str(version), key])
| def custom_key_func(key, key_prefix, version):
| "A customized cache key function"
return 'CUSTOM-' + '-'.join([key_prefix, str(version), key])
| _data)
get_cache_data = fetch_middleware.process_request(request)
self.assertNotEqual(get_cache_data, None)
self.assertEqual(get_cache_data.content, content.encode('utf-8'))
self.assertEqual(get_cache_data.cookies, response.cookies)
def custom_key_func(key, key_prefix, version):
| 64 | 64 | 37 | 11 | 53 | wnyc/django | tests/regressiontests/cache/tests.py | Python | custom_key_func | custom_key_func | 787 | 789 | 787 | 787 | 8c629fcd91fa55a3dc7094b2279274fc70e918bf | bigcode/the-stack | train |
fb6dd91a90041ad0fd75aec5 | train | class | class C:
def m(n):
return 24
| class C:
| def m(n):
return 24
| get_cache_key,
learn_cache_key, patch_cache_control, patch_response_headers)
from django.utils.encoding import force_text
from django.views.decorators.cache import cache_page
from .models import Poll, expensive_calculation
# functions/classes for complex data type tests
def f():
return 42
class C:
| 64 | 64 | 13 | 3 | 60 | wnyc/django | tests/regressiontests/cache/tests.py | Python | C | C | 41 | 43 | 41 | 41 | 09fea5f8880a037087b1ae293775a13aa39ccf51 | bigcode/the-stack | train |
de2180415adc6deca5f9ed76 | train | class | @unittest.skipUnless(
any(cache['BACKEND'].startswith('django.core.cache.backends.memcached.')
for cache in settings.CACHES.values()),
"memcached not available")
class MemcachedCacheTests(unittest.TestCase, BaseCacheTests):
def setUp(self):
for cache_key, cache in settings.CACHES.items():
... | @unittest.skipUnless(
any(cache['BACKEND'].startswith('django.core.cache.backends.memcached.')
for cache in settings.CACHES.values()),
"memcached not available")
class MemcachedCacheTests(unittest.TestCase, BaseCacheTests):
| def setUp(self):
for cache_key, cache in settings.CACHES.items():
if cache['BACKEND'].startswith('django.core.cache.backends.memcached.'):
break
random_prefix = ''.join(random.choice(string.ascii_letters) for x in range(10))
self.cache = get_cache(cache_key)
... | self.cache._expire_info[_key])
# memcached backend isn't guaranteed to be available.
# To check the memcached backend, the test settings file will
# need to contain at least one cache backend setting that points at
# your memcache server.
@unittest.skipUnless(
any(cache['BACKEND'].startswith('django.core.cache.ba... | 104 | 104 | 349 | 52 | 52 | wnyc/django | tests/regressiontests/cache/tests.py | Python | MemcachedCacheTests | MemcachedCacheTests | 938 | 971 | 938 | 943 | 59e1384b6e8878a0d84cec8db290395faee2f0ef | bigcode/the-stack | train |
23681c634f983ed46a450f7c | train | class | @override_settings(
CACHE_MIDDLEWARE_KEY_PREFIX='settingsprefix',
CACHES={
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
},
},
LANGUAGES=(
('en', 'English'),
('es', 'Spanish'),
),
)
class C... | @override_settings(
CACHE_MIDDLEWARE_KEY_PREFIX='settingsprefix',
CACHES={
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
},
},
LANGUAGES=(
('en', 'English'),
('es', 'Spanish'),
),
)
class C... | def setUp(self):
self.path = '/cache/test/'
self.cache = get_cache('default')
def tearDown(self):
self.cache.clear()
def _get_request(self, method='GET'):
request = HttpRequest()
request.META = {
'SERVER_NAME': 'testserver',
'SERVER_PORT': 80... | _response(request, response)
def test_head_caches_correctly(self):
test_content = 'test content'
request = self._get_request_cache('HEAD')
self._set_cache(request, test_content)
request = self._get_request('HEAD')
get_cache_data = FetchFromCacheMiddleware().process_request... | 256 | 256 | 1,600 | 78 | 178 | wnyc/django | tests/regressiontests/cache/tests.py | Python | CacheI18nTest | CacheI18nTest | 1,243 | 1,417 | 1,243 | 1,256 | 39f5428cb93fe51feb15cf876924b76022b9cd21 | bigcode/the-stack | train |
762c5d253727b2fce429d807 | train | class | class FileBasedCacheTests(unittest.TestCase, BaseCacheTests):
"""
Specific test cases for the file-based cache.
"""
backend_name = 'django.core.cache.backends.filebased.FileBasedCache'
def setUp(self):
self.dirname = tempfile.mkdtemp()
self.cache = get_cache(self.backend_name, LOCAT... | class FileBasedCacheTests(unittest.TestCase, BaseCacheTests):
| """
Specific test cases for the file-based cache.
"""
backend_name = 'django.core.cache.backends.filebased.FileBasedCache'
def setUp(self):
self.dirname = tempfile.mkdtemp()
self.cache = get_cache(self.backend_name, LOCATION=self.dirname, OPTIONS={'MAX_ENTRIES': 30})
self.pr... | introduce a duplicate key validation
step (for speed reasons), we just let the memcached API
library raise its own exception on bad keys. Refs #6447.
In order to be memcached-API-library agnostic, we only assert
that a generic exception of some kind is raised.
"""
# me... | 143 | 143 | 479 | 13 | 130 | wnyc/django | tests/regressiontests/cache/tests.py | Python | FileBasedCacheTests | FileBasedCacheTests | 974 | 1,019 | 974 | 974 | bb27a40552a274d23e3b67e8a71f1f2a6e288861 | bigcode/the-stack | train |
abd76b00fecdf5f0332bec0b | train | function | def hello_world_view(request, value):
return HttpResponse('Hello World %s' % value)
| def hello_world_view(request, value):
| return HttpResponse('Hello World %s' % value)
| ACHES={
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'KEY_PREFIX': 'cacheprefix'
},
},
)
class PrefixedCacheI18nTest(CacheI18nTest):
pass
def hello_world_view(request, value):
| 64 | 64 | 21 | 8 | 55 | wnyc/django | tests/regressiontests/cache/tests.py | Python | hello_world_view | hello_world_view | 1,432 | 1,433 | 1,432 | 1,432 | b61183e3162005a950624a59c7e8dd48e6116964 | bigcode/the-stack | train |
5faf241a367b23ab9f473365 | train | class | class TestEtagWithAdmin(TestCase):
# See https://code.djangoproject.com/ticket/16003
urls = "regressiontests.admin_views.urls"
def test_admin(self):
with self.settings(USE_ETAGS=False):
response = self.client.get('/test_admin/admin/')
self.assertEqual(response.status_code, 2... | class TestEtagWithAdmin(TestCase):
# See https://code.djangoproject.com/ticket/16003
| urls = "regressiontests.admin_views.urls"
def test_admin(self):
with self.settings(USE_ETAGS=False):
response = self.client.get('/test_admin/admin/')
self.assertEqual(response.status_code, 200)
self.assertFalse(response.has_header('ETag'))
with self.settings... | .has_header('ETag'))
patch_response_headers(response)
self.assertFalse(response.has_header('ETag'))
response = response.render()
self.assertTrue(response.has_header('ETag'))
class TestEtagWithAdmin(TestCase):
# See https://code.djangoproject.com/ticket/16003
| 63 | 64 | 126 | 23 | 40 | wnyc/django | tests/regressiontests/cache/tests.py | Python | TestEtagWithAdmin | TestEtagWithAdmin | 1,775 | 1,788 | 1,775 | 1,776 | ec6cb99dcdc08294d83aae11c15a8ec8bf6499f7 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.