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
a424dadc65a2a0e9c32061df
train
class
class rollup(ColumnElement): def __init__(self, *elements): self.elements = [_clause_element_as_expr(e) for e in elements]
class rollup(ColumnElement):
def __init__(self, *elements): self.elements = [_clause_element_as_expr(e) for e in elements]
2013 @author: peterb ''' from sqlalchemy.sql.expression import ColumnElement, _clause_element_as_expr from sqlalchemy.ext.compiler import compiles from sqlalchemy.ext.mutable import Mutable from sqlalchemy.types import TypeDecorator, VARCHAR from blueshed.utils.utils import dumps, loads class rollup(ColumnElement):
64
64
33
6
57
blueshed/blueshed-py
src/blueshed/model_helpers/sql_extensions.py
Python
rollup
rollup
15
17
15
15
79d30299684949ad193670d0c9258d3d841579d0
bigcode/the-stack
train
b997bd187dd756e42491b9ce
train
class
class JSONEncodedDict(TypeDecorator): "Represents an immutable structure as a json-encoded string." impl = VARCHAR def process_bind_param(self, value, dialect): if value is not None: value = dumps(value) return value def process_result_value(self, value, dialect): ...
class JSONEncodedDict(TypeDecorator):
"Represents an immutable structure as a json-encoded string." impl = VARCHAR def process_bind_param(self, value, dialect): if value is not None: value = dumps(value) return value def process_result_value(self, value, dialect): if value is not None: valu...
) for e in elements] @compiles(rollup, "mysql") def _mysql_rollup(element, compiler, **kw): return "%s WITH ROLLUP" % (', '.join([compiler.process(e, **kw) for e in element.elements])) class JSONEncodedDict(TypeDecorator):
63
64
82
7
56
blueshed/blueshed-py
src/blueshed/model_helpers/sql_extensions.py
Python
JSONEncodedDict
JSONEncodedDict
24
37
24
24
7cc30af0cdc433865200b5c591264ab56492176a
bigcode/the-stack
train
369b311b23c10e03f9927d8a
train
function
@compiles(rollup, "mysql") def _mysql_rollup(element, compiler, **kw): return "%s WITH ROLLUP" % (', '.join([compiler.process(e, **kw) for e in element.elements]))
@compiles(rollup, "mysql") def _mysql_rollup(element, compiler, **kw):
return "%s WITH ROLLUP" % (', '.join([compiler.process(e, **kw) for e in element.elements]))
blueshed.utils.utils import dumps, loads class rollup(ColumnElement): def __init__(self, *elements): self.elements = [_clause_element_as_expr(e) for e in elements] @compiles(rollup, "mysql") def _mysql_rollup(element, compiler, **kw):
64
64
50
22
42
blueshed/blueshed-py
src/blueshed/model_helpers/sql_extensions.py
Python
_mysql_rollup
_mysql_rollup
19
21
19
20
310f8a5dba044d9398e43ff7b2180a8f43848629
bigcode/the-stack
train
2ba6adb2415baf200b1317b3
train
class
class Controller: def __init__(self): """Initialise the controller. This sets up the command line argument parsing etc.""" self._parser = argparse.ArgumentParser(description='Run securify.') self._parser.add_argument('-t', '--truffle', action="store_true", ...
class Controller:
def __init__(self): """Initialise the controller. This sets up the command line argument parsing etc.""" self._parser = argparse.ArgumentParser(description='Run securify.') self._parser.add_argument('-t', '--truffle', action="store_true", ...
the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, 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 govern...
99
99
331
3
95
eluanshi7/securifyresearch
scripts/controller.py
Python
Controller
Controller
28
68
28
28
91915eabb20e630f49016413764249d99ea9c9a6
bigcode/the-stack
train
bf7e4c5a448f09a2710a69ae
train
function
def return_get_res(url, cookies=None, proxies=None, headers=None, encoding='utf-8'): if not headers: headers = DEFAULT_HEADERS # read settings from ini file use_proxy = return_config_string(['代理', '是否使用代理?']) # prioritize passed in proxies if use_proxy == '是' and not proxies: proxi...
def return_get_res(url, cookies=None, proxies=None, headers=None, encoding='utf-8'):
if not headers: headers = DEFAULT_HEADERS # read settings from ini file use_proxy = return_config_string(['代理', '是否使用代理?']) # prioritize passed in proxies if use_proxy == '是' and not proxies: proxies = return_config_string(['代理', '代理IP及端口']) res = requests.get(url, headers=hea...
pass #print('not using proxy for requests') res = requests.post(url, data, headers=headers, cookies=cookies, proxies=proxies) res.encoding = encoding return res def return_get_res(url, cookies=None, proxies=None, headers=None, encoding='utf-8'):
64
64
120
21
42
jadjz/JAVOneStop
JavHelper/core/requester_proxy.py
Python
return_get_res
return_get_res
28
41
28
28
5b2caf82d559439b5f197a174f46b442da626a57
bigcode/the-stack
train
f3a8e28fd87f8c99b299c0de
train
function
def return_html_text(url, cookies=None, proxies=None, encoding='utf-8'): # read settings from ini file use_proxy = return_config_string(['代理', '是否使用代理?']) # prioritize passed in proxies if use_proxy == '是' and not proxies: proxies = return_config_string(['代理', '代理IP及端口']) res = requests.ge...
def return_html_text(url, cookies=None, proxies=None, encoding='utf-8'): # read settings from ini file
use_proxy = return_config_string(['代理', '是否使用代理?']) # prioritize passed in proxies if use_proxy == '是' and not proxies: proxies = return_config_string(['代理', '代理IP及端口']) res = requests.get(url, cookies=cookies, proxies=proxies) res.encoding = encoding return res.text
代理', '代理IP及端口']) res = requests.get(url, headers=headers, cookies=cookies, proxies=proxies) res.encoding = encoding return res def return_html_text(url, cookies=None, proxies=None, encoding='utf-8'): # read settings from ini file
64
64
104
26
37
jadjz/JAVOneStop
JavHelper/core/requester_proxy.py
Python
return_html_text
return_html_text
44
54
44
45
e90c7a6625288b9a953524f9c36e41c6f2a77f33
bigcode/the-stack
train
bbed105cbf851235b335c159
train
function
def return_post_res(url, data=None, cookies=None, proxies=None, headers=None, encoding='utf-8'): if not headers: headers = DEFAULT_HEADERS # read settings from ini file use_proxy = return_config_string(['代理', '是否使用代理?']) # prioritize passed in proxies if use_proxy == '是' and not proxies: ...
def return_post_res(url, data=None, cookies=None, proxies=None, headers=None, encoding='utf-8'):
if not headers: headers = DEFAULT_HEADERS # read settings from ini file use_proxy = return_config_string(['代理', '是否使用代理?']) # prioritize passed in proxies if use_proxy == '是' and not proxies: proxies = return_config_string(['代理', '代理IP及端口']) else: pass #print('n...
Mac OS X 10_15_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36' } def return_post_res(url, data=None, cookies=None, proxies=None, headers=None, encoding='utf-8'):
64
64
141
24
40
jadjz/JAVOneStop
JavHelper/core/requester_proxy.py
Python
return_post_res
return_post_res
10
26
10
10
6c0db84d53f6dffdd2d63c11950f14163b90bc0b
bigcode/the-stack
train
50d5fc08acfff8519cfd7221
train
function
def FMotionStart(builder): builder.StartObject(3)
def FMotionStart(builder):
builder.StartObject(3)
(self): o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) if o != 0: return self._tab.Get(flatbuffers.number_types.Float64Flags, o + self._tab.Pos) return 0.0 def FMotionStart(builder):
64
64
12
7
56
sintefneodroid/schema
FBSSchemaGenerator/build/python/FMotion.py
Python
FMotionStart
FMotionStart
42
42
42
42
1f2e13b3748b5539c5f97643f8608f7ae40992c7
bigcode/the-stack
train
4867d96d46ec7d3ecdd96b40
train
function
def FMotionAddActuatorName(builder, actuatorName): builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(actuatorName), 0)
def FMotionAddActuatorName(builder, actuatorName):
builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(actuatorName), 0)
def FMotionStart(builder): builder.StartObject(3) def FMotionAddActorName(builder, actorName): builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(actorName), 0) def FMotionAddActuatorName(builder, actuatorName):
64
64
41
13
51
sintefneodroid/schema
FBSSchemaGenerator/build/python/FMotion.py
Python
FMotionAddActuatorName
FMotionAddActuatorName
44
44
44
44
086fe26a1a5360a2395d61322c60730d584e089d
bigcode/the-stack
train
0beeb07e85c95ee0bde615af
train
function
def FMotionAddStrength(builder, strength): builder.PrependFloat64Slot(2, strength, 0.0)
def FMotionAddStrength(builder, strength):
builder.PrependFloat64Slot(2, strength, 0.0)
_types.UOffsetTFlags.py_type(actorName), 0) def FMotionAddActuatorName(builder, actuatorName): builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(actuatorName), 0) def FMotionAddStrength(builder, strength):
64
64
25
10
54
sintefneodroid/schema
FBSSchemaGenerator/build/python/FMotion.py
Python
FMotionAddStrength
FMotionAddStrength
45
45
45
45
ca7924a33d7736e6209d87dfab9a01843fc57408
bigcode/the-stack
train
06ce67a01ac5f1de34d46b26
train
function
def FMotionAddActorName(builder, actorName): builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(actorName), 0)
def FMotionAddActorName(builder, actorName):
builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(actorName), 0)
tab.Offset(8)) if o != 0: return self._tab.Get(flatbuffers.number_types.Float64Flags, o + self._tab.Pos) return 0.0 def FMotionStart(builder): builder.StartObject(3) def FMotionAddActorName(builder, actorName):
64
64
39
12
52
sintefneodroid/schema
FBSSchemaGenerator/build/python/FMotion.py
Python
FMotionAddActorName
FMotionAddActorName
43
43
43
43
9a756498e750182d5106052c5e184f80b7b4f392
bigcode/the-stack
train
875f171d7375be97136888ab
train
function
def FMotionEnd(builder): return builder.EndObject()
def FMotionEnd(builder):
return builder.EndObject()
actuatorName): builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(actuatorName), 0) def FMotionAddStrength(builder, strength): builder.PrependFloat64Slot(2, strength, 0.0) def FMotionEnd(builder):
64
64
11
7
57
sintefneodroid/schema
FBSSchemaGenerator/build/python/FMotion.py
Python
FMotionEnd
FMotionEnd
46
46
46
46
2a7d5a006a5aa9a93ba000c9eb8bc1b5a162174d
bigcode/the-stack
train
9921c56b3520d9535a81e2a0
train
class
class FMotion(object): __slots__ = ['_tab'] @classmethod def GetRootAsFMotion(cls, buf, offset): n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) x = FMotion() x.Init(buf, n + offset) return x # FMotion def Init(self, buf, pos): self._tab ...
class FMotion(object):
__slots__ = ['_tab'] @classmethod def GetRootAsFMotion(cls, buf, offset): n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) x = FMotion() x.Init(buf, n + offset) return x # FMotion def Init(self, buf, pos): self._tab = flatbuffers.table.Tab...
# automatically generated by the FlatBuffers compiler, do not modify # namespace: Reaction import flatbuffers class FMotion(object):
27
81
271
5
21
sintefneodroid/schema
FBSSchemaGenerator/build/python/FMotion.py
Python
FMotion
FMotion
7
40
7
7
bffed7de8eba07db1d3861cc40b583c88b8d1eb2
bigcode/the-stack
train
8b70fec9a4c29742208d5e9f
train
function
@pytest.fixture def tf_v_ae_mnist(request): # load and preprocess MNIST data (X_train, _), (X_test, _) = tf.keras.datasets.mnist.load_data() X = X_train.reshape(60000, input_dim)[:1000] # only train on 1000 instances X = X.astype(np.float32) X /= 255 # init model, predict with untrained model,...
@pytest.fixture def tf_v_ae_mnist(request): # load and preprocess MNIST data
(X_train, _), (X_test, _) = tf.keras.datasets.mnist.load_data() X = X_train.reshape(60000, input_dim)[:1000] # only train on 1000 instances X = X.astype(np.float32) X /= 255 # init model, predict with untrained model, train and predict with trained model model = request.param X_recon_untra...
_dim, activation=tf.nn.sigmoid) ] ) ae = AE(encoder_net, decoder_net) vae = VAE(encoder_net, decoder_net, latent_dim) tests = [ae, vae] @pytest.fixture def tf_v_ae_mnist(request): # load and preprocess MNIST data
64
64
209
21
43
Clusks/alibi-detect
alibi_detect/models/tests/test_autoencoder.py
Python
tf_v_ae_mnist
tf_v_ae_mnist
33
49
33
35
654fe70472fab421c6fe566b2a4f0c652cb9a091
bigcode/the-stack
train
61df679e62fc3386e1bdae59
train
function
@pytest.mark.parametrize('tf_v_ae_mnist', tests, indirect=True) def test_ae_vae(tf_v_ae_mnist): pass
@pytest.mark.parametrize('tf_v_ae_mnist', tests, indirect=True) def test_ae_vae(tf_v_ae_mnist):
pass
.weights[1].numpy()).any() assert np.sum((X - X_recon_untrained)**2) > np.sum((X - X_recon)**2) @pytest.mark.parametrize('tf_v_ae_mnist', tests, indirect=True) def test_ae_vae(tf_v_ae_mnist):
64
64
32
29
35
Clusks/alibi-detect
alibi_detect/models/tests/test_autoencoder.py
Python
test_ae_vae
test_ae_vae
52
54
52
53
f7b09224c5b88341ab21827da077dd6f53031e48
bigcode/the-stack
train
3b0988eb8ad4b5685ae42251
train
function
@pytest.fixture def tf_v_aegmm_mnist(request): # load and preprocess MNIST data (X_train, _), (X_test, _) = tf.keras.datasets.mnist.load_data() X = X_train.reshape(60000, input_dim)[:1000] # only train on 1000 instances X = X.astype(np.float32) X /= 255 # init model, predict with untrained mod...
@pytest.fixture def tf_v_aegmm_mnist(request): # load and preprocess MNIST data
(X_train, _), (X_test, _) = tf.keras.datasets.mnist.load_data() X = X_train.reshape(60000, input_dim)[:1000] # only train on 1000 instances X = X.astype(np.float32) X /= 255 # init model, predict with untrained model, train and predict with trained model model, loss_fn = tests[request.param] ...
, gmm_density_net, n_gmm, latent_dim) tests = [(aegmm, loss_aegmm), (vaegmm, loss_vaegmm)] n_tests = len(tests) @pytest.fixture def tf_v_aegmm_mnist(request): # load and preprocess MNIST data
64
64
216
22
42
Clusks/alibi-detect
alibi_detect/models/tests/test_autoencoder.py
Python
tf_v_aegmm_mnist
tf_v_aegmm_mnist
72
88
72
74
b8944baeb8cba279a144c3c021551a52d508707f
bigcode/the-stack
train
ed3b7289665da710506f075b
train
function
@pytest.mark.parametrize('tf_v_aegmm_mnist', list(range(n_tests)), indirect=True) def test_aegmm_vaegmm(tf_v_aegmm_mnist): pass
@pytest.mark.parametrize('tf_v_aegmm_mnist', list(range(n_tests)), indirect=True) def test_aegmm_vaegmm(tf_v_aegmm_mnist):
pass
epochs=5, verbose=False, batch_size=1000) assert (model_weights != model.weights[1].numpy()).any() @pytest.mark.parametrize('tf_v_aegmm_mnist', list(range(n_tests)), indirect=True) def test_aegmm_vaegmm(tf_v_aegmm_mnist):
64
64
39
36
28
Clusks/alibi-detect
alibi_detect/models/tests/test_autoencoder.py
Python
test_aegmm_vaegmm
test_aegmm_vaegmm
91
93
91
92
81461758df5f3a9ef892bc3247595eba345ad83c
bigcode/the-stack
train
9e321ed5048bf1afbe866913
train
function
@pytest.fixture def tf_seq2seq_sine(request): # create artificial sine time series X = np.sin(np.linspace(-50, 50, 10000)).astype(np.float32) # init model decoder_net_, n_features = tests_seq2seq[request.param] encoder_net = EncoderLSTM(latent_dim) threshold_net = tf.keras.Sequential( [...
@pytest.fixture def tf_seq2seq_sine(request): # create artificial sine time series
X = np.sin(np.linspace(-50, 50, 10000)).astype(np.float32) # init model decoder_net_, n_features = tests_seq2seq[request.param] encoder_net = EncoderLSTM(latent_dim) threshold_net = tf.keras.Sequential( [ InputLayer(input_shape=(seq_len, latent_dim)), Dense(10, activ...
egmm_vaegmm(tf_v_aegmm_mnist): pass seq_len = 10 tests_seq2seq = [(DecoderLSTM(latent_dim, 1, None), 1), (DecoderLSTM(latent_dim, 2, None), 2)] n_tests = len(tests_seq2seq) @pytest.fixture def tf_seq2seq_sine(request): # create artificial sine time series
90
90
300
20
70
Clusks/alibi-detect
alibi_detect/models/tests/test_autoencoder.py
Python
tf_seq2seq_sine
tf_seq2seq_sine
102
130
102
104
df99d754a7baebdaaf2e6ec65ffb34aa4680695a
bigcode/the-stack
train
8b66ee82d4f5e0fb735607f4
train
function
@pytest.mark.parametrize('tf_seq2seq_sine', list(range(n_tests)), indirect=True) def test_seq2seq(tf_seq2seq_sine): pass
@pytest.mark.parametrize('tf_seq2seq_sine', list(range(n_tests)), indirect=True) def test_seq2seq(tf_seq2seq_sine):
pass
1].numpy()).any() assert np.sum((X - X_recon_untrained)**2) > np.sum((X - X_recon)**2) @pytest.mark.parametrize('tf_seq2seq_sine', list(range(n_tests)), indirect=True) def test_seq2seq(tf_seq2seq_sine):
64
64
34
31
33
Clusks/alibi-detect
alibi_detect/models/tests/test_autoencoder.py
Python
test_seq2seq
test_seq2seq
133
135
133
134
0536d0b7459651a68ab46e4749c760f6936f20a8
bigcode/the-stack
train
40617d3973e4be264ef02da6
train
function
def plot_confusion_matrix(X, Y, figsize=(10, 6), cmap=plt.cm.Greens): Y_pred = model.predict(X) Y_pred = np.argmax(Y_pred, axis=1) Y_true = np.argmax(Y, axis=1) cm = confusion_matrix(Y_true, Y_pred) plt.figure(figsize=figsize) ax = sns.heatmap(cm, cmap=cmap, annot=True, square=True) ax.set_...
def plot_confusion_matrix(X, Y, figsize=(10, 6), cmap=plt.cm.Greens):
Y_pred = model.predict(X) Y_pred = np.argmax(Y_pred, axis=1) Y_true = np.argmax(Y, axis=1) cm = confusion_matrix(Y_true, Y_pred) plt.figure(figsize=figsize) ax = sns.heatmap(cm, cmap=cmap, annot=True, square=True) ax.set_ylabel('Actual', fontsize=30) ax.set_xlabel('Predicted', fontsize=...
sklearn.metrics import confusion_matrix from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt import seaborn as sns from keras.models import load_model SEED = 42 def plot_confusion_matrix(X, Y, figsize=(10, 6), cmap=plt.cm.Greens):
64
64
122
24
39
AlphaHelix456/Digit-Recognizer
run.py
Python
plot_confusion_matrix
plot_confusion_matrix
12
22
12
12
7a8eeb63d88cc9b74c1bcb625ec3e7eb732a5358
bigcode/the-stack
train
3436794a15755d9d96c0683d
train
function
def pytest_configure(config): config.addinivalue_line("markers", "slow: mark test as slow to run") config.addinivalue_line("markers", "release: mark test as only relevant for a release")
def pytest_configure(config):
config.addinivalue_line("markers", "slow: mark test as slow to run") config.addinivalue_line("markers", "release: mark test as only relevant for a release")
def pytest_addoption(parser): parser.addoption( "--runslow", action="store_true", default=False, help="run slow tests" ) parser.addoption( "--runrelease", action="store_true", default=False, help="run release tests" ) def pytest_configure(config):
64
64
48
6
58
anoburn/mspypeline
test/conftest.py
Python
pytest_configure
pytest_configure
15
17
15
15
5241c277cd7b9776d6220807484ab2779b0d53ca
bigcode/the-stack
train
84d26303bbc6ef31881f42a9
train
function
def pytest_addoption(parser): parser.addoption( "--runslow", action="store_true", default=False, help="run slow tests" ) parser.addoption( "--runrelease", action="store_true", default=False, help="run release tests" )
def pytest_addoption(parser):
parser.addoption( "--runslow", action="store_true", default=False, help="run slow tests" ) parser.addoption( "--runrelease", action="store_true", default=False, help="run release tests" )
import pytest from .mock_data import MockData def pytest_addoption(parser):
17
64
58
6
10
anoburn/mspypeline
test/conftest.py
Python
pytest_addoption
pytest_addoption
6
12
6
6
580e37d1d45e615725923a9d3ebeeadf7e8a7148
bigcode/the-stack
train
86019ad347060b7a21e290a1
train
function
def pytest_collection_modifyitems(config, items): # if config.getoption("--runslow"): # # --runslow given in cli: do not skip slow tests # return skip_slow = pytest.mark.skip(reason="need --runslow option to run") for item in items: if "slow" in item.keywords and not config.getoption...
def pytest_collection_modifyitems(config, items): # if config.getoption("--runslow"): # # --runslow given in cli: do not skip slow tests # return
skip_slow = pytest.mark.skip(reason="need --runslow option to run") for item in items: if "slow" in item.keywords and not config.getoption("--runslow"): item.add_marker(skip_slow) skip_release = pytest.mark.skip(reason="need --release option to run") for item in items: if "r...
") config.addinivalue_line("markers", "release: mark test as only relevant for a release") def pytest_collection_modifyitems(config, items): # if config.getoption("--runslow"): # # --runslow given in cli: do not skip slow tests # return
64
64
138
41
23
anoburn/mspypeline
test/conftest.py
Python
pytest_collection_modifyitems
pytest_collection_modifyitems
20
32
20
23
62fb2403cbc7c0ea095039154c0f0a8d66b81535
bigcode/the-stack
train
ae05d620bd651faace703f64
train
class
class ImageAttribute: def __init__(self, parent=None): self.name = None self.kernel = None self.ramdisk = None self.attrs = {} def startElement(self, name, attrs, connection): if name == 'blockDeviceMapping': self.attrs['block_device_mapping'] = BlockDeviceM...
class ImageAttribute:
def __init__(self, parent=None): self.name = None self.kernel = None self.ramdisk = None self.attrs = {} def startElement(self, name, attrs, connection): if name == 'blockDeviceMapping': self.attrs['block_device_mapping'] = BlockDeviceMapping() re...
group_names) def reset_launch_attributes(self): return self.connection.reset_image_attribute(self.id, 'launchPermission') def get_kernel(self): img_attrs =self.connection.get_image_attrib...
88
88
294
4
83
bopopescu/drawquest-web
common/boto/ec2/image.py
Python
ImageAttribute
ImageAttribute
284
324
284
285
bbbc27218800a2084f0a9a3a6bac78218271098d
bigcode/the-stack
train
d7ed9f35d3fc55dbd7faf92f
train
class
class ProductCodes(list): def startElement(self, name, attrs, connection): pass def endElement(self, name, value, connection): if name == 'productCode': self.append(value)
class ProductCodes(list):
def startElement(self, name, attrs, connection): pass def endElement(self, name, value, connection): if name == 'productCode': self.append(value)
, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. from boto.ec2.ec2object import EC2Object, TaggedEC2Object from boto.ec2.blockdevicemapping import BlockDeviceMapping class ProductCodes(list):
64
64
45
5
58
bopopescu/drawquest-web
common/boto/ec2/image.py
Python
ProductCodes
ProductCodes
26
33
26
27
2e3fcc086a3a33a8f66735766aae09eea0d46c9e
bigcode/the-stack
train
86c0f9a64ccdeac81c7cd273
train
class
class Image(TaggedEC2Object): """ Represents an EC2 Image """ def __init__(self, connection=None): TaggedEC2Object.__init__(self, connection) self.id = None self.location = None self.state = None self.ownerId = None # for backwards compatibility self...
class Image(TaggedEC2Object):
""" Represents an EC2 Image """ def __init__(self, connection=None): TaggedEC2Object.__init__(self, connection) self.id = None self.location = None self.state = None self.ownerId = None # for backwards compatibility self.owner_id = None self....
merge, publish, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Softwar...
255
256
1,860
8
247
bopopescu/drawquest-web
common/boto/ec2/image.py
Python
Image
Image
35
282
35
35
7439907e4595e4d948bdfbd1a735952afea1656b
bigcode/the-stack
train
3f406993108f0d8a8a8d5647
train
function
def get_mean_and_std(dataset): '''Compute the mean and std value of dataset.''' dataloader = trainloader = torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=True, num_workers=2) mean = torch.zeros(3) std = torch.zeros(3) print('==> Computing mean and std..') for inputs, targets in data...
def get_mean_and_std(dataset):
'''Compute the mean and std value of dataset.''' dataloader = trainloader = torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=True, num_workers=2) mean = torch.zeros(3) std = torch.zeros(3) print('==> Computing mean and std..') for inputs, targets in dataloader: for i in range(...
import errno import math import os import sys import time import torch import torch.nn as nn import torch.nn.init as init __all__ = ['get_mean_and_std', 'init_params', 'mkdir_p', 'AverageMeter'] def get_mean_and_std(dataset):
60
64
136
7
53
TanayNarshana/rethinking-network-pruning
cifar/weight-level/utils/misc.py
Python
get_mean_and_std
get_mean_and_std
14
27
14
14
efead26f510dfdde238ee6b8363e7ea588c9d1fd
bigcode/the-stack
train
4ebc7f108a0a3c9ed495047a
train
function
def get_conv_zero_param(model): total = 0 for m in model.modules(): if isinstance(m, nn.Conv2d): total += torch.sum(m.weight.data.eq(0)) return total
def get_conv_zero_param(model):
total = 0 for m in model.modules(): if isinstance(m, nn.Conv2d): total += torch.sum(m.weight.data.eq(0)) return total
in dataloader: for i in range(3): mean[i] += inputs[:,i,:,:].mean() std[i] += inputs[:,i,:,:].std() mean.div_(len(dataset)) std.div_(len(dataset)) return mean, std def get_conv_zero_param(model):
64
64
46
7
56
TanayNarshana/rethinking-network-pruning
cifar/weight-level/utils/misc.py
Python
get_conv_zero_param
get_conv_zero_param
29
34
29
29
9b871b91711ec26928bc7b4529818d29b7e5d87c
bigcode/the-stack
train
a4932036c8d4b2efca9c44da
train
function
def mkdir_p(path): '''make dir if not exist''' try: os.makedirs(path) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise
def mkdir_p(path):
'''make dir if not exist''' try: os.makedirs(path) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise
nn.BatchNorm2d): init.constant(m.weight, 1) init.constant(m.bias, 0) elif isinstance(m, nn.Linear): init.normal(m.weight, std=1e-3) if m.bias: init.constant(m.bias, 0) def mkdir_p(path):
64
64
61
5
59
TanayNarshana/rethinking-network-pruning
cifar/weight-level/utils/misc.py
Python
mkdir_p
mkdir_p
51
59
51
51
6f4425b7b1627d355fb0eb09249fbe6d33ec3937
bigcode/the-stack
train
1912b8403e13420d3673821e
train
function
def init_params(net): '''Init layer parameters.''' for m in net.modules(): if isinstance(m, nn.Conv2d): init.kaiming_normal(m.weight, mode='fan_out') if m.bias: init.constant(m.bias, 0) elif isinstance(m, nn.BatchNorm2d): init.constant(m.weight...
def init_params(net):
'''Init layer parameters.''' for m in net.modules(): if isinstance(m, nn.Conv2d): init.kaiming_normal(m.weight, mode='fan_out') if m.bias: init.constant(m.bias, 0) elif isinstance(m, nn.BatchNorm2d): init.constant(m.weight, 1) init....
std.div_(len(dataset)) return mean, std def get_conv_zero_param(model): total = 0 for m in model.modules(): if isinstance(m, nn.Conv2d): total += torch.sum(m.weight.data.eq(0)) return total def init_params(net):
64
64
121
5
58
TanayNarshana/rethinking-network-pruning
cifar/weight-level/utils/misc.py
Python
init_params
init_params
36
49
36
36
491478a4c24fe5001c8e3424a4cc36043f8ab8b7
bigcode/the-stack
train
b4e2cfe886ceb9a6c03c5de3
train
class
class AverageMeter(object): """Computes and stores the average and current value Imported from https://github.com/pytorch/examples/blob/master/imagenet/main.py#L247-L262 """ def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 ...
class AverageMeter(object):
"""Computes and stores the average and current value Imported from https://github.com/pytorch/examples/blob/master/imagenet/main.py#L247-L262 """ def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 d...
_p(path): '''make dir if not exist''' try: os.makedirs(path) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise class AverageMeter(object):
64
64
126
5
58
TanayNarshana/rethinking-network-pruning
cifar/weight-level/utils/misc.py
Python
AverageMeter
AverageMeter
61
78
61
61
b09043b96d0d5b9ad491d96ee123de9c2f531368
bigcode/the-stack
train
2071e5073d71520fdbfd92b6
train
class
class EzFlask: def __init__(self): self.app = flask.Flask('') @self.app.route('/') def _index(): return _get_html('index.html') @self.app.route('/<path>') def _get(path): return _get_html(escape(path)) def run(self): ...
class EzFlask:
def __init__(self): self.app = flask.Flask('') @self.app.route('/') def _index(): return _get_html('index.html') @self.app.route('/<path>') def _get(path): return _get_html(escape(path)) def run(self): self.app.run(ho...
'\ 'If you entered the URL manually please check your spelling and try again.</p> ' def _get_html(path): try: with open(path, 'r') as file: return file.read() except FileNotFoundError: return PNF class EzFlask:
64
64
92
5
58
SmartMozart/ezflask
ezflask.py
Python
EzFlask
EzFlask
16
29
16
16
e5965f5be8e402252894eb42a670be8b005c83dc
bigcode/the-stack
train
1bd3d205918f65a7aa735aaf
train
function
def _get_html(path): try: with open(path, 'r') as file: return file.read() except FileNotFoundError: return PNF
def _get_html(path):
try: with open(path, 'r') as file: return file.read() except FileNotFoundError: return PNF
PNF = '<!DOCTYPE html><title>404 Not Found</title><h1>Not Found</h1><p>The requested URL was not found on the server. '\ 'If you entered the URL manually please check your spelling and try again.</p> ' def _get_html(path):
63
64
37
6
57
SmartMozart/ezflask
ezflask.py
Python
_get_html
_get_html
8
13
8
8
3992222bfc65ca22d2dab6fedb90639c0bd7c53d
bigcode/the-stack
train
5ecf37a95a1404bfd018064a
train
class
class IsUserlandTest(fixtures.MappedTest): @classmethod def define_tables(cls, metadata): Table( "foo", metadata, Column("id", Integer, primary_key=True), Column("someprop", Integer), ) def _test(self, value, instancelevel=None): class...
class IsUserlandTest(fixtures.MappedTest): @classmethod
def define_tables(cls, metadata): Table( "foo", metadata, Column("id", Integer, primary_key=True), Column("someprop", Integer), ) def _test(self, value, instancelevel=None): class Foo: someprop = value m = self.mapper(...
): self.value = "foobar" return self.value self.mapper(H1, ht1) self.mapper(H2, ht1) h1 = H1() h1.value = "Asdf" h1.value = "asdf asdf" # ding h2 = H2() h2.value = "Asdf" h2.value = "asdf asdf" # ding class IsUserlandTe...
106
106
354
15
90
brussee/sqlalchemy
test/orm/test_mapper.py
Python
IsUserlandTest
IsUserlandTest
2,519
2,575
2,519
2,520
d856623fd9bde48c05774e0a1c0f6595b9e7be9e
bigcode/the-stack
train
2fd69242d62508d4d4ad5d15
train
class
class ORMLoggingTest(_fixtures.FixtureTest): def setup_test(self): self.buf = logging.handlers.BufferingHandler(100) for log in [logging.getLogger("sqlalchemy.orm")]: log.addHandler(self.buf) self.mapper = registry().map_imperatively def teardown_test(self): for log...
class ORMLoggingTest(_fixtures.FixtureTest):
def setup_test(self): self.buf = logging.handlers.BufferingHandler(100) for log in [logging.getLogger("sqlalchemy.orm")]: log.addHandler(self.buf) self.mapper = registry().map_imperatively def teardown_test(self): for log in [logging.getLogger("sqlalchemy.orm")]: ...
eq_(Foo.bars.__doc__, "bar relationship") eq_(Foo.hoho.__doc__, "syn of col4") eq_(Bar.col1.__doc__, "primary key column") eq_(Bar.foo.__doc__, "foo relationship") class ORMLoggingTest(_fixtures.FixtureTest):
64
64
191
10
54
brussee/sqlalchemy
test/orm/test_mapper.py
Python
ORMLoggingTest
ORMLoggingTest
2,771
2,795
2,771
2,771
de92d69c49768de70bd6a145e38d2f7fb41e9260
bigcode/the-stack
train
34b1ad17e8ab9e28d47f4718
train
class
class MagicNamesTest(fixtures.MappedTest): @classmethod def define_tables(cls, metadata): Table( "cartographers", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("name", String(50)), ...
class MagicNamesTest(fixtures.MappedTest): @classmethod
def define_tables(cls, metadata): Table( "cartographers", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("name", String(50)), Column("alias", String(50)), Column("q...
class Foo: someprop = value m = self.mapper(Foo, self.tables.foo) is_(Foo.someprop.property.columns[0], self.tables.foo.c.someprop) assert self.tables.foo.c.someprop in m._columntoproperty def test_string(self): self._test("someprop") def test_unicode(self): ...
205
205
685
14
191
brussee/sqlalchemy
test/orm/test_mapper.py
Python
MagicNamesTest
MagicNamesTest
2,578
2,704
2,578
2,579
c34721052ff748cab7706e6578bc233ea1b8e6c3
bigcode/the-stack
train
e0c76354f9e6462d8f7f9aec
train
class
class RequirementsTest(fixtures.MappedTest): """Tests the contract for user classes.""" @classmethod def define_tables(cls, metadata): Table( "ht1", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), ...
class RequirementsTest(fixtures.MappedTest):
"""Tests the contract for user classes.""" @classmethod def define_tables(cls, metadata): Table( "ht1", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("value", String(10)), ...
name"), (["foo"], (), ())) # using it with an ORM operation, raises assert_raises( sa.orm.exc.UnmappedClassError, fixture_session().add, Sub() ) def test_unmapped_subclass_error_premap(self): users = self.tables.users class Base: pass self....
256
256
1,820
9
247
brussee/sqlalchemy
test/orm/test_mapper.py
Python
RequirementsTest
RequirementsTest
2,262
2,516
2,262
2,263
582865c1ab18cf1c29cfafd61d78dd63643c12fb
bigcode/the-stack
train
6a8687473742ef7142f72fdb
train
class
class DocumentTest(fixtures.TestBase): def setup_test(self): self.mapper = registry().map_imperatively def test_doc_propagate(self): metadata = MetaData() t1 = Table( "t1", metadata, Column( "col1", Integer, primary_key=True, doc="pri...
class DocumentTest(fixtures.TestBase):
def setup_test(self): self.mapper = registry().map_imperatively def test_doc_propagate(self): metadata = MetaData() t1 = Table( "t1", metadata, Column( "col1", Integer, primary_key=True, doc="primary key column" ), ...
t, ) def test_indirect_stateish(self): maps = self.tables.maps for reserved in ( sa.orm.instrumentation.ClassManager.STATE_ATTR, sa.orm.instrumentation.ClassManager.MANAGER_ATTR, ): class M: pass ...
129
129
433
8
121
brussee/sqlalchemy
test/orm/test_mapper.py
Python
DocumentTest
DocumentTest
2,707
2,768
2,707
2,707
2da2d0973c2700f033dcde772a99312d3c54e20a
bigcode/the-stack
train
da2623fd8da2c0d532be94fd
train
class
class MapperTest(_fixtures.FixtureTest, AssertsCompiledSQL): __dialect__ = "default" def test_decl_attributes(self): """declarative mapper() now sets up some of the convenience attributes""" Address, addresses, users, User = ( self.classes.Address, self.tables.a...
class MapperTest(_fixtures.FixtureTest, AssertsCompiledSQL):
__dialect__ = "default" def test_decl_attributes(self): """declarative mapper() now sets up some of the convenience attributes""" Address, addresses, users, User = ( self.classes.Address, self.tables.addresses, self.tables.users, self.cla...
sqlalchemy.orm import aliased from sqlalchemy.orm import attributes from sqlalchemy.orm import backref from sqlalchemy.orm import class_mapper from sqlalchemy.orm import clear_mappers from sqlalchemy.orm import column_property from sqlalchemy.orm import composite from sqlalchemy.orm import configure_mappers from sqlal...
256
256
13,363
14
241
brussee/sqlalchemy
test/orm/test_mapper.py
Python
MapperTest
MapperTest
50
2,259
50
50
4eed6f8aa66034bff4aa0f49666e38fdf5a076ef
bigcode/the-stack
train
51e5c724dfdfd1e7cbd4e90c
train
class
class RegistryConfigDisposeTest(fixtures.TestBase): """test the cascading behavior of registry configure / dispose.""" @testing.fixture def threeway_fixture(self): reg1 = registry() reg2 = registry() reg3 = registry() ab = bc = True @reg1.mapped class A: ...
class RegistryConfigDisposeTest(fixtures.TestBase):
"""test the cascading behavior of registry configure / dispose.""" @testing.fixture def threeway_fixture(self): reg1 = registry() reg2 = registry() reg3 = registry() ab = bc = True @reg1.mapped class A: __tablename__ = "a" id = Colum...
self.mapper(User, users) self.mapper( Address, addresses, properties={ "user": relationship( User, comparator_factory=MyFactory, backref=backref( "addresses", comparato...
256
256
1,106
10
246
brussee/sqlalchemy
test/orm/test_mapper.py
Python
RegistryConfigDisposeTest
RegistryConfigDisposeTest
2,960
3,112
2,960
2,960
49e2fd09bc8fda855f09c06ebae6902fc565824b
bigcode/the-stack
train
3f2828e3d6179087bc8766c9
train
class
class ConfigureOrNotConfigureTest(_fixtures.FixtureTest, AssertsCompiledSQL): __dialect__ = "default" @testing.combinations((True,), (False,)) def test_no_mapper_configure_w_selects_etc(self, use_legacy_query): Address, addresses, users, User = ( self.classes.Address, self.t...
class ConfigureOrNotConfigureTest(_fixtures.FixtureTest, AssertsCompiledSQL):
__dialect__ = "default" @testing.combinations((True,), (False,)) def test_no_mapper_configure_w_selects_etc(self, use_legacy_query): Address, addresses, users, User = ( self.classes.Address, self.tables.addresses, self.tables.users, self.classes.User,...
._dispose_called) is_true(am._dispose_called) @testing.combinations((True,), (False,), argnames="cascade") def test_clear_cascade_not_on_dependents( self, threeway_configured_fixture, cascade ): reg1, reg2, reg3 = threeway_configured_fixture A, B, C = ( reg1._cla...
256
256
875
17
239
brussee/sqlalchemy
test/orm/test_mapper.py
Python
ConfigureOrNotConfigureTest
ConfigureOrNotConfigureTest
3,115
3,247
3,115
3,115
9588fedcdbfbdb35cd470471e0864ef4228c28ae
bigcode/the-stack
train
8b316711f8249e617aecd127
train
class
class ComparatorFactoryTest(_fixtures.FixtureTest, AssertsCompiledSQL): def test_kwarg_accepted(self): users, Address = self.tables.users, self.classes.Address class DummyComposite: def __init__(self, x, y): pass from sqlalchemy.orm.interfaces import PropCompara...
class ComparatorFactoryTest(_fixtures.FixtureTest, AssertsCompiledSQL):
def test_kwarg_accepted(self): users, Address = self.tables.users, self.classes.Address class DummyComposite: def __init__(self, x, y): pass from sqlalchemy.orm.interfaces import PropComparator class MyFactory(PropComparator): pass ...
ars.__doc__, "bar relationship") eq_(Foo.hoho.__doc__, "syn of col4") eq_(Bar.col1.__doc__, "primary key column") eq_(Bar.foo.__doc__, "foo relationship") class ORMLoggingTest(_fixtures.FixtureTest): def setup_test(self): self.buf = logging.handlers.BufferingHandler(100) fo...
256
256
986
15
241
brussee/sqlalchemy
test/orm/test_mapper.py
Python
ComparatorFactoryTest
ComparatorFactoryTest
2,798
2,957
2,798
2,798
44fab69222bd0f62f3821cc85c741f4051a57dae
bigcode/the-stack
train
909952b02a83d8759c95d70c
train
class
class CreateDemandRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Ecs', '2014-05-26', 'CreateDemand','ecs') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, ...
class CreateDemandRequest(RpcRequest):
def __init__(self): RpcRequest.__init__(self, 'Ecs', '2014-05-26', 'CreateDemand','ecs') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEn...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
204
244
816
8
195
yndu13/aliyun-openapi-python-sdk
aliyun-python-sdk-ecs/aliyunsdkecs/request/v20140526/CreateDemandRequest.py
Python
CreateDemandRequest
CreateDemandRequest
23
108
23
24
9cf1bc1c53751187fc12504302471d82cde74bb9
bigcode/the-stack
train
f0593825b55b03aafc8a6d46
train
class
class Proj2012DownloaderMiddleware: # Not all methods need to be defined. If a method is not defined, # scrapy acts as if the downloader middleware does not modify the # passed objects. @classmethod def from_crawler(cls, crawler): # This method is used by Scrapy to create your spiders. ...
class Proj2012DownloaderMiddleware: # Not all methods need to be defined. If a method is not defined, # scrapy acts as if the downloader middleware does not modify the # passed objects. @classmethod
def from_crawler(cls, crawler): # This method is used by Scrapy to create your spiders. s = cls() crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) return s def process_request(self, request, spider): # Called for each request that goes through the d...
# that it doesn’t have a response associated. # Must return only requests (not items). for r in start_requests: yield r def spider_opened(self, spider): spider.logger.info('Spider opened: %s' % spider.name) class Proj2012DownloaderMiddleware: # Not all methods need...
105
105
350
48
57
miccaldas/new_rss
support_files/scraping/entries/proj_2012/proj_2012/middlewares.py
Python
Proj2012DownloaderMiddleware
Proj2012DownloaderMiddleware
59
103
59
64
0eeb0866be1cdaf3057d3b72116eab6b5c813490
bigcode/the-stack
train
85cf3c073c965de1d74ce997
train
class
class Proj2012SpiderMiddleware: # Not all methods need to be defined. If a method is not defined, # scrapy acts as if the spider middleware does not modify the # passed objects. @classmethod def from_crawler(cls, crawler): # This method is used by Scrapy to create your spiders. s = ...
class Proj2012SpiderMiddleware: # Not all methods need to be defined. If a method is not defined, # scrapy acts as if the spider middleware does not modify the # passed objects. @classmethod
def from_crawler(cls, crawler): # This method is used by Scrapy to create your spiders. s = cls() crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) return s def process_spider_input(self, response, spider): # Called for each response that goes throug...
# Define here the models for your spider middleware # # See documentation in: # https://docs.scrapy.org/en/latest/topics/spider-middleware.html from scrapy import signals # useful for handling different item types with a single interface from itemadapter import is_item, ItemAdapter class Proj2012SpiderMiddleware: ...
107
107
357
48
58
miccaldas/new_rss
support_files/scraping/entries/proj_2012/proj_2012/middlewares.py
Python
Proj2012SpiderMiddleware
Proj2012SpiderMiddleware
12
56
12
17
f08e46fe7f42cbc86b639dd3a435b67af3a49bc7
bigcode/the-stack
train
943dd1bfa0eff9576373e3a7
train
class
class EditModelTemplateTagTest(ToolbarTestBase): urls = 'cms.test_utils.project.placeholderapp_urls' edit_fields_rx = "(\?|&amp;)edit_fields=%s" def tearDown(self): Example1.objects.all().delete() MultilingualExample1.objects.all().delete() super(EditModelTemplateTagTest, self).tear...
class EditModelTemplateTagTest(ToolbarTestBase):
urls = 'cms.test_utils.project.placeholderapp_urls' edit_fields_rx = "(\?|&amp;)edit_fields=%s" def tearDown(self): Example1.objects.all().delete() MultilingualExample1.objects.all().delete() super(EditModelTemplateTagTest, self).tearDown() def test_anon(self): user = s...
%s' % get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON')) toolbar = response.context['request'].toolbar admin_menu = toolbar.get_or_create_menu(ADMIN_MENU_IDENTIFIER) self.assertEquals(admin_menu.find_first(AjaxItem, name=menu_name).item.on_success, '/') # Published page with ...
255
256
8,518
12
242
donce/django-cms
cms/tests/toolbar.py
Python
EditModelTemplateTagTest
EditModelTemplateTagTest
479
1,270
479
479
cd009274987ffda2011f80126557def076d0de3f
bigcode/the-stack
train
5a96341551143ced05ce390a
train
class
class CharPkFrontendPlaceholderAdminTest(ToolbarTestBase): def get_admin(self): admin.autodiscover() return admin.site._registry[CharPksExample] def test_url_char_pk(self): """ Tests whether the frontend admin matches the edit_fields url with alphanumeric pks """ ...
class CharPkFrontendPlaceholderAdminTest(ToolbarTestBase):
def get_admin(self): admin.autodiscover() return admin.site._registry[CharPksExample] def test_url_char_pk(self): """ Tests whether the frontend admin matches the edit_fields url with alphanumeric pks """ ex = CharPksExample( char_1='one', ...
response, '<div class="cms_plugin cms_plugin-cms-page-get_page_title-%s cms_render_model">%s</div>' % ( page.pk, page.get_page_title(language))) self.assertContains( response, '<div class="cms_plugin cms_plugin-cms-page-get_menu_title-%s cms_render_model">%s<...
187
187
624
13
174
donce/django-cms
cms/tests/toolbar.py
Python
CharPkFrontendPlaceholderAdminTest
CharPkFrontendPlaceholderAdminTest
1,273
1,347
1,273
1,274
0da08f0796f9531bed3f576530892a57fc9d3da0
bigcode/the-stack
train
8fd52715ce584ee6b11df8b9
train
class
class ToolbarTestBase(CMSTestCase): def get_page_request(self, page, user, path=None, edit=False, lang_code='en'): path = path or page and page.get_absolute_url() if edit: path += '?%s' % get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON') request = RequestFactory().get(path) req...
class ToolbarTestBase(CMSTestCase):
def get_page_request(self, page, user, path=None, edit=False, lang_code='en'): path = path or page and page.get_absolute_url() if edit: path += '?%s' % get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON') request = RequestFactory().get(path) request.session = {} request.us...
detail_view_multi_unfiltered) from cms.test_utils.testcases import (CMSTestCase, URL_CMS_PAGE_ADD, URL_CMS_PAGE_CHANGE) from cms.test_utils.util.context_managers import UserLoginContext from cms.utils.conf import get_cms_sett...
81
81
273
10
70
donce/django-cms
cms/tests/toolbar.py
Python
ToolbarTestBase
ToolbarTestBase
36
70
36
36
dc879eda92d1ff00f1fd0a22be157ad9e065c6cd
bigcode/the-stack
train
a60744896a2817612435e2d2
train
class
@override_settings(CMS_PERMISSION=False) class ToolbarTests(ToolbarTestBase): def test_no_page_anon(self): request = self.get_page_request(None, self.get_anon(), '/') toolbar = CMSToolbar(request) toolbar.populate() toolbar.post_template_populate() items = toolbar.get_left_i...
@override_settings(CMS_PERMISSION=False) class ToolbarTests(ToolbarTestBase):
def test_no_page_anon(self): request = self.get_page_request(None, self.get_anon(), '/') toolbar = CMSToolbar(request) toolbar.populate() toolbar.post_template_populate() items = toolbar.get_left_items() + toolbar.get_right_items() self.assertEqual(len(items), 0) ...
= path or page and page.get_absolute_url() if edit: path += '?%s' % get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON') request = RequestFactory().get(path) request.session = {} request.user = user request.LANGUAGE_CODE = lang_code if edit: request.GET = ...
256
256
4,376
17
238
donce/django-cms
cms/tests/toolbar.py
Python
ToolbarTests
ToolbarTests
73
476
73
75
278b68465c045b352704814c0441153b02598c1f
bigcode/the-stack
train
0728555de3f935e5df506f5e
train
class
class ToolbarAPITests(TestCase): def test_find_item(self): api = ToolbarAPIMixin() first = api.add_link_item('First', 'http://www.example.org') second = api.add_link_item('Second', 'http://www.example.org') all_links = api.find_items(LinkItem) self.assertEqual(len(all_links),...
class ToolbarAPITests(TestCase):
def test_find_item(self): api = ToolbarAPIMixin() first = api.add_link_item('First', 'http://www.example.org') second = api.add_link_item('Second', 'http://www.example.org') all_links = api.find_items(LinkItem) self.assertEqual(len(all_links), 2) result = api.find_fir...
""" page = create_page('Test', 'col_two.html', 'en', published=True) ex = Example1( char_1='one', char_2='two', char_3='tree', char_4='four' ) ex.save() superuser = self.get_superuser() request = self.get_page_reques...
124
124
416
8
116
donce/django-cms
cms/tests/toolbar.py
Python
ToolbarAPITests
ToolbarAPITests
1,350
1,392
1,350
1,350
05ac2d1a985bf7a52bbf19a8b1df155f2df97b35
bigcode/the-stack
train
b6486581ec9093b6f5e21e76
train
class
class Draco(CMakePackage): """Draco is an object-oriented component library geared towards numerically intensive, radiation (particle) transport applications built for parallel computing hardware. It consists of semi-independent packages and a robust build system. """ homepage = "https://github.com...
class Draco(CMakePackage):
"""Draco is an object-oriented component library geared towards numerically intensive, radiation (particle) transport applications built for parallel computing hardware. It consists of semi-independent packages and a robust build system. """ homepage = "https://github.com/lanl/draco" url = "htt...
# Copyright 2013-2020 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 Draco(CMakePackage):
60
256
1,224
6
54
xiki-tempula/spack
var/spack/repos/builtin/packages/draco/package.py
Python
Draco
Draco
9
75
9
9
48f751f9d59f5da1016fa18e244a2a0d87dfab00
bigcode/the-stack
train
142072a4fe9a32ce1b857780
train
function
def boundary(T): """ Returns the boundary edges of the given input topology Parameters ---------- T : LongTensor the input topology tensor Returns ------- LongTensor the boundary edge tensor """ E = poly2edge(T)[0] _, j, e = unique(torch.sort(E, 1)[0]...
def boundary(T):
""" Returns the boundary edges of the given input topology Parameters ---------- T : LongTensor the input topology tensor Returns ------- LongTensor the boundary edge tensor """ E = poly2edge(T)[0] _, j, e = unique(torch.sort(E, 1)[0], ByRows=True) ...
import torch from ..utility.unique import * from ..utility.accumarray import * from .poly2edge import * def boundary(T):
30
64
106
4
26
mauriziokovacic/ACME
ACME/topology/boundary.py
Python
boundary
boundary
7
25
7
7
a706db3074da46274536ea9b26bdb86cf75da7b9
bigcode/the-stack
train
8659669bf9c862659367d3d0
train
class
class TapeOperationRecorder(QuantumTape): """A template and quantum function inspector, allowing easy introspection of operators that have been applied without requiring a QNode. **Example**: The OperationRecorder is a context manager. Executing templates or quantum functions stores ap...
class TapeOperationRecorder(QuantumTape):
"""A template and quantum function inspector, allowing easy introspection of operators that have been applied without requiring a QNode. **Example**: The OperationRecorder is a context manager. Executing templates or quantum functions stores applied operators in the recorder, which...
See the License for the specific language governing permissions and # limitations under the License. """ This subpackage contains various quantum tapes, which track, queue, validate, execute, and differentiate quantum circuits. """ import contextlib import inspect import functools from unittest import mock i...
173
174
582
8
165
DanielPolatajko/pennylane
pennylane/tape/__init__.py
Python
TapeOperationRecorder
TapeOperationRecorder
44
117
44
44
f55bd50798409ad68c9126209f30463e0b5674a2
bigcode/the-stack
train
7b7e774f621690d161921a1e
train
function
def TapeTemplateDecorator(func): """Register a quantum template with PennyLane. This decorator wraps the given function and makes it return a list of all queued Operations. **Example:** When defining a :doc:`template </introduction/templates>`, simply decorate the template function with t...
def TapeTemplateDecorator(func):
"""Register a quantum template with PennyLane. This decorator wraps the given function and makes it return a list of all queued Operations. **Example:** When defining a :doc:`template </introduction/templates>`, simply decorate the template function with this decorator. .. code-bloc...
\n" for op in self.ops: output += repr(op) + "\n" output += "\n" output += "Observables\n" output += "==========\n" for op in self.obs: output += repr(op) + "\n" return output @property def queue(self): return self....
85
86
288
6
78
DanielPolatajko/pennylane
pennylane/tape/__init__.py
Python
TapeTemplateDecorator
TapeTemplateDecorator
120
163
120
120
ef2e59d2dd0e50ac57aa71c693094df2edb82775
bigcode/the-stack
train
9be1f8ee8f12372aeb34a3bc
train
function
def disable_tape(): """Disable tape mode. This function may be called at any time after :func:`~.enable_tape` has been executed in order to disable tape mode. Tape mode is an experimental new mode of PennyLane. QNodes created in tape mode have support for in-QNode classical processing, diff...
def disable_tape():
"""Disable tape mode. This function may be called at any time after :func:`~.enable_tape` has been executed in order to disable tape mode. Tape mode is an experimental new mode of PennyLane. QNodes created in tape mode have support for in-QNode classical processing, differentiable quantum de...
._queuing.OperationRecorder", TapeOperationRecorder), mock.patch("pennylane.template", TapeTemplateDecorator), ] with contextlib.ExitStack() as stack: for m in mocks: stack.enter_context(m) _mock_stack.append(stack.pop_all()) def disable_tape():
63
64
147
5
58
DanielPolatajko/pennylane
pennylane/tape/__init__.py
Python
disable_tape
disable_tape
219
234
219
219
5344a852de09f1129f93f77b5afb7631ac5b958c
bigcode/the-stack
train
e990c2fafe211ed7c8d529d6
train
function
def enable_tape(): """Enable tape mode. Tape mode is an experimental new mode of PennyLane. QNodes created in tape mode have support for in-QNode classical processing, differentiable quantum decompositions, returning the quantum state, less restrictive QNode signatures, and various other improveme...
def enable_tape():
"""Enable tape mode. Tape mode is an experimental new mode of PennyLane. QNodes created in tape mode have support for in-QNode classical processing, differentiable quantum decompositions, returning the quantum state, less restrictive QNode signatures, and various other improvements. For more...
ml.device('default.qubit', wires=2) @qml.qnode(dev) def circuit(): qml.inv(bell_state_preparation(wires=[0, 1])) return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) Args: func (callable): A template function Returns: callable: The wrapper functi...
139
139
464
5
133
DanielPolatajko/pennylane
pennylane/tape/__init__.py
Python
enable_tape
enable_tape
166
216
166
166
30a54b955210fa55a4328cc2a270d9269ea41fb5
bigcode/the-stack
train
d3bdb9522d34ac5c843eeaaf
train
function
def tape_mode_active(): """Returns whether tape mode is enabled.""" return inspect.isclass(qml.QNode) and issubclass(qml.QNode, qml.tape.QNode)
def tape_mode_active():
"""Returns whether tape mode is enabled.""" return inspect.isclass(qml.QNode) and issubclass(qml.QNode, qml.tape.QNode)
signatures, and various other improvements. For more details on tape mode, see :mod:`~.tape`. """ if not _mock_stack: warnings.warn("Tape mode is not currently enabled.", UserWarning) else: _mock_stack.pop().close() def tape_mode_active():
64
64
41
5
59
DanielPolatajko/pennylane
pennylane/tape/__init__.py
Python
tape_mode_active
tape_mode_active
237
239
237
237
87cb2a731c5f7f00729e756dba80c01afe1476cf
bigcode/the-stack
train
bf6dea86225ab8833c798f65
train
class
class WaveletTest(parameterized.TestCase, tf.test.TestCase): def setUp(self): super(WaveletTest, self).setUp() np.random.seed(0) def _assert_pyramids_close(self, x0, x1, epsilon): """A helper function for assering that two wavelet pyramids are close.""" if isinstance(x0, tuple) or isinstance(x0, l...
class WaveletTest(parameterized.TestCase, tf.test.TestCase):
def setUp(self): super(WaveletTest, self).setUp() np.random.seed(0) def _assert_pyramids_close(self, x0, x1, epsilon): """A helper function for assering that two wavelet pyramids are close.""" if isinstance(x0, tuple) or isinstance(x0, list): assert isinstance(x1, (list, tuple)) assert ...
# coding=utf-8 # Copyright 2019 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
205
256
3,996
14
191
rmitra/google-research
robust_loss/wavelet_test.py
Python
WaveletTest
WaveletTest
29
367
29
30
1d92c9a42e66f31c1057ff465c217ce09ce7aef1
bigcode/the-stack
train
67ea1f5750e6b7b14976210f
train
function
def load_model(model_file): torch.set_default_tensor_type('torch.cuda.FloatTensor') set_cfg('yolact_plus_resnet50_config') net = Yolact() net.load_weights(model_file) net.eval() return net
def load_model(model_file):
torch.set_default_tensor_type('torch.cuda.FloatTensor') set_cfg('yolact_plus_resnet50_config') net = Yolact() net.load_weights(model_file) net.eval() return net
import sys import cv2 import rbcompiler.api_v2 as rb import pyRbRuntime as rt import numpy as np # register pyruntime op import sg.dcn import torch from yolact import Yolact from data import set_cfg def load_model(model_file):
61
64
52
6
54
aksenventwo/yolact
export_sg.py
Python
load_model
load_model
14
20
14
14
9c6d2bb937f868cfeb78c43db1b83e96257cbb40
bigcode/the-stack
train
324de6a19b30b60b23925115
train
function
def export_sg(net): # generate sg sg = rb.gen_sg_from_pytorch(net, input_shape=[1, 3, 550, 550]) rb.save_sg(sg, 'yolact_plus.sg')
def export_sg(net): # generate sg
sg = rb.gen_sg_from_pytorch(net, input_shape=[1, 3, 550, 550]) rb.save_sg(sg, 'yolact_plus.sg')
def load_model(model_file): torch.set_default_tensor_type('torch.cuda.FloatTensor') set_cfg('yolact_plus_resnet50_config') net = Yolact() net.load_weights(model_file) net.eval() return net def export_sg(net): # generate sg
64
64
52
11
52
aksenventwo/yolact
export_sg.py
Python
export_sg
export_sg
22
25
22
23
055f58d77fe595dab7f5e82245438fcfadbf65a7
bigcode/the-stack
train
db59dc804438aaae261c8b9a
train
class
class DoorSettings(AutoFormSettings): spec = OrderedDict([ ("direction", {"type": "choice", "choices": ["north", "south", "east", "west"], "tooltip": "Set the direction to this door from currently" " selected tile"}), ("prefix", {"type": "str", "tooltip": ...
class DoorSettings(AutoFormSettings):
spec = OrderedDict([ ("direction", {"type": "choice", "choices": ["north", "south", "east", "west"], "tooltip": "Set the direction to this door from currently" " selected tile"}), ("prefix", {"type": "str", "tooltip": "Set the word that should precede " ...
": "Enable/disable wall to the south"}), ("east", {"type": "bool", "tooltip": "Enable/disable wall to the east"}), ("west", {"type": "bool", "tooltip": "Enable/disable wall to the west"}) ]) class DoorSettings(AutoFormSettings):
64
64
189
8
56
eriknyquist/text_map_builder_gui
text_game_map_maker/forms.py
Python
DoorSettings
DoorSettings
21
33
21
21
e4fe38d65ca61762052eb62676ae6064f1c5b995
bigcode/the-stack
train
b0c2d7159c718b3d15da5972
train
class
class AutoFormSettings(object): def __init__(self): if not hasattr(self, "spec"): raise RuntimeError("%s instance has no 'spec' attribute" % self.__class__.__name__) for attrname in self.spec.keys(): setattr(self, attrname, None)
class AutoFormSettings(object):
def __init__(self): if not hasattr(self, "spec"): raise RuntimeError("%s instance has no 'spec' attribute" % self.__class__.__name__) for attrname in self.spec.keys(): setattr(self, attrname, None)
from collections import OrderedDict class AutoFormSettings(object):
12
64
62
6
5
eriknyquist/text_map_builder_gui
text_game_map_maker/forms.py
Python
AutoFormSettings
AutoFormSettings
4
11
4
4
5267cef85a79d0f10293e35ea40ab26f7f7f244f
bigcode/the-stack
train
ba72d76332d11d4c26cc192a
train
class
class TileSettings(AutoFormSettings): spec = OrderedDict([ ('tile_id', {'type': 'str', 'label': 'tile ID', "tooltip": "Unique " "identifier for programmatic access to this tile"}), ('name', {'type': 'str', 'tooltip': "Short string used to describe this " "tile to...
class TileSettings(AutoFormSettings):
spec = OrderedDict([ ('tile_id', {'type': 'str', 'label': 'tile ID', "tooltip": "Unique " "identifier for programmatic access to this tile"}), ('name', {'type': 'str', 'tooltip': "Short string used to describe this " "tile to the player from afar, e.g. 'a scary r...
or 'an' (e.g. 'a' " "wooden door, 'an' oak door)"}), ("name", {"type": "str", "tooltip": "name of this door, e.g. " "'wooden door' or 'oak door'"}), ("tile_id", {"type": "str", "label": "tile ID", "tooltip": "unique " "identifier for programmatic ...
173
173
579
8
165
eriknyquist/text_map_builder_gui
text_game_map_maker/forms.py
Python
TileSettings
TileSettings
53
93
53
53
0cbe1d0eba49037eb489e839f75d3d3c11d68398
bigcode/the-stack
train
3f654ee2a8d1a9879fc10395
train
class
class WallSettings(AutoFormSettings): spec = OrderedDict([ ("north", {"type": "bool", "tooltip": "Enable/disable wall to the north"}), ("south", {"type": "bool", "tooltip": "Enable/disable wall to the south"}), ("east", {"type": "bool", "tooltip": "Enable/disable wall to the east"}), ...
class WallSettings(AutoFormSettings):
spec = OrderedDict([ ("north", {"type": "bool", "tooltip": "Enable/disable wall to the north"}), ("south", {"type": "bool", "tooltip": "Enable/disable wall to the south"}), ("east", {"type": "bool", "tooltip": "Enable/disable wall to the east"}), ("west", {"type": "bool", "tooltip": ...
def __init__(self): if not hasattr(self, "spec"): raise RuntimeError("%s instance has no 'spec' attribute" % self.__class__.__name__) for attrname in self.spec.keys(): setattr(self, attrname, None) class WallSettings(AutoFormSettings):
64
64
104
8
56
eriknyquist/text_map_builder_gui
text_game_map_maker/forms.py
Python
WallSettings
WallSettings
13
19
13
13
c2092044394592a7b5c1bcf719ed977b89397511
bigcode/the-stack
train
19307a16c70fb8837656e9bf
train
class
class KeypadDoorSettings(AutoFormSettings): spec = OrderedDict([ ("direction", {"type": "choice", "choices": ["north", "south", "east", "west"], "tooltip": "Set the direction to this door from currently" " selected tile"}), ("prefix", {"type": "str", "tool...
class KeypadDoorSettings(AutoFormSettings):
spec = OrderedDict([ ("direction", {"type": "choice", "choices": ["north", "south", "east", "west"], "tooltip": "Set the direction to this door from currently" " selected tile"}), ("prefix", {"type": "str", "tooltip": "Set the word that should precede " ...
type": "str", "tooltip": "name of this door, e.g. " "'wooden door' or 'oak door'"}), ("tile_id", {"type": "str", "label": "tile ID", "tooltip": "unique " "identifier for programmatic access to this door"}) ]) class KeypadDoorSettings(AutoFormSettings):
77
77
259
10
67
eriknyquist/text_map_builder_gui
text_game_map_maker/forms.py
Python
KeypadDoorSettings
KeypadDoorSettings
35
51
35
35
16bd928be781dbd94c8758a3166a86a316ff9f88
bigcode/the-stack
train
cbcb41f9c53836ed4955bd7a
train
class
class IsisSRTunnelList(Base): """ISIS MPLS SR Tunnel The IsisSRTunnelList class encapsulates a required isisSRTunnelList resource which will be retrieved from the server every time the property is accessed. """ __slots__ = () _SDM_NAME = 'isisSRTunnelList' _SDM_ATT_MAP = { 'Active': 'ac...
class IsisSRTunnelList(Base):
"""ISIS MPLS SR Tunnel The IsisSRTunnelList class encapsulates a required isisSRTunnelList resource which will be retrieved from the server every time the property is accessed. """ __slots__ = () _SDM_NAME = 'isisSRTunnelList' _SDM_ATT_MAP = { 'Active': 'active', 'Count': 'count...
ight # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or se...
256
256
1,709
8
247
OpenIxia/ixnetwork_restpy
uhd_restpy/testplatform/sessions/ixnetwork/topology/isissrtunnellist_4c3217e504788bc35135af392bfa9c40.py
Python
IsisSRTunnelList
IsisSRTunnelList
27
228
27
27
19cfee74451b9730c2c7daf1ec67b097a6898e8c
bigcode/the-stack
train
9b36176c6cd9ba459eb1ba63
train
class
class StoryEditorTests(BaseStoryEditorControllerTests): def test_can_not_access_story_editor_page_with_invalid_story_id(self): self.login(self.ADMIN_EMAIL) new_story_id = story_services.get_new_story_id() self.get_html_response( '%s/%s' % ( feconf.STORY_EDITOR_...
class StoryEditorTests(BaseStoryEditorControllerTests):
def test_can_not_access_story_editor_page_with_invalid_story_id(self): self.login(self.ADMIN_EMAIL) new_story_id = story_services.get_new_story_id() self.get_html_response( '%s/%s' % ( feconf.STORY_EDITOR_URL_PREFIX, new_story_id), expected_status_in...
category='Mathematics', language_code='en', correctness_feedback_enabled=True) json_response = self.get_json( '%s/%s' % ( feconf.VALIDATE_STORY_EXPLORATIONS_URL_PREFIX, self.story_id), params={ 'comma_separated_exp_ids': '15,0' }) ...
256
256
3,146
10
246
TheoLipeles/oppia
core/controllers/story_editor_test.py
Python
StoryEditorTests
StoryEditorTests
165
581
165
166
cafb11cadf0e6969914f0ba06847da8de90ea479
bigcode/the-stack
train
6b04bee4b6ab799f38fcd63d
train
class
class StoryPublicationTests(BaseStoryEditorControllerTests): def test_put_can_not_publish_story_with_invalid_story_id(self): self.login(self.ADMIN_EMAIL) new_story_id = story_services.get_new_story_id() csrf_token = self.get_new_csrf_token() self.put_json( '%s/%s' % ( ...
class StoryPublicationTests(BaseStoryEditorControllerTests):
def test_put_can_not_publish_story_with_invalid_story_id(self): self.login(self.ADMIN_EMAIL) new_story_id = story_services.get_new_story_id() csrf_token = self.get_new_csrf_token() self.put_json( '%s/%s' % ( feconf.STORY_PUBLISH_HANDLER, new_story_id), ...
self.admin_id = self.get_user_id_from_email(self.ADMIN_EMAIL) self.new_user_id = self.get_user_id_from_email(self.NEW_USER_EMAIL) self.set_admins([self.ADMIN_USERNAME]) self.admin = user_services.get_user_actions_info(self.admin_id) self.topic_id = topic_fetchers.get_new_topic_...
174
174
582
10
164
TheoLipeles/oppia
core/controllers/story_editor_test.py
Python
StoryPublicationTests
StoryPublicationTests
53
125
53
54
5ea819e16211a43d23c04c3b161c9daad45727f1
bigcode/the-stack
train
494455ada97161f1d3e8e578
train
class
class ValidateExplorationsHandlerTests(BaseStoryEditorControllerTests): def test_validation_error_messages(self): # Check that admins can publish a story. self.login(self.ADMIN_EMAIL) self.save_new_valid_exploration( '0', self.admin_id, title='Title 1', category='Mat...
class ValidateExplorationsHandlerTests(BaseStoryEditorControllerTests):
def test_validation_error_messages(self): # Check that admins can publish a story. self.login(self.ADMIN_EMAIL) self.save_new_valid_exploration( '0', self.admin_id, title='Title 1', category='Mathematics', language_code='en', correctness_feedback_enabled=T...
_id: self.assertEqual(reference.story_is_published, False) self.logout() # Check that non-admins cannot publish a story. self.put_json( '%s/%s' % ( feconf.STORY_PUBLISH_HANDLER, self.story_id), {'new_story_status_is_public': True}, csrf_t...
92
92
308
13
79
TheoLipeles/oppia
core/controllers/story_editor_test.py
Python
ValidateExplorationsHandlerTests
ValidateExplorationsHandlerTests
128
162
128
129
83fef7943093dba3dba7c8471db8111181b5d615
bigcode/the-stack
train
168af8332fff7384aa9ff536
train
class
class BaseStoryEditorControllerTests(test_utils.GenericTestBase): def setUp(self): """Completes the sign-up process for the various users.""" super(BaseStoryEditorControllerTests, self).setUp() self.signup(self.ADMIN_EMAIL, self.ADMIN_USERNAME) self.signup(self.NEW_USER_EMAIL, self....
class BaseStoryEditorControllerTests(test_utils.GenericTestBase):
def setUp(self): """Completes the sign-up process for the various users.""" super(BaseStoryEditorControllerTests, self).setUp() self.signup(self.ADMIN_EMAIL, self.ADMIN_USERNAME) self.signup(self.NEW_USER_EMAIL, self.NEW_USER_USERNAME) self.admin_id = self.get_user_id_from_e...
__future__ import unicode_literals # pylint: disable=import-only-modules from core.domain import story_domain from core.domain import story_services from core.domain import topic_fetchers from core.domain import user_services from core.tests import test_utils import feconf class BaseStoryEditorControllerTests(test_u...
69
69
232
12
56
TheoLipeles/oppia
core/controllers/story_editor_test.py
Python
BaseStoryEditorControllerTests
BaseStoryEditorControllerTests
28
50
28
29
61072c8735cf89391be947b1c403cfe11ce17474
bigcode/the-stack
train
c4e67c6725db893830996c6b
train
function
def test_predict(test_df): filters = ['col1 in [0, 2, 4]'] model_exp = 'col1 ~ col2' fit = regression.fit_model(test_df, filters, model_exp) predicted = regression.predict( test_df.query('col1 in [1, 3]'), None, fit) expected = pd.Series([1., 3.], index=['b', 'd']) pdt.assert_series_equa...
def test_predict(test_df):
filters = ['col1 in [0, 2, 4]'] model_exp = 'col1 ~ col2' fit = regression.fit_model(test_df, filters, model_exp) predicted = regression.predict( test_df.query('col1 in [1, 3]'), None, fit) expected = pd.Series([1., 3.], index=['b', 'd']) pdt.assert_series_equal(predicted, expected)
', 'x', 'y'] return test_df def test_fit_model(test_df): filters = [] model_exp = 'col1 ~ col2' fit = regression.fit_model(test_df, filters, model_exp) assert isinstance(fit, RegressionResultsWrapper) def test_predict(test_df):
64
64
103
6
58
tin6150/urbansim
urbansim/models/tests/test_regression.py
Python
test_predict
test_predict
44
51
44
44
2f56f96c21488b70eb1194e83234feb627c70c37
bigcode/the-stack
train
572a31e2200f810e3187919c
train
class
class TestRegressionModelYAMLFit(TestRegressionModelYAMLNotFit): def setup_method(self, method): super(TestRegressionModelYAMLFit, self).setup_method(method) self.model.fit(test_df()) self.expected_dict['fitted'] = True self.expected_dict['fit_rsquared'] = 1.0 self.expected...
class TestRegressionModelYAMLFit(TestRegressionModelYAMLNotFit):
def setup_method(self, method): super(TestRegressionModelYAMLFit, self).setup_method(method) self.model.fit(test_df()) self.expected_dict['fitted'] = True self.expected_dict['fit_rsquared'] = 1.0 self.expected_dict['fit_rsquared_adj'] = 1.0 self.expected_dict['fit_p...
_file = tempfile.NamedTemporaryFile(suffix='.yaml').name self.model.to_yaml(str_or_buffer=test_file) with open(test_file) as f: assert_dict_specs_equal(yaml.safe_load(f), self.expected_dict) model = regression.RegressionModel.from_yaml(str_or_buffer=test_file) assert isinst...
94
94
314
15
79
tin6150/urbansim
urbansim/models/tests/test_regression.py
Python
TestRegressionModelYAMLFit
TestRegressionModelYAMLFit
244
275
244
244
cc534be1fbbda442a8d97c332d7e45b173891550
bigcode/the-stack
train
365ab1af25875f2aea67c15a
train
function
def test_predict_with_nans(): df = pd.DataFrame( {'col1': range(5), 'col2': [5, 6, pd.np.nan, 8, 9]}, index=['a', 'b', 'c', 'd', 'e']) with pytest.raises(ModelEvaluationError): regression.fit_model(df, None, 'col1 ~ col2') fit = regression.fit_model(df.loc[['a', 'b', 'e']]...
def test_predict_with_nans():
df = pd.DataFrame( {'col1': range(5), 'col2': [5, 6, pd.np.nan, 8, 9]}, index=['a', 'b', 'c', 'd', 'e']) with pytest.raises(ModelEvaluationError): regression.fit_model(df, None, 'col1 ~ col2') fit = regression.fit_model(df.loc[['a', 'b', 'e']], None, 'col1 ~ col2') pr...
test_df.query('col1 in [1, 3]'), None, fit, ytransform=yt) expected = pd.Series([0.5, 1.5], index=['b', 'd']) pdt.assert_series_equal(predicted, expected) def test_predict_with_nans():
64
64
140
7
57
tin6150/urbansim
urbansim/models/tests/test_regression.py
Python
test_predict_with_nans
test_predict_with_nans
66
80
66
66
c821538f89deac07d580eee5d4036493d0298902
bigcode/the-stack
train
e6bbd4cd2581b926539d2c76
train
class
class TestRegressionModelYAMLNotFit(object): def setup_method(self, method): fit_filters = ['col1 in [0, 2, 4]'] predict_filters = ['col1 in [1, 3]'] model_exp = 'col1 ~ col2' ytransform = np.log1p name = 'test hedonic' self.model = regression.RegressionModel( ...
class TestRegressionModelYAMLNotFit(object):
def setup_method(self, method): fit_filters = ['col1 in [0, 2, 4]'] predict_filters = ['col1 in [1, 3]'] model_exp = 'col1 ~ col2' ytransform = np.log1p name = 'test hedonic' self.model = regression.RegressionModel( fit_filters, predict_filters, model_exp...
.sort_index(), groupby_df.col1, check_dtype=False, check_names=False) def assert_dict_specs_equal(j1, j2): j1_params = j1.pop('fit_parameters') j2_params = j2.pop('fit_parameters') assert j1 == j2 if j1_params and j2_params: pdt.assert_series_equal( pd.Series(j1_params['C...
125
125
417
10
114
tin6150/urbansim
urbansim/models/tests/test_regression.py
Python
TestRegressionModelYAMLNotFit
TestRegressionModelYAMLNotFit
188
241
188
188
d80947a8a187209f78a290c9c3b465017b4d866c
bigcode/the-stack
train
3a1364eb890177eb105714f9
train
function
def test_SegmentedRegressionModel_yaml(groupby_df): seg = regression.SegmentedRegressionModel( 'group', fit_filters=['col1 not in [2]'], predict_filters=['group != "z"'], default_model_expr='col1 ~ col2', min_segment_size=5000, name='test_seg') seg.add_segment('x') seg.add_segment('y...
def test_SegmentedRegressionModel_yaml(groupby_df):
seg = regression.SegmentedRegressionModel( 'group', fit_filters=['col1 not in [2]'], predict_filters=['group != "z"'], default_model_expr='col1 ~ col2', min_segment_size=5000, name='test_seg') seg.add_segment('x') seg.add_segment('y', 'np.exp(col2) ~ np.exp(col1)', np.log) expec...
seg.add_segment('x', 'col1 ~ col2') seg.add_segment('y', 'np.exp(col2) ~ np.exp(col1)', np.log) assert set(seg.columns_used()) == {'col1', 'col2', 'group'} fits = seg.fit(groupby_df) assert 'x' in fits and 'y' in fits assert isinstance(fits['x'], RegressionResultsWrapper) test_data = pd.Da...
193
194
649
12
181
tin6150/urbansim
urbansim/models/tests/test_regression.py
Python
test_SegmentedRegressionModel_yaml
test_SegmentedRegressionModel_yaml
338
408
338
338
e229927e33bc355676c704673547531882a2aa81
bigcode/the-stack
train
15297b9340a99dcc0ed4c787
train
function
def test_SegmentedRegressionModel_removes_gone_segments(groupby_df): seg = regression.SegmentedRegressionModel( 'group', default_model_expr='col1 ~ col2') seg.add_segment('a') seg.add_segment('b') seg.add_segment('c') seg.fit(groupby_df) assert sorted(seg._group.models.keys()) == ['x',...
def test_SegmentedRegressionModel_removes_gone_segments(groupby_df):
seg = regression.SegmentedRegressionModel( 'group', default_model_expr='col1 ~ col2') seg.add_segment('a') seg.add_segment('b') seg.add_segment('c') seg.fit(groupby_df) assert sorted(seg._group.models.keys()) == ['x', 'y']
_dict['models']['y'].pop('fit_rsquared_adj'), float) assert actual_dict == expected_dict new_seg = regression.SegmentedRegressionModel.from_yaml(seg.to_yaml()) assert new_seg.fitted is True def test_SegmentedRegressionModel_removes_gone_segments(groupby_df):
64
64
84
16
47
tin6150/urbansim
urbansim/models/tests/test_regression.py
Python
test_SegmentedRegressionModel_removes_gone_segments
test_SegmentedRegressionModel_removes_gone_segments
411
420
411
411
ff85615e831e0dae6bc328d3367fd1f485f39391
bigcode/the-stack
train
90774459a1d8fd4af5d25b8a
train
function
def test_predict_ytransform(test_df): def yt(x): return x / 2. filters = ['col1 in [0, 2, 4]'] model_exp = 'col1 ~ col2' fit = regression.fit_model(test_df, filters, model_exp) predicted = regression.predict( test_df.query('col1 in [1, 3]'), None, fit, ytransform=yt) expected = p...
def test_predict_ytransform(test_df):
def yt(x): return x / 2. filters = ['col1 in [0, 2, 4]'] model_exp = 'col1 ~ col2' fit = regression.fit_model(test_df, filters, model_exp) predicted = regression.predict( test_df.query('col1 in [1, 3]'), None, fit, ytransform=yt) expected = pd.Series([0.5, 1.5], index=['b', 'd'])...
) predicted = regression.predict( test_df.query('col1 in [1, 3]'), None, fit) expected = pd.Series([1., 3.], index=['b', 'd']) pdt.assert_series_equal(predicted, expected) def test_predict_ytransform(test_df):
64
64
125
8
56
tin6150/urbansim
urbansim/models/tests/test_regression.py
Python
test_predict_ytransform
test_predict_ytransform
54
63
54
54
07b3098defac3c6d2432b83ef96ed2316e3827b1
bigcode/the-stack
train
c04a255972f4109b2f4d21c8
train
function
def test_SegmentedRegressionModel_explicit(groupby_df): seg = regression.SegmentedRegressionModel( 'group', fit_filters=['col1 not in [2]'], predict_filters=['group != "z"']) seg.add_segment('x', 'col1 ~ col2') seg.add_segment('y', 'np.exp(col2) ~ np.exp(col1)', np.log) assert set(seg.co...
def test_SegmentedRegressionModel_explicit(groupby_df):
seg = regression.SegmentedRegressionModel( 'group', fit_filters=['col1 not in [2]'], predict_filters=['group != "z"']) seg.add_segment('x', 'col1 ~ col2') seg.add_segment('y', 'np.exp(col2) ~ np.exp(col1)', np.log) assert set(seg.columns_used()) == {'col1', 'col2', 'group'} fits = s...
group': ['x', 'y'], 'col2': [0.5, 10.5]}) predicted = seg.predict(test_data) pdt.assert_series_equal(predicted.sort_index(), pd.Series([-4.5, 5.5])) def test_SegmentedRegressionModel_explicit(groupby_df):
67
68
229
13
54
tin6150/urbansim
urbansim/models/tests/test_regression.py
Python
test_SegmentedRegressionModel_explicit
test_SegmentedRegressionModel_explicit
316
335
316
316
87008f2a2ed46f496ca32ac9e77d41819df2ae67
bigcode/the-stack
train
ffabfbf2783c8475424c565f
train
function
def test_fit_from_cfg(test_df): fit_filters = ['col1 in [0, 2, 4]'] predict_filters = ['col1 in [1, 3]'] model_exp = 'col1 ~ col2' ytransform = np.log name = 'test hedonic' model = regression.RegressionModel( fit_filters, predict_filters, model_exp, ytransform, name) cfgname = temp...
def test_fit_from_cfg(test_df):
fit_filters = ['col1 in [0, 2, 4]'] predict_filters = ['col1 in [1, 3]'] model_exp = 'col1 ~ col2' ytransform = np.log name = 'test hedonic' model = regression.RegressionModel( fit_filters, predict_filters, model_exp, ytransform, name) cfgname = tempfile.NamedTemporaryFile(suffix='...
group', default_model_expr='col1 ~ col2') seg.add_segment('a') seg.add_segment('b') seg.add_segment('c') seg.fit(groupby_df) assert sorted(seg._group.models.keys()) == ['x', 'y'] def test_fit_from_cfg(test_df):
64
64
149
8
56
tin6150/urbansim
urbansim/models/tests/test_regression.py
Python
test_fit_from_cfg
test_fit_from_cfg
423
437
423
423
7d878e2ba18b9acb7e5afc574b7a6578b4723765
bigcode/the-stack
train
be986c1f2316451897284ca8
train
function
def test_RegressionModel(test_df): fit_filters = ['col1 in [0, 2, 4]'] predict_filters = ['col1 in [1, 3]'] model_exp = 'col1 ~ col2' def ytransform(x): return x / 2. name = 'test hedonic' model = regression.RegressionModel( fit_filters, predict_filters, model_exp, ytransform,...
def test_RegressionModel(test_df):
fit_filters = ['col1 in [0, 2, 4]'] predict_filters = ['col1 in [1, 3]'] model_exp = 'col1 ~ col2' def ytransform(x): return x / 2. name = 'test hedonic' model = regression.RegressionModel( fit_filters, predict_filters, model_exp, ytransform, name) assert model.fit_filters...
pdt.assert_series_equal(wrapper.params, fit.params, check_names=False) pdt.assert_series_equal(wrapper.bse, fit.bse, check_names=False) pdt.assert_series_equal(wrapper.tvalues, fit.tvalues, check_names=False) assert wrapper.rsquared == fit.rsquared assert wrapper.rsquared_adj == fit.rsquared_adj def...
82
82
275
8
73
tin6150/urbansim
urbansim/models/tests/test_regression.py
Python
test_RegressionModel
test_RegressionModel
109
142
109
109
7e580ea48fcf83748d757957e7dab9f16b269897
bigcode/the-stack
train
4f9ff149efb6b3e6842fcbf9
train
function
def test_SegmentedRegressionModel(groupby_df): seg = regression.SegmentedRegressionModel( 'group', default_model_expr='col1 ~ col2') assert seg.fitted is False fits = seg.fit(groupby_df) assert seg.fitted is True assert 'x' in fits and 'y' in fits assert isinstance(fits['x'], Regression...
def test_SegmentedRegressionModel(groupby_df):
seg = regression.SegmentedRegressionModel( 'group', default_model_expr='col1 ~ col2') assert seg.fitted is False fits = seg.fit(groupby_df) assert seg.fitted is True assert 'x' in fits and 'y' in fits assert isinstance(fits['x'], RegressionResultsWrapper) test_data = pd.DataFrame({...
quared assert params.rsquared_adj == fit.rsquared_adj def test_SegmentedRegressionModel_raises(groupby_df): seg = regression.SegmentedRegressionModel('group') with pytest.raises(ValueError): seg.fit(groupby_df) def test_SegmentedRegressionModel(groupby_df):
64
64
148
11
53
tin6150/urbansim
urbansim/models/tests/test_regression.py
Python
test_SegmentedRegressionModel
test_SegmentedRegressionModel
300
313
300
300
4a09427945b4a068a241552183eefc4e39676355
bigcode/the-stack
train
41941839debf106a7c04fdbd
train
function
def test_model_fit_to_table(test_df): filters = [] model_exp = 'col1 ~ col2' fit = regression.fit_model(test_df, filters, model_exp) params = regression._model_fit_to_table(fit) pdt.assert_series_equal( params['Coefficient'], fit.params, check_names=False) pdt.assert_series_equal(params...
def test_model_fit_to_table(test_df):
filters = [] model_exp = 'col1 ~ col2' fit = regression.fit_model(test_df, filters, model_exp) params = regression._model_fit_to_table(fit) pdt.assert_series_equal( params['Coefficient'], fit.params, check_names=False) pdt.assert_series_equal(params['Std. Error'], fit.bse, check_names=F...
(test_df)) testing.assert_frames_equal( model.fit_parameters, self.model.fit_parameters) assert model.fit_parameters.rsquared == \ self.model.fit_parameters.rsquared assert model.fit_parameters.rsquared_adj == \ self.model.fit_parameters.rsquared_adj def test_...
64
64
131
9
54
tin6150/urbansim
urbansim/models/tests/test_regression.py
Python
test_model_fit_to_table
test_model_fit_to_table
278
290
278
278
c1b3bb3adebd1102197f81db7daa17d8255db548
bigcode/the-stack
train
1f32277339eccdf7c1d0095e
train
function
def assert_dict_specs_equal(j1, j2): j1_params = j1.pop('fit_parameters') j2_params = j2.pop('fit_parameters') assert j1 == j2 if j1_params and j2_params: pdt.assert_series_equal( pd.Series(j1_params['Coefficient']), pd.Series(j2_params['Coefficient'])) else: ...
def assert_dict_specs_equal(j1, j2):
j1_params = j1.pop('fit_parameters') j2_params = j2.pop('fit_parameters') assert j1 == j2 if j1_params and j2_params: pdt.assert_series_equal( pd.Series(j1_params['Coefficient']), pd.Series(j2_params['Coefficient'])) else: assert j1_params is None as...
['y'], RegressionResultsWrapper) predicted = hmg.predict(groupby_df) assert isinstance(predicted, pd.Series) pdt.assert_series_equal( predicted.sort_index(), groupby_df.col1, check_dtype=False, check_names=False) def assert_dict_specs_equal(j1, j2):
64
64
97
11
53
tin6150/urbansim
urbansim/models/tests/test_regression.py
Python
assert_dict_specs_equal
assert_dict_specs_equal
173
185
173
173
2119b1bd28fb45da88d3846db55ee9119e365d63
bigcode/the-stack
train
1711614465df114d8b41421a
train
function
@pytest.fixture def test_df(): return pd.DataFrame( {'col1': range(5), 'col2': range(5, 10)}, index=['a', 'b', 'c', 'd', 'e'])
@pytest.fixture def test_df():
return pd.DataFrame( {'col1': range(5), 'col2': range(5, 10)}, index=['a', 'b', 'c', 'd', 'e'])
import pytest import statsmodels.formula.api as smf import yaml from pandas.util import testing as pdt from statsmodels.regression.linear_model import RegressionResultsWrapper from .. import regression from ...exceptions import ModelEvaluationError from ...utils import testing @pytest.fixture def test_df():
64
64
51
7
56
tin6150/urbansim
urbansim/models/tests/test_regression.py
Python
test_df
test_df
23
28
23
24
afc76eef9c74aac425ec59931057ddcda64ee1e9
bigcode/the-stack
train
b0d319f314d8d9b6886b9843
train
function
def test_FakeRegressionResults(test_df): model_exp = 'col1 ~ col2' model = smf.ols(formula=model_exp, data=test_df) fit = model.fit() fit_parameters = regression._model_fit_to_table(fit) wrapper = regression._FakeRegressionResults( model_exp, fit_parameters, fit.rsquared, fit.rsquared_adj)...
def test_FakeRegressionResults(test_df):
model_exp = 'col1 ~ col2' model = smf.ols(formula=model_exp, data=test_df) fit = model.fit() fit_parameters = regression._model_fit_to_table(fit) wrapper = regression._FakeRegressionResults( model_exp, fit_parameters, fit.rsquared, fit.rsquared_adj) test_predict = pd.DataFrame({'col2'...
.isnan(predict.loc['c']) def test_rhs(): assert regression._rhs('col1 + col2') == 'col1 + col2' assert regression._rhs('col3 ~ col1 + col2') == 'col1 + col2' def test_FakeRegressionResults(test_df):
64
64
197
9
55
tin6150/urbansim
urbansim/models/tests/test_regression.py
Python
test_FakeRegressionResults
test_FakeRegressionResults
88
106
88
88
899c1189034bea27790ddd82dadd4463afe8f557
bigcode/the-stack
train
3b858c2b150c6cd9349bb8b1
train
function
def test_rhs(): assert regression._rhs('col1 + col2') == 'col1 + col2' assert regression._rhs('col3 ~ col1 + col2') == 'col1 + col2'
def test_rhs():
assert regression._rhs('col1 + col2') == 'col1 + col2' assert regression._rhs('col3 ~ col1 + col2') == 'col1 + col2'
~ col2') fit = regression.fit_model(df.loc[['a', 'b', 'e']], None, 'col1 ~ col2') predict = regression.predict( df.loc[['c', 'd']], None, fit) assert np.isnan(predict.loc['c']) def test_rhs():
63
64
47
4
59
tin6150/urbansim
urbansim/models/tests/test_regression.py
Python
test_rhs
test_rhs
83
85
83
83
b5f94cb0277d711f5c4c9a454475333fe3e11a1c
bigcode/the-stack
train
bf99e68dc02189c20b5e8ad8
train
function
def test_SegmentedRegressionModel_raises(groupby_df): seg = regression.SegmentedRegressionModel('group') with pytest.raises(ValueError): seg.fit(groupby_df)
def test_SegmentedRegressionModel_raises(groupby_df):
seg = regression.SegmentedRegressionModel('group') with pytest.raises(ValueError): seg.fit(groupby_df)
'], fit.bse, check_names=False) pdt.assert_series_equal(params['T-Score'], fit.tvalues, check_names=False) assert params.rsquared == fit.rsquared assert params.rsquared_adj == fit.rsquared_adj def test_SegmentedRegressionModel_raises(groupby_df):
64
64
39
13
50
tin6150/urbansim
urbansim/models/tests/test_regression.py
Python
test_SegmentedRegressionModel_raises
test_SegmentedRegressionModel_raises
293
297
293
293
389a21ddb2823aeb4e1d42e4d5c40fc7cb59f01c
bigcode/the-stack
train
7d17ccf35ca1e107fb888209
train
function
def test_fit_from_cfg_segmented(groupby_df): seg = regression.SegmentedRegressionModel( 'group', fit_filters=['col1 not in [2]'], predict_filters=['group != "z"'], default_model_expr='col1 ~ col2', min_segment_size=5000, name='test_seg') seg.add_segment('x') cfgname = tempfile.Named...
def test_fit_from_cfg_segmented(groupby_df):
seg = regression.SegmentedRegressionModel( 'group', fit_filters=['col1 not in [2]'], predict_filters=['group != "z"'], default_model_expr='col1 ~ col2', min_segment_size=5000, name='test_seg') seg.add_segment('x') cfgname = tempfile.NamedTemporaryFile(suffix='.yaml').name seg.to...
TemporaryFile(suffix='.yaml').name model.to_yaml(cfgname) regression.RegressionModel.fit_from_cfg(test_df, cfgname, debug=True) regression.RegressionModel.predict_from_cfg(test_df, cfgname) os.remove(cfgname) def test_fit_from_cfg_segmented(groupby_df):
64
64
156
11
53
tin6150/urbansim
urbansim/models/tests/test_regression.py
Python
test_fit_from_cfg_segmented
test_fit_from_cfg_segmented
440
452
440
440
bf869742c125fab6478ae58fd6869982a929e759
bigcode/the-stack
train
b19e6560170f008f0b896ab7
train
function
def test_fit_model(test_df): filters = [] model_exp = 'col1 ~ col2' fit = regression.fit_model(test_df, filters, model_exp) assert isinstance(fit, RegressionResultsWrapper)
def test_fit_model(test_df):
filters = [] model_exp = 'col1 ~ col2' fit = regression.fit_model(test_df, filters, model_exp) assert isinstance(fit, RegressionResultsWrapper)
10)}, index=['a', 'b', 'c', 'd', 'e']) @pytest.fixture def groupby_df(test_df): test_df['group'] = ['x', 'y', 'x', 'x', 'y'] return test_df def test_fit_model(test_df):
64
64
46
7
56
tin6150/urbansim
urbansim/models/tests/test_regression.py
Python
test_fit_model
test_fit_model
37
41
37
37
a50b27046a136d0c6597a1becb3ed0119267d934
bigcode/the-stack
train
6e3558354b185894c8e18d0f
train
function
@pytest.fixture def groupby_df(test_df): test_df['group'] = ['x', 'y', 'x', 'x', 'y'] return test_df
@pytest.fixture def groupby_df(test_df):
test_df['group'] = ['x', 'y', 'x', 'x', 'y'] return test_df
testing @pytest.fixture def test_df(): return pd.DataFrame( {'col1': range(5), 'col2': range(5, 10)}, index=['a', 'b', 'c', 'd', 'e']) @pytest.fixture def groupby_df(test_df):
63
64
37
10
53
tin6150/urbansim
urbansim/models/tests/test_regression.py
Python
groupby_df
groupby_df
31
34
31
32
4cc6e585abf70fbd798528bb70cb76d763592147
bigcode/the-stack
train
317d86913cdc646d8d21e114
train
function
def test_RegressionModelGroup(groupby_df): model_exp = 'col1 ~ col2' hmg = regression.RegressionModelGroup('group') xmodel = regression.RegressionModel(None, None, model_exp, name='x') hmg.add_model(xmodel) assert isinstance(hmg.models['x'], regression.RegressionModel) hmg.add_model_from_para...
def test_RegressionModelGroup(groupby_df):
model_exp = 'col1 ~ col2' hmg = regression.RegressionModelGroup('group') xmodel = regression.RegressionModel(None, None, model_exp, name='x') hmg.add_model(xmodel) assert isinstance(hmg.models['x'], regression.RegressionModel) hmg.add_model_from_params('y', None, None, model_exp) assert i...
ResultsWrapper) predicted = model.predict(test_df) expected = pd.Series([0.5, 1.5], index=['b', 'd']) pdt.assert_series_equal(predicted, expected) # make sure this doesn't cause an error model.report_fit() def test_RegressionModelGroup(groupby_df):
69
69
233
10
59
tin6150/urbansim
urbansim/models/tests/test_regression.py
Python
test_RegressionModelGroup
test_RegressionModelGroup
145
170
145
145
b5f4f58ae08a24dd899719b17d98ac72a70a2fc6
bigcode/the-stack
train
96f37600e0de4bc1288803ba
train
class
class Connection(apsw.Connection, ContextManagerMixin): def __init__(self, filename: Union[PathLike, str], *args): super().__init__(str(filename), *args)
class Connection(apsw.Connection, ContextManagerMixin):
def __init__(self, filename: Union[PathLike, str], *args): super().__init__(str(filename), *args)
self.cursor() try: c.execute("BEGIN TRANSACTION") yield c except Exception: c.execute("ROLLBACK TRANSACTION") raise else: c.execute("COMMIT TRANSACTION") finally: c.close() class Connection(apsw.Connection, ContextM...
64
64
41
11
53
jack1142/SinbadCogs-1
mlog/apsw_wrapper.py
Python
Connection
Connection
50
52
50
50
20a23d1dbbd9ddcfffd4f53cb038af4e72fd09f4
bigcode/the-stack
train
fa012486ecaf67a151495138
train
class
class ContextManagerMixin(ProvidesCursor): @contextmanager def with_cursor(self) -> Generator[apsw.Cursor, None, None]: c = self.cursor() try: yield c finally: c.close() @contextmanager def transaction(self) -> Generator[apsw.Cursor, None, None]: ...
class ContextManagerMixin(ProvidesCursor): @contextmanager
def with_cursor(self) -> Generator[apsw.Cursor, None, None]: c = self.cursor() try: yield c finally: c.close() @contextmanager def transaction(self) -> Generator[apsw.Cursor, None, None]: c = self.cursor() try: c.execute("BEGIN TRA...
point, but I'm being lazy in the short term here. """ if TYPE_CHECKING: from typing_extensions import Protocol else: Protocol = object class ProvidesCursor(Protocol): def cursor(self) -> apsw.Cursor: ... class ContextManagerMixin(ProvidesCursor): @contextmanager
64
64
127
13
51
jack1142/SinbadCogs-1
mlog/apsw_wrapper.py
Python
ContextManagerMixin
ContextManagerMixin
26
47
26
27
784d775a56ff8a7df19b75bc8fc41e3c542445b3
bigcode/the-stack
train
84e469c85f0c51c036988c2c
train
class
class ProvidesCursor(Protocol): def cursor(self) -> apsw.Cursor: ...
class ProvidesCursor(Protocol):
def cursor(self) -> apsw.Cursor: ...
TYPE_CHECKING, Generator, Union import apsw """ This should be moved into a pip installable lib at some point, but I'm being lazy in the short term here. """ if TYPE_CHECKING: from typing_extensions import Protocol else: Protocol = object class ProvidesCursor(Protocol):
64
64
18
6
57
jack1142/SinbadCogs-1
mlog/apsw_wrapper.py
Python
ProvidesCursor
ProvidesCursor
21
23
21
21
60e17ba2f41a2ce351f322c4df2e0917f99db28c
bigcode/the-stack
train
83736f3d651bf07ce8cefcf3
train
function
def is_windows() -> bool: """Guess if windows""" platform_string = platform.system() return os.name == "nt" or platform_string == "Windows" or "_NT" in platform_string
def is_windows() -> bool:
"""Guess if windows""" platform_string = platform.system() return os.name == "nt" or platform_string == "Windows" or "_NT" in platform_string
not, several tools don't make sense to run https://stackoverflow.com/a/39956572/33264 """ try: _ = git.Repo(path).git_dir return True except git.exc.InvalidGitRepositoryError: return False def is_windows() -> bool:
64
64
43
7
56
matthewdeanmartin/pydoc_fork
navio_tasks/system_info.py
Python
is_windows
is_windows
27
30
27
27
47dd625857be88f5ac708018d45e6bf7736aee9c
bigcode/the-stack
train
27c25fe73887c528395b2400
train
function
def is_powershell() -> bool: """ Check if parent process or other ancestor process is powershell """ # ref https://stackoverflow.com/a/55598796/33264 # Get the parent process name. try: process_name = psutil.Process(os.getppid()).name() grand_process_name = psutil.Process(os.get...
def is_powershell() -> bool:
""" Check if parent process or other ancestor process is powershell """ # ref https://stackoverflow.com/a/55598796/33264 # Get the parent process name. try: process_name = psutil.Process(os.getppid()).name() grand_process_name = psutil.Process(os.getppid()).parent().name() ...
except git.exc.InvalidGitRepositoryError: return False def is_windows() -> bool: """Guess if windows""" platform_string = platform.system() return os.name == "nt" or platform_string == "Windows" or "_NT" in platform_string def is_powershell() -> bool:
64
64
207
9
54
matthewdeanmartin/pydoc_fork
navio_tasks/system_info.py
Python
is_powershell
is_powershell
33
53
33
33
4150f05617d6edabb3c740fd4bf7b26aa031c577
bigcode/the-stack
train
c1fb938b57df63df0e284d91
train
function
def is_git_repo(path: str) -> bool: """ Are we in a git repo if not, several tools don't make sense to run https://stackoverflow.com/a/39956572/33264 """ try: _ = git.Repo(path).git_dir return True except git.exc.InvalidGitRepositoryError: return False
def is_git_repo(path: str) -> bool:
""" Are we in a git repo if not, several tools don't make sense to run https://stackoverflow.com/a/39956572/33264 """ try: _ = git.Repo(path).git_dir return True except git.exc.InvalidGitRepositoryError: return False
""" Infering what machine we are on. """ import os import platform import re import socket import git import psutil from navio_tasks.utils import inform def is_git_repo(path: str) -> bool:
48
64
78
11
36
matthewdeanmartin/pydoc_fork
navio_tasks/system_info.py
Python
is_git_repo
is_git_repo
15
24
15
15
e023ef2b9af6d3b21a966f9ad9baf02ca5e5367d
bigcode/the-stack
train
1bf4de2611bcff32ebe46058
train
function
def check_is_aws() -> bool: """ Look at domain name to see if this is an ec2 machine """ # HACK: environment variable checking is much, much faster & reliable. name = socket.getfqdn() return "ip-" in name and ".ec2.internal" in name
def check_is_aws() -> bool:
""" Look at domain name to see if this is an ec2 machine """ # HACK: environment variable checking is much, much faster & reliable. name = socket.getfqdn() return "ip-" in name and ".ec2.internal" in name
.fullmatch("pwsh|pwsh.exe|powershell.exe", grand_process_name) ) except psutil.NoSuchProcess: inform("Can't tell if this is powershell, assuming not.") is_that_shell = False return is_that_shell def check_is_aws() -> bool:
64
64
68
9
54
matthewdeanmartin/pydoc_fork
navio_tasks/system_info.py
Python
check_is_aws
check_is_aws
56
62
56
56
d750226bed3d9b45474f421bb0f8e8cf6411d7ea
bigcode/the-stack
train
7d96d6b21b5237d57d703a0f
train
function
def process_TCGA_MAF(maf_file, save_path, filetype='matrix', gene_naming='Symbol', verbose=False): loadtime = time.time() # Load MAF File TCGA_MAF = pd.read_csv(maf_file,sep='\t',low_memory=False) # Get all patient somatic mutation (sm) pairs from MAF file if gene_naming=='Entrez': TCGA_sm = TCGA_MAF.groupby(['T...
def process_TCGA_MAF(maf_file, save_path, filetype='matrix', gene_naming='Symbol', verbose=False):
loadtime = time.time() # Load MAF File TCGA_MAF = pd.read_csv(maf_file,sep='\t',low_memory=False) # Get all patient somatic mutation (sm) pairs from MAF file if gene_naming=='Entrez': TCGA_sm = TCGA_MAF.groupby(['Tumor_Sample_Barcode', 'Entrez_Gene_Id']).size() else: TCGA_sm = TCGA_MAF.groupby(['Tumor_Sample_...
data[data[score_col]>q_score][data.columns[[nodeA_col, nodeB_col, score_col]]] data_filt.columns = ['nodeA', 'nodeB', 'edgeScore'] if verbose: print(data_filt.shape[0], '/', data.shape[0], 'edges retained') data_filt.to_csv(save_path, sep='\t', header=False, index=False) return # Convert and save MAF from Broa...
204
204
680
27
177
decarlin/pyNBS_3
pyNBS/data_import_tools.py
Python
process_TCGA_MAF
process_TCGA_MAF
176
221
176
176
1d7c239adf764a9b4036ccc431790abd849368c5
bigcode/the-stack
train
565ddf0583701307e2f8fadd
train
function
def load_binary_mutation_data(filename, filetype='list', delimiter='\t', verbose=True): # Load binary mutation data from file if filetype=='list': f = open(filename) binary_mat_lines = f.read().splitlines() binary_mat_data = [(line.split('\t')[0], line.split('\t')[1]) for line in binary_mat_lines] binary_mat_...
def load_binary_mutation_data(filename, filetype='list', delimiter='\t', verbose=True): # Load binary mutation data from file
if filetype=='list': f = open(filename) binary_mat_lines = f.read().splitlines() binary_mat_data = [(line.split('\t')[0], line.split('\t')[1]) for line in binary_mat_lines] binary_mat_index = pd.MultiIndex.from_tuples(binary_mat_data, names=['Tumor_Sample_Barcode', 'Gene_Name']) binary_mat_2col = pd.DataFram...
1st column is sample/patient, 2nd column is one gene mutated in that patient # Line example in 'list' file: 'Patient ID','Gene Mutated' def load_binary_mutation_data(filename, filetype='list', delimiter='\t', verbose=True): # Load binary mutation data from file
66
66
221
29
37
decarlin/pyNBS_3
pyNBS/data_import_tools.py
Python
load_binary_mutation_data
load_binary_mutation_data
34
49
34
35
a77bec761395f6a25e939790eba0eb8626134eb7
bigcode/the-stack
train