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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
12205cd760540f6de96cfaf8 | train | function | def embed_msg_contents_into_component(component, id, msg_contents):
component["contents"] = msg_contents[id]
| def embed_msg_contents_into_component(component, id, msg_contents):
| component["contents"] = msg_contents[id]
| kind else None,
"category": get_fuzzy(root, "category", "categoryID"),
"docs": xml_get_docs(root, body=True, elaboration=True),
"history": xml_get_history(root),
}
),
)
def embed_msg_contents_into_component(component, id, msg_contents):
| 64 | 64 | 23 | 13 | 51 | fixipe/fixtodict | fixtodict/xml_logic/elem_component.py | Python | embed_msg_contents_into_component | embed_msg_contents_into_component | 32 | 33 | 32 | 32 | 52df18a76207bcf916747c0c124d98ddfa340ceb | bigcode/the-stack | train |
196731cdb045c1028902cc10 | train | function | def xml_to_component(root):
kind = get_fuzzy(root, "type", "ComponentType")
return (
# Primary key.
get_fuzzy(root, "id", "ComponentID"),
filter_none(
{
"name": get_fuzzy(root, "name"),
"nameAbbr": get_fuzzy(root, "abbrName", "nameAbbr"),
... | def xml_to_component(root):
| kind = get_fuzzy(root, "type", "ComponentType")
return (
# Primary key.
get_fuzzy(root, "id", "ComponentID"),
filter_none(
{
"name": get_fuzzy(root, "name"),
"nameAbbr": get_fuzzy(root, "abbrName", "nameAbbr"),
"kind": kind.lowe... | from .utils import (
xml_to_sorted_dict,
xml_get_history,
xml_get_docs,
filter_none,
get_fuzzy,
)
def xml_to_components(root):
return xml_to_sorted_dict(root, xml_to_component)
def xml_to_component(root):
| 55 | 64 | 139 | 6 | 49 | fixipe/fixtodict | fixtodict/xml_logic/elem_component.py | Python | xml_to_component | xml_to_component | 14 | 29 | 14 | 14 | 1e0e8dfc8de3e7de106d2076e51663459f0fec3b | bigcode/the-stack | train |
15e7fab10c1faed76a98abaf | train | function | def xml_to_components(root):
return xml_to_sorted_dict(root, xml_to_component)
| def xml_to_components(root):
| return xml_to_sorted_dict(root, xml_to_component)
| from .utils import (
xml_to_sorted_dict,
xml_get_history,
xml_get_docs,
filter_none,
get_fuzzy,
)
def xml_to_components(root):
| 37 | 64 | 18 | 6 | 31 | fixipe/fixtodict | fixtodict/xml_logic/elem_component.py | Python | xml_to_components | xml_to_components | 10 | 11 | 10 | 10 | 6ac62c321f57745cb9d9e6a75e9fdd2b9e25f682 | bigcode/the-stack | train |
dc5bf9a70f9ef20433435024 | train | function | def _get_all_combinations(input_dict):
input_list = [(k, v) for k, v in input_dict.items()]
len_list = [len(kv[1]) for kv in input_list]
input_idx = [0] * len(input_dict)
if len(input_dict) == 0:
return [{}]
output = []
done = False
while True:
new_combination = {input_lis... | def _get_all_combinations(input_dict):
| input_list = [(k, v) for k, v in input_dict.items()]
len_list = [len(kv[1]) for kv in input_list]
input_idx = [0] * len(input_dict)
if len(input_dict) == 0:
return [{}]
output = []
done = False
while True:
new_combination = {input_list[i][0]: input_list[i][1][idx] for i, i... | dataset.
:type expected: BatchDataset
"""
zipped_batches = zip(actual, expected)
for ((c_data, c_label), (data, label)) in zipped_batches:
assert np.array_equal(c_data, data)
assert np.array_equal(c_label, label)
def _get_all_combinations(input_dict):
| 68 | 68 | 229 | 9 | 59 | microsoft/ml-wrappers | tests/common_utils.py | Python | _get_all_combinations | _get_all_combinations | 696 | 727 | 696 | 696 | a2665eba556a7584129cfc6a7f6079fc42948ef3 | bigcode/the-stack | train |
6dcdcfca38aeb46bee3dc144 | train | function | def create_scikit_keras_binary_classifier(X, y):
# create simple (dummy) Keras DNN model for classification
batch_size = 500
epochs = 10
model_func = create_scikit_keras_model_func(X.shape[1], num_classes=2)
model = KerasClassifier(build_fn=model_func, nb_epoch=epochs, batch_size=batch_size, verbose... | def create_scikit_keras_binary_classifier(X, y):
# create simple (dummy) Keras DNN model for classification
| batch_size = 500
epochs = 10
model_func = create_scikit_keras_model_func(X.shape[1], num_classes=2)
model = KerasClassifier(build_fn=model_func, nb_epoch=epochs, batch_size=batch_size, verbose=1)
model.fit(X, y)
return model
| model = KerasRegressor(build_fn=model_func, nb_epoch=epochs, batch_size=batch_size, verbose=1)
model.fit(X, y)
return model
def create_scikit_keras_binary_classifier(X, y):
# create simple (dummy) Keras DNN model for classification
| 64 | 64 | 97 | 27 | 36 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_scikit_keras_binary_classifier | create_scikit_keras_binary_classifier | 294 | 301 | 294 | 295 | 57d387d807650e9cfe2f5e5e85809fa0503aa0b8 | bigcode/the-stack | train |
29464f5080e61ccd379f1260 | train | function | def create_scikit_keras_model_func(feature_number, num_classes=None):
def common_scikit_keras_model():
model = Sequential()
model.add(Dense(12, input_dim=feature_number, activation='relu'))
model.add(Dense(8, activation='relu'))
if num_classes is None:
model.add(Dense(1))... | def create_scikit_keras_model_func(feature_number, num_classes=None):
| def common_scikit_keras_model():
model = Sequential()
model.add(Dense(12, input_dim=feature_number, activation='relu'))
model.add(Dense(8, activation='relu'))
if num_classes is None:
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam'... | optimizer=keras.optimizers.Adadelta(),
metrics=['accuracy'])
model.fit(X, y,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(X, y))
return model
def create_scikit_keras_model_func(feature_number, num_classes=None):
| 64 | 64 | 189 | 15 | 48 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_scikit_keras_model_func | create_scikit_keras_model_func | 262 | 281 | 262 | 262 | 797e5eae81cca6083760ba35823dbc895f9d18a3 | bigcode/the-stack | train |
a58ce723a460f24d14bae130 | train | function | def create_random_forest_vectorizer():
vectorizer = CountVectorizer(lowercase=False, min_df=0.0, binary=True)
rf = RandomForestClassifier(n_estimators=500, random_state=777)
return Pipeline([('vectorizer', vectorizer), ('rf', rf)])
| def create_random_forest_vectorizer():
| vectorizer = CountVectorizer(lowercase=False, min_df=0.0, binary=True)
rf = RandomForestClassifier(n_estimators=500, random_state=777)
return Pipeline([('vectorizer', vectorizer), ('rf', rf)])
| def create_random_forest_tfidf():
vectorizer = TfidfVectorizer(lowercase=False)
rf = RandomForestClassifier(n_estimators=500, random_state=777)
return Pipeline([('vectorizer', vectorizer), ('rf', rf)])
def create_random_forest_vectorizer():
| 63 | 64 | 62 | 8 | 55 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_random_forest_vectorizer | create_random_forest_vectorizer | 112 | 115 | 112 | 112 | ae853f0a99c442e8b1dd0389c1d7c5ee92c719d5 | bigcode/the-stack | train |
bf051db8dbb8c5c21f1f417a | train | function | def _common_model_generator(feature_number, output_length=1):
model = Sequential()
model.add(Dense(32, activation='relu', input_shape=(feature_number,)))
model.add(Dropout(0.25))
model.add(Dense(output_length, activation='relu', input_shape=(32,)))
model.add(Dropout(0.5))
return model
| def _common_model_generator(feature_number, output_length=1):
| model = Sequential()
model.add(Dense(32, activation='relu', input_shape=(feature_number,)))
model.add(Dropout(0.25))
model.add(Dense(output_length, activation='relu', input_shape=(32,)))
model.add(Dropout(0.5))
return model
| input_idx[carry_check_pos] = 0
input_idx[carry_check_pos - 1] += 1
carry_check_pos -= 1
else:
break
if done:
break
return output
def _common_model_generator(feature_number, output_length=1):
| 64 | 64 | 79 | 13 | 50 | microsoft/ml-wrappers | tests/common_utils.py | Python | _common_model_generator | _common_model_generator | 730 | 736 | 730 | 730 | 7460b687cd4f72594b78b25f94c71a727e7d5b9c | bigcode/the-stack | train |
c1e60725714e1c9eead50955 | train | function | def create_reviews_data(test_size):
reviews_data = retrieve_dataset('reviews.json')
papers = reviews_data['paper']
reviews = []
evaluation = []
for paper in papers:
if paper['review'] is None or not paper['review']:
continue
reviews.append(paper['review'][0]['text'])
... | def create_reviews_data(test_size):
| reviews_data = retrieve_dataset('reviews.json')
papers = reviews_data['paper']
reviews = []
evaluation = []
for paper in papers:
if paper['review'] is None or not paper['review']:
continue
reviews.append(paper['review'][0]['text'])
evaluation.append(paper['review'... | y_test = train_test_split(X,
y,
test_size=0.2,
random_state=0)
classes = np.unique(y_train).tolist()
return pd.DataFrame(x_train), y_train, pd... | 64 | 64 | 100 | 7 | 56 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_reviews_data | create_reviews_data | 600 | 610 | 600 | 600 | 22c8ae0062903d99fa4e0342973a115112ade913 | bigcode/the-stack | train |
27ff3adad1d4c78c277eb9d3 | train | function | def create_sklearn_random_forest_regressor(X, y):
rfr = ensemble.RandomForestRegressor(n_estimators=10, max_depth=4, random_state=777)
model = rfr.fit(X, y)
return model
| def create_sklearn_random_forest_regressor(X, y):
| rfr = ensemble.RandomForestRegressor(n_estimators=10, max_depth=4, random_state=777)
model = rfr.fit(X, y)
return model
| svm.SVC(gamma=0.001, C=100., probability=probability, random_state=777)
pipeline = Pipeline([('pandas_only', pandas_only), ('clf', clf)])
return pipeline.fit(X, y)
def create_sklearn_random_forest_regressor(X, y):
| 64 | 64 | 53 | 14 | 50 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_sklearn_random_forest_regressor | create_sklearn_random_forest_regressor | 203 | 206 | 203 | 203 | f8cb445864c47bdd83f381c17381be1e8df26276 | bigcode/the-stack | train |
50d381b81750eb447e13a10f | train | function | def create_xgboost_regressor(X, y):
xgb = XGBRegressor(learning_rate=0.1, max_depth=3, n_estimators=100,
n_jobs=1, random_state=777)
model = xgb.fit(X, y)
return model
| def create_xgboost_regressor(X, y):
| xgb = XGBRegressor(learning_rate=0.1, max_depth=3, n_estimators=100,
n_jobs=1, random_state=777)
model = xgb.fit(X, y)
return model
| y):
xgb = XGBClassifier(learning_rate=0.1, max_depth=3, n_estimators=100,
n_jobs=1, random_state=777)
model = xgb.fit(X, y)
return model
def create_xgboost_regressor(X, y):
| 64 | 64 | 63 | 11 | 52 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_xgboost_regressor | create_xgboost_regressor | 157 | 161 | 157 | 157 | 949ff5e76c26f82e2c584219b962e4edf9626823 | bigcode/the-stack | train |
44c382efa6db8344f0962d40 | train | function | def create_cancer_data():
# Import cancer dataset
cancer = retrieve_dataset('breast-cancer.train.csv', na_values='?').interpolate().astype('int64')
cancer_target = cancer.iloc[:, 0]
cancer_data = cancer.iloc[:, 1:]
feature_names = cancer_data.columns.values
target_names = ['no_cancer', 'cancer']... | def create_cancer_data():
# Import cancer dataset
| cancer = retrieve_dataset('breast-cancer.train.csv', na_values='?').interpolate().astype('int64')
cancer_target = cancer.iloc[:, 0]
cancer_data = cancer.iloc[:, 1:]
feature_names = cancer_data.columns.values
target_names = ['no_cancer', 'cancer']
# Split data into train and test
x_train, x_t... | _train, x_test, y_train, y_validation = train_test_split(housing.data, housing.target,
test_size=0.2, random_state=7)
return x_train, x_test, y_train, y_validation, housing.feature_names
def create_cancer_data():
# Import cancer dataset
| 64 | 64 | 145 | 12 | 51 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_cancer_data | create_cancer_data | 530 | 540 | 530 | 531 | ba7de7426497ad9c409dd92cbd8ab81b19b5b0c5 | bigcode/the-stack | train |
56cc86561426c000b39ca6b0 | train | function | def create_msx_data(test_size):
sparse_matrix = retrieve_dataset('msx_transformed_2226.npz')
sparse_matrix_x = sparse_matrix[:, :sparse_matrix.shape[1] - 2]
sparse_matrix_y = sparse_matrix[:, (sparse_matrix.shape[1] - 2):(sparse_matrix.shape[1] - 1)]
return train_test_split(sparse_matrix_x, sparse_matri... | def create_msx_data(test_size):
| sparse_matrix = retrieve_dataset('msx_transformed_2226.npz')
sparse_matrix_x = sparse_matrix[:, :sparse_matrix.shape[1] - 2]
sparse_matrix_y = sparse_matrix[:, (sparse_matrix.shape[1] - 2):(sparse_matrix.shape[1] - 1)]
return train_test_split(sparse_matrix_x, sparse_matrix_y, test_size=test_size, random... | ,
test_size=0.2,
random_state=0)
feature_names = breast_cancer_data.feature_names
classes = breast_cancer_data.target_names.tolist()
return x_train, x_test, y_train, y_test, feature_names, classes... | 64 | 64 | 100 | 8 | 55 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_msx_data | create_msx_data | 571 | 575 | 571 | 571 | 3a87332a011f7f809a269ff810368a9ffebc17a0 | bigcode/the-stack | train |
3358fe8b195727d094b138bd | train | function | def create_dnn_classifier_unfit(feature_number):
# create simple (dummy) Keras DNN model for binary classification
model = _common_model_generator(feature_number)
model.add(Activation('sigmoid'))
model.compile(loss=keras.losses.binary_crossentropy,
optimizer=keras.optimizers.Adadelta()... | def create_dnn_classifier_unfit(feature_number):
# create simple (dummy) Keras DNN model for binary classification
| model = _common_model_generator(feature_number)
model.add(Activation('sigmoid'))
model.compile(loss=keras.losses.binary_crossentropy,
optimizer=keras.optimizers.Adadelta(),
metrics=['accuracy'])
return model
| optimizer = torch.optim.SGD(net.parameters(), lr=0.01)
return _train_pytorch_model(epochs, criterion, optimizer, net, torch_X, torch_y)
def create_dnn_classifier_unfit(feature_number):
# create simple (dummy) Keras DNN model for binary classification
| 64 | 64 | 76 | 26 | 38 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_dnn_classifier_unfit | create_dnn_classifier_unfit | 488 | 495 | 488 | 489 | 469e4558c07db93314fc3cba6a7e9761903a6975 | bigcode/the-stack | train |
dcaec3486d72d941f43229da | train | function | def assert_sparse_equal(actual, expected):
"""Assert that two sparse matrices are equal.
:param actual: The actual sparse matrix.
:type actual: scipy.sparse.csr_matrix
:param expected: The expected sparse matrix.
:type expected: scipy.sparse.csr_matrix
"""
assert actual.shape == expected.sh... | def assert_sparse_equal(actual, expected):
| """Assert that two sparse matrices are equal.
:param actual: The actual sparse matrix.
:type actual: scipy.sparse.csr_matrix
:param expected: The expected sparse matrix.
:type expected: scipy.sparse.csr_matrix
"""
assert actual.shape == expected.shape
assert actual.dtype == expected.dty... | (grain_comb)
X = pd.DataFrame(row_data)
data.append(X)
X = pd.concat(data).set_index([time_column_name] + list(grains_dict.keys()))
y = X.pop(target_column_name).values
return X, y
def assert_sparse_equal(actual, expected):
| 64 | 64 | 115 | 8 | 55 | microsoft/ml-wrappers | tests/common_utils.py | Python | assert_sparse_equal | assert_sparse_equal | 667 | 679 | 667 | 667 | f97fb649abeb3239237ad81de93c3f7c488e7a3d | bigcode/the-stack | train |
3e1a7cdd76359061f7bc726e | train | function | def create_sklearn_svm_classifier(X, y, probability=True):
clf = svm.SVC(gamma=0.001, C=100., probability=probability, random_state=777)
model = clf.fit(X, y)
return model
| def create_sklearn_svm_classifier(X, y, probability=True):
| clf = svm.SVC(gamma=0.001, C=100., probability=probability, random_state=777)
model = clf.fit(X, y)
return model
| = XGBRegressor(learning_rate=0.1, max_depth=3, n_estimators=100,
n_jobs=1, random_state=777)
model = xgb.fit(X, y)
return model
def create_sklearn_svm_classifier(X, y, probability=True):
| 64 | 64 | 55 | 15 | 48 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_sklearn_svm_classifier | create_sklearn_svm_classifier | 164 | 167 | 164 | 164 | c5b5ed7f05c24987b69d7cfe66ecaa9b28b73976 | bigcode/the-stack | train |
f18e9b711684300d5a0d8af3 | train | function | def create_keras_regressor(X, y):
# create simple (dummy) Keras DNN model for regression
batch_size = 128
epochs = 12
model = _common_model_generator(X.shape[1])
model.add(Activation('linear'))
model.compile(loss=keras.losses.mean_squared_error,
optimizer=keras.optimizers.Adade... | def create_keras_regressor(X, y):
# create simple (dummy) Keras DNN model for regression
| batch_size = 128
epochs = 12
model = _common_model_generator(X.shape[1])
model.add(Activation('linear'))
model.compile(loss=keras.losses.mean_squared_error,
optimizer=keras.optimizers.Adadelta(),
metrics=['accuracy'])
model.fit(X, y,
batch_size=b... | = linear_model.LogisticRegression(solver='liblinear')
if pipeline:
lin = Pipeline([('lin', lin)])
model = lin.fit(X, y)
return model
def create_keras_regressor(X, y):
# create simple (dummy) Keras DNN model for regression
| 64 | 64 | 120 | 25 | 38 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_keras_regressor | create_keras_regressor | 245 | 259 | 245 | 246 | 0988b2fc02a450625c1a70ea4458671e3775158f | bigcode/the-stack | train |
8313da444383490e25a41bf5 | train | function | def _train_pytorch_model(epochs, criterion, optimizer, net, torch_X, torch_y):
for epoch in range(epochs):
optimizer.zero_grad()
out = net(torch_X)
loss = criterion(out, torch_y)
loss.backward()
optimizer.step()
print('epoch: ', epoch, ' loss: ', loss.data.item())
... | def _train_pytorch_model(epochs, criterion, optimizer, net, torch_X, torch_y):
| for epoch in range(epochs):
optimizer.zero_grad()
out = net(torch_X)
loss = criterion(out, torch_y)
loss.backward()
optimizer.step()
print('epoch: ', epoch, ' loss: ', loss.data.item())
return net
| X = self.norm(X)
X = F.relu(self.fc1(X))
X = self.fc2(X)
X = self.fc3(X)
return self.output(X)
return Net()
def _train_pytorch_model(epochs, criterion, optimizer, net, torch_X, torch_y):
| 64 | 64 | 78 | 21 | 43 | microsoft/ml-wrappers | tests/common_utils.py | Python | _train_pytorch_model | _train_pytorch_model | 343 | 351 | 343 | 343 | 9eb159552114410940a72a144d86961ab5e23132 | bigcode/the-stack | train |
ab3523c86b1c2369f1bd65a7 | train | function | def create_scikit_keras_multiclass_classifier(X, y):
# create simple (dummy) Keras DNN model for classification
batch_size = 500
epochs = 10
num_classes = len(np.unique(y))
model_func = create_scikit_keras_model_func(X.shape[1], num_classes=num_classes)
model = KerasClassifier(build_fn=model_fun... | def create_scikit_keras_multiclass_classifier(X, y):
# create simple (dummy) Keras DNN model for classification
| batch_size = 500
epochs = 10
num_classes = len(np.unique(y))
model_func = create_scikit_keras_model_func(X.shape[1], num_classes=num_classes)
model = KerasClassifier(build_fn=model_func, nb_epoch=epochs, batch_size=batch_size, verbose=1)
model.fit(X, y)
return model
| model = KerasClassifier(build_fn=model_func, nb_epoch=epochs, batch_size=batch_size, verbose=1)
model.fit(X, y)
return model
def create_scikit_keras_multiclass_classifier(X, y):
# create simple (dummy) Keras DNN model for classification
| 64 | 64 | 108 | 29 | 34 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_scikit_keras_multiclass_classifier | create_scikit_keras_multiclass_classifier | 304 | 312 | 304 | 305 | b28379701da22b76beaccc978a7d3874494898f8 | bigcode/the-stack | train |
c3f2e15d9ababf2c6adaa710 | train | function | def wrap_classifier_without_proba(classifier):
# Wraps a classifier without a predict_proba
class WrappedWithoutProbaClassificationModel(object):
"""A class for wrapping a classification model."""
def __init__(self, classifier):
"""Initialize the WrappedWithoutProbaClassificationMod... | def wrap_classifier_without_proba(classifier):
# Wraps a classifier without a predict_proba
| class WrappedWithoutProbaClassificationModel(object):
"""A class for wrapping a classification model."""
def __init__(self, classifier):
"""Initialize the WrappedWithoutProbaClassificationModel with the underlying model."""
self._model = classifier
def predict(self,... | (X, y):
rfr = ensemble.RandomForestRegressor(n_estimators=10, max_depth=4, random_state=777)
model = rfr.fit(X, y)
return model
def wrap_classifier_without_proba(classifier):
# Wraps a classifier without a predict_proba
| 64 | 64 | 132 | 21 | 42 | microsoft/ml-wrappers | tests/common_utils.py | Python | wrap_classifier_without_proba | wrap_classifier_without_proba | 209 | 226 | 209 | 210 | fc3890c205aa67b0a5945886134931cc86463c17 | bigcode/the-stack | train |
d9980d10352a0465b3c31c40 | train | function | def create_lightgbm_classifier(X, y):
lgbm = LGBMClassifier(boosting_type='gbdt', learning_rate=0.1,
max_depth=5, n_estimators=200, n_jobs=1, random_state=777)
model = lgbm.fit(X, y)
return model
| def create_lightgbm_classifier(X, y):
| lgbm = LGBMClassifier(boosting_type='gbdt', learning_rate=0.1,
max_depth=5, n_estimators=200, n_jobs=1, random_state=777)
model = lgbm.fit(X, y)
return model
| lr)])
def create_sklearn_random_forest_classifier(X, y):
rfc = ensemble.RandomForestClassifier(n_estimators=10, max_depth=4, random_state=777)
model = rfc.fit(X, y)
return model
def create_lightgbm_classifier(X, y):
| 64 | 64 | 70 | 10 | 53 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_lightgbm_classifier | create_lightgbm_classifier | 136 | 140 | 136 | 136 | 6facaf5172fd0c93655ebbc155f42b1b3de5d045 | bigcode/the-stack | train |
820e57564e6c8058bad5c8c6 | train | function | def create_timeseries_data(sample_cnt_per_grain,
time_column_name,
target_column_name,
grains_dict=None,
freq='D'):
data = []
if grains_dict is None:
grains_dict = {}
for grain_comb in _get_al... | def create_timeseries_data(sample_cnt_per_grain,
time_column_name,
target_column_name,
grains_dict=None,
freq='D'):
| data = []
if grains_dict is None:
grains_dict = {}
for grain_comb in _get_all_combinations(grains_dict):
row_data = {
time_column_name: pd.date_range(start='2000-01-01',
periods=sample_cnt_per_grain,
... | ', axis=1)
y = data['survived']
return train_test_split(X, y, test_size=0.2, random_state=42)
def create_timeseries_data(sample_cnt_per_grain,
time_column_name,
target_column_name,
grains_dict=None,
freq... | 66 | 66 | 222 | 31 | 35 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_timeseries_data | create_timeseries_data | 640 | 664 | 640 | 644 | 0dd1fdedc56ddd2f0b749fdb41477420ab7c9a66 | bigcode/the-stack | train |
f543ad46119c69cc233b757c | train | function | def create_binary_classification_dataset():
return create_multiclass_classification_dataset(num_classes=2)
| def create_binary_classification_dataset():
| return create_multiclass_classification_dataset(num_classes=2)
| 2]
sparse_matrix_y = sparse_matrix[:, (sparse_matrix.shape[1] - 2):(sparse_matrix.shape[1] - 1)]
return train_test_split(sparse_matrix_x, sparse_matrix_y, test_size=test_size, random_state=7)
def create_binary_classification_dataset():
| 64 | 64 | 21 | 7 | 57 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_binary_classification_dataset | create_binary_classification_dataset | 578 | 579 | 578 | 578 | a7ab908e6c1be910d32ae8f9c0d6e524e4b9d739 | bigcode/the-stack | train |
6ee8ff6edefdf7065f842811 | train | function | def create_keras_multiclass_classifier(X, y):
batch_size = 128
epochs = 12
num_classes = len(np.unique(y))
model = _common_model_generator(X.shape[1], num_classes)
model.add(Dense(units=num_classes, activation=Activation('softmax')))
model.compile(loss=keras.losses.categorical_crossentropy,
... | def create_keras_multiclass_classifier(X, y):
| batch_size = 128
epochs = 12
num_classes = len(np.unique(y))
model = _common_model_generator(X.shape[1], num_classes)
model.add(Dense(units=num_classes, activation=Activation('softmax')))
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.Adade... | criterion = nn.BCELoss()
optimizer = torch.optim.SGD(net.parameters(), lr=0.01)
return _train_pytorch_model(epochs, criterion, optimizer, net, torch_X, torch_y.reshape(-1, 1))
def create_keras_multiclass_classifier(X, y):
| 64 | 64 | 144 | 12 | 52 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_keras_multiclass_classifier | create_keras_multiclass_classifier | 455 | 470 | 455 | 455 | 20f3af78b7acd56233305c38e2ae1875daa0d872 | bigcode/the-stack | train |
56521e72aecc3bb2ec7aaa57 | train | function | def create_cuml_svm_classifier(X, y):
try:
import cuml
except ImportError:
import warnings
warnings.warn(
"cuML is required to use GPU explainers. Check https://rapids.ai/start.html for \
more information on how to install it.",
ImportWarning)
clf... | def create_cuml_svm_classifier(X, y):
| try:
import cuml
except ImportError:
import warnings
warnings.warn(
"cuML is required to use GPU explainers. Check https://rapids.ai/start.html for \
more information on how to install it.",
ImportWarning)
clf = cuml.svm.SVC(gamma=0.001, C=100., p... | _sklearn_svm_classifier(X, y, probability=True):
clf = svm.SVC(gamma=0.001, C=100., probability=probability, random_state=777)
model = clf.fit(X, y)
return model
def create_cuml_svm_classifier(X, y):
| 64 | 64 | 103 | 11 | 52 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_cuml_svm_classifier | create_cuml_svm_classifier | 170 | 182 | 170 | 170 | 24184b647d5e40451df489bdd9a61fa85c7fda8d | bigcode/the-stack | train |
bcd7df1d68339e82bc723903 | train | function | def create_multiclass_classification_dataset(num_classes=5, num_features=20, num_informative=2):
import numpy as np
import pandas as pd
from sklearn.datasets import make_classification
X, y = make_classification(n_classes=num_classes,
n_features=num_features,
... | def create_multiclass_classification_dataset(num_classes=5, num_features=20, num_informative=2):
| import numpy as np
import pandas as pd
from sklearn.datasets import make_classification
X, y = make_classification(n_classes=num_classes,
n_features=num_features,
n_informative=num_informative)
# Split data into train and test
x_trai... | parse_matrix_x, sparse_matrix_y, test_size=test_size, random_state=7)
def create_binary_classification_dataset():
return create_multiclass_classification_dataset(num_classes=2)
def create_multiclass_classification_dataset(num_classes=5, num_features=20, num_informative=2):
| 64 | 64 | 151 | 25 | 39 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_multiclass_classification_dataset | create_multiclass_classification_dataset | 582 | 597 | 582 | 582 | 17d7c5081538f00b0960bb97c3a06c0be3a47962 | bigcode/the-stack | train |
e5cbd02b42e97719da2b2f8a | train | function | def create_sklearn_linear_regressor(X, y, pipeline=False):
lin = linear_model.LinearRegression(normalize=True)
if pipeline:
lin = Pipeline([('lin', lin)])
model = lin.fit(X, y)
return model
| def create_sklearn_linear_regressor(X, y, pipeline=False):
| lin = linear_model.LinearRegression(normalize=True)
if pipeline:
lin = Pipeline([('lin', lin)])
model = lin.fit(X, y)
return model
| probabilities instead of the predicted class.
:param dataset: The dataset to predict on.
:type dataset: DatasetWrapper
"""
return self._model.predict_proba(dataset)
return WrappedWithoutProbaClassificationModel(classifier)
def create_sklearn_linear_regressor(X, y, ... | 64 | 64 | 53 | 15 | 49 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_sklearn_linear_regressor | create_sklearn_linear_regressor | 229 | 234 | 229 | 229 | ef7095dac356a94529d8e27bc83203bb5e131067 | bigcode/the-stack | train |
38cc8806f0cae3dd881b0c84 | train | function | def create_scikit_cancer_data():
breast_cancer_data = load_breast_cancer()
classes = breast_cancer_data.target_names.tolist()
# Split data into train and test
x_train, x_test, y_train, y_test = train_test_split(breast_cancer_data.data,
breast_canc... | def create_scikit_cancer_data():
| breast_cancer_data = load_breast_cancer()
classes = breast_cancer_data.target_names.tolist()
# Split data into train and test
x_train, x_test, y_train, y_test = train_test_split(breast_cancer_data.data,
breast_cancer_data.target,
... | x_train, x_test, y_train, y_validation = train_test_split(cancer_data, cancer_target,
test_size=0.2, random_state=0)
return x_train, x_test, y_train, y_validation, feature_names, target_names
def create_scikit_cancer_data():
| 64 | 64 | 127 | 8 | 55 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_scikit_cancer_data | create_scikit_cancer_data | 557 | 568 | 557 | 557 | 365a684a36d6334a6a25da96889b3983ea93e2d8 | bigcode/the-stack | train |
8672aee6559c9073e9ea932b | train | function | def create_logistic_vectorizer():
vectorizer = CountVectorizer(lowercase=False, min_df=0.0, binary=True)
lr = LogisticRegression(random_state=777)
return Pipeline([('vectorizer', vectorizer), ('lr', lr)])
| def create_logistic_vectorizer():
| vectorizer = CountVectorizer(lowercase=False, min_df=0.0, binary=True)
lr = LogisticRegression(random_state=777)
return Pipeline([('vectorizer', vectorizer), ('lr', lr)])
| izer():
vectorizer = CountVectorizer(lowercase=False, min_df=0.0, binary=True)
rf = RandomForestClassifier(n_estimators=500, random_state=777)
return Pipeline([('vectorizer', vectorizer), ('rf', rf)])
def create_logistic_vectorizer():
| 63 | 64 | 54 | 7 | 56 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_logistic_vectorizer | create_logistic_vectorizer | 118 | 121 | 118 | 118 | db8a09eef174469166c22d462b6a5a17720b1424 | bigcode/the-stack | train |
6681b2739568cd55eca7f62d | train | function | def create_keras_classifier(X, y):
# create simple (dummy) Keras DNN model for binary classification
batch_size = 128
epochs = 12
model = _common_model_generator(X.shape[1])
model.add(Activation('sigmoid'))
model.compile(loss=keras.losses.binary_crossentropy,
optimizer=keras.op... | def create_keras_classifier(X, y):
# create simple (dummy) Keras DNN model for binary classification
| batch_size = 128
epochs = 12
model = _common_model_generator(X.shape[1])
model.add(Activation('sigmoid'))
model.compile(loss=keras.losses.binary_crossentropy,
optimizer=keras.optimizers.Adadelta(),
metrics=['accuracy'])
model.fit(X, y,
batch_size... | ='adam',
loss='mse',
metrics=['mae', 'mse'])
model.fit(inp_ds, epochs=5, validation_data=val_ds)
return model
def create_keras_classifier(X, y):
# create simple (dummy) Keras DNN model for binary classification
| 64 | 64 | 121 | 25 | 38 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_keras_classifier | create_keras_classifier | 398 | 412 | 398 | 399 | e2b44dec7d321fd19d0335d6b74cb27cdf32890c | bigcode/the-stack | train |
5b0b46d7b978cf00667ba9d6 | train | function | def create_random_forest_tfidf():
vectorizer = TfidfVectorizer(lowercase=False)
rf = RandomForestClassifier(n_estimators=500, random_state=777)
return Pipeline([('vectorizer', vectorizer), ('rf', rf)])
| def create_random_forest_tfidf():
| vectorizer = TfidfVectorizer(lowercase=False)
rf = RandomForestClassifier(n_estimators=500, random_state=777)
return Pipeline([('vectorizer', vectorizer), ('rf', rf)])
| _words='english', alternate_sign=False,
n_features=2**16)
x_train = vectorizer.transform(x_train)
x_test = vectorizer.transform(x_test)
return x_train, x_test, y_train, y_validation, categories, vectorizer
def create_random_forest_tfidf():
| 64 | 64 | 55 | 9 | 54 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_random_forest_tfidf | create_random_forest_tfidf | 106 | 109 | 106 | 106 | 075a11a46cc7f7df11fec12a5616027cd7fc69bb | bigcode/the-stack | train |
984c76921e8c71dbf79227c6 | train | function | def create_housing_data():
# Import California housing dataset
housing = fetch_california_housing()
# Split data into train and test
x_train, x_test, y_train, y_validation = train_test_split(housing.data, housing.target,
test_size=0.2, random... | def create_housing_data():
# Import California housing dataset
| housing = fetch_california_housing()
# Split data into train and test
x_train, x_test, y_train, y_validation = train_test_split(housing.data, housing.target,
test_size=0.2, random_state=7)
return x_train, x_test, y_train, y_validation, housin... | x_train, x_test, y_train, y_validation = train_test_split(energy_data, target,
test_size=0.2, random_state=0)
return x_train, x_test, y_train, y_validation, feature_names
def create_housing_data():
# Import California housing dataset
| 64 | 64 | 85 | 13 | 50 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_housing_data | create_housing_data | 521 | 527 | 521 | 522 | 007d6f1f9c29775a51bc7bd9b72dcf906853cd22 | bigcode/the-stack | train |
273091bc4090632e5dfaba7d | train | function | def create_binary_sparse_newsgroups_data():
categories = ['alt.atheism', 'soc.religion.christian']
newsgroups_train = fetch_20newsgroups(subset='train', categories=categories)
newsgroups_test = fetch_20newsgroups(subset='test', categories=categories)
class_names = ['atheism', 'christian']
x_train = ... | def create_binary_sparse_newsgroups_data():
| categories = ['alt.atheism', 'soc.religion.christian']
newsgroups_train = fetch_20newsgroups(subset='train', categories=categories)
newsgroups_test = fetch_20newsgroups(subset='test', categories=categories)
class_names = ['atheism', 'christian']
x_train = newsgroups_train.data
x_test = newsgroup... | _model == LinearExplainableModel:
return LINEAR_METHOD
elif surrogate_model == SGDExplainableModel:
return SGD_METHOD
elif surrogate_model == DecisionTreeExplainableModel:
return TREE_METHOD
else:
raise Exception("Unsupported surrogate model")
def create_binary_sparse_newsgro... | 64 | 64 | 199 | 9 | 55 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_binary_sparse_newsgroups_data | create_binary_sparse_newsgroups_data | 73 | 87 | 73 | 73 | 06f6c9ba049896be434df786e4305a554ff90f04 | bigcode/the-stack | train |
1fe25c72bcaea9623d32d017 | train | function | def create_pytorch_classifier(X, y):
# create simple (dummy) Pytorch DNN model for binary classification
epochs = 12
torch_X = torch.Tensor(X).float()
torch_y = torch.Tensor(y).long()
# Create network structure
net = _common_pytorch_generator(X.shape[1], num_classes=2)
# Train the model
... | def create_pytorch_classifier(X, y):
# create simple (dummy) Pytorch DNN model for binary classification
| epochs = 12
torch_X = torch.Tensor(X).float()
torch_y = torch.Tensor(y).long()
# Create network structure
net = _common_pytorch_generator(X.shape[1], num_classes=2)
# Train the model
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(net.parameters(), lr=0.01)
return _trai... | metrics=['accuracy'])
model.fit(X, y,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(X, y))
return model
def create_pytorch_classifier(X, y):
# create simple (dummy) Pytorch DNN model for binary classification
| 64 | 64 | 127 | 25 | 38 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_pytorch_classifier | create_pytorch_classifier | 415 | 425 | 415 | 416 | 40bd74eb7f03f488ac03d0513e6fa04365dfd008 | bigcode/the-stack | train |
605ca60f56ec2c7bdcad176a | train | function | def create_xgboost_classifier(X, y):
xgb = XGBClassifier(learning_rate=0.1, max_depth=3, n_estimators=100,
n_jobs=1, random_state=777)
model = xgb.fit(X, y)
return model
| def create_xgboost_classifier(X, y):
| xgb = XGBClassifier(learning_rate=0.1, max_depth=3, n_estimators=100,
n_jobs=1, random_state=777)
model = xgb.fit(X, y)
return model
| MRegressor(boosting_type='gbdt', learning_rate=0.1,
max_depth=5, n_estimators=200, n_jobs=1, random_state=777)
model = lgbm.fit(X, y)
return model
def create_xgboost_classifier(X, y):
| 64 | 64 | 61 | 10 | 53 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_xgboost_classifier | create_xgboost_classifier | 150 | 154 | 150 | 150 | 92a33d2dc1591ffc3cdd61266372d739205970ff | bigcode/the-stack | train |
78eca657459ff36a7f041428 | train | function | def create_complex_titanic_data():
titanic_url = ('https://raw.githubusercontent.com/amueller/'
'scipy-2017-sklearn/091d371/notebooks/datasets/titanic3.csv')
data = read_csv(titanic_url)
X = data.drop('survived', axis=1)
y = data['survived']
return train_test_split(X, y, test_siz... | def create_complex_titanic_data():
| titanic_url = ('https://raw.githubusercontent.com/amueller/'
'scipy-2017-sklearn/091d371/notebooks/datasets/titanic3.csv')
data = read_csv(titanic_url)
X = data.drop('survived', axis=1)
y = data['survived']
return train_test_split(X, y, test_size=0.2, random_state=42)
| + numeric_features]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
return X_train, X_test, y_train, y_test, numeric_features, categorical_features
def create_complex_titanic_data():
| 64 | 64 | 101 | 8 | 55 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_complex_titanic_data | create_complex_titanic_data | 630 | 637 | 630 | 630 | 08443656944842fc97f2e303996264728d6568c3 | bigcode/the-stack | train |
7c6b416372f9b749817c8575 | train | function | def _common_pytorch_generator(numCols, num_classes=None):
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# Apply layer normalization for stability and perf on wide variety of datasets
# https://arxiv.org/pdf/1607.06450.pdf
self.norm = nn... | def _common_pytorch_generator(numCols, num_classes=None):
| class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# Apply layer normalization for stability and perf on wide variety of datasets
# https://arxiv.org/pdf/1607.06450.pdf
self.norm = nn.LayerNorm(numCols)
self.fc1 = nn.Linear(numCo... | ))
model_func = create_scikit_keras_model_func(X.shape[1], num_classes=num_classes)
model = KerasClassifier(build_fn=model_func, nb_epoch=epochs, batch_size=batch_size, verbose=1)
model.fit(X, y)
return model
def _common_pytorch_generator(numCols, num_classes=None):
| 71 | 71 | 239 | 13 | 57 | microsoft/ml-wrappers | tests/common_utils.py | Python | _common_pytorch_generator | _common_pytorch_generator | 315 | 340 | 315 | 315 | fc5e634bc2af77834bfe7b2fb6fa00051156f32a | bigcode/the-stack | train |
0445aad96dfeef6ca9a16885 | train | function | def get_mimic_method(surrogate_model):
from interpret_community.mimic.models.lightgbm_model import \
LGBMExplainableModel
from interpret_community.mimic.models.linear_model import (
LinearExplainableModel, SGDExplainableModel)
from interpret_community.mimic.models.tree_model import \
... | def get_mimic_method(surrogate_model):
| from interpret_community.mimic.models.lightgbm_model import \
LGBMExplainableModel
from interpret_community.mimic.models.linear_model import (
LinearExplainableModel, SGDExplainableModel)
from interpret_community.mimic.models.tree_model import \
DecisionTreeExplainableModel
if su... | import retrieve_dataset
from pandas import read_csv
LIGHTGBM_METHOD = 'mimic.lightgbm'
LINEAR_METHOD = 'mimic.linear'
SGD_METHOD = 'mimic.sgd'
TREE_METHOD = 'mimic.tree'
def get_mimic_method(surrogate_model):
| 64 | 64 | 155 | 11 | 53 | microsoft/ml-wrappers | tests/common_utils.py | Python | get_mimic_method | get_mimic_method | 54 | 70 | 54 | 54 | c2480e64c385fd4abba7ea09e5b7048ce588be01 | bigcode/the-stack | train |
37ae15fa7d6e7bb69b44898a | train | function | def create_pandas_only_svm_classifier(X, y, probability=True):
class PandasOnlyEstimator(TransformerMixin):
def fit(self, X, y=None, **fitparams):
return self
def transform(self, X, **transformparams):
dataset_is_df = isinstance(X, pd.DataFrame)
if not dataset_is... | def create_pandas_only_svm_classifier(X, y, probability=True):
| class PandasOnlyEstimator(TransformerMixin):
def fit(self, X, y=None, **fitparams):
return self
def transform(self, X, **transformparams):
dataset_is_df = isinstance(X, pd.DataFrame)
if not dataset_is_df:
raise Exception("Dataset must be a pandas ... | more information on how to install it.",
ImportWarning)
clf = cuml.svm.SVC(gamma=0.001, C=100., probability=True)
model = clf.fit(X, y)
return model
def create_pandas_only_svm_classifier(X, y, probability=True):
| 64 | 64 | 150 | 15 | 48 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_pandas_only_svm_classifier | create_pandas_only_svm_classifier | 185 | 200 | 185 | 185 | 6ac4cbbb7012e49f0d4d18bd9c7d9cb283fc936c | bigcode/the-stack | train |
bb3f0babfb676b0862131dd7 | train | function | def create_linear_vectorizer():
vectorizer = CountVectorizer(lowercase=False, min_df=0.0, binary=True)
lr = LinearRegression()
return Pipeline([('vectorizer', vectorizer), ('lr', lr)])
| def create_linear_vectorizer():
| vectorizer = CountVectorizer(lowercase=False, min_df=0.0, binary=True)
lr = LinearRegression()
return Pipeline([('vectorizer', vectorizer), ('lr', lr)])
| rf)])
def create_logistic_vectorizer():
vectorizer = CountVectorizer(lowercase=False, min_df=0.0, binary=True)
lr = LogisticRegression(random_state=777)
return Pipeline([('vectorizer', vectorizer), ('lr', lr)])
def create_linear_vectorizer():
| 63 | 64 | 49 | 6 | 57 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_linear_vectorizer | create_linear_vectorizer | 124 | 127 | 124 | 124 | 440e3a4762e863a57f8d9cdb9534babf9f0844a5 | bigcode/the-stack | train |
948a3b43ddaeffa363bb216d | train | function | def create_simple_titanic_data():
titanic_url = ('https://raw.githubusercontent.com/amueller/'
'scipy-2017-sklearn/091d371/notebooks/datasets/titanic3.csv')
data = read_csv(titanic_url)
# fill missing values
data = data.fillna(method="ffill")
data = data.fillna(method="bfill")
... | def create_simple_titanic_data():
| titanic_url = ('https://raw.githubusercontent.com/amueller/'
'scipy-2017-sklearn/091d371/notebooks/datasets/titanic3.csv')
data = read_csv(titanic_url)
# fill missing values
data = data.fillna(method="ffill")
data = data.fillna(method="bfill")
numeric_features = ['age', 'fare'... | '] is None or not paper['review']:
continue
reviews.append(paper['review'][0]['text'])
evaluation.append(paper['review'][0]['evaluation'])
return train_test_split(reviews, evaluation, test_size=test_size, random_state=7)
def create_simple_titanic_data():
| 64 | 64 | 184 | 8 | 56 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_simple_titanic_data | create_simple_titanic_data | 613 | 627 | 613 | 613 | 53fa62054a058fd7135bf33a381fe9db7c80d8a2 | bigcode/the-stack | train |
4dcc7243a595c1bf94184572 | train | function | def assert_batch_equal(actual, expected):
"""Assert that two batch datasets are equal.
:param actual: The actual batch dataset.
:type actual: BatchDataset
:param expected: The expected batch dataset.
:type expected: BatchDataset
"""
zipped_batches = zip(actual, expected)
for ((c_data, c... | def assert_batch_equal(actual, expected):
| """Assert that two batch datasets are equal.
:param actual: The actual batch dataset.
:type actual: BatchDataset
:param expected: The expected batch dataset.
:type expected: BatchDataset
"""
zipped_batches = zip(actual, expected)
for ((c_data, c_label), (data, label)) in zipped_batches:... | sr_matrix
"""
assert actual.shape == expected.shape
assert actual.dtype == expected.dtype
assert np.array_equal(actual.indptr, expected.indptr)
assert np.array_equal(actual.indices, expected.indices)
assert np.array_equal(actual.data, expected.data)
def assert_batch_equal(actual, expected):
| 64 | 64 | 103 | 8 | 56 | microsoft/ml-wrappers | tests/common_utils.py | Python | assert_batch_equal | assert_batch_equal | 682 | 693 | 682 | 682 | a84ede2c54ab9c67eb03b7f7775407aab1aee598 | bigcode/the-stack | train |
790bffc20f95a749a096c791 | train | function | def create_cancer_data_booleans():
# Import cancer dataset
cancer = retrieve_dataset('breast-cancer.train.csv', na_values='?').interpolate().astype('int64')
cancer_target = cancer.iloc[:, 0]
cancer_data = cancer.iloc[:, 1:]
feature_names = cancer_data.columns.values
target_names = [False, True]
... | def create_cancer_data_booleans():
# Import cancer dataset
| cancer = retrieve_dataset('breast-cancer.train.csv', na_values='?').interpolate().astype('int64')
cancer_target = cancer.iloc[:, 0]
cancer_data = cancer.iloc[:, 1:]
feature_names = cancer_data.columns.values
target_names = [False, True]
cancer_target = cancer_target.astype(bool)
# Split data... | y_train, y_validation = train_test_split(cancer_data, cancer_target,
test_size=0.2, random_state=0)
return x_train, x_test, y_train, y_validation, feature_names, target_names
def create_cancer_data_booleans():
# Import cancer dataset
| 64 | 64 | 153 | 15 | 48 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_cancer_data_booleans | create_cancer_data_booleans | 543 | 554 | 543 | 544 | 2e0b339d8b61943a0a158c49ec39956c5a298c67 | bigcode/the-stack | train |
d8d1dfb15f32313e69606765 | train | function | def create_pytorch_regressor(X, y):
# create simple (dummy) Pytorch DNN model for regression
epochs = 12
if isinstance(X, pd.DataFrame):
X = X.values
torch_X = torch.Tensor(X).float()
torch_y = torch.Tensor(y).float()
# Create network structure
net = _common_pytorch_generator(X.shape... | def create_pytorch_regressor(X, y):
# create simple (dummy) Pytorch DNN model for regression
| epochs = 12
if isinstance(X, pd.DataFrame):
X = X.values
torch_X = torch.Tensor(X).float()
torch_y = torch.Tensor(y).float()
# Create network structure
net = _common_pytorch_generator(X.shape[1])
# Train the model
criterion = nn.MSELoss()
optimizer = torch.optim.SGD(net.param... | _X)
loss = criterion(out, torch_y)
loss.backward()
optimizer.step()
print('epoch: ', epoch, ' loss: ', loss.data.item())
return net
def create_pytorch_regressor(X, y):
# create simple (dummy) Pytorch DNN model for regression
| 64 | 64 | 138 | 25 | 38 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_pytorch_regressor | create_pytorch_regressor | 354 | 366 | 354 | 355 | a9e3e441c49b752fddcff844ddf3b134ff957a11 | bigcode/the-stack | train |
aa4b1df74992172847be21c4 | train | function | def create_lightgbm_regressor(X, y):
lgbm = LGBMRegressor(boosting_type='gbdt', learning_rate=0.1,
max_depth=5, n_estimators=200, n_jobs=1, random_state=777)
model = lgbm.fit(X, y)
return model
| def create_lightgbm_regressor(X, y):
| lgbm = LGBMRegressor(boosting_type='gbdt', learning_rate=0.1,
max_depth=5, n_estimators=200, n_jobs=1, random_state=777)
model = lgbm.fit(X, y)
return model
| MClassifier(boosting_type='gbdt', learning_rate=0.1,
max_depth=5, n_estimators=200, n_jobs=1, random_state=777)
model = lgbm.fit(X, y)
return model
def create_lightgbm_regressor(X, y):
| 64 | 64 | 72 | 11 | 52 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_lightgbm_regressor | create_lightgbm_regressor | 143 | 147 | 143 | 143 | 52c0ca7cff5d3a4466cc60773ed2cb7304e6603e | bigcode/the-stack | train |
c6d714584299d0523b6baf94 | train | function | def create_iris_data():
# Import Iris dataset
iris = load_iris()
# Split data into train and test
x_train, x_test, y_train, y_validation = train_test_split(iris.data, iris.target,
test_size=0.2, random_state=0)
feature_names = [name.repla... | def create_iris_data():
# Import Iris dataset
| iris = load_iris()
# Split data into train and test
x_train, x_test, y_train, y_validation = train_test_split(iris.data, iris.target,
test_size=0.2, random_state=0)
feature_names = [name.replace(' (cm)', '') for name in iris.feature_names]
... | classification
model = _common_model_generator(feature_number)
model.add(Activation('sigmoid'))
model.compile(loss=keras.losses.binary_crossentropy,
optimizer=keras.optimizers.Adadelta(),
metrics=['accuracy'])
return model
def create_iris_data():
# Import Iris da... | 64 | 64 | 104 | 12 | 51 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_iris_data | create_iris_data | 498 | 505 | 498 | 499 | 0eae4af10010d1ddb948b175deb0407bde1e859d | bigcode/the-stack | train |
05dfbfc37311ff8d424f0ee6 | train | function | def create_scikit_keras_regressor(X, y):
# create simple (dummy) Keras DNN model for regression
batch_size = 500
epochs = 10
model_func = create_scikit_keras_model_func(X.shape[1])
model = KerasRegressor(build_fn=model_func, nb_epoch=epochs, batch_size=batch_size, verbose=1)
model.fit(X, y)
... | def create_scikit_keras_regressor(X, y):
# create simple (dummy) Keras DNN model for regression
| batch_size = 500
epochs = 10
model_func = create_scikit_keras_model_func(X.shape[1])
model = KerasRegressor(build_fn=model_func, nb_epoch=epochs, batch_size=batch_size, verbose=1)
model.fit(X, y)
return model
| =keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.Adadelta(),
metrics=['accuracy'])
return model
return common_scikit_keras_model
def create_scikit_keras_regressor(X, y):
# create simple (dummy) Keras DNN model for regression
| 64 | 64 | 93 | 27 | 36 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_scikit_keras_regressor | create_scikit_keras_regressor | 284 | 291 | 284 | 285 | c56b1b51eef004950b5f762b65536142ca4f235d | bigcode/the-stack | train |
20ca03af96aee983db080cbb | train | function | def create_energy_data():
# Import energy data
energy_data = retrieve_dataset('energyefficiency2012_data.train.csv')
# Get the Y1 column
target = energy_data.iloc[:, len(energy_data.columns) - 2]
energy_data = energy_data.iloc[:, :len(energy_data.columns) - 3]
feature_names = energy_data.columns... | def create_energy_data():
# Import energy data
| energy_data = retrieve_dataset('energyefficiency2012_data.train.csv')
# Get the Y1 column
target = energy_data.iloc[:, len(energy_data.columns) - 2]
energy_data = energy_data.iloc[:, :len(energy_data.columns) - 3]
feature_names = energy_data.columns.values
# Split data into train and test
x_... | test_size=0.2, random_state=0)
feature_names = [name.replace(' (cm)', '') for name in iris.feature_names]
return x_train, x_test, y_train, y_validation, feature_names, iris.target_names
def create_energy_data():
# Import energy data
| 64 | 64 | 142 | 11 | 52 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_energy_data | create_energy_data | 508 | 518 | 508 | 509 | bf318781bf0a9194e29eb6c7b2859c46d51ecde8 | bigcode/the-stack | train |
3ff5705dddb0897910d0419a | train | function | def create_tf_model(inp_ds, val_ds, feature_names):
"""Create a simple TF model for regression.
:param inp_ds: input data set.
:type inp_ds: BatchDataset
:param val_ds: validation data set.
:type val_ds: BatchDataset
:param feature_names: list of feature names.
:type feature_names: list
... | def create_tf_model(inp_ds, val_ds, feature_names):
| """Create a simple TF model for regression.
:param inp_ds: input data set.
:type inp_ds: BatchDataset
:param val_ds: validation data set.
:type val_ds: BatchDataset
:param feature_names: list of feature names.
:type feature_names: list
:return: a TF model.
:rtype: tf.keras.Model
... | ])
# Train the model
criterion = nn.MSELoss()
optimizer = torch.optim.SGD(net.parameters(), lr=0.0001)
return _train_pytorch_model(epochs, criterion, optimizer, net, torch_X, torch_y)
def create_tf_model(inp_ds, val_ds, feature_names):
| 67 | 67 | 224 | 13 | 54 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_tf_model | create_tf_model | 369 | 395 | 369 | 369 | 99aae2ebd3014f1ebc457cc53905c568f01eff65 | bigcode/the-stack | train |
bfc9ad4f006e5246e313a32e | train | function | def create_sklearn_logistic_regressor(X, y, pipeline=False):
lin = linear_model.LogisticRegression(solver='liblinear')
if pipeline:
lin = Pipeline([('lin', lin)])
model = lin.fit(X, y)
return model
| def create_sklearn_logistic_regressor(X, y, pipeline=False):
| lin = linear_model.LogisticRegression(solver='liblinear')
if pipeline:
lin = Pipeline([('lin', lin)])
model = lin.fit(X, y)
return model
| _linear_regressor(X, y, pipeline=False):
lin = linear_model.LinearRegression(normalize=True)
if pipeline:
lin = Pipeline([('lin', lin)])
model = lin.fit(X, y)
return model
def create_sklearn_logistic_regressor(X, y, pipeline=False):
| 64 | 64 | 57 | 16 | 47 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_sklearn_logistic_regressor | create_sklearn_logistic_regressor | 237 | 242 | 237 | 237 | 9300bfd3fd3b6401381084ed5a614c30e986cc6e | bigcode/the-stack | train |
b4c287a05f8bc47224f6a6c3 | train | function | def create_sklearn_random_forest_classifier(X, y):
rfc = ensemble.RandomForestClassifier(n_estimators=10, max_depth=4, random_state=777)
model = rfc.fit(X, y)
return model
| def create_sklearn_random_forest_classifier(X, y):
| rfc = ensemble.RandomForestClassifier(n_estimators=10, max_depth=4, random_state=777)
model = rfc.fit(X, y)
return model
| )
def create_linear_vectorizer():
vectorizer = CountVectorizer(lowercase=False, min_df=0.0, binary=True)
lr = LinearRegression()
return Pipeline([('vectorizer', vectorizer), ('lr', lr)])
def create_sklearn_random_forest_classifier(X, y):
| 63 | 64 | 51 | 13 | 50 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_sklearn_random_forest_classifier | create_sklearn_random_forest_classifier | 130 | 133 | 130 | 130 | 86adeb469474c7c67d137aceccd10c4466b0bd7c | bigcode/the-stack | train |
4e24308a91e7b643529a32c0 | train | function | def create_multiclass_sparse_newsgroups_data():
remove = ('headers', 'footers', 'quotes')
categories = ['alt.atheism', 'talk.religion.misc', 'comp.graphics', 'sci.space']
from sklearn.datasets import fetch_20newsgroups
ngroups = fetch_20newsgroups(subset='train', categories=categories,
... | def create_multiclass_sparse_newsgroups_data():
| remove = ('headers', 'footers', 'quotes')
categories = ['alt.atheism', 'talk.religion.misc', 'comp.graphics', 'sci.space']
from sklearn.datasets import fetch_20newsgroups
ngroups = fetch_20newsgroups(subset='train', categories=categories,
shuffle=True, random_state=42, r... | ', alternate_sign=False,
n_features=2**16)
x_train = vectorizer.transform(x_train)
x_test = vectorizer.transform(x_test)
return x_train, x_test, y_train, y_validation, class_names, vectorizer
def create_multiclass_sparse_newsgroups_data():
| 64 | 64 | 208 | 11 | 52 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_multiclass_sparse_newsgroups_data | create_multiclass_sparse_newsgroups_data | 90 | 103 | 90 | 90 | c71b9404b106fc48b195c9e324fca910ed33f7c8 | bigcode/the-stack | train |
95be35d708207de8318e5c5a | train | function | def create_pytorch_multiclass_classifier(X, y):
# Get unique number of classes
num_classes = np.unique(y).shape[0]
# create simple (dummy) Pytorch DNN model for multiclass classification
epochs = 12
torch_X = torch.Tensor(X).float()
torch_y = torch.Tensor(y).long()
# Create network structure... | def create_pytorch_multiclass_classifier(X, y):
# Get unique number of classes
| num_classes = np.unique(y).shape[0]
# create simple (dummy) Pytorch DNN model for multiclass classification
epochs = 12
torch_X = torch.Tensor(X).float()
torch_y = torch.Tensor(y).long()
# Create network structure
net = _common_pytorch_generator(X.shape[1], num_classes=num_classes)
# Tra... | _categorical(y, num_classes)
model.fit(X, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(X, y_train))
return model
def create_pytorch_multiclass_classifier(X, y):
# Get unique number of classes
| 64 | 64 | 151 | 20 | 43 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_pytorch_multiclass_classifier | create_pytorch_multiclass_classifier | 473 | 485 | 473 | 474 | afc65dffadecc6b8fa1e3b61c725ef32b478b849 | bigcode/the-stack | train |
0a37835d457ed16588da08d1 | train | function | def create_pytorch_single_output_classifier(X, y):
# create simple (dummy) Pytorch DNN model for binary classification that only outputs
# the probabilities for the positive class
epochs = 100
torch_X = torch.Tensor(X).float()
torch_y = torch.Tensor(y).float()
class Net(nn.Module):
def ... | def create_pytorch_single_output_classifier(X, y):
# create simple (dummy) Pytorch DNN model for binary classification that only outputs
# the probabilities for the positive class
| epochs = 100
torch_X = torch.Tensor(X).float()
torch_y = torch.Tensor(y).float()
class Net(nn.Module):
def __init__(self, input_shape):
super(Net, self).__init__()
self.fc1 = nn.Linear(input_shape, 32)
self.fc2 = nn.Linear(32, 64)
self.fc3 = nn.Li... | GD(net.parameters(), lr=0.01)
return _train_pytorch_model(epochs, criterion, optimizer, net, torch_X, torch_y)
def create_pytorch_single_output_classifier(X, y):
# create simple (dummy) Pytorch DNN model for binary classification that only outputs
# the probabilities for the positive class
| 71 | 71 | 238 | 39 | 32 | microsoft/ml-wrappers | tests/common_utils.py | Python | create_pytorch_single_output_classifier | create_pytorch_single_output_classifier | 428 | 452 | 428 | 430 | 46a6d3ceca438d231bff84a07c05a9caa53c1ac2 | bigcode/the-stack | train |
75abeac4275bdfd3f3358023 | train | function | def compute_angle(residue_pair: Tuple[Residue]) -> float:
"""
Compute the angle between two residues. The angle is estimated as the cosine
inverse of the dot product between the normal vectors of the two residues. The
angle is normalized by dividing it by 2 * \pi
Parameters
----------
resid... | def compute_angle(residue_pair: Tuple[Residue]) -> float:
| """
Compute the angle between two residues. The angle is estimated as the cosine
inverse of the dot product between the normal vectors of the two residues. The
angle is normalized by dividing it by 2 * \pi
Parameters
----------
residue_pair: Tuple[Residue]
The pair of residues betwe... | ac = x_ca - x_c
normal = np.cross(x_oc, x_cac)
normal /= (np.sqrt(np.sum(normal**2) + 1e-8)) # Normalize by length
return normal
def compute_angle(residue_pair: Tuple[Residue]) -> float:
| 64 | 64 | 160 | 15 | 48 | vsomnath/holoprot | holoprot/feat/complex.py | Python | compute_angle | compute_angle | 208 | 228 | 208 | 208 | 4ee51be7065da0c831589950a779d5059c94b818 | bigcode/the-stack | train |
7c0e44b55befa8d808787536 | train | function | def onek_encoding_unk(x: Any, allowable_set: Union[List, Set]) -> List:
"""Converts x to one hot encoding.
Parameters
----------
x: Any,
An element of any type
allowable_set: Union[List, Set]
Allowable element collection
Returns
-------
list, indicating the one hot enco... | def onek_encoding_unk(x: Any, allowable_set: Union[List, Set]) -> List:
| """Converts x to one hot encoding.
Parameters
----------
x: Any,
An element of any type
allowable_set: Union[List, Set]
Allowable element collection
Returns
-------
list, indicating the one hot encoding of x in allowable_set
"""
if x not in allowable_set:
... | rdkit.Chem.Bond
"""
self.bond_type = bond.GetBondType()
self.is_conj = bond.GetIsConjugated()
self.is_ring = bond.IsInRing()
def onek_encoding_unk(x: Any, allowable_set: Union[List, Set]) -> List:
| 64 | 64 | 115 | 21 | 43 | vsomnath/holoprot | holoprot/feat/complex.py | Python | onek_encoding_unk | onek_encoding_unk | 83 | 99 | 83 | 83 | 19d6acdd7d523bf34eb4d826e8260e58682d4301 | bigcode/the-stack | train |
4bf5c6c4d9e745518f0528a5 | train | class | class ResidueProp(object):
"""Wrapper class that holds all attributes of a protein residue."""
def __init__(self,
residue: Residue,
sec: str,
sas: float,
hydrophobicity: float,
res_depth: float = None,
ca_dept... | class ResidueProp(object):
| """Wrapper class that holds all attributes of a protein residue."""
def __init__(self,
residue: Residue,
sec: str,
sas: float,
hydrophobicity: float,
res_depth: float = None,
ca_depth: float = None) -> None:
... | , ATOM_FDIM
from holoprot.feat import BOND_FDIM, BOND_TYPES
idxfunc = lambda a: a.GetAtomMapNum() - 1
bond_idx_fn = lambda a, b, mol: mol.GetBondBetweenAtoms(a.GetIdx(), b.GetIdx()).GetIdx()
class ResidueProp(object):
| 71 | 71 | 238 | 6 | 65 | vsomnath/holoprot | holoprot/feat/complex.py | Python | ResidueProp | ResidueProp | 18 | 48 | 18 | 18 | 6ed99db7329e2e6ca0e98c68df4c605f9abbe4c1 | bigcode/the-stack | train |
3d1dfea134d8987fa78e23a0 | train | class | class AtomProp(object):
"""Wrapper class that holds all properties of an atom."""
def __init__(self, atom: Chem.Atom) -> None:
"""
Parameters
----------
atom: Chem.Atom,
Instance of rdkit.Chem.Atom
"""
self.symbol = atom.GetSymbol()
self.degre... | class AtomProp(object):
| """Wrapper class that holds all properties of an atom."""
def __init__(self, atom: Chem.Atom) -> None:
"""
Parameters
----------
atom: Chem.Atom,
Instance of rdkit.Chem.Atom
"""
self.symbol = atom.GetSymbol()
self.degree = atom.GetDegree()
... | = residue.get_resname()
self.sec = sec
self.sas = sas
self.res_depth = res_depth
self.ca_depth = ca_depth
self.hydrophobicity = hydrophobicity # Hydrophobicity using the Kyte-Doolittle scale
class AtomProp(object):
| 64 | 64 | 111 | 5 | 58 | vsomnath/holoprot | holoprot/feat/complex.py | Python | AtomProp | AtomProp | 51 | 65 | 51 | 51 | 17fb71d74e3a19e38e4c25d6fd0ebf780a42970c | bigcode/the-stack | train |
309375919754c0c72b9a4bf7 | train | function | def get_atom_features(atom_prop: AtomProp, **kwargs) -> np.ndarray:
"""
Get atom features. The atom features computed
Parameters
----------
atom: Chem.Atom,
Atom object from RDKit
Returns
-------
atom_features: np.ndarray,
Array of atom features
"""
if atom_prop... | def get_atom_features(atom_prop: AtomProp, **kwargs) -> np.ndarray:
| """
Get atom features. The atom features computed
Parameters
----------
atom: Chem.Atom,
Atom object from RDKit
Returns
-------
atom_features: np.ndarray,
Array of atom features
"""
if atom_prop == "*":
return np.array([0] * ATOM_FDIM)
atom_features ... | list, indicating the one hot encoding of x in allowable_set
"""
if x not in allowable_set:
x = allowable_set[-1]
return list(map(lambda s: float(x == s), allowable_set))
def get_atom_features(atom_prop: AtomProp, **kwargs) -> np.ndarray:
| 64 | 64 | 173 | 17 | 47 | vsomnath/holoprot | holoprot/feat/complex.py | Python | get_atom_features | get_atom_features | 102 | 124 | 102 | 102 | 836da376ae8f4182624ad0af47a6c094088628b7 | bigcode/the-stack | train |
2ebee91ace44eccd03168e93 | train | function | def get_contact_features(residue_pair: Tuple[Residue],
mode: str = 'ca',
sigma: float = 0.01,
**kwargs) -> np.ndarray:
"""
Gets contact features. The features computed are the RBF kernel over the
distance between residues and the ang... | def get_contact_features(residue_pair: Tuple[Residue],
mode: str = 'ca',
sigma: float = 0.01,
**kwargs) -> np.ndarray:
| """
Gets contact features. The features computed are the RBF kernel over the
distance between residues and the angle between the residues. The RBF kernel's
width is modulated by the parameter `sigma`, and the mode to compute distance
is controlled by `mode` argument.
Parameters
----------
... | residues between which we want to estimate the angle.
Returns
-------
normalized angle (float) between the residues
"""
res_i, res_j = residue_pair
norm_i = compute_normal(res_i)
norm_j = compute_normal(res_j)
angle = np.arccos(norm_i.dot(norm_j))
return angle / (2 * np.pi)
def ge... | 117 | 117 | 390 | 39 | 78 | vsomnath/holoprot | holoprot/feat/complex.py | Python | get_contact_features | get_contact_features | 231 | 280 | 231 | 234 | 9e03b47f5c4c065cd8441f8ecc1ca0a94ac84410 | bigcode/the-stack | train |
5153ab6e40db966bc02fad5d | train | function | def get_bond_features(bond_prop: BondProp, **kwargs) -> np.ndarray:
"""
Get bond features. Features computed are a one hot encoding of the bond type,
its aromaticity and ring membership.
Parameters
----------
bond: Chem.Bond,
bond object
Returns
-------
bond_features: np.nd... | def get_bond_features(bond_prop: BondProp, **kwargs) -> np.ndarray:
| """
Get bond features. Features computed are a one hot encoding of the bond type,
its aromaticity and ring membership.
Parameters
----------
bond: Chem.Bond,
bond object
Returns
-------
bond_features: np.ndarray,
Array of bond features
"""
if bond_prop == "*... | _encoding_unk(atom_prop.exp_valence, EXP_VALENCE) +
onek_encoding_unk(atom_prop.imp_valence, IMP_VALENCE) +
[float(atom_prop.is_aromatic)])
return atom_features
def get_bond_features(bond_prop: BondProp, **kwargs) -> np.ndarray:
| 64 | 64 | 173 | 19 | 44 | vsomnath/holoprot | holoprot/feat/complex.py | Python | get_bond_features | get_bond_features | 127 | 148 | 127 | 127 | 078a700db125324bceef8a27eb8263fde46a9682 | bigcode/the-stack | train |
60e24f5f872265a6feeeb75b | train | function | def get_residue_features(residue_prop: ResidueProp,
use_depth: bool = False,
**kwargs) -> np.ndarray:
"""Get residue features.
Parameters
----------
residue_prop: ResidueProp
Instance of the ResidueProp class that captures properties of a residu... | def get_residue_features(residue_prop: ResidueProp,
use_depth: bool = False,
**kwargs) -> np.ndarray:
| """Get residue features.
Parameters
----------
residue_prop: ResidueProp
Instance of the ResidueProp class that captures properties of a residue
Returns
-------
res_features: np.ndarray,
Array of residue features
"""
if residue_prop == "*":
if use_depth:
... | _TYPES[1:]]
bond_features.extend([float(bond_prop.is_conj), float(bond_prop.is_ring)])
bond_features = np.array(bond_features, dtype=np.float32)
return bond_features
def get_residue_features(residue_prop: ResidueProp,
use_depth: bool = False,
**kwargs) -> np... | 74 | 74 | 248 | 29 | 44 | vsomnath/holoprot | holoprot/feat/complex.py | Python | get_residue_features | get_residue_features | 151 | 179 | 151 | 153 | 73fdbd8e94d7be8044db99f5d84e0f8077fa4c71 | bigcode/the-stack | train |
1726fff8b707bfcfabf9aae9 | train | class | class BondProp(object):
"""Wrapper class that holds all properties of a bond."""
def __init__(self, bond: Chem.Bond) -> None:
"""
Parameters
----------
bond: Chem.Bond,
Instance of rdkit.Chem.Bond
"""
self.bond_type = bond.GetBondType()
self.i... | class BondProp(object):
| """Wrapper class that holds all properties of a bond."""
def __init__(self, bond: Chem.Bond) -> None:
"""
Parameters
----------
bond: Chem.Bond,
Instance of rdkit.Chem.Bond
"""
self.bond_type = bond.GetBondType()
self.is_conj = bond.GetIsConju... | .Chem.Atom
"""
self.symbol = atom.GetSymbol()
self.degree = atom.GetDegree()
self.exp_valence = atom.GetExplicitValence()
self.imp_valence = atom.GetImplicitValence()
self.is_aromatic = atom.GetIsAromatic()
class BondProp(object):
| 64 | 64 | 93 | 5 | 59 | vsomnath/holoprot | holoprot/feat/complex.py | Python | BondProp | BondProp | 68 | 80 | 68 | 68 | 5e6f84c66ee89187a7c474f0fc8029d9cf66fe97 | bigcode/the-stack | train |
c5c1b5e9ae61571d5bccdcec | train | function | def get_secondary_struct_features(pdb_file: str,
dssp_bin: str = 'dssp') -> Dict[str, List]:
"""Compute secondary structure features for the protein using DSSP.
Parameters
----------
pdb_file: str,
PDB file for the protein.
dssp_bin: str,
Path to th... | def get_secondary_struct_features(pdb_file: str,
dssp_bin: str = 'dssp') -> Dict[str, List]:
| """Compute secondary structure features for the protein using DSSP.
Parameters
----------
pdb_file: str,
PDB file for the protein.
dssp_bin: str,
Path to the DSSP binary executable
Returns
-------
dssp_dict: Dict[str, List]
Dictionary containing the secondary st... | np.sum(y**2) / sigma**2)
angle = compute_angle(residue_pair)
edge_features = np.array([dist, angle])
return edge_features
def get_secondary_struct_features(pdb_file: str,
dssp_bin: str = 'dssp') -> Dict[str, List]:
| 64 | 64 | 132 | 28 | 35 | vsomnath/holoprot | holoprot/feat/complex.py | Python | get_secondary_struct_features | get_secondary_struct_features | 283 | 300 | 283 | 284 | 4b18c84da9a85f4049dc852c1a06c038717b788b | bigcode/the-stack | train |
ea3dda77f5c3943fff0ec7e6 | train | function | def compute_normal(residue: Residue) -> np.ndarray:
"""
Compute the normal vector for a given residue. The normal vector is estimated
as the cross product of the vectors formed by the difference of Calpha, C and
O coordinates. The normal vector is length normalized to get a unit vector.
Parameters
... | def compute_normal(residue: Residue) -> np.ndarray:
| """
Compute the normal vector for a given residue. The normal vector is estimated
as the cross product of the vectors formed by the difference of Calpha, C and
O coordinates. The normal vector is length normalized to get a unit vector.
Parameters
----------
residue: Residue,
Residue... | \
[residue_prop.sas, residue_prop.hydrophobicity]
if use_depth:
res_features.extend([residue_prop.res_depth, residue_prop.ca_depth])
res_features = np.array(res_features)
return res_features
def compute_normal(residue: Residue) -> np.ndarray:
| 64 | 64 | 204 | 13 | 50 | vsomnath/holoprot | holoprot/feat/complex.py | Python | compute_normal | compute_normal | 182 | 205 | 182 | 182 | 09909ea80ece8bf9431e8900dcf91af057602530 | bigcode/the-stack | train |
28d3e6b25f3f04cf8681e571 | train | class | class Lrzip(Package):
"""A compression utility that excels at compressing large files
(usually > 10-50 MB). Larger files and/or more free RAM means that the
utility will be able to more effectively compress your files (ie: faster /
smaller size), especially if the filesize(s) exceed 100 MB. You can eith... | class Lrzip(Package):
| """A compression utility that excels at compressing large files
(usually > 10-50 MB). Larger files and/or more free RAM means that the
utility will be able to more effectively compress your files (ie: faster /
smaller size), especially if the filesize(s) exceed 100 MB. You can either
choose to optim... | # Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Lrzip(Package):
| 61 | 139 | 464 | 7 | 54 | adrianjhpc/spack | var/spack/repos/builtin/packages/lrzip/package.py | Python | Lrzip | Lrzip | 9 | 43 | 9 | 9 | 91f03406355c401476dacacf699228da250a2719 | bigcode/the-stack | train |
57d252eb5527773fbbebe0d9 | train | function | def test_tag_to_str():
assert str(Tag.CATEGORICAL) == "categorical"
| def test_tag_to_str():
| assert str(Tag.CATEGORICAL) == "categorical"
| language governing permissions and
# limitations under the License.
#
from merlin_standard_lib import Tag
def test_tag_equality():
assert Tag.CATEGORICAL == "categorical"
assert Tag.CONTINUOUS == "continuous"
assert Tag.ITEM_ID == "item_id"
def test_tag_to_str():
| 64 | 64 | 20 | 6 | 58 | Jwmc999/Transformers4Rec | tests/merlin_standard_lib/schema/test_tag.py | Python | test_tag_to_str | test_tag_to_str | 25 | 26 | 25 | 25 | 5151daf317008c845a2eafc0707bca00eb422537 | bigcode/the-stack | train |
0998ff451655f379bedf55ec | train | function | def test_tag_equality():
assert Tag.CATEGORICAL == "categorical"
assert Tag.CONTINUOUS == "continuous"
assert Tag.ITEM_ID == "item_id"
| def test_tag_equality():
| assert Tag.CATEGORICAL == "categorical"
assert Tag.CONTINUOUS == "continuous"
assert Tag.ITEM_ID == "item_id"
| software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from merlin_standard_lib import Tag
def test_tag_equality():
| 64 | 64 | 38 | 6 | 57 | Jwmc999/Transformers4Rec | tests/merlin_standard_lib/schema/test_tag.py | Python | test_tag_equality | test_tag_equality | 19 | 22 | 19 | 19 | a34d867754ebd5fb232e01356318aedcad01c21e | bigcode/the-stack | train |
e389c22978bad1a7eedb736f | train | class | class TCoffeeCommandline(AbstractCommandline):
"""Commandline object for the TCoffee alignment program.
http://www.tcoffee.org/Projects_home_page/t_coffee_home_page.html
The T-Coffee command line tool has a lot of switches and options.
This wrapper implements a VERY limited number of options - if you
... | class TCoffeeCommandline(AbstractCommandline):
| """Commandline object for the TCoffee alignment program.
http://www.tcoffee.org/Projects_home_page/t_coffee_home_page.html
The T-Coffee command line tool has a lot of switches and options.
This wrapper implements a VERY limited number of options - if you
would like to help improve it please get in... | # Copyright 2009 by Cymon J. Cox and Brad Chapman. All rights reserved.
#
# This file is part of the Biopython distribution and governed by your
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
# Please see the LICENSE file that should have been included as part of this
# package.
"""Command... | 113 | 256 | 874 | 9 | 103 | lukasz-kozlowski/biopython | Bio/Align/Applications/_TCoffee.py | Python | TCoffeeCommandline | TCoffeeCommandline | 13 | 119 | 13 | 13 | 3e042cfaea3a6acd871c10680c24327d0b1b15de | bigcode/the-stack | train |
52611e7443a7a0e837d91724 | train | class | class Migration(migrations.Migration):
dependencies = [
('nominations', '0055_auto_20170928_1553'),
]
operations = [
migrations.AddField(
model_name='application',
name='classification_level',
field=models.CharField(choices=[('1', 'I'), ('2', 'II'), ('3'... | class Migration(migrations.Migration):
| dependencies = [
('nominations', '0055_auto_20170928_1553'),
]
operations = [
migrations.AddField(
model_name='application',
name='classification_level',
field=models.CharField(choices=[('1', 'I'), ('2', 'II'), ('3', 'III')], default='1', max_length=64),
... | # -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2017-10-02 00:40
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
| 54 | 113 | 378 | 7 | 46 | JoshZero87/site | nominations/migrations/0056_auto_20171002_0040.py | Python | Migration | Migration | 8 | 55 | 8 | 9 | ef0ed5537e7c1629a368b8c108969a8d3092c485 | bigcode/the-stack | train |
71a3330a0823271aebe62b66 | train | function | def to_commands(module, commands):
if not isinstance(commands, list):
raise AssertionError('argument must be of type <list>')
transform = EntityCollection(module, command_spec)
commands = transform(commands)
for index, item in enumerate(commands):
if module.check_mode and not item['com... | def to_commands(module, commands):
| if not isinstance(commands, list):
raise AssertionError('argument must be of type <list>')
transform = EntityCollection(module, command_spec)
commands = transform(commands)
for index, item in enumerate(commands):
if module.check_mode and not item['command'].startswith('show'):
... | pec():
return ironware_provider_spec
def check_args(module):
pass
def get_connection(module):
global _CONNECTION
if _CONNECTION:
return _CONNECTION
_CONNECTION = Connection(module._socket_path)
return _CONNECTION
def to_commands(module, commands):
| 64 | 64 | 101 | 7 | 56 | gvashchenkolineate/gvashchenkolineate_infra_trytravis | ansible/venv/lib/python2.7/site-packages/ansible/module_utils/network/ironware/ironware.py | Python | to_commands | to_commands | 69 | 81 | 69 | 69 | 5db2674a56ad17fa2f8e690b1ab6fc453773eac5 | bigcode/the-stack | train |
cc8dec2a4b25ca1e83149764 | train | function | def get_connection(module):
global _CONNECTION
if _CONNECTION:
return _CONNECTION
_CONNECTION = Connection(module._socket_path)
return _CONNECTION
| def get_connection(module):
| global _CONNECTION
if _CONNECTION:
return _CONNECTION
_CONNECTION = Connection(module._socket_path)
return _CONNECTION
| dict(type='dict', options=ironware_provider_spec)
}
command_spec = {
'command': dict(key=True),
'prompt': dict(),
'answer': dict()
}
def get_provider_argspec():
return ironware_provider_spec
def check_args(module):
pass
def get_connection(module):
| 64 | 64 | 40 | 5 | 58 | gvashchenkolineate/gvashchenkolineate_infra_trytravis | ansible/venv/lib/python2.7/site-packages/ansible/module_utils/network/ironware/ironware.py | Python | get_connection | get_connection | 60 | 66 | 60 | 60 | 266af8f956e8cc488fdbad7b675aca7a32f7b222 | bigcode/the-stack | train |
e8a04a43060fbfa942b70138 | train | function | def check_args(module):
pass
| def check_args(module):
| pass
| _argument_spec = {
'provider': dict(type='dict', options=ironware_provider_spec)
}
command_spec = {
'command': dict(key=True),
'prompt': dict(),
'answer': dict()
}
def get_provider_argspec():
return ironware_provider_spec
def check_args(module):
| 64 | 64 | 8 | 5 | 58 | gvashchenkolineate/gvashchenkolineate_infra_trytravis | ansible/venv/lib/python2.7/site-packages/ansible/module_utils/network/ironware/ironware.py | Python | check_args | check_args | 56 | 57 | 56 | 56 | f02f9fb3b73536240f9ab0cb4d3d9370f7e4dca1 | bigcode/the-stack | train |
2bf216b0296957a754905544 | train | function | def get_config(module, source='running', flags=None):
global _DEVICE_CONFIG
if source == 'running' and flags is None and _DEVICE_CONFIG is not None:
return _DEVICE_CONFIG
else:
conn = get_connection(module)
out = conn.get_config(source=source, flags=flags)
cfg = to_text(out, ... | def get_config(module, source='running', flags=None):
| global _DEVICE_CONFIG
if source == 'running' and flags is None and _DEVICE_CONFIG is not None:
return _DEVICE_CONFIG
else:
conn = get_connection(module)
out = conn.get_config(source=source, flags=flags)
cfg = to_text(out, errors='surrogate_then_replace').strip()
if so... | get_connection(module)
commands = to_commands(module, to_list(commands))
responses = list()
for cmd in commands:
out = connection.get(**cmd)
responses.append(to_text(out, errors='surrogate_then_replace'))
return responses
def get_config(module, source='running', flags=None):
| 64 | 64 | 106 | 12 | 51 | gvashchenkolineate/gvashchenkolineate_infra_trytravis | ansible/venv/lib/python2.7/site-packages/ansible/module_utils/network/ironware/ironware.py | Python | get_config | get_config | 98 | 108 | 98 | 98 | dbed85e7c9767c1e4fe0350e4efaba4cce529856 | bigcode/the-stack | train |
d880abeef9320d5cf99a5e13 | train | function | def get_provider_argspec():
return ironware_provider_spec
| def get_provider_argspec():
| return ironware_provider_spec
| 'timeout': dict(type='int'),
}
ironware_argument_spec = {
'provider': dict(type='dict', options=ironware_provider_spec)
}
command_spec = {
'command': dict(key=True),
'prompt': dict(),
'answer': dict()
}
def get_provider_argspec():
| 64 | 64 | 13 | 6 | 58 | gvashchenkolineate/gvashchenkolineate_infra_trytravis | ansible/venv/lib/python2.7/site-packages/ansible/module_utils/network/ironware/ironware.py | Python | get_provider_argspec | get_provider_argspec | 52 | 53 | 52 | 52 | c9e6e73362c2b6720d8998fdbff3208303e8c0e7 | bigcode/the-stack | train |
a493e4da2dfd7101217cfc2e | train | function | def run_commands(module, commands, check_rc=True):
connection = get_connection(module)
commands = to_commands(module, to_list(commands))
responses = list()
for cmd in commands:
out = connection.get(**cmd)
responses.append(to_text(out, errors='surrogate_then_replace'))
return resp... | def run_commands(module, commands, check_rc=True):
| connection = get_connection(module)
commands = to_commands(module, to_list(commands))
responses = list()
for cmd in commands:
out = connection.get(**cmd)
responses.append(to_text(out, errors='surrogate_then_replace'))
return responses
| , item in enumerate(commands):
if module.check_mode and not item['command'].startswith('show'):
module.warn('only show commands are supported when using check '
'mode, not executing `%s`' % item['command'])
return commands
def run_commands(module, commands, check_rc=True... | 64 | 64 | 66 | 11 | 52 | gvashchenkolineate/gvashchenkolineate_infra_trytravis | ansible/venv/lib/python2.7/site-packages/ansible/module_utils/network/ironware/ironware.py | Python | run_commands | run_commands | 84 | 95 | 84 | 84 | cd1cccc01dc4ff282519e48740cc2d27e7b9acaf | bigcode/the-stack | train |
db776be595ec9e05e7f03962 | train | function | def load_config(module, config):
conn = get_connection(module)
conn.edit_config(config)
| def load_config(module, config):
| conn = get_connection(module)
conn.edit_config(config)
| get_connection(module)
out = conn.get_config(source=source, flags=flags)
cfg = to_text(out, errors='surrogate_then_replace').strip()
if source == 'running' and flags is None:
_DEVICE_CONFIG = cfg
return cfg
def load_config(module, config):
| 64 | 64 | 20 | 7 | 56 | gvashchenkolineate/gvashchenkolineate_infra_trytravis | ansible/venv/lib/python2.7/site-packages/ansible/module_utils/network/ironware/ironware.py | Python | load_config | load_config | 111 | 113 | 111 | 111 | 3590e336b09ba93a8a55392c2300821946047789 | bigcode/the-stack | train |
d3d0be2ab8cf86e72f8f86b2 | train | class | class takestoolong:
def test_list_images(self):
HEADING()
images = self.p.images()
pprint(images[:10])
print(Printer.flatwrite(images[:10],
sort_keys=["id", "name"],
order=["name", "id", 'architecture',
... | class takestoolong:
| def test_list_images(self):
HEADING()
images = self.p.images()
pprint(images[:10])
print(Printer.flatwrite(images[:10],
sort_keys=["id", "name"],
order=["name", "id", 'architecture',
... | *"
ssh = subprocess.Popen(
["ssh", "%s@%s" % (self.clouduser, pubip), COMMAND],
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
result = ssh.stdout.readlines()
if result == []:
error = ssh.stderr.readlines()
pr... | 126 | 126 | 421 | 6 | 120 | brianfunk3/cloudmesh-cloud | tests/aws/test_compute_aws.py | Python | takestoolong | takestoolong | 300 | 347 | 300 | 301 | a464a0a1e273ae7dc6e37f7b17f9f9ef9abef7aa | bigcode/the-stack | train |
09f3be1fed946cf69c133918 | train | class | class other:
def test_rename(self):
HEADING()
self.p.rename(source=self.name, destination=self.new_name)
| class other:
| def test_rename(self):
HEADING()
self.p.rename(source=self.name, destination=self.new_name)
| 'paravirtual'},
'id': 'ami-3b560641',
'kind': 'image',
'name': 'aws-elasticbeanstalk-amzn-2017.09.1.x86_64-golang-pv-201801050757'},
"""
class other:
| 63 | 64 | 27 | 3 | 60 | brianfunk3/cloudmesh-cloud | tests/aws/test_compute_aws.py | Python | other | other | 350 | 355 | 350 | 351 | e27ea480583b098cc300f4a791dd228a5147dcac | bigcode/the-stack | train |
9c70584472a0a5a860736a42 | train | class | @pytest.mark.incremental
class TestName:
def setup(self):
banner("setup", c="-")
self.user = Config()["cloudmesh.profile.user"]
self.clouduser = 'cc'
self.name_generator = Name(
schema=f"{self.user}-vm",
counter=1)
self.name = str(self.name_generator... | @pytest.mark.incremental
class TestName:
| def setup(self):
banner("setup", c="-")
self.user = Config()["cloudmesh.profile.user"]
self.clouduser = 'cc'
self.name_generator = Name(
schema=f"{self.user}-vm",
counter=1)
self.name = str(self.name_generator)
self.name_generator.incr()
... | ###############################################################
# pytest -v --capture=no tests/aws/test_compute_aws.py
# pytest -v tests/aws/test_compute_aws.py
# pytest -v --capture=no tests/aws/test_compute_awas.py:Test_compute_aws.<METHODNAME>
###############################################################
import ... | 164 | 256 | 1,837 | 9 | 155 | brianfunk3/cloudmesh-cloud | tests/aws/test_compute_aws.py | Python | TestName | TestName | 25 | 297 | 25 | 27 | e437a89e748026bade8e35859d5c1baddddd7cf1 | bigcode/the-stack | train |
909399b4486d85c47ee836d0 | train | class | class StaticStorage(S3Boto3Storage):
location = 'static'
default_acl = 'public-read'
| class StaticStorage(S3Boto3Storage):
| location = 'static'
default_acl = 'public-read'
| from storages.backends.s3boto3 import S3Boto3Storage
from bloggy import settings
class StaticStorage(S3Boto3Storage):
| 33 | 64 | 24 | 10 | 22 | ediziks/yaziyo.co | bloggy/custom_storage.py | Python | StaticStorage | StaticStorage | 5 | 7 | 5 | 5 | 514f114a0af56bc0eb770d1d3c23b219986439e7 | bigcode/the-stack | train |
bb62dcd9e493968d0d7bc184 | train | class | class ThumbnailStorage(S3Boto3Storage):
location = 'media/thumbnails'
default_acl = 'public-read'
| class ThumbnailStorage(S3Boto3Storage):
| location = 'media/thumbnails'
default_acl = 'public-read'
| from storages.backends.s3boto3 import S3Boto3Storage
from bloggy import settings
class StaticStorage(S3Boto3Storage):
location = 'static'
default_acl = 'public-read'
class ThumbnailStorage(S3Boto3Storage):
| 57 | 64 | 26 | 10 | 47 | ediziks/yaziyo.co | bloggy/custom_storage.py | Python | ThumbnailStorage | ThumbnailStorage | 10 | 12 | 10 | 10 | 1cf5d9c347fedcdb7f1dbd0a664e79daadb66422 | bigcode/the-stack | train |
c2e15074070c0bc6bd0a8d80 | train | class | class MediaStorage(S3Boto3Storage):
bucket_name = settings.AWS_STORAGE_BUCKET_NAME
location = settings.PUBLIC_MEDIA_LOCATION
isfilecached = {}
default_acl = 'public-read'
file_overwrite = True
def isdir(self, name):
if not name: # Empty name is a directory
return True
... | class MediaStorage(S3Boto3Storage):
| bucket_name = settings.AWS_STORAGE_BUCKET_NAME
location = settings.PUBLIC_MEDIA_LOCATION
isfilecached = {}
default_acl = 'public-read'
file_overwrite = True
def isdir(self, name):
if not name: # Empty name is a directory
return True
if self.isfile(name):
... | from storages.backends.s3boto3 import S3Boto3Storage
from bloggy import settings
class StaticStorage(S3Boto3Storage):
location = 'static'
default_acl = 'public-read'
class ThumbnailStorage(S3Boto3Storage):
location = 'media/thumbnails'
default_acl = 'public-read'
class MediaStorage(S3Boto3Storage):
| 83 | 225 | 752 | 10 | 73 | ediziks/yaziyo.co | bloggy/custom_storage.py | Python | MediaStorage | MediaStorage | 15 | 124 | 15 | 15 | b106495048e688c50263dc00bba8d720a962ecdf | bigcode/the-stack | train |
e939b090b830da2d3c98175b | train | class | class packetHandler(SocketServer.BaseRequestHandler):
def handle(self):
data = bytearray(self.request[0].strip())
log("Beacon recieved from %s : %s" % (str(self.client_address), data))
sock = self.request[1]
if data == pf_packet: # if we get the magic sauce
m = self.getAddresses()
try:
sock.sendto(... | class packetHandler(SocketServer.BaseRequestHandler):
| def handle(self):
data = bytearray(self.request[0].strip())
log("Beacon recieved from %s : %s" % (str(self.client_address), data))
sock = self.request[1]
if data == pf_packet: # if we get the magic sauce
m = self.getAddresses()
try:
sock.sendto(m, self.client_address)
except (socket.timeout, socke... |
def ts():
return str(datetime.datetime.now())
# basic log function
def log(string):
d = datetime.date.today()
logFile = "/var/log/pifinder.log"
mode = 'a+'
try:
f = open(logFile, mode)
f.write('\n %s : %s' % (ts(), string))
f.close()
except IOError as e:
sys.exit(0)
class packetHandler(SocketServer.B... | 96 | 96 | 323 | 10 | 86 | stevenewbs/pifinder | pifinder_server.py | Python | packetHandler | packetHandler | 33 | 67 | 33 | 34 | e16c4a0724a1a49ca62de1cd8bc63b41ff630f16 | bigcode/the-stack | train |
c4dbbe2998cbaf96bff73e51 | train | function | def log(string):
d = datetime.date.today()
logFile = "/var/log/pifinder.log"
mode = 'a+'
try:
f = open(logFile, mode)
f.write('\n %s : %s' % (ts(), string))
f.close()
except IOError as e:
sys.exit(0)
| def log(string):
| d = datetime.date.today()
logFile = "/var/log/pifinder.log"
mode = 'a+'
try:
f = open(logFile, mode)
f.write('\n %s : %s' % (ts(), string))
f.close()
except IOError as e:
sys.exit(0)
|
import SocketServer
from time import sleep
import sys
import subprocess
import datetime
# the response we will be looking for
pf_packet = "PIFINDER"
# lazy function to get a current timestamp
def ts():
return str(datetime.datetime.now())
# basic log function
def log(string):
| 64 | 64 | 70 | 4 | 59 | stevenewbs/pifinder | pifinder_server.py | Python | log | log | 22 | 31 | 22 | 22 | db5316530a609a988e2c5915d9309415a7050235 | bigcode/the-stack | train |
5d52fc9f95059e93710a29b8 | train | function | def ts():
return str(datetime.datetime.now())
| def ts():
| return str(datetime.datetime.now())
| bury
# see ./LICENSE for more info
import socket
import threading
import SocketServer
from time import sleep
import sys
import subprocess
import datetime
# the response we will be looking for
pf_packet = "PIFINDER"
# lazy function to get a current timestamp
def ts():
| 64 | 64 | 9 | 3 | 60 | stevenewbs/pifinder | pifinder_server.py | Python | ts | ts | 18 | 19 | 18 | 18 | babc988f6c6b9930598a93fcd488c01185daa39f | bigcode/the-stack | train |
86ced43c337d0cd501553f8f | train | class | class ThreadedUDPServer(SocketServer.ThreadingMixIn, SocketServer.UDPServer):
pass
| class ThreadedUDPServer(SocketServer.ThreadingMixIn, SocketServer.UDPServer):
| pass
| [ipindex].split(' ') # splits line containing ip address by spaces
ip = ipline[0]
msg.append("\tIP Address: %s " % ip)
return '\n'.join(msg)
class ThreadedUDPServer(SocketServer.ThreadingMixIn, SocketServer.UDPServer):
| 63 | 64 | 19 | 17 | 46 | stevenewbs/pifinder | pifinder_server.py | Python | ThreadedUDPServer | ThreadedUDPServer | 70 | 71 | 70 | 70 | 8ccbaf26cbf93f81ff2fa9c1c47c8e25a657bb7c | bigcode/the-stack | train |
f3938f558441b46f6034f65c | train | class | class Pi_Finder_Server():
def __init__(self):
self.HOST = "0.0.0.0"
self.PORT = 8899
self.server = ThreadedUDPServer((self.HOST, self.PORT), packetHandler)
self.server_thread = threading.Thread(target=self.server.serve_forever)
self.server_thread.daemon = True
def start(self):
try:
self.server_t... | class Pi_Finder_Server():
| def __init__(self):
self.HOST = "0.0.0.0"
self.PORT = 8899
self.server = ThreadedUDPServer((self.HOST, self.PORT), packetHandler)
self.server_thread = threading.Thread(target=self.server.serve_forever)
self.server_thread.daemon = True
def start(self):
try:
self.server_thread.start()
log("======... | containing ip address by spaces
ip = ipline[0]
msg.append("\tIP Address: %s " % ip)
return '\n'.join(msg)
class ThreadedUDPServer(SocketServer.ThreadingMixIn, SocketServer.UDPServer):
pass
class Pi_Finder_Server():
| 64 | 64 | 151 | 7 | 56 | stevenewbs/pifinder | pifinder_server.py | Python | Pi_Finder_Server | Pi_Finder_Server | 73 | 92 | 73 | 74 | 920689b977ad91ae22bd0bcbad5914417d53eebb | bigcode/the-stack | train |
f813a04a482fb0398e5dd5cb | train | class | class TypenameError(RuntimeError):
def __init__(self, type, msg):
msg = "%s(%s): %s" % (type.parent.parser_file, type.parent.parser_line, msg)
super(TypenameError, self).__init__(msg)
pass
| class TypenameError(RuntimeError):
| def __init__(self, type, msg):
msg = "%s(%s): %s" % (type.parent.parser_file, type.parent.parser_line, msg)
super(TypenameError, self).__init__(msg)
pass
| self.infos:
print("")
for item in self.errors + self.warnings + self.infos:
print(item)
log = Log()
# -------------------------------------------------------------------------
# Exception classes
class SkipFileError(RuntimeError):
pass
class NoInterfaceError(RuntimeEr... | 64 | 64 | 59 | 7 | 56 | rjpdasilva/WPEFramework | Tools/ProxyStubGenerator/StubGenerator.py | Python | TypenameError | TypenameError | 106 | 110 | 106 | 106 | f0ef1e9b73e3eb614d4cc38bb6d3e7c5933c8c88 | bigcode/the-stack | train |
a6fc70e5d9279000a83da0f6 | train | function | def GenerateStubs(output_file, source_file, defaults="", scan_only=False):
class Interface():
def __init__(self, obj, iid, file):
self.obj = obj
self.id = iid
self.file = file
# Looks for interface classes (ie. classes inheriting from Core::Unknown and specifying ID ... | def GenerateStubs(output_file, source_file, defaults="", scan_only=False):
| class Interface():
def __init__(self, obj, iid, file):
self.obj = obj
self.id = iid
self.file = file
# Looks for interface classes (ie. classes inheriting from Core::Unknown and specifying ID enum).
def FindInterfaceClasses(tree):
interfaces = []
... | .errors.append("%s: ERROR: %s%s%s" % (NAME, file, ": " if file else "", text))
print(self.errors[-1], file=sys.stderr)
def Print(self, text, file=""):
print("%s: %s%s%s" % (NAME, file, ": " if file else "", text))
def Dump(self):
if self.errors or self.warnings or self.infos:
... | 255 | 256 | 10,483 | 16 | 239 | rjpdasilva/WPEFramework | Tools/ProxyStubGenerator/StubGenerator.py | Python | GenerateStubs | GenerateStubs | 120 | 1,253 | 120 | 120 | 0457b869bb5bd64df855a8c432f1e82794aaeee8 | bigcode/the-stack | train |
ea48c9e564c30c38d6772668 | train | class | class NoInterfaceError(RuntimeError):
pass
| class NoInterfaceError(RuntimeError):
| pass
| ):
if self.errors or self.warnings or self.infos:
print("")
for item in self.errors + self.warnings + self.infos:
print(item)
log = Log()
# -------------------------------------------------------------------------
# Exception classes
class SkipFileError(RuntimeError)... | 64 | 64 | 10 | 7 | 56 | rjpdasilva/WPEFramework | Tools/ProxyStubGenerator/StubGenerator.py | Python | NoInterfaceError | NoInterfaceError | 102 | 103 | 102 | 102 | ad13e09b9328301bd4fb96231045c313d272bb2e | bigcode/the-stack | train |
99521cad924c5c57eb4d0743 | train | class | class Log:
def __init__(self):
self.warnings = []
self.errors = []
self.infos = []
def Info(self, text, file=""):
if BE_VERBOSE:
self.infos.append("%s: INFO: %s%s%s" % (NAME, file, ": " if file else "", text))
print(self.infos[-1])
def Warn(self, tex... | class Log:
| def __init__(self):
self.warnings = []
self.errors = []
self.infos = []
def Info(self, text, file=""):
if BE_VERBOSE:
self.infos.append("%s: INFO: %s%s%s" % (NAME, file, ": " if file else "", text))
print(self.infos[-1])
def Warn(self, text, file="")... | "
INTERFACE_NAMESPACE = "::WPEFramework::Exchange"
CLASS_IUNKNOWN = "::WPEFramework::Core::IUnknown"
PROXYSTUB_CPP_NAME = "ProxyStubs_%s.cpp"
MIN_INTERFACE_ID = 64
DEFAULT_DEFINITIONS_FILE = "default.h"
IDS_DEFINITIONS_FILE = "Ids.h"
# -------------------------------------------------------------------------
# Logge... | 76 | 76 | 255 | 3 | 72 | rjpdasilva/WPEFramework | Tools/ProxyStubGenerator/StubGenerator.py | Python | Log | Log | 62 | 89 | 62 | 62 | 40963e1c294ca99724e0c848d58b3b65733da160 | bigcode/the-stack | train |
895e0a87483b024853f70508 | train | function | def CreateName(ns):
return ns.replace("::I", "").replace("::", "")[1 if ns[0] == "I" else 0:]
| def CreateName(ns):
| return ns.replace("::I", "").replace("::", "")[1 if ns[0] == "I" else 0:]
| (RuntimeError):
def __init__(self, type, msg):
msg = "%s(%s): %s" % (type.parent.parser_file, type.parent.parser_line, msg)
super(TypenameError, self).__init__(msg)
pass
# -------------------------------------------------------------------------
def CreateName(ns):
| 63 | 64 | 34 | 5 | 58 | rjpdasilva/WPEFramework | Tools/ProxyStubGenerator/StubGenerator.py | Python | CreateName | CreateName | 116 | 117 | 116 | 116 | aa11c1d318d619664c2623699a9e5b2efc5cc6ec | bigcode/the-stack | train |
b65893ff5af6af2897714e2c | train | class | class SkipFileError(RuntimeError):
pass
| class SkipFileError(RuntimeError):
| pass
| if file else "", text))
def Dump(self):
if self.errors or self.warnings or self.infos:
print("")
for item in self.errors + self.warnings + self.infos:
print(item)
log = Log()
# -------------------------------------------------------------------------
# Exception ... | 64 | 64 | 10 | 7 | 56 | rjpdasilva/WPEFramework | Tools/ProxyStubGenerator/StubGenerator.py | Python | SkipFileError | SkipFileError | 98 | 99 | 98 | 98 | 5588ecf9988d54aee1a84564291a10351f1be790 | bigcode/the-stack | train |
b6e3dae303d6f25d5814061c | train | class | class Env(EnvBase):
'''Wraps environment configuration. Optionally, accepts a Coin class
as first argument to have ElectrumX serve custom coins not part of
the standard distribution.
'''
# Peer discovery
PD_OFF, PD_SELF, PD_ON = ('OFF', 'SELF', 'ON')
SSL_PROTOCOLS = {'ssl', 'wss'}
... | class Env(EnvBase):
| '''Wraps environment configuration. Optionally, accepts a Coin class
as first argument to have ElectrumX serve custom coins not part of
the standard distribution.
'''
# Peer discovery
PD_OFF, PD_SELF, PD_ON = ('OFF', 'SELF', 'ON')
SSL_PROTOCOLS = {'ssl', 'wss'}
KNOWN_PROTOCOLS = {... | # Copyright (c) 2016, Neil Booth
#
# All rights reserved.
#
# See the file "LICENCE" for information about the copyright
# and warranty status of this software.
'''Class for handling environment configuration and defaults.'''
import re
from ipaddress import IPv4Address, IPv6Address
from aiorpcx import Service, Serv... | 113 | 256 | 1,559 | 6 | 106 | CoolBitX-Technology/electrumx | electrumx/server/env.py | Python | Env | Env | 23 | 177 | 23 | 23 | df35a05797b04e09aaf2274e3268f76567cd9725 | bigcode/the-stack | train |
f8b23d095c57f08183622bfe | train | class | class ServiceError(Exception):
pass
| class ServiceError(Exception):
| pass
| .
'''Class for handling environment configuration and defaults.'''
import re
from ipaddress import IPv4Address, IPv6Address
from aiorpcx import Service, ServicePart
from electrumx.lib.coins import Coin
from electrumx.lib.env_base import EnvBase
class ServiceError(Exception):
| 64 | 64 | 8 | 5 | 58 | CoolBitX-Technology/electrumx | electrumx/server/env.py | Python | ServiceError | ServiceError | 19 | 20 | 19 | 19 | 8834fa10d8a564189ba94c3d346d92719211628b | bigcode/the-stack | train |
61f9f5901a2342a79290b76c | train | class | class S3Reporter(ReporterMeta):
"""Python report class for uploading the report results in json format into an S3 bucket
uses boto3 AWS library
https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html#configuration"""
REPORTER_NAME: str = "s3"
SHORT_DESCRIPTION: str = "s3 uplo... | class S3Reporter(ReporterMeta):
| """Python report class for uploading the report results in json format into an S3 bucket
uses boto3 AWS library
https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html#configuration"""
REPORTER_NAME: str = "s3"
SHORT_DESCRIPTION: str = "s3 uploader reporter"
INSTALL_HELP:... | """JSON reporter exported to S3 bucket class implementation"""
import os
from datetime import datetime
import boto3
from botocore.exceptions import ClientError
from pydash import py_
from eze import __version__
from eze.core.reporter import ReporterMeta
from eze.utils.io import pretty_print_json
from eze.utils.git i... | 111 | 216 | 722 | 8 | 102 | RiverSafeUK/eze-cli | eze/plugins/reporters/s3.py | Python | S3Reporter | S3Reporter | 18 | 94 | 18 | 18 | aa24df2895cbd7099050886502b0cb24ff18c050 | bigcode/the-stack | train |
4afc5d15995e9f92930005e2 | train | function | def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'word_learning_33989.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"avai... | def main():
| os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'word_learning_33989.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on you... | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
| 26 | 64 | 96 | 3 | 22 | crowdbotics-apps/word-learning-33989 | backend/manage.py | Python | main | main | 7 | 17 | 7 | 7 | e1f523493b0fdff0a08ec14445f65c5c09d85470 | bigcode/the-stack | train |
1de6586a008f84ddf83a0905 | train | class | class SetupApp3Test(SetupAppBaseTest):
module = "tests.sample_app_3"
app_name = "App3"
def test_setup_from_cmsapp(self):
self._setup_from_cmsapp()
def test_setup_filled(self):
self._setup_filled()
| class SetupApp3Test(SetupAppBaseTest):
| module = "tests.sample_app_3"
app_name = "App3"
def test_setup_from_cmsapp(self):
self._setup_from_cmsapp()
def test_setup_filled(self):
self._setup_filled()
| ):
module = "tests.sample_app_2"
app_name = "App2"
def test_setup_from_cmsapp(self):
self._setup_from_cmsapp()
def test_setup_filled(self):
self._setup_filled()
class SetupApp3Test(SetupAppBaseTest):
| 64 | 64 | 63 | 11 | 53 | nephila/djangocms-apphook-setup | tests/test_setup.py | Python | SetupApp3Test | SetupApp3Test | 137 | 145 | 137 | 137 | aac65b1461c52523810c28de284c2ca32c450ebf | bigcode/the-stack | train |
5ef125cf40a16b5b5e093e5c | train | class | class SetupApp4Test(SetupAppBaseTest):
config = App4Config
module = "tests.sample_app_4"
app_name = "App4"
def test_setup_from_cmsapp(self):
self._setup_from_cmsapp()
def test_setup_filled(self):
self._setup_filled()
def test_config_values(self):
# importing cms_app tr... | class SetupApp4Test(SetupAppBaseTest):
| config = App4Config
module = "tests.sample_app_4"
app_name = "App4"
def test_setup_from_cmsapp(self):
self._setup_from_cmsapp()
def test_setup_filled(self):
self._setup_filled()
def test_config_values(self):
# importing cms_app triggers the auto setup
__import_... | ):
module = "tests.sample_app_3"
app_name = "App3"
def test_setup_from_cmsapp(self):
self._setup_from_cmsapp()
def test_setup_filled(self):
self._setup_filled()
class SetupApp4Test(SetupAppBaseTest):
| 64 | 64 | 155 | 11 | 53 | nephila/djangocms-apphook-setup | tests/test_setup.py | Python | SetupApp4Test | SetupApp4Test | 148 | 166 | 148 | 148 | a66e9b702f36ef4fcce4b1364b8e80dd9738f833 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.