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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e98d11f2ffe8b0189924dce4 | train | function | def main_test():
'''Main function for testing'''
EXPERIMENT_NAME = 'Adam_lr0.0001_max_vocab_size50000'
params = open_experiment(EXPERIMENT_NAME)
cfg_path = params['cfg_path']
# Hyper-parameters
BATCH_SIZE = 256
EMBEDDING_DIM = 200
HIDDEN_DIM = 256
MAX_VOCAB_SIZE = 50000 # use the s... | def main_test():
| '''Main function for testing'''
EXPERIMENT_NAME = 'Adam_lr0.0001_max_vocab_size50000'
params = open_experiment(EXPERIMENT_NAME)
cfg_path = params['cfg_path']
# Hyper-parameters
BATCH_SIZE = 256
EMBEDDING_DIM = 200
HIDDEN_DIM = 256
MAX_VOCAB_SIZE = 50000 # use the same "max_vocab_si... | trainer.load_checkpoint(model=MODEL, optimiser=OPTIMIZER,
optimiser_params=optimiser_params, loss_function=LOSS_FUNCTION, weight=weights)
else:
trainer.setup_model(model=MODEL, optimiser=OPTIMIZER,
optimiser_params=optimiser_params, loss_function=LOSS_FUNCTIO... | 91 | 91 | 304 | 4 | 87 | jeroenvanriel/retweet | main.py | Python | main_test | main_test | 93 | 115 | 93 | 93 | 7f9619ef8cc4a2d8bf8149bc752b652980e113aa | bigcode/the-stack | train |
6daa85b4b0c980879d06c6dd | train | function | def main_test_postreply():
'''Main function for testing of the second part of the project
Sentiment analysis of the Post-Replies.
'''
EXPERIMENT_NAME = 'new_october_CNN'
BATCH_SIZE = 256
params = open_experiment(EXPERIMENT_NAME)
cfg_path = params['cfg_path']
vocab_size = params['Network... | def main_test_postreply():
| '''Main function for testing of the second part of the project
Sentiment analysis of the Post-Replies.
'''
EXPERIMENT_NAME = 'new_october_CNN'
BATCH_SIZE = 256
params = open_experiment(EXPERIMENT_NAME)
cfg_path = params['cfg_path']
vocab_size = params['Network']['vocab_size']
PAD_ID... | params['Network']['HIDDEN_DIM'] = HIDDEN_DIM
params['Network']['EMBEDDING_DIM'] = EMBEDDING_DIM
params['Network']['conv_out_ch'] = conv_out_ch
params['Network']['MODEL_MODE'] = MODEL_MODE
params['total_train_tweets'] = total_train_tweets
params['total_valid_tweets'] = tot... | 124 | 124 | 416 | 6 | 118 | jeroenvanriel/retweet | main.py | Python | main_test_postreply | main_test_postreply | 309 | 345 | 309 | 309 | e2ef532639b15d7988a8edac22e8c15cfd091658 | bigcode/the-stack | train |
4381134ee0df42bda3c841fa | train | function | def main_manual_predict(PHRASE=None, prediction_mode='Manualpart1'):
'''
Manually predicts the polarity of the given sentence.
:mode:
'Manualpart1' predicts the sentiment of the tweet (part 1 pf the project)
'Manualpart2' predicts the semtiment of the potential reply of the tweet (part 2)
... | def main_manual_predict(PHRASE=None, prediction_mode='Manualpart1'):
| '''
Manually predicts the polarity of the given sentence.
:mode:
'Manualpart1' predicts the sentiment of the tweet (part 1 pf the project)
'Manualpart2' predicts the semtiment of the potential reply of the tweet (part 2)
Note that for each part you should give the correct experiment ... | # Prepare data
data_handler_test = data_provider_V2(cfg_path=cfg_path, batch_size=BATCH_SIZE, split_ratio=SPLIT_RATIO,
max_vocab_size=MAX_VOCAB_SIZE, mode=Mode.TEST, model_mode=MODEL_MODE)
test_iterator, vocab_size, PAD_IDX, UNK_IDX, pretrained_embeddings, classes = ... | 182 | 182 | 608 | 17 | 165 | jeroenvanriel/retweet | main.py | Python | main_manual_predict | main_manual_predict | 119 | 166 | 119 | 119 | 7f6abe626c10072d0869fc71caba6bce72c54cd8 | bigcode/the-stack | train |
806c1dec1b182554c57ad183 | train | function | def main_reply_predict(DATA_MODE = 'getoldtweet'):
'''
Manually predicts the polarity of the given replies,
which will be regarded as the labels for the corresponding tweets
and creates a labeled dataset of only tweets and corresponding labels.
:DATA_MODE: 'getoldtweet' or 'philipp'
'''
star... | def main_reply_predict(DATA_MODE = 'getoldtweet'):
| '''
Manually predicts the polarity of the given replies,
which will be regarded as the labels for the corresponding tweets
and creates a labeled dataset of only tweets and corresponding labels.
:DATA_MODE: 'getoldtweet' or 'philipp'
'''
start_time = time.time()
EXPERIMENT_NAME = 'Adam_lr... | vocab_idx, vocab_size, PAD_IDX, UNK_IDX, pretrained_embeddings, classes = data_handler_test.data_loader()
# Initialize prediction
predictor = Prediction(cfg_path, model_mode=MODEL_MODE)
predictor.setup_model(model=biLSTM, vocab_size=vocab_size, embedding_dim=EMBEDDING_DIM, hidden_dim=HIDDEN_DIM,
... | 190 | 191 | 638 | 12 | 178 | jeroenvanriel/retweet | main.py | Python | main_reply_predict | main_reply_predict | 170 | 224 | 170 | 170 | ea3695e264e7176e944c3994f4d52032f8fe60be | bigcode/the-stack | train |
bbc2f933dd1f554664d02cd2 | train | function | def test_every_epoch():
EXPERIMENT_NAME = 'new_october_CNN'
BATCH_SIZE = 256
params = open_experiment(EXPERIMENT_NAME)
cfg_path = params['cfg_path']
vocab_size = params['Network']['vocab_size']
PAD_IDX = params['Network']['PAD_IDX']
UNK_IDX = params['Network']['UNK_IDX']
classes = param... | def test_every_epoch():
| EXPERIMENT_NAME = 'new_october_CNN'
BATCH_SIZE = 256
params = open_experiment(EXPERIMENT_NAME)
cfg_path = params['cfg_path']
vocab_size = params['Network']['vocab_size']
PAD_IDX = params['Network']['PAD_IDX']
UNK_IDX = params['Network']['UNK_IDX']
classes = params['Network']['classes']
... | NN.data_loader()
# Initialize predictor
predictor = Prediction(cfg_path=params_RNN['cfg_path'], model_mode=MODEL_MODE, classes=classes,
cfg_path_RNN=cfg_path_RNN, cfg_path_CNN=cfg_path_CNN)
predictor.setup_model(model=biLSTM, vocab_size=vocab_size, embeddings=pretrained_embedding... | 164 | 164 | 548 | 5 | 159 | jeroenvanriel/retweet | main.py | Python | test_every_epoch | test_every_epoch | 389 | 433 | 389 | 389 | dadc7da2d454240a293082600d68dff325001eae | bigcode/the-stack | train |
030d6af23a2bc2508547a958 | train | function | def main_train_postreply():
'''
Main function for training + validation of the second part of the project:
Sentiment analysis of the Post-Replies.
'''
# if we are resuming training on a model
RESUME = False
# Hyper-parameters
NUM_EPOCH = 500
LOSS_FUNCTION = CrossEntropyLoss
OPTI... | def main_train_postreply():
| '''
Main function for training + validation of the second part of the project:
Sentiment analysis of the Post-Replies.
'''
# if we are resuming training on a model
RESUME = False
# Hyper-parameters
NUM_EPOCH = 500
LOSS_FUNCTION = CrossEntropyLoss
OPTIMIZER = optim.Adam
BATCH... | _dim=EMBEDDING_DIM, hidden_dim=HIDDEN_DIM, pad_idx=PAD_IDX, unk_idx=UNK_IDX)
data = pd.read_csv(os.path.join(params['postreply_data_path'], original_data))
data = data.reindex(columns=['label', 'tweet', 'id', 'user', 'reply'])
# Execute Prediction
nlp = spacy.load('en')
for idx, item in enumerate(d... | 255 | 256 | 940 | 6 | 249 | jeroenvanriel/retweet | main.py | Python | main_train_postreply | main_train_postreply | 228 | 305 | 228 | 228 | 3a59f46b32423d466cf22c2ffced6790c4900f67 | bigcode/the-stack | train |
4ef91b7d4ab5376b21fc7361 | train | function | def main_ensemble_test_postreply():
'''Main function for testing ensemble model.
'''
EXPERIMENT_NAME_RNN = 'new_october'
EXPERIMENT_NAME_CNN = 'new_october_CNN'
BATCH_SIZE = 256
params_RNN = open_experiment(EXPERIMENT_NAME_RNN)
params_CNN = open_experiment(EXPERIMENT_NAME_CNN)
cfg_path_... | def main_ensemble_test_postreply():
| '''Main function for testing ensemble model.
'''
EXPERIMENT_NAME_RNN = 'new_october'
EXPERIMENT_NAME_CNN = 'new_october_CNN'
BATCH_SIZE = 256
params_RNN = open_experiment(EXPERIMENT_NAME_RNN)
params_CNN = open_experiment(EXPERIMENT_NAME_CNN)
cfg_path_RNN = params_RNN['cfg_path']
cfg... | MAX_VOCAB_SIZE, mode=Mode.TEST, model_mode=MODEL_MODE)
test_iterator = data_handler_test.data_loader()
# Initialize predictor
predictor = Prediction(cfg_path, model_mode=MODEL_MODE, classes=classes)
if MODEL_MODE == "RNN":
MODEL = biLSTM
elif MODEL_MODE == "CNN":
MODEL = CNN1d
... | 169 | 169 | 564 | 8 | 161 | jeroenvanriel/retweet | main.py | Python | main_ensemble_test_postreply | main_ensemble_test_postreply | 349 | 386 | 349 | 349 | e50a862620b30fa12dfcefc1214df606d3115a1c | bigcode/the-stack | train |
130c3eac06fa5516c0ac1e64 | train | function | def prediction_time(start_time, end_time):
elapsed_time = end_time - start_time
elapsed_mins = int(elapsed_time / 60)
elapsed_secs = int(elapsed_time - (elapsed_mins * 60))
return elapsed_mins, elapsed_secs
| def prediction_time(start_time, end_time):
| elapsed_time = end_time - start_time
elapsed_mins = int(elapsed_time / 60)
elapsed_secs = int(elapsed_time - (elapsed_mins * 60))
return elapsed_mins, elapsed_secs
| columns=['epoch', 'F1']))
test_F1.to_csv(os.path.join(params['output_data_path'], 'test_F1.csv'), index=False)
test_acc.to_csv(os.path.join(params['output_data_path'], 'test_acc.csv'), index=False)
def prediction_time(start_time, end_time):
| 63 | 64 | 58 | 9 | 54 | jeroenvanriel/retweet | main.py | Python | prediction_time | prediction_time | 439 | 443 | 439 | 439 | 8da54380b34a791c64b8fb402937f42a126530ed | bigcode/the-stack | train |
ca3a1f536f8ae6042063cd86 | train | function | def main_train():
'''Main function for training + validation.'''
# if we are resuming training on a model
RESUME = True
# Hyper-parameters
NUM_EPOCH = 100
LOSS_FUNCTION = CrossEntropyLoss
OPTIMIZER = optim.Adam
BATCH_SIZE = 256
MAX_VOCAB_SIZE = 50000 #max_vocab_size: takes the 100,... | def main_train():
| '''Main function for training + validation.'''
# if we are resuming training on a model
RESUME = True
# Hyper-parameters
NUM_EPOCH = 100
LOSS_FUNCTION = CrossEntropyLoss
OPTIMIZER = optim.Adam
BATCH_SIZE = 256
MAX_VOCAB_SIZE = 50000 #max_vocab_size: takes the 100,000 most frequent ... | '''
This is the main function running the Training, Validation, Testing process.
Set the hyper-parameters and model parameters here. [data parameters from config file]
@author: Soroosh Tayebi Arasteh <soroosh.arasteh@fau.de>
https://github.com/tayebiarasteh/
https://tayebiarasteh.com/
'''
# Deep Learning Modules
from... | 174 | 220 | 734 | 4 | 170 | jeroenvanriel/retweet | main.py | Python | main_train | main_train | 33 | 89 | 33 | 33 | bfc3d15ed71bb2c26d993b24d483abbb323bfbdc | bigcode/the-stack | train |
71eeda34bda3f726e091c460 | train | function | def test_line_model_invalid_input():
with testing.raises(ValueError):
LineModelND().estimate(np.empty((1, 3)))
| def test_line_model_invalid_input():
| with testing.raises(ValueError):
LineModelND().estimate(np.empty((1, 3)))
| EllipseModel, ransac
from skimage.transform import AffineTransform
from skimage.measure.fit import _dynamic_max_trials
from skimage._shared import testing
from skimage._shared.testing import (assert_equal, assert_almost_equal,
assert_array_less)
def test_line_model_invalid_input()... | 64 | 64 | 28 | 7 | 57 | portugueslab/scikit-image | skimage/measure/tests/test_fit.py | Python | test_line_model_invalid_input | test_line_model_invalid_input | 11 | 13 | 11 | 11 | bca5dfa681e3ab966c89f8365965ca82999d293b | bigcode/the-stack | train |
4fc4fc25212e2df821234b5c | train | function | def test_line_model_nd_predict():
model = LineModelND()
model.params = (np.array([0, 0]), np.array([0.2, 0.8]))
x = np.arange(-10, 10)
y = model.predict_y(x)
assert_almost_equal(x, model.predict_x(y))
| def test_line_model_nd_predict():
| model = LineModelND()
model.params = (np.array([0, 0]), np.array([0.2, 0.8]))
x = np.arange(-10, 10)
y = model.predict_y(x)
assert_almost_equal(x, model.predict_x(y))
| .empty((1, 3)))
with testing.raises(AssertionError):
LineModelND().residuals(np.empty((1, 3)))
data = np.empty((1, 2))
with testing.raises(ValueError):
LineModelND().estimate(data)
def test_line_model_nd_predict():
| 64 | 64 | 70 | 7 | 57 | portugueslab/scikit-image | skimage/measure/tests/test_fit.py | Python | test_line_model_nd_predict | test_line_model_nd_predict | 51 | 56 | 51 | 51 | 30dc8a5c82f8f52e944c68d8708f5fdb97182111 | bigcode/the-stack | train |
1cfe8ec537cd074e84cb7faa | train | function | def test_ransac_is_data_valid():
def is_data_valid(data):
return data.shape[0] > 2
model, inliers = ransac(np.empty((10, 2)), LineModelND, 2, np.inf,
is_data_valid=is_data_valid, random_state=1)
assert_equal(model, None)
assert_equal(inliers, None)
| def test_ransac_is_data_valid():
| def is_data_valid(data):
return data.shape[0] > 2
model, inliers = ransac(np.empty((10, 2)), LineModelND, 2, np.inf,
is_data_valid=is_data_valid, random_state=1)
assert_equal(model, None)
assert_equal(inliers, None)
| Transform, 2, 20,
random_state=random_state)
# test whether estimated parameters equal original parameters
assert_almost_equal(model0.params, model_est.params)
assert np.all(np.nonzero(inliers == False)[0] == outliers)
def test_ransac_is_data_valid():
| 64 | 64 | 82 | 9 | 55 | portugueslab/scikit-image | skimage/measure/tests/test_fit.py | Python | test_ransac_is_data_valid | test_ransac_is_data_valid | 282 | 288 | 282 | 282 | f69e17e89edf1a25c36f290c0992c0e89ecc055c | bigcode/the-stack | train |
1f58fbcce809505bda4e17fe | train | function | def test_ransac_is_model_valid():
def is_model_valid(model, data):
return False
model, inliers = ransac(np.empty((10, 2)), LineModelND, 2, np.inf,
is_model_valid=is_model_valid, random_state=1)
assert_equal(model, None)
assert_equal(inliers, None)
| def test_ransac_is_model_valid():
| def is_model_valid(model, data):
return False
model, inliers = ransac(np.empty((10, 2)), LineModelND, 2, np.inf,
is_model_valid=is_model_valid, random_state=1)
assert_equal(model, None)
assert_equal(inliers, None)
| model, inliers = ransac(np.empty((10, 2)), LineModelND, 2, np.inf,
is_data_valid=is_data_valid, random_state=1)
assert_equal(model, None)
assert_equal(inliers, None)
def test_ransac_is_model_valid():
| 64 | 64 | 77 | 9 | 55 | portugueslab/scikit-image | skimage/measure/tests/test_fit.py | Python | test_ransac_is_model_valid | test_ransac_is_model_valid | 291 | 297 | 291 | 291 | 17b3a597f96363fce182bea4ec986ad2e42da973 | bigcode/the-stack | train |
b2c8dd66cc6419eb6c8faa42 | train | function | def test_ransac_geometric():
random_state = np.random.RandomState(1)
# generate original data without noise
src = 100 * random_state.random_sample((50, 2))
model0 = AffineTransform(scale=(0.5, 0.3), rotation=1,
translation=(10, 20))
dst = model0(src)
# add some fau... | def test_ransac_geometric():
| random_state = np.random.RandomState(1)
# generate original data without noise
src = 100 * random_state.random_sample((50, 2))
model0 = AffineTransform(scale=(0.5, 0.3), rotation=1,
translation=(10, 20))
dst = model0(src)
# add some faulty data
outliers = (0, 5... | ac(data0, CircleModel, 3, 5,
random_state=1)
# test whether estimated parameters equal original parameters
assert_almost_equal(model0.params, model_est.params)
for outlier in outliers:
assert outlier not in inliers
def test_ransac_geometric():
| 67 | 67 | 224 | 8 | 58 | portugueslab/scikit-image | skimage/measure/tests/test_fit.py | Python | test_ransac_geometric | test_ransac_geometric | 258 | 279 | 258 | 258 | 0ecbfa8a26ee467fc2367fb120e3eb9976448a39 | bigcode/the-stack | train |
04664ef04a3de89466fd2e8c | train | function | def test_line_model_predict():
model = LineModelND()
model.params = ((0, 0), (1, 1))
x = np.arange(-10, 10)
y = model.predict_y(x)
assert_almost_equal(x, model.predict_x(y))
| def test_line_model_predict():
| model = LineModelND()
model.params = ((0, 0), (1, 1))
x = np.arange(-10, 10)
y = model.predict_y(x)
assert_almost_equal(x, model.predict_x(y))
| from skimage._shared import testing
from skimage._shared.testing import (assert_equal, assert_almost_equal,
assert_array_less)
def test_line_model_invalid_input():
with testing.raises(ValueError):
LineModelND().estimate(np.empty((1, 3)))
def test_line_model_predict():
| 63 | 64 | 60 | 6 | 57 | portugueslab/scikit-image | skimage/measure/tests/test_fit.py | Python | test_line_model_predict | test_line_model_predict | 16 | 21 | 16 | 16 | 0d178da70f3d54610abbac97c8ccbd00a58a1bf6 | bigcode/the-stack | train |
aea64a297afa70d46223c669 | train | function | def test_circle_model_residuals():
model = CircleModel()
model.params = (0, 0, 5)
assert_almost_equal(abs(model.residuals(np.array([[5, 0]]))), 0)
assert_almost_equal(abs(model.residuals(np.array([[6, 6]]))),
np.sqrt(2 * 6**2) - 5)
assert_almost_equal(abs(model.residuals(np.a... | def test_circle_model_residuals():
| model = CircleModel()
model.params = (0, 0, 5)
assert_almost_equal(abs(model.residuals(np.array([[5, 0]]))), 0)
assert_almost_equal(abs(model.residuals(np.array([[6, 6]]))),
np.sqrt(2 * 6**2) - 5)
assert_almost_equal(abs(model.residuals(np.array([[10, 0]]))), 5)
| _state.normal(size=data0.shape)
# estimate parameters of noisy data
model_est = CircleModel()
model_est.estimate(data)
# test whether estimated parameters almost equal original parameters
assert_almost_equal(model0.params, model_est.params, 0)
def test_circle_model_residuals():
| 64 | 64 | 105 | 8 | 56 | portugueslab/scikit-image | skimage/measure/tests/test_fit.py | Python | test_circle_model_residuals | test_circle_model_residuals | 139 | 145 | 139 | 139 | fa02ebd4ea0768bfebaef830619063675c710209 | bigcode/the-stack | train |
ce8798b00e6139d64ad19e98 | train | function | def test_circle_model_predict():
model = CircleModel()
r = 5
model.params = (0, 0, r)
t = np.arange(0, 2 * np.pi, np.pi / 2)
xy = np.array(((5, 0), (0, 5), (-5, 0), (0, -5)))
assert_almost_equal(xy, model.predict_xy(t))
| def test_circle_model_predict():
| model = CircleModel()
r = 5
model.params = (0, 0, r)
t = np.arange(0, 2 * np.pi, np.pi / 2)
xy = np.array(((5, 0), (0, 5), (-5, 0), (0, -5)))
assert_almost_equal(xy, model.predict_xy(t))
| _under_determined():
data = np.empty((1, 3))
with testing.raises(ValueError):
LineModelND().estimate(data)
def test_circle_model_invalid_input():
with testing.raises(ValueError):
CircleModel().estimate(np.empty((5, 3)))
def test_circle_model_predict():
| 63 | 64 | 92 | 6 | 57 | portugueslab/scikit-image | skimage/measure/tests/test_fit.py | Python | test_circle_model_predict | test_circle_model_predict | 110 | 117 | 110 | 110 | d0ada476b6bc171a292181ad679317876aba2c36 | bigcode/the-stack | train |
f68e63221e8ce22a2010e1bb | train | function | def test_line_model_nd_residuals():
model = LineModelND()
model.params = (np.array([0, 0, 0]), np.array([0, 0, 1]))
assert_equal(abs(model.residuals(np.array([[0, 0, 0]]))), 0)
assert_equal(abs(model.residuals(np.array([[0, 0, 1]]))), 0)
assert_equal(abs(model.residuals(np.array([[10, 0, 0]]))), 10)... | def test_line_model_nd_residuals():
| model = LineModelND()
model.params = (np.array([0, 0, 0]), np.array([0, 0, 1]))
assert_equal(abs(model.residuals(np.array([[0, 0, 0]]))), 0)
assert_equal(abs(model.residuals(np.array([[0, 0, 1]]))), 0)
assert_equal(abs(model.residuals(np.array([[10, 0, 0]]))), 10)
| _est.params[0] - model0.params[0]
if np.linalg.norm(a) > 0:
a /= np.linalg.norm(a)
assert_almost_equal(np.linalg.norm(np.cross(model0.params[1], a)), 0, 1)
def test_line_model_nd_residuals():
| 64 | 64 | 112 | 9 | 55 | portugueslab/scikit-image | skimage/measure/tests/test_fit.py | Python | test_line_model_nd_residuals | test_line_model_nd_residuals | 91 | 96 | 91 | 91 | 76f9bc380d452afae600393d6fea046c35442913 | bigcode/the-stack | train |
c356e5467478c96a70ad86c1 | train | function | def test_ransac_shape():
# generate original data without noise
model0 = CircleModel()
model0.params = (10, 12, 3)
t = np.linspace(0, 2 * np.pi, 1000)
data0 = model0.predict_xy(t)
# add some faulty data
outliers = (10, 30, 200)
data0[outliers[0], :] = (1000, 1000)
data0[outliers[1],... | def test_ransac_shape():
# generate original data without noise
| model0 = CircleModel()
model0.params = (10, 12, 3)
t = np.linspace(0, 2 * np.pi, 1000)
data0 = model0.predict_xy(t)
# add some faulty data
outliers = (10, 30, 200)
data0[outliers[0], :] = (1000, 1000)
data0[outliers[1], :] = (-50, 50)
data0[outliers[2], :] = (-100, -10)
# estim... | ]]))), 0)
assert_almost_equal(abs(model.residuals(np.array([[0, 5]]))), 0)
assert_almost_equal(abs(model.residuals(np.array([[0, 10]]))), 5)
def test_ransac_shape():
# generate original data without noise
| 64 | 64 | 210 | 15 | 49 | portugueslab/scikit-image | skimage/measure/tests/test_fit.py | Python | test_ransac_shape | test_ransac_shape | 235 | 255 | 235 | 236 | 5ed5be955dc10ca51f6f2c661b552b5ced6b6141 | bigcode/the-stack | train |
bebbf327cca1c8328a438977 | train | function | def test_ellipse_model_estimate_from_data():
data = np.array([
[264, 854], [265, 875], [268, 863], [270, 857], [275, 905], [285, 915],
[305, 925], [324, 934], [335, 764], [336, 915], [345, 925], [345, 945],
[354, 933], [355, 745], [364, 936], [365, 754], [375, 745], [375, 735],
[385,... | def test_ellipse_model_estimate_from_data():
| data = np.array([
[264, 854], [265, 875], [268, 863], [270, 857], [275, 905], [285, 915],
[305, 925], [324, 934], [335, 764], [336, 915], [345, 925], [345, 945],
[354, 933], [355, 745], [364, 936], [365, 754], [375, 745], [375, 735],
[385, 736], [395, 735], [394, 935], [405, 727], [4... | xy = np.array(((5, 0), (0, 10), (-5, 0), (0, -10)))
assert_almost_equal(xy, model.predict_xy(t))
def test_ellipse_model_estimate():
for angle in range(0, 180, 15):
rad = np.deg2rad(angle)
# generate original data without noise
model0 = EllipseModel()
model0.params = (10, 20... | 256 | 256 | 916 | 10 | 246 | portugueslab/scikit-image | skimage/measure/tests/test_fit.py | Python | test_ellipse_model_estimate_from_data | test_ellipse_model_estimate_from_data | 185 | 216 | 185 | 185 | 5358ef34d161ca5c1cc83194136266d48c851399 | bigcode/the-stack | train |
7eb766813a611bf93bbdd465 | train | function | def test_ellipse_model_estimate_failers():
# estimate parameters of real data
model = EllipseModel()
assert not model.estimate(np.ones((5, 2)))
assert not model.estimate(np.array([[50, 80], [51, 81], [52, 80]]))
| def test_ellipse_model_estimate_failers():
# estimate parameters of real data
| model = EllipseModel()
assert not model.estimate(np.ones((5, 2)))
assert not model.estimate(np.array([[50, 80], [51, 81], [52, 80]]))
| ()
model.estimate(data)
# test whether estimated parameters are smaller then 1000, so means stable
assert_array_less(np.abs(model.params[:4]), np.array([2e3] * 4))
def test_ellipse_model_estimate_failers():
# estimate parameters of real data
| 64 | 64 | 66 | 18 | 46 | portugueslab/scikit-image | skimage/measure/tests/test_fit.py | Python | test_ellipse_model_estimate_failers | test_ellipse_model_estimate_failers | 219 | 223 | 219 | 220 | d1e2af2e3e4625ef593d2db3ef15150a5a4f2fe4 | bigcode/the-stack | train |
fab23e9e42480ca6bb44085b | train | function | def test_ransac_dynamic_max_trials():
# Numbers hand-calculated and confirmed on page 119 (Table 4.3) in
# Hartley, R.~I. and Zisserman, A., 2004,
# Multiple View Geometry in Computer Vision, Second Edition,
# Cambridge University Press, ISBN: 0521540518
# e = 0%, min_samples = X
assert_e... | def test_ransac_dynamic_max_trials():
# Numbers hand-calculated and confirmed on page 119 (Table 4.3) in
# Hartley, R.~I. and Zisserman, A., 2004,
# Multiple View Geometry in Computer Vision, Second Edition,
# Cambridge University Press, ISBN: 0521540518
# e = 0%, min_samples = X
| assert_equal(_dynamic_max_trials(100, 100, 2, 0.99), 1)
# e = 5%, min_samples = 2
assert_equal(_dynamic_max_trials(95, 100, 2, 0.99), 2)
# e = 10%, min_samples = 2
assert_equal(_dynamic_max_trials(90, 100, 2, 0.99), 3)
# e = 30%, min_samples = 2
assert_equal(_dynamic_max_trials(70, 100, 2, ... | ransac(np.empty((10, 2)), LineModelND, 2, np.inf,
is_model_valid=is_model_valid, random_state=1)
assert_equal(model, None)
assert_equal(inliers, None)
def test_ransac_dynamic_max_trials():
# Numbers hand-calculated and confirmed on page 119 (Table 4.3) in
# Hartley, R.~I. ... | 140 | 140 | 469 | 91 | 49 | portugueslab/scikit-image | skimage/measure/tests/test_fit.py | Python | test_ransac_dynamic_max_trials | test_ransac_dynamic_max_trials | 300 | 329 | 300 | 306 | 88f237988ecf983bdcf0b9f9a29207c4d85e4407 | bigcode/the-stack | train |
9b11b12771dfe1d08542fbd6 | train | function | def test_circle_model_invalid_input():
with testing.raises(ValueError):
CircleModel().estimate(np.empty((5, 3)))
| def test_circle_model_invalid_input():
| with testing.raises(ValueError):
CircleModel().estimate(np.empty((5, 3)))
| assert_equal(abs(model.residuals(np.array([[10, 0, 0]]))), 10)
def test_line_modelND_under_determined():
data = np.empty((1, 3))
with testing.raises(ValueError):
LineModelND().estimate(data)
def test_circle_model_invalid_input():
| 64 | 64 | 27 | 7 | 57 | portugueslab/scikit-image | skimage/measure/tests/test_fit.py | Python | test_circle_model_invalid_input | test_circle_model_invalid_input | 105 | 107 | 105 | 105 | b1ba3dfda06f913066a7cbee8b1394a211d27898 | bigcode/the-stack | train |
8206d337333f61eeed62b545 | train | function | def test_ellipse_model_invalid_input():
with testing.raises(ValueError):
EllipseModel().estimate(np.empty((5, 3)))
| def test_ellipse_model_invalid_input():
| with testing.raises(ValueError):
EllipseModel().estimate(np.empty((5, 3)))
| assert_almost_equal(abs(model.residuals(np.array([[6, 6]]))),
np.sqrt(2 * 6**2) - 5)
assert_almost_equal(abs(model.residuals(np.array([[10, 0]]))), 5)
def test_ellipse_model_invalid_input():
| 64 | 64 | 29 | 8 | 56 | portugueslab/scikit-image | skimage/measure/tests/test_fit.py | Python | test_ellipse_model_invalid_input | test_ellipse_model_invalid_input | 148 | 150 | 148 | 148 | ed11f57f7d8d033c4952f668022cf19b669a6f36 | bigcode/the-stack | train |
bd099e552468fda1b9f9008e | train | function | def test_ellipse_model_estimate():
for angle in range(0, 180, 15):
rad = np.deg2rad(angle)
# generate original data without noise
model0 = EllipseModel()
model0.params = (10, 20, 15, 25, rad)
t = np.linspace(0, 2 * np.pi, 100)
data0 = model0.predict_xy(t)
# a... | def test_ellipse_model_estimate():
| for angle in range(0, 180, 15):
rad = np.deg2rad(angle)
# generate original data without noise
model0 = EllipseModel()
model0.params = (10, 20, 15, 25, rad)
t = np.linspace(0, 2 * np.pi, 100)
data0 = model0.predict_xy(t)
# add gaussian noise to data
r... | 0, 2 * np.pi, np.pi / 2)
xy = np.array(((5, 0), (0, 10), (-5, 0), (0, -10)))
assert_almost_equal(xy, model.predict_xy(t))
def test_ellipse_model_estimate():
| 64 | 64 | 204 | 8 | 56 | portugueslab/scikit-image | skimage/measure/tests/test_fit.py | Python | test_ellipse_model_estimate | test_ellipse_model_estimate | 162 | 182 | 162 | 162 | df3d92cd7e8a031d08da2cd1c29722fddce448fa | bigcode/the-stack | train |
fe160db8ea56773805971666 | train | function | def test_line_model_nd_invalid_input():
with testing.raises(AssertionError):
LineModelND().predict_x(np.zeros(1))
with testing.raises(AssertionError):
LineModelND().predict_y(np.zeros(1))
with testing.raises(ValueError):
LineModelND().predict_x(np.zeros(1), np.zeros(1))
with t... | def test_line_model_nd_invalid_input():
| with testing.raises(AssertionError):
LineModelND().predict_x(np.zeros(1))
with testing.raises(AssertionError):
LineModelND().predict_y(np.zeros(1))
with testing.raises(ValueError):
LineModelND().predict_x(np.zeros(1), np.zeros(1))
with testing.raises(AssertionError):
L... | _predict():
model = LineModelND()
model.params = ((0, 0), (1, 1))
x = np.arange(-10, 10)
y = model.predict_y(x)
assert_almost_equal(x, model.predict_x(y))
def test_line_model_nd_invalid_input():
| 64 | 64 | 187 | 8 | 56 | portugueslab/scikit-image | skimage/measure/tests/test_fit.py | Python | test_line_model_nd_invalid_input | test_line_model_nd_invalid_input | 24 | 48 | 24 | 24 | ce496ff089f29016b65b1eca88025eeb164977fe | bigcode/the-stack | train |
4f56c611f8062731100aac0c | train | function | def test_line_model_nd_estimate():
# generate original data without noise
model0 = LineModelND()
model0.params = (np.array([0, 0, 0], dtype='float'),
np.array([1, 1, 1], dtype='float')/np.sqrt(3))
# we scale the unit vector with a factor 10 when generating points on the
# line i... | def test_line_model_nd_estimate():
# generate original data without noise
| model0 = LineModelND()
model0.params = (np.array([0, 0, 0], dtype='float'),
np.array([1, 1, 1], dtype='float')/np.sqrt(3))
# we scale the unit vector with a factor 10 when generating points on the
# line in order to compensate for the scale of the random noise
data0 = (model0.pa... | 1, 2))
with testing.raises(ValueError):
LineModelND().estimate(data)
def test_line_model_nd_predict():
model = LineModelND()
model.params = (np.array([0, 0]), np.array([0.2, 0.8]))
x = np.arange(-10, 10)
y = model.predict_y(x)
assert_almost_equal(x, model.predict_x(y))
def test_line_mo... | 106 | 106 | 355 | 16 | 90 | portugueslab/scikit-image | skimage/measure/tests/test_fit.py | Python | test_line_model_nd_estimate | test_line_model_nd_estimate | 59 | 88 | 59 | 60 | 7afbae51c85f6f684e7e7925baa78b3d7d7b5cde | bigcode/the-stack | train |
09e670befdb23bb5ff794ce6 | train | function | def test_circle_model_estimate():
# generate original data without noise
model0 = CircleModel()
model0.params = (10, 12, 3)
t = np.linspace(0, 2 * np.pi, 1000)
data0 = model0.predict_xy(t)
# add gaussian noise to data
random_state = np.random.RandomState(1234)
data = data0 + random_stat... | def test_circle_model_estimate():
# generate original data without noise
| model0 = CircleModel()
model0.params = (10, 12, 3)
t = np.linspace(0, 2 * np.pi, 1000)
data0 = model0.predict_xy(t)
# add gaussian noise to data
random_state = np.random.RandomState(1234)
data = data0 + random_state.normal(size=data0.shape)
# estimate parameters of noisy data
model... | , np.pi / 2)
xy = np.array(((5, 0), (0, 5), (-5, 0), (0, -5)))
assert_almost_equal(xy, model.predict_xy(t))
def test_circle_model_estimate():
# generate original data without noise
| 64 | 64 | 147 | 15 | 49 | portugueslab/scikit-image | skimage/measure/tests/test_fit.py | Python | test_circle_model_estimate | test_circle_model_estimate | 120 | 136 | 120 | 121 | 53b26bb404c63660f3cf5e11761c4109e7d39c3f | bigcode/the-stack | train |
7c2cb8450e802788d79806ec | train | function | def test_line_modelND_under_determined():
data = np.empty((1, 3))
with testing.raises(ValueError):
LineModelND().estimate(data)
| def test_line_modelND_under_determined():
| data = np.empty((1, 3))
with testing.raises(ValueError):
LineModelND().estimate(data)
| 0, 0]]))), 0)
assert_equal(abs(model.residuals(np.array([[0, 0, 1]]))), 0)
assert_equal(abs(model.residuals(np.array([[10, 0, 0]]))), 10)
def test_line_modelND_under_determined():
| 64 | 64 | 35 | 9 | 55 | portugueslab/scikit-image | skimage/measure/tests/test_fit.py | Python | test_line_modelND_under_determined | test_line_modelND_under_determined | 99 | 102 | 99 | 99 | ef9e35b8fa95c10d60a9ba92e22692e1c0948787 | bigcode/the-stack | train |
5e1369b45a77ab34c1ca3165 | train | function | def test_ellipse_model_residuals():
model = EllipseModel()
# vertical line through origin
model.params = (0, 0, 10, 5, 0)
assert_almost_equal(abs(model.residuals(np.array([[10, 0]]))), 0)
assert_almost_equal(abs(model.residuals(np.array([[0, 5]]))), 0)
assert_almost_equal(abs(model.residuals(np.... | def test_ellipse_model_residuals():
| model = EllipseModel()
# vertical line through origin
model.params = (0, 0, 10, 5, 0)
assert_almost_equal(abs(model.residuals(np.array([[10, 0]]))), 0)
assert_almost_equal(abs(model.residuals(np.array([[0, 5]]))), 0)
assert_almost_equal(abs(model.residuals(np.array([[0, 10]]))), 5)
| # estimate parameters of real data
model = EllipseModel()
assert not model.estimate(np.ones((5, 2)))
assert not model.estimate(np.array([[50, 80], [51, 81], [52, 80]]))
def test_ellipse_model_residuals():
| 64 | 64 | 108 | 9 | 55 | portugueslab/scikit-image | skimage/measure/tests/test_fit.py | Python | test_ellipse_model_residuals | test_ellipse_model_residuals | 226 | 232 | 226 | 226 | fab04d67b82c53d983d878a5e6d75806f64d5c42 | bigcode/the-stack | train |
7c4d2a43142616260a9b44cf | train | function | def test_ransac_invalid_input():
with testing.raises(ValueError):
ransac(np.zeros((10, 2)), None, min_samples=2,
residual_threshold=0, max_trials=-1)
with testing.raises(ValueError):
ransac(np.zeros((10, 2)), None, min_samples=2,
residual_threshold=0, stop_probabili... | def test_ransac_invalid_input():
| with testing.raises(ValueError):
ransac(np.zeros((10, 2)), None, min_samples=2,
residual_threshold=0, max_trials=-1)
with testing.raises(ValueError):
ransac(np.zeros((10, 2)), None, min_samples=2,
residual_threshold=0, stop_probability=-1)
with testing.raises(Va... | # e = 0%, min_samples = 5
assert_equal(_dynamic_max_trials(1, 100, 5, 0), 0)
assert_equal(_dynamic_max_trials(1, 100, 5, 1), np.inf)
def test_ransac_invalid_input():
| 64 | 64 | 121 | 8 | 56 | portugueslab/scikit-image | skimage/measure/tests/test_fit.py | Python | test_ransac_invalid_input | test_ransac_invalid_input | 332 | 341 | 332 | 332 | 6ef9959c6393be92f27720a463f9fd084ba251be | bigcode/the-stack | train |
52729b9f65a9405f28a9a2ff | train | function | def test_ellipse_model_predict():
model = EllipseModel()
model.params = (0, 0, 5, 10, 0)
t = np.arange(0, 2 * np.pi, np.pi / 2)
xy = np.array(((5, 0), (0, 10), (-5, 0), (0, -10)))
assert_almost_equal(xy, model.predict_xy(t))
| def test_ellipse_model_predict():
| model = EllipseModel()
model.params = (0, 0, 5, 10, 0)
t = np.arange(0, 2 * np.pi, np.pi / 2)
xy = np.array(((5, 0), (0, 10), (-5, 0), (0, -10)))
assert_almost_equal(xy, model.predict_xy(t))
| ) - 5)
assert_almost_equal(abs(model.residuals(np.array([[10, 0]]))), 5)
def test_ellipse_model_invalid_input():
with testing.raises(ValueError):
EllipseModel().estimate(np.empty((5, 3)))
def test_ellipse_model_predict():
| 63 | 64 | 95 | 7 | 56 | portugueslab/scikit-image | skimage/measure/tests/test_fit.py | Python | test_ellipse_model_predict | test_ellipse_model_predict | 153 | 159 | 153 | 153 | bba5fe4a794df0b11f6f4c49fe2250dbe2d1d2f9 | bigcode/the-stack | train |
a44dd4636c4d20ff8767feb3 | train | class | class CreateTest(Resource):
def __init__(self):
self.parser = reqparse.RequestParser()
self.parser.add_argument('test_id',type=str,required=True,help="This field cannot be left blank.")
self.parser.add_argument('test_details',type=dict,required=True,help="This field cannot be left blank.")
... | class CreateTest(Resource):
| def __init__(self):
self.parser = reqparse.RequestParser()
self.parser.add_argument('test_id',type=str,required=True,help="This field cannot be left blank.")
self.parser.add_argument('test_details',type=dict,required=True,help="This field cannot be left blank.")
def post(self):... | _for, make_response
from flask_restful import Resource, Api, reqparse
import os
from werkzeug.utils import secure_filename
from test_functions import testFunction
app = Flask(__name__)
api= Api(app)
testFunc = testFunction()
testFunc.connect2DB()
class CreateTest(Resource):
| 64 | 64 | 139 | 5 | 59 | hrimG/Nerds-of-a-feather-TM | src/TestServer/server.py | Python | CreateTest | CreateTest | 12 | 27 | 12 | 12 | 86631b21c33241c982505f9eff500aead4d4b9e9 | bigcode/the-stack | train |
50b6a4111efcacf0e0498afe | train | class | class GetAllTest(Resource):
def __init__(self):
self.parser = reqparse.RequestParser()
pass
def post(self):
print("get Test Called")
headers: {"Accept": "application/json","Content-type": "application/json",}
result = testFunc.getAllTest()
return result
| class GetAllTest(Resource):
| def __init__(self):
self.parser = reqparse.RequestParser()
pass
def post(self):
print("get Test Called")
headers: {"Accept": "application/json","Content-type": "application/json",}
result = testFunc.getAllTest()
return result
| def post(self):
print("get Test Called")
headers: {"Accept": "application/json","Content-type": "application/json",}
response = self.parser.parse_args()
print(response)
result = testFunc.getTest(response['test_id'])
return result
class GetAllTest(Resource):
| 64 | 64 | 68 | 6 | 57 | hrimG/Nerds-of-a-feather-TM | src/TestServer/server.py | Python | GetAllTest | GetAllTest | 43 | 53 | 43 | 43 | e0c7bc076e78bc4d0a98a8db815d973eef1b20fb | bigcode/the-stack | train |
4a6492b287d5f2ad3b8a3e7d | train | class | class GetTest(Resource):
def __init__(self):
self.parser = reqparse.RequestParser()
self.parser.add_argument('test_id',type=str,required=True,help="This field cannot be left blank.")
def post(self):
print("get Test Called")
headers: {"Accept": "application/json","Content-type": ... | class GetTest(Resource):
| def __init__(self):
self.parser = reqparse.RequestParser()
self.parser.add_argument('test_id',type=str,required=True,help="This field cannot be left blank.")
def post(self):
print("get Test Called")
headers: {"Accept": "application/json","Content-type": "application/json",}
... | ")
headers: {"Accept": "application/json","Content-type": "application/json",}
response = self.parser.parse_args()
print(response)
result = testFunc.createTest(response['test_id'],
response['test_details'])
return jsonify({'testCreation':'Success'})
c... | 63 | 64 | 103 | 5 | 58 | hrimG/Nerds-of-a-feather-TM | src/TestServer/server.py | Python | GetTest | GetTest | 29 | 41 | 29 | 29 | 88db761a58a9e16fe8ad4f775b1b05bfd3e73eed | bigcode/the-stack | train |
ee364df84303f4dae66c5fed | train | function | def _do_setup(name='dagit'):
ver = get_version(name)
setup(
name=name,
version=ver,
author='Elementl',
license='Apache-2.0',
description='Web UI for dagster.',
long_description=long_description(),
long_description_content_type='text/markdown',
url=... | def _do_setup(name='dagit'):
| ver = get_version(name)
setup(
name=name,
version=ver,
author='Elementl',
license='Apache-2.0',
description='Web UI for dagster.',
long_description=long_description(),
long_description_content_type='text/markdown',
url='https://github.com/dagster-i... | import find_packages, setup
def long_description():
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.rst'), 'r') as fh:
return fh.read()
def get_version(name):
version = {}
with open('dagit/version.py') as fp:
exec(fp.read(), version) # pylint:... | 170 | 170 | 569 | 9 | 161 | jake-billings/dagster | python_modules/dagit/setup.py | Python | _do_setup | _do_setup | 31 | 82 | 31 | 31 | 8c543c41ba3577bd22556940bd2bd6eb7ba32ed9 | bigcode/the-stack | train |
de9bee59904784af7fb3ba43 | train | function | def long_description():
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.rst'), 'r') as fh:
return fh.read()
| def long_description():
| here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.rst'), 'r') as fh:
return fh.read()
| import argparse
import sys
import os
from setuptools import find_packages, setup
def long_description():
| 21 | 64 | 41 | 4 | 16 | jake-billings/dagster | python_modules/dagit/setup.py | Python | long_description | long_description | 8 | 11 | 8 | 8 | a7267c230ea865513e81c52c096171328f3cf327 | bigcode/the-stack | train |
bf4670a19ef1003f5f84dc77 | train | function | def get_version(name):
version = {}
with open('dagit/version.py') as fp:
exec(fp.read(), version) # pylint: disable=W0122
if name == 'dagit':
return version['__version__']
elif name == 'dagit-nightly':
return version['__nightly__']
else:
raise Exception('Shouldn\'t ... | def get_version(name):
| version = {}
with open('dagit/version.py') as fp:
exec(fp.read(), version) # pylint: disable=W0122
if name == 'dagit':
return version['__version__']
elif name == 'dagit-nightly':
return version['__nightly__']
else:
raise Exception('Shouldn\'t be here: bad package na... | import argparse
import sys
import os
from setuptools import find_packages, setup
def long_description():
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.rst'), 'r') as fh:
return fh.read()
def get_version(name):
| 63 | 64 | 96 | 5 | 58 | jake-billings/dagster | python_modules/dagit/setup.py | Python | get_version | get_version | 14 | 24 | 14 | 14 | bb6238d4cbfdf27177e0a8955b37d438f23c5d74 | bigcode/the-stack | train |
1def4f72bb804b3204145d28 | train | class | class Solution(object):
def splitBST(self, root, V):
"""
:type root: TreeNode
:type V: int
:rtype: List[TreeNode]
"""
if not root:
return None, None
elif root.val <= V:
bns = self.splitBST(root.right, V)
root.right = bns[0]
... | class Solution(object):
| def splitBST(self, root, V):
"""
:type root: TreeNode
:type V: int
:rtype: List[TreeNode]
"""
if not root:
return None, None
elif root.val <= V:
bns = self.splitBST(root.right, V)
root.right = bns[0]
return root,... | valid and each node's value is different.
#
import unittest
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# 20ms 100%
class Solution(object):
| 64 | 64 | 123 | 4 | 60 | JulyKikuAkita/PythonPrac | cs15211/SplitBST.py | Python | Solution | Solution | 57 | 73 | 57 | 57 | 27fe45aba13d20222ba595eb4ea98b5d0fff3fd8 | bigcode/the-stack | train |
1437bc5ed670bf3245fe372d | train | class | class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
| class TreeNode(object):
| def __init__(self, x):
self.val = x
self.left = None
self.right = None
| # / \ /
# 5 7 1
# Note:
#
# The size of the BST will not exceed 50.
# The BST is always valid and each node's value is different.
#
import unittest
# Definition for a binary tree node.
class TreeNode(object):
| 64 | 64 | 32 | 5 | 59 | JulyKikuAkita/PythonPrac | cs15211/SplitBST.py | Python | TreeNode | TreeNode | 50 | 54 | 50 | 50 | d882cebc8045768f552161c618ba908ede3b6db2 | bigcode/the-stack | train |
f1c0f3deb549c2c957ed382c | train | class | class TestMethods(unittest.TestCase):
def test_Local(self):
self.assertEqual(1, 1)
| class TestMethods(unittest.TestCase):
| def test_Local(self):
self.assertEqual(1, 1)
| BST(root.right, V)
root.right = bns[0]
return root, bns[1]
else:
bns = self.splitBST(root.left, V)
root.left = bns[1]
return bns[0], root
class TestMethods(unittest.TestCase):
| 64 | 64 | 23 | 7 | 56 | JulyKikuAkita/PythonPrac | cs15211/SplitBST.py | Python | TestMethods | TestMethods | 75 | 77 | 75 | 75 | 6b1fe9c6e828796aec1648920d3a13c200ac4ee9 | bigcode/the-stack | train |
14479780e5e29f236f8b6404 | train | function | def _create_pipeline(pipeline_name: Text, pipeline_root: Text, data_root: Text,
module_file: Text, serving_model_dir: Text,
metadata_path: Text, enable_tuning: bool,
beam_pipeline_args: List[Text]) -> pipeline.Pipeline:
"""Implements the Iris flowers pipe... | def _create_pipeline(pipeline_name: Text, pipeline_root: Text, data_root: Text,
module_file: Text, serving_model_dir: Text,
metadata_path: Text, enable_tuning: bool,
beam_pipeline_args: List[Text]) -> pipeline.Pipeline:
| """Implements the Iris flowers pipeline with TFX."""
examples = external_input(data_root)
# Brings data into the pipeline or otherwise joins/converts training data.
example_gen = CsvExampleGen(input=examples)
# Computes statistics over data for visualization and example validation.
statistics_gen = Statis... | server. Pusher will output the
# trained model here.
_serving_model_dir = os.path.join(_iris_root, 'serving_model', _pipeline_name)
# Directory and data locations. This example assumes all of the flowers
# example code and metadata library is relative to $HOME, but you can store
# these files anywhere on your local... | 256 | 256 | 1,126 | 58 | 198 | epona-science/tfx | tfx/examples/iris/iris_pipeline_native_keras.py | Python | _create_pipeline | _create_pipeline | 80 | 208 | 80 | 83 | d0dd67e2c34387754624e52088a1004bc37d55b5 | bigcode/the-stack | train |
3253e265233f86b632e4478b | train | class | class OutputGeneratorGraphics:
""" Implemented to avoid having a `god object` controlling all output. It also allows us to decouple the logic
used to generate the graphics from the logic used to save the data tables.
This class is designed to be used in parts rather than as a whole so that any workflow (suck as t... | class OutputGeneratorGraphics:
| """ Implemented to avoid having a `god object` controlling all output. It also allows us to decouple the logic
used to generate the graphics from the logic used to save the data tables.
This class is designed to be used in parts rather than as a whole so that any workflow (suck as the `ggmuller` workflow)
can u... | from pathlib import Path
from typing import Dict, List, Optional
import pandas
from muller import graphics
from muller.graphics import Palette
# The filenames should be mapped to their corresponding palette.
# The dictionary maps palette names to the filenames that should be generated.
GraphicPath = Dict[str, List[P... | 70 | 190 | 636 | 5 | 65 | andreashirley/Lolipop | muller/graphics/graphicsio.py | Python | OutputGeneratorGraphics | OutputGeneratorGraphics | 14 | 80 | 14 | 14 | ddfe858af16cc265c274b65eaf449b64897c4b64 | bigcode/the-stack | train |
f4d59b2d991b77b82c7f3034 | train | function | def merge_logging(base, override):
md = MergeDict(base, override)
md.merge_scalar('driver')
if md.get('driver') == base.get('driver') or base.get('driver') is None:
md.merge_mapping('options', lambda m: m or {})
elif override.get('options'):
md['options'] = override.get('options', {})
... | def merge_logging(base, override):
| md = MergeDict(base, override)
md.merge_scalar('driver')
if md.get('driver') == base.get('driver') or base.get('driver') is None:
md.merge_mapping('options', lambda m: m or {})
elif override.get('options'):
md['options'] = override.get('options', {})
return dict(md)
| for field in [
"device_read_bps", "device_read_iops", "device_write_bps",
"device_write_iops", "weight_device",
]:
md.merge_field(field, merge_blkio_limits, default=[])
return dict(md)
def merge_logging(base, override):
| 64 | 64 | 82 | 7 | 57 | jovobe/compose | compose/config/config.py | Python | merge_logging | merge_logging | 1,193 | 1,200 | 1,193 | 1,193 | 8bc0dc92a0c5bb589bdd6687f03294242a6b7e67 | bigcode/the-stack | train |
f7bf089a4156b3a0a9b835c2 | train | function | def process_depends_on(service_dict):
if 'depends_on' in service_dict and not isinstance(service_dict['depends_on'], dict):
service_dict['depends_on'] = dict([
(svc, {'condition': 'service_started'}) for svc in service_dict['depends_on']
])
return service_dict
| def process_depends_on(service_dict):
| if 'depends_on' in service_dict and not isinstance(service_dict['depends_on'], dict):
service_dict['depends_on'] = dict([
(svc, {'condition': 'service_started'}) for svc in service_dict['depends_on']
])
return service_dict
|
ports = []
for port_definition in service_dict['ports']:
if isinstance(port_definition, ServicePort):
ports.append(port_definition)
else:
ports.extend(ServicePort.parse(port_definition))
service_dict['ports'] = ports
return service_dict
def process_depends_on(se... | 64 | 64 | 65 | 8 | 55 | jovobe/compose | compose/config/config.py | Python | process_depends_on | process_depends_on | 776 | 781 | 776 | 776 | ad093fb93be2b47d727bc6a83f91c61a375ffa03 | bigcode/the-stack | train |
1889adf2ecf58160ccf33869 | train | function | def expand_path(working_dir, path):
return os.path.abspath(os.path.join(working_dir, os.path.expanduser(path)))
| def expand_path(working_dir, path):
| return os.path.abspath(os.path.join(working_dir, os.path.expanduser(path)))
| isinstance(host, dict):
return host
elif host is None:
return container
else:
host, mode = host
result = ":".join((host, container))
if mode:
result += ":" + mode
return result
def expand_path(working_dir, path):
| 64 | 64 | 27 | 9 | 54 | jovobe/compose | compose/config/config.py | Python | expand_path | expand_path | 1,423 | 1,424 | 1,423 | 1,423 | 3fc7921e6f6ae5a104b1647c5a9198181fd9f8cf | bigcode/the-stack | train |
41a2a6a69e5266d65d80fe9d | train | function | def merge_service_dicts_from_files(base, override, version):
"""When merging services from multiple files we need to merge the `extends`
field. This is not handled by `merge_service_dicts()` which is used to
perform the `extends`.
"""
new_service = merge_service_dicts(base, override, version)
if... | def merge_service_dicts_from_files(base, override, version):
| """When merging services from multiple files we need to merge the `extends`
field. This is not handled by `merge_service_dicts()` which is used to
perform the `extends`.
"""
new_service = merge_service_dicts(base, override, version)
if 'extends' in override:
new_service['extends'] = over... | if 'dockerfile' in service_dict:
service_dict['build'] = service_dict.get('build', {})
service_dict['build'].update({
'dockerfile': service_dict.pop('dockerfile')
})
return service_dict
def merge_service_dicts_from_files(base, override, version):
| 64 | 64 | 113 | 13 | 50 | jovobe/compose | compose/config/config.py | Python | merge_service_dicts_from_files | merge_service_dicts_from_files | 978 | 988 | 978 | 978 | f9dbdb35000e76df620a32db3d002ad2f368fd30 | bigcode/the-stack | train |
5c20560a9b2d33774e545d5c | train | function | def resolve_build_path(working_dir, build_path):
if is_url(build_path):
return build_path
return expand_path(working_dir, build_path)
| def resolve_build_path(working_dir, build_path):
| if is_url(build_path):
return build_path
return expand_path(working_dir, build_path)
| build')
else:
build.update(service_dict['build'])
if 'args' in build:
build['args'] = build_string_dict(
resolve_build_args(build.get('args'), environment)
)
service_dict['build'] = build
def resolve_build_path(working_dir, bui... | 64 | 64 | 34 | 11 | 52 | jovobe/compose | compose/config/config.py | Python | resolve_build_path | resolve_build_path | 1,329 | 1,332 | 1,329 | 1,329 | c25688342f564b9ba81a1e045a02544fd42b46d4 | bigcode/the-stack | train |
3228cb99a60b54e5e0837cd0 | train | function | def validate_paths(service_dict):
if 'build' in service_dict:
build = service_dict.get('build', {})
if isinstance(build, six.string_types):
build_path = build
elif isinstance(build, dict) and 'context' in build:
build_path = build['context']
else:
... | def validate_paths(service_dict):
| if 'build' in service_dict:
build = service_dict.get('build', {})
if isinstance(build, six.string_types):
build_path = build
elif isinstance(build, dict) and 'context' in build:
build_path = build['context']
else:
# We have a build section but no ... | build'] = build
def resolve_build_path(working_dir, build_path):
if is_url(build_path):
return build_path
return expand_path(working_dir, build_path)
def is_url(build_path):
return build_path.startswith(DOCKER_VALID_URL_PREFIXES)
def validate_paths(service_dict):
| 64 | 64 | 153 | 6 | 58 | jovobe/compose | compose/config/config.py | Python | validate_paths | validate_paths | 1,339 | 1,357 | 1,339 | 1,339 | 76ce40b67d3807dcb7c727c0cd9c688e435caa9f | bigcode/the-stack | train |
1e14cd02ce42043550ba7dfd | train | function | def translate_resource_keys_to_container_config(resources_dict, service_dict):
if 'limits' in resources_dict:
service_dict['mem_limit'] = resources_dict['limits'].get('memory')
if 'cpus' in resources_dict['limits']:
service_dict['cpus'] = float(resources_dict['limits']['cpus'])
if 'r... | def translate_resource_keys_to_container_config(resources_dict, service_dict):
| if 'limits' in resources_dict:
service_dict['mem_limit'] = resources_dict['limits'].get('memory')
if 'cpus' in resources_dict['limits']:
service_dict['cpus'] = float(resources_dict['limits']['cpus'])
if 'reservations' in resources_dict:
service_dict['mem_reservation'] = resou... | following deploy sub-keys are not supported in compatibility mode and have'
' been ignored: {}'.format(', '.join(ignored_keys))
)
service_dict['name'] = service_config.name
return normalize_v1_service_format(service_dict)
def translate_resource_keys_to_container_config(resources_di... | 64 | 64 | 123 | 13 | 51 | jovobe/compose | compose/config/config.py | Python | translate_resource_keys_to_container_config | translate_resource_keys_to_container_config | 897 | 906 | 897 | 897 | d92695c0a7fafd0393067cd9bc0de10d076ad056 | bigcode/the-stack | train |
1ad0a1c19b6e2497d3dd1fdb | train | function | def merge_service_dicts(base, override, version):
md = MergeDict(base, override)
md.merge_mapping('environment', parse_environment)
md.merge_mapping('labels', parse_labels)
md.merge_mapping('ulimits', parse_flat_dict)
md.merge_mapping('networks', parse_networks)
md.merge_mapping('sysctls', pars... | def merge_service_dicts(base, override, version):
| md = MergeDict(base, override)
md.merge_mapping('environment', parse_environment)
md.merge_mapping('labels', parse_labels)
md.merge_mapping('ulimits', parse_flat_dict)
md.merge_mapping('networks', parse_networks)
md.merge_mapping('sysctls', parse_sysctls)
md.merge_mapping('depends_on', pars... | _func):
def parse_sequence_func(seq):
return to_mapping((parse_func(item) for item in seq), 'merge_field')
if not self.needs_merge(field):
return
merged = parse_sequence_func(self.base.get(field, []))
merged.update(parse_sequence_func(self.override.get(field, []... | 126 | 126 | 423 | 11 | 115 | jovobe/compose | compose/config/config.py | Python | merge_service_dicts | merge_service_dicts | 1,036 | 1,082 | 1,036 | 1,036 | 86c8088353327758f1d0da8139fed7dab98c5c14 | bigcode/the-stack | train |
83e54d7cfc5f0104018006f2 | train | function | def resolve_volume_paths(working_dir, service_dict):
return [
resolve_volume_path(working_dir, volume)
for volume in service_dict['volumes']
]
| def resolve_volume_paths(working_dir, service_dict):
| return [
resolve_volume_path(working_dir, volume)
for volume in service_dict['volumes']
]
| Invalid type: expected mapping")
def resolve_env_var(key, val, environment):
if val is not None:
return key, val
elif environment and key in environment:
return key, environment[key]
else:
return key, None
def resolve_volume_paths(working_dir, service_dict):
| 64 | 64 | 36 | 11 | 52 | jovobe/compose | compose/config/config.py | Python | resolve_volume_paths | resolve_volume_paths | 1,284 | 1,288 | 1,284 | 1,284 | c309eb83c086e4079335b7b532af2511c1aa53d1 | bigcode/the-stack | train |
4928e3aa546ffb415ef894d4 | train | function | def load_mapping(config_files, get_func, entity_type, working_dir=None):
mapping = {}
for config_file in config_files:
for name, config in getattr(config_file, get_func)().items():
mapping[name] = config or {}
if not config:
continue
external = confi... | def load_mapping(config_files, get_func, entity_type, working_dir=None):
| mapping = {}
for config_file in config_files:
for name, config in getattr(config_file, get_func)().items():
mapping[name] = config or {}
if not config:
continue
external = config.get('external')
if external:
validate_exter... | _only_config(service_dicts, compatibility)
version = V2_3 if compatibility and main_file.version >= V3_0 else main_file.version
return Config(version, service_dicts, volumes, networks, secrets, configs)
def load_mapping(config_files, get_func, entity_type, working_dir=None):
| 64 | 64 | 197 | 16 | 48 | jovobe/compose | compose/config/config.py | Python | load_mapping | load_mapping | 415 | 443 | 415 | 415 | 080acc04a02f8f89a664fcf3f2420908fc59288a | bigcode/the-stack | train |
f96598752763e9ea14ff429f | train | class | class ConfigFile(namedtuple('_ConfigFile', 'filename config')):
"""
:param filename: filename of the config file
:type filename: string
:param config: contents of the config file
:type config: :class:`dict`
"""
@classmethod
def from_filename(cls, filename):
return cls(filename... | class ConfigFile(namedtuple('_ConfigFile', 'filename config')):
| """
:param filename: filename of the config file
:type filename: string
:param config: contents of the config file
:type config: :class:`dict`
"""
@classmethod
def from_filename(cls, filename):
return cls(filename, load_yaml(filename))
@cached_property
def version(sel... | :type working_dir: string
:param config_files: list of configuration files to load
:type config_files: list of :class:`ConfigFile`
:param environment: computed environment values for this project
:type environment: :class:`environment.Environment`
"""
def __new__(cls, working_dir, config... | 132 | 132 | 440 | 13 | 119 | jovobe/compose | compose/config/config.py | Python | ConfigFile | ConfigFile | 178 | 238 | 178 | 178 | 4826891d8748984f082af0dcd4d189cc440f2cf3 | bigcode/the-stack | train |
a8229d68f68752bc2ec386a0 | train | class | class ConfigDetails(namedtuple('_ConfigDetails', 'working_dir config_files environment')):
"""
:param working_dir: the directory to use for relative paths in the config
:type working_dir: string
:param config_files: list of configuration files to load
:type config_files: list of :class:`ConfigFile... | class ConfigDetails(namedtuple('_ConfigDetails', 'working_dir config_files environment')):
| """
:param working_dir: the directory to use for relative paths in the config
:type working_dir: string
:param config_files: list of configuration files to load
:type config_files: list of :class:`ConfigFile`
:param environment: computed environment values for this project
:type environme... | @',
)
SUPPORTED_FILENAMES = [
'docker-compose.yml',
'docker-compose.yaml',
]
DEFAULT_OVERRIDE_FILENAMES = ('docker-compose.override.yml', 'docker-compose.override.yaml')
log = logging.getLogger(__name__)
class ConfigDetails(namedtuple('_ConfigDetails', 'working_dir config_files environment')):
| 64 | 64 | 154 | 16 | 48 | jovobe/compose | compose/config/config.py | Python | ConfigDetails | ConfigDetails | 161 | 175 | 161 | 161 | 689f3ad6977fe4a758e71a424062abe4d5769077 | bigcode/the-stack | train |
35447e04db0e24bb2f0e2443 | train | function | def merge_healthchecks(base, override):
if override.get('disabled') is True:
return override
result = base.copy()
result.update(override)
return result
| def merge_healthchecks(base, override):
| if override.get('disabled') is True:
return override
result = base.copy()
result.update(override)
return result
| merge_build(md, base, override)
return dict(md)
def merge_unique_items_lists(base, override):
override = [str(o) for o in override]
base = [str(b) for b in base]
return sorted(set().union(base, override))
def merge_healthchecks(base, override):
| 64 | 64 | 38 | 8 | 56 | jovobe/compose | compose/config/config.py | Python | merge_healthchecks | merge_healthchecks | 1,091 | 1,096 | 1,091 | 1,091 | 6f9011c5b3412d70bcc60ce6625ae130bd5fd201 | bigcode/the-stack | train |
95ee267accd3c3aa8ed2c320 | train | function | def validate_config_version(config_files):
main_file = config_files[0]
validate_top_level_object(main_file)
for next_file in config_files[1:]:
validate_top_level_object(next_file)
if main_file.version != next_file.version:
raise ConfigurationError(
"Version misma... | def validate_config_version(config_files):
| main_file = config_files[0]
validate_top_level_object(main_file)
for next_file in config_files[1:]:
validate_top_level_object(next_file)
if main_file.version != next_file.version:
raise ConfigurationError(
"Version mismatch: file {0} specifies version {1} but "
... | (base_dir)
log.debug("Using configuration files: {}".format(",".join(filenames)))
return ConfigDetails(
override_dir if override_dir else os.path.dirname(filenames[0]),
[ConfigFile.from_filename(f) for f in filenames],
environment
)
def validate_config_version(config_files):
| 64 | 64 | 108 | 7 | 57 | jovobe/compose | compose/config/config.py | Python | validate_config_version | validate_config_version | 293 | 306 | 293 | 293 | 08313020e6545a49b05378464b7eb15d84e7fc35 | bigcode/the-stack | train |
f8e09cd73725b64bea13ad64 | train | function | def is_url(build_path):
return build_path.startswith(DOCKER_VALID_URL_PREFIXES)
| def is_url(build_path):
| return build_path.startswith(DOCKER_VALID_URL_PREFIXES)
| _dict(
resolve_build_args(build.get('args'), environment)
)
service_dict['build'] = build
def resolve_build_path(working_dir, build_path):
if is_url(build_path):
return build_path
return expand_path(working_dir, build_path)
def is_url(build_path):
| 64 | 64 | 19 | 6 | 58 | jovobe/compose | compose/config/config.py | Python | is_url | is_url | 1,335 | 1,336 | 1,335 | 1,335 | 904d1c59717c4b4139dd1c9af89d9e7e96ee3d18 | bigcode/the-stack | train |
4e87ed93930e509df1170bc7 | train | function | def load_services(config_details, config_file, compatibility=False):
def build_service(service_name, service_dict, service_names):
service_config = ServiceConfig.with_abs_paths(
config_details.working_dir,
config_file.filename,
service_name,
service_dict)
... | def load_services(config_details, config_file, compatibility=False):
| def build_service(service_name, service_dict, service_names):
service_config = ServiceConfig.with_abs_paths(
config_details.working_dir,
config_file.filename,
service_name,
service_dict)
resolver = ServiceExtendsResolver(
service_config, co... | config, version):
if (version < V2_1 or (version >= V3_0 and version < V3_4)) and len(config.keys()) > 1:
raise ConfigurationError(
"{} {} declared as external but specifies additional attributes "
"({}).".format(
entity_type, name, ', '.join(k for k in config if k !... | 93 | 94 | 315 | 12 | 81 | jovobe/compose | compose/config/config.py | Python | load_services | load_services | 454 | 502 | 454 | 454 | ee73edca4016c0d66c196c784fb7a2cc65ad5744 | bigcode/the-stack | train |
83ad761c645f107541f2b9a9 | train | function | def resolve_build_args(buildargs, environment):
args = parse_build_arguments(buildargs)
return dict(resolve_env_var(k, v, environment) for k, v in six.iteritems(args))
| def resolve_build_args(buildargs, environment):
| args = parse_build_arguments(buildargs)
return dict(resolve_env_var(k, v, environment) for k, v in six.iteritems(args))
| for env_file in service_dict.get('env_file', []):
env.update(env_vars_from_file(env_file))
env.update(parse_environment(service_dict.get('environment')))
return dict(resolve_env_var(k, v, environment) for k, v in six.iteritems(env))
def resolve_build_args(buildargs, environment):
| 64 | 64 | 39 | 9 | 55 | jovobe/compose | compose/config/config.py | Python | resolve_build_args | resolve_build_args | 664 | 666 | 664 | 664 | 0b104f9df5b3208c68615d5daf4583a4d9d40513 | bigcode/the-stack | train |
16fc5163d0f1910c6c15b0da | train | function | def process_security_opt(service_dict):
security_opts = service_dict.get('security_opt', [])
result = []
for value in security_opts:
result.append(SecurityOpt.parse(value))
if result:
service_dict['security_opt'] = result
return service_dict
| def process_security_opt(service_dict):
| security_opts = service_dict.get('security_opt', [])
result = []
for value in security_opts:
result.append(SecurityOpt.parse(value))
if result:
service_dict['security_opt'] = result
return service_dict
| drive(container)
mode = None
if ':' in container_path:
container_path, mode = container_path.rsplit(':', 1)
return (container_drive + container_path, (drive + host, mode))
else:
return (volume_path, None)
def process_security_opt(service_dict):
| 64 | 64 | 57 | 7 | 57 | jovobe/compose | compose/config/config.py | Python | process_security_opt | process_security_opt | 1,399 | 1,406 | 1,399 | 1,399 | c1d3eadf871bbeb903a07b8d9b1f0b3c1f8e07b3 | bigcode/the-stack | train |
2c640132a7994da94de3ee69 | train | function | def merge_unique_items_lists(base, override):
override = [str(o) for o in override]
base = [str(b) for b in base]
return sorted(set().union(base, override))
| def merge_unique_items_lists(base, override):
| override = [str(o) for o in override]
base = [str(b) for b in base]
return sorted(set().union(base, override))
| md.merge_scalar(field)
if version == V1:
legacy_v1_merge_image_or_build(md, base, override)
elif md.needs_merge('build'):
md['build'] = merge_build(md, base, override)
return dict(md)
def merge_unique_items_lists(base, override):
| 64 | 64 | 43 | 9 | 55 | jovobe/compose | compose/config/config.py | Python | merge_unique_items_lists | merge_unique_items_lists | 1,085 | 1,088 | 1,085 | 1,085 | 14a814d4e25fa59306069978b055c23f3d4d8cdc | bigcode/the-stack | train |
38a23f971e73ea5f4d1709e5 | train | function | def finalize_service(service_config, service_names, version, environment, compatibility):
service_dict = dict(service_config.config)
if 'environment' in service_dict or 'env_file' in service_dict:
service_dict['environment'] = resolve_environment(service_dict, environment)
service_dict.pop('env... | def finalize_service(service_config, service_names, version, environment, compatibility):
| service_dict = dict(service_config.config)
if 'environment' in service_dict or 'env_file' in service_dict:
service_dict['environment'] = resolve_environment(service_dict, environment)
service_dict.pop('env_file', None)
if 'volumes_from' in service_dict:
service_dict['volumes_from']... | volumes' in service_dict:
finalized_volumes = []
normalize = environment.get_boolean('COMPOSE_CONVERT_WINDOWS_PATHS')
win_host = environment.get_boolean('COMPOSE_FORCE_WINDOWS_HOST')
for v in service_dict['volumes']:
if isinstance(v, dict):
finalized_volumes.a... | 126 | 126 | 422 | 15 | 110 | jovobe/compose | compose/config/config.py | Python | finalize_service | finalize_service | 842 | 894 | 842 | 842 | a2872faf19f3901c98366eca0e3c1a7a2bb3cc5a | bigcode/the-stack | train |
4d08523a8551721423f8f540 | train | function | def process_healthcheck(service_dict):
if 'healthcheck' not in service_dict:
return service_dict
hc = service_dict['healthcheck']
if 'disable' in hc:
del hc['disable']
hc['test'] = ['NONE']
for field in ['interval', 'timeout', 'start_period']:
if field not in hc or isi... | def process_healthcheck(service_dict):
| if 'healthcheck' not in service_dict:
return service_dict
hc = service_dict['healthcheck']
if 'disable' in hc:
del hc['disable']
hc['test'] = ['NONE']
for field in ['interval', 'timeout', 'start_period']:
if field not in hc or isinstance(hc[field], six.integer_types):
... | ):
try:
v['rate'] = int(v.get('rate', 0))
except ValueError:
raise ConfigurationError(
'Invalid IOPS value: "{}". Must be a positive integer.'.format(v.get('rate'))
)
return service_dict
def process_... | 64 | 64 | 106 | 7 | 56 | jovobe/compose | compose/config/config.py | Python | process_healthcheck | process_healthcheck | 809 | 824 | 809 | 809 | fb6e7024c5aa2fbbfe235e602b9cdd54853c1923 | bigcode/the-stack | train |
6a943270776fd6571d433fb4 | train | function | def dict_from_path_mappings(path_mappings):
if path_mappings:
return dict(split_path_mapping(v) for v in path_mappings)
else:
return {}
| def dict_from_path_mappings(path_mappings):
| if path_mappings:
return dict(split_path_mapping(v) for v in path_mappings)
else:
return {}
| , "
"or is not a valid URL." % build_path)
def merge_path_mappings(base, override):
d = dict_from_path_mappings(base)
d.update(dict_from_path_mappings(override))
return path_mappings_from_dict(d)
def dict_from_path_mappings(path_mappings):
| 64 | 64 | 37 | 10 | 54 | jovobe/compose | compose/config/config.py | Python | dict_from_path_mappings | dict_from_path_mappings | 1,366 | 1,370 | 1,366 | 1,366 | acabe6916efbf878d2491075ab3453b7fa78ec08 | bigcode/the-stack | train |
52ef0c7ca86cf0d5f770a322 | train | function | def join_path_mapping(pair):
(container, host) = pair
if isinstance(host, dict):
return host
elif host is None:
return container
else:
host, mode = host
result = ":".join((host, container))
if mode:
result += ":" + mode
return result
| def join_path_mapping(pair):
| (container, host) = pair
if isinstance(host, dict):
return host
elif host is None:
return container
else:
host, mode = host
result = ":".join((host, container))
if mode:
result += ":" + mode
return result
| )
def process_security_opt(service_dict):
security_opts = service_dict.get('security_opt', [])
result = []
for value in security_opts:
result.append(SecurityOpt.parse(value))
if result:
service_dict['security_opt'] = result
return service_dict
def join_path_mapping(pair):
| 64 | 64 | 72 | 6 | 57 | jovobe/compose | compose/config/config.py | Python | join_path_mapping | join_path_mapping | 1,409 | 1,420 | 1,409 | 1,409 | 482a3c34f9bbee4045853401c61311ea75b4b5d2 | bigcode/the-stack | train |
8e8e1cdfb30d23f3cdc48783 | train | function | def split_kv(kvpair):
if '=' in kvpair:
return kvpair.split('=', 1)
else:
return kvpair, ''
| def split_kv(kvpair):
| if '=' in kvpair:
return kvpair.split('=', 1)
else:
return kvpair, ''
| (base)
env.update(parse_environment(override))
return env
def merge_labels(base, override):
labels = parse_labels(base)
labels.update(parse_labels(override))
return labels
def merge_override_items_lists(base, override):
return sorted(set(override))
def split_kv(kvpair):
| 64 | 64 | 34 | 8 | 56 | jovobe/compose | compose/config/config.py | Python | split_kv | split_kv | 1,232 | 1,236 | 1,232 | 1,232 | f20ee9128e72762a011ea041f9a9d8d05a7a139b | bigcode/the-stack | train |
c1b95462e11bc84571633ace | train | function | def merge_deploy(base, override):
md = MergeDict(base or {}, override or {})
md.merge_scalar('mode')
md.merge_scalar('endpoint_mode')
md.merge_scalar('replicas')
md.merge_mapping('labels', parse_labels)
md.merge_mapping('update_config')
md.merge_mapping('rollback_config')
md.merge_mappin... | def merge_deploy(base, override):
| md = MergeDict(base or {}, override or {})
md.merge_scalar('mode')
md.merge_scalar('endpoint_mode')
md.merge_scalar('replicas')
md.merge_mapping('labels', parse_labels)
md.merge_mapping('update_config')
md.merge_mapping('rollback_config')
md.merge_mapping('restart_policy')
if md.need... | ('isolation')
md.merge_mapping('args', parse_build_arguments)
md.merge_field('cache_from', merge_unique_items_lists, default=[])
md.merge_mapping('labels', parse_labels)
md.merge_mapping('extra_hosts', parse_extra_hosts)
return dict(md)
def merge_deploy(base, override):
| 66 | 66 | 221 | 8 | 58 | jovobe/compose | compose/config/config.py | Python | merge_deploy | merge_deploy | 1,137 | 1,157 | 1,137 | 1,137 | 113faf8a66d1ff8fbf74040d1068b8d3bddfe029 | bigcode/the-stack | train |
132ba43f7d7d3fe1143b9913 | train | function | def process_service(service_config):
working_dir = service_config.working_dir
service_dict = dict(service_config.config)
if 'env_file' in service_dict:
service_dict['env_file'] = [
expand_path(working_dir, path)
for path in to_list(service_dict['env_file'])
]
if... | def process_service(service_config):
| working_dir = service_config.working_dir
service_dict = dict(service_config.config)
if 'env_file' in service_dict:
service_dict['env_file'] = [
expand_path(working_dir, path)
for path in to_list(service_dict['env_file'])
]
if 'build' in service_dict:
pro... | ') and has_uppercase(service_name):
raise ConfigurationError(
"Service '{name}' contains uppercase characters which are not valid "
"as part of an image name. Either use a lowercase service name or "
"use the `image` field to set a custom name for the service image."
... | 76 | 76 | 256 | 6 | 70 | jovobe/compose | compose/config/config.py | Python | process_service | process_service | 716 | 748 | 716 | 716 | ccf9c345e93dad2d37762a7b844b7127172e2efc | bigcode/the-stack | train |
082a83951d4924cdd25508b4 | train | function | def legacy_v1_merge_image_or_build(output, base, override):
output.pop('image', None)
output.pop('build', None)
if 'image' in override:
output['image'] = override['image']
elif 'build' in override:
output['build'] = override['build']
elif 'image' in base:
output['image'] = ba... | def legacy_v1_merge_image_or_build(output, base, override):
| output.pop('image', None)
output.pop('build', None)
if 'image' in override:
output['image'] = override['image']
elif 'build' in override:
output['build'] = override['build']
elif 'image' in base:
output['image'] = base['image']
elif 'build' in base:
output['build'... | .get('driver') or base.get('driver') is None:
md.merge_mapping('options', lambda m: m or {})
elif override.get('options'):
md['options'] = override.get('options', {})
return dict(md)
def legacy_v1_merge_image_or_build(output, base, override):
| 64 | 64 | 102 | 14 | 50 | jovobe/compose | compose/config/config.py | Python | legacy_v1_merge_image_or_build | legacy_v1_merge_image_or_build | 1,203 | 1,213 | 1,203 | 1,203 | 82ea856efd1703d0e3e121a67dc557c17893324d | bigcode/the-stack | train |
914bf9e6e54563e141cc9cea | train | function | def path_mappings_from_dict(d):
return [join_path_mapping(v) for v in sorted(d.items())]
| def path_mappings_from_dict(d):
| return [join_path_mapping(v) for v in sorted(d.items())]
| .update(dict_from_path_mappings(override))
return path_mappings_from_dict(d)
def dict_from_path_mappings(path_mappings):
if path_mappings:
return dict(split_path_mapping(v) for v in path_mappings)
else:
return {}
def path_mappings_from_dict(d):
| 63 | 64 | 24 | 8 | 55 | jovobe/compose | compose/config/config.py | Python | path_mappings_from_dict | path_mappings_from_dict | 1,373 | 1,374 | 1,373 | 1,373 | c7ce947048fc638fc4e1d19167fc5aba38a553b2 | bigcode/the-stack | train |
0f649078d828cc71acabfbe6 | train | function | def merge_unique_objects_lists(base, override):
result = dict((json_hash(i), i) for i in base + override)
return [i[1] for i in sorted([(k, v) for k, v in result.items()], key=lambda x: x[0])]
| def merge_unique_objects_lists(base, override):
| result = dict((json_hash(i), i) for i in base + override)
return [i[1] for i in sorted([(k, v) for k, v in result.items()], key=lambda x: x[0])]
| return dict(md)
def merge_reservations(base, override):
md = MergeDict(base, override)
md.merge_scalar('cpus')
md.merge_scalar('memory')
md.merge_sequence('generic_resources', types.GenericResource.parse)
return dict(md)
def merge_unique_objects_lists(base, override):
| 64 | 64 | 59 | 9 | 55 | jovobe/compose | compose/config/config.py | Python | merge_unique_objects_lists | merge_unique_objects_lists | 1,168 | 1,170 | 1,168 | 1,168 | bb7cd332adc64ec7b4e6cd6db2e264693b257369 | bigcode/the-stack | train |
1585e1bb333360c26e70fd97 | train | class | class ServiceConfig(namedtuple('_ServiceConfig', 'working_dir filename name config')):
@classmethod
def with_abs_paths(cls, working_dir, filename, name, config):
if not working_dir:
raise ValueError("No working_dir for ServiceConfig.")
return cls(
os.path.abspath(workin... | class ServiceConfig(namedtuple('_ServiceConfig', 'working_dir filename name config')):
@classmethod
| def with_abs_paths(cls, working_dir, filename, name, config):
if not working_dir:
raise ValueError("No working_dir for ServiceConfig.")
return cls(
os.path.abspath(working_dir),
os.path.abspath(filename) if filename else filename,
name,
co... | mapping secret names to description dictionaries
:type secrets: :class:`dict`
:param configs: Dictionary mapping config names to description dictionaries
:type configs: :class:`dict`
"""
class ServiceConfig(namedtuple('_ServiceConfig', 'working_dir filename name config')):
@classmethod
| 63 | 64 | 84 | 21 | 42 | jovobe/compose | compose/config/config.py | Python | ServiceConfig | ServiceConfig | 258 | 269 | 258 | 260 | 2247f98734ba366ab0da3e09e3da1b680b660df4 | bigcode/the-stack | train |
77b25fa5e70b7d86f7d06b18 | train | function | def normalize_build(service_dict, working_dir, environment):
if 'build' in service_dict:
build = {}
# Shortcut where specifying a string is treated as the build context
if isinstance(service_dict['build'], six.string_types):
build['context'] = service_dict.pop('build')
e... | def normalize_build(service_dict, working_dir, environment):
| if 'build' in service_dict:
build = {}
# Shortcut where specifying a string is treated as the build context
if isinstance(service_dict['build'], six.string_types):
build['context'] = service_dict.pop('build')
else:
build.update(service_dict['build'])
... | '):
host_path = expand_path(working_dir, host_path)
host_path = os.path.expanduser(host_path)
return u"{}:{}{}".format(host_path, container_path, (':' + mode if mode else ''))
return container_path
def normalize_build(service_dict, working_dir, environment):
| 64 | 64 | 113 | 11 | 52 | jovobe/compose | compose/config/config.py | Python | normalize_build | normalize_build | 1,312 | 1,326 | 1,312 | 1,313 | ac0601c01a46e13b71548cf52822b53a810a442f | bigcode/the-stack | train |
ce8eefb4a8414e13076b2c95 | train | function | def resolve_volume_path(working_dir, volume):
if isinstance(volume, dict):
if volume.get('source', '').startswith('.') and volume['type'] == 'bind':
volume['source'] = expand_path(working_dir, volume['source'])
return volume
mount_params = None
container_path, mount_params = spl... | def resolve_volume_path(working_dir, volume):
| if isinstance(volume, dict):
if volume.get('source', '').startswith('.') and volume['type'] == 'bind':
volume['source'] = expand_path(working_dir, volume['source'])
return volume
mount_params = None
container_path, mount_params = split_path_mapping(volume)
if mount_params i... | :
return key, environment[key]
else:
return key, None
def resolve_volume_paths(working_dir, service_dict):
return [
resolve_volume_path(working_dir, volume)
for volume in service_dict['volumes']
]
def resolve_volume_path(working_dir, volume):
| 63 | 64 | 162 | 10 | 53 | jovobe/compose | compose/config/config.py | Python | resolve_volume_path | resolve_volume_path | 1,291 | 1,309 | 1,291 | 1,291 | f4830836f7db471708ddbc8f292a9b8cb92055af | bigcode/the-stack | train |
caf1186d5accb113ec440db3 | train | function | def find(base_dir, filenames, environment, override_dir=None):
if filenames == ['-']:
return ConfigDetails(
os.path.abspath(override_dir) if override_dir else os.getcwd(),
[ConfigFile(None, yaml.safe_load(sys.stdin))],
environment
)
if filenames:
file... | def find(base_dir, filenames, environment, override_dir=None):
| if filenames == ['-']:
return ConfigDetails(
os.path.abspath(override_dir) if override_dir else os.getcwd(),
[ConfigFile(None, yaml.safe_load(sys.stdin))],
environment
)
if filenames:
filenames = [os.path.join(base_dir, f) for f in filenames]
else... | name, config):
if not working_dir:
raise ValueError("No working_dir for ServiceConfig.")
return cls(
os.path.abspath(working_dir),
os.path.abspath(filename) if filename else filename,
name,
config)
def find(base_dir, filenames, environment, o... | 64 | 64 | 146 | 13 | 51 | jovobe/compose | compose/config/config.py | Python | find | find | 272 | 290 | 272 | 272 | eb6c23a60f90ccd08fe344b6be05bddf95ada1a5 | bigcode/the-stack | train |
8906dbf1278e3a7196380c04 | train | function | def translate_deploy_keys_to_container_config(service_dict):
if 'credential_spec' in service_dict:
del service_dict['credential_spec']
if 'configs' in service_dict:
del service_dict['configs']
if 'deploy' not in service_dict:
return service_dict, []
deploy_dict = service_dict['... | def translate_deploy_keys_to_container_config(service_dict):
| if 'credential_spec' in service_dict:
del service_dict['credential_spec']
if 'configs' in service_dict:
del service_dict['configs']
if 'deploy' not in service_dict:
return service_dict, []
deploy_dict = service_dict['deploy']
ignored_keys = [
k for k in ['endpoint_m... | ']:
return ['resources.reservations.cpus']
return []
def convert_restart_policy(name):
try:
return {
'any': 'always',
'none': 'no',
'on-failure': 'on-failure'
}[name]
except KeyError:
raise ConfigurationError('Invalid restart policy "... | 87 | 87 | 290 | 11 | 76 | jovobe/compose | compose/config/config.py | Python | translate_deploy_keys_to_container_config | translate_deploy_keys_to_container_config | 920 | 955 | 920 | 920 | b3140d5b01f550349e1174c91608f389cc06b1fc | bigcode/the-stack | train |
f2cf90eafa73b316f529bb38 | train | function | def validate_external(entity_type, name, config, version):
if (version < V2_1 or (version >= V3_0 and version < V3_4)) and len(config.keys()) > 1:
raise ConfigurationError(
"{} {} declared as external but specifies additional attributes "
"({}).".format(
entity_type, ... | def validate_external(entity_type, name, config, version):
| if (version < V2_1 or (version >= V3_0 and version < V3_4)) and len(config.keys()) > 1:
raise ConfigurationError(
"{} {} declared as external but specifies additional attributes "
"({}).".format(
entity_type, name, ', '.join(k for k in config if k != 'external')))
| _opts']
)
if 'labels' in config:
config['labels'] = parse_labels(config['labels'])
if 'file' in config:
config['file'] = expand_path(working_dir, config['file'])
return mapping
def validate_external(entity_type, name, config, version):
| 64 | 64 | 89 | 12 | 51 | jovobe/compose | compose/config/config.py | Python | validate_external | validate_external | 446 | 451 | 446 | 446 | e1935e23d09d4c3d98a0a01ef6644737148ffb3a | bigcode/the-stack | train |
442042c9fad15f14a39846d7 | train | function | def process_blkio_config(service_dict):
if not service_dict.get('blkio_config'):
return service_dict
for field in ['device_read_bps', 'device_write_bps']:
if field in service_dict['blkio_config']:
for v in service_dict['blkio_config'].get(field, []):
rate = v.get('ra... | def process_blkio_config(service_dict):
| if not service_dict.get('blkio_config'):
return service_dict
for field in ['device_read_bps', 'device_write_bps']:
if field in service_dict['blkio_config']:
for v in service_dict['blkio_config'].get(field, []):
rate = v.get('rate', 0)
v['rate'] = pars... | if 'depends_on' in service_dict and not isinstance(service_dict['depends_on'], dict):
service_dict['depends_on'] = dict([
(svc, {'condition': 'service_started'}) for svc in service_dict['depends_on']
])
return service_dict
def process_blkio_config(service_dict):
| 64 | 64 | 213 | 8 | 55 | jovobe/compose | compose/config/config.py | Python | process_blkio_config | process_blkio_config | 784 | 806 | 784 | 784 | 5f8f29e09899e72c229e2c38136456390b745236 | bigcode/the-stack | train |
c2d000b4c51fdb3619161402 | train | function | def convert_restart_policy(name):
try:
return {
'any': 'always',
'none': 'no',
'on-failure': 'on-failure'
}[name]
except KeyError:
raise ConfigurationError('Invalid restart policy "{}"'.format(name))
| def convert_restart_policy(name):
| try:
return {
'any': 'always',
'none': 'no',
'on-failure': 'on-failure'
}[name]
except KeyError:
raise ConfigurationError('Invalid restart policy "{}"'.format(name))
| us'])
if 'reservations' in resources_dict:
service_dict['mem_reservation'] = resources_dict['reservations'].get('memory')
if 'cpus' in resources_dict['reservations']:
return ['resources.reservations.cpus']
return []
def convert_restart_policy(name):
| 63 | 64 | 61 | 6 | 57 | jovobe/compose | compose/config/config.py | Python | convert_restart_policy | convert_restart_policy | 909 | 917 | 909 | 909 | a647229f930722586d53443bb1a67965d6e9d957 | bigcode/the-stack | train |
d85486f5f74b3aa76fea8b31 | train | function | def interpolate_config_section(config_file, config, section, environment):
validate_config_section(config_file.filename, config, section)
return interpolate_environment_variables(
config_file.version,
config,
section,
environment
)
| def interpolate_config_section(config_file, config, section, environment):
| validate_config_section(config_file.filename, config, section)
return interpolate_environment_variables(
config_file.version,
config,
section,
environment
)
| s() for file in config_details.config_files
]
service_config = service_configs[0]
for next_config in service_configs[1:]:
service_config = merge_services(service_config, next_config)
return build_services(service_config)
def interpolate_config_section(config_file, config, section, environment)... | 64 | 64 | 47 | 13 | 51 | jovobe/compose | compose/config/config.py | Python | interpolate_config_section | interpolate_config_section | 505 | 512 | 505 | 505 | 4624364a358526304fe4b60170e9768a6e4ab59e | bigcode/the-stack | train |
72ade9b4a126659d89385ce6 | train | function | def to_mapping(sequence, key_field):
return {getattr(item, key_field): item for item in sequence}
| def to_mapping(sequence, key_field):
| return {getattr(item, key_field): item for item in sequence}
| def merge_list_or_string(base, override):
return to_list(base) + to_list(override)
def to_list(value):
if value is None:
return []
elif isinstance(value, six.string_types):
return [value]
else:
return value
def to_mapping(sequence, key_field):
| 64 | 64 | 24 | 8 | 55 | jovobe/compose | compose/config/config.py | Python | to_mapping | to_mapping | 1,440 | 1,441 | 1,440 | 1,440 | f32dcff746393c280c290c39a102478062a4a2bd | bigcode/the-stack | train |
45ac2ea189e7bbe28c2bab91 | train | function | def parse_flat_dict(d):
if not d:
return {}
if isinstance(d, dict):
return dict(d)
raise ConfigurationError("Invalid type: expected mapping")
| def parse_flat_dict(d):
| if not d:
return {}
if isinstance(d, dict):
return dict(d)
raise ConfigurationError("Invalid type: expected mapping")
| 'networks')
parse_sysctls = functools.partial(parse_dict_or_list, split_kv, 'sysctls')
parse_depends_on = functools.partial(
parse_dict_or_list, lambda k: (k, {'condition': 'service_started'}), 'depends_on'
)
def parse_flat_dict(d):
| 64 | 64 | 37 | 6 | 58 | jovobe/compose | compose/config/config.py | Python | parse_flat_dict | parse_flat_dict | 1,265 | 1,272 | 1,265 | 1,265 | 8a85cefd5a3341696e320620eff2d1b8ff482332 | bigcode/the-stack | train |
d8d69d22c5420b60f09ad4a5 | train | function | def resolve_environment(service_dict, environment=None):
"""Unpack any environment variables from an env_file, if set.
Interpolate environment values if set.
"""
env = {}
for env_file in service_dict.get('env_file', []):
env.update(env_vars_from_file(env_file))
env.update(parse_environm... | def resolve_environment(service_dict, environment=None):
| """Unpack any environment variables from an env_file, if set.
Interpolate environment values if set.
"""
env = {}
for env_file in service_dict.get('env_file', []):
env.update(env_vars_from_file(env_file))
env.update(parse_environment(service_dict.get('environment')))
return dict(res... | filename = self.service_config.filename
validate_extends_file_path(
self.service_config.name,
extends_options,
filename)
if 'file' in extends_options:
return expand_path(self.working_dir, extends_options['file'])
return filename
def resolve... | 64 | 64 | 94 | 9 | 54 | jovobe/compose | compose/config/config.py | Python | resolve_environment | resolve_environment | 652 | 661 | 652 | 652 | 2d8c3a667268e0fb8706c666ed066c4edbf9e798 | bigcode/the-stack | train |
8933a936e60125c220301113 | train | function | def get_default_config_files(base_dir):
(candidates, path) = find_candidates_in_parent_dirs(SUPPORTED_FILENAMES, base_dir)
if not candidates:
raise ComposeFileNotFound(SUPPORTED_FILENAMES)
winner = candidates[0]
if len(candidates) > 1:
log.warn("Found multiple config files with suppor... | def get_default_config_files(base_dir):
| (candidates, path) = find_candidates_in_parent_dirs(SUPPORTED_FILENAMES, base_dir)
if not candidates:
raise ComposeFileNotFound(SUPPORTED_FILENAMES)
winner = candidates[0]
if len(candidates) > 1:
log.warn("Found multiple config files with supported names: %s", ", ".join(candidates))
... | :
raise ConfigurationError(
"Version mismatch: file {0} specifies version {1} but "
"extension file {2} uses version {3}".format(
main_file.filename,
main_file.version,
next_file.filename,
next_fi... | 64 | 64 | 115 | 8 | 56 | jovobe/compose | compose/config/config.py | Python | get_default_config_files | get_default_config_files | 309 | 321 | 309 | 309 | cc36ef7784e677d1a8d87e562cdcf72064b6ff77 | bigcode/the-stack | train |
fe3e5d951813a7e8324fe519 | train | function | def process_build_section(service_dict, working_dir):
if isinstance(service_dict['build'], six.string_types):
service_dict['build'] = resolve_build_path(working_dir, service_dict['build'])
elif isinstance(service_dict['build'], dict):
if 'context' in service_dict['build']:
path = ser... | def process_build_section(service_dict, working_dir):
| if isinstance(service_dict['build'], six.string_types):
service_dict['build'] = resolve_build_path(working_dir, service_dict['build'])
elif isinstance(service_dict['build'], dict):
if 'context' in service_dict['build']:
path = service_dict['build']['context']
service_dict... | _search', 'tmpfs']:
if field in service_dict:
service_dict[field] = to_list(service_dict[field])
service_dict = process_security_opt(process_blkio_config(process_ports(
process_healthcheck(service_dict)
)))
return service_dict
def process_build_section(service_dict, working_dir... | 64 | 64 | 119 | 10 | 53 | jovobe/compose | compose/config/config.py | Python | process_build_section | process_build_section | 751 | 759 | 751 | 751 | 1204220dd2165dcc35f2a5953406de3d7c8617cd | bigcode/the-stack | train |
a703a68302b68e4e9e00ed3d | train | function | def validate_extended_service_dict(service_dict, filename, service):
error_prefix = "Cannot extend service '%s' in %s:" % (service, filename)
if 'links' in service_dict:
raise ConfigurationError(
"%s services with 'links' cannot be extended" % error_prefix)
if 'volumes_from' in service... | def validate_extended_service_dict(service_dict, filename, service):
| error_prefix = "Cannot extend service '%s' in %s:" % (service, filename)
if 'links' in service_dict:
raise ConfigurationError(
"%s services with 'links' cannot be extended" % error_prefix)
if 'volumes_from' in service_dict:
raise ConfigurationError(
"%s services wit... | (k, v, environment) for k, v in six.iteritems(env))
def resolve_build_args(buildargs, environment):
args = parse_build_arguments(buildargs)
return dict(resolve_env_var(k, v, environment) for k, v in six.iteritems(args))
def validate_extended_service_dict(service_dict, filename, service):
| 66 | 66 | 222 | 12 | 54 | jovobe/compose | compose/config/config.py | Python | validate_extended_service_dict | validate_extended_service_dict | 669 | 692 | 669 | 669 | 37c3277fa87149d88b5bd04438d136a6dcf7c0fc | bigcode/the-stack | train |
5f6d15717f363cc4f31b012d | train | function | def merge_labels(base, override):
labels = parse_labels(base)
labels.update(parse_labels(override))
return labels
| def merge_labels(base, override):
| labels = parse_labels(base)
labels.update(parse_labels(override))
return labels
| in base:
output['image'] = base['image']
elif 'build' in base:
output['build'] = base['build']
def merge_environment(base, override):
env = parse_environment(base)
env.update(parse_environment(override))
return env
def merge_labels(base, override):
| 64 | 64 | 26 | 7 | 56 | jovobe/compose | compose/config/config.py | Python | merge_labels | merge_labels | 1,222 | 1,225 | 1,222 | 1,222 | 63abad4f85a40b4aedeb57e6b929684b9f5f6a04 | bigcode/the-stack | train |
39c067d7a59017503e2c00e4 | train | function | def normalize_v1_service_format(service_dict):
if 'log_driver' in service_dict or 'log_opt' in service_dict:
if 'logging' not in service_dict:
service_dict['logging'] = {}
if 'log_driver' in service_dict:
service_dict['logging']['driver'] = service_dict['log_driver']
... | def normalize_v1_service_format(service_dict):
| if 'log_driver' in service_dict or 'log_opt' in service_dict:
if 'logging' not in service_dict:
service_dict['logging'] = {}
if 'log_driver' in service_dict:
service_dict['logging']['driver'] = service_dict['log_driver']
del service_dict['log_driver']
if '... | ignored_keys.append('restart_policy.{}'.format(k))
ignored_keys.extend(
translate_resource_keys_to_container_config(
deploy_dict.get('resources', {}), service_dict
)
)
del service_dict['deploy']
return service_dict, ignored_keys
def normalize_v1_service_format(service_dic... | 64 | 64 | 162 | 9 | 54 | jovobe/compose | compose/config/config.py | Python | normalize_v1_service_format | normalize_v1_service_format | 958 | 975 | 958 | 958 | fdf55ddc40a93e65b93fbef6c8d6f2d7525ac489 | bigcode/the-stack | train |
910f681daae31a34ebaf2280 | train | function | def check_swarm_only_config(service_dicts, compatibility=False):
warning_template = (
"Some services ({services}) use the '{key}' key, which will be ignored. "
"Compose does not support '{key}' configuration - use "
"`docker stack deploy` to deploy to a swarm."
)
def check_swarm_onl... | def check_swarm_only_config(service_dicts, compatibility=False):
| warning_template = (
"Some services ({services}) use the '{key}' key, which will be ignored. "
"Compose does not support '{key}' configuration - use "
"`docker stack deploy` to deploy to a swarm."
)
def check_swarm_only_key(service_dicts, key):
services = [s for s in service... | if not candidates:
parent_dir = os.path.join(path, '..')
if os.path.abspath(parent_dir) != os.path.abspath(path):
return find_candidates_in_parent_dirs(filenames, parent_dir)
return (candidates, path)
def check_swarm_only_config(service_dicts, compatibility=False):
| 64 | 64 | 176 | 13 | 51 | jovobe/compose | compose/config/config.py | Python | check_swarm_only_config | check_swarm_only_config | 352 | 371 | 352 | 352 | 29a0beee0b7f469928e029a0dc44c3f53ee474a3 | bigcode/the-stack | train |
4bbde7dcdd2babc531a3746e | train | function | def finalize_service_volumes(service_dict, environment):
if 'volumes' in service_dict:
finalized_volumes = []
normalize = environment.get_boolean('COMPOSE_CONVERT_WINDOWS_PATHS')
win_host = environment.get_boolean('COMPOSE_FORCE_WINDOWS_HOST')
for v in service_dict['volumes']:
... | def finalize_service_volumes(service_dict, environment):
| if 'volumes' in service_dict:
finalized_volumes = []
normalize = environment.get_boolean('COMPOSE_CONVERT_WINDOWS_PATHS')
win_host = environment.get_boolean('COMPOSE_FORCE_WINDOWS_HOST')
for v in service_dict['volumes']:
if isinstance(v, dict):
finalized_v... | ['NONE']
for field in ['interval', 'timeout', 'start_period']:
if field not in hc or isinstance(hc[field], six.integer_types):
continue
hc[field] = parse_nanoseconds_int(hc[field])
return service_dict
def finalize_service_volumes(service_dict, environment):
| 64 | 64 | 124 | 10 | 53 | jovobe/compose | compose/config/config.py | Python | finalize_service_volumes | finalize_service_volumes | 827 | 839 | 827 | 827 | 07338ad83d91e6c0b97db2ac88a5397f9cda2151 | bigcode/the-stack | train |
cdae67888a7c8173cc7168b2 | train | class | class MergeDict(dict):
"""A dict-like object responsible for merging two dicts into one."""
def __init__(self, base, override):
self.base = base
self.override = override
def needs_merge(self, field):
return field in self.base or field in self.override
def merge_field(self, fie... | class MergeDict(dict):
| """A dict-like object responsible for merging two dicts into one."""
def __init__(self, base, override):
self.base = base
self.override = override
def needs_merge(self, field):
return field in self.base or field in self.override
def merge_field(self, field, merge_func, default... | `
field. This is not handled by `merge_service_dicts()` which is used to
perform the `extends`.
"""
new_service = merge_service_dicts(base, override, version)
if 'extends' in override:
new_service['extends'] = override['extends']
elif 'extends' in base:
new_service['extends'] = b... | 90 | 90 | 303 | 5 | 84 | jovobe/compose | compose/config/config.py | Python | MergeDict | MergeDict | 991 | 1,033 | 991 | 991 | 2a5c06ebb24fa481e426c16ca8205e5dff26ff07 | bigcode/the-stack | train |
a26451fde9865599403484f8 | train | function | def merge_blkio_config(base, override):
md = MergeDict(base, override)
md.merge_scalar('weight')
def merge_blkio_limits(base, override):
index = dict((b['path'], b) for b in base)
for o in override:
index[o['path']] = o
return sorted(list(index.values()), key=lambda x: ... | def merge_blkio_config(base, override):
| md = MergeDict(base, override)
md.merge_scalar('weight')
def merge_blkio_limits(base, override):
index = dict((b['path'], b) for b in base)
for o in override:
index[o['path']] = o
return sorted(list(index.values()), key=lambda x: x['path'])
for field in [
... | (base, override):
result = dict((json_hash(i), i) for i in base + override)
return [i[1] for i in sorted([(k, v) for k, v in result.items()], key=lambda x: x[0])]
def merge_blkio_config(base, override):
| 63 | 64 | 138 | 9 | 54 | jovobe/compose | compose/config/config.py | Python | merge_blkio_config | merge_blkio_config | 1,173 | 1,190 | 1,173 | 1,173 | 803373c2db4b1448b8004386f7f7b29e6d8e6280 | bigcode/the-stack | train |
ed1d41fcd60bb3c8d5e9818a | train | function | def merge_path_mappings(base, override):
d = dict_from_path_mappings(base)
d.update(dict_from_path_mappings(override))
return path_mappings_from_dict(d)
| def merge_path_mappings(base, override):
| d = dict_from_path_mappings(base)
d.update(dict_from_path_mappings(override))
return path_mappings_from_dict(d)
| (not os.path.exists(build_path) or not os.access(build_path, os.R_OK))
):
raise ConfigurationError(
"build path %s either does not exist, is not accessible, "
"or is not a valid URL." % build_path)
def merge_path_mappings(base, override):
| 64 | 64 | 39 | 9 | 55 | jovobe/compose | compose/config/config.py | Python | merge_path_mappings | merge_path_mappings | 1,360 | 1,363 | 1,360 | 1,360 | b230daacd3664ffb142e61285e7ee20151a8f6c3 | bigcode/the-stack | train |
ea6094c6bc37633337a42109 | train | function | def merge_environment(base, override):
env = parse_environment(base)
env.update(parse_environment(override))
return env
| def merge_environment(base, override):
| env = parse_environment(base)
env.update(parse_environment(override))
return env
| ['image']
elif 'build' in override:
output['build'] = override['build']
elif 'image' in base:
output['image'] = base['image']
elif 'build' in base:
output['build'] = base['build']
def merge_environment(base, override):
| 64 | 64 | 26 | 7 | 57 | jovobe/compose | compose/config/config.py | Python | merge_environment | merge_environment | 1,216 | 1,219 | 1,216 | 1,216 | 9c818e6224a31857868d0bbf57b0c5778dd89648 | bigcode/the-stack | train |
74cae428591757c659e0dd72 | train | function | def get_default_override_file(path):
override_files_in_path = [os.path.join(path, override_filename) for override_filename
in DEFAULT_OVERRIDE_FILENAMES
if os.path.exists(os.path.join(path, override_filename))]
if len(override_files_in_path) > 1:
... | def get_default_override_file(path):
| override_files_in_path = [os.path.join(path, override_filename) for override_filename
in DEFAULT_OVERRIDE_FILENAMES
if os.path.exists(os.path.join(path, override_filename))]
if len(override_files_in_path) > 1:
raise DuplicateOverrideFileFound(o... | len(candidates) > 1:
log.warn("Found multiple config files with supported names: %s", ", ".join(candidates))
log.warn("Using %s\n", winner)
return [os.path.join(path, winner)] + get_default_override_file(path)
def get_default_override_file(path):
| 64 | 64 | 79 | 7 | 57 | jovobe/compose | compose/config/config.py | Python | get_default_override_file | get_default_override_file | 324 | 330 | 324 | 324 | 805b0faed6dd87be688a2365ce14bc6048eabb59 | bigcode/the-stack | train |
51e245e3f151aa064bf71fb6 | train | function | def resolve_env_var(key, val, environment):
if val is not None:
return key, val
elif environment and key in environment:
return key, environment[key]
else:
return key, None
| def resolve_env_var(key, val, environment):
| if val is not None:
return key, val
elif environment and key in environment:
return key, environment[key]
else:
return key, None
| : (k, {'condition': 'service_started'}), 'depends_on'
)
def parse_flat_dict(d):
if not d:
return {}
if isinstance(d, dict):
return dict(d)
raise ConfigurationError("Invalid type: expected mapping")
def resolve_env_var(key, val, environment):
| 64 | 64 | 47 | 10 | 54 | jovobe/compose | compose/config/config.py | Python | resolve_env_var | resolve_env_var | 1,275 | 1,281 | 1,275 | 1,275 | aab8022a1863952a225920a24e29853bb4f1d4de | bigcode/the-stack | train |
1701aa63c7ea0f09f0bf7c1b | train | function | def process_config_file(config_file, environment, service_name=None):
services = interpolate_config_section(
config_file,
config_file.get_service_dicts(),
'service',
environment)
if config_file.version > V1:
processed_config = dict(config_file.config)
processed_c... | def process_config_file(config_file, environment, service_name=None):
| services = interpolate_config_section(
config_file,
config_file.get_service_dicts(),
'service',
environment)
if config_file.version > V1:
processed_config = dict(config_file.config)
processed_config['services'] = services
processed_config['volumes'] = int... | _config in service_configs[1:]:
service_config = merge_services(service_config, next_config)
return build_services(service_config)
def interpolate_config_section(config_file, config, section, environment):
validate_config_section(config_file.filename, config, section)
return interpolate_environme... | 87 | 87 | 291 | 13 | 74 | jovobe/compose | compose/config/config.py | Python | process_config_file | process_config_file | 515 | 559 | 515 | 515 | a0a09d0fb25ccaf6977fd30f54eff525a490264c | bigcode/the-stack | train |
6f4ba70aee0e3114a6c5b08a | train | function | def to_list(value):
if value is None:
return []
elif isinstance(value, six.string_types):
return [value]
else:
return value
| def to_list(value):
| if value is None:
return []
elif isinstance(value, six.string_types):
return [value]
else:
return value
| result += ":" + mode
return result
def expand_path(working_dir, path):
return os.path.abspath(os.path.join(working_dir, os.path.expanduser(path)))
def merge_list_or_string(base, override):
return to_list(base) + to_list(override)
def to_list(value):
| 64 | 64 | 35 | 5 | 59 | jovobe/compose | compose/config/config.py | Python | to_list | to_list | 1,431 | 1,437 | 1,431 | 1,431 | 6c16bc8d0a65cc2e98465753496d5cb4474e7a86 | bigcode/the-stack | train |
8cd51f5fb5ca6eb4e0979e67 | train | class | class ServiceExtendsResolver(object):
def __init__(self, service_config, config_file, environment, already_seen=None):
self.service_config = service_config
self.working_dir = service_config.working_dir
self.already_seen = already_seen or []
self.config_file = config_file
self... | class ServiceExtendsResolver(object):
| def __init__(self, service_config, config_file, environment, already_seen=None):
self.service_config = service_config
self.working_dir = service_config.working_dir
self.already_seen = already_seen or []
self.config_file = config_file
self.environment = environment
@prope... | .get_networks(),
'network',
environment)
if config_file.version >= const.COMPOSEFILE_V3_1:
processed_config['secrets'] = interpolate_config_section(
config_file,
config_file.get_secrets(),
'secret',
environment)
... | 183 | 183 | 610 | 7 | 175 | jovobe/compose | compose/config/config.py | Python | ServiceExtendsResolver | ServiceExtendsResolver | 562 | 649 | 562 | 562 | a0332dfc76ccdfe6071f5541fa2045e497681bc4 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.