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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
57b3b3ac737ffe5f36b3104e | train | function | @pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_while_with_param_basic_grad_three():
class MyWhileNet(nn.Cell):
def __init__(self):
super().__init__()
self.max = P.ReduceMax()
self.para... | @pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_while_with_param_basic_grad_three():
| class MyWhileNet(nn.Cell):
def __init__(self):
super().__init__()
self.max = P.ReduceMax()
self.param = Parameter(Tensor(np.arange(2 * 2 * 2).reshape((2, 2, 2)), ms.float32), name="weight")
self.weight = Parameter(Tensor(np.arange(2 * 2 * 2).reshape((2, 2, 2))... | net = GradNet(while_net)
graph_output = net(idx, end, x)
expect1 = np.array([[[4, 4], [4, 4]],
[[4, 4], [4, 4]]]).astype(np.float32)
expect2 = np.array([[[3, 3], [3, 3]],
[[3, 3], [3, 3]]]).astype(np.float32)
assert np.allclose(graph_output[0].asnumpy... | 190 | 190 | 636 | 38 | 152 | PowerOlive/mindspore | tests/st/control/test_cont_grad.py | Python | test_while_with_param_basic_grad_three | test_while_with_param_basic_grad_three | 688 | 735 | 688 | 692 | 04f77c778b7fd9238982f0bafb974f29baa5492f | bigcode/the-stack | train |
cbc279c0331b5c3c3e177edd | train | function | @pytest.mark.level1
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_ascend_training
@pytest.mark.env_onecard
def test_if_by_if_forward_const_branch_inner():
class MyIfByIfNet(nn.Cell):
def __init__(self):
super().__init__()
self.add = P.Add()
self.sub ... | @pytest.mark.level1
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_ascend_training
@pytest.mark.env_onecard
def test_if_by_if_forward_const_branch_inner():
| class MyIfByIfNet(nn.Cell):
def __init__(self):
super().__init__()
self.add = P.Add()
self.sub = P.Sub()
self.mul = P.Mul()
self.div = P.RealDiv()
def construct(self, a, b, x):
add = P.Add()
sub = P.Sub()
... | .GRAPH_MODE)
if_net = MyIfByIfNet()
net = if_net
graph_output = net(idx, end, x)
expect = 18.0
assert np.allclose(graph_output.asnumpy(), expect, 0.0001, 0.0001)
@pytest.mark.level1
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_ascend_training
@pytest.mark.env_onecard
def test... | 103 | 103 | 345 | 40 | 63 | PowerOlive/mindspore | tests/st/control/test_cont_grad.py | Python | test_if_by_if_forward_const_branch_inner | test_if_by_if_forward_const_branch_inner | 1,368 | 1,412 | 1,368 | 1,372 | 7310ba86edcc29bc58a49beff0a6fd8f98dcfb5e | bigcode/the-stack | train |
a3df39c21838f5a3cd692d87 | train | function | @pytest.mark.level1
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_ascend_training
@pytest.mark.env_onecard
def test_for_with_if_by_if_forward():
class MyIfByIfNet(nn.Cell):
def __init__(self):
super().__init__()
self.add = P.Add()
self.sub = P.Sub()
... | @pytest.mark.level1
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_ascend_training
@pytest.mark.env_onecard
def test_for_with_if_by_if_forward():
| class MyIfByIfNet(nn.Cell):
def __init__(self):
super().__init__()
self.add = P.Add()
self.sub = P.Sub()
def construct(self, a, b, x):
for _ in range(0, 4):
if a < b:
a = self.add(a, b)
else:
... | (idx, end, x)
expect = 4.444444
assert np.allclose(graph_output.asnumpy(), expect, 0.0001, 0.0001)
@pytest.mark.level1
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_ascend_training
@pytest.mark.env_onecard
def test_for_with_if_by_if_forward():
| 78 | 78 | 263 | 39 | 39 | PowerOlive/mindspore | tests/st/control/test_cont_grad.py | Python | test_for_with_if_by_if_forward | test_for_with_if_by_if_forward | 1,298 | 1,329 | 1,298 | 1,302 | 2c9c2650b33a0691c38fe27253b20d386377229d | bigcode/the-stack | train |
8c806a4bcf460ad317f41aed | train | function | @pytest.mark.level1
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_while_opt_endless():
"""endless during optimization case"""
class MyWhileNet(nn.Cell):
def __init__(self):
super().__init__()
self.max = P.Reduc... | @pytest.mark.level1
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_while_opt_endless():
| """endless during optimization case"""
class MyWhileNet(nn.Cell):
def __init__(self):
super().__init__()
self.max = P.ReduceMax()
self.param = Parameter(Tensor(np.arange(2 * 2 * 2).reshape((2, 2, 2)), ms.float32), name="weight")
self.zero = Tensor(np.zero... | 2, 2).astype(np.float32), dtype=ms.float32)
# graph mode
context.set_context(mode=context.GRAPH_MODE)
while_net = MyWhileNet()
net = while_net
graph_output = net(idx, end, x)
expect = np.array([[[0, 4], [8, 12]],
[[16, 20], [24, 28]]]).astype(np.float32)
assert np.all... | 153 | 153 | 511 | 36 | 117 | PowerOlive/mindspore | tests/st/control/test_cont_grad.py | Python | test_while_opt_endless | test_while_opt_endless | 286 | 334 | 286 | 290 | 20a06dcb228cf3e158e16535db207d6b19162168 | bigcode/the-stack | train |
0ade08204815496c1cd71d60 | train | function | @pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_while_with_const_param_grad():
class MyWhileNet(nn.Cell):
def __init__(self):
super().__init__()
self.mul = P.Mul()
self.add = P.Add()
... | @pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_while_with_const_param_grad():
| class MyWhileNet(nn.Cell):
def __init__(self):
super().__init__()
self.mul = P.Mul()
self.add = P.Add()
def construct(self, x, y):
while x < y:
z = self.mul(x, x)
x = self.add(z, 1)
return x
class GradN... | dtype=ms.float32)
# graph mode
context.set_context(mode=context.GRAPH_MODE)
while_net = MyWhileNet()
net = GradNet(while_net)
graph_output = net(idx, end, x)
assert graph_output == 0
@pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.m... | 95 | 95 | 317 | 37 | 57 | PowerOlive/mindspore | tests/st/control/test_cont_grad.py | Python | test_while_with_const_param_grad | test_while_with_const_param_grad | 66 | 100 | 66 | 70 | d7021559c403a625623880eb3b5362ba0f749681 | bigcode/the-stack | train |
22553c53b1f575814dfe6a88 | train | function | @pytest.mark.level1
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_ascend_training
@pytest.mark.env_onecard
def test_if_by_if_forward_use_global_op():
class MyIfByIfNet(nn.Cell):
def __init__(self):
super().__init__()
self.add = P.Add()
self.sub = P.S... | @pytest.mark.level1
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_ascend_training
@pytest.mark.env_onecard
def test_if_by_if_forward_use_global_op():
| class MyIfByIfNet(nn.Cell):
def __init__(self):
super().__init__()
self.add = P.Add()
self.sub = P.Sub()
self.mul = P.Mul()
self.div = P.RealDiv()
def construct(self, a, b, x):
add = P.Add()
sub = P.Sub()
... | APH_MODE)
if_net = MyIfByIfNet()
net = if_net
graph_output = net(idx, end, x)
expect = 4.444444
assert np.allclose(graph_output.asnumpy(), expect, 0.0001, 0.0001)
@pytest.mark.level1
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_ascend_training
@pytest.mark.env_onecard
def test... | 103 | 103 | 344 | 40 | 63 | PowerOlive/mindspore | tests/st/control/test_cont_grad.py | Python | test_if_by_if_forward_use_global_op | test_if_by_if_forward_use_global_op | 1,251 | 1,295 | 1,251 | 1,255 | b2fb3defe2dad7ac3f5335323dda0560c4d185b4 | bigcode/the-stack | train |
0097f16dd812ddcef0602d0b | train | function | @pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_for_while_with_param_grad_basic():
class MyWhileNet(nn.Cell):
def __init__(self):
super().__init__()
self.max = P.ReduceMax()
self.param ... | @pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_for_while_with_param_grad_basic():
| class MyWhileNet(nn.Cell):
def __init__(self):
super().__init__()
self.max = P.ReduceMax()
self.param = Parameter(Tensor(np.arange(2 * 2 * 2).reshape((2, 2, 2)), ms.float32), name="weight")
self.zero = Tensor(np.zeros(([2, 2, 2])), ms.float32)
self... | APH_MODE)
while_net = MyWhileNet()
net = GradNet(while_net)
graph_output = net(idx, end, x)
expect = np.array([[[8, 8], [8, 8]],
[[8, 8], [8, 8]]]).astype(np.float32)
assert np.allclose(graph_output[0].asnumpy(), expect, 0.0001, 0.0001)
@pytest.mark.level0
@pytest.mark.platfo... | 133 | 133 | 446 | 38 | 95 | PowerOlive/mindspore | tests/st/control/test_cont_grad.py | Python | test_for_while_with_param_grad_basic | test_for_while_with_param_grad_basic | 467 | 509 | 467 | 471 | 4c538a869d080ea629991e81fc3025c1cc64dd22 | bigcode/the-stack | train |
edd814a87e5f1abce39f65a4 | train | function | @pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_while_with_param_grad_with_const_branch():
class MyWhileNet(nn.Cell):
def __init__(self):
super().__init__()
self.max = P.ReduceMax()
sel... | @pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_while_with_param_grad_with_const_branch():
| class MyWhileNet(nn.Cell):
def __init__(self):
super().__init__()
self.max = P.ReduceMax()
self.param = Parameter(Tensor(np.arange(2 * 2 * 2).reshape((2, 2, 2)), ms.float32), name="weight")
self.zero = Tensor(np.zeros(([2, 2, 2])), ms.float32)
self... | =context.GRAPH_MODE)
while_net = MyWhileNet()
net = while_net
graph_output = net(idx, end, x)
expect = np.array([[[0, 1], [2, 3]],
[[4, 5], [6, 7]]]).astype(np.float32)
assert np.allclose(graph_output.asnumpy(), expect, 0.0001, 0.0001)
@pytest.mark.level0
@pytest.mark.platfor... | 130 | 130 | 435 | 39 | 91 | PowerOlive/mindspore | tests/st/control/test_cont_grad.py | Python | test_while_with_param_grad_with_const_branch | test_while_with_param_grad_with_const_branch | 372 | 415 | 372 | 376 | cf9f12df11d9729fe878a486ef14ee45e3dd395a | bigcode/the-stack | train |
fea68cddd6e86dee48995190 | train | function | @pytest.mark.level1
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_ascend_training
@pytest.mark.env_onecard
def test_if_by_if_forward_use_namespace():
class MyIfByIfNet(nn.Cell):
def __init__(self):
super().__init__()
self.add = P.Add()
self.sub = P.S... | @pytest.mark.level1
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_ascend_training
@pytest.mark.env_onecard
def test_if_by_if_forward_use_namespace():
| class MyIfByIfNet(nn.Cell):
def __init__(self):
super().__init__()
self.add = P.Add()
self.sub = P.Sub()
self.mul = P.Mul()
self.div = P.RealDiv()
def construct(self, a, b, x):
if a < b:
a = P.Add()(a, b)
... | if_net = MyIfByIfNet()
net = if_net
graph_output = net(idx, end, x)
expect = 4.444444
assert np.allclose(graph_output.asnumpy(), expect, 0.0001, 0.0001)
@pytest.mark.level1
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_ascend_training
@pytest.mark.env_onecard
def test_if_by_if_... | 99 | 99 | 331 | 39 | 60 | PowerOlive/mindspore | tests/st/control/test_cont_grad.py | Python | test_if_by_if_forward_use_namespace | test_if_by_if_forward_use_namespace | 1,209 | 1,248 | 1,209 | 1,213 | 2a0a3091e36935541d93c13023a7dc4e6e0b74bb | bigcode/the-stack | train |
218937b5d05d9ce898f9d5c7 | train | function | @pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_while_with_param_basic_grad():
class MyWhileNet(nn.Cell):
def __init__(self):
super().__init__()
self.max = P.ReduceMax()
self.param = Pa... | @pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_while_with_param_basic_grad():
| class MyWhileNet(nn.Cell):
def __init__(self):
super().__init__()
self.max = P.ReduceMax()
self.param = Parameter(Tensor(np.arange(2 * 2 * 2).reshape((2, 2, 2)), ms.float32), name="weight")
self.zero = Tensor(np.zeros(([2, 2, 2])), ms.float32)
self... | = MyWhileNet()
net = GradNet(while_net)
graph_output = net(idx, end, x)
expect = np.array([[[8, 8], [8, 8]],
[[8, 8], [8, 8]]]).astype(np.float32)
assert np.allclose(graph_output[0].asnumpy(), expect, 0.0001, 0.0001)
@pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@... | 126 | 126 | 423 | 37 | 89 | PowerOlive/mindspore | tests/st/control/test_cont_grad.py | Python | test_while_with_param_basic_grad | test_while_with_param_basic_grad | 557 | 596 | 557 | 561 | 0814b4da14a9fe2e313513ba1831a22bc767ebfe | bigcode/the-stack | train |
2121ffb4da90f8a8574888d5 | train | function | @pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_with_param_if_by_if_grad_parameter():
class MyIfByIfNet(nn.Cell):
def __init__(self):
super().__init__()
self.max = P.ReduceMax()
self.pa... | @pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_with_param_if_by_if_grad_parameter():
| class MyIfByIfNet(nn.Cell):
def __init__(self):
super().__init__()
self.max = P.ReduceMax()
self.param = Parameter(Tensor(np.arange(2 * 2 * 2).reshape((2, 2, 2)), ms.float32), name="weight")
self.zero = Tensor(np.zeros(([2, 2, 2])), ms.float32)
def co... | assert np.allclose(graph_output[0].asnumpy(), expect1.asnumpy(), 0.0001, 0.0001)
assert np.allclose(graph_output[1].asnumpy(), expect2.asnumpy(), 0.0001, 0.0001)
assert np.allclose(graph_output[2].asnumpy(), expect3, 0.0001, 0.0001)
@pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.pla... | 125 | 125 | 417 | 38 | 87 | PowerOlive/mindspore | tests/st/control/test_cont_grad.py | Python | test_with_param_if_by_if_grad_parameter | test_with_param_if_by_if_grad_parameter | 904 | 944 | 904 | 908 | a1479a9340345db76836e1714bbfde27bc97bb43 | bigcode/the-stack | train |
713ce3f4d948094f0481f938 | train | function | @pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_while_endless_case():
"""endless case when optimization"""
class MyWhileNet(nn.Cell):
def __init__(self):
super().__init__()
self.max = P.Reduce... | @pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_while_endless_case():
| """endless case when optimization"""
class MyWhileNet(nn.Cell):
def __init__(self):
super().__init__()
self.max = P.ReduceMax()
self.param = Parameter(Tensor(np.arange(2 * 2 * 2).reshape((2, 2, 2)), ms.float32), name="weight")
self.zero = Tensor(np.zeros(... | , x)
expect = np.array([[[6, 8], [10, 12]], [[19, 22], [25, 28]]], dtype=np.int32)
assert np.allclose(graph_output.asnumpy(), expect, 0.0001, 0.0001)
@pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_while_endless_case():
| 99 | 99 | 333 | 36 | 63 | PowerOlive/mindspore | tests/st/control/test_cont_grad.py | Python | test_while_endless_case | test_while_endless_case | 173 | 204 | 173 | 177 | df9fa39325fd2435805d8c9eeda8b03174ae0472 | bigcode/the-stack | train |
5e71cc9252c9635f39725dae | train | function | @pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_ascend_training
@pytest.mark.env_onecard
def test_for_while_with_param_grad_with_const_branch():
class MyWhileNet(nn.Cell):
def __init__(self):
super().__init__()
self.max = P.ReduceMax()
... | @pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_ascend_training
@pytest.mark.env_onecard
def test_for_while_with_param_grad_with_const_branch():
| class MyWhileNet(nn.Cell):
def __init__(self):
super().__init__()
self.max = P.ReduceMax()
self.param = Parameter(Tensor(np.arange(2 * 2 * 2).reshape((2, 2, 2)), ms.float32), name="weight")
self.zero = Tensor(np.zeros(([2, 2, 2])), ms.float32)
self... | _context(mode=context.GRAPH_MODE)
while_net = MyWhileNet()
net = GradNet(while_net)
graph_output = net(idx, end, x)
expect = np.array([[[4, 4], [4, 4]],
[[4, 4], [4, 4]]]).astype(np.float32)
assert np.allclose(graph_output[0].asnumpy(), expect, 0.0001, 0.0001)
@pytest.mark.le... | 141 | 141 | 471 | 42 | 99 | PowerOlive/mindspore | tests/st/control/test_cont_grad.py | Python | test_for_while_with_param_grad_with_const_branch | test_for_while_with_param_grad_with_const_branch | 418 | 464 | 418 | 422 | 087eea070e2ab0558f9ed09c91c9f88a5e1c38c3 | bigcode/the-stack | train |
50a4432c1da5dfadc59e5734 | train | function | @pytest.mark.level1
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_while_with_param_forward():
class MyWhileNet(nn.Cell):
def __init__(self):
super().__init__()
self.max = P.ReduceMax()
self.param = Param... | @pytest.mark.level1
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_while_with_param_forward():
| class MyWhileNet(nn.Cell):
def __init__(self):
super().__init__()
self.max = P.ReduceMax()
self.param = Parameter(Tensor(np.arange(2 * 2 * 2).reshape((2, 2, 2)), ms.float32), name="weight")
self.zero = Tensor(np.zeros(([2, 2, 2])), ms.float32)
def con... | 00000000e+00], dtype=np.float32)
assert np.allclose(graph_output[0].asnumpy(), expect_one, 0.0001, 0.0001)
assert np.allclose(graph_output[1].asnumpy(), expect_two, 0.0001, 0.0001)
@pytest.mark.level1
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def t... | 104 | 104 | 349 | 36 | 68 | PowerOlive/mindspore | tests/st/control/test_cont_grad.py | Python | test_while_with_param_forward | test_while_with_param_forward | 140 | 170 | 140 | 144 | a7e70827f42daa74c3a8a927e83d57d2adf9d3bb | bigcode/the-stack | train |
6aadc9099ca3c02a067572b2 | train | function | @pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_while_if_with_param_grad():
class MyWhileNet(nn.Cell):
def __init__(self):
super().__init__()
self.max = P.ReduceMax()
self.param = Param... | @pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_while_if_with_param_grad():
| class MyWhileNet(nn.Cell):
def __init__(self):
super().__init__()
self.max = P.ReduceMax()
self.param = Parameter(Tensor(np.arange(2 * 2 * 2).reshape((2, 2, 2)), ms.float32), name="weight")
self.zero = Tensor(np.zeros(([2, 2, 2])), ms.float32)
self... | , 3]]]).astype(np.float32)
assert np.allclose(graph_output[0].asnumpy(), expect1, 0.0001, 0.0001)
assert np.allclose(graph_output[1].asnumpy(), expect2, 0.0001, 0.0001)
assert np.allclose(graph_output[2].asnumpy(), expect3, 0.0001, 0.0001)
@pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytes... | 131 | 131 | 439 | 37 | 94 | PowerOlive/mindspore | tests/st/control/test_cont_grad.py | Python | test_while_if_with_param_grad | test_while_if_with_param_grad | 738 | 779 | 738 | 742 | f5cd9f357115187beddb54152ff570120a90d091 | bigcode/the-stack | train |
47a7a21e93addbc8bdcb4d2c | train | function | @pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_while_with_param_basic_grad_two():
class MyWhileNet(nn.Cell):
def __init__(self):
super().__init__()
self.max = P.ReduceMax()
self.param ... | @pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_while_with_param_basic_grad_two():
| class MyWhileNet(nn.Cell):
def __init__(self):
super().__init__()
self.max = P.ReduceMax()
self.param = Parameter(Tensor(np.arange(2 * 2 * 2).reshape((2, 2, 2)), ms.float32), name="weight")
self.weight = Parameter(Tensor(np.arange(2 * 2 * 2).reshape((2, 2, 2))... | 2).astype(np.float32), dtype=ms.float32)
# graph mode
context.set_context(mode=context.GRAPH_MODE)
while_net = MyWhileNet()
net = GradNet(while_net)
graph_output = net(idx, end, x)
expect = np.array([[[1, 4], [13, 28]],
[[49, 76], [109, 148]]]).astype(np.float32)
asse... | 159 | 159 | 531 | 38 | 121 | PowerOlive/mindspore | tests/st/control/test_cont_grad.py | Python | test_while_with_param_basic_grad_two | test_while_with_param_basic_grad_two | 641 | 685 | 641 | 645 | 77cb0bc77426044132f81b522380c4b90a945bf0 | bigcode/the-stack | train |
d7e654e12a54ffd8718e08ac | train | function | def test_while_grad():
class MyWhileNet(nn.Cell):
def __init__(self):
super().__init__()
self.max = P.ReduceMax()
def construct(self, idx, end, x):
while idx < end:
part = x[idx, :, :]
max_num = self.max(part)
x[idx... | def test_while_grad():
| class MyWhileNet(nn.Cell):
def __init__(self):
super().__init__()
self.max = P.ReduceMax()
def construct(self, idx, end, x):
while idx < end:
part = x[idx, :, :]
max_num = self.max(part)
x[idx, :, 0:2] = max_num
... | mindspore import context
from mindspore import nn
from mindspore.common.parameter import Parameter, ParameterTuple
from mindspore.ops import composite as C
from mindspore.ops import operations as P
grad_by_list = C.GradOperation(get_by_list=True)
grad_all = C.GradOperation(get_all=True)
def test_while_grad():
| 75 | 75 | 253 | 6 | 69 | PowerOlive/mindspore | tests/st/control/test_cont_grad.py | Python | test_while_grad | test_while_grad | 32 | 63 | 32 | 32 | b3d812b9ebbbc45b61b34f074b0a5e22185442a3 | bigcode/the-stack | train |
931eb5fdf1433be094882572 | train | function | @pytest.mark.level1
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_ascend_training
@pytest.mark.env_onecard
def test_if_by_if_forward_all_const_branch():
class MyIfByIfNet(nn.Cell):
def __init__(self):
super().__init__()
self.add = P.Add()
self.sub = ... | @pytest.mark.level1
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_ascend_training
@pytest.mark.env_onecard
def test_if_by_if_forward_all_const_branch():
| class MyIfByIfNet(nn.Cell):
def __init__(self):
super().__init__()
self.add = P.Add()
self.sub = P.Sub()
self.mul = P.Mul()
self.div = P.RealDiv()
def construct(self, a, b, x):
add = P.Add()
sub = P.Sub()
... | =context.GRAPH_MODE)
if_net = MyIfByIfNet()
net = if_net
graph_output = net(idx, end, x)
expect = 240.0
assert np.allclose(graph_output.asnumpy(), expect, 0.0001, 0.0001)
@pytest.mark.level1
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_ascend_training
@pytest.mark.env_onecard... | 104 | 104 | 349 | 40 | 64 | PowerOlive/mindspore | tests/st/control/test_cont_grad.py | Python | test_if_by_if_forward_all_const_branch | test_if_by_if_forward_all_const_branch | 1,415 | 1,459 | 1,415 | 1,419 | 6fa77cb578f078982832118f6e355eeadbaf2a1b | bigcode/the-stack | train |
d0a3323011416603c1806d8c | train | function | @pytest.mark.level1
@pytest.mark.platform_x86_cpu
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_while_const_grad():
class MyNet(nn.Cell):
def __init__(self):
super().__init__()
self.add = P.Add()
def construct(self, *inputs):
out = self... | @pytest.mark.level1
@pytest.mark.platform_x86_cpu
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_while_const_grad():
| class MyNet(nn.Cell):
def __init__(self):
super().__init__()
self.add = P.Add()
def construct(self, *inputs):
out = self.add(*inputs)
return out
class GradNet(nn.Cell):
def __init__(self, net):
super(GradNet, self).__init__()
... | = Tensor(np.array(0), dtype=ms.int32)
b = Tensor(np.array(1), dtype=ms.int32)
net(a, b)
@pytest.mark.level1
@pytest.mark.platform_x86_cpu
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_while_const_grad():
| 67 | 67 | 226 | 33 | 34 | PowerOlive/mindspore | tests/st/control/test_cont_grad.py | Python | test_while_const_grad | test_while_const_grad | 1,538 | 1,569 | 1,538 | 1,542 | 30c3feffd1cd8544bf607755af9df56d7690590d | bigcode/the-stack | train |
5d66f7a86eca1dc53b37a83a | train | function | @pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_with_param_if_by_if_grad_inputs():
class MyIfByIfNet(nn.Cell):
def __init__(self):
super().__init__()
self.max = P.ReduceMax()
self.param... | @pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_with_param_if_by_if_grad_inputs():
| class MyIfByIfNet(nn.Cell):
def __init__(self):
super().__init__()
self.max = P.ReduceMax()
self.param = Parameter(Tensor(np.arange(2 * 2 * 2).reshape((2, 2, 2)), ms.float32), name="weight")
self.zero = Tensor(np.zeros(([2, 2, 2])), ms.float32)
def co... | 32), dtype=ms.float32)
# graph mode
context.set_context(mode=context.GRAPH_MODE)
if_net = MyIfByIfNet()
net = if_net
graph_output = net(idx, end, x)
expect = np.array([[[3, 4], [5, 6]],
[[7, 8], [9, 10]]]).astype(np.float32)
assert np.allclose(graph_output.asnumpy(), e... | 149 | 149 | 499 | 38 | 111 | PowerOlive/mindspore | tests/st/control/test_cont_grad.py | Python | test_with_param_if_by_if_grad_inputs | test_with_param_if_by_if_grad_inputs | 859 | 901 | 859 | 863 | 37235ef8d7301fc1a88fdea57f84f6d4e795db27 | bigcode/the-stack | train |
fd339d1a4d6cbe49323e4fc7 | train | function | @pytest.mark.level1
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_ascend_training
@pytest.mark.env_onecard
def test_for_with_if_by_if_forward_namespace():
class MyIfByIfNet(nn.Cell):
def __init__(self):
super().__init__()
self.add = P.Add()
self.sub ... | @pytest.mark.level1
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_ascend_training
@pytest.mark.env_onecard
def test_for_with_if_by_if_forward_namespace():
| class MyIfByIfNet(nn.Cell):
def __init__(self):
super().__init__()
self.add = P.Add()
self.sub = P.Sub()
self.mul = P.Mul()
self.div = P.RealDiv()
def construct(self, a, b, x):
for _ in range(0, 6):
if a < b:
... |
graph_output = net(idx, end, x)
expect = 18.0
assert np.allclose(graph_output.asnumpy(), expect, 0.0001, 0.0001)
@pytest.mark.level1
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_ascend_training
@pytest.mark.env_onecard
def test_for_with_if_by_if_forward_namespace():
| 84 | 84 | 282 | 40 | 44 | PowerOlive/mindspore | tests/st/control/test_cont_grad.py | Python | test_for_with_if_by_if_forward_namespace | test_for_with_if_by_if_forward_namespace | 1,332 | 1,365 | 1,332 | 1,336 | 664c4b8904109f37901ef6d648e2ca77a0d4bd35 | bigcode/the-stack | train |
9a5fe7afadb0114112eb2f10 | train | function | @pytest.mark.level1
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_if_by_if_forward():
class MyIfByIfNet(nn.Cell):
def __init__(self):
super().__init__()
self.add = P.Add()
self.sub = P.Sub()
... | @pytest.mark.level1
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_if_by_if_forward():
| class MyIfByIfNet(nn.Cell):
def __init__(self):
super().__init__()
self.add = P.Add()
self.sub = P.Sub()
self.mul = P.Mul()
self.div = P.RealDiv()
def construct(self, a, b, x):
if a < b:
a = self.add(a, b)
... | .array([[[3, 3], [3, 3]],
[[3, 3], [3, 3]]]).astype(np.float32)
assert np.allclose(graph_output[0].asnumpy(), expect, 0.0001, 0.0001)
@pytest.mark.level1
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_if_by_if_forward():
| 95 | 95 | 319 | 35 | 60 | PowerOlive/mindspore | tests/st/control/test_cont_grad.py | Python | test_if_by_if_forward | test_if_by_if_forward | 1,031 | 1,070 | 1,031 | 1,035 | d03d2f355d4e245c910ea0285ecac2a8736ecce7 | bigcode/the-stack | train |
baec9485e48712559042fcfa | train | function | @pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_ascend_training
@pytest.mark.env_onecard
def test_no_while_call():
class MyWhileNet(nn.Cell):
def __init__(self):
super().__init__()
self.max = P.ReduceMax()
self.param = Parameter(Ten... | @pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_ascend_training
@pytest.mark.env_onecard
def test_no_while_call():
| class MyWhileNet(nn.Cell):
def __init__(self):
super().__init__()
self.max = P.ReduceMax()
self.param = Parameter(Tensor(np.arange(2 * 2 * 2).reshape((2, 2, 2)), ms.float32), name="weight")
self.zero = Tensor(np.zeros(([2, 2, 2])), ms.float32)
self... | 0001, 0.0001)
assert np.allclose(graph_output[1].asnumpy(), expect2, 0.0001, 0.0001)
assert np.allclose(graph_output[2].asnumpy(), expect3, 0.0001, 0.0001)
@pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_ascend_training
@pytest.mark.env_onecard
def test_no_while_call():
| 102 | 102 | 342 | 37 | 65 | PowerOlive/mindspore | tests/st/control/test_cont_grad.py | Python | test_no_while_call | test_no_while_call | 337 | 369 | 337 | 341 | e10e5f8102acc9cfc59a6717c9e9beaf8fafb0a4 | bigcode/the-stack | train |
b8b1bca12e51fd745844bfa7 | train | function | @pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_ascend_training
@pytest.mark.env_onecard
def test_while_with_param_grad_not_enter_while():
class MyWhileNet(nn.Cell):
def __init__(self):
super().__init__()
self.max = P.ReduceMax()
se... | @pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_ascend_training
@pytest.mark.env_onecard
def test_while_with_param_grad_not_enter_while():
| class MyWhileNet(nn.Cell):
def __init__(self):
super().__init__()
self.max = P.ReduceMax()
self.param = Parameter(Tensor(2, ms.float32), name="weight")
self.zero = Tensor(0, ms.float32)
def construct(self, idx, end, x):
out = self.zero
... | [[5, 5], [5, 5]],
[[5, 5], [5, 5]]]).astype(np.float32)
assert np.allclose(graph_output[0].asnumpy(), expect, 0.0001, 0.0001)
@pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_ascend_training
@pytest.mark.env_onecard
def test_while_with_param_grad_not_ent... | 100 | 100 | 335 | 42 | 58 | PowerOlive/mindspore | tests/st/control/test_cont_grad.py | Python | test_while_with_param_grad_not_enter_while | test_while_with_param_grad_not_enter_while | 782 | 819 | 782 | 786 | 73ff8d36c09d88761cf884dadbc53f5fa76322d4 | bigcode/the-stack | train |
d46791f619057d8dca7ec2a0 | train | function | @pytest.mark.level1
@pytest.mark.platform_x86_cpu
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_if_by_while_const_grad():
class MyNet(nn.Cell):
def __init__(self):
super().__init__()
self.add = P.Add()
def construct(self, *inputs):
out ... | @pytest.mark.level1
@pytest.mark.platform_x86_cpu
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_if_by_while_const_grad():
| class MyNet(nn.Cell):
def __init__(self):
super().__init__()
self.add = P.Add()
def construct(self, *inputs):
out = self.add(*inputs)
return out
class GradNet(nn.Cell):
def __init__(self, net):
super(GradNet, self).__init__()
... | Net(my_net)
a = Tensor(np.array(0), dtype=ms.int32)
b = Tensor(np.array(1), dtype=ms.int32)
net(a, b)
@pytest.mark.level1
@pytest.mark.platform_x86_cpu
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_if_by_while_const_grad():
| 75 | 75 | 252 | 35 | 40 | PowerOlive/mindspore | tests/st/control/test_cont_grad.py | Python | test_if_by_while_const_grad | test_if_by_while_const_grad | 1,572 | 1,607 | 1,572 | 1,576 | c15efbf9d498ba38858cae36f8960a044198a94a | bigcode/the-stack | train |
137b239ae730397049287ac7 | train | function | @pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_if_by_if_forward_control_tuple_switch():
"""tuple_get from switch op will generate new switch inside to eliminate tuple_get"""
class Branch3Net(nn.Cell):
def __init__(... | @pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_if_by_if_forward_control_tuple_switch():
| """tuple_get from switch op will generate new switch inside to eliminate tuple_get"""
class Branch3Net(nn.Cell):
def __init__(self):
super().__init__()
self.add = P.Add()
self.sub = P.Sub()
self.mul = P.Mul()
self.div = P.RealDiv()
d... | .array(2), dtype=ms.float32)
end = Tensor(np.array(3), dtype=ms.float32)
x = Tensor(np.array(4), dtype=ms.float32)
# graph mode
context.set_context(mode=context.GRAPH_MODE)
if_net = MyIfByIfNet()
net = if_net
graph_output = net(idx, end, x)
expect = 19.11111
assert np.allclose(graph_... | 153 | 153 | 511 | 38 | 115 | PowerOlive/mindspore | tests/st/control/test_cont_grad.py | Python | test_if_by_if_forward_control_tuple_switch | test_if_by_if_forward_control_tuple_switch | 1,073 | 1,139 | 1,073 | 1,077 | f3500fede4f69e4406269cdecb8b1f746b87c32c | bigcode/the-stack | train |
31b9be95733fe20d38aee6aa | train | function | def seq_header_to_chr(header):
import re
c = re.compile(r'\[segment (L|S)\]')
m = c.search(header)
if not m:
raise Exception("Unknown or invalid segment in header %s" % header)
seg = m.group(1)
return "segment_" + seg
| def seq_header_to_chr(header):
| import re
c = re.compile(r'\[segment (L|S)\]')
m = c.search(header)
if not m:
raise Exception("Unknown or invalid segment in header %s" % header)
seg = m.group(1)
return "segment_" + seg
| strain and/or isolate,
these sequences were able to be grouped into 4 genomes. Many genomes
may have fewer than 2 segments.
THIS PYTHON FILE WAS GENERATED BY A COMPUTER PROGRAM! DO NOT EDIT!
"""
import sys
from catch.datasets import GenomesDatasetMultiChrom
def seq_header_to_chr(header):
| 64 | 64 | 70 | 7 | 56 | broadinstitute/catch | catch/datasets/serra_do_navio_mammarenavirus.py | Python | seq_header_to_chr | seq_header_to_chr | 16 | 23 | 16 | 16 | c29a0b6b3be16f4e650fdbf11ae83bab1300c241 | bigcode/the-stack | train |
c964ce8491a9a0b0d70982b9 | train | function | def seq_header_to_genome(header):
import re
c = re.compile(r'\[genome (.+)\]')
m = c.search(header)
if not m:
raise Exception("Unknown genome in header %s" % header)
return m.group(1)
| def seq_header_to_genome(header):
| import re
c = re.compile(r'\[genome (.+)\]')
m = c.search(header)
if not m:
raise Exception("Unknown genome in header %s" % header)
return m.group(1)
| re.compile(r'\[segment (L|S)\]')
m = c.search(header)
if not m:
raise Exception("Unknown or invalid segment in header %s" % header)
seg = m.group(1)
return "segment_" + seg
def seq_header_to_genome(header):
| 64 | 64 | 59 | 8 | 55 | broadinstitute/catch | catch/datasets/serra_do_navio_mammarenavirus.py | Python | seq_header_to_genome | seq_header_to_genome | 25 | 31 | 25 | 25 | f0e526dc299e8b6882a7254185d38804f4144796 | bigcode/the-stack | train |
a844c4546033f083146043c8 | train | class | class Bcp47Tag():
def __init__(self, language=None, script=None, region=None, privateUse=[], variant=[],
extension=[], grandFathered=None, extLang=[], langTagPrivateUse=[]):
self.language = language
self.privateUse = privateUse
self.variant = variant
self.extension =... | class Bcp47Tag():
| def __init__(self, language=None, script=None, region=None, privateUse=[], variant=[],
extension=[], grandFathered=None, extLang=[], langTagPrivateUse=[]):
self.language = language
self.privateUse = privateUse
self.variant = variant
self.extension = extension
... | #!/usr/bin/python3
import re
class Bcp47Tag():
| 15 | 256 | 1,306 | 6 | 8 | srl295/keyman | linux/keyman-config/keyman_config/bcp47tag.py | Python | Bcp47Tag | Bcp47Tag | 5 | 150 | 5 | 5 | 0cedbb17c43a370c7da43b8ac9b28586e6a673bd | bigcode/the-stack | train |
ca7eeda21ad4c343819efb13 | train | class | class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
cur = self.root
for w in word:
if cur.children.get(... | class Trie:
| def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
cur = self.root
for w in word:
if cur.children.get(w) is None:
... | class TrieNode:
def __init__(self):
self.children = {}
self.isWord = False
class Trie:
| 26 | 72 | 241 | 3 | 22 | Yong-Zhuang/Tutoring | Coding/Tree/implement-trie-prefix-tree.py | Python | Trie | Trie | 7 | 48 | 7 | 8 | 96e4e1189d95477b3bc5f5697352ed2b941a80b0 | bigcode/the-stack | train |
12a83a55c1b94a125e139ab7 | train | class | class TrieNode:
def __init__(self):
self.children = {}
self.isWord = False
| class TrieNode:
| def __init__(self):
self.children = {}
self.isWord = False
| class TrieNode:
| 4 | 64 | 23 | 4 | 0 | Yong-Zhuang/Tutoring | Coding/Tree/implement-trie-prefix-tree.py | Python | TrieNode | TrieNode | 1 | 4 | 1 | 1 | 5c031dd7f88977978be8875ac3c407d53f18e724 | bigcode/the-stack | train |
166326889a975e9ea06284db | train | class | class ExtractionMultiProcessEngineTest(shared_test_lib.BaseTestCase):
"""Tests for the task-based multi-process extraction engine."""
def testProcessSources(self):
"""Tests the PreprocessSources and ProcessSources function."""
artifacts_path = shared_test_lib.GetTestFilePath(['artifacts'])
self._SkipIf... | class ExtractionMultiProcessEngineTest(shared_test_lib.BaseTestCase):
| """Tests for the task-based multi-process extraction engine."""
def testProcessSources(self):
"""Tests the PreprocessSources and ProcessSources function."""
artifacts_path = shared_test_lib.GetTestFilePath(['artifacts'])
self._SkipIfPathNotExists(artifacts_path)
test_engine = extraction_engine.Ext... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests the multi-process processing engine."""
import collections
import os
import unittest
from dfvfs.lib import definitions as dfvfs_definitions
from dfvfs.path import factory as path_spec_factory
from plaso.containers import artifacts
from plaso.containers import s... | 131 | 160 | 535 | 13 | 117 | jonathan-greig/plaso | tests/multi_process/extraction_engine.py | Python | ExtractionMultiProcessEngineTest | ExtractionMultiProcessEngineTest | 22 | 90 | 22 | 22 | 58bc594612f10a5c2f08bc6551e2df88aa5d0781 | bigcode/the-stack | train |
6640809e855cf45d26913018 | train | function | def create(kernel):
result = Building()
result.template = "object/building/poi/shared_lok_nymshenchman_small3.iff"
result.attribute_template_id = -1
result.stfName("poi_n","base_poi_building")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result | def create(kernel):
| result = Building()
result.template = "object/building/poi/shared_lok_nymshenchman_small3.iff"
result.attribute_template_id = -1
result.stfName("poi_n","base_poi_building")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
| 46 | 64 | 73 | 4 | 42 | obi-two/GameServer | data/scripts/templates/object/building/poi/shared_lok_nymshenchman_small3.py | Python | create | create | 7 | 17 | 7 | 7 | 226b71ead8f60f8a642ecc59b9b4778b018c9659 | bigcode/the-stack | train |
b145e44f2ac73d6e17cce4c3 | train | function | def commandverify(cmd: str) -> bool:
return call("type " + cmd, shell=True, stdout=PIPE, stderr=PIPE) == 0
| def commandverify(cmd: str) -> bool:
| return call("type " + cmd, shell=True, stdout=PIPE, stderr=PIPE) == 0
| Raspberry Pi 4, inicia sesión como root/root, si tienes errores, repórtalo a 036raspberry"
)
if LANGUAGE == 1: return DICTIONARY_ENG[position]
else: return DICTIONARY_ESP[position]
def commandverify(cmd: str) -> bool:
| 64 | 64 | 34 | 10 | 54 | victor7w7r/036raspberry | python/archrpi4-install.py | Python | commandverify | commandverify | 92 | 93 | 92 | 92 | 717ab8231bf18d9bb3c0fbf7527a6b2b030de8d2 | bigcode/the-stack | train |
163116f178199d2f4215353f | train | function | def cover() -> None:
utils.clear()
print(r''' `"~>v??*^;rikD&MNBQku*;` ''')
print(r''' `!{wQNWWWWWWWWWWWWWWWNWWWWWWNdi^` ''')
print(r''' ... | def cover() -> None:
| utils.clear()
print(r''' `"~>v??*^;rikD&MNBQku*;` ''')
print(r''' `!{wQNWWWWWWWWWWWWWWWNWWWWWWNdi^` ''')
print(r''' .v9NWWWWNRFm... | "ZONA DE PELIGRO!!",
"Este dispositivo se va a formatear ¿Continuar? \n",
"Presione Enter para continuar...",
"En la carpeta home de root está disponible el script de configuración, si lo deseas",
"LISTO!!!, Tu SD fue instalada con Arch Linux ARM para la Raspberry Pi 4, inicia sesión como root/root, si tienes ... | 256 | 256 | 1,770 | 7 | 249 | victor7w7r/036raspberry | python/archrpi4-install.py | Python | cover | cover | 107 | 153 | 107 | 108 | 745a8d1f74c7503651729ee6d158ed0deaf3e384 | bigcode/the-stack | train |
03a66ba5bd3ceae2b0736b45 | train | function | def printer(type: str, position: int) -> None:
GREEN = '\033[92m'; WARNING = '\033[93m'; FAIL = '\033[91m'; ENDC = '\033[0m'
DICTIONARY_ENG=(
"Your Operating System is not GNU/Linux, exiting",
"This PC doesn't have internet connection, please check",
"dialog is not available in this system, ... | def printer(type: str, position: int) -> None:
| GREEN = '\033[92m'; WARNING = '\033[93m'; FAIL = '\033[91m'; ENDC = '\033[0m'
DICTIONARY_ENG=(
"Your Operating System is not GNU/Linux, exiting",
"This PC doesn't have internet connection, please check",
"dialog is not available in this system, please install it",
"parted is not available in th... | from subprocess import call, PIPE, Popen
from sys import stdin, stdout, platform, version_info
from os import system, getuid
from urllib.request import urlopen
from termios import tcgetattr, tcsetattr, TCSADRAIN
from time import sleep
from tty import setcbreak
from dialog import Dialog
d = Dialog(dialog="dialog")
d.se... | 124 | 232 | 775 | 14 | 110 | victor7w7r/036raspberry | python/archrpi4-install.py | Python | printer | printer | 16 | 63 | 16 | 17 | ee4662ad541c6bb8eb5d3fdbeb9bbb007b5c18a9 | bigcode/the-stack | train |
f7ee7b85b81ba2507b6da826 | train | function | def main() -> None:
utils.clear(); language(); cover(); verify(); usbverify(); diskmenu()
| def main() -> None:
| utils.clear(); language(); cover(); verify(); usbverify(); diskmenu()
| from urllib.request import urlopen
from termios import tcgetattr, tcsetattr, TCSADRAIN
from time import sleep
from tty import setcbreak
from dialog import Dialog
d = Dialog(dialog="dialog")
d.set_background_title("036 Creative Studios")
def main() -> None:
| 64 | 64 | 23 | 7 | 57 | victor7w7r/036raspberry | python/archrpi4-install.py | Python | main | main | 13 | 14 | 13 | 13 | cb709d48108e9d39e5385e834498c638769c6105 | bigcode/the-stack | train |
b69e547692ee7520ebb182b2 | train | function | def finisher() -> None:
utils.clear(); d.msgbox(reader(6),8,50)
d.msgbox(reader(7),10,50)
utils.clear(); exit(0)
| def finisher() -> None:
| utils.clear(); d.msgbox(reader(6),8,50)
d.msgbox(reader(7),10,50)
utils.clear(); exit(0)
| system("umount /mnt/root")
system("rm -rf /mnt/boot"); system("rm -rf /mnt/root")
print(" ")
print("=============== OK =============== \n")
input(reader(5)); utils.clear(); finisher()
def finisher() -> None:
| 63 | 64 | 43 | 8 | 55 | victor7w7r/036raspberry | python/archrpi4-install.py | Python | finisher | finisher | 266 | 270 | 266 | 267 | aed3aa7e47de943637e3cbe51df79323f541daf1 | bigcode/the-stack | train |
05506c08c86f465789c40a64 | train | function | def usbverify() -> None:
VERIFYUSB: str = Popen(r"""find /dev/disk/by-id/ -name 'usb*' | sort -n | sed 's/^\/dev\/disk\/by-id\///'
""", shell=True, stdout=PIPE).stdout.read().decode('utf-8').replace("\n", "")
if(VERIFYUSB == ""): utils.clear(); printer("error",10); exit(1)
| def usbverify() -> None:
| VERIFYUSB: str = Popen(r"""find /dev/disk/by-id/ -name 'usb*' | sort -n | sed 's/^\/dev\/disk\/by-id\///'
""", shell=True, stdout=PIPE).stdout.read().decode('utf-8').replace("\n", "")
if(VERIFYUSB == ""): utils.clear(); printer("error",10); exit(1)
| :.....::.....:::..::..::...:::.....::::.....:::..::.....::.....::..:.....::.....:''')
print(r''':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::''')
print(r'''::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::... | 64 | 64 | 96 | 8 | 56 | victor7w7r/036raspberry | python/archrpi4-install.py | Python | usbverify | usbverify | 155 | 159 | 155 | 156 | 92a27148179685c9079eb481f2824b27701a82a7 | bigcode/the-stack | train |
09ccad719b9fa33d71059965 | train | function | def language() -> None:
global LANGUAGE
print("Bienvenido / Welcome")
print("Please, choose your language / Por favor selecciona tu idioma")
print("1) English"); print("2) Espanol")
option: str = utils.char()
if option == "1": LANGUAGE=1
elif option == "2": LANGUAGE=2
else: ex... | def language() -> None:
| global LANGUAGE
print("Bienvenido / Welcome")
print("Please, choose your language / Por favor selecciona tu idioma")
print("1) English"); print("2) Espanol")
option: str = utils.char()
if option == "1": LANGUAGE=1
elif option == "2": LANGUAGE=2
else: exit(1)
| == 1: return DICTIONARY_ENG[position]
else: return DICTIONARY_ESP[position]
def commandverify(cmd: str) -> bool:
return call("type " + cmd, shell=True, stdout=PIPE, stderr=PIPE) == 0
def language() -> None:
| 64 | 64 | 87 | 7 | 56 | victor7w7r/036raspberry | python/archrpi4-install.py | Python | language | language | 95 | 105 | 95 | 96 | 2272ea431afdca9ea0b5cbaa16658c29a1a2d29b | bigcode/the-stack | train |
0bf9bc1fdee5aed59495c0ac | train | function | def baseinstall() -> None:
printer("print",9)
system("wget http://os.archlinuxarm.org/os/ArchLinuxARM-rpi-aarch64-latest.tar.gz -P /mnt/root/")
system("bsdtar -xpf /mnt/root/ArchLinuxARM-rpi-aarch64-latest.tar.gz -C /mnt/root/")
system("sync"); system("rm /mnt/root/ArchLinuxARM-rpi-aarch64-latest.t... | def baseinstall() -> None:
| printer("print",9)
system("wget http://os.archlinuxarm.org/os/ArchLinuxARM-rpi-aarch64-latest.tar.gz -P /mnt/root/")
system("bsdtar -xpf /mnt/root/ArchLinuxARM-rpi-aarch64-latest.tar.gz -C /mnt/root/")
system("sync"); system("rm /mnt/root/ArchLinuxARM-rpi-aarch64-latest.tar.gz")
system("mv /mnt/root... | mkdir /mnt/boot"); system("mkdir /mnt/root")
system(f"mount {disk}2 /mnt/root"); system(f"mount {disk}1 /mnt/boot")
print(" ")
print("=============== OK =============== \n")
input(reader(5)); utils.clear(); baseinstall()
else: utils.clear(); exit(1)
def baseinstall() -> None:
| 83 | 84 | 281 | 8 | 75 | victor7w7r/036raspberry | python/archrpi4-install.py | Python | baseinstall | baseinstall | 249 | 264 | 249 | 250 | e26ba94876b07ee2b77c1e9ad2a4b84f83922028 | bigcode/the-stack | train |
79b5a6b55bdf93e634554de3 | train | class | class utils:
def clear() -> None: system('clear')
def char() -> str:
fd = stdin.fileno()
oldSettings = tcgetattr(fd)
try:
setcbreak(fd)
answer = stdin.read(1)
finally:
tcsetattr(fd, TCSADRAIN, oldSettings)
return answer
... | class utils:
| def clear() -> None: system('clear')
def char() -> str:
fd = stdin.fileno()
oldSettings = tcgetattr(fd)
try:
setcbreak(fd)
answer = stdin.read(1)
finally:
tcsetattr(fd, TCSADRAIN, oldSettings)
return answer
def spinning():... | \n")
input(reader(5)); utils.clear(); finisher()
def finisher() -> None:
utils.clear(); d.msgbox(reader(6),8,50)
d.msgbox(reader(7),10,50)
utils.clear(); exit(0)
class utils:
| 63 | 64 | 97 | 4 | 59 | victor7w7r/036raspberry | python/archrpi4-install.py | Python | utils | utils | 272 | 289 | 272 | 273 | 8505ac1204e84aeb082e437934175ee40d2eb50c | bigcode/the-stack | train |
85086b2337efa993ee527ffc | train | function | def reader(position: int) -> str:
DICTIONARY_ENG=(
"ATTENTION!!! Your SD card would be listed as a USB device, ensure that your SD is empty and ready for format",
"Format a Device",
"Choose a device",
"DANGER ZONE!!!",
"This device will be format Continue? \n",
"Press Enter to continue...",
... | def reader(position: int) -> str:
| DICTIONARY_ENG=(
"ATTENTION!!! Your SD card would be listed as a USB device, ensure that your SD is empty and ready for format",
"Format a Device",
"Choose a device",
"DANGER ZONE!!!",
"This device will be format Continue? \n",
"Press Enter to continue...",
"At the superuser home directory, we p... | }+{ENDC}] INFO: {DICTIONARY_ESP[position]}")
elif type == "warn": print(f"[{WARNING}*{ENDC}] WARNING: {DICTIONARY_ESP[position]}")
elif type == "error": print(f"[{FAIL}!{ENDC}] ERROR: {DICTIONARY_ESP[position]}")
else: print(f"[?] UNKNOWN: {DICTIONARY_ESP[position]}")
def reader(position: int) -... | 102 | 102 | 340 | 10 | 92 | victor7w7r/036raspberry | python/archrpi4-install.py | Python | reader | reader | 65 | 90 | 65 | 66 | 97f611a661669588dd6c39fd0d037f8fc36985f2 | bigcode/the-stack | train |
8f60b695860aea8cb2d92eb1 | train | function | def diskmenu() -> None:
utils.clear(); usbverify()
d.msgbox(reader(0),7,70)
DIRTYDEVS: list = []; BLOCK: list = []
COUNT: int = 0; MODEL: int = 0; BLOCKCOUNT: int = 0
DEVICE: int = 0; ARGSUSB: list = []
USB = Popen(r"""find /dev/disk/by-id/ -name 'usb*' | sort -n | sed 's/^\/dev\/disk\/by-id... | def diskmenu() -> None:
| utils.clear(); usbverify()
d.msgbox(reader(0),7,70)
DIRTYDEVS: list = []; BLOCK: list = []
COUNT: int = 0; MODEL: int = 0; BLOCKCOUNT: int = 0
DEVICE: int = 0; ARGSUSB: list = []
USB = Popen(r"""find /dev/disk/by-id/ -name 'usb*' | sort -n | sed 's/^\/dev\/disk\/by-id\///'
"... | .clear(); printer("error",1); exit(1)
if not commandverify("dialog"):
utils.clear(); printer("error",2); exit(1)
if not commandverify("parted"):
utils.clear(); printer("error",3); exit(1)
if not commandverify("wget"):
utils.clear(); printer("error",4); exit(1)
if ... | 163 | 163 | 544 | 8 | 155 | victor7w7r/036raspberry | python/archrpi4-install.py | Python | diskmenu | diskmenu | 188 | 225 | 188 | 189 | 579c63d229ada5414e2da2666c8384dbdd18eed1 | bigcode/the-stack | train |
1163de4b70deefb33e842657 | train | function | def diskformat(disk: str) -> None:
if disk == "": utils.clear(); exit(0)
if d.yesno(reader(4),7,60) == d.OK:
utils.clear()
printer("print",7)
system(f"umount -f {disk}?* &> /dev/null")
system(f"parted --script {disk} mklabel msdos mkpart primary fat32 1MiB 200MiB set 1 boot ... | def diskformat(disk: str) -> None:
| if disk == "": utils.clear(); exit(0)
if d.yesno(reader(4),7,60) == d.OK:
utils.clear()
printer("print",7)
system(f"umount -f {disk}?* &> /dev/null")
system(f"parted --script {disk} mklabel msdos mkpart primary fat32 1MiB 200MiB set 1 boot on mkpart primary ext4 200MiB 100% print... | -8').rstrip()
ARGSUSB.append([DEVICE, MODEL+ " " +SIZE]); COUNT += 1
response = d.menu(reader(2), 15, 50, 4, ARGSUSB)
if(response[0] == "ok"): diskformat(response[1])
def diskformat(disk: str) -> None:
| 76 | 77 | 257 | 12 | 64 | victor7w7r/036raspberry | python/archrpi4-install.py | Python | diskformat | diskformat | 227 | 247 | 227 | 228 | 20fa265822ff0f41638757dcd78088db60e41094 | bigcode/the-stack | train |
7f5529f0d474b00c4db48261 | train | function | def verify() -> None:
if version_info < (3, 5):
utils.clear(); printer("error",11); exit(1)
if platform != "linux":
utils.clear(); printer("error",0); exit(1)
if getuid() != 0:
utils.clear(); printer("error",12); exit(1)
try: urlopen('http://google.com')
except: utils.cl... | def verify() -> None:
| if version_info < (3, 5):
utils.clear(); printer("error",11); exit(1)
if platform != "linux":
utils.clear(); printer("error",0); exit(1)
if getuid() != 0:
utils.clear(); printer("error",12); exit(1)
try: urlopen('http://google.com')
except: utils.clear(); printer("error",1); ... | *' | sort -n | sed 's/^\/dev\/disk\/by-id\///'
""", shell=True, stdout=PIPE).stdout.read().decode('utf-8').replace("\n", "")
if(VERIFYUSB == ""): utils.clear(); printer("error",10); exit(1)
def verify() -> None:
| 73 | 73 | 246 | 7 | 66 | victor7w7r/036raspberry | python/archrpi4-install.py | Python | verify | verify | 161 | 186 | 161 | 162 | 630e52c40b350b54e1dc5d4e2e4923cdcde34baf | bigcode/the-stack | train |
556446a0c6edaf7ce38e2e6a | train | function | def get_unspent(listunspent, amount):
for utx in listunspent:
if utx['amount'] == amount:
return utx
raise AssertionError('Could not find unspent with amount={}'.format(amount))
| def get_unspent(listunspent, amount):
| for utx in listunspent:
if utx['amount'] == amount:
return utx
raise AssertionError('Could not find unspent with amount={}'.format(amount))
| MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the fundrawtransaction RPC."""
from test_framework.test_framework import BitcoinTestFramework, BITCOIND_PROC_WAIT_TIMEOUT
from test_framework.util import *
def get_unspent(listunspent, amount):
| 64 | 64 | 51 | 10 | 54 | tomkoker/teddycoin | test/functional/fundrawtransaction.py | Python | get_unspent | get_unspent | 11 | 15 | 11 | 11 | 62a9fa8952a3d8293a8619fff2b6be922c8cc56d | bigcode/the-stack | train |
93014306e9745a555ca11519 | train | class | class RawTransactionsTest(BitcoinTestFramework):
def __init__(self):
super().__init__()
self.setup_clean_chain = True
self.num_nodes = 4
def setup_network(self, split=False):
self.setup_nodes()
connect_nodes_bi(self.nodes, 0, 1)
connect_nodes_bi(self.nodes, 1, ... | class RawTransactionsTest(BitcoinTestFramework):
| def __init__(self):
super().__init__()
self.setup_clean_chain = True
self.num_nodes = 4
def setup_network(self, split=False):
self.setup_nodes()
connect_nodes_bi(self.nodes, 0, 1)
connect_nodes_bi(self.nodes, 1, 2)
connect_nodes_bi(self.nodes, 0, 2)
... | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the fundrawtransaction RPC."""
from test_framework.test_framework import BitcoinTestFramework, BI... | 141 | 256 | 8,013 | 9 | 132 | tomkoker/teddycoin | test/functional/fundrawtransaction.py | Python | RawTransactionsTest | RawTransactionsTest | 18 | 721 | 18 | 19 | 1d19baacabe322ba63a6fcf344605482a73b34c6 | bigcode/the-stack | train |
50838c588bc405c67f0e02ca | train | function | def read_csv(path):
with open(path, 'r', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
_headers = next(reader, None)
# get column
_columns = {}
for h in _headers:
_columns[h] = []
for row in reader:
for h, v in zip(... | def read_csv(path):
| with open(path, 'r', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
_headers = next(reader, None)
# get column
_columns = {}
for h in _headers:
_columns[h] = []
for row in reader:
for h, v in zip(_headers, row):
... | import sys
import pandas as pd
from collections import OrderedDict
from bokeh.io import show, output_file
from bokeh.plotting import figure
from bokeh.models import HoverTool, CDSView, IndexFilter, ColumnDataSource
from bokeh.transform import factor_cmap
def read_csv(path):
| 64 | 64 | 112 | 5 | 58 | hubmapconsortium/vccf-visualization-2022- | visualization/kidney_distance_bokeh_cover.py | Python | read_csv | read_csv | 12 | 28 | 12 | 12 | 3f0154ac4b2980a0cb61c3c4f4d3d694c0772a84 | bigcode/the-stack | train |
a76ffcac8d3ee0b39df0e25b | train | class | class DiscriminativeLoss(_Loss):
def __init__(self, delta_var=0.5, delta_dist=1.5, norm=2, alpha=1.0, beta=1.0, gamma=0.001,
usegpu=False, size_average=True):
super(DiscriminativeLoss, self).__init__(reduction='mean')
self.delta_var = delta_var
self.delta_dist = delta_dist
... | class DiscriminativeLoss(_Loss):
| def __init__(self, delta_var=0.5, delta_dist=1.5, norm=2, alpha=1.0, beta=1.0, gamma=0.001,
usegpu=False, size_average=True):
super(DiscriminativeLoss, self).__init__(reduction='mean')
self.delta_var = delta_var
self.delta_dist = delta_dist
self.norm = norm
s... | from torch.nn.modules.loss import _Loss
import torch
import torch.nn.functional as F
class DiscriminativeLoss(_Loss):
| 27 | 256 | 903 | 8 | 18 | RajArPatra/Lane_Segmentation | Code/loss/discriminative.py | Python | DiscriminativeLoss | DiscriminativeLoss | 5 | 90 | 5 | 6 | ba7fdca7a4da6838bb67d49da8f74ef4fbaa131b | bigcode/the-stack | train |
b8ceff60d17f58a992c42246 | train | class | class FakeDS8KProxy(ds8kproxy.DS8KProxy):
"""Fake IBM DS8K Proxy Driver."""
def __init__(self, storage_info, logger, exception,
driver=None, active_backend_id=None,
HTTPConnectorObject=None, host=TEST_HOST_1):
with mock.patch.object(proxy.IBMStorageProxy,
... | class FakeDS8KProxy(ds8kproxy.DS8KProxy):
| """Fake IBM DS8K Proxy Driver."""
def __init__(self, storage_info, logger, exception,
driver=None, active_backend_id=None,
HTTPConnectorObject=None, host=TEST_HOST_1):
with mock.patch.object(proxy.IBMStorageProxy,
'_get_safely_from_config... | (replication.Replication):
"""Fake Replication class."""
def __init__(self, source_helper, device):
self._source_helper = source_helper
if device.get('connection_type') == storage.XIV_CONNECTION_TYPE_FC:
self._target_helper = FakeDS8KReplTargetHelper(device)
else:
... | 126 | 126 | 421 | 16 | 110 | traghavendra/cinder-train | cinder/tests/unit/volume/drivers/ibm/test_ds8k_proxy.py | Python | FakeDS8KProxy | FakeDS8KProxy | 1,035 | 1,081 | 1,035 | 1,035 | 8a1e84680c25a60333237c796c1b7c401700282f | bigcode/the-stack | train |
c243507125a1184e038a779f | train | class | class FakeReplication(replication.Replication):
"""Fake Replication class."""
def __init__(self, source_helper, device):
self._source_helper = source_helper
if device.get('connection_type') == storage.XIV_CONNECTION_TYPE_FC:
self._target_helper = FakeDS8KReplTargetHelper(device)
... | class FakeReplication(replication.Replication):
| """Fake Replication class."""
def __init__(self, source_helper, device):
self._source_helper = source_helper
if device.get('connection_type') == storage.XIV_CONNECTION_TYPE_FC:
self._target_helper = FakeDS8KReplTargetHelper(device)
else:
self._target_helper = Fak... | pass
class FakeDS8KReplTargetECKDHelper(FakeDS8KECKDHelper,
helper.DS8KReplicationTargetECKDHelper):
"""Fake IBM DS8K Replication Target ECKD Helper."""
pass
class FakeReplication(replication.Replication):
| 64 | 64 | 113 | 9 | 54 | traghavendra/cinder-train | cinder/tests/unit/volume/drivers/ibm/test_ds8k_proxy.py | Python | FakeReplication | FakeReplication | 1,022 | 1,032 | 1,022 | 1,022 | 478bf82b90ee808493bef0b319eed360c2a157a2 | bigcode/the-stack | train |
3ce6de7ef5b0528316dd0579 | train | class | class FakeDS8KReplTargetHelper(FakeDS8KReplSourceHelper,
helper.DS8KReplicationTargetHelper):
"""Fake IBM DS8K Replication Target Helper."""
pass
| class FakeDS8KReplTargetHelper(FakeDS8KReplSourceHelper,
helper.DS8KReplicationTargetHelper):
| """Fake IBM DS8K Replication Target Helper."""
pass
| SourceHelper(FakeDS8KCommonHelper,
helper.DS8KReplicationSourceHelper):
"""Fake IBM DS8K Replication Target Helper."""
pass
class FakeDS8KReplTargetHelper(FakeDS8KReplSourceHelper,
helper.DS8KReplicationTargetHelper):
| 64 | 64 | 44 | 29 | 34 | traghavendra/cinder-train | cinder/tests/unit/volume/drivers/ibm/test_ds8k_proxy.py | Python | FakeDS8KReplTargetHelper | FakeDS8KReplTargetHelper | 1,008 | 1,012 | 1,008 | 1,009 | b8fc471d00469f4aa2c74db6150cc895c7496774 | bigcode/the-stack | train |
a9736ebde621e7d51f4abf83 | train | class | class FakeDS8KECKDHelper(FakeDS8KCommonHelper, helper.DS8KECKDHelper):
"""Fake IBM DS8K ECKD Helper."""
pass
| class FakeDS8KECKDHelper(FakeDS8KCommonHelper, helper.DS8KECKDHelper):
| """Fake IBM DS8K ECKD Helper."""
pass
| self._get_value('san_login'),
self._get_value('san_password'),
None, True)
self.backend['rest_version'] = self._get_version()['bundle_version']
class FakeDS8KECKDHelper(FakeDS8KCommonHelper... | 64 | 64 | 40 | 25 | 39 | traghavendra/cinder-train | cinder/tests/unit/volume/drivers/ibm/test_ds8k_proxy.py | Python | FakeDS8KECKDHelper | FakeDS8KECKDHelper | 995 | 998 | 995 | 995 | 6c76b4f38ee3d14dfba64b09751221bf911ac32d | bigcode/the-stack | train |
ae81f7f9ed6d877768792503 | train | class | @ddt.ddt
class DS8KProxyTest(test.TestCase):
"""Test proxy for DS8K volume driver."""
VERSION = "2.0.0"
def setUp(self):
"""Initialize IBM DS8K Driver."""
super(DS8KProxyTest, self).setUp()
self.ctxt = context.get_admin_context()
self.configuration = mock.Mock(conf.Configu... | @ddt.ddt
class DS8KProxyTest(test.TestCase):
| """Test proxy for DS8K volume driver."""
VERSION = "2.0.0"
def setUp(self):
"""Initialize IBM DS8K Driver."""
super(DS8KProxyTest, self).setUp()
self.ctxt = context.get_admin_context()
self.configuration = mock.Mock(conf.Configuration)
self.configuration.connection... | {}
self._host = host
self.setup(None)
def setup(self, context):
connection_type = self.configuration.connection_type
repl_devices = getattr(self.configuration, 'replication_device', None)
if connection_type == storage.XIV_CONNECTION_TYPE_FC:
if not repl_devices:... | 256 | 256 | 34,122 | 16 | 239 | traghavendra/cinder-train | cinder/tests/unit/volume/drivers/ibm/test_ds8k_proxy.py | Python | DS8KProxyTest | DS8KProxyTest | 1,084 | 4,466 | 1,084 | 1,085 | f2104438cf02483d435f178f1fa0333237fa8ef7 | bigcode/the-stack | train |
a1a198de8ea1f658122a2a18 | train | class | class FakeDefaultRESTConnector(restclient.DefaultRESTConnector):
"""Fake the Default Connector."""
def connect(self):
pass
def send(self, method='', url='', headers=None, payload='', timeout=900):
host = url.split('https://')[1].split(':8452')[0]
endpoint = url.split('v1')[1].split... | class FakeDefaultRESTConnector(restclient.DefaultRESTConnector):
| """Fake the Default Connector."""
def connect(self):
pass
def send(self, method='', url='', headers=None, payload='', timeout=900):
host = url.split('https://')[1].split(':8452')[0]
endpoint = url.split('v1')[1].split('?')[0]
start = url.index('type') if 'type=' in url else... | Bid=' + TEST_HOST_ID + '%5D/delete':
FAKE_DELETE_HOSTS_RESPONSE,
TEST_TARGET_DS8K_IP + '/hosts%5Bid=' + TEST_HOST_ID + '%5D/delete':
FAKE_DELETE_HOSTS_RESPONSE
}
class FakeDefaultRESTConnector(restclient.DefaultRESTConnector):
| 64 | 64 | 159 | 11 | 53 | traghavendra/cinder-train | cinder/tests/unit/volume/drivers/ibm/test_ds8k_proxy.py | Python | FakeDefaultRESTConnector | FakeDefaultRESTConnector | 936 | 951 | 936 | 936 | 55102e6ae48a8b9adb26610ac6347e50d989fa56 | bigcode/the-stack | train |
6a12b7a2ac7c5c0b7acd107a | train | class | class FakeRESTScheduler(restclient.RESTScheduler):
"""Fake REST Scheduler."""
def __init__(self, host, user, passw, connector_obj, verify=False):
self.token = ''
self.host = host
self.port = '8452'
self.user = user
self.passw = passw
self.connector = connector_ob... | class FakeRESTScheduler(restclient.RESTScheduler):
| """Fake REST Scheduler."""
def __init__(self, host, user, passw, connector_obj, verify=False):
self.token = ''
self.host = host
self.port = '8452'
self.user = user
self.passw = passw
self.connector = connector_obj or FakeDefaultRESTConnector(verify)
self.... | :].split('&')[0].split('=')[1]
else:
type_str = ''
request = host + endpoint + '/' + type_str + method.lower()
return 200, json.dumps(FAKE_REST_API_RESPONSES[request])
class FakeRESTScheduler(restclient.RESTScheduler):
| 64 | 64 | 87 | 10 | 54 | traghavendra/cinder-train | cinder/tests/unit/volume/drivers/ibm/test_ds8k_proxy.py | Python | FakeRESTScheduler | FakeRESTScheduler | 954 | 964 | 954 | 954 | 03e1cf1857aec84f51c57a45467f0ab5f7136cf5 | bigcode/the-stack | train |
679f44ecbab7b21bf22409f1 | train | class | class FakeDS8KReplTargetECKDHelper(FakeDS8KECKDHelper,
helper.DS8KReplicationTargetECKDHelper):
"""Fake IBM DS8K Replication Target ECKD Helper."""
pass
| class FakeDS8KReplTargetECKDHelper(FakeDS8KECKDHelper,
helper.DS8KReplicationTargetECKDHelper):
| """Fake IBM DS8K Replication Target ECKD Helper."""
pass
| ReplSourceHelper,
helper.DS8KReplicationTargetHelper):
"""Fake IBM DS8K Replication Target Helper."""
pass
class FakeDS8KReplTargetECKDHelper(FakeDS8KECKDHelper,
helper.DS8KReplicationTargetECKDHelper):
| 64 | 64 | 52 | 34 | 29 | traghavendra/cinder-train | cinder/tests/unit/volume/drivers/ibm/test_ds8k_proxy.py | Python | FakeDS8KReplTargetECKDHelper | FakeDS8KReplTargetECKDHelper | 1,015 | 1,019 | 1,015 | 1,016 | 179686d52c494b40b49e09c2bffd953f2e931baf | bigcode/the-stack | train |
32c8895a8aa2dc22af986039 | train | class | class FakeDS8KCommonHelper(helper.DS8KCommonHelper):
"""Fake IBM DS8K Helper."""
def __init__(self, conf, HTTPConnectorObject=None):
self.conf = conf
self._connector_obj = HTTPConnectorObject
self._connection_type = self._get_value('connection_type')
self._storage_pools = None
... | class FakeDS8KCommonHelper(helper.DS8KCommonHelper):
| """Fake IBM DS8K Helper."""
def __init__(self, conf, HTTPConnectorObject=None):
self.conf = conf
self._connector_obj = HTTPConnectorObject
self._connection_type = self._get_value('connection_type')
self._storage_pools = None
self.backend = {}
self.setup()
... | self.token = ''
self.host = host
self.port = '8452'
self.user = user
self.passw = passw
self.connector = connector_obj or FakeDefaultRESTConnector(verify)
self.connect()
class FakeDS8KCommonHelper(helper.DS8KCommonHelper):
| 66 | 66 | 223 | 15 | 51 | traghavendra/cinder-train | cinder/tests/unit/volume/drivers/ibm/test_ds8k_proxy.py | Python | FakeDS8KCommonHelper | FakeDS8KCommonHelper | 967 | 992 | 967 | 967 | a38c2e5e6abebfabe1b4dc55b38b6b184cc488a6 | bigcode/the-stack | train |
6898eb474c96f62efe67ba3c | train | class | class FakeDS8KReplSourceHelper(FakeDS8KCommonHelper,
helper.DS8KReplicationSourceHelper):
"""Fake IBM DS8K Replication Target Helper."""
pass
| class FakeDS8KReplSourceHelper(FakeDS8KCommonHelper,
helper.DS8KReplicationSourceHelper):
| """Fake IBM DS8K Replication Target Helper."""
pass
| 8KECKDHelper(FakeDS8KCommonHelper, helper.DS8KECKDHelper):
"""Fake IBM DS8K ECKD Helper."""
pass
class FakeDS8KReplSourceHelper(FakeDS8KCommonHelper,
helper.DS8KReplicationSourceHelper):
| 64 | 64 | 42 | 27 | 36 | traghavendra/cinder-train | cinder/tests/unit/volume/drivers/ibm/test_ds8k_proxy.py | Python | FakeDS8KReplSourceHelper | FakeDS8KReplSourceHelper | 1,001 | 1,005 | 1,001 | 1,002 | 1264c0c5076c3ef717a83525054738349c86f0b9 | bigcode/the-stack | train |
5ceb0228d32a7bdbac9e788e | train | class | class Configuration(object): # pylint: disable=too-many-instance-attributes
"""
Represents a configuration of a test bench
"""
def __init__(self, # pylint: disable=too-many-arguments
name,
design_unit,
generics=None,
sim_options=None,... | class Configuration(object): # pylint: disable=too-many-instance-attributes
| """
Represents a configuration of a test bench
"""
def __init__(self, # pylint: disable=too-many-arguments
name,
design_unit,
generics=None,
sim_options=None,
pre_config=None,
post_check=None):
... | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (c) 2014-2018, Lars Asplund lars.anders.asplund@gmail.com
"""
Contains Configuration class which contains ... | 158 | 256 | 872 | 16 | 141 | bjacobs1/vunit | vunit/configuration.py | Python | Configuration | Configuration | 24 | 153 | 24 | 24 | bfeb0ec83aa37724d84a13c4e457befa045aeaa2 | bigcode/the-stack | train |
a3db0bd9c126c38d65a546c7 | train | class | class ConfigurationVisitor(object):
"""
An interface to visit simulation run configurations
"""
def _check_enabled(self):
pass
@staticmethod
def get_configuration_dicts():
raise NotImplementedError
def set_generic(self, name, value):
"""
Set generic
... | class ConfigurationVisitor(object):
| """
An interface to visit simulation run configurations
"""
def _check_enabled(self):
pass
@staticmethod
def get_configuration_dicts():
raise NotImplementedError
def set_generic(self, name, value):
"""
Set generic
"""
self._check_enabled()
... |
def call_post_check(self, output_path, read_output):
"""
Call post_check if available. Setting optional output_path
"""
if self.post_check is None:
return True
args = inspect.getargspec(self.post_check).args # pylint: disable=deprecated-method
kwargs ... | 134 | 134 | 449 | 5 | 128 | bjacobs1/vunit | vunit/configuration.py | Python | ConfigurationVisitor | ConfigurationVisitor | 156 | 233 | 156 | 156 | 5033fc6212eccb5a9e48eafe2cf08af319255a6a | bigcode/the-stack | train |
84264c4edf818d3b467f6b22 | train | function | def soft_round(x: torch.Tensor, alpha: float, eps: float = 1e-3) -> torch.Tensor:
"""Differentiable approximation of ``torch.round``.
A larger ``alpha`` correspond to a closer approximation of ``round``. If
``alpha`` is close to zero, this function reduces to the identity.
This operation is descri... | def soft_round(x: torch.Tensor, alpha: float, eps: float = 1e-3) -> torch.Tensor:
| """Differentiable approximation of ``torch.round``.
A larger ``alpha`` correspond to a closer approximation of ``round``. If
``alpha`` is close to zero, this function reduces to the identity.
This operation is described in Sec. 4.1. in the paper:
> "Universally Quantized Neural Compression"<b... | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch
def soft_round(x: torch.Tensor, alpha: float, eps: float = 1e-3) -> torch.Tensor:
| 69 | 76 | 255 | 26 | 42 | tallamjr/NeuralCompression | neuralcompression/functional/_soft_round.py | Python | soft_round | soft_round | 9 | 37 | 9 | 9 | edccb9330d6160bbdaeb11e0c4a5eda0d3b5264e | bigcode/the-stack | train |
b0e29c29fe07a593fe607e69 | train | function | def get_test_name(testset_name, testset_index, subtask_index, test_index, test_offset, line):
return (testset_name if subtask_index < 0 else str(subtask_index)) + "-%02d" % test_offset
| def get_test_name(testset_name, testset_index, subtask_index, test_index, test_offset, line):
| return (testset_name if subtask_index < 0 else str(subtask_index)) + "-%02d" % test_offset
| import sys
def get_test_name(testset_name, testset_index, subtask_index, test_index, test_offset, line):
| 27 | 64 | 53 | 24 | 2 | Grackins/tps | samples/TwoSteps/coins/scripts/templates/test_name.py | Python | get_test_name | get_test_name | 4 | 5 | 4 | 4 | e056cfd44445ee80700558d1b271e58e5be4b58c | bigcode/the-stack | train |
8059afd12966dbdd51e0d760 | train | class | @admin.register(GitHubHookConf)
class GitHubHookConfAdmin(admin.ModelAdmin):
fields = ('name', 'url', 'paths', 'install')
| @admin.register(GitHubHookConf)
class GitHubHookConfAdmin(admin.ModelAdmin):
| fields = ('name', 'url', 'paths', 'install')
| from django.contrib import admin
from .models import GitHubHookConf
# Register your models here.
@admin.register(GitHubHookConf)
class GitHubHookConfAdmin(admin.ModelAdmin):
| 40 | 64 | 34 | 19 | 21 | Alexoner/sloth | sloth_hook/admin.py | Python | GitHubHookConfAdmin | GitHubHookConfAdmin | 6 | 8 | 6 | 7 | 516cdebbbcb0ae1fdea8f97edcfd6f40fcc072e2 | bigcode/the-stack | train |
600fc9e999e9334976860e46 | train | function | def makeExtension(**kwargs):
return BleachExtension(**kwargs)
| def makeExtension(**kwargs):
| return BleachExtension(**kwargs)
| # -*- coding: utf-8 -*-
from .extension import BleachExtension
VERSION = '0.1.4'
def makeExtension(**kwargs):
| 31 | 64 | 14 | 6 | 25 | PudgyPoppins/AP-Crowd-2020 | wiki/extensions/bleach/__init__.py | Python | makeExtension | makeExtension | 8 | 9 | 8 | 8 | 6006a757bc2eb3bf3cf8b222530dc1ca74dfc563 | bigcode/the-stack | train |
03a564aa3fe0a04f9b229979 | train | function | @login_manager.user_loader
def load_user(id):
return User.query.get(int(id))
| @login_manager.user_loader
def load_user(id):
| return User.query.get(int(id))
| country):
self.name = name
self.country = country
class Country(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
def __init__(self, name):
self.name = name
@login_manager.user_loader
def load_user(id):
| 64 | 64 | 18 | 10 | 53 | exit107/run | run/models.py | Python | load_user | load_user | 304 | 306 | 304 | 305 | 037b214d8bbd96dd8f47eb7f4ca08d716b7d1dbc | bigcode/the-stack | train |
03b69b3a6443f5d01f0f7c54 | train | class | class Run(db.Model):
id = db.Column(db.Integer, primary_key=True)
start_time = db.Column(db.DateTime)
total_timer_time = db.Column(db.Numeric(scale=2))
total_elapsed_time = db.Column(db.Numeric(scale=2))
# Dynamic Properties
# total_ascent = db.Column(db.Numeric(scale=1))
# total_descent = d... | class Run(db.Model):
| id = db.Column(db.Integer, primary_key=True)
start_time = db.Column(db.DateTime)
total_timer_time = db.Column(db.Numeric(scale=2))
total_elapsed_time = db.Column(db.Numeric(scale=2))
# Dynamic Properties
# total_ascent = db.Column(db.Numeric(scale=1))
# total_descent = db.Column(db.Numeric(s... | [0].distance
@property
def distance_in_miles(self):
distance = Q_(self.distance, ureg.meter)
return distance.to(ureg.mile).magnitude
@property
def start_position(self):
return {
'longitude': self.points[0].longitude,
'latitude': self.points[0].latitude
... | 194 | 194 | 649 | 5 | 188 | exit107/run | run/models.py | Python | Run | Run | 188 | 269 | 188 | 188 | 1e1f18d1f5d6be9d0a933e50aceb45bc19aca2a4 | bigcode/the-stack | train |
4b6f360ab3e1e2c79a456012 | train | class | class Country(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
def __init__(self, name):
self.name = name
| class Country(db.Model):
| id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
def __init__(self, name):
self.name = name
| .Column(db.String)
country_id = db.Column(db.Integer, db.ForeignKey('country.id'))
country = db.relationship('Country', backref=db.backref('states'))
def __init__(self, name, country):
self.name = name
self.country = country
class Country(db.Model):
| 64 | 64 | 40 | 5 | 58 | exit107/run | run/models.py | Python | Country | Country | 296 | 301 | 296 | 296 | df35f66759e7b25378ccedfaa376c0dfffadbc4a | bigcode/the-stack | train |
1559b2737b35ffe1e86cbea8 | train | class | class State(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
country_id = db.Column(db.Integer, db.ForeignKey('country.id'))
country = db.relationship('Country', backref=db.backref('states'))
def __init__(self, name, country):
self.name = name
sel... | class State(db.Model):
| id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
country_id = db.Column(db.Integer, db.ForeignKey('country.id'))
country = db.relationship('Country', backref=db.backref('states'))
def __init__(self, name, country):
self.name = name
self.country = country
| .Column(db.String)
state_id = db.Column(db.Integer, db.ForeignKey('state.id'))
state = db.relationship('State', backref=db.backref('cities'))
def __init__(self, name, state):
self.name = name
self.state = state
class State(db.Model):
| 64 | 64 | 80 | 5 | 58 | exit107/run | run/models.py | Python | State | State | 284 | 293 | 284 | 284 | 43603f0fe7f35e3363c5c2b2bc5cba469f73170a | bigcode/the-stack | train |
0f38d7866834f2f2ebc48161 | train | class | class City(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
state_id = db.Column(db.Integer, db.ForeignKey('state.id'))
state = db.relationship('State', backref=db.backref('cities'))
def __init__(self, name, state):
self.name = name
self.state = s... | class City(db.Model):
| id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
state_id = db.Column(db.Integer, db.ForeignKey('state.id'))
state = db.relationship('State', backref=db.backref('cities'))
def __init__(self, name, state):
self.name = name
self.state = state
| ref('runs'))
city_id = db.Column(db.Integer, db.ForeignKey('city.id'))
city = db.relationship('City', backref=db.backref('runs'))
def __init__(self, city, user):
self.city = city
self.user = user
class City(db.Model):
| 64 | 64 | 80 | 5 | 58 | exit107/run | run/models.py | Python | City | City | 272 | 281 | 272 | 272 | 2bf962c0ca970018a79b978d13907b52707ad79b | bigcode/the-stack | train |
f4ba7c01bd0ed871d8d19e47 | train | class | class Leg(db.Model):
id = db.Column(db.Integer, primary_key=True)
# Dynamic Properties
# total_ascent = db.Column(db.Numeric(scale=1))
# total_descent = db.Column(db.Numeric(scale=1))
@property
def centroid(self):
latitude = db.session.query(func.avg(Point.latitude)).filter(Point.run_id ... | class Leg(db.Model):
| id = db.Column(db.Integer, primary_key=True)
# Dynamic Properties
# total_ascent = db.Column(db.Numeric(scale=1))
# total_descent = db.Column(db.Numeric(scale=1))
@property
def centroid(self):
latitude = db.session.query(func.avg(Point.latitude)).filter(Point.run_id == self.id).scalar()
... | timestamp_to_datetime(self, timestamp):
'''Convert a string to a datetime instance'''
utc_time = pendulum.instance(timestamp)
return utc_time
#TODO: Move lat long into one var: coords
def __init__(self, timestamp, elevation, latitude,
longitude, distance, speed, leg, r... | 180 | 180 | 601 | 5 | 174 | exit107/run | run/models.py | Python | Leg | Leg | 111 | 185 | 111 | 111 | 44e97f31472dbdfd6337666b10a253c15f64d436 | bigcode/the-stack | train |
c77bbd5e79c183450cac06d6 | train | class | class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String, index=True, unique=True)
email = db.Column(db.String, index=True, unique=True)
password_hash = db.Column(db.String)
created_on = db.Column(db.DateTime)
last_login = db.Column(db.DateTim... | class User(UserMixin, db.Model):
| id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String, index=True, unique=True)
email = db.Column(db.String, index=True, unique=True)
password_hash = db.Column(db.String)
created_on = db.Column(db.DateTime)
last_login = db.Column(db.DateTime)
def set_password(self, pa... | pylint: disable=missing-class-docstring
from datetime import datetime
from flask_login import UserMixin
import pendulum
from sqlalchemy import func
from werkzeug.security import generate_password_hash, check_password_hash
from run import db, ureg, Q_, login_manager
class User(UserMixin, db.Model):
| 64 | 64 | 187 | 8 | 55 | exit107/run | run/models.py | Python | User | User | 15 | 39 | 15 | 15 | b10b1de68150b02e5f754e2e37071a6b94d44e14 | bigcode/the-stack | train |
9a29b7bf1ee1d93020cba138 | train | class | class Point(db.Model):
id = db.Column(db.Integer, primary_key=True)
timestamp = db.Column(db.DateTime, nullable=False)
elevation = db.Column(db.Numeric)
latitude = db.Column(db.Float)
longitude = db.Column(db.Float)
distance = db.Column(db.Numeric)
speed = db.Column(db.Numeric)
# prec... | class Point(db.Model):
| id = db.Column(db.Integer, primary_key=True)
timestamp = db.Column(db.DateTime, nullable=False)
elevation = db.Column(db.Numeric)
latitude = db.Column(db.Float)
longitude = db.Column(db.Float)
distance = db.Column(db.Numeric)
speed = db.Column(db.Numeric)
# precipitation = db.Column(d... | , unique=True)
email = db.Column(db.String, index=True, unique=True)
password_hash = db.Column(db.String)
created_on = db.Column(db.DateTime)
last_login = db.Column(db.DateTime)
def set_password(self, password):
"""Create hashed password."""
self.password_hash = generate_password_ha... | 162 | 162 | 542 | 5 | 157 | exit107/run | run/models.py | Python | Point | Point | 42 | 108 | 42 | 42 | 9db49b76250516678da21b9ecd8a2f4cd55ae9ec | bigcode/the-stack | train |
796b4c6ef38e85d4f3e9970b | train | class | class ResetUserPasswrodResponse(SdkResponse):
"""
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.
"""
... | class ResetUserPasswrodResponse(SdkResponse):
| """
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 re
import six
from huaweicloudsdkcore.sdk_response import SdkResponse
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class ResetUserPasswrodResponse(SdkResponse):
| 53 | 140 | 467 | 12 | 40 | huaweicloud/huaweicloud-sdk-python-v3 | huaweicloud-sdk-kafka/huaweicloudsdkkafka/v2/model/reset_user_passwrod_response.py | Python | ResetUserPasswrodResponse | ResetUserPasswrodResponse | 11 | 85 | 11 | 13 | eaaba8667b7418c9ec4bb9beed55f37782cfcbd9 | bigcode/the-stack | train |
5a5f0891580ab7e17e4bde2a | train | function | @pytest.mark.parametrize("window_size", [5, 11])
@pytest.mark.parametrize("sigma", [1.5, 5.0])
def test_get_gaussian_kernel(window_size, sigma):
kernel = image.get_gaussian_kernel(window_size, sigma)
assert kernel.shape == (window_size,)
assert kernel.sum().item() == pytest.approx(1.0)
| @pytest.mark.parametrize("window_size", [5, 11])
@pytest.mark.parametrize("sigma", [1.5, 5.0])
def test_get_gaussian_kernel(window_size, sigma):
| kernel = image.get_gaussian_kernel(window_size, sigma)
assert kernel.shape == (window_size,)
assert kernel.sum().item() == pytest.approx(1.0)
| torchgeometry.image as image
from torch.autograd import gradcheck
import utils
from common import TEST_DEVICES
@pytest.mark.parametrize("window_size", [5, 11])
@pytest.mark.parametrize("sigma", [1.5, 5.0])
def test_get_gaussian_kernel(window_size, sigma):
| 64 | 64 | 78 | 40 | 23 | kajal-puri/torchgeometry | test/test_image.py | Python | test_get_gaussian_kernel | test_get_gaussian_kernel | 11 | 16 | 11 | 13 | ae3cd0f31d8c5283b1808d06951506b8bdc13240 | bigcode/the-stack | train |
c5dc780bc7e77007a1d6dfd1 | train | class | class TestGaussianBlur:
@pytest.mark.parametrize("device_type", TEST_DEVICES)
@pytest.mark.parametrize("batch_shape",
[(1, 4, 8, 15), (2, 3, 11, 7)])
def test_gaussian_blur(self, batch_shape, device_type):
kernel_size = (5, 7)
sigma = (1.5, 2.1)
input = ... | class TestGaussianBlur:
@pytest.mark.parametrize("device_type", TEST_DEVICES)
@pytest.mark.parametrize("batch_shape",
[(1, 4, 8, 15), (2, 3, 11, 7)])
| def test_gaussian_blur(self, batch_shape, device_type):
kernel_size = (5, 7)
sigma = (1.5, 2.1)
input = torch.rand(batch_shape).to(torch.device(device_type))
gauss = image.GaussianBlur(kernel_size, sigma)
assert gauss(input).shape == batch_shape
def test_gradcheck(self)... | )
assert kernel.sum().item() == pytest.approx(1.0)
class TestGaussianBlur:
@pytest.mark.parametrize("device_type", TEST_DEVICES)
@pytest.mark.parametrize("batch_shape",
[(1, 4, 8, 15), (2, 3, 11, 7)])
| 69 | 69 | 233 | 52 | 17 | kajal-puri/torchgeometry | test/test_image.py | Python | TestGaussianBlur | TestGaussianBlur | 29 | 51 | 29 | 32 | 648418ead14a0389ab537f76f884df9a3f05c111 | bigcode/the-stack | train |
0882e8bcd48476ef57374002 | train | function | @pytest.mark.parametrize("ksize_x", [5, 11])
@pytest.mark.parametrize("ksize_y", [3, 7])
@pytest.mark.parametrize("sigma", [1.5, 2.1])
def test_get_gaussian_kernel2d(ksize_x, ksize_y, sigma):
kernel = image.get_gaussian_kernel2d(
(ksize_x, ksize_y), (sigma, sigma))
assert kernel.shape == (ksize_x, ksize... | @pytest.mark.parametrize("ksize_x", [5, 11])
@pytest.mark.parametrize("ksize_y", [3, 7])
@pytest.mark.parametrize("sigma", [1.5, 2.1])
def test_get_gaussian_kernel2d(ksize_x, ksize_y, sigma):
| kernel = image.get_gaussian_kernel2d(
(ksize_x, ksize_y), (sigma, sigma))
assert kernel.shape == (ksize_x, ksize_y)
assert kernel.sum().item() == pytest.approx(1.0)
| )
@pytest.mark.parametrize("ksize_x", [5, 11])
@pytest.mark.parametrize("ksize_y", [3, 7])
@pytest.mark.parametrize("sigma", [1.5, 2.1])
def test_get_gaussian_kernel2d(ksize_x, ksize_y, sigma):
| 64 | 64 | 119 | 63 | 1 | kajal-puri/torchgeometry | test/test_image.py | Python | test_get_gaussian_kernel2d | test_get_gaussian_kernel2d | 19 | 26 | 19 | 22 | e3b4e990191d4abc4fc066b62807dc4c7fc730c9 | bigcode/the-stack | train |
409a5cc1f3761e235281f97a | train | class | class Test(unittest.TestCase):
def test_invalid_input(self):
class SomeService(ServiceBase):
@srpc()
def yay():
pass
app = Application([SomeService], 'tns',
in_protocol=YamlDocument(),
out_protoc... | class Test(unittest.TestCase):
| def test_invalid_input(self):
class SomeService(ServiceBase):
@srpc()
def yay():
pass
app = Application([SomeService], 'tns',
in_protocol=YamlDocument(),
out_protocol=YamlDocument())
ser... | from spyne.service import ServiceBase
from spyne.server import ServerBase
from spyne.protocol.yaml import yaml
yaml.dumps = yaml.dump
yaml.loads = yaml.load
TestYamlDocument = TDictDocumentTest(yaml, YamlDocument, YamlDocument().out_kwargs)
class Test(unittest.TestCase):
| 64 | 64 | 109 | 6 | 58 | infoxchange/spyne | spyne/test/protocol/test_yaml.py | Python | Test | Test | 38 | 54 | 38 | 38 | 99427cbd55731fadcba383f1b529471962dbbef6 | bigcode/the-stack | train |
0908a63da5258852e850cb23 | train | class | class PrecisionRecallCurve(Metric):
"""
Computes precision-recall pairs for different thresholds. Works for both
binary and multiclass problems. In the case of multiclass, the values will
be calculated based on a one-vs-the-rest approach.
Forward accepts
- ``preds`` (float tensor): ``(N, ...)`... | class PrecisionRecallCurve(Metric):
| """
Computes precision-recall pairs for different thresholds. Works for both
binary and multiclass problems. In the case of multiclass, the values will
be calculated based on a one-vs-the-rest approach.
Forward accepts
- ``preds`` (float tensor): ``(N, ...)`` (binary) or ``(N, C, ...)`` (multi... | # Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | 202 | 256 | 1,297 | 7 | 194 | alanhdu/metrics | torchmetrics/classification/precision_recall_curve.py | Python | PrecisionRecallCurve | PrecisionRecallCurve | 27 | 148 | 27 | 27 | 2d3ead68bf865c5b8a6b939b32c621376f133ea3 | bigcode/the-stack | train |
403b024784e569ef6a511d53 | train | class | class DriverSaltlocal:
def __init__(self):
self.opts = {}
self.name = ""
def cmd(self):
print ("cmd")
| class DriverSaltlocal:
| def __init__(self):
self.opts = {}
self.name = ""
def cmd(self):
print ("cmd")
| class DriverSaltlocal:
| 5 | 64 | 32 | 5 | 0 | terminal-labs/fuzzball | src/fuzzball/drivers/driver_local_external_salt.py | Python | DriverSaltlocal | DriverSaltlocal | 1 | 8 | 1 | 2 | 2291fd5c9751a4beb46fc41ce62164e29ae59c2c | bigcode/the-stack | train |
db68a4255a4605b6c6c08075 | train | function | def mk_pjt_files(dirname):
files_to_write = {
'project.py': PJT_TEMPLATE,
'settings.py': SETTINGS_TEMPLATE,
'dist_settings.py': DIST_SETTINGS_TEMPLATE,
'tests.py': TEST_TEMPLATE,
}
ctx = dict()
for fname, template in files_to_write.items():
full_name = os.path.j... | def mk_pjt_files(dirname):
| files_to_write = {
'project.py': PJT_TEMPLATE,
'settings.py': SETTINGS_TEMPLATE,
'dist_settings.py': DIST_SETTINGS_TEMPLATE,
'tests.py': TEST_TEMPLATE,
}
ctx = dict()
for fname, template in files_to_write.items():
full_name = os.path.join(dirname, fname)
... | import os
def new_project(dirname):
os.makedirs(dirname)
mk_pjt_files(dirname)
def mk_pjt_files(dirname):
| 27 | 64 | 96 | 7 | 20 | klausfmh/pypeman | pypeman/pjt_templates.py | Python | mk_pjt_files | mk_pjt_files | 9 | 23 | 9 | 10 | 21e265a8ea4f9152658cfb964ecd6ed1edcbeba2 | bigcode/the-stack | train |
473e40fb20782ac9706050cc | train | function | def new_project(dirname):
os.makedirs(dirname)
mk_pjt_files(dirname)
| def new_project(dirname):
| os.makedirs(dirname)
mk_pjt_files(dirname)
| import os
def new_project(dirname):
| 8 | 64 | 17 | 5 | 2 | klausfmh/pypeman | pypeman/pjt_templates.py | Python | new_project | new_project | 4 | 6 | 4 | 4 | 5a234000a75baba1af12c9e5ecdd389e3c4591e9 | bigcode/the-stack | train |
0ae59f4ab6f8aa13c6e30a3d | train | function | def _raise_on_error(result_code: int) -> None:
"""Raise error if error result."""
# pylint: disable=import-outside-toplevel
import paho.mqtt.client as mqtt
if result_code != 0:
raise HomeAssistantError(
f"Error talking to MQTT: {mqtt.error_string(result_code)}"
)
| def _raise_on_error(result_code: int) -> None:
| """Raise error if error result."""
# pylint: disable=import-outside-toplevel
import paho.mqtt.client as mqtt
if result_code != 0:
raise HomeAssistantError(
f"Error talking to MQTT: {mqtt.error_string(result_code)}"
)
| covery = self.hass.data[LAST_DISCOVERY]
last_subscribe = self._last_subscribe
wait_until = max(
last_discovery + DISCOVERY_COOLDOWN, last_subscribe + DISCOVERY_COOLDOWN
)
def _raise_on_error(result_code: int) -> None:
| 64 | 64 | 75 | 13 | 51 | mikan-megane/core | homeassistant/components/mqtt/__init__.py | Python | _raise_on_error | _raise_on_error | 956 | 964 | 956 | 956 | dbc1e1ef0f76c433bd6c9909aa27cd21aff27013 | bigcode/the-stack | train |
83654bb1d95dbda8c78ecaa1 | train | function | @websocket_api.async_response
@websocket_api.websocket_command(
{
vol.Required("type"): "mqtt/subscribe",
vol.Required("topic"): valid_subscribe_topic,
}
)
async def websocket_subscribe(hass, connection, msg):
"""Subscribe to a MQTT topic."""
if not connection.user.is_admin:
rais... | @websocket_api.async_response
@websocket_api.websocket_command(
{
vol.Required("type"): "mqtt/subscribe",
vol.Required("topic"): valid_subscribe_topic,
}
)
async def websocket_subscribe(hass, connection, msg):
| """Subscribe to a MQTT topic."""
if not connection.user.is_admin:
raise Unauthorized
async def forward_messages(mqttmsg: Message):
"""Forward events to websocket."""
connection.send_message(
websocket_api.event_message(
msg["id"],
{
... | ERR_NOT_FOUND, "Non MQTT device"
)
@websocket_api.async_response
@websocket_api.websocket_command(
{
vol.Required("type"): "mqtt/subscribe",
vol.Required("topic"): valid_subscribe_topic,
}
)
async def websocket_subscribe(hass, connection, msg):
| 64 | 64 | 189 | 53 | 11 | mikan-megane/core | homeassistant/components/mqtt/__init__.py | Python | websocket_subscribe | websocket_subscribe | 1,018 | 1,048 | 1,018 | 1,025 | ec0c66d4dda0d12fbb80ff46cc0997ea6a8efde6 | bigcode/the-stack | train |
e4cee19fa4faf7c317908986 | train | function | @bind_hass
def async_publish_template(
hass: HomeAssistant, topic, payload_template, qos=None, retain=None
) -> None:
"""Publish message to an MQTT topic using a template payload."""
data = _build_publish_data(topic, qos, retain)
data[ATTR_PAYLOAD_TEMPLATE] = payload_template
hass.async_create_task(... | @bind_hass
def async_publish_template(
hass: HomeAssistant, topic, payload_template, qos=None, retain=None
) -> None:
| """Publish message to an MQTT topic using a template payload."""
data = _build_publish_data(topic, qos, retain)
data[ATTR_PAYLOAD_TEMPLATE] = payload_template
hass.async_create_task(hass.services.async_call(DOMAIN, SERVICE_PUBLISH, data))
|
) -> None:
"""Publish message to an MQTT topic."""
hass.add_job(async_publish_template, hass, topic, payload_template, qos, retain)
@bind_hass
def async_publish_template(
hass: HomeAssistant, topic, payload_template, qos=None, retain=None
) -> None:
| 64 | 64 | 89 | 31 | 33 | mikan-megane/core | homeassistant/components/mqtt/__init__.py | Python | async_publish_template | async_publish_template | 278 | 285 | 278 | 281 | f85ee833916cfd0046e659568428c0f9d97a89be | bigcode/the-stack | train |
4c15b3ff193213ad6f379b41 | train | function | def _build_publish_data(topic: Any, qos: int, retain: bool) -> ServiceDataType:
"""Build the arguments for the publish service without the payload."""
data = {ATTR_TOPIC: topic}
if qos is not None:
data[ATTR_QOS] = qos
if retain is not None:
data[ATTR_RETAIN] = retain
return data
| def _build_publish_data(topic: Any, qos: int, retain: bool) -> ServiceDataType:
| """Build the arguments for the publish service without the payload."""
data = {ATTR_TOPIC: topic}
if qos is not None:
data[ATTR_QOS] = qos
if retain is not None:
data[ATTR_RETAIN] = retain
return data
| vol.Optional(ATTR_RETAIN, default=DEFAULT_RETAIN): cv.boolean,
},
required=True,
)
SubscribePayloadType = Union[str, bytes] # Only bytes if encoding is None
def _build_publish_data(topic: Any, qos: int, retain: bool) -> ServiceDataType:
| 64 | 64 | 82 | 22 | 41 | mikan-megane/core | homeassistant/components/mqtt/__init__.py | Python | _build_publish_data | _build_publish_data | 243 | 250 | 243 | 243 | b9ac156e4ab1a113f329b6df6e3f8b377228fa62 | bigcode/the-stack | train |
63d93c51735dda08dbac8610 | train | function | def _matcher_for_topic(subscription: str) -> Any:
# pylint: disable=import-outside-toplevel
from paho.mqtt.matcher import MQTTMatcher
matcher = MQTTMatcher()
matcher[subscription] = True
return lambda topic: next(matcher.iter_match(topic), False)
| def _matcher_for_topic(subscription: str) -> Any:
# pylint: disable=import-outside-toplevel
| from paho.mqtt.matcher import MQTTMatcher
matcher = MQTTMatcher()
matcher[subscription] = True
return lambda topic: next(matcher.iter_match(topic), False)
| paho.mqtt.client as mqtt
if result_code != 0:
raise HomeAssistantError(
f"Error talking to MQTT: {mqtt.error_string(result_code)}"
)
def _matcher_for_topic(subscription: str) -> Any:
# pylint: disable=import-outside-toplevel
| 64 | 64 | 63 | 24 | 40 | mikan-megane/core | homeassistant/components/mqtt/__init__.py | Python | _matcher_for_topic | _matcher_for_topic | 967 | 974 | 967 | 968 | f84d5785776c94495b8501f30bb50e0014867747 | bigcode/the-stack | train |
f11788b02488e94545ffa2e8 | train | function | async def async_setup_entry(hass, entry):
"""Load a config entry."""
conf = hass.data.get(DATA_MQTT_CONFIG)
# Config entry was created because user had configuration.yaml entry
# They removed that, so remove entry.
if conf is None and entry.source == config_entries.SOURCE_IMPORT:
hass.async... | async def async_setup_entry(hass, entry):
| """Load a config entry."""
conf = hass.data.get(DATA_MQTT_CONFIG)
# Config entry was created because user had configuration.yaml entry
# They removed that, so remove entry.
if conf is None and entry.source == config_entries.SOURCE_IMPORT:
hass.async_create_task(hass.config_entries.async_rem... | """Start the MQTT protocol service."""
conf: ConfigType | None = config.get(DOMAIN)
websocket_api.async_register_command(hass, websocket_subscribe)
websocket_api.async_register_command(hass, websocket_remove_device)
websocket_api.async_register_command(hass, websocket_mqtt_info)
if conf is None:
... | 225 | 225 | 751 | 10 | 215 | mikan-megane/core | homeassistant/components/mqtt/__init__.py | Python | async_setup_entry | async_setup_entry | 427 | 532 | 427 | 427 | 8e4006004f59a5c6565bf5cd49052ed393d5c78a | bigcode/the-stack | train |
096bf3ced2d7d4d201a6a8e0 | train | function | @callback
@bind_hass
def async_publish(
hass: HomeAssistant, topic: Any, payload, qos=None, retain=None
) -> None:
"""Publish message to an MQTT topic."""
data = _build_publish_data(topic, qos, retain)
data[ATTR_PAYLOAD] = payload
hass.async_create_task(hass.services.async_call(DOMAIN, SERVICE_PUBLI... | @callback
@bind_hass
def async_publish(
hass: HomeAssistant, topic: Any, payload, qos=None, retain=None
) -> None:
| """Publish message to an MQTT topic."""
data = _build_publish_data(topic, qos, retain)
data[ATTR_PAYLOAD] = payload
hass.async_create_task(hass.services.async_call(DOMAIN, SERVICE_PUBLISH, data))
| ) -> None:
"""Publish message to an MQTT topic."""
hass.add_job(async_publish, hass, topic, payload, qos, retain)
@callback
@bind_hass
def async_publish(
hass: HomeAssistant, topic: Any, payload, qos=None, retain=None
) -> None:
| 64 | 64 | 86 | 34 | 30 | mikan-megane/core | homeassistant/components/mqtt/__init__.py | Python | async_publish | async_publish | 259 | 267 | 259 | 263 | 7cbcb65a95e004eff039e90eb67f4b58da61c3ff | bigcode/the-stack | train |
408ae8470663d3b05460b7af | train | function | def is_connected(hass):
"""Return if MQTT client is connected."""
return hass.data[DATA_MQTT].connected
| def is_connected(hass):
| """Return if MQTT client is connected."""
return hass.data[DATA_MQTT].connected
| "connect": async_dispatcher_connect(hass, MQTT_CONNECTED, connected),
"disconnect": async_dispatcher_connect(hass, MQTT_DISCONNECTED, disconnected),
}
@callback
def unsubscribe():
subscriptions["connect"]()
subscriptions["disconnect"]()
return unsubscribe
def is_connected(hass... | 64 | 64 | 27 | 6 | 57 | mikan-megane/core | homeassistant/components/mqtt/__init__.py | Python | is_connected | is_connected | 1,079 | 1,081 | 1,079 | 1,079 | 061bd083ba55f1d5a5cbe8a014ecdb82f4f2c259 | bigcode/the-stack | train |
80d92729df42e4baf191900b | train | class | class MQTT:
"""Home Assistant MQTT client."""
def __init__(
self,
hass: HomeAssistant,
config_entry,
conf,
) -> None:
"""Initialize Home Assistant MQTT client."""
# We don't import on the top because some integrations
# should be able to optionally re... | class MQTT:
| """Home Assistant MQTT client."""
def __init__(
self,
hass: HomeAssistant,
config_entry,
conf,
) -> None:
"""Initialize Home Assistant MQTT client."""
# We don't import on the top because some integrations
# should be able to optionally rely on MQTT.
... | scribe(hass, call.data["topic"], collect_msg)
def write_dump():
with open(hass.config.path("mqtt_dump.txt"), "wt") as fp:
for msg in messages:
fp.write(",".join(msg) + "\n")
async def finish_dump(_):
"""Write dump to file."""
unsu... | 256 | 256 | 3,070 | 3 | 253 | mikan-megane/core | homeassistant/components/mqtt/__init__.py | Python | MQTT | MQTT | 546 | 953 | 546 | 546 | a8ce546bde21e1741934e142017b0c92e51ada87 | bigcode/the-stack | train |
69161bb948626b6d17a5bbd7 | train | function | def wrap_msg_callback(msg_callback: MessageCallbackType) -> MessageCallbackType:
"""Wrap an MQTT message callback to support deprecated signature."""
# Check for partials to properly determine if coroutine function
check_func = msg_callback
while isinstance(check_func, partial):
check_func = che... | def wrap_msg_callback(msg_callback: MessageCallbackType) -> MessageCallbackType:
| """Wrap an MQTT message callback to support deprecated signature."""
# Check for partials to properly determine if coroutine function
check_func = msg_callback
while isinstance(check_func, partial):
check_func = check_func.func
wrapper_func = None
if asyncio.iscoroutinefunction(check_fu... | template payload."""
data = _build_publish_data(topic, qos, retain)
data[ATTR_PAYLOAD_TEMPLATE] = payload_template
hass.async_create_task(hass.services.async_call(DOMAIN, SERVICE_PUBLISH, data))
def wrap_msg_callback(msg_callback: MessageCallbackType) -> MessageCallbackType:
| 64 | 64 | 178 | 16 | 48 | mikan-megane/core | homeassistant/components/mqtt/__init__.py | Python | wrap_msg_callback | wrap_msg_callback | 288 | 312 | 288 | 288 | 1075f5e2bf568967239d31e27451e65656959322 | bigcode/the-stack | train |
282955e63119df027a2c88db | train | function | @bind_hass
async def async_subscribe(
hass: HomeAssistant,
topic: str,
msg_callback: MessageCallbackType,
qos: int = DEFAULT_QOS,
encoding: str | None = "utf-8",
):
"""Subscribe to an MQTT topic.
Call the return value to unsubscribe.
"""
# Count callback parameters which don't have ... | @bind_hass
async def async_subscribe(
hass: HomeAssistant,
topic: str,
msg_callback: MessageCallbackType,
qos: int = DEFAULT_QOS,
encoding: str | None = "utf-8",
):
| """Subscribe to an MQTT topic.
Call the return value to unsubscribe.
"""
# Count callback parameters which don't have a default value
non_default = 0
if msg_callback:
non_default = sum(
p.default == inspect.Parameter.empty
for _, p in inspect.signature(msg_callba... | None:
"""Call with deprecated signature."""
msg_callback(msg.topic, msg.payload, msg.qos)
wrapper_func = wrapper
return wrapper_func
@bind_hass
async def async_subscribe(
hass: HomeAssistant,
topic: str,
msg_callback: MessageCallbackType,
qos: int = DEFAULT_QOS,
... | 85 | 85 | 286 | 52 | 32 | mikan-megane/core | homeassistant/components/mqtt/__init__.py | Python | async_subscribe | async_subscribe | 315 | 357 | 315 | 322 | a437845a9fd4c083c501f5785353c9400846e0b9 | bigcode/the-stack | train |
c0f43ea905d4d5fc28ac91a3 | train | function | @callback
def async_subscribe_connection_status(hass, connection_status_callback):
"""Subscribe to MQTT connection changes."""
connection_status_callback_job = HassJob(connection_status_callback)
async def connected():
task = hass.async_run_hass_job(connection_status_callback_job, True)
if ... | @callback
def async_subscribe_connection_status(hass, connection_status_callback):
| """Subscribe to MQTT connection changes."""
connection_status_callback_job = HassJob(connection_status_callback)
async def connected():
task = hass.async_run_hass_job(connection_status_callback_job, True)
if task:
await task
async def disconnected():
task = hass.asy... | tain,
},
)
)
connection.subscriptions[msg["id"]] = await async_subscribe(
hass, msg["topic"], forward_messages
)
connection.send_message(websocket_api.result_message(msg["id"]))
@callback
def async_subscribe_connection_status(hass, connection_status_callback):
| 63 | 64 | 157 | 16 | 47 | mikan-megane/core | homeassistant/components/mqtt/__init__.py | Python | async_subscribe_connection_status | async_subscribe_connection_status | 1,051 | 1,076 | 1,051 | 1,052 | b14a15d2cb5808a498cdad1a043d99c848b77789 | bigcode/the-stack | train |
693de14598fd1256a86579a8 | train | function | @bind_hass
def publish(hass: HomeAssistant, topic, payload, qos=None, retain=None) -> None:
"""Publish message to an MQTT topic."""
hass.add_job(async_publish, hass, topic, payload, qos, retain)
| @bind_hass
def publish(hass: HomeAssistant, topic, payload, qos=None, retain=None) -> None:
| """Publish message to an MQTT topic."""
hass.add_job(async_publish, hass, topic, payload, qos, retain)
| if qos is not None:
data[ATTR_QOS] = qos
if retain is not None:
data[ATTR_RETAIN] = retain
return data
@bind_hass
def publish(hass: HomeAssistant, topic, payload, qos=None, retain=None) -> None:
| 64 | 64 | 52 | 26 | 37 | mikan-megane/core | homeassistant/components/mqtt/__init__.py | Python | publish | publish | 253 | 256 | 253 | 254 | b9cc76db730ba67a86bcb5f0cd79a4e3fe709b07 | bigcode/the-stack | train |
424aa59a1b62e3d06a007071 | train | function | async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Start the MQTT protocol service."""
conf: ConfigType | None = config.get(DOMAIN)
websocket_api.async_register_command(hass, websocket_subscribe)
websocket_api.async_register_command(hass, websocket_remove_device)
websocket_a... | async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
| """Start the MQTT protocol service."""
conf: ConfigType | None = config.get(DOMAIN)
websocket_api.async_register_command(hass, websocket_subscribe)
websocket_api.async_register_command(hass, websocket_remove_device)
websocket_api.async_register_command(hass, websocket_mqtt_info)
if conf is Non... | to start the discovery of MQTT devices.
This method is a coroutine.
"""
success: bool = await discovery.async_start(
hass, conf[CONF_DISCOVERY_PREFIX], config_entry
)
return success
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
| 64 | 64 | 206 | 18 | 45 | mikan-megane/core | homeassistant/components/mqtt/__init__.py | Python | async_setup | async_setup | 394 | 419 | 394 | 394 | 5a3326429a802bc3df61461de1d99c65cf251028 | bigcode/the-stack | train |
9f18df034ef3766f950c6601 | train | function | @websocket_api.websocket_command(
{vol.Required("type"): "mqtt/device/remove", vol.Required("device_id"): str}
)
@websocket_api.async_response
async def websocket_remove_device(hass, connection, msg):
"""Delete device."""
device_id = msg["device_id"]
dev_registry = await hass.helpers.device_registry.asy... | @websocket_api.websocket_command(
{vol.Required("type"): "mqtt/device/remove", vol.Required("device_id"): str}
)
@websocket_api.async_response
async def websocket_remove_device(hass, connection, msg):
| """Delete device."""
device_id = msg["device_id"]
dev_registry = await hass.helpers.device_registry.async_get_registry()
device = dev_registry.async_get(device_id)
if not device:
connection.send_error(
msg["id"], websocket_api.const.ERR_NOT_FOUND, "Device not found"
)
... | (hass, device_id)
connection.send_result(msg["id"], mqtt_info)
@websocket_api.websocket_command(
{vol.Required("type"): "mqtt/device/remove", vol.Required("device_id"): str}
)
@websocket_api.async_response
async def websocket_remove_device(hass, connection, msg):
| 64 | 64 | 212 | 47 | 17 | mikan-megane/core | homeassistant/components/mqtt/__init__.py | Python | websocket_remove_device | websocket_remove_device | 989 | 1,015 | 989 | 993 | c774b94f23c3035a70b9e23412b2ecf1c98062bf | bigcode/the-stack | train |
add77e911555871d3093905a | train | function | @bind_hass
def subscribe(
hass: HomeAssistant,
topic: str,
msg_callback: MessageCallbackType,
qos: int = DEFAULT_QOS,
encoding: str = "utf-8",
) -> Callable[[], None]:
"""Subscribe to an MQTT topic."""
async_remove = asyncio.run_coroutine_threadsafe(
async_subscribe(hass, topic, msg_... | @bind_hass
def subscribe(
hass: HomeAssistant,
topic: str,
msg_callback: MessageCallbackType,
qos: int = DEFAULT_QOS,
encoding: str = "utf-8",
) -> Callable[[], None]:
| """Subscribe to an MQTT topic."""
async_remove = asyncio.run_coroutine_threadsafe(
async_subscribe(hass, topic, msg_callback, qos, encoding), hass.loop
).result()
def remove():
"""Remove listener convert."""
run_callback_threadsafe(hass.loop, async_remove).result()
return r... | ,
encoding,
)
return async_remove
@bind_hass
def subscribe(
hass: HomeAssistant,
topic: str,
msg_callback: MessageCallbackType,
qos: int = DEFAULT_QOS,
encoding: str = "utf-8",
) -> Callable[[], None]:
| 64 | 64 | 123 | 53 | 10 | mikan-megane/core | homeassistant/components/mqtt/__init__.py | Python | subscribe | subscribe | 360 | 377 | 360 | 367 | 2aff3d34819716e6241f70a7a64d4626780071fc | bigcode/the-stack | train |
b92a605e58fb17adc91df647 | train | function | @bind_hass
def publish_template(
hass: HomeAssistant, topic, payload_template, qos=None, retain=None
) -> None:
"""Publish message to an MQTT topic."""
hass.add_job(async_publish_template, hass, topic, payload_template, qos, retain)
| @bind_hass
def publish_template(
hass: HomeAssistant, topic, payload_template, qos=None, retain=None
) -> None:
| """Publish message to an MQTT topic."""
hass.add_job(async_publish_template, hass, topic, payload_template, qos, retain)
| qos, retain)
data[ATTR_PAYLOAD] = payload
hass.async_create_task(hass.services.async_call(DOMAIN, SERVICE_PUBLISH, data))
@bind_hass
def publish_template(
hass: HomeAssistant, topic, payload_template, qos=None, retain=None
) -> None:
| 64 | 64 | 58 | 30 | 34 | mikan-megane/core | homeassistant/components/mqtt/__init__.py | Python | publish_template | publish_template | 270 | 275 | 270 | 273 | e99a9cbebab703f4aabd6da10c4dd0e7d0a028b8 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.