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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2f1b2055173eb39a909cdbf3 | train | function | def test_should_save_tensor_with_tf_collection(out_dir):
hook = helper_create_hook(out_dir, [CollectionKeys.GRADIENTS, CollectionKeys.LAYERS])
for layer in model.layers:
layer_name = layer.name
assert hook.should_save_tensor_or_collection(layer_name, CollectionKeys.GRADIENTS)
assert hook... | def test_should_save_tensor_with_tf_collection(out_dir):
| hook = helper_create_hook(out_dir, [CollectionKeys.GRADIENTS, CollectionKeys.LAYERS])
for layer in model.layers:
layer_name = layer.name
assert hook.should_save_tensor_or_collection(layer_name, CollectionKeys.GRADIENTS)
assert hook.should_save_tensor_or_collection(layer_name, CollectionK... | S)
for layer in model.layers:
layer_name = layer.name
assert not hook.should_save_tensor_or_collection(layer_name, CollectionKeys.GRADIENTS)
assert not hook.should_save_tensor_or_collection(layer_name, CollectionKeys.LAYERS)
def test_should_save_tensor_with_tf_collection(out_dir):
| 64 | 64 | 83 | 11 | 53 | jsspric/sagemaker-debugger | tests/tensorflow2/test_should_save_tensor.py | Python | test_should_save_tensor_with_tf_collection | test_should_save_tensor_with_tf_collection | 46 | 51 | 46 | 46 | 3e6379dbf0a1c984d3ae1f42bbc71401430b7a3b | bigcode/the-stack | train |
cae7445b65d9452385d963e5 | train | function | def test_should_save_tensor_with_default_collections(out_dir):
hook = helper_create_hook(out_dir, TF_DEFAULT_SAVED_COLLECTIONS)
for layer in model.layers:
layer_name = layer.name
assert not hook.should_save_tensor_or_collection(layer_name, CollectionKeys.GRADIENTS)
assert not hook.should... | def test_should_save_tensor_with_default_collections(out_dir):
| hook = helper_create_hook(out_dir, TF_DEFAULT_SAVED_COLLECTIONS)
for layer in model.layers:
layer_name = layer.name
assert not hook.should_save_tensor_or_collection(layer_name, CollectionKeys.GRADIENTS)
assert not hook.should_save_tensor_or_collection(layer_name, CollectionKeys.LAYERS)
| hook.get_collection(collection).include(include_regex)
hook.register_model(model)
hook.set_mode(ModeKeys.TRAIN)
hook._prepare_collections_for_tf2()
hook._increment_step()
hook.on_train_begin()
return hook
def test_should_save_tensor_with_default_collections(out_dir):
| 64 | 64 | 79 | 12 | 51 | jsspric/sagemaker-debugger | tests/tensorflow2/test_should_save_tensor.py | Python | test_should_save_tensor_with_default_collections | test_should_save_tensor_with_default_collections | 38 | 43 | 38 | 38 | 4f5423565bc2e0a7f4ec5f04c140616f2845e548 | bigcode/the-stack | train |
f2bd3fad00d21744608399d0 | train | class | class TestValue:
def __init__(self, value):
self.value = value
def __eq__(self, other):
return other.value == self.value
def __gt__(self, other):
return other.value > self.value
def __repr__(self):
return f"TestValue({self.value})"
| class TestValue:
| def __init__(self, value):
self.value = value
def __eq__(self, other):
return other.value == self.value
def __gt__(self, other):
return other.value > self.value
def __repr__(self):
return f"TestValue({self.value})"
| import numpy as np
import pandas as pd
import pytest
from exasol_data_science_utils_python.model_utils.reservoir_shuffle import ReservoirShuffle
class TestValue:
| 35 | 64 | 71 | 4 | 30 | exasol/data-science-utils-python | tests/unit_tests/model_utils/test_reservoir_shuffle.py | Python | TestValue | TestValue | 8 | 19 | 8 | 8 | 5e0f588b0d6c1ab76bf5e3cb16e119ea4978250d | bigcode/the-stack | train |
74c36b3334f1ba981a418a46 | train | function | def two_types(i, x):
if i == 0:
return x
else:
return x * 0.1
| def two_types(i, x):
| if i == 0:
return x
else:
return x * 0.1
| return other.value == self.value
def __gt__(self, other):
return other.value > self.value
def __repr__(self):
return f"TestValue({self.value})"
map_to_test_value = np.vectorize(lambda y: TestValue(y))
def two_types(i, x):
| 64 | 64 | 30 | 7 | 57 | exasol/data-science-utils-python | tests/unit_tests/model_utils/test_reservoir_shuffle.py | Python | two_types | two_types | 25 | 29 | 25 | 25 | b021a6e68ca25388aac4f2042818e3961a11b192 | bigcode/the-stack | train |
e841a84e7d8254565612c3b8 | train | function | @pytest.mark.parametrize("input_size,batch_size,buffer_size,columns_count,column_generator", [
(50, 10, 20, 1, lambda i, x: x),
(50, 10, 20, 2, lambda i, x: x),
(50, 20, 20, 1, lambda i, x: x),
(50, 10, 25, 1, lambda i, x: x),
(100, 20, 20, 1, lambda i, x: x),
(100, 20, 20, 2, two_types),
(1... | @pytest.mark.parametrize("input_size,batch_size,buffer_size,columns_count,column_generator", [
(50, 10, 20, 1, lambda i, x: x),
(50, 10, 20, 2, lambda i, x: x),
(50, 20, 20, 1, lambda i, x: x),
(50, 10, 25, 1, lambda i, x: x),
(100, 20, 20, 1, lambda i, x: x),
(100, 20, 20, 2, two_types),
(1... | columns = {i: np.arange(input_size) for i in range(columns_count)}
columns = {i: column_generator(i, x) for i, x in columns.items()}
input_df = pd.DataFrame(data=columns, index=np.arange(input_size))
def batch_iterator(input_df, batch_size):
for i in range(0, len(input_df), batch_size):
... | @pytest.mark.parametrize("input_size,batch_size,buffer_size,columns_count,column_generator", [
(50, 10, 20, 1, lambda i, x: x),
(50, 10, 20, 2, lambda i, x: x),
(50, 20, 20, 1, lambda i, x: x),
(50, 10, 25, 1, lambda i, x: x),
(100, 20, 20, 1, lambda i, x: x),
(100, 20, 20, 2, two_types),
(1... | 204 | 127 | 424 | 204 | 0 | exasol/data-science-utils-python | tests/unit_tests/model_utils/test_reservoir_shuffle.py | Python | test_reservoir_shuffle | test_reservoir_shuffle | 32 | 64 | 32 | 42 | f87d0c4ee649ae4ac31f8e02e51d40c86a67c59a | bigcode/the-stack | train |
d49eb434e6713f3c697e9d47 | train | function | def _update_camera_config(config: yacs.config.CfgNode) -> None:
logger.debug('Called update_camera_config()')
package_root = pathlib.Path(__file__).parent.resolve()
if not config.gaze_estimator.camera_params:
logger.debug('config.gaze_estimator.camera_params is not specified.')
logger.debug(... | def _update_camera_config(config: yacs.config.CfgNode) -> None:
| logger.debug('Called update_camera_config()')
package_root = pathlib.Path(__file__).parent.resolve()
if not config.gaze_estimator.camera_params:
logger.debug('config.gaze_estimator.camera_params is not specified.')
logger.debug(f'config.demo.use_camera is {config.demo.use_camera}')
i... | ., 0., 0., 0.]
}
}
with open('/tmp/camera_params.yaml', 'w') as f:
yaml.safe_dump(dic, f)
config.gaze_estimator.camera_params = '/tmp/camera_params.yaml'
logger.debug(
'Update config.gaze_estimator.camera_params to /tmp/camera_params.yaml'
)
def _update_camera_config(config: ... | 95 | 95 | 317 | 17 | 78 | ollipal/pytorch_mpiigaze_demo | saurongaze/ptgaze/utils.py | Python | _update_camera_config | _update_camera_config | 122 | 152 | 122 | 122 | 945bcb1a038e09f9d8a2b232d763f5401b828d38 | bigcode/the-stack | train |
d83ba25e47faa3c98df0847f | train | function | def _set_face_default_camera(config: yacs.config.CfgNode) -> None:
logger.debug('Called _set_face_default_camera()')
package_root = pathlib.Path(__file__).resolve().parent
filename = 'data/calib/normalized_camera_params_face.yaml'
default_params = package_root / filename
config.gaze_estimator.normal... | def _set_face_default_camera(config: yacs.config.CfgNode) -> None:
| logger.debug('Called _set_face_default_camera()')
package_root = pathlib.Path(__file__).resolve().parent
filename = 'data/calib/normalized_camera_params_face.yaml'
default_params = package_root / filename
config.gaze_estimator.normalized_camera_params = default_params.as_posix()
config.gaze_esti... | aze_estimator.normalized_camera_distance = 0.6
logger.debug('config.gaze_estimator.normalized_camera_params is set.')
logger.debug('config.gaze_estimator.normalized_camera_distance is set.')
def _set_face_default_camera(config: yacs.config.CfgNode) -> None:
| 63 | 64 | 131 | 18 | 45 | ollipal/pytorch_mpiigaze_demo | saurongaze/ptgaze/utils.py | Python | _set_face_default_camera | _set_face_default_camera | 166 | 174 | 166 | 166 | d87229f76e18d103d228c65204ed90ec126f01ae | bigcode/the-stack | train |
9137b21f196820d41730d216 | train | function | def _expanduser(path: str) -> str:
if not path:
return path
return pathlib.Path(path).expanduser().as_posix()
| def _expanduser(path: str) -> str:
| if not path:
return path
return pathlib.Path(path).expanduser().as_posix()
| .as_posix()
config.gaze_estimator.normalized_camera_distance = 1.0
logger.debug('config.gaze_estimator.normalized_camera_params is set.')
logger.debug('config.gaze_estimator.normalized_camera_distance is set.')
def _expanduser(path: str) -> str:
| 63 | 64 | 33 | 11 | 52 | ollipal/pytorch_mpiigaze_demo | saurongaze/ptgaze/utils.py | Python | _expanduser | _expanduser | 177 | 180 | 177 | 177 | b428fce68a1b50b74119d4d4f7628ea788317ad2 | bigcode/the-stack | train |
d74f71318e4740638b2f2b21 | train | function | def _check_path_all(config: yacs.config.CfgNode) -> None:
if config.face_detector.mode == 'dlib':
_check_path(config, 'face_detector.dlib.model')
_check_path(config, 'gaze_estimator.checkpoint')
_check_path(config, 'gaze_estimator.camera_params')
_check_path(config, 'gaze_estimator.normalized_ca... | def _check_path_all(config: yacs.config.CfgNode) -> None:
| if config.face_detector.mode == 'dlib':
_check_path(config, 'face_detector.dlib.model')
_check_path(config, 'gaze_estimator.checkpoint')
_check_path(config, 'gaze_estimator.camera_params')
_check_path(config, 'gaze_estimator.normalized_camera_params')
if config.demo.image_path:
_chec... | NotFoundError(f'config.{key}: {path.as_posix()} not found.')
if not path.is_file():
raise ValueError(f'config.{key}: {path.as_posix()} is not a file.')
def _check_path_all(config: yacs.config.CfgNode) -> None:
| 63 | 64 | 121 | 17 | 46 | ollipal/pytorch_mpiigaze_demo | saurongaze/ptgaze/utils.py | Python | _check_path_all | _check_path_all | 206 | 215 | 206 | 206 | 6cf79d19a95a35720d61a39d33186b92f3f0fcce | bigcode/the-stack | train |
3f18e4a6bbf6c2a4c636e296 | train | function | def _download_dlib_pretrained_model(config: yacs.config.CfgNode) -> None:
logger.debug('Called download_dlib_pretrained_model()')
if config.face_detector.mode != 'dlib':
logger.debug('config.facedetector.mode is not \'dlib\'.')
return
if config.face_detector.dlib.model:
logger.debug(... | def _download_dlib_pretrained_model(config: yacs.config.CfgNode) -> None:
| logger.debug('Called download_dlib_pretrained_model()')
if config.face_detector.mode != 'dlib':
logger.debug('config.facedetector.mode is not \'dlib\'.')
return
if config.face_detector.dlib.model:
logger.debug('config.facedetector.mode is specified.')
return
dlib_model_d... | import argparse
import bz2
import logging
import operator
import pathlib
import warnings
import cv2
import torch.hub
import yacs.config
import yaml
logger = logging.getLogger(__name__)
def _download_dlib_pretrained_model(config: yacs.config.CfgNode) -> None:
| 64 | 101 | 338 | 20 | 44 | ollipal/pytorch_mpiigaze_demo | saurongaze/ptgaze/utils.py | Python | _download_dlib_pretrained_model | _download_dlib_pretrained_model | 16 | 47 | 16 | 16 | 0b5892482b9937021bcaaf0835d507bd9c6b8385 | bigcode/the-stack | train |
39678c72c5b2d9999553308b | train | function | def _expanduser_all(config: yacs.config.CfgNode) -> None:
config.face_detector.dlib.model = _expanduser(
config.face_detector.dlib.model)
config.gaze_estimator.checkpoint = _expanduser(
config.gaze_estimator.checkpoint)
config.gaze_estimator.camera_params = _expanduser(
config.gaze_e... | def _expanduser_all(config: yacs.config.CfgNode) -> None:
| config.face_detector.dlib.model = _expanduser(
config.face_detector.dlib.model)
config.gaze_estimator.checkpoint = _expanduser(
config.gaze_estimator.checkpoint)
config.gaze_estimator.camera_params = _expanduser(
config.gaze_estimator.camera_params)
config.gaze_estimator.normaliz... | ('config.gaze_estimator.normalized_camera_distance is set.')
def _expanduser(path: str) -> str:
if not path:
return path
return pathlib.Path(path).expanduser().as_posix()
def _expanduser_all(config: yacs.config.CfgNode) -> None:
| 64 | 64 | 149 | 17 | 47 | ollipal/pytorch_mpiigaze_demo | saurongaze/ptgaze/utils.py | Python | _expanduser_all | _expanduser_all | 183 | 194 | 183 | 183 | 22db85de08fee26ddc8af043762e19e9dc7131de | bigcode/the-stack | train |
7e64b72031c62f16e7617c70 | train | function | def update_config(config: yacs.config.CfgNode) -> None:
if config.mode == 'MPIIGaze':
_set_eye_default_camera(config)
elif config.mode == 'MPIIFaceGaze':
_set_face_default_camera(config)
else:
raise ValueError
_update_camera_config(config)
_download_dlib_pretrained_model(conf... | def update_config(config: yacs.config.CfgNode) -> None:
| if config.mode == 'MPIIGaze':
_set_eye_default_camera(config)
elif config.mode == 'MPIIFaceGaze':
_set_face_default_camera(config)
else:
raise ValueError
_update_camera_config(config)
_download_dlib_pretrained_model(config)
_expanduser_all(config)
_check_path_all(conf... | .demo.display_on_screen False')
if not config.demo.output_dir:
logger.debug('config.demo.output_dir is not specified.')
config.demo.output_dir = 'outputs'
logger.debug('Set config.demo.output_dir \'outputs\'')
def update_config(config: yacs.config.CfgNode) -> None:
| 63 | 64 | 96 | 15 | 48 | ollipal/pytorch_mpiigaze_demo | saurongaze/ptgaze/utils.py | Python | update_config | update_config | 283 | 295 | 283 | 283 | c8264f52f5ccfeae6fcf49584b82cb210eb3e15f | bigcode/the-stack | train |
00d97ce0244cb95de2b53f3c | train | function | def _download_face_model() -> pathlib.Path:
logger.debug('Called _download_face_model()')
output_dir = pathlib.Path('~/.saurongaze/models/').expanduser()
output_dir.mkdir(exist_ok=True, parents=True)
output_path = output_dir / 'mpiifacegaze_resnet_simple.pth'
if not output_path.exists():
log... | def _download_face_model() -> pathlib.Path:
| logger.debug('Called _download_face_model()')
output_dir = pathlib.Path('~/.saurongaze/models/').expanduser()
output_dir.mkdir(exist_ok=True, parents=True)
output_path = output_dir / 'mpiifacegaze_resnet_simple.pth'
if not output_path.exists():
logger.debug('Download the pretrained model')
... | ysts/pytorch_mpiigaze_demo/releases/download/v0.1.0/mpiigaze_resnet_preact.pth',
output_path)
else:
logger.debug(f'The pretrained model {output_path} already exists.')
return output_path
def _download_face_model() -> pathlib.Path:
| 64 | 64 | 156 | 10 | 53 | ollipal/pytorch_mpiigaze_demo | saurongaze/ptgaze/utils.py | Python | _download_face_model | _download_face_model | 65 | 77 | 65 | 65 | 59d98850a3637c2c0d0a9c25d4f9b8f0d4980170 | bigcode/the-stack | train |
41762819d855c213884bf667 | train | function | def _set_eye_default_camera(config: yacs.config.CfgNode) -> None:
logger.debug('Called _set_eye_default_camera()')
package_root = pathlib.Path(__file__).resolve().parent
filename = 'data/calib/normalized_camera_params_eye.yaml'
default_params = package_root / filename
config.gaze_estimator.normalize... | def _set_eye_default_camera(config: yacs.config.CfgNode) -> None:
| logger.debug('Called _set_eye_default_camera()')
package_root = pathlib.Path(__file__).resolve().parent
filename = 'data/calib/normalized_camera_params_eye.yaml'
default_params = package_root / filename
config.gaze_estimator.normalized_camera_params = default_params.as_posix()
config.gaze_estima... | _estimator.camera_params).expanduser()
config.gaze_estimator.camera_params = path.as_posix()
logger.debug(
f'Update config.gaze_estimator.camera_params to {path.as_posix()}')
def _set_eye_default_camera(config: yacs.config.CfgNode) -> None:
| 63 | 64 | 131 | 18 | 45 | ollipal/pytorch_mpiigaze_demo | saurongaze/ptgaze/utils.py | Python | _set_eye_default_camera | _set_eye_default_camera | 155 | 163 | 155 | 155 | 1c34f9a513c183ca7d6fbd130a45037c059709f9 | bigcode/the-stack | train |
56d3b224ccba09e5a2650c25 | train | function | def _check_path(config: yacs.config.CfgNode, key: str) -> None:
path_str = operator.attrgetter(key)(config)
path = pathlib.Path(path_str)
if not path.exists():
raise FileNotFoundError(f'config.{key}: {path.as_posix()} not found.')
if not path.is_file():
raise ValueError(f'config.{key}: {... | def _check_path(config: yacs.config.CfgNode, key: str) -> None:
| path_str = operator.attrgetter(key)(config)
path = pathlib.Path(path_str)
if not path.exists():
raise FileNotFoundError(f'config.{key}: {path.as_posix()} not found.')
if not path.is_file():
raise ValueError(f'config.{key}: {path.as_posix()} is not a file.')
| _params)
config.demo.image_path = _expanduser(config.demo.image_path)
config.demo.video_path = _expanduser(config.demo.video_path)
config.demo.output_dir = _expanduser(config.demo.output_dir)
def _check_path(config: yacs.config.CfgNode, key: str) -> None:
| 64 | 64 | 94 | 20 | 44 | ollipal/pytorch_mpiigaze_demo | saurongaze/ptgaze/utils.py | Python | _check_path | _check_path | 197 | 203 | 197 | 197 | 1f71bde161e3f0a732fb05cf521cd60043c54fff | bigcode/the-stack | train |
0ad3799da6ed7aba77d27bcb | train | function | def update_default_config(config: yacs.config.CfgNode,
args: argparse.Namespace) -> None:
logger.debug('Called update_default_config()')
if not args.mode:
logger.debug('--mode is not specified.')
raise ValueError
else:
logger.debug(f'--mode is {args.mode}')
... | def update_default_config(config: yacs.config.CfgNode,
args: argparse.Namespace) -> None:
| logger.debug('Called update_default_config()')
if not args.mode:
logger.debug('--mode is not specified.')
raise ValueError
else:
logger.debug(f'--mode is {args.mode}')
if args.mode == 'eye':
config.mode = 'MPIIGaze'
model_path = _download_eye_model()
... | {path.as_posix()} not found.')
if not path.is_file():
raise ValueError(f'config.{key}: {path.as_posix()} is not a file.')
def _check_path_all(config: yacs.config.CfgNode) -> None:
if config.face_detector.mode == 'dlib':
_check_path(config, 'face_detector.dlib.model')
_check_path(config, '... | 181 | 181 | 604 | 22 | 159 | ollipal/pytorch_mpiigaze_demo | saurongaze/ptgaze/utils.py | Python | update_default_config | update_default_config | 218 | 280 | 218 | 219 | 2ccf391f207afcd4933ad9041091e94f620eb61a | bigcode/the-stack | train |
fe6d444682fe28f8d2b0e604 | train | function | def _generate_dummy_camera_params(config: yacs.config.CfgNode) -> None:
logger.debug('Called _generate_dummy_camera_params()')
if config.demo.image_path:
path = pathlib.Path(config.demo.image_path).expanduser()
image = cv2.imread(path.as_posix())
h, w = image.shape[:2]
elif config.de... | def _generate_dummy_camera_params(config: yacs.config.CfgNode) -> None:
| logger.debug('Called _generate_dummy_camera_params()')
if config.demo.image_path:
path = pathlib.Path(config.demo.image_path).expanduser()
image = cv2.imread(path.as_posix())
h, w = image.shape[:2]
elif config.demo.video_path:
logger.debug(f'Open video {config.demo.video_path... | output_path = output_dir / 'mpiifacegaze_resnet_simple.pth'
if not output_path.exists():
logger.debug('Download the pretrained model')
torch.hub.download_url_to_file(
'https://github.com/hysts/pytorch_mpiigaze_demo/releases/download/v0.1.0/mpiifacegaze_resnet_simple.pth',
... | 122 | 122 | 408 | 18 | 103 | ollipal/pytorch_mpiigaze_demo | saurongaze/ptgaze/utils.py | Python | _generate_dummy_camera_params | _generate_dummy_camera_params | 80 | 119 | 80 | 80 | 77db7d315eb982a4a5eba2e3eb3843a74417d178 | bigcode/the-stack | train |
5b8701b52c3875bc53e79cc9 | train | function | def _download_eye_model() -> pathlib.Path:
logger.debug('Called _download_eye_model()')
output_dir = pathlib.Path('~/.saurongaze/models/').expanduser()
output_dir.mkdir(exist_ok=True, parents=True)
output_path = output_dir / 'mpiigaze_resnet_preact.pth'
if not output_path.exists():
logger.de... | def _download_eye_model() -> pathlib.Path:
| logger.debug('Called _download_eye_model()')
output_dir = pathlib.Path('~/.saurongaze/models/').expanduser()
output_dir.mkdir(exist_ok=True, parents=True)
output_path = output_dir / 'mpiigaze_resnet_preact.pth'
if not output_path.exists():
logger.debug('Download the pretrained model')
... | 2',
bz2_path)
with bz2.BZ2File(bz2_path, 'rb') as f_in, open(dlib_model_path,
'wb') as f_out:
data = f_in.read()
f_out.write(data)
def _download_eye_model() -> pathlib.Path:
| 64 | 64 | 156 | 10 | 54 | ollipal/pytorch_mpiigaze_demo | saurongaze/ptgaze/utils.py | Python | _download_eye_model | _download_eye_model | 50 | 62 | 50 | 50 | 9c762b95a1788923694832fbc6626d0b7a37f26f | bigcode/the-stack | train |
e26bc262a4078f591607733e | train | class | class ClearDTCMethodFactory(IServiceMethodFactory):
##
# @brief method to create the request function for the service element
@staticmethod
def create_requestFunction(diagServiceElement, xmlElements):
serviceId = 0
diagnosticId = 0
shortName = "request_{0}".format(diagServiceEl... | class ClearDTCMethodFactory(IServiceMethodFactory):
##
# @brief method to create the request function for the service element
@staticmethod
| def create_requestFunction(diagServiceElement, xmlElements):
serviceId = 0
diagnosticId = 0
shortName = "request_{0}".format(diagServiceElement.find('SHORT-NAME').text)
requestElement = xmlElements[diagServiceElement.find('REQUEST-REF').attrib['ID-REF']]
paramsElement = requ... | n"
" serviceId = DecodeFunctions.buildIntFromList(input[{2}:{3}])\n"
" if(len(input) != {4}): raise Exception(\"Total length returned not as expected. Expected: {4}; Got {{0}}\".format(len(input)))\n"
" if(serviceId != serviceI... | 256 | 256 | 1,389 | 31 | 225 | sebclrsn/python-uds | uds/uds_config_tool/FunctionCreation/ClearDTCMethodFactory.py | Python | ClearDTCMethodFactory | ClearDTCMethodFactory | 42 | 193 | 42 | 46 | 859f6aacb637d6c56e707d6d8309e32855636277 | bigcode/the-stack | train |
5108642440e08d6c01ccd6bc | train | function | def robust_save(fname):
plt.savefig(os.path.join(save_bin,'overlayed_predictions.png',dpi=200,bbox_inches='tight'))
| def robust_save(fname):
| plt.savefig(os.path.join(save_bin,'overlayed_predictions.png',dpi=200,bbox_inches='tight'))
| import PCA
from skimage.feature import hog
from sklearn.neighbors import KNeighborsClassifier
import SVM
import Filters
import ML_interface_SVM_V3
import DataManager
dirname = os.path.dirname(__file__)
save_bin = os.path.join(dirname,"save_bin")
def robust_save(fname):
| 63 | 64 | 28 | 5 | 58 | eduluca/Generalized-Sklearn-ML-Pipeline | main-KNN.py | Python | robust_save | robust_save | 39 | 40 | 39 | 39 | 24e1a3eb0bcb1373255d279428d53f58733ddaf1 | bigcode/the-stack | train |
f9ef6a5f80ddfb144bd2b5d1 | train | class | class PatchAssessor(object):
""" Wrapper class of a single patch assessment """
def __init__(self, env_layer, execution_config, composite_logger, telemetry_writer, status_handler, package_manager, lifecycle_manager):
self.env_layer = env_layer
self.execution_config = execution_config
se... | class PatchAssessor(object):
| """ Wrapper class of a single patch assessment """
def __init__(self, env_layer, execution_config, composite_logger, telemetry_writer, status_handler, package_manager, lifecycle_manager):
self.env_layer = env_layer
self.execution_config = execution_config
self.composite_logger = composi... | # Copyright 2020 Microsoft Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | 159 | 238 | 796 | 6 | 152 | Azure/LinuxPatchExtension | src/core/src/core_logic/PatchAssessor.py | Python | PatchAssessor | PatchAssessor | 22 | 91 | 22 | 22 | 5b18b7a6b45b98b3e1391d886e3eeb94598c8688 | bigcode/the-stack | train |
ec9a5b36a30d0d43abc236d8 | train | class | class PlotLosses(keras.callbacks.Callback):
def on_train_begin(self, logs={}):
self.i = 0
self.x = []
self.losses = []
self.val_losses = []
self.fig = plt.figure()
self.logs = []
def on_epoch_end(self, epoch, logs={}):
self.logs.append(l... | class PlotLosses(keras.callbacks.Callback):
| def on_train_begin(self, logs={}):
self.i = 0
self.x = []
self.losses = []
self.val_losses = []
self.fig = plt.figure()
self.logs = []
def on_epoch_end(self, epoch, logs={}):
self.logs.append(logs)
self.x.append(self.i)
s... | import keras
from matplotlib import pyplot as plt
# Class for plotting loss values
class PlotLosses(keras.callbacks.Callback):
| 26 | 64 | 142 | 9 | 16 | iabhra/Action_Image_Classification | plot_losses.py | Python | PlotLosses | PlotLosses | 5 | 24 | 5 | 5 | 3e407a5b13e01c70e5a9607d1bb154270bcad021 | bigcode/the-stack | train |
86f6c5b6801800643037b070 | train | class | class FakeIndividual:
genotype = None
phenotype = "Phenotype"
def __init__(self, code):
self.genotype = FakeGenotype(code)
| class FakeIndividual:
| genotype = None
phenotype = "Phenotype"
def __init__(self, code):
self.genotype = FakeGenotype(code)
| from random import sample
from unittest import TestCase
from ga_cm.cm_plugin import CmPlugin
class FakeGenotype:
code = []
def __init__(self, code):
self.code = code
class FakeIndividual:
| 48 | 64 | 35 | 4 | 43 | lipopo/ga | test/ga_cm/cm_plugin.py | Python | FakeIndividual | FakeIndividual | 14 | 19 | 14 | 14 | d133023098cef1371f9f2402cd13ee6b4e8b173e | bigcode/the-stack | train |
565e28a854fe7c34cc8fb035 | train | class | class FakeGenotype:
code = []
def __init__(self, code):
self.code = code
| class FakeGenotype:
| code = []
def __init__(self, code):
self.code = code
| from random import sample
from unittest import TestCase
from ga_cm.cm_plugin import CmPlugin
class FakeGenotype:
| 25 | 64 | 24 | 5 | 19 | lipopo/ga | test/ga_cm/cm_plugin.py | Python | FakeGenotype | FakeGenotype | 7 | 11 | 7 | 7 | b0e4653d8716aab741bd7ad5aed105374ddaf92d | bigcode/the-stack | train |
a62eaa9dfbd03f7aac244c32 | train | class | class CmPluginTestCase(TestCase):
def setUp(self):
self.cm_plugin = CmPlugin(
0.1, 0.1
)
self.code_base = [True] * 100 + [False] * 100
def testCross(self):
i1code = sample(self.code_base, 100)
i2code = sample(self.code_base, 100)
i1 = FakeIndividual(... | class CmPluginTestCase(TestCase):
| def setUp(self):
self.cm_plugin = CmPlugin(
0.1, 0.1
)
self.code_base = [True] * 100 + [False] * 100
def testCross(self):
i1code = sample(self.code_base, 100)
i2code = sample(self.code_base, 100)
i1 = FakeIndividual(i1code)
i2 = FakeIndividual... | from random import sample
from unittest import TestCase
from ga_cm.cm_plugin import CmPlugin
class FakeGenotype:
code = []
def __init__(self, code):
self.code = code
class FakeIndividual:
genotype = None
phenotype = "Phenotype"
def __init__(self, code):
self.genotype = FakeGen... | 87 | 150 | 501 | 8 | 79 | lipopo/ga | test/ga_cm/cm_plugin.py | Python | CmPluginTestCase | CmPluginTestCase | 22 | 85 | 22 | 23 | c1176e2e2bec29c0d0055f06d17bd5faa3e31a46 | bigcode/the-stack | train |
502a8633ec659cd0cf7b6f3d | train | class | class SetHostNamePlugin(base.BasePlugin):
def execute(self, service, shared_data):
osutils = osutils_factory.get_os_utils()
metadata_host_name = service.get_host_name()
if not metadata_host_name:
LOG.debug('Hostname not found in metadata')
return (base.PLUGIN_EXECUTI... | class SetHostNamePlugin(base.BasePlugin):
| def execute(self, service, shared_data):
osutils = osutils_factory.get_os_utils()
metadata_host_name = service.get_host_name()
if not metadata_host_name:
LOG.debug('Hostname not found in metadata')
return (base.PLUGIN_EXECUTION_DONE, False)
metadata_host_nam... | from cloudbaseinit.plugins.common import base
opts = [
cfg.BoolOpt('netbios_host_name_compatibility', default=True,
help='Truncates the hostname to 15 characters for Netbios '
'compatibility'),
]
CONF = cfg.CONF
CONF.register_opts(opts)
LOG = logging.getLogger(__name__)
NETB... | 89 | 89 | 298 | 9 | 79 | rrbarreto/bsd-cloudinit-pfsense | cloudbaseinit/plugins/common/sethostname.py | Python | SetHostNamePlugin | SetHostNamePlugin | 38 | 68 | 38 | 38 | 3e13697b37bef3704ff7233441f3e31bbed87336 | bigcode/the-stack | train |
f4f01624dd6dac428b1682b6 | train | class | @pytest.mark.django_db
class TestTransactionManager:
def test_retrieves_only_own_transactions(self):
user = User.objects.create_superuser('test 1')
transaction = Transaction.objects.create(
date=date(2020, 4, 20),
to_account_number='NL11RABO0101010444',
payee='t... | @pytest.mark.django_db
class TestTransactionManager:
| def test_retrieves_only_own_transactions(self):
user = User.objects.create_superuser('test 1')
transaction = Transaction.objects.create(
date=date(2020, 4, 20),
to_account_number='NL11RABO0101010444',
payee='timo',
memo='small memo',
inflo... | import date, datetime
from decimal import Decimal
import pytest
from homebank.transaction_management.managers import RabobankCsvRowParser
from homebank.transaction_management.models import Transaction
from homebank.transaction_management.tests.factories import TransactionFactory
from homebank.users.models import Use... | 78 | 78 | 263 | 11 | 66 | timohermans/homebank-django | homebank/transaction_management/tests/test_managers.py | Python | TestTransactionManager | TestTransactionManager | 13 | 41 | 13 | 15 | 2c23c141af54c5c7f502e9d824142bfe137c3b22 | bigcode/the-stack | train |
c499a64e69e5ff824511df2a | train | class | @pytest.mark.django_db
class TestRabobankCsvRowParser:
def test_parses_inflow_transaction(self, parser):
user = User.objects.create_user("timo")
csv_row = ['NL11RABO0104955555', 'EUR', 'RABONL2U', '000000000000007213', '2019-09-01', '2019-09-01', '+2,50',
'+1868,12', 'NL42RABO0114... | @pytest.mark.django_db
class TestRabobankCsvRowParser:
| def test_parses_inflow_transaction(self, parser):
user = User.objects.create_user("timo")
csv_row = ['NL11RABO0104955555', 'EUR', 'RABONL2U', '000000000000007213', '2019-09-01', '2019-09-01', '+2,50',
'+1868,12', 'NL42RABO0114164838', 'J.M.G. Kerkhoffs eo', '', '', 'RABONL2U', 'cb... | .transactions.all()) == 0
assert len(Transaction.objects.for_user(user_2)) == 0
def test_gets_total_spent_for_month(self):
date = datetime(2020, 2, 1)
user = UserFactory()
TransactionFactory(user=user, date=date, category=None, inflow=600, outflow=0)
TransactionFactory.creat... | 165 | 165 | 553 | 14 | 151 | timohermans/homebank-django | homebank/transaction_management/tests/test_managers.py | Python | TestRabobankCsvRowParser | TestRabobankCsvRowParser | 49 | 85 | 49 | 50 | ff19b88dc8d9260ee742d5fde3420dfb68bce660 | bigcode/the-stack | train |
f90ef94d744801ce056e5acd | train | function | @pytest.fixture
def parser():
return RabobankCsvRowParser()
| @pytest.fixture
def parser():
| return RabobankCsvRowParser()
| .create_batch(size=50, outflow=10, inflow=1, date=date, user=user)
total_spent = Transaction.objects.total_spent_for_month(date, user)
assert total_spent == Decimal((1 * 50) - (10 * 50))
@pytest.fixture
def parser():
| 64 | 64 | 14 | 6 | 58 | timohermans/homebank-django | homebank/transaction_management/tests/test_managers.py | Python | parser | parser | 44 | 46 | 44 | 45 | b85f0220cec405e6f62e5e069e975cef910ef1bd | bigcode/the-stack | train |
fd2a6e5cfcbf13d0ce40b29e | train | class | class SamplingResult(util_mixins.NiceRepr):
"""Bbox sampling result.
Example:
>>> # xdoctest: +IGNORE_WANT
>>> from mmdet.core.bbox.samplers.sampling_result import * # NOQA
>>> self = SamplingResult.random(rng=10)
>>> print(f'self = {self}')
self = <SamplingResult({
... | class SamplingResult(util_mixins.NiceRepr):
| """Bbox sampling result.
Example:
>>> # xdoctest: +IGNORE_WANT
>>> from mmdet.core.bbox.samplers.sampling_result import * # NOQA
>>> self = SamplingResult.random(rng=10)
>>> print(f'self = {self}')
self = <SamplingResult({
'neg_bboxes': torch.Size([12, 4]),
... | # Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | 155 | 256 | 1,303 | 11 | 143 | Ascend/modelzoo | built-in/PyTorch/Official/cv/image_object_detection/YoloV3_ID1790_for_PyTorch/mmdet/core/bbox/samplers/sampling_result.py | Python | SamplingResult | SamplingResult | 20 | 166 | 20 | 20 | 8f5b29ae519f1ca767d5639a06acacb291b7c740 | bigcode/the-stack | train |
3bf9d5e0595456e3ef2cc05f | train | class | class TestAuditActions(TestCase, WithQueryApi):
"""Test Audit related actions"""
def setUp(self):
self.clear_data()
super(TestAuditActions, self).setUp()
self.client.get("/login")
self.gen = generator.ObjectGenerator()
filename = "program_audit.csv"
self.import_file(filename)
self.asser... | class TestAuditActions(TestCase, WithQueryApi):
| """Test Audit related actions"""
def setUp(self):
self.clear_data()
super(TestAuditActions, self).setUp()
self.client.get("/login")
self.gen = generator.ObjectGenerator()
filename = "program_audit.csv"
self.import_file(filename)
self.assertEqual(2, Audit.query.count())
audit = Audit... | # Copyright (C) 2020 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Tests for actions available on audits handle."""
from ggrc.models import Audit
from ggrc.models import Program
from ggrc.models import all_models
from integration.ggrc import generator
from integration.... | 113 | 182 | 609 | 11 | 101 | pavelglebov/ggrc-core | test/integration/ggrc/services/test_audits.py | Python | TestAuditActions | TestAuditActions | 16 | 90 | 16 | 16 | 7deac0643a739061be5cfadab5a83c1e92d6fb18 | bigcode/the-stack | train |
0d22b12c32747e0414ee16b7 | train | function | def check_if_overlap_count(seg_arrays):
num_voxels = 0
for i in range(len(seg_arrays)-1):
for j in range(len(seg_arrays)):
if (seg_arrays[i]==seg_arrays[j]).sum()!=0:
num_voxels += (seg_arrays[i]==seg_arrays[j]).sum()
if num_voxels > 0:
return True, num_voxels
... | def check_if_overlap_count(seg_arrays):
| num_voxels = 0
for i in range(len(seg_arrays)-1):
for j in range(len(seg_arrays)):
if (seg_arrays[i]==seg_arrays[j]).sum()!=0:
num_voxels += (seg_arrays[i]==seg_arrays[j]).sum()
if num_voxels > 0:
return True, num_voxels
else:
return False
| ITK as sitk
def check_if_overlap(seg_arrays):
for i in range(len(seg_arrays)-1):
for j in range(len(seg_arrays)):
if (seg_arrays[i]==seg_arrays[j]).sum()!=0:
return True
return False
def check_if_overlap_count(seg_arrays):
| 64 | 64 | 95 | 8 | 55 | hihunjin/Code-snippet-for-everything | nifty_upload_merge_save.py | Python | check_if_overlap_count | check_if_overlap_count | 20 | 29 | 20 | 20 | 7faca48ca3a97f40d3cf1fb395ed3338ab183cdd | bigcode/the-stack | train |
152b22789e9b8a8743e33d24 | train | function | def check_if_overlap(seg_arrays):
for i in range(len(seg_arrays)-1):
for j in range(len(seg_arrays)):
if (seg_arrays[i]==seg_arrays[j]).sum()!=0:
return True
return False
| def check_if_overlap(seg_arrays):
| for i in range(len(seg_arrays)-1):
for j in range(len(seg_arrays)):
if (seg_arrays[i]==seg_arrays[j]).sum()!=0:
return True
return False
| '''
class num : organ name
1 : Gallbladder
2 : Liver
3 : Pancreas
4 : Spleen
5 : Stomach
'''
import numpy as np
import SimpleITK as sitk
def check_if_overlap(seg_arrays):
| 61 | 64 | 50 | 7 | 53 | hihunjin/Code-snippet-for-everything | nifty_upload_merge_save.py | Python | check_if_overlap | check_if_overlap | 12 | 17 | 12 | 12 | 31a0954a0cd1a6906764054070e8ff7b630e4cd5 | bigcode/the-stack | train |
db1a3c128b08377719c243e8 | train | function | def test_save_state(state: State):
with TemporaryFile('wb') as f:
state.save(f)
assert f.tell() > 0
| def test_save_state(state: State):
| with TemporaryFile('wb') as f:
state.save(f)
assert f.tell() > 0
| from tempfile import TemporaryFile
from nlisim.state import State
def test_save_state(state: State):
| 21 | 64 | 32 | 8 | 12 | jbeezley/simulation-hello-world | test/test_state.py | Python | test_save_state | test_save_state | 6 | 9 | 6 | 6 | 3b9441b63bd2635c3e1af5de3aaeb0dfa2a1f162 | bigcode/the-stack | train |
0d546fd712298a3fec43c90e | train | function | def test_load_state(state: State):
new_state = state.load(state.serialize())
assert new_state is not state
| def test_load_state(state: State):
| new_state = state.load(state.serialize())
assert new_state is not state
| with TemporaryFile('wb') as f:
state.save(f)
assert f.tell() > 0
def test_serialize_state(state: State):
serialized = state.serialize()
assert isinstance(serialized, bytes)
assert len(serialized) > 0
def test_load_state(state: State):
| 64 | 64 | 25 | 8 | 55 | jbeezley/simulation-hello-world | test/test_state.py | Python | test_load_state | test_load_state | 18 | 20 | 18 | 18 | 9e1f92c74b87e930455aac41b360db6b8f7e116a | bigcode/the-stack | train |
af50263001bec55673766e94 | train | function | def test_serialize_state(state: State):
serialized = state.serialize()
assert isinstance(serialized, bytes)
assert len(serialized) > 0
| def test_serialize_state(state: State):
| serialized = state.serialize()
assert isinstance(serialized, bytes)
assert len(serialized) > 0
| from tempfile import TemporaryFile
from nlisim.state import State
def test_save_state(state: State):
with TemporaryFile('wb') as f:
state.save(f)
assert f.tell() > 0
def test_serialize_state(state: State):
| 54 | 64 | 33 | 9 | 44 | jbeezley/simulation-hello-world | test/test_state.py | Python | test_serialize_state | test_serialize_state | 12 | 15 | 12 | 12 | ed77c2658ff526d7670f8b5d781dde81738274e2 | bigcode/the-stack | train |
4a05617e920a04ff520b826a | train | function | def mock_pyquery(url):
class MockPQ:
def __init__(self, html_contents, status=200):
self.url = url
self.reason = 'Bad URL' # Used when throwing HTTPErrors
self.headers = {} # Used when throwing HTTPErrors
self.status_code = status
self.html_conte... | def mock_pyquery(url):
| class MockPQ:
def __init__(self, html_contents, status=200):
self.url = url
self.reason = 'Bad URL' # Used when throwing HTTPErrors
self.headers = {} # Used when throwing HTTPErrors
self.status_code = status
self.html_contents = html_contents
... | oster
from sportsreference.nba.teams import Team
YEAR = 2018
def read_file(filename):
filepath = os.path.join(os.path.dirname(__file__), 'nba', filename)
return open('%s.html' % filepath, 'r', encoding='utf8').read()
def mock_pyquery(url):
| 66 | 66 | 222 | 6 | 60 | jordan-day/sportsreference | tests/integration/roster/test_nba_roster.py | Python | mock_pyquery | mock_pyquery | 20 | 42 | 20 | 20 | 41c98f82dccdef9bec47c376cf4b82014a1f6dcf | bigcode/the-stack | train |
c417db3337188ee99a209be0 | train | function | def mock_request(url):
class MockRequest:
def __init__(self, html_contents, status_code=200):
self.status_code = status_code
self.html_contents = html_contents
self.text = html_contents
if str(YEAR) in url:
return MockRequest('good')
else:
return ... | def mock_request(url):
| class MockRequest:
def __init__(self, html_contents, status_code=200):
self.status_code = status_code
self.html_contents = html_contents
self.text = html_contents
if str(YEAR) in url:
return MockRequest('good')
else:
return MockRequest('bad', stat... | PQ(read_file('blackta01'))
if 'youngtr01' in url:
return MockPQ(read_file('youngtr01'))
if 'BAD' in url:
return MockPQ(None, 404)
return MockPQ(read_file('hardeja01'))
def mock_request(url):
| 63 | 64 | 79 | 5 | 58 | jordan-day/sportsreference | tests/integration/roster/test_nba_roster.py | Python | mock_request | mock_request | 45 | 55 | 45 | 45 | 0ac7fcec86fc201329f1c2ebfe6951cd927036f1 | bigcode/the-stack | train |
7168ca61e749c4ab13af535b | train | class | class TestNBARoster:
@mock.patch('requests.get', side_effect=mock_pyquery)
def test_roster_class_pulls_all_player_stats(self, *args, **kwargs):
flexmock(utils) \
.should_receive('_find_year_for_season') \
.and_return('2018')
roster = Roster('HOU')
assert len(rost... | class TestNBARoster:
@mock.patch('requests.get', side_effect=mock_pyquery)
| def test_roster_class_pulls_all_player_stats(self, *args, **kwargs):
flexmock(utils) \
.should_receive('_find_year_for_season') \
.and_return('2018')
roster = Roster('HOU')
assert len(roster.players) == 4
for player in roster.players:
assert play... | ']
df = pd.DataFrame(dataframe, index=indices)
player = self.player('')
# Pandas doesn't natively allow comparisons of DataFrames.
# Concatenating the two DataFrames (the one generated during the test
# and the expected one above) and dropping duplicate rows leaves only
... | 235 | 236 | 789 | 21 | 214 | jordan-day/sportsreference | tests/integration/roster/test_nba_roster.py | Python | TestNBARoster | TestNBARoster | 1,235 | 1,328 | 1,235 | 1,236 | 04ef5890b1b1b3b624d89c64eeea9b9913d173b1 | bigcode/the-stack | train |
cb7860f6ffa421f01a61df3a | train | function | def read_file(filename):
filepath = os.path.join(os.path.dirname(__file__), 'nba', filename)
return open('%s.html' % filepath, 'r', encoding='utf8').read()
| def read_file(filename):
| filepath = os.path.join(os.path.dirname(__file__), 'nba', filename)
return open('%s.html' % filepath, 'r', encoding='utf8').read()
|
import os
import pandas as pd
import pytest
from datetime import datetime
from flexmock import flexmock
from sportsreference import utils
from sportsreference.nba.roster import Player, Roster
from sportsreference.nba.teams import Team
YEAR = 2018
def read_file(filename):
| 64 | 64 | 42 | 5 | 58 | jordan-day/sportsreference | tests/integration/roster/test_nba_roster.py | Python | read_file | read_file | 15 | 17 | 15 | 15 | 713057eb9e23b84377b0cd8b590e0849e245bdff | bigcode/the-stack | train |
d3744421b3a6063a2fdb5a65 | train | class | class TestNBAPlayer:
@mock.patch('requests.get', side_effect=mock_pyquery)
def setup_method(self, *args, **kwargs):
self.results_career = {
'player_id': 'hardeja01',
'season': 'Career',
'name': 'James Harden',
'team_abbreviation': '',
'position... | class TestNBAPlayer:
@mock.patch('requests.get', side_effect=mock_pyquery)
| def setup_method(self, *args, **kwargs):
self.results_career = {
'player_id': 'hardeja01',
'season': 'Career',
'name': 'James Harden',
'team_abbreviation': '',
'position': 'SG',
'height': '6-5',
'weight': 220,
'b... | self.status_code = status
self.html_contents = html_contents
self.text = html_contents
if 'HOU' in url:
return MockPQ(read_file('2018'))
if 'anderry01' in url:
return MockPQ(read_file('anderry01'))
if 'arizatr01' in url:
return MockPQ(read_file('a... | 256 | 256 | 13,221 | 20 | 236 | jordan-day/sportsreference | tests/integration/roster/test_nba_roster.py | Python | TestNBAPlayer | TestNBAPlayer | 58 | 1,232 | 58 | 59 | a1cce55d70f51cc44e8a1399553e60952ed7809e | bigcode/the-stack | train |
272415076baa2b8866413567 | train | function | def main():
jrpc_urls = [
'/pm/config/adom/{adom}/obj/waf/profile/{profile}/constraint/max-range-segment',
'/pm/config/global/obj/waf/profile/{profile}/constraint/max-range-segment'
]
perobject_jrpc_urls = [
'/pm/config/adom/{adom}/obj/waf/profile/{profile}/constraint/max-range-segm... | def main():
| jrpc_urls = [
'/pm/config/adom/{adom}/obj/waf/profile/{profile}/constraint/max-range-segment',
'/pm/config/global/obj/waf/profile/{profile}/constraint/max-range-segment'
]
perobject_jrpc_urls = [
'/pm/config/adom/{adom}/obj/waf/profile/{profile}/constraint/max-range-segment/{max-ran... | profile: <your own value>
waf_profile_constraint_maxrangesegment:
action: <value in [allow, block]>
log: <value in [disable, enable]>
max-range-segment: <value of integer>
severity: <value in [low, medium, high]>
status: <value in [disable, enable]>
... | 256 | 256 | 1,338 | 3 | 252 | usegalaxy-no/usegalaxy | venv/lib/python3.6/site-packages/ansible_collections/fortinet/fortimanager/plugins/modules/fmgr_waf_profile_constraint_maxrangesegment.py | Python | main | main | 186 | 371 | 186 | 186 | 3c8e2c5902c9d471af1065be1978c2ae38ef29a4 | bigcode/the-stack | train |
254f7cdd2fa4e54693fef28d | train | class | class FaceRecognitionBinary(BaseFormatConverter):
__provider__ = 'face_recognition_bin'
@classmethod
def parameters(cls):
params = super().parameters()
params.update({
'bin_file': PathField(description='binary data file'),
'images_dir': PathField(
is_... | class FaceRecognitionBinary(BaseFormatConverter):
| __provider__ = 'face_recognition_bin'
@classmethod
def parameters(cls):
params = super().parameters()
params.update({
'bin_file': PathField(description='binary data file'),
'images_dir': PathField(
is_directory=True, optional=True, check_exists=False,... | = len(all_images)
for image_id, image in enumerate(all_images):
annotation = ReIdentificationClassificationAnnotation(image, positive_data[image], negative_data[image])
if landmarks_map:
image_landmarks = landmarks_map.get(image)
annotation.metadata['key... | 171 | 171 | 571 | 8 | 163 | ivanvikhrev/open_model_zoo | tools/accuracy_checker/accuracy_checker/annotation_converters/lfw.py | Python | FaceRecognitionBinary | FaceRecognitionBinary | 139 | 195 | 139 | 139 | b6b7bcd05152e2d5deb7e8aac9ef48e1f5626717 | bigcode/the-stack | train |
345ccc1b2f52b5ac1ae333d8 | train | class | class LFWConverter(BaseFormatConverter):
__provider__ = 'lfw'
annotation_types = (ReIdentificationClassificationAnnotation, )
@classmethod
def parameters(cls):
configuration_parameters = super().parameters()
configuration_parameters.update({
'pairs_file': PathField(descripti... | class LFWConverter(BaseFormatConverter):
| __provider__ = 'lfw'
annotation_types = (ReIdentificationClassificationAnnotation, )
@classmethod
def parameters(cls):
configuration_parameters = super().parameters()
configuration_parameters.update({
'pairs_file': PathField(description="Path to file with annotation positive... | """
Copyright (c) 2018-2020 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in wri... | 199 | 256 | 864 | 8 | 190 | ivanvikhrev/open_model_zoo | tools/accuracy_checker/accuracy_checker/annotation_converters/lfw.py | Python | LFWConverter | LFWConverter | 31 | 136 | 31 | 31 | 9d3d09f6702f51dd3deb2c28a5bb4c7fd4dcea7f | bigcode/the-stack | train |
5299ea136a7de39bf7f23ed7 | train | function | def parse_count_commits(base_url, branch='master'): # count the total number of up-to-date commits in "master"
branch_page = f"{base_url}/tree/{branch}"
html_page = requests.get(branch_page)
while True:
try:
html_page.raise_for_status()
break
except Exception as exc:... | def parse_count_commits(base_url, branch='master'): # count the total number of up-to-date commits in "master"
| branch_page = f"{base_url}/tree/{branch}"
html_page = requests.get(branch_page)
while True:
try:
html_page.raise_for_status()
break
except Exception as exc:
input(f'There was a problem while getting the web page: {exc}.\nPress Enter to retry\n>')
... | import requests, bs4
def parse_count_commits(base_url, branch='master'): # count the total number of up-to-date commits in "master"
| 33 | 72 | 242 | 27 | 5 | AngeStan/github-list-commits | features/html_parser.py | Python | parse_count_commits | parse_count_commits | 4 | 21 | 4 | 4 | 558eb914070bdeba894fb247b6f05c39abb39ce2 | bigcode/the-stack | train |
7b8a77632621702aa2fdcb17 | train | function | def quit():
global run
run=0
| def quit():
| global run
run=0
| import traceback
print("(Hacky shell running inside yeezip!)")
run=1
def quit():
| 21 | 64 | 10 | 3 | 17 | 602p/yeezip | src/extentions/shell.py | Python | quit | quit | 5 | 7 | 5 | 5 | 904cc6f69dbf965762782c1c51f43e0f5d3f5da4 | bigcode/the-stack | train |
c87a14f27c25b2023b36c153 | train | function | @functools.lru_cache(10)
def get_win_conditions():
"""Returns an M x 62 matrix, C, of the win conditions. Multiply C*P and look for zeros."""
# M should be 3*(2 + 3 + 4 + 5 + 6 + 5 + 4 + 3 + 2) = 102
result = get_linear_condition_matrix((1, 1, 1, 1))
assert len(result) == 102, "I expect 102 loss condit... | @functools.lru_cache(10)
def get_win_conditions():
| """Returns an M x 62 matrix, C, of the win conditions. Multiply C*P and look for zeros."""
# M should be 3*(2 + 3 + 4 + 5 + 6 + 5 + 4 + 3 + 2) = 102
result = get_linear_condition_matrix((1, 1, 1, 1))
assert len(result) == 102, "I expect 102 loss conditions"
return result
| _in_direction(uvK_tuples, axis_n_starts, 5)) # Direction 3
return numpy.matrix(numpy.array(list(itertools.chain(*result))).reshape((len(result), result[0].shape[0])))
@functools.lru_cache(10)
def get_win_conditions():
| 63 | 64 | 120 | 15 | 48 | adamsd5/yavalath | players/blue/blue1.py | Python | get_win_conditions | get_win_conditions | 141 | 147 | 141 | 142 | 0bde14c05f7053d354890a207f4cc5bcb09a9a07 | bigcode/the-stack | train |
59073496cad6094b1e68b020 | train | function | @functools.lru_cache(10)
def get_check_conditions():
"""Returns an M x 62 matrix, C, of the win conditions. Multiply C*P and look for zeros."""
# M should be 3*(2 + 3 + 4 + 5 + 6 + 5 + 4 + 3 + 2) = 102
result = get_linear_condition_matrix((2, 1, 1, 2), delta=-1)
assert len(result) == 102, "I expect 102... | @functools.lru_cache(10)
def get_check_conditions():
| """Returns an M x 62 matrix, C, of the win conditions. Multiply C*P and look for zeros."""
# M should be 3*(2 + 3 + 4 + 5 + 6 + 5 + 4 + 3 + 2) = 102
result = get_linear_condition_matrix((2, 1, 1, 2), delta=-1)
assert len(result) == 102, "I expect 102 check conditions"
return result
| 3 + 2) = 102
result = get_linear_condition_matrix((1, 1, 1, 1))
assert len(result) == 102, "I expect 102 loss conditions"
return result
@functools.lru_cache(10)
def get_check_conditions():
| 64 | 64 | 124 | 15 | 48 | adamsd5/yavalath | players/blue/blue1.py | Python | get_check_conditions | get_check_conditions | 150 | 156 | 150 | 151 | febc0d0dee52695a74a857229768864b028770c1 | bigcode/the-stack | train |
83379a03eab5cdd1d91df0bc | train | function | def vector_player(game_so_far, depth=0, verbose=False):
state = GameState(game_so_far, verbose=verbose)
move_index, score = state.play(depth)
result = state.options[move_index]
#print("Shortcuts:")
#pprint.pprint(state.shortcuts)
#print("Key Spaces:")
#pprint.pprint(state.key_spaces)
ret... | def vector_player(game_so_far, depth=0, verbose=False):
| state = GameState(game_so_far, verbose=verbose)
move_index, score = state.play(depth)
result = state.options[move_index]
#print("Shortcuts:")
#pprint.pprint(state.shortcuts)
#print("Key Spaces:")
#pprint.pprint(state.key_spaces)
return result, score
| self.verbose:
print("==== play_uncached({}, {}), token:{}, returns:".format(depth, shortcut_threshold, self.token_for_next_player), self.options[my_move_index], my_score)
return my_move_index, my_score
def vector_player(game_so_far, depth=0, verbose=False):
| 64 | 64 | 85 | 14 | 49 | adamsd5/yavalath | players/blue/blue1.py | Python | vector_player | vector_player | 677 | 685 | 677 | 677 | edd26766a7135a27460e8973d353fa01cc582f43 | bigcode/the-stack | train |
041867625570689072f7c357 | train | function | @functools.lru_cache(10)
def get_loss_conditions():
"""Returns an M x 62 matrix, C, of the loss conditions. Multiply C*P and look for zeros."""
# M should be 3*(3 + 4 + 5 + 6 + 7 + 6 + 5 + 4 + 3) = 129
result = get_linear_condition_matrix((1, 1, 1))
assert len(result) == 129, "I expect 129 loss conditi... | @functools.lru_cache(10)
def get_loss_conditions():
| """Returns an M x 62 matrix, C, of the loss conditions. Multiply C*P and look for zeros."""
# M should be 3*(3 + 4 + 5 + 6 + 7 + 6 + 5 + 4 + 3) = 129
result = get_linear_condition_matrix((1, 1, 1))
assert len(result) == 129, "I expect 129 loss conditions"
return result
| ) = 102
result = get_linear_condition_matrix((2, 1, 1, 2), delta=-1)
assert len(result) == 102, "I expect 102 check conditions"
return result
@functools.lru_cache(10)
def get_loss_conditions():
| 64 | 64 | 117 | 15 | 48 | adamsd5/yavalath | players/blue/blue1.py | Python | get_loss_conditions | get_loss_conditions | 159 | 165 | 159 | 160 | 514437024e5cb0cfdbbb1f80fa7d1a82d01931f6 | bigcode/the-stack | train |
04ef2da8b7c7e5c444f51523 | train | function | def spaces_to_condition_vector(spaces, value, level):
result = spaces_to_board_vector(spaces, value)
result[61] = level
return result.transpose()
| def spaces_to_condition_vector(spaces, value, level):
| result = spaces_to_board_vector(spaces, value)
result[61] = level
return result.transpose()
| ")
for turn, move in enumerate(spaces):
# TODO: Handle 'swap'
result[space_to_index[move]] = value
result[61] = 1 # To account for the level of indicators.
return result
def spaces_to_condition_vector(spaces, value, level):
| 64 | 64 | 37 | 12 | 51 | adamsd5/yavalath | players/blue/blue1.py | Python | spaces_to_condition_vector | spaces_to_condition_vector | 71 | 74 | 71 | 71 | 860dd44b248342ea5c2a99e6acbc575e9027a1d8 | bigcode/the-stack | train |
4db0d484e0831dda25fd096b | train | function | def get_linear_condition_matrix(kernel, delta=0):
"""Applies a linear kernel as much as it can across the board, and returns a condition matrix for this kernel.
For example, the kernel for winning is (1,1,1,1). The resulting condition matrix is the set of win conditions.
The losing kernel is (1,1,1). The... | def get_linear_condition_matrix(kernel, delta=0):
| """Applies a linear kernel as much as it can across the board, and returns a condition matrix for this kernel.
For example, the kernel for winning is (1,1,1,1). The resulting condition matrix is the set of win conditions.
The losing kernel is (1,1,1). The resulting matrix is the set of lose conditions.
... | N = 61+1
result = numpy.zeros((N,1), dtype="i1")
for turn, move in enumerate(spaces):
# TODO: Handle 'swap'
result[space_to_index[move]] = value
result[61] = 1 # To account for the level of indicators.
return result
def spaces_to_condition_vector(spaces, value, level):
result = spa... | 244 | 244 | 815 | 11 | 232 | adamsd5/yavalath | players/blue/blue1.py | Python | get_linear_condition_matrix | get_linear_condition_matrix | 89 | 138 | 89 | 89 | 8734b1e5088d0aa55dd130a09b1c7a67f685858c | bigcode/the-stack | train |
c1064c3e8720c4b8b42affc6 | train | class | class GameState:
"""Each turn, a GameState is created by the player. This class allows the minimax algo to add and remove moves as
it is traversing the search tree."""
def __init__(self, game_so_far, verbose=True):
self.verbose = verbose
# Allocating memory. Ideally just do this once per c... | class GameState:
| """Each turn, a GameState is created by the player. This class allows the minimax algo to add and remove moves as
it is traversing the search tree."""
def __init__(self, game_so_far, verbose=True):
self.verbose = verbose
# Allocating memory. Ideally just do this once per call from the game... | print.pprint(sorted(opp_responses))
selection = sorted(opp_responses)[0] # Return my move that minimizes the opponent's best score. TODO: Select randomly among ties.
if verbose:
print("Selected:", selection)
opp_score, my_move_index, opp_move = selection
return options[my_move_index], -opp_sc... | 256 | 256 | 5,120 | 4 | 252 | adamsd5/yavalath | players/blue/blue1.py | Python | GameState | GameState | 330 | 675 | 330 | 330 | 5fce4c2ba63d25e7d09b7915f19911ebaba3292d | bigcode/the-stack | train |
fba4c5525160be29cc43edc8 | train | function | def main():
pass
| def main():
| pass
| =verbose)
move_index, score = state.play(depth)
result = state.options[move_index]
#print("Shortcuts:")
#pprint.pprint(state.shortcuts)
#print("Key Spaces:")
#pprint.pprint(state.key_spaces)
return result, score
def main():
| 64 | 64 | 6 | 3 | 60 | adamsd5/yavalath | players/blue/blue1.py | Python | main | main | 687 | 688 | 687 | 687 | 378685506c7f6439c83db41d6cba95c3fcdadc8e | bigcode/the-stack | train |
5eb21f8038e7085ef4402f10 | train | function | def vector_player_broken(game_so_far, depth=0, verbose=False):
"""This is my second attmept at an AI-driven player. Likely I'll have many variants.
"""
# First basic strategy, heading toward minimax. Score all moves on the current board.
# This implementation uses numpy matrices to speed things up
... | def vector_player_broken(game_so_far, depth=0, verbose=False):
| """This is my second attmept at an AI-driven player. Likely I'll have many variants.
"""
# First basic strategy, heading toward minimax. Score all moves on the current board.
# This implementation uses numpy matrices to speed things up
if verbose:
print("vector_player({}, {}, {})".format(g... | _far, option)
# I need to see if I win or lose with this option as-is
simple_score = simple_score_for_option(game_so_far, option)
if simple_score != 0:
return simple_score
# Consider all responses to your move, and the opponents best score for each
response_options = set(board.spaces) - se... | 256 | 256 | 1,498 | 16 | 239 | adamsd5/yavalath | players/blue/blue1.py | Python | vector_player_broken | vector_player_broken | 204 | 324 | 204 | 204 | c0e750fd8b0f3ddede5cb6642ec0fa01079fd2c1 | bigcode/the-stack | train |
dd4fadf37fa74d97967bded0 | train | function | def vector_minimax_score_for_option(board, game_so_far, option, depth, decay=0.9):
if depth == 0:
return simple_score_for_option(game_so_far, option)
# I need to see if I win or lose with this option as-is
simple_score = simple_score_for_option(game_so_far, option)
if simple_score != 0:
... | def vector_minimax_score_for_option(board, game_so_far, option, depth, decay=0.9):
| if depth == 0:
return simple_score_for_option(game_so_far, option)
# I need to see if I win or lose with this option as-is
simple_score = simple_score_for_option(game_so_far, option)
if simple_score != 0:
return simple_score
# Consider all responses to your move, and the opponents ... | , 1))
assert len(result) == 129, "I expect 129 loss conditions"
return result
#============================================================================================================
#== Using numpy arrays, and condition matrices
#========================================================================... | 64 | 64 | 201 | 23 | 41 | adamsd5/yavalath | players/blue/blue1.py | Python | vector_minimax_score_for_option | vector_minimax_score_for_option | 173 | 188 | 173 | 173 | 2503040f9680f5df98db662a271c76ae4d21236f | bigcode/the-stack | train |
469d157996c85f789371d3b6 | train | function | def moves_to_board_vector(moves):
board = yavalath_engine.HexBoard()
space_to_index = {space: i for i, space in enumerate(board.spaces)}
N = 61+1
result = numpy.zeros((N,1), dtype="i1")
for turn, move in enumerate(moves):
# TODO: Handle 'swap'
result[space_to_index[move]] = 1 if turn... | def moves_to_board_vector(moves):
| board = yavalath_engine.HexBoard()
space_to_index = {space: i for i, space in enumerate(board.spaces)}
N = 61+1
result = numpy.zeros((N,1), dtype="i1")
for turn, move in enumerate(moves):
# TODO: Handle 'swap'
result[space_to_index[move]] = 1 if turn % 2 == 0 else -1
result[61] =... | [61] = 1 # To account for the level of indicators.
return result
def spaces_to_condition_vector(spaces, value, level):
result = spaces_to_board_vector(spaces, value)
result[61] = level
return result.transpose()
def moves_to_board_vector(moves):
| 64 | 64 | 123 | 8 | 56 | adamsd5/yavalath | players/blue/blue1.py | Python | moves_to_board_vector | moves_to_board_vector | 76 | 85 | 76 | 76 | 2407da0de148a181b81df38b353e9f2da4b505c4 | bigcode/the-stack | train |
29da94122d3da891bae4a8d6 | train | function | def spaces_to_board_vector(spaces, value):
space_to_index = {space: i for i, space in enumerate(board.spaces)}
N = 61+1
result = numpy.zeros((N,1), dtype="i1")
for turn, move in enumerate(spaces):
# TODO: Handle 'swap'
result[space_to_index[move]] = value
result[61] = 1 # To account ... | def spaces_to_board_vector(spaces, value):
| space_to_index = {space: i for i, space in enumerate(board.spaces)}
N = 61+1
result = numpy.zeros((N,1), dtype="i1")
for turn, move in enumerate(spaces):
# TODO: Handle 'swap'
result[space_to_index[move]] = value
result[61] = 1 # To account for the level of indicators.
return res... | oss/check/multicheck (checks need a 3-horizon)
# classifications # dict of states -> set of options
# next_turn_token #-1 or 1, depending who goes next
# ==== The linear condition vectors approach ===
def spaces_to_board_vector(spaces, value):
| 64 | 64 | 103 | 10 | 53 | adamsd5/yavalath | players/blue/blue1.py | Python | spaces_to_board_vector | spaces_to_board_vector | 61 | 69 | 61 | 61 | 3503307576d83a94bc2cef8a567d156623ca1797 | bigcode/the-stack | train |
a7ea84faa16339a4ae04b8a9 | train | class | class Conditions():
win_conditions = get_win_conditions()
loss_conditions = get_loss_conditions()
check_conditions = get_check_conditions()
board = yavalath_engine.HexBoard()
space_to_index = {space:i for i, space in enumerate(board.spaces)}
| class Conditions():
| win_conditions = get_win_conditions()
loss_conditions = get_loss_conditions()
check_conditions = get_check_conditions()
board = yavalath_engine.HexBoard()
space_to_index = {space:i for i, space in enumerate(board.spaces)}
| [option], o, depth-1), o) for o in response_options]
# The score for this option for me is the negative of my opponent's best score.
best_opponent_response = max(response_scored_options)
return -best_opponent_response[0]*decay
class Conditions():
| 64 | 64 | 55 | 3 | 60 | adamsd5/yavalath | players/blue/blue1.py | Python | Conditions | Conditions | 191 | 196 | 191 | 191 | 3dfa090cafb15addecaa7df5bbd7d2df91c5eb7b | bigcode/the-stack | train |
37ca1752979201b90b294180 | train | function | def is_even(v):
return v%2 == 0
| def is_even(v):
| return v%2 == 0
| decay
class Conditions():
win_conditions = get_win_conditions()
loss_conditions = get_loss_conditions()
check_conditions = get_check_conditions()
board = yavalath_engine.HexBoard()
space_to_index = {space:i for i, space in enumerate(board.spaces)}
def is_even(v):
| 63 | 64 | 14 | 5 | 58 | adamsd5/yavalath | players/blue/blue1.py | Python | is_even | is_even | 199 | 200 | 199 | 199 | b07fc4af667f894609acca7bad357b6944b27b68 | bigcode/the-stack | train |
4d7734c25f5156d0a016da59 | train | class | class EC2InternetGateway(GenericBaseModel):
@staticmethod
def cloudformation_type():
return "AWS::EC2::InternetGateway"
def fetch_state(self, stack_name, resources):
client = aws_stack.connect_to_service("ec2")
gateways = client.describe_internet_gateways()["InternetGateways"]
... | class EC2InternetGateway(GenericBaseModel):
@staticmethod
| def cloudformation_type():
return "AWS::EC2::InternetGateway"
def fetch_state(self, stack_name, resources):
client = aws_stack.connect_to_service("ec2")
gateways = client.describe_internet_gateways()["InternetGateways"]
tags = self.props.get("Tags")
gateway = [g for g in... | "parameters": {
"DestinationCidrBlock": "DestinationCidrBlock",
"DestinationIpv6CidrBlock": "DestinationIpv6CidrBlock",
"RouteTableId": "RouteTableId",
},
},
}
class EC2InternetGateway(GenericBaseModel):
... | 65 | 65 | 219 | 13 | 52 | rajendersaini/localstack | localstack/services/cloudformation/models/ec2.py | Python | EC2InternetGateway | EC2InternetGateway | 101 | 130 | 101 | 102 | 80a25cd077f11a23ed7de84b70396bf1bebf9232 | bigcode/the-stack | train |
fb6874a4948daa615192e10d | train | class | class EC2Instance(GenericBaseModel):
@staticmethod
def cloudformation_type():
return "AWS::EC2::Instance"
def fetch_state(self, stack_name, resources):
instance_id = self.get_physical_resource_id()
if not instance_id:
return
return self._get_state()
def upda... | class EC2Instance(GenericBaseModel):
@staticmethod
| def cloudformation_type():
return "AWS::EC2::Instance"
def fetch_state(self, stack_name, resources):
instance_id = self.get_physical_resource_id()
if not instance_id:
return
return self._get_state()
def update_resource(self, new_resource, stack_name, resources):... | [ga["AllocationId"] for ga in gw["NatGatewayAddresses"]]
]
return (result or [None])[0]
@staticmethod
def get_deploy_templates():
return {
"create": {
"function": "create_nat_gateway",
"parameters": {
"SubnetId": "SubnetId... | 166 | 166 | 555 | 12 | 154 | rajendersaini/localstack | localstack/services/cloudformation/models/ec2.py | Python | EC2Instance | EC2Instance | 370 | 440 | 370 | 371 | 68e9802d1d5bb4ef95b809507f075acf21d7116b | bigcode/the-stack | train |
ba173a852fb09411079a25d4 | train | class | class EC2NatGateway(GenericBaseModel):
@staticmethod
def cloudformation_type():
return "AWS::EC2::NatGateway"
def fetch_state(self, stack_name, resources):
client = aws_stack.connect_to_service("ec2")
props = self.props
subnet_id = self.resolve_refs_recursively(stack_name, p... | class EC2NatGateway(GenericBaseModel):
@staticmethod
| def cloudformation_type():
return "AWS::EC2::NatGateway"
def fetch_state(self, stack_name, resources):
client = aws_stack.connect_to_service("ec2")
props = self.props
subnet_id = self.resolve_refs_recursively(stack_name, props.get("SubnetId"), resources)
assoc_id = self.... | ancy": "InstanceTenancy"
# TODO: add TagSpecifications
},
},
"delete": {
"function": "delete_vpc",
"parameters": {"VpcId": "PhysicalResourceId"},
},
}
def get_physical_resource_id(self, attribute=None, *... | 93 | 93 | 311 | 13 | 80 | rajendersaini/localstack | localstack/services/cloudformation/models/ec2.py | Python | EC2NatGateway | EC2NatGateway | 328 | 367 | 328 | 329 | 8c59385879646379df151838e6099d41493e4a2d | bigcode/the-stack | train |
91cceca2f1f780273190416e | train | class | class EC2Route(GenericBaseModel):
@staticmethod
def cloudformation_type():
return "AWS::EC2::Route"
def fetch_state(self, stack_name, resources):
client = aws_stack.connect_to_service("ec2")
props = self.props
dst_cidr = self.resolve_refs_recursively(
stack_name,... | class EC2Route(GenericBaseModel):
@staticmethod
| def cloudformation_type():
return "AWS::EC2::Route"
def fetch_state(self, stack_name, resources):
client = aws_stack.connect_to_service("ec2")
props = self.props
dst_cidr = self.resolve_refs_recursively(
stack_name, props.get("DestinationCidrBlock"), resources
... | return self.physical_resource_id or self.props.get("RouteTableId")
@staticmethod
def get_deploy_templates():
return {
"create": {
"function": "create_route_table",
"parameters": {
"VpcId": "VpcId",
"TagSpecifica... | 137 | 137 | 459 | 12 | 125 | rajendersaini/localstack | localstack/services/cloudformation/models/ec2.py | Python | EC2Route | EC2Route | 44 | 98 | 44 | 45 | 48d967cd08dd03316070ed91186ec0ae5bf197ee | bigcode/the-stack | train |
394eb7953c1a3460a1a66c00 | train | class | class EC2SubnetRouteTableAssociation(GenericBaseModel):
@staticmethod
def cloudformation_type():
return "AWS::EC2::SubnetRouteTableAssociation"
def fetch_state(self, stack_name, resources):
client = aws_stack.connect_to_service("ec2")
props = self.props
table_id = self.resol... | class EC2SubnetRouteTableAssociation(GenericBaseModel):
@staticmethod
| def cloudformation_type():
return "AWS::EC2::SubnetRouteTableAssociation"
def fetch_state(self, stack_name, resources):
client = aws_stack.connect_to_service("ec2")
props = self.props
table_id = self.resolve_refs_recursively(stack_name, props.get("RouteTableId"), resources)
... | create_params(params, **kwargs):
return {
"TagSpecifications": [
{"ResourceType": "internet-gateway", "Tags": params.get("Tags", [])}
]
}
return {
"create": {
"function": "create_internet_gateway",
... | 85 | 85 | 284 | 15 | 70 | rajendersaini/localstack | localstack/services/cloudformation/models/ec2.py | Python | EC2SubnetRouteTableAssociation | EC2SubnetRouteTableAssociation | 133 | 164 | 133 | 134 | 2a43d04ae6a26f096dfe88da91b8e94bbd4ecc8f | bigcode/the-stack | train |
73c022feefd13e81f62ab2e9 | train | class | class EC2VPC(GenericBaseModel):
@staticmethod
def cloudformation_type():
return "AWS::EC2::VPC"
def fetch_state(self, stack_name, resources):
client = aws_stack.connect_to_service("ec2")
resp = client.describe_vpcs(Filters=[{"Name": "cidr", "Values": [self.props["CidrBlock"]]}])
... | class EC2VPC(GenericBaseModel):
@staticmethod
| def cloudformation_type():
return "AWS::EC2::VPC"
def fetch_state(self, stack_name, resources):
client = aws_stack.connect_to_service("ec2")
resp = client.describe_vpcs(Filters=[{"Name": "cidr", "Values": [self.props["CidrBlock"]]}])
return (resp["Vpcs"] or [None])[0]
@stat... | Block",
"AvailabilityZone": "AvailabilityZone"
# TODO: add TagSpecifications
},
},
"delete": {
"function": "delete_subnet",
"parameters": {"SubnetId": "PhysicalResourceId"},
},
}
class EC2... | 67 | 67 | 225 | 13 | 54 | rajendersaini/localstack | localstack/services/cloudformation/models/ec2.py | Python | EC2VPC | EC2VPC | 297 | 325 | 297 | 298 | 4ab6ec7c7f9cb0463801090d8e4645bab5caa914 | bigcode/the-stack | train |
a936d76346c7de4559a1a950 | train | class | class EC2Subnet(GenericBaseModel):
@staticmethod
def cloudformation_type():
return "AWS::EC2::Subnet"
def fetch_state(self, stack_name, resources):
client = aws_stack.connect_to_service("ec2")
props = self.props
filters = [
{"Name": "cidr-block", "Values": [props... | class EC2Subnet(GenericBaseModel):
@staticmethod
| def cloudformation_type():
return "AWS::EC2::Subnet"
def fetch_state(self, stack_name, resources):
client = aws_stack.connect_to_service("ec2")
props = self.props
filters = [
{"Name": "cidr-block", "Values": [props["CidrBlock"]]},
{"Name": "vpc-id", "Valu... | function": "create_security_group",
"parameters": {
"GroupName": "GroupName",
"VpcId": "VpcId",
"Description": "GroupDescription",
},
},
"delete": {
"function": "delete_security_group",
... | 85 | 85 | 284 | 12 | 73 | rajendersaini/localstack | localstack/services/cloudformation/models/ec2.py | Python | EC2Subnet | EC2Subnet | 258 | 294 | 258 | 259 | 83f1404dbeecc6a86581d089512fcf5d02ca2873 | bigcode/the-stack | train |
74638788d598f297af6aa6d5 | train | class | class EC2VPCGatewayAttachment(GenericBaseModel):
@staticmethod
def cloudformation_type():
return "AWS::EC2::VPCGatewayAttachment"
def fetch_state(self, stack_name, resources):
client = aws_stack.connect_to_service("ec2")
props = self.props
igw_id = self.resolve_refs_recursiv... | class EC2VPCGatewayAttachment(GenericBaseModel):
@staticmethod
| def cloudformation_type():
return "AWS::EC2::VPCGatewayAttachment"
def fetch_state(self, stack_name, resources):
client = aws_stack.connect_to_service("ec2")
props = self.props
igw_id = self.resolve_refs_recursively(
stack_name, props.get("InternetGatewayId"), resour... | :
associations = route_table.get("Associations", [])
association = [a for a in associations if a.get("GatewayId") == gw_id]
return (association or [None])[0]
def get_physical_resource_id(self, attribute=None, **kwargs):
return self.props.get("RouteTableAssociationId")
... | 151 | 151 | 505 | 15 | 136 | rajendersaini/localstack | localstack/services/cloudformation/models/ec2.py | Python | EC2VPCGatewayAttachment | EC2VPCGatewayAttachment | 167 | 214 | 167 | 168 | 00bd82ce74744ae6eb15034edef49c805cf2fcfd | bigcode/the-stack | train |
263d0997eb54a123905c24a2 | train | class | class EC2RouteTable(GenericBaseModel):
@staticmethod
def cloudformation_type():
return "AWS::EC2::RouteTable"
def fetch_state(self, stack_name, resources):
client = aws_stack.connect_to_service("ec2")
route_tables = client.describe_route_tables(
Filters=[
... | class EC2RouteTable(GenericBaseModel):
@staticmethod
| def cloudformation_type():
return "AWS::EC2::RouteTable"
def fetch_state(self, stack_name, resources):
client = aws_stack.connect_to_service("ec2")
route_tables = client.describe_route_tables(
Filters=[
{"Name": "vpc-id", "Values": [self.props["VpcId"]]},
... | from moto.ec2.utils import generate_route_id
from localstack.services.cloudformation.service_models import REF_ID_ATTRS, GenericBaseModel
from localstack.utils.aws import aws_stack
class EC2RouteTable(GenericBaseModel):
@staticmethod
| 50 | 77 | 259 | 13 | 36 | rajendersaini/localstack | localstack/services/cloudformation/models/ec2.py | Python | EC2RouteTable | EC2RouteTable | 7 | 41 | 7 | 8 | 620e4dab2d08657b60793b6511c1f3e79d812e1e | bigcode/the-stack | train |
020c60685c8128771821c7a2 | train | class | class SecurityGroup(GenericBaseModel):
@staticmethod
def cloudformation_type():
return "AWS::EC2::SecurityGroup"
def fetch_state(self, stack_name, resources):
props = self.props
group_id = props.get("GroupId")
group_name = props.get("GroupName")
client = aws_stack.co... | class SecurityGroup(GenericBaseModel):
@staticmethod
| def cloudformation_type():
return "AWS::EC2::SecurityGroup"
def fetch_state(self, stack_name, resources):
props = self.props
group_id = props.get("GroupId")
group_name = props.get("GroupName")
client = aws_stack.connect_to_service("ec2")
if group_id:
... | ("VpcId")
if igw_id:
client.attach_internet_gateway(VpcId=vpc_id, InternetGatewayId=igw_id)
elif vpngw_id:
client.attach_vpn_gateway(VpcId=vpc_id, VpnGatewayId=vpngw_id)
return {"create": {"function": _attach_gateway}}
class SecurityGroup(GenericBaseModel... | 83 | 84 | 280 | 11 | 72 | rajendersaini/localstack | localstack/services/cloudformation/models/ec2.py | Python | SecurityGroup | SecurityGroup | 217 | 255 | 217 | 218 | b8280e21f2be85b6ca9392970044b025b159ce9f | bigcode/the-stack | train |
b810bf13d5a271707cc21671 | train | class | @setup
class SaveHumanity(Endpoint):
params = ['text']
def generate(self, avatars, text, usernames, kwargs):
base = Image.open(self.assets.get('assets/humanity/humanity.bmp')).convert('RGBA')
# We need a text layer here for the rotation
text_layer = Image.new('RGBA', base.size)
... | @setup
class SaveHumanity(Endpoint):
| params = ['text']
def generate(self, avatars, text, usernames, kwargs):
base = Image.open(self.assets.get('assets/humanity/humanity.bmp')).convert('RGBA')
# We need a text layer here for the rotation
text_layer = Image.new('RGBA', base.size)
font = self.assets.get_font('assets/f... | from io import BytesIO
from PIL import Image, ImageDraw
from flask import send_file
from utils.endpoint import Endpoint, setup
from utils.textutils import wrap
@setup
class SaveHumanity(Endpoint):
| 45 | 64 | 208 | 10 | 34 | thelucyclub/meme-server | endpoints/savehumanity.py | Python | SaveHumanity | SaveHumanity | 10 | 32 | 10 | 11 | d5d36a6f191f310e15f565e675693f545cfb4317 | bigcode/the-stack | train |
c9eafc1940fd2d541ead1181 | train | function | @patch('bigchaindb_driver.transport.time')
@patch('bigchaindb_driver.transport.Connection._request')
def test_timeout_after_second_node(request_mock, time_mock):
request_mock.side_effect = ConnectionError
time_mock.side_effect = [0, 1, 1, 2]
transport = Transport(*normalize_nodes('first_node', 'second_nod... | @patch('bigchaindb_driver.transport.time')
@patch('bigchaindb_driver.transport.Connection._request')
def test_timeout_after_second_node(request_mock, time_mock):
| request_mock.side_effect = ConnectionError
time_mock.side_effect = [0, 1, 1, 2]
transport = Transport(*normalize_nodes('first_node', 'second_node'),
timeout=2)
with pytest.raises(TimeoutError):
transport.forward_request('POST')
# timeout=2 now so we manage to hit... | ' in request_kwargs['url']
# timeout is propagated to the HTTP request
assert request_kwargs['timeout'] == 1
@patch('bigchaindb_driver.transport.time')
@patch('bigchaindb_driver.transport.Connection._request')
def test_timeout_after_second_node(request_mock, time_mock):
| 64 | 64 | 206 | 36 | 27 | 18000548d/bigchaindb-driver | tests/test_transport.py | Python | test_timeout_after_second_node | test_timeout_after_second_node | 57 | 77 | 57 | 60 | e7c3356a4f4b3e991c79de54328aeca73b90c15b | bigcode/the-stack | train |
5816c178340ab2cfa3e93fda | train | function | def test_init_with_headers():
from bigchaindb_driver.transport import Transport
from bigchaindb_driver.utils import normalize_nodes
headers = {'app_id': 'id'}
nodes = normalize_nodes('node1',
{'endpoint': 'node2', 'headers': {'custom': 'c'}},
heade... | def test_init_with_headers():
| from bigchaindb_driver.transport import Transport
from bigchaindb_driver.utils import normalize_nodes
headers = {'app_id': 'id'}
nodes = normalize_nodes('node1',
{'endpoint': 'node2', 'headers': {'custom': 'c'}},
headers=headers)
transport = Tr... | .0
import pytest
from unittest.mock import patch
from requests.exceptions import ConnectionError
from requests.utils import default_headers
from bigchaindb_driver.exceptions import TimeoutError
from bigchaindb_driver.transport import Transport
from bigchaindb_driver.utils import normalize_nodes
def test_init_with_h... | 64 | 64 | 131 | 6 | 57 | 18000548d/bigchaindb-driver | tests/test_transport.py | Python | test_init_with_headers | test_init_with_headers | 17 | 31 | 17 | 17 | a97909a1fb3c95d43ed0e816fbfa547689af724b | bigcode/the-stack | train |
7917d1548e9e8a9f86ba4ee7 | train | function | @patch('bigchaindb_driver.transport.time')
@patch('bigchaindb_driver.transport.Connection._request')
def test_timeout_during_request(request_mock, time_mock):
request_mock.side_effect = TimeoutError
time_mock.side_effect = [0, 1]
transport = Transport(*normalize_nodes('first_node', 'second_node'),
... | @patch('bigchaindb_driver.transport.time')
@patch('bigchaindb_driver.transport.Connection._request')
def test_timeout_during_request(request_mock, time_mock):
| request_mock.side_effect = TimeoutError
time_mock.side_effect = [0, 1]
transport = Transport(*normalize_nodes('first_node', 'second_node'),
timeout=100)
with pytest.raises(TimeoutError):
transport.forward_request('POST')
assert len(request_mock.call_args_list) ==... | 2
assert 'second_node' in second_request_kwargs['url']
assert second_request_kwargs['timeout'] == 1
@patch('bigchaindb_driver.transport.time')
@patch('bigchaindb_driver.transport.Connection._request')
def test_timeout_during_request(request_mock, time_mock):
| 64 | 64 | 142 | 36 | 27 | 18000548d/bigchaindb-driver | tests/test_transport.py | Python | test_timeout_during_request | test_timeout_during_request | 80 | 96 | 80 | 83 | 1ad6bea8c7463f7754dddf7d0d8d142c02fc0efe | bigcode/the-stack | train |
b96c938821b8b1a9dca0816f | train | function | @patch('bigchaindb_driver.transport.time')
@patch('bigchaindb_driver.transport.Connection._request')
def test_timeout_after_first_node(request_mock, time_mock):
# simulate intermittent network failure on every attempt
request_mock.side_effect = ConnectionError
# simulate a second passing in between each p... | @patch('bigchaindb_driver.transport.time')
@patch('bigchaindb_driver.transport.Connection._request')
def test_timeout_after_first_node(request_mock, time_mock):
# simulate intermittent network failure on every attempt
| request_mock.side_effect = ConnectionError
# simulate a second passing in between each pair of time() calls
time_mock.side_effect = [0, 1]
transport = Transport(*normalize_nodes('first_node', 'second_node'),
timeout=1)
with pytest.raises(TimeoutError):
transport.f... | 1].session.headers == {**expected_headers,
'custom': 'c'}
@patch('bigchaindb_driver.transport.time')
@patch('bigchaindb_driver.transport.Connection._request')
def test_timeout_after_first_node(request_mock, time_mock):
# simulate intermittent network failure on every a... | 63 | 64 | 188 | 46 | 17 | 18000548d/bigchaindb-driver | tests/test_transport.py | Python | test_timeout_after_first_node | test_timeout_after_first_node | 34 | 54 | 34 | 38 | 724dc05a1210c2f963f60d2758661af7f490663f | bigcode/the-stack | train |
3d61b00ed5d7de230d3ec1f6 | train | function | def main():
current_dir = os.path.dirname(os.path.realpath(__file__))
with open('%s/../../src/iris/__init__.py' % current_dir, 'r') as fd:
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)
print('Generating packer config for... | def main():
| current_dir = os.path.dirname(os.path.realpath(__file__))
with open('%s/../../src/iris/__init__.py' % current_dir, 'r') as fd:
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)
print('Generating packer config for iris v%s' %... | #!/usr/bin/env python
# -*- coding:utf-8 -*-
from __future__ import print_function
import re
import os
import yaml
import json
import sys
OUTPUT_DIR = 'output'
def main():
| 45 | 64 | 214 | 3 | 42 | minhaz1/iris | ops/packer/gen_packer_cfg.py | Python | main | main | 14 | 33 | 14 | 14 | bd582b3060d3344b1d38d11e50d187c1eb615db7 | bigcode/the-stack | train |
9f025b30b84d3f8a4975c851 | train | function | def lorem_ipsum_app(environ, start_response):
start_response('200 OK', [('Content-type','text/plain'), ('Content-Length','19')])
return ['Lorem ipsum dolor..']
| def lorem_ipsum_app(environ, start_response):
| start_response('200 OK', [('Content-type','text/plain'), ('Content-Length','19')])
return ['Lorem ipsum dolor..']
| def lorem_ipsum_app(environ, start_response):
| 11 | 64 | 40 | 11 | 0 | ionelmc/cogen | examples/helloworld-twistedweb2-wsgi-app.py | Python | lorem_ipsum_app | lorem_ipsum_app | 1 | 3 | 1 | 1 | cfdd243b1924b2eb7b95b530efb1b118b12b65d2 | bigcode/the-stack | train |
fb7d7b776ca3fe4f328f0667 | train | function | def read_number(): # function to read in the text
with open(fileName) as f:
num = int(f.read()) # convert the number string to an integer
return num # return the integer
| def read_number(): # function to read in the text
| with open(fileName) as f:
num = int(f.read()) # convert the number string to an integer
return num # return the integer
| # program read in a text file from an existing text
# helen oshea
# 20210224
fileName = 'count.txt' # location of the file
def read_number(): # function to read in the text
| 49 | 64 | 46 | 12 | 36 | Osheah/hospfcs2021 | week06/readsNumber.py | Python | read_number | read_number | 7 | 10 | 7 | 7 | da0cd99400938f4f55a9eca6f7418efff317272a | bigcode/the-stack | train |
eebb066880f87635f58cf9b7 | train | function | def parseArguments():
for qv in [ "qvina02" ]:
qvina = which(qv)
if qvina:
break
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--infile", help="Compound file for docking in pdbqt format", type=str, default=None)
parser.add_argument("-o", "--outfile", help="C... | def parseArguments():
| for qv in [ "qvina02" ]:
qvina = which(qv)
if qvina:
break
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--infile", help="Compound file for docking in pdbqt format", type=str, default=None)
parser.add_argument("-o", "--outfile", help="CSV file for writing ta... | os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None
def parseArguments():
| 71 | 71 | 239 | 4 | 66 | dspoel/cetoxa | cetoxa.py | Python | parseArguments | parseArguments | 213 | 227 | 213 | 213 | 9923b8cc40be6acd789afb49c998d0c478d0ba2c | bigcode/the-stack | train |
7c76dc4ec2166563f8771f7d | train | class | class BoxSize():
def __init__(self, dimx, dimy, dimz):
self.dimx = dimx
self.dimy = dimy
self.dimz = dimz
| class BoxSize():
| def __init__(self, dimx, dimy, dimz):
self.dimx = dimx
self.dimy = dimy
self.dimz = dimz
| icm.uu.se>
# David van der Spoel <david.vanderspoel@icm.uu.se>
#=====================================================================
import os, glob, getpass, math, sys, argparse
from random import randint
import pandas as pd
import tempfile, shutil
class BoxSize():
| 64 | 64 | 44 | 4 | 59 | dspoel/cetoxa | cetoxa.py | Python | BoxSize | BoxSize | 14 | 18 | 14 | 14 | 2c4df79d4a2a2ee565f4052a47f79386332b340b | bigcode/the-stack | train |
0380a570b36f7b8b5ad6a203 | train | class | class DockingResult:
def __init__(self, family, name, score, site):
self.family = family.strip()
self.name = name.strip()
self.score = score
self.site = site
def __lt__(self, other):
if self.family == other.family:
return self.score < other.score
... | class DockingResult:
| def __init__(self, family, name, score, site):
self.family = family.strip()
self.name = name.strip()
self.score = score
self.site = site
def __lt__(self, other):
if self.family == other.family:
return self.score < other.score
else:
ret... | cm[i]), float(zcm[i]), box.dimx, box.dimy, box.dimz, ncpu ) )
print("%s site %d" % ( pdbcode, i ) )
if verbose:
os.system(cmd)
else:
os.system("%s >& /dev/null" % cmd)
class DockingResult:
| 70 | 70 | 235 | 5 | 65 | dspoel/cetoxa | cetoxa.py | Python | DockingResult | DockingResult | 130 | 155 | 130 | 130 | f204116032c48891a3faf9f0e221505e13a2820c | bigcode/the-stack | train |
61bc04315476c130d5d0d573 | train | function | def dock(pathway, tmpdir, target_dir, targets, binding_dir,
ligand, ncpu, verbose):
for ppp in range(len(targets)):
p=targets[ppp]
target_pdbqt = target_dir + "/" + p
pdbcode = p[:-6]
bindingsites_txt = binding_dir + "/" + pdbcode + "_bindingsites.txt"
#Get the b... | def dock(pathway, tmpdir, target_dir, targets, binding_dir,
ligand, ncpu, verbose):
| for ppp in range(len(targets)):
p=targets[ppp]
target_pdbqt = target_dir + "/" + p
pdbcode = p[:-6]
bindingsites_txt = binding_dir + "/" + pdbcode + "_bindingsites.txt"
#Get the box dimensions
box = default_box_size(ligand)
xcm,ycm,zcm,bindingsites=get_bin... |
xcm=[]
ycm=[]
zcm=[]
with open(filename, "r") as Sites:
for line in Sites:
bindingsites+=1
xcm.append(line.split()[0])
ycm.append(line.split()[1])
zcm.append(line.split()[2])
return xcm,ycm,zcm,bindingsites
def dock(pathway, tmpdir, target_d... | 100 | 100 | 336 | 24 | 75 | dspoel/cetoxa | cetoxa.py | Python | dock | dock | 108 | 128 | 108 | 109 | e23024de0224c537278caaa7de8fdaeb50221f60 | bigcode/the-stack | train |
7fadf5a72036026adeddb2de | train | function | def default_box_size(filename):
coord_x = []
coord_y = []
coord_z = []
with open(filename, "r") as Structure:
for line in Structure:
try:
if line[0:6] == "HETATM" or line[0:4] == "ATOM":
coord_x.append(float(line[30:38]))
coord... | def default_box_size(filename):
| coord_x = []
coord_y = []
coord_z = []
with open(filename, "r") as Structure:
for line in Structure:
try:
if line[0:6] == "HETATM" or line[0:4] == "ATOM":
coord_x.append(float(line[30:38]))
coord_y.append(float(line[38:46]))
... | # Script to dock one ligand to CETOXA using QVina-2
# Authors: Natasha Kamerlin <natasha.kamerlin@icm.uu.se>
# David van der Spoel <david.vanderspoel@icm.uu.se>
#=====================================================================
import os, glob, getpass, math, sys, argparse
from random import randint
im... | 141 | 141 | 470 | 6 | 134 | dspoel/cetoxa | cetoxa.py | Python | default_box_size | default_box_size | 20 | 84 | 20 | 20 | f11a9b486ed111d3ad6d1b5570e0e8d365e311aa | bigcode/the-stack | train |
70502e1c8933325ea9380e9a | train | function | def extract(protInfo, tmpdir, targets, binding_dir, ligand, outfile):
output = []
for ppp in range(len(targets)):
p = targets[ppp]
target = p[:-6]
protname=protInfo['Name'][protInfo['PDBID']==target].to_string(index=False)
protfam=protInfo['Family'][protInfo['PDBID']==target... | def extract(protInfo, tmpdir, targets, binding_dir, ligand, outfile):
| output = []
for ppp in range(len(targets)):
p = targets[ppp]
target = p[:-6]
protname=protInfo['Name'][protInfo['PDBID']==target].to_string(index=False)
protfam=protInfo['Family'][protInfo['PDBID']==target].to_string(index=False)
bindingsites_txt = binding_dir + "/" ... | def __le__(self, other):
return __eq__(other) or __lt__(other)
def __ge__(self, other):
return __eq__(other) or __gt__(other)
def __ne__(self, other):
return not __eq__(other)
def printCsv(self, outputFile):
outputFile.write("%s,%s,%g,%s\n" % ( self.family, self.name, sel... | 117 | 118 | 396 | 18 | 99 | dspoel/cetoxa | cetoxa.py | Python | extract | extract | 157 | 195 | 157 | 157 | 3b8da176dacc8ead09c38b5e177ff12c8a5b7759 | bigcode/the-stack | train |
f4f403676f4308e772927099 | train | function | def get_bindingsite(filename):
bindingsites=0
xcm=[]
ycm=[]
zcm=[]
with open(filename, "r") as Sites:
for line in Sites:
bindingsites+=1
xcm.append(line.split()[0])
ycm.append(line.split()[1])
zcm.append(line.split()[2])
return xcm,ycm,zc... | def get_bindingsite(filename):
| bindingsites=0
xcm=[]
ycm=[]
zcm=[]
with open(filename, "r") as Sites:
for line in Sites:
bindingsites+=1
xcm.append(line.split()[0])
ycm.append(line.split()[1])
zcm.append(line.split()[2])
return xcm,ycm,zcm,bindingsites
| zmin
return BoxSize(dimx, dimy, dimz)
def get_pdbqt(dir):
wd = os.getcwd()
os.chdir(dir)
pdbqt = glob.glob("*.pdbqt")
os.chdir(wd)
return pdbqt
def get_bindingsite(filename):
| 64 | 64 | 88 | 7 | 56 | dspoel/cetoxa | cetoxa.py | Python | get_bindingsite | get_bindingsite | 93 | 106 | 93 | 93 | b00590c389aeab9d872db22960b27564d921d67c | bigcode/the-stack | train |
af5dc6637bb7a93291ad5a94 | train | function | def which(program):
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
exe_file = os.path... | def which(program):
| def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
exe_file = os.path.join(path, program)... | open(outfile, "w") as outputfile:
# Print the results
outputfile.write("%s,%s,%s,%s\n" % ( 'Class', 'Target', 'Score', 'Site' ) )
for data in sorted_output:
data.printCsv(outputfile)
def which(program):
| 64 | 64 | 103 | 4 | 60 | dspoel/cetoxa | cetoxa.py | Python | which | which | 197 | 211 | 197 | 197 | 6b6d9770f61e641ff595052732450737a6216e95 | bigcode/the-stack | train |
15b9d9bb8182122d0eb59aca | train | function | def get_pdbqt(dir):
wd = os.getcwd()
os.chdir(dir)
pdbqt = glob.glob("*.pdbqt")
os.chdir(wd)
return pdbqt
| def get_pdbqt(dir):
| wd = os.getcwd()
os.chdir(dir)
pdbqt = glob.glob("*.pdbqt")
os.chdir(wd)
return pdbqt
| < 22.5:
offsetz = (22.5 - dimz)/2
zmax += offsetz
zmin -= offsetz
dimz = zmax - zmin
return BoxSize(dimx, dimy, dimz)
def get_pdbqt(dir):
| 64 | 64 | 41 | 7 | 57 | dspoel/cetoxa | cetoxa.py | Python | get_pdbqt | get_pdbqt | 86 | 91 | 86 | 86 | a72fdb74ef43c192e4308f74e5b0673a4de90925 | bigcode/the-stack | train |
8f3c0b016a31da329a198ab6 | train | class | @base.Hidden
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class Create(base.Command):
"""Create a DataPol taxonomy."""
@staticmethod
def Args(parser):
"""Register flags for this command."""
parser.add_argument('name',
default='',
metavar='TAXONOMY_NAME',
... | @base.Hidden
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class Create(base.Command):
| """Create a DataPol taxonomy."""
@staticmethod
def Args(parser):
"""Register flags for this command."""
parser.add_argument('name',
default='',
metavar='TAXONOMY_NAME',
help='Name of the taxonomy.')
parser.add_argument('--adminis... | IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""datapol taxonomies create command."""
from googlecloudsdk.calliope import arg_parsers
from googlecloudsdk.calliope import bas... | 100 | 100 | 336 | 20 | 79 | bopopescu/searchparty | google-cloud-sdk/lib/surface/datapol/taxonomies/create.py | Python | Create | Create | 22 | 71 | 22 | 24 | bb4253d9c210f88c0de7d0d23105ddc4ef28103e | bigcode/the-stack | train |
f2dd99572f901e9f1d202171 | train | function | def _get_exact_model(name):
manifest = _load_zoo_models_manifest()
try:
return manifest.get_model_with_name(name)
except etam.ModelError:
raise ValueError("No model with name '%s' was found" % name)
| def _get_exact_model(name):
| manifest = _load_zoo_models_manifest()
try:
return manifest.get_model_with_name(name)
except etam.ModelError:
raise ValueError("No model with name '%s' was found" % name)
| fo.config.model_zoo_dir
model_path = model.get_path_in_dir(models_dir)
return model, model_path
def _get_model(name):
if ZooModel.has_version_str(name):
return _get_exact_model(name)
return _get_latest_model(name)
def _get_exact_model(name):
| 64 | 64 | 54 | 7 | 57 | FLIR/fiftyone | fiftyone/zoo/models/__init__.py | Python | _get_exact_model | _get_exact_model | 364 | 369 | 364 | 364 | 437c3bd1bab40ef1eebd5d0338bdbe69ccee9b86 | bigcode/the-stack | train |
09038399d2667cf2aa29503b | train | function | def ensure_zoo_model_requirements(name, error_level=None, log_success=True):
"""Ensures that the package requirements for the zoo model with the given
name are satisfied.
Args:
name: the name of the zoo model, which can have ``@<ver>`` appended to
refer to a specific version of the mode... | def ensure_zoo_model_requirements(name, error_level=None, log_success=True):
| """Ensures that the package requirements for the zoo model with the given
name are satisfied.
Args:
name: the name of the zoo model, which can have ``@<ver>`` appended to
refer to a specific version of the model. If no version is
specified, the latest version of the model is... | : ignore install fails requirements
By default, ``fo.config.requirement_error_level`` is used
"""
if error_level is None:
error_level = fo.config.requirement_error_level
model = _get_model(name)
model.install_requirements(error_level=error_level)
def ensure_zoo_model_requirements(n... | 77 | 77 | 257 | 17 | 60 | FLIR/fiftyone | fiftyone/zoo/models/__init__.py | Python | ensure_zoo_model_requirements | ensure_zoo_model_requirements | 125 | 149 | 125 | 125 | e4a336c8092693938dc3103998cab6cb21aabcbe | bigcode/the-stack | train |
9a8154efed1161fbfc4e5ffc | train | function | def get_zoo_model(name):
"""Returns the :class:`ZooModel` instance for the model with the given
name.
Args:
name: the name of the zoo model
Returns:
a :class:`ZooModel`
"""
return _get_model(name)
| def get_zoo_model(name):
| """Returns the :class:`ZooModel` instance for the model with the given
name.
Args:
name: the name of the zoo model
Returns:
a :class:`ZooModel`
"""
return _get_model(name)
| model does not exist or has not been downloaded
"""
model, model_path = _get_model_in_dir(name)
if not model.is_model_downloaded(model_path):
raise ValueError("Model '%s' is not downloaded" % name)
return model_path
def get_zoo_model(name):
| 64 | 64 | 61 | 7 | 56 | FLIR/fiftyone | fiftyone/zoo/models/__init__.py | Python | get_zoo_model | get_zoo_model | 234 | 244 | 234 | 234 | 28b7c7d23dc0631c01d23fb7b91b33ebbeed2b8b | bigcode/the-stack | train |
14189d6c465d5d7482306127 | train | class | class ZooModelsManifest(etam.ModelsManifest):
"""Class that describes the collection of models in the FiftyOne Model Zoo.
Args:
models: a list of :class:`ZooModel` instances
"""
_MODEL_CLS = ZooModel
| class ZooModelsManifest(etam.ModelsManifest):
| """Class that describes the collection of models in the FiftyOne Model Zoo.
Args:
models: a list of :class:`ZooModel` instances
"""
_MODEL_CLS = ZooModel
| is inaccurate, you can set "
"`fiftyone.config.requirement_error_level` to 1 (warning) or 2 (ignore).\n"
"See https://voxel51.com/docs/fiftyone/user_guide/config.html for details."
)
class ZooModelsManifest(etam.ModelsManifest):
| 64 | 64 | 53 | 9 | 55 | FLIR/fiftyone | fiftyone/zoo/models/__init__.py | Python | ZooModelsManifest | ZooModelsManifest | 327 | 334 | 327 | 327 | 919c1a9a07b48a5c851cc845ec8ad49ff0a27d35 | bigcode/the-stack | train |
1d6cc9b30f2d2b85a73ad72e | train | function | def list_zoo_models():
"""Returns the list of available models in the FiftyOne Model Zoo.
Returns:
a list of model names
"""
manifest = _load_zoo_models_manifest()
return sorted([model.name for model in manifest])
| def list_zoo_models():
| """Returns the list of available models in the FiftyOne Model Zoo.
Returns:
a list of model names
"""
manifest = _load_zoo_models_manifest()
return sorted([model.name for model in manifest])
| as etau
import fiftyone as fo
import fiftyone.core.models as fom
logger = logging.getLogger(__name__)
_THIS_DIR = os.path.dirname(os.path.abspath(__file__))
_MODELS_MANIFEST_PATT = os.path.join(_THIS_DIR, "manifest-*.json")
def list_zoo_models():
| 64 | 64 | 54 | 6 | 58 | FLIR/fiftyone | fiftyone/zoo/models/__init__.py | Python | list_zoo_models | list_zoo_models | 29 | 36 | 29 | 29 | 7df72cd49f6a5a94f44e135d378637d15727774e | bigcode/the-stack | train |
3899156d41ba592df14de3a8 | train | function | def is_zoo_model_downloaded(name):
"""Determines whether the zoo model of the given name is downloaded.
Args:
name: the name of the zoo model, which can have ``@<ver>`` appended to
refer to a specific version of the model. If no version is
specified, the latest version of the mo... | def is_zoo_model_downloaded(name):
| """Determines whether the zoo model of the given name is downloaded.
Args:
name: the name of the zoo model, which can have ``@<ver>`` appended to
refer to a specific version of the model. If no version is
specified, the latest version of the model is used
Returns:
T... | fo.config.model_zoo_dir
models = {}
for model in manifest:
if model.is_in_dir(models_dir):
model_path = model.get_path_in_dir(models_dir)
models[model.name] = (model_path, model)
return models
def is_zoo_model_downloaded(name):
| 64 | 64 | 114 | 9 | 54 | FLIR/fiftyone | fiftyone/zoo/models/__init__.py | Python | is_zoo_model_downloaded | is_zoo_model_downloaded | 57 | 70 | 57 | 57 | 0e3b7289854fc83c219120ca0749a9d4b93c3178 | bigcode/the-stack | train |
3428956e4fd4d48eae66def7 | train | function | def _get_latest_model(base_name):
manifest = _load_zoo_models_manifest()
try:
return manifest.get_latest_model_with_base_name(base_name)
except etam.ModelError:
raise ValueError("No models found with base name '%s'" % base_name)
| def _get_latest_model(base_name):
| manifest = _load_zoo_models_manifest()
try:
return manifest.get_latest_model_with_base_name(base_name)
except etam.ModelError:
raise ValueError("No models found with base name '%s'" % base_name)
| (name)
def _get_exact_model(name):
manifest = _load_zoo_models_manifest()
try:
return manifest.get_model_with_name(name)
except etam.ModelError:
raise ValueError("No model with name '%s' was found" % name)
def _get_latest_model(base_name):
| 64 | 64 | 58 | 8 | 56 | FLIR/fiftyone | fiftyone/zoo/models/__init__.py | Python | _get_latest_model | _get_latest_model | 372 | 377 | 372 | 372 | 116c5bae11b0f451a31ab4b3d4f7f79b6aee70f5 | bigcode/the-stack | train |
775202084d02cc9c013a5cce | train | function | def find_zoo_model(name):
"""Returns the path to the zoo model on disk.
The model must be downloaded. Use :func:`download_zoo_model` to download
models.
Args:
name: the name of the zoo model, which can have ``@<ver>`` appended to
refer to a specific version of the model. If no vers... | def find_zoo_model(name):
| """Returns the path to the zoo model on disk.
The model must be downloaded. Use :func:`download_zoo_model` to download
models.
Args:
name: the name of the zoo model, which can have ``@<ver>`` appended to
refer to a specific version of the model. If no version is
specifi... | error_level)
else:
model.ensure_requirements(error_level=error_level)
config_dict = deepcopy(model.default_deployment_config_dict)
model_path = model.get_path_in_dir(models_dir)
return fom.load_model(config_dict, model_path=model_path, **kwargs)
def find_zoo_model(name):
| 64 | 64 | 171 | 7 | 57 | FLIR/fiftyone | fiftyone/zoo/models/__init__.py | Python | find_zoo_model | find_zoo_model | 210 | 231 | 210 | 210 | 2bfbef1c7c44343cd87b016798a4186af5acfefb | bigcode/the-stack | train |
d6d701434189efd8274238f9 | train | function | def _get_model_in_dir(name):
model = _get_model(name)
models_dir = fo.config.model_zoo_dir
model_path = model.get_path_in_dir(models_dir)
return model, model_path
| def _get_model_in_dir(name):
| model = _get_model(name)
models_dir = fo.config.model_zoo_dir
model_path = model.get_path_in_dir(models_dir)
return model, model_path
| (_MODELS_MANIFEST_PATT)
if fo.config.model_zoo_manifest_paths:
manifest_paths.extend(fo.config.model_zoo_manifest_paths)
for manifest_path in manifest_paths:
manifest.merge(ZooModelsManifest.from_json(manifest_path))
return manifest
def _get_model_in_dir(name):
| 64 | 64 | 46 | 8 | 55 | FLIR/fiftyone | fiftyone/zoo/models/__init__.py | Python | _get_model_in_dir | _get_model_in_dir | 350 | 354 | 350 | 350 | 15a228bf8a62b9d33922fcc71a191fe81bd21a85 | bigcode/the-stack | train |
9115f72633dce2e871dc60d4 | train | function | def list_downloaded_zoo_models():
"""Returns information about the zoo models that have been downloaded.
Returns:
a dict mapping model names to (model path, :class:`ZooModel`) tuples
"""
manifest = _load_zoo_models_manifest()
models_dir = fo.config.model_zoo_dir
models = {}
for mod... | def list_downloaded_zoo_models():
| """Returns information about the zoo models that have been downloaded.
Returns:
a dict mapping model names to (model path, :class:`ZooModel`) tuples
"""
manifest = _load_zoo_models_manifest()
models_dir = fo.config.model_zoo_dir
models = {}
for model in manifest:
if model.i... | json")
def list_zoo_models():
"""Returns the list of available models in the FiftyOne Model Zoo.
Returns:
a list of model names
"""
manifest = _load_zoo_models_manifest()
return sorted([model.name for model in manifest])
def list_downloaded_zoo_models():
| 64 | 64 | 114 | 8 | 56 | FLIR/fiftyone | fiftyone/zoo/models/__init__.py | Python | list_downloaded_zoo_models | list_downloaded_zoo_models | 39 | 54 | 39 | 39 | c46a93fe66fdb7ff1f41dd638ef7407b3fd576c7 | bigcode/the-stack | train |
15e9bdd534e4e61eca8f8f53 | train | function | def _get_model(name):
if ZooModel.has_version_str(name):
return _get_exact_model(name)
return _get_latest_model(name)
| def _get_model(name):
| if ZooModel.has_version_str(name):
return _get_exact_model(name)
return _get_latest_model(name)
| ModelsManifest.from_json(manifest_path))
return manifest
def _get_model_in_dir(name):
model = _get_model(name)
models_dir = fo.config.model_zoo_dir
model_path = model.get_path_in_dir(models_dir)
return model, model_path
def _get_model(name):
| 64 | 64 | 31 | 6 | 57 | FLIR/fiftyone | fiftyone/zoo/models/__init__.py | Python | _get_model | _get_model | 357 | 361 | 357 | 357 | 0a886667acba795626ff8cd5aa7c06bcde4819a9 | bigcode/the-stack | train |
23a5f9106d8324763bdccfc7 | train | function | def _load_zoo_models_manifest():
manifest = ZooModelsManifest()
manifest_paths = etau.get_glob_matches(_MODELS_MANIFEST_PATT)
if fo.config.model_zoo_manifest_paths:
manifest_paths.extend(fo.config.model_zoo_manifest_paths)
for manifest_path in manifest_paths:
manifest.merge(ZooModelsMa... | def _load_zoo_models_manifest():
| manifest = ZooModelsManifest()
manifest_paths = etau.get_glob_matches(_MODELS_MANIFEST_PATT)
if fo.config.model_zoo_manifest_paths:
manifest_paths.extend(fo.config.model_zoo_manifest_paths)
for manifest_path in manifest_paths:
manifest.merge(ZooModelsManifest.from_json(manifest_path))
... | ."
)
class ZooModelsManifest(etam.ModelsManifest):
"""Class that describes the collection of models in the FiftyOne Model Zoo.
Args:
models: a list of :class:`ZooModel` instances
"""
_MODEL_CLS = ZooModel
def _load_zoo_models_manifest():
| 64 | 64 | 81 | 8 | 55 | FLIR/fiftyone | fiftyone/zoo/models/__init__.py | Python | _load_zoo_models_manifest | _load_zoo_models_manifest | 337 | 347 | 337 | 337 | 6527ca6c03cd9bfb6436c0875a915ed9466711f3 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.