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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f97f69df26d8199f3511df1b | train | class | class SimpleParamStore(ParamStore):
"""A module that carries a direct variable as the parameter."""
value: Tensor
def __init__(self,
shape: List[int],
initializer: TensorInitArgType,
device: Optional[str] = None):
device = device or current_device... | class SimpleParamStore(ParamStore):
| """A module that carries a direct variable as the parameter."""
value: Tensor
def __init__(self,
shape: List[int],
initializer: TensorInitArgType,
device: Optional[str] = None):
device = device or current_device()
super().__init__(shape)
... | return f'shape={self.shape}'
def forward(self) -> Tensor:
return self.get()
def get(self) -> Tensor:
raise NotImplementedError()
def set(self, value: TensorOrData) -> None:
raise NotImplementedError()
class SimpleParamStore(ParamStore):
| 64 | 64 | 141 | 8 | 56 | lizeyan/tensorkit | tensorkit/backend/pytorch_/layers.py | Python | SimpleParamStore | SimpleParamStore | 275 | 296 | 275 | 275 | 58fa694b6764945fbca85c3a6b3881992673ec5f | bigcode/the-stack | train |
ba6c41d634e696401302af9d | train | class | class LinearConv2d(LinearConvNd):
def _get_spatial_ndims(self) -> int:
return 2
@jit_method
def _conv_transform(self,
input: Tensor,
weight: Tensor,
bias: Optional[Tensor]
) -> Tensor:
r... | class LinearConv2d(LinearConvNd):
| def _get_spatial_ndims(self) -> int:
return 2
@jit_method
def _conv_transform(self,
input: Tensor,
weight: Tensor,
bias: Optional[Tensor]
) -> Tensor:
return torch.nn.functional.conv2d(
... | Tensor,
bias: Optional[Tensor]
) -> Tensor:
return torch.nn.functional.conv1d(
input=input, weight=weight, bias=bias, stride=self.stride,
padding=self._conv_padding, dilation=self.dilation
)
class LinearConv2d(LinearConvNd):
| 64 | 64 | 102 | 10 | 54 | lizeyan/tensorkit | tensorkit/backend/pytorch_/layers.py | Python | LinearConv2d | LinearConv2d | 735 | 749 | 735 | 736 | cef5a87513486d527920998343a4ca8e3a5f0acf | bigcode/the-stack | train |
c211fab84d8c837704ba2f45 | train | function | def set_eval_mode(layer: Module):
layer.train(False)
return layer
| def set_eval_mode(layer: Module):
| layer.train(False)
return layer
| iter_named_buffers(layer: Module, recursive: bool = True
) -> Iterator[Tuple[str, Tensor]]:
return layer.named_buffers(recurse=recursive)
def set_train_mode(layer: Module, training: bool = True):
layer.train(training)
return layer
def set_eval_mode(layer: Module):
| 64 | 64 | 17 | 8 | 55 | lizeyan/tensorkit | tensorkit/backend/pytorch_/layers.py | Python | set_eval_mode | set_eval_mode | 224 | 226 | 224 | 224 | 885b7b5bf0e486cf9542d2b47c4e35d1f36a8554 | bigcode/the-stack | train |
d6af92e197a7e2dbdff74e74 | train | function | def is_jit_layer(layer: Module) -> bool:
"""Check whether or not `layer` is a JIT compiled layer."""
return isinstance(layer, (torch.jit.ScriptModule, torch.jit.RecursiveScriptModule))
| def is_jit_layer(layer: Module) -> bool:
| """Check whether or not `layer` is a JIT compiled layer."""
return isinstance(layer, (torch.jit.ScriptModule, torch.jit.RecursiveScriptModule))
| )
for c in val
])
setattr(m, attr, jit_compile(module_list, filter, filter_key))
else:
val = jit_compile(val, filter, filter_key)
setattr(m, attr, val)
return m
def is_jit_... | 64 | 64 | 48 | 12 | 51 | lizeyan/tensorkit | tensorkit/backend/pytorch_/layers.py | Python | is_jit_layer | is_jit_layer | 138 | 140 | 138 | 138 | 6f0597d3d04a15a593a55cce9a75303fa0501dff | bigcode/the-stack | train |
45dff128d903a230481079f7 | train | class | class Linear(CoreLinear):
__constants__ = CoreLinear.__constants__ + (
'in_features', 'out_features',
)
in_features: int
out_features: int
def __init__(self,
in_features: int,
out_features: int,
use_bias: bool = True,
wei... | class Linear(CoreLinear):
| __constants__ = CoreLinear.__constants__ + (
'in_features', 'out_features',
)
in_features: int
out_features: int
def __init__(self,
in_features: int,
out_features: int,
use_bias: bool = True,
weight_norm: WeightNormArgType... | _store
self.use_bias = use_bias
if data_init is not None:
data_init.register(self)
def _is_attr_included_in_repr(self, attr: str, value: Any) -> bool:
return attr != 'use_bias' or not value
def __repr__(self):
return f'{self.__class__.__qualname__}({self.extra_repr... | 89 | 89 | 298 | 5 | 84 | lizeyan/tensorkit | tensorkit/backend/pytorch_/layers.py | Python | Linear | Linear | 581 | 623 | 581 | 582 | d2bbe871bb241a4f780eef646a9a45c5ca00364e | bigcode/the-stack | train |
6fa5608b1636ad28d2e4e9e0 | train | function | def get_buffer(layer: Module, name: str) -> Optional[Tensor]:
return getattr(layer, name)
| def get_buffer(layer: Module, name: str) -> Optional[Tensor]:
| return getattr(layer, name)
| return layer.named_parameters(recurse=recursive)
def add_buffer(layer: Module,
name: str,
value: Optional[Tensor]
) -> Optional[Tensor]:
layer.register_buffer(name, value)
return value
def get_buffer(layer: Module, name: str) -> Optional[Tensor]:
| 64 | 64 | 23 | 16 | 47 | lizeyan/tensorkit | tensorkit/backend/pytorch_/layers.py | Python | get_buffer | get_buffer | 201 | 202 | 201 | 201 | 6ee7bb2c63485715f4f874755324c7f81fbe61c3 | bigcode/the-stack | train |
b07ac1fba10b39066a932df8 | train | function | def is_batch_norm(module: Module) -> bool:
"""
Check whether or not `module` is a Batch Norm module.
JIT compiled Batch Norm module is not recognized by this method.
Args:
module: The module to be checked.
Returns:
Whether or not `module` is a Batch Norm module.
"""
return ... | def is_batch_norm(module: Module) -> bool:
| """
Check whether or not `module` is a Batch Norm module.
JIT compiled Batch Norm module is not recognized by this method.
Args:
module: The module to be checked.
Returns:
Whether or not `module` is a Batch Norm module.
"""
return has_batch_norm(module, recursive=False)
| or isinstance(
m,
(torch_nn.BatchNorm1d, torch_nn.BatchNorm2d, torch_nn.BatchNorm3d)
)
if recursive:
module.apply(fn)
else:
fn(module)
return ret[0]
def is_batch_norm(module: Module) -> bool:
| 64 | 64 | 81 | 11 | 53 | lizeyan/tensorkit | tensorkit/backend/pytorch_/layers.py | Python | is_batch_norm | is_batch_norm | 1,029 | 1,040 | 1,029 | 1,029 | 7cede553bb68cd4c1cb39234f24e5ce3a866ad98 | bigcode/the-stack | train |
77bf969ba59f067b9bc71116 | train | class | class LinearConvTranspose2d(LinearConvTransposeNd):
def _get_spatial_ndims(self) -> int:
return 2
@jit_method
def _deconv_transform(self,
input: Tensor,
weight: Tensor,
bias: Optional[Tensor]
) ... | class LinearConvTranspose2d(LinearConvTransposeNd):
| def _get_spatial_ndims(self) -> int:
return 2
@jit_method
def _deconv_transform(self,
input: Tensor,
weight: Tensor,
bias: Optional[Tensor]
) -> Tensor:
return torch.nn.functional.conv_tr... | -> Tensor:
return torch.nn.functional.conv_transpose1d(
input=input, weight=weight, bias=bias, stride=self.stride,
padding=self._conv_padding, output_padding=self.output_padding,
dilation=self.dilation
)
class LinearConvTranspose2d(LinearConvTransposeNd):
| 64 | 64 | 114 | 12 | 52 | lizeyan/tensorkit | tensorkit/backend/pytorch_/layers.py | Python | LinearConvTranspose2d | LinearConvTranspose2d | 885 | 900 | 885 | 886 | d13b24598a02d911cb56c90b9c8f8bd2ae7b870f | bigcode/the-stack | train |
e05bb7926db9676f1545311a | train | class | class Embedding2d(EmbeddingNd):
def _get_spatial_ndims(self) -> int:
return 2
| class Embedding2d(EmbeddingNd):
| def _get_spatial_ndims(self) -> int:
return 2
| embedding_size, initializer, freeze, device)
def _get_spatial_ndims(self) -> int:
raise NotImplementedError()
class Embedding1d(EmbeddingNd):
def _get_spatial_ndims(self) -> int:
return 1
class Embedding2d(EmbeddingNd):
| 64 | 64 | 27 | 9 | 54 | lizeyan/tensorkit | tensorkit/backend/pytorch_/layers.py | Python | Embedding2d | Embedding2d | 1,224 | 1,227 | 1,224 | 1,225 | d65992616bd37a6192765448f024ff3903787e67 | bigcode/the-stack | train |
d1cffb0139564f3cdb498b6c | train | function | def add_parameter(layer: Module,
name: str,
value: Optional[Tensor],
requires_grad: bool = True
) -> Optional[Variable]:
if value is not None:
v = torch.nn.Parameter(value, requires_grad=requires_grad)
else:
v = value
la... | def add_parameter(layer: Module,
name: str,
value: Optional[Tensor],
requires_grad: bool = True
) -> Optional[Variable]:
| if value is not None:
v = torch.nn.Parameter(value, requires_grad=requires_grad)
else:
v = value
layer.register_parameter(name, v)
return v
| instance.
"""
if device is None:
device = current_device()
layer = layer.to(device=torch.device(device))
return layer
def add_parameter(layer: Module,
name: str,
value: Optional[Tensor],
requires_grad: bool = True
) -> Opti... | 64 | 64 | 75 | 34 | 29 | lizeyan/tensorkit | tensorkit/backend/pytorch_/layers.py | Python | add_parameter | add_parameter | 162 | 172 | 162 | 166 | d6822f7693d3a9b627c27eaee7d9cafa8154ccc1 | bigcode/the-stack | train |
e07eae367c80c6be6c7efc82 | train | function | def get_buffers(layer: Module, recursive: bool = True) -> List[Variable]:
return list(iter_buffers(layer, recursive))
| def get_buffers(layer: Module, recursive: bool = True) -> List[Variable]:
| return list(iter_buffers(layer, recursive))
| name: str) -> Optional[Tensor]:
return getattr(layer, name)
def iter_buffers(layer: Module, recursive: bool = True
) -> Iterator[Tensor]:
return layer.buffers(recurse=recursive)
def get_buffers(layer: Module, recursive: bool = True) -> List[Variable]:
| 64 | 64 | 27 | 18 | 46 | lizeyan/tensorkit | tensorkit/backend/pytorch_/layers.py | Python | get_buffers | get_buffers | 210 | 211 | 210 | 210 | b4f6e7d2a8683126b24b73c700c9d319650f297b | bigcode/the-stack | train |
a4c31bdf0304c89b6ef63bd3 | train | function | def count_frame_get(total_frame, frame_gap):
count = 0
cur_frame = 0
while cur_frame < total_frame:
if cur_frame % frame_gap != 0:
cur_frame += 1
continue
count += 1
cur_frame += 1
return count
| def count_frame_get(total_frame, frame_gap):
| count = 0
cur_frame = 0
while cur_frame < total_frame:
if cur_frame % frame_gap != 0:
cur_frame += 1
continue
count += 1
cur_frame += 1
return count
| )
raise Exception
def _wait_queue(self):
"""Wait for the queue to be empty."""
while True:
time.sleep(0.1)
if self.queue.unfinished_tasks == 0 or self.stop_signal.is_set():
return
def count_frame_get(total_frame, frame_gap):
| 64 | 64 | 69 | 10 | 53 | JunweiLiang/Object_Detection_Tracking | enqueuer_thread.py | Python | count_frame_get | count_frame_get | 157 | 166 | 157 | 157 | ffcf1c78539df8134be75fdb0babb0511e937959 | bigcode/the-stack | train |
172111458922c87807c580ab | train | class | class VideoEnqueuer(object):
def __init__(self,
cfg,
vcap,
num_frame,
frame_gap=1,
prefetch=5,
start=True, # start the dataset get thread when init
is_moviepy=False,
batch_size=4,
):
... | class VideoEnqueuer(object):
| def __init__(self,
cfg,
vcap,
num_frame,
frame_gap=1,
prefetch=5,
start=True, # start the dataset get thread when init
is_moviepy=False,
batch_size=4,
):
self.cfg = cfg
self.vc... | .dataset.batch_size_per_gpu)
for this_batch_idxs_per_gpu in this_batch_idxs_gpus:
batches.append(self.dataset.collect_batch(
samples, this_batch_idxs_per_gpu))
batch = batches
else:
batch = self.dataset.collect_batch(samples)
self.cur_batch_cou... | 256 | 256 | 998 | 7 | 248 | JunweiLiang/Object_Detection_Tracking | enqueuer_thread.py | Python | VideoEnqueuer | VideoEnqueuer | 168 | 317 | 168 | 168 | 1d72084738ed5d1f7b0d0c6deec8c649c6acdebb | bigcode/the-stack | train |
c5e591a1e495da2be8335b83 | train | class | class DatasetEnqueuer(object):
def __init__(self, dataset, prefetch=5, num_workers=1,
start=True, # start the dataset get thread when init
shuffle=False,
# whether to break down each mini-batch for each gpu
is_multi_gpu=False,
last_full_batch=... | class DatasetEnqueuer(object):
| def __init__(self, dataset, prefetch=5, num_workers=1,
start=True, # start the dataset get thread when init
shuffle=False,
# whether to break down each mini-batch for each gpu
is_multi_gpu=False,
last_full_batch=False, # make sure the last ba... | # coding=utf-8
"""Given the dataset object, make a multithread enqueuer"""
import os
import queue
import threading
import contextlib
import multiprocessing
import time
import random
import sys
import utils
import traceback
# for video queuer
from nn import resizeImage
import cv2
# modified from keras
class DatasetEnq... | 80 | 256 | 951 | 7 | 72 | JunweiLiang/Object_Detection_Tracking | enqueuer_thread.py | Python | DatasetEnqueuer | DatasetEnqueuer | 19 | 154 | 19 | 19 | 61c85d880c9c29a09a8823af0f41c2f730e8b04b | bigcode/the-stack | train |
50a40f0a5a8337b8376c1b21 | train | class | class CheckFunction:
def newFunction(self, code):
m = [6, 2, 5, 5, 4, 5, 6, 3, 7, 6]
return sum(map(lambda c: m[ord(c)-ord('0')], code))
| class CheckFunction:
| def newFunction(self, code):
m = [6, 2, 5, 5, 4, 5, 6, 3, 7, 6]
return sum(map(lambda c: m[ord(c)-ord('0')], code))
| class CheckFunction:
| 4 | 64 | 64 | 4 | 0 | gauravsingh58/algo | topCoder/srms/200s/srm271/div2/check_function.py | Python | CheckFunction | CheckFunction | 1 | 4 | 1 | 1 | 2146068bd4b47c34033926babe9bd5a62b720e77 | bigcode/the-stack | train |
c603111ad7fd476be4919b09 | train | class | class GhettoTest(IsolatedTestCase):
@vcr.use_cassette('tests/cassettes/ghetto.yaml')
def test_ghetto(self):
self.assertCommand('!ghetto hi, whats up?', 'hi, wassup?')
with requests_mock.Mocker() as m:
m.register_uri('POST', 'http://www.gizoogle.net/textilizer.php',
... | class GhettoTest(IsolatedTestCase):
@vcr.use_cassette('tests/cassettes/ghetto.yaml')
| def test_ghetto(self):
self.assertCommand('!ghetto hi, whats up?', 'hi, wassup?')
with requests_mock.Mocker() as m:
m.register_uri('POST', 'http://www.gizoogle.net/textilizer.php',
text='test text which will not match with the regex')
self.assertCom... | import requests_mock
import vcr
from tests.isolated_testcase import IsolatedTestCase
class GhettoTest(IsolatedTestCase):
@vcr.use_cassette('tests/cassettes/ghetto.yaml')
| 46 | 64 | 112 | 26 | 19 | Arna-Maity/corobo | tests/ghetto_test.py | Python | GhettoTest | GhettoTest | 7 | 15 | 7 | 9 | e3f36ef700dfcd329dd97252b2668be1a077d1b4 | bigcode/the-stack | train |
fa0094e149bb4f6b748aa0a5 | train | class | class Recommendation26:
"""
Recomendação 26: Disponibilizar uma explicação para siglas, abreviaturas e palavras incomuns
"""
def __init__(self, sourcecode):
self.rec = 26
self.occurrences = Occurrences()
self.sourcecode = sourcecode
def avaliacao(self):
soap = Beaut... | class Recommendation26:
| """
Recomendação 26: Disponibilizar uma explicação para siglas, abreviaturas e palavras incomuns
"""
def __init__(self, sourcecode):
self.rec = 26
self.occurrences = Occurrences()
self.sourcecode = sourcecode
def avaliacao(self):
soap = BeautifulSoup(self.sourcecode... | from bs4 import BeautifulSoup
from ..occurrences.occurrences import Occurrences
from ..occurrences.occurrence_interface import OccurrenceInterface
class Recommendation26:
| 35 | 64 | 177 | 4 | 30 | carlosbognar/TCC-WCGA-1 | crawling/recommendations/recommendation26.py | Python | Recommendation26 | Recommendation26 | 7 | 28 | 7 | 7 | 97a29153151fbc2a91a788341d277f8e800447d9 | bigcode/the-stack | train |
7ac0155cf50f33276cec5bdd | train | function | def convert(text, fromformat, toformat, **options):
"""
Converts input text by sending it the Docverter online service.
Arguments:
- **text**: The text to be converted to another language format. If converting file use open(filepath).read().
Text should be encoded as raw byte string (e.g. "yourtex... | def convert(text, fromformat, toformat, **options):
| """
Converts input text by sending it the Docverter online service.
Arguments:
- **text**: The text to be converted to another language format. If converting file use open(filepath).read().
Text should be encoded as raw byte string (e.g. "yourtext".encode(...)".
- **fromformat**: From language... | , filename))
L.append('Content-Type: %s' % _get_content_type(filename))
L.append('')
L.append(value)
L.append('--' + BOUNDARY + '--')
L.append('')
body = CRLF.join(L)
content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
return content_type, body
def _get_content_typ... | 129 | 129 | 430 | 13 | 116 | karimbahgat/iPandoc | ipandoc.py | Python | convert | convert | 143 | 180 | 143 | 143 | 3e44c1f2aadc879be3774c6108407c5d9f44cf7f | bigcode/the-stack | train |
3e8a9eead8a73515a033f623 | train | function | def _post_multipart(host, selector, fields, files):
"""
Post fields and files to an http host as multipart/form-data.
fields is a sequence of (name, value) elements for regular form fields.
files is a sequence of (name, filename, value) elements for data to be uploaded as files
Return the server's r... | def _post_multipart(host, selector, fields, files):
| """
Post fields and files to an http host as multipart/form-data.
fields is a sequence of (name, value) elements for regular form fields.
files is a sequence of (name, filename, value) elements for data to be uploaded as files
Return the server's response page.
"""
content_type, body = _enco... | .github.com/wcaleb/b6a8c97ccb0f11bd16ab
# see docverter example using this method: http://omz-forums.appspot.com/editorial/post/4955159939514368
#######################
def _post_multipart(host, selector, fields, files):
| 63 | 64 | 181 | 13 | 50 | karimbahgat/iPandoc | ipandoc.py | Python | _post_multipart | _post_multipart | 87 | 105 | 87 | 87 | f472200c1f53d006d8ba70f61ba1080d91fdf2ee | bigcode/the-stack | train |
edd126b758cecf3c98a5600c | train | function | def _encode_multipart_formdata(fields, files):
"""
fields is a sequence of (name, value) elements for regular form fields.
files is a sequence of (name, filename, value) elements for data to be uploaded as files
Return (content_type, body) ready for httplib.HTTP instance
"""
BOUNDARY = '--------... | def _encode_multipart_formdata(fields, files):
| """
fields is a sequence of (name, value) elements for regular form fields.
files is a sequence of (name, filename, value) elements for data to be uploaded as files
Return (content_type, body) ready for httplib.HTTP instance
"""
BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
CRLF = '\r\n'
... | = body.encode()
h.putrequest('POST', selector)
h.putheader('content-type', content_type)
h.putheader('content-length', str(len(body)))
h.endheaders()
h.send(body)
response = h.getresponse()
output = response.read()
return output # return h.file.read()
def _encode_multipart_formdata(fie... | 80 | 80 | 267 | 11 | 69 | karimbahgat/iPandoc | ipandoc.py | Python | _encode_multipart_formdata | _encode_multipart_formdata | 108 | 132 | 108 | 108 | 94b7bc776cd659ff8980f7c86101a1ebae3a0831 | bigcode/the-stack | train |
a9e8036ef3da70e27079941f | train | function | def _get_content_type(filename):
return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
| def _get_content_type(filename):
| return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
| L.append('')
L.append(value)
L.append('--' + BOUNDARY + '--')
L.append('')
body = CRLF.join(L)
content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
return content_type, body
def _get_content_type(filename):
| 64 | 64 | 25 | 7 | 56 | karimbahgat/iPandoc | ipandoc.py | Python | _get_content_type | _get_content_type | 135 | 136 | 135 | 135 | 657e2ed06b52a493fa9a323c227e01ffb55b79e2 | bigcode/the-stack | train |
6c3951e5cdc693cf73154ee4 | train | class | class ArenaTimeToWin(enum.IntEnum):
SECONDS_10 = 0
SECONDS_20 = 1
SECONDS_30 = 2
SECONDS_40 = 3
SECONDS_50 = 4
SECONDS_60 = 5
SECONDS_70 = 6
SECONDS_80 = 7
SECONDS_90 = 8
SECONDS_99 = 9
| class ArenaTimeToWin(enum.IntEnum):
| SECONDS_10 = 0
SECONDS_20 = 1
SECONDS_30 = 2
SECONDS_40 = 3
SECONDS_50 = 4
SECONDS_60 = 5
SECONDS_70 = 6
SECONDS_80 = 7
SECONDS_90 = 8
SECONDS_99 = 9
| TimerEnding(enum.IntEnum):
ROUND_ENDS = 0
DEATH_MIST = 1
ALIEN_BLAST = 2
LOOSE_BOMBS = 3
GHOST = 4
RANDOM = 5
class ArenaTimeToWin(enum.IntEnum):
| 64 | 64 | 99 | 9 | 54 | d11z/modlunky2 | src/modlunky2/mem/arena_state.py | Python | ArenaTimeToWin | ArenaTimeToWin | 63 | 73 | 63 | 63 | 03d602a2c8d9cc0236f25c718b6beb81ce4e2a7e | bigcode/the-stack | train |
3266e7f57bbd19d625d8ff8e | train | class | class ArenaMount(enum.IntEnum):
NONE = 0
TURKEY = 1
ROCKDOG = 2
AXOLOTL = 3
RANDOM = 4
| class ArenaMount(enum.IntEnum):
| NONE = 0
TURKEY = 1
ROCKDOG = 2
AXOLOTL = 3
RANDOM = 4
| 2
X0_75 = 3
X1_00 = 4
X1_25 = 5
X1_50 = 6
X1_75 = 7
X2_00 = 8
class ArenaMount(enum.IntEnum):
| 64 | 64 | 42 | 7 | 56 | d11z/modlunky2 | src/modlunky2/mem/arena_state.py | Python | ArenaMount | ArenaMount | 88 | 93 | 88 | 88 | 93fe83f5d5a1a6788f8ac57c5f8ef65e6e119b7c | bigcode/the-stack | train |
49ac92a5430016176c2f89bf | train | class | class ArenaBreathCooldown(enum.IntEnum):
NONE = 0
X0_25 = 1
X0_50 = 2
X0_75 = 3
X1_00 = 4
X1_25 = 5
X1_50 = 6
X1_75 = 7
X2_00 = 8
BREATH_OFF = 9
| class ArenaBreathCooldown(enum.IntEnum):
| NONE = 0
X0_25 = 1
X0_50 = 2
X0_75 = 3
X1_00 = 4
X1_25 = 5
X1_50 = 6
X1_75 = 7
X2_00 = 8
BREATH_OFF = 9
| HP_1 = 1
HP_2 = 2
HP_3 = 3
HP_4 = 4
HP_5 = 5
HP_10 = 6
HP_99 = 7
class ArenaBreathCooldown(enum.IntEnum):
| 64 | 64 | 95 | 9 | 54 | d11z/modlunky2 | src/modlunky2/mem/arena_state.py | Python | ArenaBreathCooldown | ArenaBreathCooldown | 128 | 138 | 128 | 128 | 327655b41ea1dc01d2f2fb68bf8ac9b148cd29b1 | bigcode/the-stack | train |
bd9370ca14d5b6b1e57dec6c | train | class | class ArenaRuleset(enum.IntEnum):
CASUAL = 0
TOURNAMENT = 1
JOUST = 2
FRANTIC = 3
CUSTOM = 4
FAVORITE = 5
| class ArenaRuleset(enum.IntEnum):
| CASUAL = 0
TOURNAMENT = 1
JOUST = 2
FRANTIC = 3
CUSTOM = 4
FAVORITE = 5
| lunky2.mem.memrauder.dsl import (
array,
struct_field,
sc_uint8,
sc_int8,
sc_bool,
)
class ArenaFormat(enum.IntEnum):
DEATHMATCH = 0
HOLD_THE_IDOL = 1
class ArenaRuleset(enum.IntEnum):
| 64 | 64 | 52 | 8 | 55 | d11z/modlunky2 | src/modlunky2/mem/arena_state.py | Python | ArenaRuleset | ArenaRuleset | 21 | 27 | 21 | 21 | 7dc2fcad23410f32a2e067c7ba554af8370d574b | bigcode/the-stack | train |
9b74c251c7f172453d0e3198 | train | class | class ArenaWhipDamage(enum.IntEnum):
HP_0 = 0
HP_1 = 1
HP_2 = 2
HP_3 = 3
HP_4 = 4
HP_5 = 5
HP_10 = 6
HP_99 = 7
| class ArenaWhipDamage(enum.IntEnum):
| HP_0 = 0
HP_1 = 1
HP_2 = 2
HP_3 = 3
HP_4 = 4
HP_5 = 5
HP_10 = 6
HP_99 = 7
| PERCENT_50 = 2
ALWAYS = 3
class ArenaCrateFrequency(enum.IntEnum):
NONE = 0
LOW = 1
MEDIUM = 2
HIGH = 3
VERY_HIGH = 4
class ArenaWhipDamage(enum.IntEnum):
| 64 | 64 | 73 | 9 | 54 | d11z/modlunky2 | src/modlunky2/mem/arena_state.py | Python | ArenaWhipDamage | ArenaWhipDamage | 117 | 125 | 117 | 117 | bbbf35c85b1327a0069ba41259e50a8f1826b196 | bigcode/the-stack | train |
c28c595d0304a2e44526b977 | train | class | class ArenaDarkLevelChance(enum.IntEnum):
NONE = 0
PERCENT_10 = 1
PERCENT_50 = 2
ALWAYS = 3
| class ArenaDarkLevelChance(enum.IntEnum):
| NONE = 0
PERCENT_10 = 1
PERCENT_50 = 2
ALWAYS = 3
| 1
ROCKDOG = 2
AXOLOTL = 3
RANDOM = 4
class ArenaSelect(enum.IntEnum):
TAKE_TURNS = 0
LOSER_PICKS = 1
RANDOM_LEVEL = 2
class ArenaDarkLevelChance(enum.IntEnum):
| 64 | 64 | 39 | 9 | 54 | d11z/modlunky2 | src/modlunky2/mem/arena_state.py | Python | ArenaDarkLevelChance | ArenaDarkLevelChance | 102 | 106 | 102 | 102 | d3cf64c93bb653891a372b33417628f1672796c9 | bigcode/the-stack | train |
43dc8d3bb3e482c6d172a707 | train | class | class ArenaFormat(enum.IntEnum):
DEATHMATCH = 0
HOLD_THE_IDOL = 1
| class ArenaFormat(enum.IntEnum):
| DEATHMATCH = 0
HOLD_THE_IDOL = 1
|
from dataclasses import dataclass
from typing import FrozenSet, Tuple
from serde import serialize, deserialize
from modlunky2.mem.memrauder.dsl import (
array,
struct_field,
sc_uint8,
sc_int8,
sc_bool,
)
class ArenaFormat(enum.IntEnum):
| 64 | 64 | 24 | 7 | 57 | d11z/modlunky2 | src/modlunky2/mem/arena_state.py | Python | ArenaFormat | ArenaFormat | 16 | 18 | 16 | 16 | 8fcab106521600d0228ebf5d352970db27fd875d | bigcode/the-stack | train |
3e41b20356a07479955f988b | train | class | class ArenaTimer(enum.IntEnum):
TIME_00_30 = 0
TIME_01_00 = 1
TIME_01_30 = 2
TIME_02_00 = 3
TIME_02_30 = 4
TIME_03_00 = 5
TIME_03_30 = 6
TIME_04_00 = 7
TIME_04_30 = 8
TIME_05_00 = 9
TIME_05_30 = 10
TIME_06_00 = 11
TIME_06_30 = 12
TIME_07_00 = 13
TIME_07_30 = 1... | class ArenaTimer(enum.IntEnum):
| TIME_00_30 = 0
TIME_01_00 = 1
TIME_01_30 = 2
TIME_02_00 = 3
TIME_02_30 = 4
TIME_03_00 = 5
TIME_03_30 = 6
TIME_04_00 = 7
TIME_04_30 = 8
TIME_05_00 = 9
TIME_05_30 = 10
TIME_06_00 = 11
TIME_06_30 = 12
TIME_07_00 = 13
TIME_07_30 = 14
TIME_08_00 = 15
TIME_0... | OL = 1
class ArenaRuleset(enum.IntEnum):
CASUAL = 0
TOURNAMENT = 1
JOUST = 2
FRANTIC = 3
CUSTOM = 4
FAVORITE = 5
class ArenaTimer(enum.IntEnum):
| 64 | 64 | 214 | 7 | 56 | d11z/modlunky2 | src/modlunky2/mem/arena_state.py | Python | ArenaTimer | ArenaTimer | 30 | 51 | 30 | 30 | 79eba26a53b3e5bc34c6dd3ba00c3b9c2a3f69cf | bigcode/the-stack | train |
28a1757bf0dbddb74cf0946f | train | class | class ArenaSelect(enum.IntEnum):
TAKE_TURNS = 0
LOSER_PICKS = 1
RANDOM_LEVEL = 2
| class ArenaSelect(enum.IntEnum):
| TAKE_TURNS = 0
LOSER_PICKS = 1
RANDOM_LEVEL = 2
| _75 = 7
X2_00 = 8
class ArenaMount(enum.IntEnum):
NONE = 0
TURKEY = 1
ROCKDOG = 2
AXOLOTL = 3
RANDOM = 4
class ArenaSelect(enum.IntEnum):
| 64 | 64 | 31 | 7 | 56 | d11z/modlunky2 | src/modlunky2/mem/arena_state.py | Python | ArenaSelect | ArenaSelect | 96 | 99 | 96 | 96 | 87c2a9facb680a0d7ee82af5b52d8df765734fb6 | bigcode/the-stack | train |
84fffba006fefb81efbc33dc | train | class | class ArenaItem(enum.IntEnum):
NOTHING = -1
ROCK = 0
POT = enum.auto()
BOMBBAG = enum.auto()
BOMBBOX = enum.auto()
ROPEPILE = enum.auto()
PICKUP_12BAG = enum.auto()
PICKUP_24BAG = enum.auto()
COOKED_TURKEY = enum.auto()
ROYAL_JELLY = enum.auto()
TORCH = enum.auto()
BOOMER... | class ArenaItem(enum.IntEnum):
| NOTHING = -1
ROCK = 0
POT = enum.auto()
BOMBBAG = enum.auto()
BOMBBOX = enum.auto()
ROPEPILE = enum.auto()
PICKUP_12BAG = enum.auto()
PICKUP_24BAG = enum.auto()
COOKED_TURKEY = enum.auto()
ROYAL_JELLY = enum.auto()
TORCH = enum.auto()
BOOMERANG = enum.auto()
MACHETE =... | 7
class ArenaBreathCooldown(enum.IntEnum):
NONE = 0
X0_25 = 1
X0_50 = 2
X0_75 = 3
X1_00 = 4
X1_25 = 5
X1_50 = 6
X1_75 = 7
X2_00 = 8
BREATH_OFF = 9
class ArenaItem(enum.IntEnum):
| 105 | 105 | 352 | 7 | 97 | d11z/modlunky2 | src/modlunky2/mem/arena_state.py | Python | ArenaItem | ArenaItem | 141 | 182 | 141 | 141 | 73493af5bcae5ac4338c422c339592514f411d08 | bigcode/the-stack | train |
a4f90ce68e3460ead0844a72 | train | class | class ArenaStunTime(enum.IntEnum):
X0_00 = 0
X0_25 = 1
X0_50 = 2
X0_75 = 3
X1_00 = 4
X1_25 = 5
X1_50 = 6
X1_75 = 7
X2_00 = 8
| class ArenaStunTime(enum.IntEnum):
| X0_00 = 0
X0_25 = 1
X0_50 = 2
X0_75 = 3
X1_00 = 4
X1_25 = 5
X1_50 = 6
X1_75 = 7
X2_00 = 8
|
SECONDS_50 = 4
SECONDS_60 = 5
SECONDS_70 = 6
SECONDS_80 = 7
SECONDS_90 = 8
SECONDS_99 = 9
class ArenaStunTime(enum.IntEnum):
| 64 | 64 | 90 | 9 | 54 | d11z/modlunky2 | src/modlunky2/mem/arena_state.py | Python | ArenaStunTime | ArenaStunTime | 76 | 85 | 76 | 76 | 19f29853fb1c9646170c0cd7c0ba103fe0ebba23 | bigcode/the-stack | train |
23c851b1e769c70e5edb46f9 | train | class | class ArenaCrateFrequency(enum.IntEnum):
NONE = 0
LOW = 1
MEDIUM = 2
HIGH = 3
VERY_HIGH = 4
| class ArenaCrateFrequency(enum.IntEnum):
| NONE = 0
LOW = 1
MEDIUM = 2
HIGH = 3
VERY_HIGH = 4
| LOSER_PICKS = 1
RANDOM_LEVEL = 2
class ArenaDarkLevelChance(enum.IntEnum):
NONE = 0
PERCENT_10 = 1
PERCENT_50 = 2
ALWAYS = 3
class ArenaCrateFrequency(enum.IntEnum):
| 64 | 64 | 41 | 9 | 54 | d11z/modlunky2 | src/modlunky2/mem/arena_state.py | Python | ArenaCrateFrequency | ArenaCrateFrequency | 109 | 114 | 109 | 109 | a901ec02e8a64ae9fdc9ac1fc76f7ac42ca57533 | bigcode/the-stack | train |
4d48ba95c9d8e45a3deba454 | train | class | @serialize(rename_all="spinalcase")
@deserialize(rename_all="spinalcase")
@dataclass(frozen=True)
class ArenaState:
format: ArenaFormat = struct_field(
0x964 - ARENA_STATE_BASE, sc_int8, default=ArenaFormat.DEATHMATCH
)
ruleset: ArenaRuleset = struct_field(
0x965 - ARENA_STATE_BASE, sc_int8,... | @serialize(rename_all="spinalcase")
@deserialize(rename_all="spinalcase")
@dataclass(frozen=True)
class ArenaState:
| format: ArenaFormat = struct_field(
0x964 - ARENA_STATE_BASE, sc_int8, default=ArenaFormat.DEATHMATCH
)
ruleset: ArenaRuleset = struct_field(
0x965 - ARENA_STATE_BASE, sc_int8, default=ArenaRuleset.CUSTOM
)
timer: ArenaTimer = struct_field(
0x978 - ARENA_STATE_BASE, sc_int8, ... | NEOBABYLON_5 = enum.auto()
SUNKENCITY_1 = enum.auto()
SUNKENCITY_2 = enum.auto()
SUNKENCITY_3 = enum.auto()
SUNKENCITY_4 = enum.auto()
SUNKENCITY_5 = enum.auto()
ARENA_STATE_BASE = 0x95C
# Used for both Arena Config and Arena Levels which both happen to be
# 40-tuple of bools.
TupleBool40 = Tuple... | 256 | 256 | 1,011 | 28 | 228 | d11z/modlunky2 | src/modlunky2/mem/arena_state.py | Python | ArenaState | ArenaState | 275 | 356 | 275 | 278 | e1a9adcc1a64a99f802f88802505332293732d7f | bigcode/the-stack | train |
7519ae198b4f629b489d8ac4 | train | class | class ArenaLevel(enum.IntEnum):
DWELLING_1 = 0
DWELLING_2 = enum.auto()
DWELLING_3 = enum.auto()
DWELLING_4 = enum.auto()
DWELLING_5 = enum.auto()
JUNGLE_1 = enum.auto()
JUNGLE_2 = enum.auto()
JUNGLE_3 = enum.auto()
JUNGLE_4 = enum.auto()
JUNGLE_5 = enum.auto()
VOLCANA_1 = en... | class ArenaLevel(enum.IntEnum):
| DWELLING_1 = 0
DWELLING_2 = enum.auto()
DWELLING_3 = enum.auto()
DWELLING_4 = enum.auto()
DWELLING_5 = enum.auto()
JUNGLE_1 = enum.auto()
JUNGLE_2 = enum.auto()
JUNGLE_3 = enum.auto()
JUNGLE_4 = enum.auto()
JUNGLE_5 = enum.auto()
VOLCANA_1 = enum.auto()
VOLCANA_2 = enum.a... | .auto()
PITCHERS_MITT = enum.auto()
SPIKE_SHOES = enum.auto()
SPRING_SHOES = enum.auto()
PARACHUTE = enum.auto()
CAPE = enum.auto()
VLADS_CAPE = enum.auto()
JETPACK = enum.auto()
HOVERPACK = enum.auto()
TELEPACK = enum.auto()
POWERPACK = enum.auto()
EXCALIBUR = enum.auto()
... | 126 | 126 | 422 | 7 | 119 | d11z/modlunky2 | src/modlunky2/mem/arena_state.py | Python | ArenaLevel | ArenaLevel | 185 | 225 | 185 | 185 | 779d2587a714000ba3782e390aceeab11ee40fdf | bigcode/the-stack | train |
e1bf7d50bfbc334adea09caa | train | class | class ArenaTimerEnding(enum.IntEnum):
ROUND_ENDS = 0
DEATH_MIST = 1
ALIEN_BLAST = 2
LOOSE_BOMBS = 3
GHOST = 4
RANDOM = 5
| class ArenaTimerEnding(enum.IntEnum):
| ROUND_ENDS = 0
DEATH_MIST = 1
ALIEN_BLAST = 2
LOOSE_BOMBS = 3
GHOST = 4
RANDOM = 5
| TIME_08_00 = 15
TIME_08_30 = 16
TIME_09_00 = 17
TIME_09_30 = 18
TIME_10_00 = 19
INFINITE = 20
class ArenaTimerEnding(enum.IntEnum):
| 64 | 64 | 57 | 8 | 55 | d11z/modlunky2 | src/modlunky2/mem/arena_state.py | Python | ArenaTimerEnding | ArenaTimerEnding | 54 | 60 | 54 | 54 | 00768217601d39bc4274e7bad9a2dc50bf17c865 | bigcode/the-stack | train |
613151313665fbeb2d9dcbf2 | train | class | class LinearSpaceDecoderWrapper(RNNCell):
"""Operator adding a linear encoder to an RNN cell"""
def __init__(self, cell, output_size, w_name, b_name, scope=None):
"""Create a cell with with a linear encoder in space.
Args:
cell: an RNNCell. The input is passed through a linear layer.
... | class LinearSpaceDecoderWrapper(RNNCell):
| """Operator adding a linear encoder to an RNN cell"""
def __init__(self, cell, output_size, w_name, b_name, scope=None):
"""Create a cell with with a linear encoder in space.
Args:
cell: an RNNCell. The input is passed through a linear layer.
Raises:
TypeError: if ce... | ._cell = cell
@property
def state_size(self):
return self._cell.state_size
@property
def output_size(self):
return self._cell.output_size
def __call__(self, inputs, state, scope=None):
"""Run the cell and add a residual connection."""
output, new_state = self._cel... | 130 | 130 | 434 | 9 | 120 | TuyenNguyenTanViet/ForecastingNonverbalSignals | lib/rnn_cell_extensions.py | Python | LinearSpaceDecoderWrapper | LinearSpaceDecoderWrapper | 49 | 102 | 49 | 49 | ea949b66df485b79f25bcacabd8ed822749c18e4 | bigcode/the-stack | train |
b749e1a0c77d94db210b05da | train | class | class ResidualWrapper(RNNCell):
"""Operator adding residual connections to a given cell."""
def __init__(self, cell):
"""Create a cell with added residual connection.
Args:
cell: an RNNCell. The input is added to the output.
Raises:
TypeError: if cell is not an R... | class ResidualWrapper(RNNCell):
| """Operator adding residual connections to a given cell."""
def __init__(self, cell):
"""Create a cell with added residual connection.
Args:
cell: an RNNCell. The input is added to the output.
Raises:
TypeError: if cell is not an RNNCell.
"""
if n... | pkg_resources import parse_version as pv
if pv(tf.__version__) >= pv('1.2.0'):
from tensorflow.contrib.rnn import LSTMStateTuple
else:
from tensorflow.contrib.rnn.python.ops.core_rnn_cell import LSTMStateTuple
del pv
class ResidualWrapper(RNNCell):
| 66 | 66 | 223 | 8 | 57 | TuyenNguyenTanViet/ForecastingNonverbalSignals | lib/rnn_cell_extensions.py | Python | ResidualWrapper | ResidualWrapper | 16 | 46 | 16 | 16 | 9f333506c62a3a8385b0a6430363218fb13521e4 | bigcode/the-stack | train |
db59d3e08b9fc229a2e55cbc | train | class | class MultipleChoicesTest(unittest.TestCase):
def test_init(self):
# It is really just like a list
self.assertEquals([], MultipleChoices())
self.assertEquals(['a'], MultipleChoices(['a']))
self.assertEquals(['a'], MultipleChoices('a'))
def test_contains_for_a_single_item(self):... | class MultipleChoicesTest(unittest.TestCase):
| def test_init(self):
# It is really just like a list
self.assertEquals([], MultipleChoices())
self.assertEquals(['a'], MultipleChoices(['a']))
self.assertEquals(['a'], MultipleChoices('a'))
def test_contains_for_a_single_item(self):
subject = MultipleChoices(['a', 'b'])
... | #!/usr/bin/env python3
import os
import unittest
from unittest import mock
from quibble import cmd
from quibble.cmd import MultipleChoices
import quibble.commands
class MultipleChoicesTest(unittest.TestCase):
| 45 | 71 | 238 | 8 | 36 | kostajh/quibble | tests/test_cmd.py | Python | MultipleChoicesTest | MultipleChoicesTest | 12 | 40 | 12 | 13 | 5c2446636286123d5089da4b5baa0f254762ba6d | bigcode/the-stack | train |
8dcbb4a6fa56b947165f875e | train | class | class CmdTest(unittest.TestCase):
@mock.patch.dict('os.environ', clear=True)
def test_projects_to_clone(self):
q = cmd.QuibbleCmd()
self.assertEqual(
q.set_repos_to_clone(),
['mediawiki/core', 'mediawiki/skins/Vector'],
'Incorrect repos to clone')
@mock.... | class CmdTest(unittest.TestCase):
@mock.patch.dict('os.environ', clear=True)
| def test_projects_to_clone(self):
q = cmd.QuibbleCmd()
self.assertEqual(
q.set_repos_to_clone(),
['mediawiki/core', 'mediawiki/skins/Vector'],
'Incorrect repos to clone')
@mock.patch.dict('os.environ', clear=True)
def test_projects_to_clone_with_vendor(se... | MultipleChoicesTest(unittest.TestCase):
def test_init(self):
# It is really just like a list
self.assertEquals([], MultipleChoices())
self.assertEquals(['a'], MultipleChoices(['a']))
self.assertEquals(['a'], MultipleChoices('a'))
def test_contains_for_a_single_item(self):
... | 256 | 256 | 2,279 | 19 | 237 | kostajh/quibble | tests/test_cmd.py | Python | CmdTest | CmdTest | 43 | 300 | 43 | 45 | 74510b87190fce084faca76a55fcf430def4fa1b | bigcode/the-stack | train |
4053bf328d37d95f80328e3f | train | class | @bacpypes_debugging
class BVLLServiceElement(ApplicationServiceElement):
def __init__(self, aseID=None):
if _debug: BVLLServiceElement._debug("__init__ aseID=%r", aseID)
ApplicationServiceElement.__init__(self, aseID)
def indication(self, npdu, forwarded=False):
if _debug: BVLLServiceE... | @bacpypes_debugging
class BVLLServiceElement(ApplicationServiceElement):
| def __init__(self, aseID=None):
if _debug: BVLLServiceElement._debug("__init__ aseID=%r", aseID)
ApplicationServiceElement.__init__(self, aseID)
def indication(self, npdu, forwarded=False):
if _debug: BVLLServiceElement._debug("indication %r %r", npdu)
# redirect
fn = n... | range(len(self.bbmdBDT)-1, -1, -1):
if addr == self.bbmdBDT[i]:
del self.bbmdBDT[i]
break
else:
pass
#
# BVLLServiceElement
#
@bacpypes_debugging
class BVLLServiceElement(ApplicationServiceElement):
| 70 | 70 | 234 | 16 | 54 | mteter-upenn/bacpypes | py34/bacpypes/bvllservice.py | Python | BVLLServiceElement | BVLLServiceElement | 940 | 965 | 940 | 942 | de70902086ec309085cbe4aa0d54c3616d51ccb6 | bigcode/the-stack | train |
7581dac8dd4090a626673378 | train | class | class _MultiplexServer(Server):
def __init__(self, mux):
Server.__init__(self)
self.multiplexer = mux
def indication(self, pdu):
self.multiplexer.indication(self, pdu)
| class _MultiplexServer(Server):
| def __init__(self, mux):
Server.__init__(self)
self.multiplexer = mux
def indication(self, pdu):
self.multiplexer.indication(self, pdu)
| lex Client and Server
#
class _MultiplexClient(Client):
def __init__(self, mux):
Client.__init__(self)
self.multiplexer = mux
def confirmation(self, pdu):
self.multiplexer.confirmation(self, pdu)
class _MultiplexServer(Server):
| 64 | 64 | 51 | 7 | 57 | mteter-upenn/bacpypes | py34/bacpypes/bvllservice.py | Python | _MultiplexServer | _MultiplexServer | 45 | 52 | 45 | 46 | 442c9f559d693caab372d7d2eeaf724617081853 | bigcode/the-stack | train |
3504d3a10462b752eb55c436 | train | class | @bacpypes_debugging
class UDPMultiplexer:
def __init__(self, addr=None, noBroadcast=False, rebootQueue=None):
if _debug: UDPMultiplexer._debug("__init__ %r noBroadcast=%r", addr, noBroadcast)
# check for some options
specialBroadcast = False
if addr is None:
self.addres... | @bacpypes_debugging
class UDPMultiplexer:
| def __init__(self, addr=None, noBroadcast=False, rebootQueue=None):
if _debug: UDPMultiplexer._debug("__init__ %r noBroadcast=%r", addr, noBroadcast)
# check for some options
specialBroadcast = False
if addr is None:
self.address = Address()
self.addrTuple = ... | LocalBroadcast, LocalStation, PDU, \
unpack_ip_addr
from .bvll import BVLPDU, DeleteForeignDeviceTableEntry, \
DistributeBroadcastToNetwork, FDTEntry, ForwardedNPDU, \
OriginalBroadcastNPDU, OriginalUnicastNPDU, \
ReadBroadcastDistributionTable, ReadBroadcastDistributionTableAck, \
ReadForeignDevic... | 256 | 256 | 1,026 | 13 | 243 | mteter-upenn/bacpypes | py34/bacpypes/bvllservice.py | Python | UDPMultiplexer | UDPMultiplexer | 58 | 176 | 58 | 60 | ab04e2615c4cdfd8a146b0254ccae9fd7ce0aafb | bigcode/the-stack | train |
57b61956f77e91dbe720fba2 | train | class | class _MultiplexClient(Client):
def __init__(self, mux):
Client.__init__(self)
self.multiplexer = mux
def confirmation(self, pdu):
self.multiplexer.confirmation(self, pdu)
| class _MultiplexClient(Client):
| def __init__(self, mux):
Client.__init__(self)
self.multiplexer = mux
def confirmation(self, pdu):
self.multiplexer.confirmation(self, pdu)
| ReadForeignDeviceTable, ReadForeignDeviceTableAck, RegisterForeignDevice, \
Result, WriteBroadcastDistributionTable, bvl_pdu_types
# some debugging
_debug = 0
_log = ModuleLogger(globals())
#
# _Multiplex Client and Server
#
class _MultiplexClient(Client):
| 64 | 64 | 51 | 7 | 57 | mteter-upenn/bacpypes | py34/bacpypes/bvllservice.py | Python | _MultiplexClient | _MultiplexClient | 36 | 43 | 36 | 37 | ee9455ea2b9f6af1866ffef02a7f7084c080f62d | bigcode/the-stack | train |
00b428f7d0b98a15855f91ce | train | class | @bacpypes_debugging
class AnnexJCodec(Client, Server):
def __init__(self, cid=None, sid=None):
if _debug: AnnexJCodec._debug("__init__ cid=%r sid=%r", cid, sid)
Client.__init__(self, cid)
Server.__init__(self, sid)
def indication(self, rpdu):
if _debug: AnnexJCodec._debug("indi... | @bacpypes_debugging
class AnnexJCodec(Client, Server):
| def __init__(self, cid=None, sid=None):
if _debug: AnnexJCodec._debug("__init__ cid=%r sid=%r", cid, sid)
Client.__init__(self, cid)
Server.__init__(self, sid)
def indication(self, rpdu):
if _debug: AnnexJCodec._debug("indication %r", rpdu)
# encode it as a generic BVLL... | debug("delete_peer %r", peerAddr)
# get the peer networks
# networks = self.peers[peerAddr]
### send a control message upstream that these are no longer reachable
# now delete the peer
del self.peers[peerAddr]
#
# AnnexJCodec
#
@bacpypes_debugging
class AnnexJCodec(Client, ... | 81 | 81 | 270 | 15 | 66 | mteter-upenn/bacpypes | py34/bacpypes/bvllservice.py | Python | AnnexJCodec | AnnexJCodec | 268 | 302 | 268 | 270 | 4bcb2e2f1a2282a131c7352b223d5f4c3940a0b6 | bigcode/the-stack | train |
aa4e009841158a6bc35c4110 | train | class | @bacpypes_debugging
class BIPSimple(BIPSAP, Client, Server):
def __init__(self, sapID=None, cid=None, sid=None):
"""A BIP node."""
if _debug: BIPSimple._debug("__init__ sapID=%r cid=%r sid=%r", sapID, cid, sid)
BIPSAP.__init__(self, sapID)
Client.__init__(self, cid)
Server._... | @bacpypes_debugging
class BIPSimple(BIPSAP, Client, Server):
| def __init__(self, sapID=None, cid=None, sid=None):
"""A BIP node."""
if _debug: BIPSimple._debug("__init__ sapID=%r cid=%r sid=%r", sapID, cid, sid)
BIPSAP.__init__(self, sapID)
Client.__init__(self, cid)
Server.__init__(self, sid)
def indication(self, pdu, forwarded=Fa... | ]()
rpdu.decode(bvlpdu)
# send it upstream
self.response(rpdu)
#
# BIPSAP
#
@bacpypes_debugging
class BIPSAP(ServiceAccessPoint):
def __init__(self, sap=None):
"""A BIP service access point."""
if _debug: BIPSAP._debug("__init__ sap=%r", sap)
ServiceAccessPoint.... | 237 | 237 | 791 | 19 | 218 | mteter-upenn/bacpypes | py34/bacpypes/bvllservice.py | Python | BIPSimple | BIPSimple | 332 | 407 | 332 | 334 | 1a407033d14123d93a4557bce0dfe6ba20c1165d | bigcode/the-stack | train |
4874f74251fbe0e911879c02 | train | class | @bacpypes_debugging
class BIPBBMD(BIPSAP, Client, Server, RecurringTask, DebugContents):
_debug_contents = ('bbmdAddress', 'bbmdBDT+', 'bbmdFDT+')
def __init__(self, addr, sapID=None, cid=None, sid=None):
"""A BBMD node."""
if _debug: BIPBBMD._debug("__init__ %r sapID=%r cid=%r sid=%r", addr, ... | @bacpypes_debugging
class BIPBBMD(BIPSAP, Client, Server, RecurringTask, DebugContents):
| _debug_contents = ('bbmdAddress', 'bbmdBDT+', 'bbmdFDT+')
def __init__(self, addr, sapID=None, cid=None, sid=None):
"""A BBMD node."""
if _debug: BIPBBMD._debug("__init__ %r sapID=%r cid=%r sid=%r", addr, sapID, cid, sid)
BIPSAP.__init__(self, sapID)
Client.__init__(self, cid)
... | .bbmdAddress = Address(addr)
self.bbmdTimeToLive = ttl
# install this task to run when it gets a chance
self.install_task(0)
def unregister(self):
if _debug: BIPForeign._debug("unregister")
"""Drop the registration with a BBMD."""
pdu = RegisterForeignDevice(0)
... | 256 | 256 | 3,150 | 27 | 229 | mteter-upenn/bacpypes | py34/bacpypes/bvllservice.py | Python | BIPBBMD | BIPBBMD | 618 | 934 | 618 | 620 | 03c7ada4e2a5f4229304f004b5b5226227e868d8 | bigcode/the-stack | train |
7b45389811792675a2e967cc | train | class | @bacpypes_debugging
class BIPForeign(BIPSAP, Client, Server, OneShotTask, DebugContents):
_debug_contents = ('registrationStatus', 'bbmdAddress', 'bbmdTimeToLive')
def __init__(self, addr=None, ttl=None, sapID=None, cid=None, sid=None):
"""A BIP node."""
if _debug: BIPForeign._debug("__init__ ... | @bacpypes_debugging
class BIPForeign(BIPSAP, Client, Server, OneShotTask, DebugContents):
| _debug_contents = ('registrationStatus', 'bbmdAddress', 'bbmdTimeToLive')
def __init__(self, addr=None, ttl=None, sapID=None, cid=None, sid=None):
"""A BIP node."""
if _debug: BIPForeign._debug("__init__ addr=%r ttl=%r sapID=%r cid=%r sid=%r", addr, ttl, sapID, cid, sid)
BIPSAP.__init__... | du, forwarded=forwarded)
elif isinstance(pdu, OriginalBroadcastNPDU):
# build a PDU with a local broadcast address
xpdu = PDU(pdu.pduData, source=pdu.pduSource, destination=LocalBroadcast(), user_data=pdu.pduUserData)
if _debug: BIPSimple._debug(" - xpdu: %r", xpdu)
... | 256 | 256 | 2,020 | 26 | 230 | mteter-upenn/bacpypes | py34/bacpypes/bvllservice.py | Python | BIPForeign | BIPForeign | 413 | 612 | 413 | 415 | ea611ff9314493665dec10a4b21df8931e9fe91c | bigcode/the-stack | train |
eb5ab04fe834191ffb248e00 | train | class | @bacpypes_debugging
class BTR(Client, Server, DebugContents):
_debug_contents = ('peers+',)
def __init__(self, cid=None, sid=None):
"""An Annex-H BACnet Tunneling Router node."""
if _debug: BTR._debug("__init__ cid=%r sid=%r", cid, sid)
Client.__init__(self, cid)
Server.__init_... | @bacpypes_debugging
class BTR(Client, Server, DebugContents):
| _debug_contents = ('peers+',)
def __init__(self, cid=None, sid=None):
"""An Annex-H BACnet Tunneling Router node."""
if _debug: BTR._debug("__init__ cid=%r sid=%r", cid, sid)
Client.__init__(self, cid)
Server.__init__(self, sid)
# initialize a dicitonary of peers
... | # must have at least one octet
if not pdu.pduData:
if _debug: UDPMultiplexer._debug(" - no data")
return
# extract the first octet
msg_type = pdu.pduData[0]
# check for the message type
if msg_type == 0x01:
if self.annexH.serverPeer:
... | 184 | 184 | 614 | 17 | 167 | mteter-upenn/bacpypes | py34/bacpypes/bvllservice.py | Python | BTR | BTR | 182 | 262 | 182 | 184 | bfc2c857fc373f94978236ccd32a2ddf0f41cbca | bigcode/the-stack | train |
1a5c6905b107428d23f77ddb | train | class | @bacpypes_debugging
class BIPSAP(ServiceAccessPoint):
def __init__(self, sap=None):
"""A BIP service access point."""
if _debug: BIPSAP._debug("__init__ sap=%r", sap)
ServiceAccessPoint.__init__(self, sap)
def sap_indication(self, pdu, forwarded=False):
if _debug: BIPSAP._debug... | @bacpypes_debugging
class BIPSAP(ServiceAccessPoint):
| def __init__(self, sap=None):
"""A BIP service access point."""
if _debug: BIPSAP._debug("__init__ sap=%r", sap)
ServiceAccessPoint.__init__(self, sap)
def sap_indication(self, pdu, forwarded=False):
if _debug: BIPSAP._debug("sap_indication %r", pdu)
# this is a request... |
rpdu = bvl_pdu_types[bvlpdu.bvlciFunction]()
rpdu.decode(bvlpdu)
# send it upstream
self.response(rpdu)
#
# BIPSAP
#
@bacpypes_debugging
class BIPSAP(ServiceAccessPoint):
| 64 | 64 | 179 | 15 | 49 | mteter-upenn/bacpypes | py34/bacpypes/bvllservice.py | Python | BIPSAP | BIPSAP | 308 | 326 | 308 | 310 | 3df9df32187ecace691bf67ef146fdf2a6ac275d | bigcode/the-stack | train |
79e066c991ab69c25ce7c4f8 | train | class | class Migration(migrations.Migration):
dependencies = [
('core', '0010_archer_agb_age'),
]
operations = [
migrations.AddField(
model_name='user',
name='name',
field=models.CharField(default='', max_length=255),
),
]
| class Migration(migrations.Migration):
| dependencies = [
('core', '0010_archer_agb_age'),
]
operations = [
migrations.AddField(
model_name='user',
name='name',
field=models.CharField(default='', max_length=255),
),
]
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
| 31 | 64 | 62 | 7 | 23 | mjtamlyn/tamlynscore | core/migrations/0011_user_name.py | Python | Migration | Migration | 7 | 19 | 7 | 8 | 8377d086cbe11689aa08b692733825f6208a5993 | bigcode/the-stack | train |
fd56c4b64e814177cc30a261 | train | function | @then(r'I see {metrics_count} metrics emitted')
def _i_see_metrics_emitted(context, metrics_count):
metrics = list(LocalMonitoring(context.medusa_config).load_metrics())
logging.info('There is {} metrics'.format(len(metrics)))
logging.info('The metrics are: {}'.format(metrics))
assert int(len(metrics)) ... | @then(r'I see {metrics_count} metrics emitted')
def _i_see_metrics_emitted(context, metrics_count):
| metrics = list(LocalMonitoring(context.medusa_config).load_metrics())
logging.info('There is {} metrics'.format(len(metrics)))
logging.info('The metrics are: {}'.format(metrics))
assert int(len(metrics)) == int(metrics_count)
| def _i_purge_the_backup_history_to_retain_only_nb_backups(context, backup_count):
medusa.purge.main(context.medusa_config, max_backup_count=int(backup_count))
@then(r'I see {metrics_count} metrics emitted')
def _i_see_metrics_emitted(context, metrics_count):
| 64 | 64 | 75 | 25 | 39 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _i_see_metrics_emitted | _i_see_metrics_emitted | 456 | 461 | 456 | 457 | 9e2b71b3168cd13e3cff573aa8a0c1d552cac296 | bigcode/the-stack | train |
a2e6f30e8eb2f0fa0edbba42 | train | function | @when(r'I truncate the backup index')
def _truncate_the_index(context):
path_root = "/tmp/medusa_it_bucket"
index_path = '{}/index'.format(path_root)
shutil.rmtree(index_path)
| @when(r'I truncate the backup index')
def _truncate_the_index(context):
| path_root = "/tmp/medusa_it_bucket"
index_path = '{}/index'.format(path_root)
shutil.rmtree(index_path)
| _cluster_backup_is(context, expected_backup_name):
storage = Storage(config=context.medusa_config.storage)
actual_backup = storage.latest_complete_cluster_backup()
if actual_backup is not None:
assert expected_backup_name == actual_backup.name
@when(r'I truncate the backup index')
def _truncate_the_... | 64 | 64 | 47 | 16 | 47 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _truncate_the_index | _truncate_the_index | 377 | 381 | 377 | 378 | 09f2c7bd7869910de4a6c517dee953c47de67c72 | bigcode/the-stack | train |
a2e2f16a9e557cf78239a5fb | train | function | @then(r'the latest complete cluster backup is "{expected_backup_name}"')
def _the_latest_complete_cluster_backup_is(context, expected_backup_name):
storage = Storage(config=context.medusa_config.storage)
actual_backup = storage.latest_complete_cluster_backup()
if actual_backup is not None:
assert ex... | @then(r'the latest complete cluster backup is "{expected_backup_name}"')
def _the_latest_complete_cluster_backup_is(context, expected_backup_name):
| storage = Storage(config=context.medusa_config.storage)
actual_backup = storage.latest_complete_cluster_backup()
if actual_backup is not None:
assert expected_backup_name == actual_backup.name
| print backups without errors')
def _can_list_print_backups_without_error(context):
medusa.listing.list_backups(config=context.medusa_config, show_all=True)
@then(r'the latest complete cluster backup is "{expected_backup_name}"')
def _the_latest_complete_cluster_backup_is(context, expected_backup_name):
| 64 | 64 | 69 | 30 | 34 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _the_latest_complete_cluster_backup_is | _the_latest_complete_cluster_backup_is | 369 | 374 | 369 | 370 | 82a90ed188c6f10ce5766e5b63f284a6e4cc2f89 | bigcode/the-stack | train |
1cc8e3629d33da03dd0191b8 | train | function | @then(r'I can report latest backups without errors')
def _can_report_backups_without_errors(context):
medusa.report_latest.report_latest(config=context.medusa_config, push_metrics=True)
| @then(r'I can report latest backups without errors')
def _can_report_backups_without_errors(context):
| medusa.report_latest.report_latest(config=context.medusa_config, push_metrics=True)
| format(path_root)
shutil.rmtree(backup_path)
@when(r'I re-create the backup index')
def _recreate_the_index(context):
medusa.index.build_indices(context.medusa_config, False)
@then(r'I can report latest backups without errors')
def _can_report_backups_without_errors(context):
| 64 | 64 | 38 | 21 | 43 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _can_report_backups_without_errors | _can_report_backups_without_errors | 396 | 398 | 396 | 397 | 7ac3b7b2a0dfee5359a8c87a9d927b982e125223 | bigcode/the-stack | train |
7ae8c557446f10218a4605ea | train | function | @then(r'there is no latest complete backup')
def _there_is_no_latest_complete_backup(context):
storage = Storage(config=context.medusa_config.storage)
actual_backup = storage.latest_complete_cluster_backup()
assert actual_backup is None
| @then(r'there is no latest complete backup')
def _there_is_no_latest_complete_backup(context):
| storage = Storage(config=context.medusa_config.storage)
actual_backup = storage.latest_complete_cluster_backup()
assert actual_backup is None
| }"')
def _the_latest_cluster_backup_is(context, expected_backup_name):
storage = Storage(config=context.medusa_config.storage)
backup = storage.latest_cluster_backup()
assert expected_backup_name == backup.name
@then(r'there is no latest complete backup')
def _there_is_no_latest_complete_backup(context):
| 64 | 64 | 49 | 21 | 42 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _there_is_no_latest_complete_backup | _there_is_no_latest_complete_backup | 357 | 361 | 357 | 358 | 55719071f725549a9bf279aa95bccf2856c2dcc7 | bigcode/the-stack | train |
62202c55f92efb3e135b88e2 | train | function | def connect_cassandra():
connected = False
attempt = 0
session = None
while not connected and attempt < 10:
try:
cluster = Cluster(['127.0.0.1'])
session = cluster.connect()
connected = True
except cassandra.cluster.NoHostAvailable:
attempt... | def connect_cassandra():
| connected = False
attempt = 0
session = None
while not connected and attempt < 10:
try:
cluster = Cluster(['127.0.0.1'])
session = cluster.connect()
connected = True
except cassandra.cluster.NoHostAvailable:
attempt += 1
time.sl... | storage=context.medusa_config.storage,
cassandra=context.medusa_config.cassandra,
monitoring=context.medusa_config.monitoring,
restore=_namedtuple_from_dict(ChecksConfig, restore_config),
ssh=None
)
medusa.verify_restore.verify_restore(['localhost'], custom_config)
def co... | 64 | 64 | 83 | 5 | 59 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | connect_cassandra | connect_cassandra | 487 | 500 | 487 | 487 | 0e3387a29431fe3048d71ca656d42e431ab2a077 | bigcode/the-stack | train |
01d5e1f0e728837d50253486 | train | function | @then(r'verify fails on the backup named "{backup_name}"')
def _verify_fails_on_the_backup_named(context, backup_name):
try:
medusa.verify.verify(context.medusa_config, backup_name)
raise AssertionError("Backup verification should have failed but didn't.")
except RuntimeError:
# This exc... | @then(r'verify fails on the backup named "{backup_name}"')
def _verify_fails_on_the_backup_named(context, backup_name):
| try:
medusa.verify.verify(context.medusa_config, backup_name)
raise AssertionError("Backup verification should have failed but didn't.")
except RuntimeError:
# This exception is required to be raised to validate the step
pass
| ):
logging.error("Was expecting {} files, got {}".format(nb_files, len(section['objects'])))
assert len(section['objects']) == int(nb_files)
@then(r'verify fails on the backup named "{backup_name}"')
def _verify_fails_on_the_backup_named(context, backup_name):
| 64 | 64 | 81 | 30 | 34 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _verify_fails_on_the_backup_named | _verify_fails_on_the_backup_named | 441 | 448 | 441 | 442 | c80782c29ef2d3b6fd74bda47094ec33d9a041f9 | bigcode/the-stack | train |
a2c836c07060ed0da1ccf370 | train | function | @then(r'the backup named "{backup_name}" has {nb_sstables} SSTables '
+ r'for the "{table_name}" table in keyspace "{keyspace}"')
def _the_backup_named_backupname_has_nb_sstables_for_the_whatever_table(context, backup_name, nb_sstables, table_name,
... | @then(r'the backup named "{backup_name}" has {nb_sstables} SSTables '
+ r'for the "{table_name}" table in keyspace "{keyspace}"')
def _the_backup_named_backupname_has_nb_sstables_for_the_whatever_table(context, backup_name, nb_sstables, table_name,
... | storage = Storage(config=context.medusa_config.storage)
path = os.path.join(context.medusa_config.storage.fqdn, backup_name, "data", keyspace, table_name)
objects = storage.storage_driver.list_objects(path)
sstables = list(filter(lambda obj: '-Data.db' in obj.name, objects))
if len(sstables) != int(... | @then(r'the backup named "{backup_name}" has {nb_sstables} SSTables '
+ r'for the "{table_name}" table in keyspace "{keyspace}"')
def _the_backup_named_backupname_has_nb_sstables_for_the_whatever_table(context, backup_name, nb_sstables, table_name,
... | 74 | 64 | 204 | 74 | 0 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _the_backup_named_backupname_has_nb_sstables_for_the_whatever_table | _the_backup_named_backupname_has_nb_sstables_for_the_whatever_table | 224 | 235 | 224 | 227 | 4c13618a32d2155084f0b60f6fa6fa3c89d0f9b8 | bigcode/the-stack | train |
13eaf220c62c66357c2e4320 | train | function | @when(r'I run a "{command}" command')
def _i_run_a_whatever_command(context, command):
os.popen(command).read()
| @when(r'I run a "{command}" command')
def _i_run_a_whatever_command(context, command):
| os.popen(command).read()
| , nb_rows, table_name):
for i in range(int(nb_rows)):
context.session.execute("INSERT INTO {} (id, value) VALUES(now(), '{}')".format(table_name, i))
@when(r'I run a "{command}" command')
def _i_run_a_whatever_command(context, command):
| 64 | 64 | 31 | 23 | 41 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _i_run_a_whatever_command | _i_run_a_whatever_command | 178 | 180 | 178 | 179 | 87505489791b68e6288e226af2a5386a65324840 | bigcode/the-stack | train |
5451007a8ab58143dba64c47 | train | function | @when(r'I truncate the backup folder')
def _truncate_the_backup_folder(context):
path_root = "/tmp/medusa_it_bucket"
backup_path = '{}/localhost'.format(path_root)
shutil.rmtree(backup_path)
| @when(r'I truncate the backup folder')
def _truncate_the_backup_folder(context):
| path_root = "/tmp/medusa_it_bucket"
backup_path = '{}/localhost'.format(path_root)
shutil.rmtree(backup_path)
| @when(r'I truncate the backup index')
def _truncate_the_index(context):
path_root = "/tmp/medusa_it_bucket"
index_path = '{}/index'.format(path_root)
shutil.rmtree(index_path)
@when(r'I truncate the backup folder')
def _truncate_the_backup_folder(context):
| 64 | 64 | 49 | 17 | 47 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _truncate_the_backup_folder | _truncate_the_backup_folder | 384 | 388 | 384 | 385 | 4a935d52876b3f3ffb8d88afdc9f20757a8d89d2 | bigcode/the-stack | train |
c61683a13394e8b4324096ce | train | function | @then(r'I can verify the restore verify query "{query}" restored {expected_rows} rows')
def _i_can_verify_the_restore_verify_query_restored_rows(context, query, expected_rows):
restore_config = {
'health_check': 'cql',
'query': query,
'expected_rows': expected_rows
}
custom_config = ... | @then(r'I can verify the restore verify query "{query}" restored {expected_rows} rows')
def _i_can_verify_the_restore_verify_query_restored_rows(context, query, expected_rows):
| restore_config = {
'health_check': 'cql',
'query': query,
'expected_rows': expected_rows
}
custom_config = MedusaConfig(
storage=context.medusa_config.storage,
cassandra=context.medusa_config.cassandra,
monitoring=context.medusa_config.monitoring,
rest... | _table(context, table_name):
context.session = connect_cassandra()
context.session.execute("truncate {}".format(table_name))
@then(r'I can verify the restore verify query "{query}" restored {expected_rows} rows')
def _i_can_verify_the_restore_verify_query_restored_rows(context, query, expected_rows):
| 64 | 64 | 136 | 39 | 25 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _i_can_verify_the_restore_verify_query_restored_rows | _i_can_verify_the_restore_verify_query_restored_rows | 470 | 484 | 470 | 471 | f5dd257201fa47899becac314784cd643eec7584 | bigcode/the-stack | train |
b027b2e126f0e10854eb79e2 | train | function | @when(r'I purge the backup history to retain only {backup_count} backups')
def _i_purge_the_backup_history_to_retain_only_nb_backups(context, backup_count):
medusa.purge.main(context.medusa_config, max_backup_count=int(backup_count))
| @when(r'I purge the backup history to retain only {backup_count} backups')
def _i_purge_the_backup_history_to_retain_only_nb_backups(context, backup_count):
| medusa.purge.main(context.medusa_config, max_backup_count=int(backup_count))
| have failed but didn't.")
except RuntimeError:
# This exception is required to be raised to validate the step
pass
@when(r'I purge the backup history to retain only {backup_count} backups')
def _i_purge_the_backup_history_to_retain_only_nb_backups(context, backup_count):
| 64 | 64 | 56 | 37 | 26 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _i_purge_the_backup_history_to_retain_only_nb_backups | _i_purge_the_backup_history_to_retain_only_nb_backups | 451 | 453 | 451 | 452 | ee0e17e292d7fcd3795bb1aa17ca63c62103bc98 | bigcode/the-stack | train |
6026c6dd263c8fd454dcf7a5 | train | function | @then(r'the backup index does not exist')
def _the_backup_index_does_not_exist(context):
storage = Storage(config=context.medusa_config.storage)
assert False is medusa.index.index_exists(storage)
| @then(r'the backup index does not exist')
def _the_backup_index_does_not_exist(context):
| storage = Storage(config=context.medusa_config.storage)
assert False is medusa.index.index_exists(storage)
| _config, False)
@then(r'I can report latest backups without errors')
def _can_report_backups_without_errors(context):
medusa.report_latest.report_latest(config=context.medusa_config, push_metrics=True)
@then(r'the backup index does not exist')
def _the_backup_index_does_not_exist(context):
| 64 | 64 | 44 | 22 | 42 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _the_backup_index_does_not_exist | _the_backup_index_does_not_exist | 401 | 404 | 401 | 402 | 0065d69baab12dd68419bf0af14d08c7148b8070 | bigcode/the-stack | train |
ae935edf8428dd9fa7b34f90 | train | function | @when(r'I restore the backup named "{backup_name}" with the sstableloader')
def _i_restore_the_backup_named_with_sstableloader(context, backup_name):
medusa.restore_node.restore_node(context.medusa_config, Path("/tmp"), backup_name, in_place=True, keep_auth=False,
seeds=None, ve... | @when(r'I restore the backup named "{backup_name}" with the sstableloader')
def _i_restore_the_backup_named_with_sstableloader(context, backup_name):
| medusa.restore_node.restore_node(context.medusa_config, Path("/tmp"), backup_name, in_place=True, keep_auth=False,
seeds=None, verify=None, keyspaces={}, tables={}, use_sstableloader=True)
| "), backup_name, in_place=True, keep_auth=False,
seeds=None, verify=None, keyspaces={}, tables={}, use_sstableloader=False)
@when(r'I restore the backup named "{backup_name}" with the sstableloader')
def _i_restore_the_backup_named_with_sstableloader(context, backup_name):
| 64 | 64 | 79 | 34 | 30 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _i_restore_the_backup_named_with_sstableloader | _i_restore_the_backup_named_with_sstableloader | 249 | 252 | 249 | 250 | 0662d7c83fb01caaf9c81f51528b32cfd4991a23 | bigcode/the-stack | train |
0fbf96d6eb479cdc44f87fda | train | function | def cleanup_monitoring(context):
LocalMonitoring(context.medusa_config.monitoring).truncate_metric_file()
| def cleanup_monitoring(context):
| LocalMonitoring(context.medusa_config.monitoring).truncate_metric_file()
| err = p.communicate()
for line in out.splitlines():
if b'org.apache.cassandra.service.CassandraDaemon' in line:
logging.info(line)
pid = int(line.split(None, 1)[0])
os.kill(pid, signal.SIGKILL)
def cleanup_monitoring(context):
| 64 | 64 | 20 | 6 | 58 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | cleanup_monitoring | cleanup_monitoring | 57 | 58 | 57 | 57 | 6502a400e09d5f81424dc52c4d38fb9174a87ec9 | bigcode/the-stack | train |
76c3e74fbc8d50af93ecd05c | train | function | @when(r'I re-create the backup index')
def _recreate_the_index(context):
medusa.index.build_indices(context.medusa_config, False)
| @when(r'I re-create the backup index')
def _recreate_the_index(context):
| medusa.index.build_indices(context.medusa_config, False)
| 'I truncate the backup folder')
def _truncate_the_backup_folder(context):
path_root = "/tmp/medusa_it_bucket"
backup_path = '{}/localhost'.format(path_root)
shutil.rmtree(backup_path)
@when(r'I re-create the backup index')
def _recreate_the_index(context):
| 64 | 64 | 31 | 18 | 46 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _recreate_the_index | _recreate_the_index | 391 | 393 | 391 | 392 | f799abba4c1ab59257bfeb797f7fb4ed07a323ca | bigcode/the-stack | train |
705ace9f7e31f71fbc37661d | train | function | @then(r'I can see no backups when I list the backups')
def _i_can_see_no_backups(context):
storage = Storage(config=context.medusa_config.storage)
cluster_backups = storage.list_cluster_backups()
assert 0 == len(list(cluster_backups))
| @then(r'I can see no backups when I list the backups')
def _i_can_see_no_backups(context):
| storage = Storage(config=context.medusa_config.storage)
cluster_backups = storage.list_cluster_backups()
assert 0 == len(list(cluster_backups))
| status command')
def _i_can_see_backup_status_when_i_run_the_status_command(context, backup_name):
medusa.status.status(config=context.medusa_config, backup_name=backup_name)
@then(r'I can see no backups when I list the backups')
def _i_can_see_no_backups(context):
| 64 | 64 | 58 | 25 | 39 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _i_can_see_no_backups | _i_can_see_no_backups | 217 | 221 | 217 | 218 | 7ddba17ba0aba5b2efb21d301d5fcbe62ad13b7e | bigcode/the-stack | train |
a8a2c729e3bad58d1571f3ca | train | function | @then(r'backup named "{backup_name}" has {nb_files} files '
+ r'in the manifest for the "{table_name}" table in keyspace "{keyspace_name}"')
def _backup_named_something_has_nb_files_in_the_manifest(context, backup_name, nb_files, table_name, keyspace_name):
storage = Storage(config=context.medusa_config.stora... | @then(r'backup named "{backup_name}" has {nb_files} files '
+ r'in the manifest for the "{table_name}" table in keyspace "{keyspace_name}"')
def _backup_named_something_has_nb_files_in_the_manifest(context, backup_name, nb_files, table_name, keyspace_name):
| storage = Storage(config=context.medusa_config.storage)
node_backups = storage.list_node_backups()
# Find the backup we're looking for
target_backup = list(filter(lambda backup: backup.name == backup_name, node_backups))[0]
# Parse its manifest
manifest = json.loads(target_backup.manifest)
f... | @then(r'backup named "{backup_name}" has {nb_files} files '
+ r'in the manifest for the "{table_name}" table in keyspace "{keyspace_name}"')
def _backup_named_something_has_nb_files_in_the_manifest(context, backup_name, nb_files, table_name, keyspace_name):
| 66 | 64 | 211 | 66 | 0 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _backup_named_something_has_nb_files_in_the_manifest | _backup_named_something_has_nb_files_in_the_manifest | 425 | 438 | 425 | 427 | eef2b18dedd1c5aeabd2282b2c5c0bc57d28d6ea | bigcode/the-stack | train |
2cf30593c108903b42df9f91 | train | function | def kill_cassandra():
p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)
out, err = p.communicate()
for line in out.splitlines():
if b'org.apache.cassandra.service.CassandraDaemon' in line:
logging.info(line)
pid = int(line.split(None, 1)[0])
os.kill(pid, ... | def kill_cassandra():
| p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)
out, err = p.communicate()
for line in out.splitlines():
if b'org.apache.cassandra.service.CassandraDaemon' in line:
logging.info(line)
pid = int(line.split(None, 1)[0])
os.kill(pid, signal.SIGKILL)
|
import medusa.status
import medusa.verify
from medusa.config import MedusaConfig, StorageConfig, CassandraConfig, MonitoringConfig, ChecksConfig
from medusa.config import _namedtuple_from_dict
from medusa.storage import Storage
from medusa.monitoring import LocalMonitoring
def kill_cassandra():
| 64 | 64 | 81 | 5 | 58 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | kill_cassandra | kill_cassandra | 47 | 54 | 47 | 47 | 4115abe8b7ca50d983cd6c6381c8b7b11cd3025a | bigcode/the-stack | train |
8f2fa1e09412e1f3581fa9ef | train | function | @when(r'I load {nb_rows} rows in the "{table_name}" table')
def _i_load_rows_in_the_whatever_table(context, nb_rows, table_name):
for i in range(int(nb_rows)):
context.session.execute("INSERT INTO {} (id, value) VALUES(now(), '{}')".format(table_name, i))
| @when(r'I load {nb_rows} rows in the "{table_name}" table')
def _i_load_rows_in_the_whatever_table(context, nb_rows, table_name):
| for i in range(int(nb_rows)):
context.session.execute("INSERT INTO {} (id, value) VALUES(now(), '{}')".format(table_name, i))
| EXISTS {}.{} (id timeuuid PRIMARY KEY, value text);"
context.session.execute(table.format(keyspace_name, table_name))
@when(r'I load {nb_rows} rows in the "{table_name}" table')
def _i_load_rows_in_the_whatever_table(context, nb_rows, table_name):
| 64 | 64 | 70 | 36 | 28 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _i_load_rows_in_the_whatever_table | _i_load_rows_in_the_whatever_table | 172 | 175 | 172 | 173 | fde79c2cacd7dfa334f31bd7d9c9fe264610e128 | bigcode/the-stack | train |
e642b53d32b821ee61aae946 | train | function | @then(r'I can see the backup named "{backup_name}" when I list the backups')
def _i_can_see_the_backup_named_backupname_when_i_list_the_backups(context, backup_name):
storage = Storage(config=context.medusa_config.storage)
cluster_backups = storage.list_cluster_backups()
found = False
for backup in clus... | @then(r'I can see the backup named "{backup_name}" when I list the backups')
def _i_can_see_the_backup_named_backupname_when_i_list_the_backups(context, backup_name):
| storage = Storage(config=context.medusa_config.storage)
cluster_backups = storage.list_cluster_backups()
found = False
for backup in cluster_backups:
if backup.name == backup_name:
found = True
assert found is True
| , backup_name):
medusa.backup.main(context.medusa_config, backup_name, None, backup_mode)
@then(r'I can see the backup named "{backup_name}" when I list the backups')
def _i_can_see_the_backup_named_backupname_when_i_list_the_backups(context, backup_name):
| 64 | 64 | 95 | 41 | 23 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _i_can_see_the_backup_named_backupname_when_i_list_the_backups | _i_can_see_the_backup_named_backupname_when_i_list_the_backups | 188 | 197 | 188 | 189 | 1b4b0bd21b37c3eff95ed233fe692d5e2d4a95cb | bigcode/the-stack | train |
a8e741a262e66b5f67a06aad | train | function | @then(r'I can verify the backup named "{backup_name}" successfully')
def _i_can_verify_the_backup_named_successfully(context, backup_name):
medusa.verify.verify(context.medusa_config, backup_name)
| @then(r'I can verify the backup named "{backup_name}" successfully')
def _i_can_verify_the_backup_named_successfully(context, backup_name):
| medusa.verify.verify(context.medusa_config, backup_name)
| sstables))
logging.error("Was expecting {} SSTables".format(nb_sstables))
assert len(sstables) == int(nb_sstables)
@then(r'I can verify the backup named "{backup_name}" successfully')
def _i_can_verify_the_backup_named_successfully(context, backup_name):
| 64 | 64 | 43 | 30 | 34 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _i_can_verify_the_backup_named_successfully | _i_can_verify_the_backup_named_successfully | 238 | 240 | 238 | 239 | 59f0d4aff2a9e489b03efbf55945fff536a7b054 | bigcode/the-stack | train |
1596b07364c0171135fa90c4 | train | function | @then(r'I can see the backup index entry for "{backup_name}"')
def _the_backup_named_backupname_is_present_in_the_index(context, backup_name):
storage = Storage(config=context.medusa_config.storage)
fqdn = context.medusa_config.storage.fqdn
path = os.path.join('index/backup_index', backup_name, 'tokenmap_{}... | @then(r'I can see the backup index entry for "{backup_name}"')
def _the_backup_named_backupname_is_present_in_the_index(context, backup_name):
| storage = Storage(config=context.medusa_config.storage)
fqdn = context.medusa_config.storage.fqdn
path = os.path.join('index/backup_index', backup_name, 'tokenmap_{}.json'.format(fqdn))
tokenmap_from_index = storage.storage_driver.get_blob_content_as_string(path)
path = os.path.join(fqdn, backup_nam... | table_name):
context.session = connect_cassandra()
rows = context.session.execute("select count(*) as nb from {}".format(table_name))
assert rows[0].nb == int(nb_rows)
@then(r'I can see the backup index entry for "{backup_name}"')
def _the_backup_named_backupname_is_present_in_the_index(context, backup_nam... | 74 | 74 | 248 | 33 | 41 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _the_backup_named_backupname_is_present_in_the_index | _the_backup_named_backupname_is_present_in_the_index | 268 | 281 | 268 | 269 | 24ae5ec8419d0c85d5f8ce13894d16dc0f177e98 | bigcode/the-stack | train |
ce964ae2f1dafb4d251bed82 | train | function | @then(r'there is no latest backup for node "{fqdn}"')
def _there_is_no_latest_backup_for_node_fqdn(context, fqdn):
storage = Storage(config=context.medusa_config.storage)
node_backup = storage.latest_node_backup(fqdn=fqdn)
assert node_backup is None
| @then(r'there is no latest backup for node "{fqdn}"')
def _there_is_no_latest_backup_for_node_fqdn(context, fqdn):
| storage = Storage(config=context.medusa_config.storage)
node_backup = storage.latest_node_backup(fqdn=fqdn)
assert node_backup is None
| usa_config.storage)
latest_backup = storage.latest_node_backup(fqdn=expected_fqdn)
assert latest_backup.name == expected_backup_name
@then(r'there is no latest backup for node "{fqdn}"')
def _there_is_no_latest_backup_for_node_fqdn(context, fqdn):
| 64 | 64 | 66 | 33 | 30 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _there_is_no_latest_backup_for_node_fqdn | _there_is_no_latest_backup_for_node_fqdn | 291 | 295 | 291 | 292 | 02f692e5411f412365323692de94e32bbc9934aa | bigcode/the-stack | train |
6cb74d83b599807ab065203a | train | function | @then(r'I have {nb_rows} rows in the "{table_name}" table')
def _i_have_rows_in_the_table(context, nb_rows, table_name):
context.session = connect_cassandra()
rows = context.session.execute("select count(*) as nb from {}".format(table_name))
assert rows[0].nb == int(nb_rows)
| @then(r'I have {nb_rows} rows in the "{table_name}" table')
def _i_have_rows_in_the_table(context, nb_rows, table_name):
| context.session = connect_cassandra()
rows = context.session.execute("select count(*) as nb from {}".format(table_name))
assert rows[0].nb == int(nb_rows)
| , in_place=True, keep_auth=False,
seeds=None, verify=None, keyspaces={}, tables={fqtn}, use_sstableloader=False)
@then(r'I have {nb_rows} rows in the "{table_name}" table')
def _i_have_rows_in_the_table(context, nb_rows, table_name):
| 64 | 64 | 72 | 34 | 30 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _i_have_rows_in_the_table | _i_have_rows_in_the_table | 261 | 265 | 261 | 262 | 078a8ad2fe4f67a7d300c7d4c368478a38507817 | bigcode/the-stack | train |
05bcd0c7d87ff32869e55f70 | train | function | @then(r'I can see {nb_sstables} SSTables in the SSTable pool for the "{table_name}" table in keyspace "{keyspace}"')
def _i_can_see_nb_sstables_in_the_sstable_pool(context, nb_sstables, table_name, keyspace):
storage = Storage(config=context.medusa_config.storage)
path = os.path.join(context.medusa_config.stora... | @then(r'I can see {nb_sstables} SSTables in the SSTable pool for the "{table_name}" table in keyspace "{keyspace}"')
def _i_can_see_nb_sstables_in_the_sstable_pool(context, nb_sstables, table_name, keyspace):
| storage = Storage(config=context.medusa_config.storage)
path = os.path.join(context.medusa_config.storage.fqdn, "data", keyspace, table_name)
objects = storage.storage_driver.list_objects(path)
sstables = list(filter(lambda obj: '-Data.db' in obj.name, objects))
if len(sstables) != int(nb_sstables):... | (storage)
@then(r'I can see {nb_sstables} SSTables in the SSTable pool for the "{table_name}" table in keyspace "{keyspace}"')
def _i_can_see_nb_sstables_in_the_sstable_pool(context, nb_sstables, table_name, keyspace):
| 64 | 64 | 189 | 62 | 2 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _i_can_see_nb_sstables_in_the_sstable_pool | _i_can_see_nb_sstables_in_the_sstable_pool | 413 | 422 | 413 | 414 | a146026bc036458fc909a30664ec84a40e5c7420 | bigcode/the-stack | train |
dcae7809018bb6ff02b7c1e3 | train | function | @then(r'I can see the latest backup for "{expected_fqdn}" being called "{expected_backup_name}"')
def _the_latest_backup_for_fqdn_is_called_backupname(context, expected_fqdn, expected_backup_name):
storage = Storage(config=context.medusa_config.storage)
latest_backup = storage.latest_node_backup(fqdn=expected_f... | @then(r'I can see the latest backup for "{expected_fqdn}" being called "{expected_backup_name}"')
def _the_latest_backup_for_fqdn_is_called_backupname(context, expected_fqdn, expected_backup_name):
| storage = Storage(config=context.medusa_config.storage)
latest_backup = storage.latest_node_backup(fqdn=expected_fqdn)
assert latest_backup.name == expected_backup_name
| _from_backup == tokenmap_from_index and manifest_from_backup == manifest_from_index
@then(r'I can see the latest backup for "{expected_fqdn}" being called "{expected_backup_name}"')
def _the_latest_backup_for_fqdn_is_called_backupname(context, expected_fqdn, expected_backup_name):
| 64 | 64 | 86 | 48 | 15 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _the_latest_backup_for_fqdn_is_called_backupname | _the_latest_backup_for_fqdn_is_called_backupname | 284 | 288 | 284 | 285 | d085a170d5772e31005cab356977f970d493f09d | bigcode/the-stack | train |
c165f4702abd7d1cc32cf691 | train | function | @when(r'I restore the backup named "{backup_name}" for "{fqtn}" table')
def _i_restore_the_backup_named_for_table(context, backup_name, fqtn):
medusa.restore_node.restore_node(context.medusa_config, Path("/tmp"), backup_name, in_place=True, keep_auth=False,
seeds=None, verify=No... | @when(r'I restore the backup named "{backup_name}" for "{fqtn}" table')
def _i_restore_the_backup_named_for_table(context, backup_name, fqtn):
| medusa.restore_node.restore_node(context.medusa_config, Path("/tmp"), backup_name, in_place=True, keep_auth=False,
seeds=None, verify=None, keyspaces={}, tables={fqtn}, use_sstableloader=False)
| _name, in_place=True, keep_auth=False,
seeds=None, verify=None, keyspaces={}, tables={}, use_sstableloader=True)
@when(r'I restore the backup named "{backup_name}" for "{fqtn}" table')
def _i_restore_the_backup_named_for_table(context, backup_name, fqtn):
| 64 | 64 | 84 | 36 | 28 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _i_restore_the_backup_named_for_table | _i_restore_the_backup_named_for_table | 255 | 258 | 255 | 256 | 372d58d55478b9910b494877bbc61d0b467a3a67 | bigcode/the-stack | train |
cfb3c487f6561acd750f8247 | train | function | def cleanup_storage(context, storage_provider):
if storage_provider == "local":
if os.path.isdir(os.path.join("/tmp", "medusa_it_bucket")):
shutil.rmtree(os.path.join("/tmp", "medusa_it_bucket"))
os.makedirs(os.path.join("/tmp", "medusa_it_bucket"))
elif storage_provider == "google_s... | def cleanup_storage(context, storage_provider):
| if storage_provider == "local":
if os.path.isdir(os.path.join("/tmp", "medusa_it_bucket")):
shutil.rmtree(os.path.join("/tmp", "medusa_it_bucket"))
os.makedirs(os.path.join("/tmp", "medusa_it_bucket"))
elif storage_provider == "google_storage" or storage_provider.find("s3") == 0:
... | .CassandraDaemon' in line:
logging.info(line)
pid = int(line.split(None, 1)[0])
os.kill(pid, signal.SIGKILL)
def cleanup_monitoring(context):
LocalMonitoring(context.medusa_config.monitoring).truncate_metric_file()
def cleanup_storage(context, storage_provider):
| 64 | 64 | 120 | 8 | 56 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | cleanup_storage | cleanup_storage | 61 | 70 | 61 | 61 | 085b5c5f31579ce928aaa83bf460cff8a735b1aa | bigcode/the-stack | train |
578aa54e1c7fbb47eb71ce83 | train | function | @then('I can see the backup status for "{backup_name}" when I run the status command')
def _i_can_see_backup_status_when_i_run_the_status_command(context, backup_name):
medusa.status.status(config=context.medusa_config, backup_name=backup_name)
| @then('I can see the backup status for "{backup_name}" when I run the status command')
def _i_can_see_backup_status_when_i_run_the_status_command(context, backup_name):
| medusa.status.status(config=context.medusa_config, backup_name=backup_name)
| in cluster_backups:
if backup.name == backup_name:
found = True
assert found is False
@then('I can see the backup status for "{backup_name}" when I run the status command')
def _i_can_see_backup_status_when_i_run_the_status_command(context, backup_name):
| 64 | 64 | 57 | 40 | 23 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _i_can_see_backup_status_when_i_run_the_status_command | _i_can_see_backup_status_when_i_run_the_status_command | 212 | 214 | 212 | 213 | 78ce7a62d6ee06b50d0d1872b94b243eb5ffd692 | bigcode/the-stack | train |
f0f30360a07d87068b54feeb | train | function | @when(r'I restore the backup named "{backup_name}"')
def _i_restore_the_backup_named(context, backup_name):
medusa.restore_node.restore_node(context.medusa_config, Path("/tmp"), backup_name, in_place=True, keep_auth=False,
seeds=None, verify=None, keyspaces={}, tables={}, use_ss... | @when(r'I restore the backup named "{backup_name}"')
def _i_restore_the_backup_named(context, backup_name):
| medusa.restore_node.restore_node(context.medusa_config, Path("/tmp"), backup_name, in_place=True, keep_auth=False,
seeds=None, verify=None, keyspaces={}, tables={}, use_sstableloader=False)
| can verify the backup named "{backup_name}" successfully')
def _i_can_verify_the_backup_named_successfully(context, backup_name):
medusa.verify.verify(context.medusa_config, backup_name)
@when(r'I restore the backup named "{backup_name}"')
def _i_restore_the_backup_named(context, backup_name):
| 64 | 64 | 70 | 25 | 39 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _i_restore_the_backup_named | _i_restore_the_backup_named | 243 | 246 | 243 | 244 | 723168b9adcee32a4f5aaf6706172f78fb0affd7 | bigcode/the-stack | train |
c864b82e950debf50e0ff90e | train | function | @when(r'I perform a backup in "{backup_mode}" mode of the node named "{backup_name}"')
def _i_perform_a_backup_of_the_node_named_backupname(context, backup_mode, backup_name):
medusa.backup.main(context.medusa_config, backup_name, None, backup_mode)
| @when(r'I perform a backup in "{backup_mode}" mode of the node named "{backup_name}"')
def _i_perform_a_backup_of_the_node_named_backupname(context, backup_mode, backup_name):
| medusa.backup.main(context.medusa_config, backup_name, None, backup_mode)
| ')
def _i_run_a_whatever_command(context, command):
os.popen(command).read()
@when(r'I perform a backup in "{backup_mode}" mode of the node named "{backup_name}"')
def _i_perform_a_backup_of_the_node_named_backupname(context, backup_mode, backup_name):
| 64 | 64 | 62 | 43 | 21 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _i_perform_a_backup_of_the_node_named_backupname | _i_perform_a_backup_of_the_node_named_backupname | 183 | 185 | 183 | 184 | 794a1473142498aab0e1a3a96d40538a64abc545 | bigcode/the-stack | train |
ae5e586e72bc0f8976adbaca | train | function | @given(r'I am using "{storage_provider}" as storage provider')
def i_am_using_storage_provider(context, storage_provider):
logging.info("Starting the tests")
if not hasattr(context, 'cluster_name'):
context.cluster_name = 'test'
config = configparser.ConfigParser(interpolation=None)
if storage_... | @given(r'I am using "{storage_provider}" as storage provider')
def i_am_using_storage_provider(context, storage_provider):
| logging.info("Starting the tests")
if not hasattr(context, 'cluster_name'):
context.cluster_name = 'test'
config = configparser.ConfigParser(interpolation=None)
if storage_provider == "local":
if os.path.isdir(os.path.join("/tmp", "medusa_it_bucket")):
shutil.rmtree(os.path.... | context.session = None
context.cluster_name = cluster_name
subprocess.run(["ccm", "stop"], stdout=PIPE, stderr=PIPE)
kill_cassandra()
res = subprocess.run(["ccm", "switch", context.cluster_name], stdout=PIPE, stderr=PIPE)
if b"does not appear to be a valid cluster" not in res.stderr:
subpro... | 183 | 183 | 610 | 25 | 158 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | i_am_using_storage_provider | i_am_using_storage_provider | 89 | 159 | 89 | 90 | 54ca9e38f1721bbf5c7d04954f39de34be877be9 | bigcode/the-stack | train |
29b85ba1a396c3a513a46128 | train | function | @when(r'I create the "{table_name}" table in keyspace "{keyspace_name}"')
def _i_create_the_whatever_table(context, table_name, keyspace_name):
keyspace = """CREATE KEYSPACE IF NOT EXISTS {} WITH replication = {{'class':'SimpleStrategy',
'replication_factor':1}}"""
context.session.execute(keyspace.format(ke... | @when(r'I create the "{table_name}" table in keyspace "{keyspace_name}"')
def _i_create_the_whatever_table(context, table_name, keyspace_name):
| keyspace = """CREATE KEYSPACE IF NOT EXISTS {} WITH replication = {{'class':'SimpleStrategy',
'replication_factor':1}}"""
context.session.execute(keyspace.format(keyspace_name))
table = "CREATE TABLE IF NOT EXISTS {}.{} (id timeuuid PRIMARY KEY, value text);"
context.session.execute(table.format(ke... | monitoring']),
ssh=None,
restore=None
)
cleanup_storage(context, storage_provider)
cleanup_monitoring(context)
@when(r'I create the "{table_name}" table in keyspace "{keyspace_name}"')
def _i_create_the_whatever_table(context, table_name, keyspace_name):
| 64 | 64 | 115 | 37 | 27 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _i_create_the_whatever_table | _i_create_the_whatever_table | 162 | 169 | 162 | 163 | 4b65af24d6a344fcd3d36e9c8550d23a77e652d8 | bigcode/the-stack | train |
113ca33a6eb21ef283057d77 | train | function | @given(r'I have a fresh ccm cluster running named "{cluster_name}"')
def _i_have_a_fresh_ccm_cluster_running(context, cluster_name):
context.cassandra_version = "2.2.14"
context.session = None
context.cluster_name = cluster_name
subprocess.run(["ccm", "stop"], stdout=PIPE, stderr=PIPE)
kill_cassandr... | @given(r'I have a fresh ccm cluster running named "{cluster_name}"')
def _i_have_a_fresh_ccm_cluster_running(context, cluster_name):
| context.cassandra_version = "2.2.14"
context.session = None
context.cluster_name = cluster_name
subprocess.run(["ccm", "stop"], stdout=PIPE, stderr=PIPE)
kill_cassandra()
res = subprocess.run(["ccm", "switch", context.cluster_name], stdout=PIPE, stderr=PIPE)
if b"does not appear to be a vali... | Storage(config=context.medusa_config.storage)
objects = storage.storage_driver.list_objects()
for obj in objects:
storage.storage_driver.delete_object(obj)
@given(r'I have a fresh ccm cluster running named "{cluster_name}"')
def _i_have_a_fresh_ccm_cluster_running(context, cluster_name):
| 64 | 64 | 204 | 33 | 31 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _i_have_a_fresh_ccm_cluster_running | _i_have_a_fresh_ccm_cluster_running | 73 | 86 | 73 | 74 | 99a38d158bb9f1ca5c2db1b1551410924917b29e | bigcode/the-stack | train |
710be9cba28de17326892bc4 | train | function | @then(r'the latest cluster backup is "{expected_backup_name}"')
def _the_latest_cluster_backup_is(context, expected_backup_name):
storage = Storage(config=context.medusa_config.storage)
backup = storage.latest_cluster_backup()
assert expected_backup_name == backup.name
| @then(r'the latest cluster backup is "{expected_backup_name}"')
def _the_latest_cluster_backup_is(context, expected_backup_name):
| storage = Storage(config=context.medusa_config.storage)
backup = storage.latest_cluster_backup()
assert expected_backup_name == backup.name
| map = '{}/{}/{}/meta/tokenmap.json'.format(path_root, fqdn, backup_name)
write_dummy_file(path_tokenmap, backup_datetime, fake_tokenmap)
@then(r'the latest cluster backup is "{expected_backup_name}"')
def _the_latest_cluster_backup_is(context, expected_backup_name):
| 64 | 64 | 56 | 28 | 36 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _the_latest_cluster_backup_is | _the_latest_cluster_backup_is | 350 | 354 | 350 | 351 | 99c4d04048edaa4c2c809b43a6afd40a53d79d95 | bigcode/the-stack | train |
75fca394dceb8f91cfad6baa | train | function | @when(r'I truncate the "{table_name}" table')
def _i_truncate_the_table(context, table_name):
context.session = connect_cassandra()
context.session.execute("truncate {}".format(table_name))
| @when(r'I truncate the "{table_name}" table')
def _i_truncate_the_table(context, table_name):
| context.session = connect_cassandra()
context.session.execute("truncate {}".format(table_name))
| ).load_metrics())
logging.info('There is {} metrics'.format(len(metrics)))
logging.info('The metrics are: {}'.format(metrics))
assert int(len(metrics)) == int(metrics_count)
@when(r'I truncate the "{table_name}" table')
def _i_truncate_the_table(context, table_name):
| 64 | 64 | 43 | 24 | 40 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _i_truncate_the_table | _i_truncate_the_table | 464 | 467 | 464 | 465 | 165e5d0e7598b183ac00797011ff6b4cac2eaea5 | bigcode/the-stack | train |
fe929070531795fa7890122a | train | function | def write_dummy_file(path, mtime_str, contents=None):
# create the file. if there's some contents, write them too
with open(path, 'w') as f:
if contents is not None:
f.write(contents)
f.flush()
f.close()
# we set the access and modification times for the file we just ... | def write_dummy_file(path, mtime_str, contents=None):
# create the file. if there's some contents, write them too
| with open(path, 'w') as f:
if contents is not None:
f.write(contents)
f.flush()
f.close()
# we set the access and modification times for the file we just created
# this time is set as seconds since epoch
t = datetime.datetime.strptime(mtime_str, '%Y-%m-%d %H:%M:%S... | session = cluster.connect()
connected = True
except cassandra.cluster.NoHostAvailable:
attempt += 1
time.sleep(10)
return session
def write_dummy_file(path, mtime_str, contents=None):
# create the file. if there's some contents, write them too
| 64 | 64 | 151 | 28 | 35 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | write_dummy_file | write_dummy_file | 503 | 515 | 503 | 504 | 79fd1fb1c7d997bfd32e8201a0b785abfba0a434 | bigcode/the-stack | train |
4981546a03ff3123fe509986 | train | function | @then(r'the backup index exists')
def _the_backup_index_exists(context):
storage = Storage(config=context.medusa_config.storage)
assert True is medusa.index.index_exists(storage)
| @then(r'the backup index exists')
def _the_backup_index_exists(context):
| storage = Storage(config=context.medusa_config.storage)
assert True is medusa.index.index_exists(storage)
| _metrics=True)
@then(r'the backup index does not exist')
def _the_backup_index_does_not_exist(context):
storage = Storage(config=context.medusa_config.storage)
assert False is medusa.index.index_exists(storage)
@then(r'the backup index exists')
def _the_backup_index_exists(context):
| 64 | 64 | 39 | 17 | 47 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _the_backup_index_exists | _the_backup_index_exists | 407 | 410 | 407 | 408 | 9f13a3492bba764bc4a47037aa3b699b411fc4c1 | bigcode/the-stack | train |
c626d723e6c6603f0ba7c015 | train | function | @then(r'I can list and print backups without errors')
def _can_list_print_backups_without_error(context):
medusa.listing.list_backups(config=context.medusa_config, show_all=True)
| @then(r'I can list and print backups without errors')
def _can_list_print_backups_without_error(context):
| medusa.listing.list_backups(config=context.medusa_config, show_all=True)
| complete backup')
def _there_is_no_latest_complete_backup(context):
storage = Storage(config=context.medusa_config.storage)
actual_backup = storage.latest_complete_cluster_backup()
assert actual_backup is None
@then(r'I can list and print backups without errors')
def _can_list_print_backups_without_error(c... | 64 | 64 | 41 | 23 | 40 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _can_list_print_backups_without_error | _can_list_print_backups_without_error | 364 | 366 | 364 | 365 | 1cc25ed3f4d779f333283cb06221d91fa4b12349 | bigcode/the-stack | train |
f8b21a6d7d3d2e984fb81538 | train | function | @then(r'I cannot see the backup named "{backup_name}" when I list the backups')
def _i_cannot_see_the_backup_named_backupname_when_i_list_the_backups(context, backup_name):
storage = Storage(config=context.medusa_config.storage)
cluster_backups = storage.list_cluster_backups()
found = False
for backup i... | @then(r'I cannot see the backup named "{backup_name}" when I list the backups')
def _i_cannot_see_the_backup_named_backupname_when_i_list_the_backups(context, backup_name):
| storage = Storage(config=context.medusa_config.storage)
cluster_backups = storage.list_cluster_backups()
found = False
for backup in cluster_backups:
if backup.name == backup_name:
found = True
assert found is False
| _backups:
if backup.name == backup_name:
found = True
assert found is True
@then(r'I cannot see the backup named "{backup_name}" when I list the backups')
def _i_cannot_see_the_backup_named_backupname_when_i_list_the_backups(context, backup_name):
| 64 | 64 | 96 | 42 | 21 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _i_cannot_see_the_backup_named_backupname_when_i_list_the_backups | _i_cannot_see_the_backup_named_backupname_when_i_list_the_backups | 200 | 209 | 200 | 201 | ac6e1d2e94ea81722c800fcb164a1e4fcb3fd34d | bigcode/the-stack | train |
ddba0cc8d13a8b4738a8a58c | train | function | @when(r'node "{fqdn}" fakes a complete backup named "{backup_name}" on "{backup_datetime}"')
def _node_fakes_a_complete_backup(context, fqdn, backup_name, backup_datetime):
path_root = "/tmp/medusa_it_bucket"
fake_tokenmap = json.dumps({
"n1": {"tokens": [1], "is_up": True},
"n2": {"tokens": [2... | @when(r'node "{fqdn}" fakes a complete backup named "{backup_name}" on "{backup_datetime}"')
def _node_fakes_a_complete_backup(context, fqdn, backup_name, backup_datetime):
| path_root = "/tmp/medusa_it_bucket"
fake_tokenmap = json.dumps({
"n1": {"tokens": [1], "is_up": True},
"n2": {"tokens": [2], "is_up": True},
"n3": {"tokens": [3], "is_up": True}
})
dir_path = os.path.join(path_root, 'index', 'backup_index', backup_name)
if not os.path.exist... | "{expected_backup_name}"')
def _the_latest_backup_for_fqdn_is_called_backupname(context, expected_fqdn, expected_backup_name):
storage = Storage(config=context.medusa_config.storage)
latest_backup = storage.latest_node_backup(fqdn=expected_fqdn)
assert latest_backup.name == expected_backup_name
@then(r't... | 178 | 178 | 596 | 44 | 133 | chenjiang1985/cassandra-medusa | tests/integration/features/steps/integration_steps.py | Python | _node_fakes_a_complete_backup | _node_fakes_a_complete_backup | 298 | 347 | 298 | 299 | 078b0ec083dea3b0bb3e031eee29191c76b006f9 | bigcode/the-stack | train |
c9ab0bfe76b0c3b03e29a5b7 | train | function | @click.group()
@click.option(
"--debug",
is_flag=True,
default=False,
help="Debug mode: Print to stdout instead of sending to Slack",
)
@click.option(
"--slack-bot-token",
envvar="SLACK_BOT_TOKEN",
help="Bot token to make web API calls to Slack.",
)
@click.option(
"--slack-app-token",
... | @click.group()
@click.option(
"--debug",
is_flag=True,
default=False,
help="Debug mode: Print to stdout instead of sending to Slack",
)
@click.option(
"--slack-bot-token",
envvar="SLACK_BOT_TOKEN",
help="Bot token to make web API calls to Slack.",
)
@click.option(
"--slack-app-token",
... | obj.sc = MFBSlackClientV2(slack_bot_token, slack_app_token=slack_app_token)
if debug:
obj.publish_state = lambda msg: logger(msg, head="[debug state] ")
obj.reply = lambda msg: logger(msg, head="[debug reply] ")
else:
if admin_thread:
obj.publish_state = lambda msg: obj.s... | @click.group()
@click.option(
"--debug",
is_flag=True,
default=False,
help="Debug mode: Print to stdout instead of sending to Slack",
)
@click.option(
"--slack-bot-token",
envvar="SLACK_BOT_TOKEN",
help="Bot token to make web API calls to Slack.",
)
@click.option(
"--slack-app-token",
... | 176 | 98 | 328 | 176 | 0 | valayDave/metaflowbot | metaflowbot/cli.py | Python | cli | cli | 27 | 70 | 27 | 54 | c7ecd91dd12206b9b563d1dc31bb830c79be6eee | bigcode/the-stack | train |
15cce208ccd9964e815d2420 | train | function | @cli.group(help="Bot actions")
@click.pass_obj
def action(ctx):
pass
| @cli.group(help="Bot actions")
@click.pass_obj
def action(ctx):
| pass
| thread")
server.new_admin_thread()
time.sleep(2)
server.reconstruct_state()
except:
raise
log("State reconstructed.")
log(head="Activating the bot..")
server.loop_forever()
@cli.group(help="Bot actions")
@click.pass_obj
def action(ctx):
| 64 | 64 | 19 | 16 | 48 | valayDave/metaflowbot | metaflowbot/cli.py | Python | action | action | 135 | 138 | 135 | 137 | 403d8fac44d08311bc543b894f846334b46adc09 | bigcode/the-stack | train |
e3efc9cb2670cf223f86d7fa | train | function | def logger(body="", system_msg=False, head="", bad=False, timestamp=True):
if timestamp:
tstamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
click.secho(tstamp + " ", fg=LOGGER_TIMESTAMP, nl=False)
if head:
click.secho(head, fg=LOGGER_COLOR, nl=False)
click.secho(body, bold... | def logger(body="", system_msg=False, head="", bad=False, timestamp=True):
| if timestamp:
tstamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
click.secho(tstamp + " ", fg=LOGGER_TIMESTAMP, nl=False)
if head:
click.secho(head, fg=LOGGER_COLOR, nl=False)
click.secho(body, bold=system_msg, fg=LOGGER_BAD_COLOR if bad else None)
| BRules
from .server import MFBServer, StateNotFound
from .slack_client import MFBSlackClientV2
LOGGER_TIMESTAMP = "magenta"
LOGGER_COLOR = "green"
LOGGER_BAD_COLOR = "red"
def logger(body="", system_msg=False, head="", bad=False, timestamp=True):
| 64 | 64 | 102 | 16 | 48 | valayDave/metaflowbot | metaflowbot/cli.py | Python | logger | logger | 18 | 24 | 18 | 18 | 5e7db3d79c3e5f7859a8817d93ed0e43821bb43c | bigcode/the-stack | train |
eb05c79b1571f0b51a21be6c | train | function | @cli.command(help="Start the Metaflow bot server.")
@click.option(
"--admin",
required=True,
help="Email of the admin user (used to idenify the admin " "Slack account).",
)
@click.option(
"--new-admin-thread",
is_flag=True,
default=False,
help="Initialize a new admin thread in a DM between "... | @cli.command(help="Start the Metaflow bot server.")
@click.option(
"--admin",
required=True,
help="Email of the admin user (used to idenify the admin " "Slack account).",
)
@click.option(
"--new-admin-thread",
is_flag=True,
default=False,
help="Initialize a new admin thread in a DM between "... | def log(msg="", **kwargs):
logger(msg, system_msg=True, **kwargs)
if os.getuid() != 0:
action_user = None
spaces = "\n\t\t\t"
modules = spaces.join(SUPPORTED_ACTIONS.keys())
modules_message = f"Discovered the following actions :{spaces}{modules}"
log(modules_message)
rules_o... | @cli.command(help="Start the Metaflow bot server.")
@click.option(
"--admin",
required=True,
help="Email of the admin user (used to idenify the admin " "Slack account).",
)
@click.option(
"--new-admin-thread",
is_flag=True,
default=False,
help="Initialize a new admin thread in a DM between "... | 198 | 130 | 435 | 198 | 0 | valayDave/metaflowbot | metaflowbot/cli.py | Python | server | server | 73 | 132 | 73 | 100 | 4bfb78bd0186eeb2fc635c59d68bb05ea87d9d64 | bigcode/the-stack | train |
309a5796b1aa25a7ba76ab9f | train | class | class PngCorrObject(CorrObject):
"""
Correlation Object that reads a numpy array from a png image file
(converts to greyscale)
"""
def __init__(self, path, parent=None):
self.path = path
self.parent = parent
self.get_array()
#############################################... | class PngCorrObject(CorrObject):
| """
Correlation Object that reads a numpy array from a png image file
(converts to greyscale)
"""
def __init__(self, path, parent=None):
self.path = path
self.parent = parent
self.get_array()
###########################################################
def get_array... | sig_ax.set_xlabel("sample index (at 44kHz)")
sig_ax.set_ylabel('signal amplitude (arb. units)')
sig_fig.savefig(str(img_dir) + '/' + filename + '.png', dpi=600,
bbox_inches='tight')
###############################################################################
class Pn... | 65 | 66 | 221 | 9 | 56 | SamScholten/stereo_vision | correlation_tools.py | Python | PngCorrObject | PngCorrObject | 744 | 771 | 744 | 744 | bedebeb65dafd366a4c033d9c928ea28f05f8a2a | bigcode/the-stack | train |
428e94e2bedc36490a8d59b6 | train | class | class IterableCorrObject(CorrObject):
"""
Hmmm
"""
def __init__(self, oldCorrObj, geom, parent=None):
"""
copy the array from the old correlation object to this one, also
specifying any parent IterableCorrObjects, and the geometry
"""
if not isinstance(oldCorrObj,... | class IterableCorrObject(CorrObject):
| """
Hmmm
"""
def __init__(self, oldCorrObj, geom, parent=None):
"""
copy the array from the old correlation object to this one, also
specifying any parent IterableCorrObjects, and the geometry
"""
if not isinstance(oldCorrObj, CorrObject):
raise TypeEr... | Error('not sure what to do with an image ' +
'inputted with this format')
# otherwise assume grayscale input image
self.ar = image_ar
###############################################################################
class GaussianCorrObject(CorrObject):
"""
c... | 212 | 213 | 710 | 8 | 204 | SamScholten/stereo_vision | correlation_tools.py | Python | IterableCorrObject | IterableCorrObject | 830 | 919 | 830 | 830 | a6be18745c39e881e1febe8b6da7da6cdba7f15a | bigcode/the-stack | train |
4f161a212dc69b4bc4b9e418 | train | function | def pad_to_shape(ar, new_shape):
"""
Zero pads numpy array 'ar' to 'new_shape'. pads down and right (assumes 2d)
Pads with zeros
"""
if np.ndim(ar) != 2:
raise RuntimeError("ar needs to be 2D")
if type(new_shape) is not tuple or len(new_shape) != 2:
raise TypeError("requires new_... | def pad_to_shape(ar, new_shape):
| """
Zero pads numpy array 'ar' to 'new_shape'. pads down and right (assumes 2d)
Pads with zeros
"""
if np.ndim(ar) != 2:
raise RuntimeError("ar needs to be 2D")
if type(new_shape) is not tuple or len(new_shape) != 2:
raise TypeError("requires new_shape to be a tuple of 2 elements... | _change//2
# right = net_change - left
left = 0
right = net_change
pad_width = (left, right)
return np.pad(t, pad_width, 'constant', constant_values=0)
###########################################################
def pad_to_shape(ar, new_shape):
| 63 | 64 | 166 | 9 | 54 | SamScholten/stereo_vision | correlation_tools.py | Python | pad_to_shape | pad_to_shape | 963 | 975 | 963 | 963 | a347c30778c8ddd8d18ac2c7b16edac80dae2ea5 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.