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
744f10a4a41ff6bf409e5fc0
train
function
def save_checkpoint(epoch, top1, best_acc): if opt.save_frequency and (epoch + 1) % opt.save_frequency == 0: fname = os.path.join(opt.prefix, '%s_%d_acc_%.4f.params' % (opt.model, epoch, top1)) net.save_parameters(fname) logger.info('[Epoch %d] Saving checkpoint to %s with Accuracy: %.4f', e...
def save_checkpoint(epoch, top1, best_acc):
if opt.save_frequency and (epoch + 1) % opt.save_frequency == 0: fname = os.path.join(opt.prefix, '%s_%d_acc_%.4f.params' % (opt.model, epoch, top1)) net.save_parameters(fname) logger.info('[Epoch %d] Saving checkpoint to %s with Accuracy: %.4f', epoch, fname, top1) if top1 > best_acc[0]...
, steps): """Set the learning rate to the initial value decayed by ratio every N epochs.""" new_lr = lr * (ratio ** int(np.sum(np.array(steps) < epoch))) trainer.set_learning_rate(new_lr) return trainer def save_checkpoint(epoch, top1, best_acc):
64
64
166
11
52
tkameyama/incubator-mxnet
example/gluon/image_classification.py
Python
save_checkpoint
save_checkpoint
180
189
180
180
f1d1488ba2422141d8b75f3320cbac8a9ad216cc
bigcode/the-stack
train
98729133e946b0b400324d71
train
function
def train(opt, ctx): if isinstance(ctx, mx.Context): ctx = [ctx] train_data, val_data = get_data_iters(dataset, batch_size, opt) net.collect_params().reset_ctx(ctx) trainer = gluon.Trainer(net.collect_params(), 'sgd', optimizer_params={'learning_rate': opt.lr, ...
def train(opt, ctx):
if isinstance(ctx, mx.Context): ctx = [ctx] train_data, val_data = get_data_iters(dataset, batch_size, opt) net.collect_params().reset_ctx(ctx) trainer = gluon.Trainer(net.collect_params(), 'sgd', optimizer_params={'learning_rate': opt.lr, ...
_lr = lr * (ratio ** int(np.sum(np.array(steps) < epoch))) trainer.set_learning_rate(new_lr) return trainer def save_checkpoint(epoch, top1, best_acc): if opt.save_frequency and (epoch + 1) % opt.save_frequency == 0: fname = os.path.join(opt.prefix, '%s_%d_acc_%.4f.params' % (opt.model, epoch, top1...
202
202
674
6
196
tkameyama/incubator-mxnet
example/gluon/image_classification.py
Python
train
train
191
253
191
191
08980b0bca992b540697c4d8cc81d2ea352abf4f
bigcode/the-stack
train
c9550e6d2e36461d1813528d
train
function
def get_data_iters(dataset, batch_size, opt): """get dataset iterators""" if dataset == 'mnist': train_data, val_data = get_mnist_iterator(batch_size, (1, 28, 28), num_parts=kv.num_workers, part_index=kv.rank) elif dataset == 'cifar10': train...
def get_data_iters(dataset, batch_size, opt):
"""get dataset iterators""" if dataset == 'mnist': train_data, val_data = get_mnist_iterator(batch_size, (1, 28, 28), num_parts=kv.num_workers, part_index=kv.rank) elif dataset == 'cifar10': train_data, val_data = get_cifar10_iterator(batch_s...
(model, **kwargs) if opt.resume: net.load_parameters(opt.resume) elif not opt.use_pretrained: if model in ['alexnet']: net.initialize(mx.init.Normal()) else: net.initialize(mx.init.Xavier(magnitude=2)) net.cast(opt.dtype) return net net = get_model(opt.mo...
87
87
290
11
76
tkameyama/incubator-mxnet
example/gluon/image_classification.py
Python
get_data_iters
get_data_iters
138
160
138
138
83baaeb9eefb82040400f68f4c84a605a9047b49
bigcode/the-stack
train
d8c24ff48896ec1bd38902dc
train
function
def main(): if opt.builtin_profiler > 0: profiler.set_config(profile_all=True, aggregate_stats=True) profiler.set_state('run') if opt.mode == 'symbolic': data = mx.sym.var('data') if opt.dtype == 'float16': data = mx.sym.Cast(data=data, dtype=np.float16) out =...
def main():
if opt.builtin_profiler > 0: profiler.set_config(profile_all=True, aggregate_stats=True) profiler.set_state('run') if opt.mode == 'symbolic': data = mx.sym.var('data') if opt.dtype == 'float16': data = mx.sym.Cast(data=data, dtype=np.float16) out = net(data) ...
, val_acc = test(ctx, val_data) logger.info('[Epoch %d] validation: %s=%f, %s=%f'%(epoch, name[0], val_acc[0], name[1], val_acc[1])) # save model if meet requirements save_checkpoint(epoch, val_acc[0], best_acc) if num_epochs > 1: print('Average epoch time: {}'.format(float(total_ti...
101
101
339
3
98
tkameyama/incubator-mxnet
example/gluon/image_classification.py
Python
main
main
255
285
255
255
027e1e154b8a594009d51a7d58c58d62e9288caa
bigcode/the-stack
train
b78f0db5d0d9929acdc13577
train
function
def update_learning_rate(lr, trainer, epoch, ratio, steps): """Set the learning rate to the initial value decayed by ratio every N epochs.""" new_lr = lr * (ratio ** int(np.sum(np.array(steps) < epoch))) trainer.set_learning_rate(new_lr) return trainer
def update_learning_rate(lr, trainer, epoch, ratio, steps):
"""Set the learning rate to the initial value decayed by ratio every N epochs.""" new_lr = lr * (ratio ** int(np.sum(np.array(steps) < epoch))) trainer.set_learning_rate(new_lr) return trainer
_and_load(batch.label[0].astype(opt.dtype, copy=False), ctx_list=ctx, batch_axis=0) outputs = [net(X) for X in data] metric.update(label, outputs) return metric.get() def update_learning_rate(lr, trainer, epoch, ratio, steps):
64
64
65
15
49
tkameyama/incubator-mxnet
example/gluon/image_classification.py
Python
update_learning_rate
update_learning_rate
174
178
174
174
39f309e9f81f77d73ee6ceaa96a59d9e415dbf6b
bigcode/the-stack
train
7e6519ee4c8ff3786d403ea2
train
function
def test(ctx, val_data): metric.reset() val_data.reset() for batch in val_data: data = gluon.utils.split_and_load(batch.data[0].astype(opt.dtype, copy=False), ctx_list=ctx, batch_axis=0) label = gluon.utils.split_and_load(batch.label[0].astype(opt.dt...
def test(ctx, val_data):
metric.reset() val_data.reset() for batch in val_data: data = gluon.utils.split_and_load(batch.data[0].astype(opt.dtype, copy=False), ctx_list=ctx, batch_axis=0) label = gluon.utils.split_and_load(batch.label[0].astype(opt.dtype, copy=False), ...
) elif dataset == 'dummy': shape_dim = 299 if model_name == 'inceptionv3' else 224 train_data, val_data = dummy_iterator(batch_size, (3, shape_dim, shape_dim)) return train_data, val_data def test(ctx, val_data):
64
64
111
7
56
tkameyama/incubator-mxnet
example/gluon/image_classification.py
Python
test
test
162
172
162
162
707118049258923d858071a94c1873db95b64aca
bigcode/the-stack
train
d09459d575e32ba8dbe1e05d
train
function
def get_model(model, ctx, opt): """Model initialization.""" kwargs = {'ctx': ctx, 'pretrained': opt.use_pretrained, 'classes': classes} if model.startswith('resnet'): kwargs['thumbnail'] = opt.use_thumbnail elif model.startswith('vgg'): kwargs['batch_norm'] = opt.batch_norm net = mo...
def get_model(model, ctx, opt):
"""Model initialization.""" kwargs = {'ctx': ctx, 'pretrained': opt.use_pretrained, 'classes': classes} if model.startswith('resnet'): kwargs['thumbnail'] = opt.use_thumbnail elif model.startswith('vgg'): kwargs['batch_norm'] = opt.batch_norm net = models.get_model(model, **kwargs) ...
_size *= max(1, num_gpus) lr_steps = [int(x) for x in opt.lr_steps.split(',') if x.strip()] metric = CompositeEvalMetric([Accuracy(), TopKAccuracy(5)]) kv = mx.kv.create(opt.kvstore) def get_model(model, ctx, opt):
64
64
144
9
55
tkameyama/incubator-mxnet
example/gluon/image_classification.py
Python
get_model
get_model
117
134
117
117
76b8470ce690608685132df314e318f4d227a2de
bigcode/the-stack
train
d58ae2228d8f6c586526d69a
train
function
def get_provider_package_from_package_id(package_id: str): """ Builds the name of provider package out of the package id provided/ :param package_id: id of the package (like amazon or microsoft.azure) :return: full name of package in PyPI """ package_suffix = package_id.replace(".", "-") re...
def get_provider_package_from_package_id(package_id: str):
""" Builds the name of provider package out of the package id provided/ :param package_id: id of the package (like amazon or microsoft.azure) :return: full name of package in PyPI """ package_suffix = package_id.replace(".", "-") return f"apache-airflow-providers-{package_suffix}"
_PROVIDERS_FROM_SOURCES') == 'true': self.install_requires = [ # pylint: disable=attribute-defined-outside-init req for req in self.install_requires if not req.startswith('apache-airflow-providers-') ] def get_provider_package_from_package_id(package_id: str):
63
64
82
12
51
nic314/airflow
setup.py
Python
get_provider_package_from_package_id
get_provider_package_from_package_id
906
914
906
906
3582097c164bb884c09da831b6ab1508a8d8bef5
bigcode/the-stack
train
79e88efb56582a6f235c81ba
train
class
class ListExtras(Command): """ List all available extras Registered as cmdclass in setup() so it can be called with ``python setup.py list_extras``. """ description = "List available extras" user_options = [] # type: List[str] def initialize_options(self): """Set default values fo...
class ListExtras(Command):
""" List all available extras Registered as cmdclass in setup() so it can be called with ``python setup.py list_extras``. """ description = "List available extras" user_options = [] # type: List[str] def initialize_options(self): """Set default values for options.""" def fina...
initialize_options(self): """Set default values for options.""" def finalize_options(self): """Set final values for options.""" def run(self): # noqa """Run a command to compile and build assets.""" subprocess.check_call('./airflow/www/compile_assets.sh') class ListExtras(Com...
64
64
121
5
59
nic314/airflow
setup.py
Python
ListExtras
ListExtras
88
105
88
88
e95686d52951051575dae1fef865449bd031f723
bigcode/the-stack
train
1f410f723c750d25e87212a4
train
function
def airflow_test_suite(): """Test suite for Airflow tests""" test_loader = unittest.TestLoader() test_suite = test_loader.discover(os.path.join(my_dir, 'tests'), pattern='test_*.py') return test_suite
def airflow_test_suite():
"""Test suite for Airflow tests""" test_loader = unittest.TestLoader() test_suite = test_loader.discover(os.path.join(my_dir, 'tests'), pattern='test_*.py') return test_suite
from typing import Dict, Iterable, List from setuptools import Command, Distribution, find_namespace_packages, setup logger = logging.getLogger(__name__) version = '2.0.0' PY3 = sys.version_info[0] == 3 my_dir = dirname(__file__) def airflow_test_suite():
64
64
51
5
59
nic314/airflow
setup.py
Python
airflow_test_suite
airflow_test_suite
40
44
40
40
ec4e3b63b9df21433f5bda601dd8301cb2b1f134
bigcode/the-stack
train
80a77748208101de27abd549
train
class
class AirflowDistribtuion(Distribution): """setuptools.Distribution subclass with Airflow specific behaviour""" # https://github.com/PyCQA/pylint/issues/3737 def parse_config_files(self, *args, **kwargs): # pylint: disable=signature-differs """ Ensure that when we have been asked to instal...
class AirflowDistribtuion(Distribution):
"""setuptools.Distribution subclass with Airflow specific behaviour""" # https://github.com/PyCQA/pylint/issues/3737 def parse_config_files(self, *args, **kwargs): # pylint: disable=signature-differs """ Ensure that when we have been asked to install providers from sources that we ...
PACKAGES_EXCLUDED_FOR_ALL ) ] # Those are development requirements that install all useful devel tools EXTRAS_REQUIREMENTS.update( { 'devel_all': devel_all, 'devel_ci': devel_ci, } ) class AirflowDistribtuion(Distribution):
64
64
167
9
55
nic314/airflow
setup.py
Python
AirflowDistribtuion
AirflowDistribtuion
890
903
890
890
0e6af30c0918eb8a5ba94e7857998d10fabe414a
bigcode/the-stack
train
937d69b41020bd5a0948e374
train
function
def write_version(filename: str = os.path.join(*[my_dir, "airflow", "git_version"])): """ Write the Semver version + git hash to file, e.g. ".dev0+2f635dc265e78db6708f59f68e8009abb92c1e65". :param str filename: Destination file to write """ text = "{}".format(git_version(version)) with open(fil...
def write_version(filename: str = os.path.join(*[my_dir, "airflow", "git_version"])):
""" Write the Semver version + git hash to file, e.g. ".dev0+2f635dc265e78db6708f59f68e8009abb92c1e65". :param str filename: Destination file to write """ text = "{}".format(git_version(version)) with open(filename, 'w') as file: file.write(text)
return f'.dev0+{sha}.dirty' # commit is clean return f'.release:{version_}+{sha}' else: return 'no_git_version' def write_version(filename: str = os.path.join(*[my_dir, "airflow", "git_version"])):
64
64
109
24
40
nic314/airflow
setup.py
Python
write_version
write_version
145
153
145
145
9e39705fa53938a50704a511b4090eea61812048
bigcode/the-stack
train
96bf4b2edce9565a89ec6032
train
function
def do_setup(): """Perform the Airflow package setup.""" setup_kwargs = {} if os.getenv('INSTALL_PROVIDERS_FROM_SOURCES') == 'true': # Only specify this if we need this option, otherwise let default from # setup.cfg control this (kwargs in setup() call take priority) setup_kwargs['p...
def do_setup():
"""Perform the Airflow package setup.""" setup_kwargs = {} if os.getenv('INSTALL_PROVIDERS_FROM_SOURCES') == 'true': # Only specify this if we need this option, otherwise let default from # setup.cfg control this (kwargs in setup() call take priority) setup_kwargs['packages'] = find...
str): """ Builds the name of provider package out of the package id provided/ :param package_id: id of the package (like amazon or microsoft.azure) :return: full name of package in PyPI """ package_suffix = package_id.replace(".", "-") return f"apache-airflow-providers-{package_suffix}" de...
76
77
259
4
72
nic314/airflow
setup.py
Python
do_setup
do_setup
917
946
917
917
015f9ae8b62ce6841147dc58ffbc2f5fc94a1fcb
bigcode/the-stack
train
36d38dc7c38f41a3e8c45ee1
train
function
def is_package_excluded(package: str, exclusion_list: List[str]): """ Checks if package should be excluded. :param package: package name (beginning of it) :param exclusion_list: list of excluded packages :return: true if package should be excluded """ return any(package.startswith(excluded_...
def is_package_excluded(package: str, exclusion_list: List[str]):
""" Checks if package should be excluded. :param package: package name (beginning of it) :param exclusion_list: list of excluded packages :return: true if package should be excluded """ return any(package.startswith(excluded_package) for excluded_package in exclusion_list)
', ] ) # Those packages are excluded because they break tests (downgrading mock) and they are # not needed to run our test suite. PACKAGES_EXCLUDED_FOR_CI = [ 'apache-beam', ] def is_package_excluded(package: str, exclusion_list: List[str]):
64
64
78
15
49
nic314/airflow
setup.py
Python
is_package_excluded
is_package_excluded
856
864
856
856
49c8d2cd9ac94586d4c82f760318b8716a8a5840
bigcode/the-stack
train
7dc837f26cded5d14d658ac9
train
class
class CleanCommand(Command): """ Command to tidy up the project root. Registered as cmdclass in setup() so it can be called with ``python setup.py extra_clean``. """ description = "Tidy up the project root" user_options = [] # type: List[str] def initialize_options(self): """Set d...
class CleanCommand(Command):
""" Command to tidy up the project root. Registered as cmdclass in setup() so it can be called with ``python setup.py extra_clean``. """ description = "Tidy up the project root" user_options = [] # type: List[str] def initialize_options(self): """Set default values for options."""...
my_dir = dirname(__file__) def airflow_test_suite(): """Test suite for Airflow tests""" test_loader = unittest.TestLoader() test_suite = test_loader.discover(os.path.join(my_dir, 'tests'), pattern='test_*.py') return test_suite class CleanCommand(Command):
64
64
142
5
58
nic314/airflow
setup.py
Python
CleanCommand
CleanCommand
47
65
47
47
3457664007abd1455674caf151e8e394577046f3
bigcode/the-stack
train
fab2128883bba1b50a3bf6df
train
class
class CompileAssets(Command): """ Compile and build the frontend assets using yarn and webpack. Registered as cmdclass in setup() so it can be called with ``python setup.py compile_assets``. """ description = "Compile and build the frontend assets" user_options = [] # type: List[str] def ...
class CompileAssets(Command):
""" Compile and build the frontend assets using yarn and webpack. Registered as cmdclass in setup() so it can be called with ``python setup.py compile_assets``. """ description = "Compile and build the frontend assets" user_options = [] # type: List[str] def initialize_options(self): ...
"""Set final values for options.""" def run(self): # noqa """Run command to remove temporary files and directories.""" os.chdir(my_dir) os.system('rm -vrf ./build ./dist ./*.pyc ./*.tgz ./*.egg-info') class CompileAssets(Command):
64
64
127
5
59
nic314/airflow
setup.py
Python
CompileAssets
CompileAssets
68
85
68
68
ffc8ff0336b77913004f9a12afd5f46daade4e54
bigcode/the-stack
train
c860466a14142d201411bbb2
train
function
def git_version(version_: str) -> str: """ Return a version to identify the state of the underlying git repo. The version will indicate whether the head of the current git-backed working directory is tied to a release tag or not : it will indicate the former with a 'release:{version}' prefix and the...
def git_version(version_: str) -> str:
""" Return a version to identify the state of the underlying git repo. The version will indicate whether the head of the current git-backed working directory is tied to a release tag or not : it will indicate the former with a 'release:{version}' prefix and the latter with a 'dev0' prefix. Following...
= "List available extras" user_options = [] # type: List[str] def initialize_options(self): """Set default values for options.""" def finalize_options(self): """Set final values for options.""" def run(self): # noqa """List extras.""" print("\n".join(wrap(", ".join(...
91
92
308
10
81
nic314/airflow
setup.py
Python
git_version
git_version
108
142
108
108
c97f83d1a4895b0f6984873839a7853956e008a8
bigcode/the-stack
train
5c235c1e0fb6590b618eed1c
train
class
class lidc_data(): def __init__(self, exp_config): # data = lidc_data_loader.load_and_maybe_process_data( # input_file=exp_config.data_root, # preprocessing_folder=exp_config.preproc_folder, # force_overwrite=False, # ) data = h5py.File(exp_config.data_r...
class lidc_data():
def __init__(self, exp_config): # data = lidc_data_loader.load_and_maybe_process_data( # input_file=exp_config.data_root, # preprocessing_folder=exp_config.preproc_folder, # force_overwrite=False, # ) data = h5py.File(exp_config.data_root, 'r') s...
# Authors: # Christian F. Baumgartner (c.f.baumgartner@gmail.com) import numpy as np from data import lidc_data_loader from data.batch_provider import BatchProvider import h5py class lidc_data():
51
119
399
5
45
Rochan-A/PHiSeg-code
data/lidc_data.py
Python
lidc_data
lidc_data
9
54
9
10
7b440e50095669e80770ec9de1cb9b33ccad59df
bigcode/the-stack
train
7745ac40bbb3ac298c534f9a
train
class
class VersionTooHighError(Exception): """Raised when the OS version is greater than the highest supported.""" def __init__(self, version): Exception.__init__(self) self.version = version
class VersionTooHighError(Exception):
"""Raised when the OS version is greater than the highest supported.""" def __init__(self, version): Exception.__init__(self) self.version = version
Exception.__init__(self) self.system = system class VersionUnsupportedError(Exception): """Raised when the version of an OS is unrecognised or unsupported.""" def __init__(self, version): Exception.__init__(self) self.version = version class VersionTooHighError(Exception):
64
64
43
7
56
niu2x/gxm
dependencies/fplutil/setuputil/common.py
Python
VersionTooHighError
VersionTooHighError
80
85
80
80
00916df99e851e7b4b0faf5e42e656c7ef929375
bigcode/the-stack
train
8e7396d56d93da77bad26248
train
class
class VersionUnsupportedError(Exception): """Raised when the version of an OS is unrecognised or unsupported.""" def __init__(self, version): Exception.__init__(self) self.version = version
class VersionUnsupportedError(Exception):
"""Raised when the version of an OS is unrecognised or unsupported.""" def __init__(self, version): Exception.__init__(self) self.version = version
or not the bash profile has been changed.""" return self.bash_profile_changed class SystemUnsupportedError(Exception): """Raised when an OS is unrecognised or unsupported.""" def __init__(self, system): Exception.__init__(self) self.system = system class VersionUnsupportedError(Exception):
64
64
44
6
57
niu2x/gxm
dependencies/fplutil/setuputil/common.py
Python
VersionUnsupportedError
VersionUnsupportedError
72
77
72
72
291ba8863cc732d7624a953f0d8b82fea2ccf129
bigcode/the-stack
train
71cf5053be3438004d35f891
train
class
class UnknownFileTypeError(Exception): """Raised when the extension of a file is unrecognised.""" def __init__(self, filetype, instructions): Exception.__init__(self) self.filetype = filetype self.instructions = instructions
class UnknownFileTypeError(Exception):
"""Raised when the extension of a file is unrecognised.""" def __init__(self, filetype, instructions): Exception.__init__(self) self.filetype = filetype self.instructions = instructions
= link self.instructions = instructions class FileDownloadError(Exception): """Raised when a file was unable to download.""" def __init__(self, link, instructions=""): Exception.__init__(self) self.link = link self.instructions = instructions class UnknownFileTypeError(Exception):
64
64
54
7
56
niu2x/gxm
dependencies/fplutil/setuputil/common.py
Python
UnknownFileTypeError
UnknownFileTypeError
133
139
133
133
527a772e79b4e730304df487dbe538eeecfa1796
bigcode/the-stack
train
b816e50ad650399cc77d4d0e
train
class
class Setup(object): """Base class for installing prerequisites for Linux, Mac OS X and Windows. Attributes: bash_profile_changed: A boolean indicating whether or not the bash profile has been edited by the script, and the user should call source. cwebp_path: A string of the path to the location of...
class Setup(object):
"""Base class for installing prerequisites for Linux, Mac OS X and Windows. Attributes: bash_profile_changed: A boolean indicating whether or not the bash profile has been edited by the script, and the user should call source. cwebp_path: A string of the path to the location of the cwebp directory....
# See the License for the specific language governing permissions and # limitations under the License. import os BASE_DIR = os.path.expanduser("~") LINUX = "LINUX" LINUX_32 = LINUX + "32" LINUX_64 = LINUX + "64" MAC = "MAC" WINDOWS = "WINDOWS" WINDOWS_32 = WINDOWS + "32" WINDOWS_64 = WINDOWS + "64" class Setup(obje...
96
96
323
4
92
niu2x/gxm
dependencies/fplutil/setuputil/common.py
Python
Setup
Setup
31
61
31
31
b17e5da1443cf8e88c325f249adfa076e0d31683
bigcode/the-stack
train
86ba3184653c4e671b53fd23
train
class
class CommandFailedError(Exception): """Raised when a subprocess fails for unforseeable reasons.""" def __init__(self, command, link): Exception.__init__(self) self.command = command self.link = link
class CommandFailedError(Exception):
"""Raised when a subprocess fails for unforseeable reasons.""" def __init__(self, command, link): Exception.__init__(self) self.command = command self.link = link
__(self) self.filetype = filetype self.instructions = instructions class ExtractionError(Exception): """Raised when a compressed file was unable to be extracted.""" def __init__(self, filepath): Exception.__init__(self) self.filepath = filepath class CommandFailedError(Exception):
64
64
49
6
57
niu2x/gxm
dependencies/fplutil/setuputil/common.py
Python
CommandFailedError
CommandFailedError
150
156
150
150
325118e16a3b0342ef552a6851c1b9ef9b72005f
bigcode/the-stack
train
421a7984402cd02558aa652a
train
class
class PermissionDeniedError(Exception): """Raised when the script was not able to gain the correct permissions.""" def __init__(self, program, instructions): Exception.__init__(self) self.program = program self.instructions = instructions
class PermissionDeniedError(Exception):
"""Raised when the script was not able to gain the correct permissions.""" def __init__(self, program, instructions): Exception.__init__(self) self.program = program self.instructions = instructions
self) self.filepath = filepath class CommandFailedError(Exception): """Raised when a subprocess fails for unforseeable reasons.""" def __init__(self, command, link): Exception.__init__(self) self.command = command self.link = link class PermissionDeniedError(Exception):
64
64
51
6
57
niu2x/gxm
dependencies/fplutil/setuputil/common.py
Python
PermissionDeniedError
PermissionDeniedError
159
165
159
159
c594d995731e60116cc819aac85b41f046256cfd
bigcode/the-stack
train
82c2103df17b67d0f7bdee47
train
class
class FileDownloadError(Exception): """Raised when a file was unable to download.""" def __init__(self, link, instructions=""): Exception.__init__(self) self.link = link self.instructions = instructions
class FileDownloadError(Exception):
"""Raised when a file was unable to download.""" def __init__(self, link, instructions=""): Exception.__init__(self) self.link = link self.instructions = instructions
class InstallFailedError(Exception): """Raised when installation fails for reasons other than user interrupt.""" def __init__(self, program, link="", instructions=""): Exception.__init__(self) self.program = program self.link = link self.instructions = instructions class FileDownloadError(Exception...
64
64
48
6
57
niu2x/gxm
dependencies/fplutil/setuputil/common.py
Python
FileDownloadError
FileDownloadError
124
130
124
124
e51bf510f5bef168a55196f21aefc7b13480de63
bigcode/the-stack
train
3ff46e447cbfdc860474986e
train
class
class WebbrowserFailedError(Exception): """Raised when a url was unable to be opened in the webbrowser.""" def __init__(self, pagename, link): Exception.__init__(self) self.pagename = pagename self.link = link
class WebbrowserFailedError(Exception):
"""Raised when a url was unable to be opened in the webbrowser.""" def __init__(self, pagename, link): Exception.__init__(self) self.pagename = pagename self.link = link
self.link = link class PermissionDeniedError(Exception): """Raised when the script was not able to gain the correct permissions.""" def __init__(self, program, instructions): Exception.__init__(self) self.program = program self.instructions = instructions class WebbrowserFailedError(Exception):
64
64
59
7
56
niu2x/gxm
dependencies/fplutil/setuputil/common.py
Python
WebbrowserFailedError
WebbrowserFailedError
168
174
168
168
38a775ceac460a73914675d7b87abfeb5ed7f8d5
bigcode/the-stack
train
9da2608385fb0655b93f3fe9
train
class
class InstallFailedError(Exception): """Raised when installation fails for reasons other than user interrupt.""" def __init__(self, program, link="", instructions=""): Exception.__init__(self) self.program = program self.link = link self.instructions = instructions
class InstallFailedError(Exception):
"""Raised when installation fails for reasons other than user interrupt.""" def __init__(self, program, link="", instructions=""): Exception.__init__(self) self.program = program self.link = link self.instructions = instructions
self.directory = directory class InstallInterruptError(Exception): """Raised when installation of a program was interrupted by the user.""" def __init__(self, program, instructions=""): Exception.__init__(self) self.program = program self.instructions = instructions class InstallFailedError(Exce...
64
64
58
6
57
niu2x/gxm
dependencies/fplutil/setuputil/common.py
Python
InstallFailedError
InstallFailedError
114
121
114
114
5081eba9335de1916c44995ea7d4c884740ccd8d
bigcode/the-stack
train
1b6cdbd793a71ed91423b9d4
train
class
class ExtractionError(Exception): """Raised when a compressed file was unable to be extracted.""" def __init__(self, filepath): Exception.__init__(self) self.filepath = filepath
class ExtractionError(Exception):
"""Raised when a compressed file was unable to be extracted.""" def __init__(self, filepath): Exception.__init__(self) self.filepath = filepath
self.instructions = instructions class UnknownFileTypeError(Exception): """Raised when the extension of a file is unrecognised.""" def __init__(self, filetype, instructions): Exception.__init__(self) self.filetype = filetype self.instructions = instructions class ExtractionError(Exception):
64
64
41
5
58
niu2x/gxm
dependencies/fplutil/setuputil/common.py
Python
ExtractionError
ExtractionError
142
147
142
142
95a6329f054aedf1e6ffb6820f8fe60acc4cd338
bigcode/the-stack
train
faf4630e69c39ab629a21fb3
train
class
class SystemUnsupportedError(Exception): """Raised when an OS is unrecognised or unsupported.""" def __init__(self, system): Exception.__init__(self) self.system = system
class SystemUnsupportedError(Exception):
"""Raised when an OS is unrecognised or unsupported.""" def __init__(self, system): Exception.__init__(self) self.system = system
_DIR, options.ant_location) if not os.path.isdir(self.ant_path): raise BadDirectoryError("--ant", self.ant_path) def has_bash_changed(self): """Returns wheter or not the bash profile has been changed.""" return self.bash_profile_changed class SystemUnsupportedError(Exception):
64
64
41
6
57
niu2x/gxm
dependencies/fplutil/setuputil/common.py
Python
SystemUnsupportedError
SystemUnsupportedError
64
69
64
64
4bf8bb8c8188a65545aafa7dceaae4e526b88d77
bigcode/the-stack
train
96b8b2367c43ccb5ed1efbda
train
class
class VersionTooLowError(Exception): """Raised when the OS version is less than the lowest supported.""" def __init__(self, version): Exception.__init__(self) self.version = version
class VersionTooLowError(Exception):
"""Raised when the OS version is less than the lowest supported.""" def __init__(self, version): Exception.__init__(self) self.version = version
): Exception.__init__(self) self.version = version class VersionTooHighError(Exception): """Raised when the OS version is greater than the highest supported.""" def __init__(self, version): Exception.__init__(self) self.version = version class VersionTooLowError(Exception):
64
64
43
7
56
niu2x/gxm
dependencies/fplutil/setuputil/common.py
Python
VersionTooLowError
VersionTooLowError
88
93
88
88
e462d2822623d42aaa59a9df0a38df17f3b15e83
bigcode/the-stack
train
1dc2abd9cef524d4d5f9dad2
train
class
class BadDirectoryError(Exception): """Raised when a directory given through a command line flag doesn't exist.""" def __init__(self, flag, directory): Exception.__init__(self) self.flag = flag self.directory = directory
class BadDirectoryError(Exception):
"""Raised when a directory given through a command line flag doesn't exist.""" def __init__(self, flag, directory): Exception.__init__(self) self.flag = flag self.directory = directory
version): Exception.__init__(self) self.version = version class VersionTooLowError(Exception): """Raised when the OS version is less than the lowest supported.""" def __init__(self, version): Exception.__init__(self) self.version = version class BadDirectoryError(Exception):
64
64
51
6
57
niu2x/gxm
dependencies/fplutil/setuputil/common.py
Python
BadDirectoryError
BadDirectoryError
96
102
96
96
7906e5be205b0c9babf40a82bc31e67e9a7f16b4
bigcode/the-stack
train
8ca71568a552790805ae24b1
train
class
class InstallInterruptError(Exception): """Raised when installation of a program was interrupted by the user.""" def __init__(self, program, instructions=""): Exception.__init__(self) self.program = program self.instructions = instructions
class InstallInterruptError(Exception):
"""Raised when installation of a program was interrupted by the user.""" def __init__(self, program, instructions=""): Exception.__init__(self) self.program = program self.instructions = instructions
) self.version = version class BadDirectoryError(Exception): """Raised when a directory given through a command line flag doesn't exist.""" def __init__(self, flag, directory): Exception.__init__(self) self.flag = flag self.directory = directory class InstallInterruptError(Exception):
64
64
51
6
57
niu2x/gxm
dependencies/fplutil/setuputil/common.py
Python
InstallInterruptError
InstallInterruptError
105
111
105
105
93c5cbfc69cf75c4b1938ed3e876a9cbc614b0f5
bigcode/the-stack
train
2fe719069a013fa1821bf3c0
train
class
@dataclass class Remarks(StringOrRefType): """Information about this object or code. Contains text or refers to external text. """ class Meta: name = "remarks" namespace = "http://www.opengis.net/gml"
@dataclass class Remarks(StringOrRefType):
"""Information about this object or code. Contains text or refers to external text. """ class Meta: name = "remarks" namespace = "http://www.opengis.net/gml"
from dataclasses import dataclass from bindings.csw.string_or_ref_type import StringOrRefType __NAMESPACE__ = "http://www.opengis.net/gml" @dataclass class Remarks(StringOrRefType):
46
64
53
10
36
NIVANorge/s-enda-playground
catalog/bindings/csw/remarks.py
Python
Remarks
Remarks
7
16
7
8
4fc5c99875d8a544f47a09f75dda7abaf8184509
bigcode/the-stack
train
f71bc27e40fcf0c6488bd3ec
train
class
class ModuleNode(Node): """a node that extends `torch.nn.Module` `ModuleNode` manages neural network modules (`torch.nn.Module`) and the optimizers responsible to train them. For each `ModuleNode`, multiple optimizers can be specified, each of which can be responsible for different group of parameters by filte...
class ModuleNode(Node):
"""a node that extends `torch.nn.Module` `ModuleNode` manages neural network modules (`torch.nn.Module`) and the optimizers responsible to train them. For each `ModuleNode`, multiple optimizers can be specified, each of which can be responsible for different group of parameters by filtering parameters names. ...
from __future__ import annotations import re from time import sleep from typing import TYPE_CHECKING, Any, Callable, Dict, List, Set, Tuple, overload from ice.llutil.config import freeze from ice.core.graph import GraphOutputCache, Node from ice.core.optim import Optimizer from ice.llutil.argparser import as_dict, as...
123
256
2,436
5
117
tjyuyao/ice-learn
ice/core/module.py
Python
ModuleNode
ModuleNode
19
293
19
19
9e84be7b6dc6df1d1ff31836597a48aa08d34b5c
bigcode/the-stack
train
4bdf75f89e4c504a400aab68
train
class
class PyDaskSphinxTheme(PythonPackage): """Sphinx theme for Dask documentation.""" homepage = "https://github.com/dask/dask-sphinx-theme/" pypi = "dask_sphinx_theme/dask_sphinx_theme-1.3.5.tar.gz" version('1.3.5', sha256='151970cf0efedeb398fd6ca080407d3e81b4584d333e24498262d954171baa33') depends_...
class PyDaskSphinxTheme(PythonPackage):
"""Sphinx theme for Dask documentation.""" homepage = "https://github.com/dask/dask-sphinx-theme/" pypi = "dask_sphinx_theme/dask_sphinx_theme-1.3.5.tar.gz" version('1.3.5', sha256='151970cf0efedeb398fd6ca080407d3e81b4584d333e24498262d954171baa33') depends_on('py-setuptools', type='build') de...
2013-2022 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.package import * class PyDaskSphinxTheme(PythonPackage):
64
64
136
11
53
jeanbez/spack
var/spack/repos/builtin/packages/py-dask-sphinx-theme/package.py
Python
PyDaskSphinxTheme
PyDaskSphinxTheme
9
18
9
9
bb45309b9189e5a528c42a99d17e3dd4332ccabd
bigcode/the-stack
train
193a38cab44cdc02ea1c6b85
train
function
def uncovered_func(): a = 1 b = 2 c = 3 return a + b + c
def uncovered_func():
a = 1 b = 2 c = 3 return a + b + c
def covered_func(): a = 1 b = 2 return a + b def uncovered_func():
26
64
30
4
21
djeebus/teamcity-python
tests/guinea-pigs/pytest/coverage_test/funcs.py
Python
uncovered_func
uncovered_func
7
11
7
7
f6bec331df6263751ac9f0c0e0a3fb05f4863df1
bigcode/the-stack
train
e58e24f4c651486964a23259
train
function
def covered_func(): a = 1 b = 2 return a + b
def covered_func():
a = 1 b = 2 return a + b
def covered_func():
4
64
22
4
0
djeebus/teamcity-python
tests/guinea-pigs/pytest/coverage_test/funcs.py
Python
covered_func
covered_func
1
4
1
1
ebedb40c250499b930d5a4f7fcd80ac53b26a7d6
bigcode/the-stack
train
6820fbd9ee94adc87f69fb34
train
function
def gaderypoluki(napis): wynik = '' for i in range(len(napis)): match napis[i]: case 'g': wynik += 'a' case 'a': wynik += 'g' case 'd': wynik += 'e' case 'e': wynik += 'd' case 'r': wynik += 'y' case 'y': wynik += 'r' ca...
def gaderypoluki(napis):
wynik = '' for i in range(len(napis)): match napis[i]: case 'g': wynik += 'a' case 'a': wynik += 'g' case 'd': wynik += 'e' case 'e': wynik += 'd' case 'r': wynik += 'y' case 'y': wynik += 'r' case 'p': wynik += 'o' ...
def gaderypoluki(napis):
8
64
158
8
0
virgohi21/school-3
szyfry_proste/gaderypoluki.py
Python
gaderypoluki
gaderypoluki
1
18
1
1
ac39c5c7c67ec9e882903501917d1d6585f99321
bigcode/the-stack
train
9aea4539e046fe52c732912d
train
class
class ClockTimerA(Clock): """Represents a clock timer of type A.""" def __init__(self, x, y, game, time_in_secs, name=None): self.file_mid_prefix = 'timer_01' self.type = ActorType.CLOCK_TIMER_A super().__init__(x, y, game, name=name) self.clock = ClockTimer(self.game, time_in_...
class ClockTimerA(Clock):
"""Represents a clock timer of type A.""" def __init__(self, x, y, game, time_in_secs, name=None): self.file_mid_prefix = 'timer_01' self.type = ActorType.CLOCK_TIMER_A super().__init__(x, y, game, name=name) self.clock = ClockTimer(self.game, time_in_secs, trigger_method=self....
def set_on(self): clock = ClockTimerA(self.game.player.rect.x, self.game.player.rect.y - 60, self.game, self.time_in_secs) self.game.active_sprites.add([clock]) self.game.clock_sprites.add([clock]) self.kill() class ClockTimerA(Clock):
67
67
225
7
60
japinol7/the-codemaster
codemaster/models/actors/items/clocks.py
Python
ClockTimerA
ClockTimerA
54
78
54
54
0248dcc29e48f6db160ef0c5f642b699f12daa28
bigcode/the-stack
train
7ce82001df09cee043d15232
train
class
class Clock(ActorItem): """Represents a clock. It is not intended to be instantiated. """ def __init__(self, x, y, game, name=None): self.file_folder = BM_CLOCKS_FOLDER self.file_name_key = 'im_clocks' self.images_sprite_no = 1 self.category_type = ActorCategoryType.CLOCK...
class Clock(ActorItem):
"""Represents a clock. It is not intended to be instantiated. """ def __init__(self, x, y, game, name=None): self.file_folder = BM_CLOCKS_FOLDER self.file_name_key = 'im_clocks' self.images_sprite_no = 1 self.category_type = ActorCategoryType.CLOCK self.stats = St...
actors import ActorItem from codemaster.models.stats import Stats from codemaster.models.clocks import ClockTimer from codemaster.utils.colors import Color from codemaster.utils import utils_graphics as libg_jp from codemaster.config.settings import logger class Clock(ActorItem):
64
64
167
6
57
japinol7/the-codemaster
codemaster/models/actors/items/clocks.py
Python
Clock
Clock
14
34
14
14
fd016bb2f8445f304cf5648527486aa5a8fbc707
bigcode/the-stack
train
c9e12caddeee96b7e6b0fba8
train
class
class ClockA(Clock): """Represents a clock of type A. It generates a clock timer A""" def __init__(self, x, y, game, time_in_secs, name=None): self.file_mid_prefix = '01' self.type = ActorType.CLOCK_A self.time_in_secs = time_in_secs super().__init__(x, y, game, name=name) ...
class ClockA(Clock):
"""Represents a clock of type A. It generates a clock timer A""" def __init__(self, x, y, game, time_in_secs, name=None): self.file_mid_prefix = '01' self.type = ActorType.CLOCK_A self.time_in_secs = time_in_secs super().__init__(x, y, game, name=name) def set_on(self): ...
= 0 self.stats.strength = self.stats.strength_total = 1 super().__init__(x, y, game, name=name) def update_when_hit(self): """Cannot be hit.""" pass def set_on(self): pass class ClockA(Clock):
64
64
146
6
57
japinol7/the-codemaster
codemaster/models/actors/items/clocks.py
Python
ClockA
ClockA
37
51
37
37
0da4f16d823b232e9653e71db411bbdf53a84641
bigcode/the-stack
train
e9fcdb4043aa65030447a685
train
class
class FootnoteAssociationGoodsNomenclature(TrackedModel, ValidityMixin): record_code = "400" subrecord_code = "20" goods_nomenclature = models.ForeignKey( GoodsNomenclature, on_delete=models.PROTECT, related_name="footnote_associations", ) associated_footnote = models.Foreig...
class FootnoteAssociationGoodsNomenclature(TrackedModel, ValidityMixin):
record_code = "400" subrecord_code = "20" goods_nomenclature = models.ForeignKey( GoodsNomenclature, on_delete=models.PROTECT, related_name="footnote_associations", ) associated_footnote = models.ForeignKey( "footnotes.Footnote", on_delete=models.PROTECT, ...
) def __str__(self): return ( f"replaced=({self.replaced_goods_nomenclature}), " f"absorbed_into=({self.absorbed_into_goods_nomenclature})" ) class FootnoteAssociationGoodsNomenclature(TrackedModel, ValidityMixin):
64
64
174
16
48
uktrade/tamato
commodities/models/orm.py
Python
FootnoteAssociationGoodsNomenclature
FootnoteAssociationGoodsNomenclature
487
513
487
487
c55044f3e7955bfa1492d58a097d49f048fc5c71
bigcode/the-stack
train
f488a5227dbcbfec5297f5ae
train
class
class GoodsNomenclatureDescription(DescriptionMixin, TrackedModel): record_code = "400" subrecord_code = "15" period_record_code = "400" period_subrecord_code = "10" objects = PolymorphicManager.from_queryset(DescriptionQueryset)() sid = NumericSID() described_goods_nomenclature = models.F...
class GoodsNomenclatureDescription(DescriptionMixin, TrackedModel):
record_code = "400" subrecord_code = "15" period_record_code = "400" period_subrecord_code = "10" objects = PolymorphicManager.from_queryset(DescriptionQueryset)() sid = NumericSID() described_goods_nomenclature = models.ForeignKey( GoodsNomenclature, on_delete=models.PROTE...
_valid_between(valid_between) for child in self.get_children(): child.restrict_valid_between(self.valid_between) self.save() def __str__(self): return f"path={self.path}, indent=({self.indent})" class GoodsNomenclatureDescription(DescriptionMixin, TrackedModel):
64
64
132
14
50
uktrade/tamato
commodities/models/orm.py
Python
GoodsNomenclatureDescription
GoodsNomenclatureDescription
391
410
391
391
abb6ff0c36ec3d35e0fdc6cb5e89f346fd791ab7
bigcode/the-stack
train
1b57e1dd23217cc829cc5acd
train
class
class GoodsNomenclatureIndent(TrackedModel, ValidityStartMixin): record_code = "400" subrecord_code = "05" objects: GoodsNomenclatureIndentQuerySet = PolymorphicManager.from_queryset( GoodsNomenclatureIndentQuerySet, )() sid = NumericSID() indent = models.PositiveIntegerField(db_index...
class GoodsNomenclatureIndent(TrackedModel, ValidityStartMixin):
record_code = "400" subrecord_code = "05" objects: GoodsNomenclatureIndentQuerySet = PolymorphicManager.from_queryset( GoodsNomenclatureIndentQuerySet, )() sid = NumericSID() indent = models.PositiveIntegerField(db_index=True) indented_goods_nomenclature = models.ForeignKey( ...
property def dependent_measures(self): return self.measures.model.objects.filter( goods_nomenclature__sid=self.sid, ).approved_up_to_transaction(self.transaction) @property def is_taric_code(self) -> bool: return self.code.is_taric_code def in_use(self): ret...
91
91
305
15
76
uktrade/tamato
commodities/models/orm.py
Python
GoodsNomenclatureIndent
GoodsNomenclatureIndent
202
243
202
202
a1bd612f38cff16ecb3f356890fe5725478d4501
bigcode/the-stack
train
bf411fc15f2a4a2c5e418175
train
class
class GoodsNomenclatureSuccessor(TrackedModel): """ Represents a link between a end-dated GoodsNomenclature and the codes that have replaced it (or in TARIC parlance have "absorbed" it). The replacing codes cover the goods that this classification code previously covered. """ record_code =...
class GoodsNomenclatureSuccessor(TrackedModel):
""" Represents a link between a end-dated GoodsNomenclature and the codes that have replaced it (or in TARIC parlance have "absorbed" it). The replacing codes cover the goods that this classification code previously covered. """ record_code = "400" subrecord_code = "40" replaced_g...
5,) business_rules = (business_rules.NIG7, UpdateValidity) def __str__(self): return ( f"derived_from=({self.derived_from_goods_nomenclature}), " f"new=({self.new_goods_nomenclature})" ) class GoodsNomenclatureSuccessor(TrackedModel):
70
70
234
11
59
uktrade/tamato
commodities/models/orm.py
Python
GoodsNomenclatureSuccessor
GoodsNomenclatureSuccessor
451
484
451
451
8ee0bc8e5bdc7c8a56169b1d6ba4d5989fa5fdae
bigcode/the-stack
train
c8bb83d197059e0309749a4e
train
class
@dataclass class CommodityCode: """A dataclass for commodity codes with a range of convenience properties.""" code: str @property def chapter(self) -> str: """Returns the HS chapter for the commodity code.""" return self.code[:2] @property def heading(self) -> str: ...
@dataclass class CommodityCode:
"""A dataclass for commodity codes with a range of convenience properties.""" code: str @property def chapter(self) -> str: """Returns the HS chapter for the commodity code.""" return self.code[:2] @property def heading(self) -> str: """Returns the HS heading for t...
import models from django.db import transaction from django.db.models import Q from polymorphic.managers import PolymorphicManager from treebeard.mp_tree import MP_Node from commodities import business_rules from commodities import validators from commodities.querysets import GoodsNomenclatureIndentQuerySet from comm...
171
171
572
7
163
uktrade/tamato
commodities/models/orm.py
Python
CommodityCode
CommodityCode
28
107
28
29
59dbb37c513a952339706be7d9fc1e7e7f8da75c
bigcode/the-stack
train
ec313ac0d73b39b2d1b364ed
train
class
class GoodsNomenclatureOrigin(TrackedModel): """ Represents a link between a newly-created GoodsNomenclature and the codes that previously represented it. This will often be the parent nomenclature code. A GoodsNomenclature can have multiple origins when the hierarchy has been reorganised and the n...
class GoodsNomenclatureOrigin(TrackedModel):
""" Represents a link between a newly-created GoodsNomenclature and the codes that previously represented it. This will often be the parent nomenclature code. A GoodsNomenclature can have multiple origins when the hierarchy has been reorganised and the new classification was previously covered ...
described_goods_nomenclature = models.ForeignKey( GoodsNomenclature, on_delete=models.PROTECT, related_name="descriptions", ) description = LongDescription() indirect_business_rules = (business_rules.NIG12,) class Meta: ordering = ("validity_start",) class GoodsNome...
75
75
250
10
65
uktrade/tamato
commodities/models/orm.py
Python
GoodsNomenclatureOrigin
GoodsNomenclatureOrigin
413
448
413
413
e735462d7dbc2126106fc7424c4cf02d8091cce7
bigcode/the-stack
train
2807ed5bf2abece97eccb4ae
train
class
class GoodsNomenclatureIndentNode(MP_Node, ValidityMixin): """ Goods Nomenclature naturally falls into the structure of a hierarchical tree. As there is a root good e.g. "Live Animals; Animal Products" which then has branch nodes such as "Live animals" and "Meat and edible meat offal". And so on and...
class GoodsNomenclatureIndentNode(MP_Node, ValidityMixin):
""" Goods Nomenclature naturally falls into the structure of a hierarchical tree. As there is a root good e.g. "Live Animals; Animal Products" which then has branch nodes such as "Live animals" and "Meat and edible meat offal". And so on and so forth until leaf nodes are found. To represent thi...
() indent = models.PositiveIntegerField(db_index=True) indented_goods_nomenclature = models.ForeignKey( GoodsNomenclature, on_delete=models.PROTECT, related_name="indents", ) indirect_business_rules = (business_rules.NIG11,) business_rules = (business_rules.NIG2, UpdateVal...
255
256
1,238
15
240
uktrade/tamato
commodities/models/orm.py
Python
GoodsNomenclatureIndentNode
GoodsNomenclatureIndentNode
246
388
246
246
b7112a2020826ec2ac34a891863b67266cabd926
bigcode/the-stack
train
845f0f83d2466e3861ffe350
train
class
class GoodsNomenclature(TrackedModel, ValidityMixin): record_code = "400" subrecord_code = "00" sid = NumericSID() # These are character fields as they often has leading 0s item_id = models.CharField( max_length=10, validators=[validators.item_id_validator], db_index=True, ...
class GoodsNomenclature(TrackedModel, ValidityMixin):
record_code = "400" subrecord_code = "00" sid = NumericSID() # These are character fields as they often has leading 0s item_id = models.CharField( max_length=10, validators=[validators.item_id_validator], db_index=True, ) suffix = models.CharField( max_lengt...
Returns true if the commodity code represents a HS subheading.""" return self.trimmed_code == self.subheading @property def is_cn_subheading(self) -> bool: """Returns true if the commodity code represents a CN subheading.""" return self.trimmed_code == self.cn_subheading @property ...
168
168
561
13
154
uktrade/tamato
commodities/models/orm.py
Python
GoodsNomenclature
GoodsNomenclature
110
199
110
110
3c904b8d72636db4d5bea640d928c05f07baf42c
bigcode/the-stack
train
d33781e84882d72bb8d2e1b2
train
class
class GearSystem: def __init__(self, palette): self.n_gears = random.choice([2, 3, 4, 5, 6]) self.speeds = 1.*np.random.choice([-1, 1], self.n_gears)*np.random.choice([0, 0, 1, 2, 4, 8, 16], self.n_gears) radii = np.random.uniform(0.05, 1, self.n_gears) # this will lead to a strong bias towards smaller gea...
class GearSystem:
def __init__(self, palette): self.n_gears = random.choice([2, 3, 4, 5, 6]) self.speeds = 1.*np.random.choice([-1, 1], self.n_gears)*np.random.choice([0, 0, 1, 2, 4, 8, 16], self.n_gears) radii = np.random.uniform(0.05, 1, self.n_gears) # this will lead to a strong bias towards smaller gears, while keeping t...
import random import numpy as np import math from PIL import ImageColor from utils import shadeN class GearSystem:
27
226
756
4
22
tannerbohn/EvolvingSpirograph
GearSystem.py
Python
GearSystem
GearSystem
7
76
7
8
ba154992f20b59e4774a57ef82bbd4c4a28a3d69
bigcode/the-stack
train
38231ebe882bffdca0d72a07
train
function
@pytest.mark.django_db @pytest.mark.vcr def test_ingest(): state = stripe.Customer.create(email='test@example.com') instance, created = reconciliate(state, persist=True) assert created assert instance.id == state['id'] assert instance.data == state assert isinstance(instance, Customer)
@pytest.mark.django_db @pytest.mark.vcr def test_ingest():
state = stripe.Customer.create(email='test@example.com') instance, created = reconciliate(state, persist=True) assert created assert instance.id == state['id'] assert instance.data == state assert isinstance(instance, Customer)
import pytest import stripe from rayures.models import Customer, state_factory from rayures.reconciliation import reconciliate, reconciliate_by_event @pytest.mark.django_db @pytest.mark.vcr def test_ingest():
46
64
67
16
29
johnnoone/django-rayures
tests/ingestion_tests.py
Python
test_ingest
test_ingest
7
15
7
9
21db25f1732690aa80bf2be6cd964767e9827865
bigcode/the-stack
train
fb5513a90716816b218c59fa
train
function
@pytest.mark.django_db @pytest.mark.vcr def test_event(): event = state_factory({ "created": 1326853478, "livemode": False, "id": "evt_00000000000000", "type": "account.external_account.created", "object": "event", "request": None, "pending_webhooks": 1, ...
@pytest.mark.django_db @pytest.mark.vcr def test_event():
event = state_factory({ "created": 1326853478, "livemode": False, "id": "evt_00000000000000", "type": "account.external_account.created", "object": "event", "request": None, "pending_webhooks": 1, "api_version": "2017-08-15", "data": { ...
.mark.vcr def test_ingest(): state = stripe.Customer.create(email='test@example.com') instance, created = reconciliate(state, persist=True) assert created assert instance.id == state['id'] assert instance.data == state assert isinstance(instance, Customer) @pytest.mark.django_db @pytest.mark.vcr...
75
75
253
15
60
johnnoone/django-rayures
tests/ingestion_tests.py
Python
test_event
test_event
18
49
18
20
eedc0ce3f1e70a730d0cc768e671cb3c0e6c9f1f
bigcode/the-stack
train
ffddbf25af61d9324a27065f
train
function
def create_dumps_foo(id, designation, last_visit, bar): # if bar: bar = settings.SITE.models.dumps.Bars.get_by_value(bar) kw = dict() kw.update(id=id) if designation is not None: kw.update(bv2kw('designation',designation)) kw.update(last_visit=last_visit) kw.update(bar=bar) return dumps_Foo(*...
def create_dumps_foo(id, designation, last_visit, bar): # if bar: bar = settings.SITE.models.dumps.Bars.get_by_value(bar)
kw = dict() kw.update(id=id) if designation is not None: kw.update(bv2kw('designation',designation)) kw.update(last_visit=last_visit) kw.update(bar=bar) return dumps_Foo(**kw)
=values[0],de=values[1],fr=values[2]) dumps_Foo = resolve_model("dumps.Foo") def create_dumps_foo(id, designation, last_visit, bar): # if bar: bar = settings.SITE.models.dumps.Bars.get_by_value(bar)
64
64
87
34
30
lino-framework/lino_book
lino_book/projects/dumps/a/restore.py
Python
create_dumps_foo
create_dumps_foo
61
68
61
62
2990ef25461a528b68ce485413320897eb4fb662
bigcode/the-stack
train
cf75a8b3821afe5e6eb36bae
train
function
def bv2kw(fieldname, values): """ Needed if `Site.languages` changed between dumpdata and loaddata """ return settings.SITE.babelkw(fieldname, en=values[0],de=values[1],fr=values[2])
def bv2kw(fieldname, values):
""" Needed if `Site.languages` changed between dumpdata and loaddata """ return settings.SITE.babelkw(fieldname, en=values[0],de=values[1],fr=values[2])
) def execfile(fn, *args): logger.info("Execute file %s ...", fn) six.exec_(compile(open(fn, "rb").read(), fn, 'exec'), *args) # pmem() # requires pip install psutil def bv2kw(fieldname, values):
64
64
58
9
54
lino-framework/lino_book
lino_book/projects/dumps/a/restore.py
Python
bv2kw
bv2kw
52
56
52
52
d3fc33132c50a68abfff1b07f5f659a198545e3f
bigcode/the-stack
train
8f5d99ae7e6c4827706d4a08
train
function
def pmem(): # Thanks to https://stackoverflow.com/questions/938733/total-memory-used-by-python-process process = psutil.Process(os.getpid()) print(process.memory_info().rss)
def pmem(): # Thanks to https://stackoverflow.com/questions/938733/total-memory-used-by-python-process
process = psutil.Process(os.getpid()) print(process.memory_info().rss)
if m is None: return m ct = settings.SITE.models.contenttypes.ContentType.objects.get_for_model(m) if ct is None: return None return ct.pk def pmem(): # Thanks to https://stackoverflow.com/questions/938733/total-memory-used-by-python-process
64
64
42
24
39
lino-framework/lino_book
lino_book/projects/dumps/a/restore.py
Python
pmem
pmem
41
44
41
42
d521f1bbe75372eb5a14b10ac4db4ae314789af2
bigcode/the-stack
train
50e47c28212fe24de23b1ba2
train
function
def new_content_type_id(m): if m is None: return m ct = settings.SITE.models.contenttypes.ContentType.objects.get_for_model(m) if ct is None: return None return ct.pk
def new_content_type_id(m):
if m is None: return m ct = settings.SITE.models.contenttypes.ContentType.objects.get_for_model(m) if ct is None: return None return ct.pk
lino.utils.dpy import DpyLoader from lino.core.utils import resolve_model if settings.USE_TZ: def dt(*args): return make_aware(datetime(*args), timezone=utc) else: def dt(*args): return datetime(*args) def new_content_type_id(m):
64
64
47
7
57
lino-framework/lino_book
lino_book/projects/dumps/a/restore.py
Python
new_content_type_id
new_content_type_id
35
39
35
35
2d1507ab1d6ca38da20d7c504863e2d567fd3337
bigcode/the-stack
train
6752f83940632acd26f4e065
train
function
def execfile(fn, *args): logger.info("Execute file %s ...", fn) six.exec_(compile(open(fn, "rb").read(), fn, 'exec'), *args)
def execfile(fn, *args):
logger.info("Execute file %s ...", fn) six.exec_(compile(open(fn, "rb").read(), fn, 'exec'), *args)
if ct is None: return None return ct.pk def pmem(): # Thanks to https://stackoverflow.com/questions/938733/total-memory-used-by-python-process process = psutil.Process(os.getpid()) print(process.memory_info().rss) def execfile(fn, *args):
64
64
41
8
56
lino-framework/lino_book
lino_book/projects/dumps/a/restore.py
Python
execfile
execfile
46
48
46
46
67243a4d6c72fa247c5ad20f9045946bb703af70
bigcode/the-stack
train
1258732e1f1f1681d1ad2657
train
function
def main(args): loader = DpyLoader(globals(), quick=args.quick) from django.core.management import call_command call_command('initdb', interactive=args.interactive) os.chdir(os.path.dirname(__file__)) loader.initialize() args = (globals(), locals()) execfile("dumps_foo.py", *args) loade...
def main(args):
loader = DpyLoader(globals(), quick=args.quick) from django.core.management import call_command call_command('initdb', interactive=args.interactive) os.chdir(os.path.dirname(__file__)) loader.initialize() args = (globals(), locals()) execfile("dumps_foo.py", *args) loader.finalize() ...
.Bars.get_by_value(bar) kw = dict() kw.update(id=id) if designation is not None: kw.update(bv2kw('designation',designation)) kw.update(last_visit=last_visit) kw.update(bar=bar) return dumps_Foo(**kw) def main(args):
64
64
98
4
60
lino-framework/lino_book
lino_book/projects/dumps/a/restore.py
Python
main
main
73
84
73
73
7f2dfc60a796162e2312ba4cf9c81f1769a63a8f
bigcode/the-stack
train
835d75d0b392a5d7db9ff2bf
train
function
def link_py_so(obj_files, so_file=None, cwd=None, libraries=None, cplus=False, fort=False, **kwargs): """ Link python extension module (shared object) for importing Parameters ========== obj_files: iterable of str Paths to object files to be linked. so_file: str Name...
def link_py_so(obj_files, so_file=None, cwd=None, libraries=None, cplus=False, fort=False, **kwargs):
""" Link python extension module (shared object) for importing Parameters ========== obj_files: iterable of str Paths to object files to be linked. so_file: str Name (path) of shared object file to create. If not specified it will have the basname of the last object file in...
else: Runner = CCompilerRunner flags = kwargs.pop('flags', []) if shared: if '-shared' not in flags: flags.append('-shared') run_linker = kwargs.pop('run_linker', True) if not run_linker: raise ValueError("run_linker was set to False (nonsensical...
149
149
499
28
120
clyring/sympy
sympy/utilities/_compilation/compilation.py
Python
link_py_so
link_py_so
192
254
192
193
ffefeaff2591ec86b893e8c84cb1c813d5160a06
bigcode/the-stack
train
e7194507f8dc524059017995
train
function
def pyx2obj(pyxpath, objpath=None, destdir=None, cwd=None, include_dirs=None, cy_kwargs=None, cplus=None, **kwargs): """ Convenience function If cwd is specified, pyxpath and dst are taken to be relative If only_update is set to `True` the modification time is checked and compilation is...
def pyx2obj(pyxpath, objpath=None, destdir=None, cwd=None, include_dirs=None, cy_kwargs=None, cplus=None, **kwargs):
""" Convenience function If cwd is specified, pyxpath and dst are taken to be relative If only_update is set to `True` the modification time is checked and compilation is only run if the source is newer than the destination Parameters ========== pyxpath: str Path to Cython...
Runner, std = extension_mapping[ext.lower()] if 'std' not in kwargs: kwargs['std'] = std flags = kwargs.pop('flags', []) needed_flags = ('-fPIC',) for flag in needed_flags: if flag not in flags: flags.append(flag) # src2obj implies not running the linker... ...
192
192
642
35
156
clyring/sympy
sympy/utilities/_compilation/compilation.py
Python
pyx2obj
pyx2obj
388
466
388
389
cf03bfff427bd453322e2d97c67707e80d10da6e
bigcode/the-stack
train
843223c658743d07f54fbb30
train
function
def simple_cythonize(src, destdir=None, cwd=None, **cy_kwargs): """ Generates a C file from a Cython source file. Parameters ========== src: str Path to Cython source. destdir: str (optional) Path to output directory (default: '.'). cwd: path string (optional) Root of r...
def simple_cythonize(src, destdir=None, cwd=None, **cy_kwargs):
""" Generates a C file from a Cython source file. Parameters ========== src: str Path to Cython source. destdir: str (optional) Path to output directory (default: '.'). cwd: path string (optional) Root of relative paths (default: '.'). **cy_kwargs: Second ar...
libraries += [pythonlib] else: pass flags = kwargs.pop('flags', []) needed_flags = ('-pthread',) for flag in needed_flags: if flag not in flags: flags.append(flag) return link(obj_files, shared=True, flags=flags, cwd=cwd, cplus=cplus,...
115
115
384
18
97
clyring/sympy
sympy/utilities/_compilation/compilation.py
Python
simple_cythonize
simple_cythonize
257
304
257
257
e336bd0502bb667b19907440aa6c926e29e6ae6f
bigcode/the-stack
train
fe7e3f93f709e4576186c201
train
function
def _any_X(srcs, cls): for src in srcs: name, ext = os.path.splitext(src) key = ext.lower() if key in extension_mapping: if extension_mapping[key][0] == cls: return True return False
def _any_X(srcs, cls):
for src in srcs: name, ext = os.path.splitext(src) key = ext.lower() if key in extension_mapping: if extension_mapping[key][0] == cls: return True return False
c99') return src2obj(interm_c_file, objpath=objpath, cwd=cwd, include_dirs=include_dirs, flags=flags, std=std, options=options, inc_py=True, strict_aliasing=False, **kwargs) def _any_X(srcs, cls):
64
64
58
9
55
clyring/sympy
sympy/utilities/_compilation/compilation.py
Python
_any_X
_any_X
469
476
469
469
c21724f09f3c3d89d1cfbcdaef74756aebe6f52c
bigcode/the-stack
train
20599f6d2dbb0343ba92fe25
train
function
def link(obj_files, out_file=None, shared=False, Runner=None, cwd=None, cplus=False, fort=False, **kwargs): """ Link object files. Parameters ========== obj_files: iterable of str Paths to object files. out_file: str (optional) Path to executable/shared library, if ``None`...
def link(obj_files, out_file=None, shared=False, Runner=None, cwd=None, cplus=False, fort=False, **kwargs):
""" Link object files. Parameters ========== obj_files: iterable of str Paths to object files. out_file: str (optional) Path to executable/shared library, if ``None`` it will be deduced from the last item in obj_files. shared: bool Generate a shared library? ...
return (FortranCompilerRunner, {'flags': ['-nofor_main', '-cxxlib']}, vendor) else: return (FortranCompilerRunner, {'flags': ['-nofor_main']}, vendor) elif vendor.lower() == 'gnu' or 'llvm': if cplus: return (CppCompilerRunn...
143
144
481
29
114
clyring/sympy
sympy/utilities/_compilation/compilation.py
Python
link
link
122
189
122
123
735ee1efac81553e33f7ba03c444d6089223d284
bigcode/the-stack
train
db69a18c4bbd2ffbf2041a2b
train
function
def src2obj(srcpath, Runner=None, objpath=None, cwd=None, inc_py=False, **kwargs): """ Compiles a source code file to an object file. Files ending with '.pyx' assumed to be cython files and are dispatched to pyx2obj. Parameters ========== srcpath: str Path to source file. Runner: ...
def src2obj(srcpath, Runner=None, objpath=None, cwd=None, inc_py=False, **kwargs):
""" Compiles a source code file to an object file. Files ending with '.pyx' assumed to be cython files and are dispatched to pyx2obj. Parameters ========== srcpath: str Path to source file. Runner: CompilerRunner subclass (optional) If ``None``: deduced from extension of s...
CCompilerRunner, None), '.cpp': (CppCompilerRunner, None), '.cxx': (CppCompilerRunner, None), '.f': (FortranCompilerRunner, None), '.for': (FortranCompilerRunner, None), '.ftn': (FortranCompilerRunner, None), '.f90': (FortranCompilerRunner, None), # ifort only knows about .f90 '.f95': (Fort...
162
162
543
24
138
clyring/sympy
sympy/utilities/_compilation/compilation.py
Python
src2obj
src2obj
321
385
321
321
db4ae4f667bd7959ea5d82f7fdb04a0dc3996f60
bigcode/the-stack
train
2acdad8ce1d28189f2f1f70f
train
function
def compile_run_strings(sources, build_dir=None, clean=False, compile_kwargs=None, link_kwargs=None): """ Compiles, links and runs a program built from sources. Parameters ========== sources : iterable of name/source pair tuples build_dir : string (default: None) Path. ``None`` implies use...
def compile_run_strings(sources, build_dir=None, clean=False, compile_kwargs=None, link_kwargs=None):
""" Compiles, links and runs a program built from sources. Parameters ========== sources : iterable of name/source pair tuples build_dir : string (default: None) Path. ``None`` implies use a temporary directory. clean : bool Whether to remove build_dir after use. This will only...
**kwargs: Keyword arguments passed onto `compile_link_import_py_ext`. Returns ======= mod : module The compiled and imported extension module. info : dict Containing ``build_dir`` as 'build_dir'. """ source_files, build_dir = _write_sources_to_build_dir(sources, bu...
132
132
443
22
109
clyring/sympy
sympy/utilities/_compilation/compilation.py
Python
compile_run_strings
compile_run_strings
589
633
589
589
28e0f8584bac9517728e06dc772d63a426252ddb
bigcode/the-stack
train
494b4e00945a2e4440c1fb1f
train
function
def _write_sources_to_build_dir(sources, build_dir): build_dir = build_dir or tempfile.mkdtemp() if not os.path.isdir(build_dir): raise OSError("Non-existent directory: ", build_dir) source_files = [] for name, src in sources: dest = os.path.join(build_dir, name) differs = True ...
def _write_sources_to_build_dir(sources, build_dir):
build_dir = build_dir or tempfile.mkdtemp() if not os.path.isdir(build_dir): raise OSError("Non-existent directory: ", build_dir) source_files = [] for name, src in sources: dest = os.path.join(build_dir, name) differs = True sha256_in_mem = sha256_of_string(src.encode('...
so = link_py_so(objs, cwd=build_dir, fort=any_fortran_src(sources), cplus=any_cplus_src(sources), **link_kwargs) mod = import_module_from_file(so) return mod def _write_sources_to_build_dir(sources, build_dir):
64
64
212
13
50
clyring/sympy
sympy/utilities/_compilation/compilation.py
Python
_write_sources_to_build_dir
_write_sources_to_build_dir
537
559
537
537
576c8694848099120379c6d7351539bc0e20f427
bigcode/the-stack
train
d031cf3ae5773a2d1540f921
train
function
def get_mixed_fort_c_linker(vendor=None, cplus=False, cwd=None): vendor = vendor or os.environ.get('SYMPY_COMPILER_VENDOR', 'gnu') if vendor.lower() == 'intel': if cplus: return (FortranCompilerRunner, {'flags': ['-nofor_main', '-cxxlib']}, vendor) else: ...
def get_mixed_fort_c_linker(vendor=None, cplus=False, cwd=None):
vendor = vendor or os.environ.get('SYMPY_COMPILER_VENDOR', 'gnu') if vendor.lower() == 'intel': if cplus: return (FortranCompilerRunner, {'flags': ['-nofor_main', '-cxxlib']}, vendor) else: return (FortranCompilerRunner, {'flags': ...
file_kwargs = kwargs.copy() file_kwargs.update(_per_file_kwargs.get(f, {})) dstpaths.append(src2obj(f, Runner, cwd=cwd, **file_kwargs)) return dstpaths def get_mixed_fort_c_linker(vendor=None, cplus=False, cwd=None):
64
64
167
20
43
clyring/sympy
sympy/utilities/_compilation/compilation.py
Python
get_mixed_fort_c_linker
get_mixed_fort_c_linker
101
119
101
101
afab5418bde4c05e5b73003b784203763dd773be
bigcode/the-stack
train
0a5fa7d27661c031a0685a6b
train
function
def compile_link_import_py_ext(sources, extname=None, build_dir='.', compile_kwargs=None, link_kwargs=None): """ Compiles sources to a shared object (python extension) and imports it Sources in ``sources`` which is imported. If shared object is newer than the sources, they ar...
def compile_link_import_py_ext(sources, extname=None, build_dir='.', compile_kwargs=None, link_kwargs=None):
""" Compiles sources to a shared object (python extension) and imports it Sources in ``sources`` which is imported. If shared object is newer than the sources, they are not recompiled but instead it is imported. Parameters ========== sources : string List of paths to sources. extn...
s, cls): for src in srcs: name, ext = os.path.splitext(src) key = ext.lower() if key in extension_mapping: if extension_mapping[key][0] == cls: return True return False def any_fortran_src(srcs): return _any_X(srcs, FortranCompilerRunner) def any_cplus...
121
121
406
26
95
clyring/sympy
sympy/utilities/_compilation/compilation.py
Python
compile_link_import_py_ext
compile_link_import_py_ext
487
535
487
488
7f89bc17f6bcb4d58d25a0d14123c7139ed15f29
bigcode/the-stack
train
d6c54f729b3e837df1b2c01a
train
function
def any_cplus_src(srcs): return _any_X(srcs, CppCompilerRunner)
def any_cplus_src(srcs):
return _any_X(srcs, CppCompilerRunner)
.splitext(src) key = ext.lower() if key in extension_mapping: if extension_mapping[key][0] == cls: return True return False def any_fortran_src(srcs): return _any_X(srcs, FortranCompilerRunner) def any_cplus_src(srcs):
64
64
21
8
56
clyring/sympy
sympy/utilities/_compilation/compilation.py
Python
any_cplus_src
any_cplus_src
483
484
483
483
6b58c839750758824d61c381efb7fd85524688a0
bigcode/the-stack
train
910170b55540479cd06a87aa
train
function
def compile_sources(files, Runner=None, destdir=None, cwd=None, keep_dir_struct=False, per_file_kwargs=None, **kwargs): """ Compile source code files to object files. Parameters ========== files : iterable of str Paths to source files, if ``cwd`` is given, the paths are tak...
def compile_sources(files, Runner=None, destdir=None, cwd=None, keep_dir_struct=False, per_file_kwargs=None, **kwargs):
""" Compile source code files to object files. Parameters ========== files : iterable of str Paths to source files, if ``cwd`` is given, the paths are taken as relative. Runner: CompilerRunner subclass (optional) Could be e.g. ``FortranCompilerRunner``. Will be inferred from filena...
_file, pyx_is_cplus, sha256_of_string, sha256_of_file ) from .runners import ( CCompilerRunner, CppCompilerRunner, FortranCompilerRunner ) sharedext = get_config_var('EXT_SUFFIX' if sys.version_info >= (3, 3) else 'SO') if os.name == 'posix': objext = '.o' elif os.name == 'nt': objext = '.ob...
151
151
504
29
122
clyring/sympy
sympy/utilities/_compilation/compilation.py
Python
compile_sources
compile_sources
38
98
38
39
11fdea93d94a809253a652956e0a17fa1ccf3f28
bigcode/the-stack
train
120bef11d64eaaa0920e35c5
train
function
def compile_link_import_strings(sources, build_dir=None, **kwargs): """ Compiles, links and imports extension module from source. Parameters ========== sources : iterable of name/source pair tuples build_dir : string (default: None) Path. ``None`` implies use a temporary directory. **k...
def compile_link_import_strings(sources, build_dir=None, **kwargs):
""" Compiles, links and imports extension module from source. Parameters ========== sources : iterable of name/source pair tuples build_dir : string (default: None) Path. ``None`` implies use a temporary directory. **kwargs: Keyword arguments passed onto `compile_link_import_py...
differs: with open(dest, 'wt') as fh: fh.write(src) open(dest+'.sha256', 'wt').write(sha256_in_mem) source_files.append(dest) return source_files, build_dir def compile_link_import_strings(sources, build_dir=None, **kwargs):
64
64
177
15
48
clyring/sympy
sympy/utilities/_compilation/compilation.py
Python
compile_link_import_strings
compile_link_import_strings
562
586
562
562
6cda3c0b3f24fc2a0cee81d7255d20e379e32d3c
bigcode/the-stack
train
2159a9e92b6ae9aa3bb896e3
train
function
def any_fortran_src(srcs): return _any_X(srcs, FortranCompilerRunner)
def any_fortran_src(srcs):
return _any_X(srcs, FortranCompilerRunner)
any_X(srcs, cls): for src in srcs: name, ext = os.path.splitext(src) key = ext.lower() if key in extension_mapping: if extension_mapping[key][0] == cls: return True return False def any_fortran_src(srcs):
64
64
21
8
55
clyring/sympy
sympy/utilities/_compilation/compilation.py
Python
any_fortran_src
any_fortran_src
479
480
479
479
fcf12eafc3055b5b2e78f96fc94ae51a2fe5c4eb
bigcode/the-stack
train
95c17c8717ea59085aa47da4
train
class
class AlertList(ListResource): """ """ def __init__(self, version): """ Initialize the AlertList :param Version version: Version that contains the resource :returns: twilio.rest.monitor.v1.alert.AlertList :rtype: twilio.rest.monitor.v1.alert.AlertList """ ...
class AlertList(ListResource):
""" """ def __init__(self, version): """ Initialize the AlertList :param Version version: Version that contains the resource :returns: twilio.rest.monitor.v1.alert.AlertList :rtype: twilio.rest.monitor.v1.alert.AlertList """ super(AlertList, self).__in...
# coding=utf-8 r""" This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / """ from twilio.base import deserialize from twilio.base import serialize from twilio.base import values from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import...
115
256
1,332
6
108
NCPlayz/twilio-python
twilio/rest/monitor/v1/alert.py
Python
AlertList
AlertList
18
176
18
18
9dc32dd8a5f0bdcd275d5f61b388a2df76e160c7
bigcode/the-stack
train
c69c214ad481fc45672cd1ca
train
class
class AlertPage(Page): """ """ def __init__(self, version, response, solution): """ Initialize the AlertPage :param Version version: Version that contains the resource :param Response response: Response from the API :returns: twilio.rest.monitor.v1.alert.AlertPage ...
class AlertPage(Page):
""" """ def __init__(self, version, response, solution): """ Initialize the AlertPage :param Version version: Version that contains the resource :param Response response: Response from the API :returns: twilio.rest.monitor.v1.alert.AlertPage :rtype: twilio.res...
Context """ return AlertContext(self._version, sid=sid, ) def __repr__(self): """ Provide a friendly representation :returns: Machine friendly representation :rtype: str """ return '<Twilio.Monitor.V1.AlertList>' class AlertPage(Page):
65
66
222
5
60
NCPlayz/twilio-python
twilio/rest/monitor/v1/alert.py
Python
AlertPage
AlertPage
179
215
179
179
314c958b95cd275a686a5db727b6e31fcc075312
bigcode/the-stack
train
cadca12b7506e2c77aa14413
train
class
class AlertContext(InstanceContext): """ """ def __init__(self, version, sid): """ Initialize the AlertContext :param Version version: Version that contains the resource :param sid: The SID that identifies the resource to fetch :returns: twilio.rest.monitor.v1.alert.A...
class AlertContext(InstanceContext):
""" """ def __init__(self, version, sid): """ Initialize the AlertContext :param Version version: Version that contains the resource :param sid: The SID that identifies the resource to fetch :returns: twilio.rest.monitor.v1.alert.AlertContext :rtype: twilio.re...
.monitor.v1.alert.AlertInstance :rtype: twilio.rest.monitor.v1.alert.AlertInstance """ return AlertInstance(self._version, payload, ) def __repr__(self): """ Provide a friendly representation :returns: Machine friendly representation :rtype: str """ ...
84
85
286
7
77
NCPlayz/twilio-python
twilio/rest/monitor/v1/alert.py
Python
AlertContext
AlertContext
218
262
218
218
0606ba7ffece877c5fac8acabbd43633fbc798f7
bigcode/the-stack
train
4f79c902ff2414363ab2c346
train
class
class AlertInstance(InstanceResource): """ """ def __init__(self, version, payload, sid=None): """ Initialize the AlertInstance :returns: twilio.rest.monitor.v1.alert.AlertInstance :rtype: twilio.rest.monitor.v1.alert.AlertInstance """ super(AlertInstance, self...
class AlertInstance(InstanceResource):
""" """ def __init__(self, version, payload, sid=None): """ Initialize the AlertInstance :returns: twilio.rest.monitor.v1.alert.AlertInstance :rtype: twilio.rest.monitor.v1.alert.AlertInstance """ super(AlertInstance, self).__init__(version) # Marshale...
that contains the resource :param sid: The SID that identifies the resource to fetch :returns: twilio.rest.monitor.v1.alert.AlertContext :rtype: twilio.rest.monitor.v1.alert.AlertContext """ super(AlertContext, self).__init__(version) # Path Solution self._solu...
256
256
1,376
7
249
NCPlayz/twilio-python
twilio/rest/monitor/v1/alert.py
Python
AlertInstance
AlertInstance
265
486
265
265
3491404e442699c362fd7860c59bbc88e3f9ca6c
bigcode/the-stack
train
563616c06e8f7d72767b8d91
train
class
class Migration(migrations.Migration): dependencies = [ ('accounts', '0002_order_product'), ] operations = [ migrations.CreateModel( name='Tag', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_...
class Migration(migrations.Migration):
dependencies = [ ('accounts', '0002_order_product'), ] operations = [ migrations.CreateModel( name='Tag', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', mod...
# Generated by Django 3.0.6 on 2020-06-03 07:14 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
45
70
235
7
37
Maniddarky/crm-django
accounts/migrations/0003_auto_20200603_1244.py
Python
Migration
Migration
7
41
7
8
7e1294c15415eed580481c8ea66cbc08c1911652
bigcode/the-stack
train
1391691ae418f35e5de84eec
train
class
class AlignedDataset(Dataset): def __init__( self, root: str, is_train: bool = True, transform: Optional[Callable] = None, direction: str = 'AtoB' ): self._root = root self._is_train = is_train self._transform = transform self._directi...
class AlignedDataset(Dataset):
def __init__( self, root: str, is_train: bool = True, transform: Optional[Callable] = None, direction: str = 'AtoB' ): self._root = root self._is_train = is_train self._transform = transform self._direction = direction self...
from typing import Callable, Dict, Optional import pathlib from PIL import Image import torch import numpy as np from torch.utils.data import Dataset class AlignedDataset(Dataset):
40
90
302
8
31
markovka17/efficient-dl-systems
week08_compress_models/homework_utils/dataset.py
Python
AlignedDataset
AlignedDataset
11
46
11
12
cf652f4ef82fa3b89fff86c3f1bb36cc08bb134e
bigcode/the-stack
train
1d803aa1877ea53dfe37f059
train
class
class SS_CRF(sklearn_crfsuite.CRF): def save(self, model_filename): destination = model_filename source = self.modelfile.name shutil.copy(src=source, dst=destination) # type: ignore @staticmethod def load(model_filename): model = SS_CRF(model_filename=model_filename) ...
class SS_CRF(sklearn_crfsuite.CRF):
def save(self, model_filename): destination = model_filename source = self.modelfile.name shutil.copy(src=source, dst=destination) # type: ignore @staticmethod def load(model_filename): model = SS_CRF(model_filename=model_filename) return model
import shutil import sklearn_crfsuite class SS_CRF(sklearn_crfsuite.CRF):
22
64
78
13
8
hieunguyen1053/ViNLP
ViNLP/models/ss_crf.py
Python
SS_CRF
SS_CRF
6
15
6
6
48936743f1d69847893620db0b33a4a4ffce06c7
bigcode/the-stack
train
fa0fff628dcdb205685ef567
train
class
class StartStreamPredictRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'ivision', '2019-03-08', 'StartStreamPredict','ivision') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"):...
class StartStreamPredictRequest(RpcRequest):
def __init__(self): RpcRequest.__init__(self, 'ivision', '2019-03-08', 'StartStreamPredict','ivision') 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", endpoin...
WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkivision.endpoint import endpoint_data class StartStreamPredictRequest(RpcRequest):
64
64
184
9
54
yndu13/aliyun-openapi-python-sdk
aliyun-python-sdk-ivision/aliyunsdkivision/request/v20190308/StartStreamPredictRequest.py
Python
StartStreamPredictRequest
StartStreamPredictRequest
23
44
23
24
3c73e1ffb647101fe70553f4191a628d028ac43e
bigcode/the-stack
train
db9ae179d7b40ecca8e350ba
train
function
def normal_distribution_cdf( x, miu, sigma): z_score = ( x - miu )/ sigma cdf_of_x = ( 1 + erf( z_score / (2 ** 0.5) ) ) / 2 return cdf_of_x
def normal_distribution_cdf( x, miu, sigma):
z_score = ( x - miu )/ sigma cdf_of_x = ( 1 + erf( z_score / (2 ** 0.5) ) ) / 2 return cdf_of_x
# Enter your code here. Read input from STDIN. Print output to STDOUT from math import erf def normal_distribution_cdf( x, miu, sigma):
36
64
62
13
22
brianchiang-tw/HackerRank
Statistics/Day_5_Normal Distribution I/normal_distribution_i.py
Python
normal_distribution_cdf
normal_distribution_cdf
5
11
5
6
d74846c38cfdc665934295bd126149fd56d35b15
bigcode/the-stack
train
28855867400850138549d6ab
train
class
@pulumi.input_type class OrderArgs: def __init__(__self__, *, contact_information: pulumi.Input['ContactDetailsArgs'], device_name: pulumi.Input[str], resource_group_name: pulumi.Input[str], shipping_address: pulumi.Input['AddressArgs'], ...
@pulumi.input_type class OrderArgs:
def __init__(__self__, *, contact_information: pulumi.Input['ContactDetailsArgs'], device_name: pulumi.Input[str], resource_group_name: pulumi.Input[str], shipping_address: pulumi.Input['AddressArgs'], current_status: Optional[pulu...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities fro...
113
206
687
10
103
polivbr/pulumi-azure-native
sdk/python/pulumi_azure_native/databoxedge/v20200501preview/order.py
Python
OrderArgs
OrderArgs
16
97
16
17
dd9fd83b7059ffe954331b57fac374fd0a50d1b0
bigcode/the-stack
train
3794d3793884c59cbcecf0ff
train
class
class Order(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, contact_information: Optional[pulumi.Input[pulumi.InputType['ContactDetailsArgs']]] = None, current_status: ...
class Order(pulumi.CustomResource): @overload
def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, contact_information: Optional[pulumi.Input[pulumi.InputType['ContactDetailsArgs']]] = None, current_status: Optional[pulumi.Input[pulumi.InputType['OrderStatu...
def resource_group_name(self) -> pulumi.Input[str]: """ The resource group name. """ return pulumi.get(self, "resource_group_name") @resource_group_name.setter def resource_group_name(self, value: pulumi.Input[str]): pulumi.set(self, "resource_group_name", value) ...
256
256
2,165
13
243
polivbr/pulumi-azure-native
sdk/python/pulumi_azure_native/databoxedge/v20200501preview/order.py
Python
Order
Order
100
287
100
101
b35e8677ff46e5b1874e7d2877eb8794211426d9
bigcode/the-stack
train
94019920fa4f02d1316d7c9f
train
class
class DeleteImageSyncRepoRequest: """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ sensitive...
class DeleteImageSyncRepoRequest:
""" Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ sensitive_list = [] openapi_types = { ...
# coding: utf-8 import pprint import re import six class DeleteImageSyncRepoRequest:
23
256
868
7
15
wuchen-huawei/huaweicloud-sdk-python-v3
huaweicloud-sdk-swr/huaweicloudsdkswr/v2/model/delete_image_sync_repo_request.py
Python
DeleteImageSyncRepoRequest
DeleteImageSyncRepoRequest
12
160
12
14
9cf75a40237278c5e558ed1a7b328c5ed76bad79
bigcode/the-stack
train
d7516aab4273a7d3c72fd56a
train
function
def load_silver_trees_single(path): with gzip.open(path, mode='rt') as f: linenum = 0 for line in f: linenum += 1 tokens = line.replace("(", " ( ").replace(")", " ) ").split() def helper(index): trees = [] while index < len(tokens...
def load_silver_trees_single(path):
with gzip.open(path, mode='rt') as f: linenum = 0 for line in f: linenum += 1 tokens = line.replace("(", " ( ").replace(")", " ) ").split() def helper(index): trees = [] while index < len(tokens) and tokens[index] == "(": ...
rees): if isinstance(tree, LeafTreebankNode): trees[i] = InternalTreebankNode("VROOT", [tree]) if strip_top: for i, tree in enumerate(trees): if tree.label in ("TOP", "ROOT"): assert len(tree.children) == 1 trees[i] = tree.children[0] ...
87
87
290
9
77
ebiggerr/malaya
session/constituency/src/trees_newline.py
Python
load_silver_trees_single
load_silver_trees_single
249
294
249
249
b01aa3d306e7c897d1046f1ae3f330790e8c4513
bigcode/the-stack
train
9da0b6c6d542b02466e4578c
train
class
class LeafTreebankNode(TreebankNode): def __init__(self, tag, word): assert isinstance(tag, str) self.tag = tag assert isinstance(word, str) self.word = word def linearize(self): return "({} {})".format(self.tag, self.word) def leaves(self): yield self ...
class LeafTreebankNode(TreebankNode):
def __init__(self, tag, word): assert isinstance(tag, str) self.tag = tag assert isinstance(word, str) self.word = word def linearize(self): return "({} {})".format(self.tag, self.word) def leaves(self): yield self def convert(self, index=0): r...
] sublabels.append(tree.label) children = [] for child in tree.children: children.append(child.convert(index=index)) index = children[-1].right return InternalParseNode(tuple(sublabels), children, nocache=nocache) class LeafTreebankNode(TreebankNode):
64
64
97
9
55
ebiggerr/malaya
session/constituency/src/trees_newline.py
Python
LeafTreebankNode
LeafTreebankNode
41
56
41
41
550d87ff1f28b2d12b265c4e46a495898dd0795a
bigcode/the-stack
train
e1c3e7c9395b3b4e1ca6ec2e
train
class
class TreebankNode(object): pass
class TreebankNode(object):
pass
import collections.abc import gzip class TreebankNode(object):
14
64
9
6
7
ebiggerr/malaya
session/constituency/src/trees_newline.py
Python
TreebankNode
TreebankNode
4
5
4
4
be4545a8604d1cdaebed33205aa9e3b92926cda2
bigcode/the-stack
train
9d8545ffaacfcd3a37538f29
train
class
class LeafParseNode(ParseNode): def __init__(self, index, tag, word): assert isinstance(index, int) assert index >= 0 self.left = index self.right = index + 1 assert isinstance(tag, str) self.tag = tag assert isinstance(word, str) self.word = word ...
class LeafParseNode(ParseNode):
def __init__(self, index, tag, word): assert isinstance(index, int) assert index >= 0 self.left = index self.right = index + 1 assert isinstance(tag, str) self.tag = tag assert isinstance(word, str) self.word = word def leaves(self): yie...
left and enclosing.right == right: return enclosing.label return () def oracle_splits(self, left, right): return [ child.left for child in self.enclosing(left, right).children if left < child.left < right ] class LeafParseNode(ParseNode):
64
64
101
7
57
ebiggerr/malaya
session/constituency/src/trees_newline.py
Python
LeafParseNode
LeafParseNode
115
132
115
115
70163f23754183f0a795a16fb6b492f596e974b4
bigcode/the-stack
train
442f731ad00c394255624788
train
function
def tree_from_str(treebank, strip_top=True, strip_spmrl_features=True): # Features bounded by `##` may contain spaces, so if we strip the features # we need to do so prior to tokenization if strip_spmrl_features: treebank = "".join(treebank.split("##")[::2]) tokens = treebank.replace("(", " ( "...
def tree_from_str(treebank, strip_top=True, strip_spmrl_features=True): # Features bounded by `##` may contain spaces, so if we strip the features # we need to do so prior to tokenization
if strip_spmrl_features: treebank = "".join(treebank.split("##")[::2]) tokens = treebank.replace("(", " ( ").replace(")", " ) ").split() def helper(index): trees = [] while index < len(tokens) and tokens[index] == "(": paren_count = 0 while tokens[index] ==...
, str) self.tag = tag assert isinstance(word, str) self.word = word def leaves(self): yield self def convert(self): return LeafTreebankNode(self.tag, self.word) def tree_from_str(treebank, strip_top=True, strip_spmrl_features=True): # Features bounded by `##` may c...
97
97
326
49
48
ebiggerr/malaya
session/constituency/src/trees_newline.py
Python
tree_from_str
tree_from_str
135
181
135
137
e0cb9e4da66e438d3709a7a43d834a64b4f71749
bigcode/the-stack
train
77f16fab899eb92160445a2a
train
function
def load_trees(path, strip_top=True, strip_spmrl_features=True): with open(path) as infile: treebanks = infile.read().split('\n') trees = [] for treebank in treebanks: try: # Features bounded by `##` may contain spaces, so if we strip the features # we need to do...
def load_trees(path, strip_top=True, strip_spmrl_features=True):
with open(path) as infile: treebanks = infile.read().split('\n') trees = [] for treebank in treebanks: try: # Features bounded by `##` may contain spaces, so if we strip the features # we need to do so prior to tokenization # if strip_spmrl_features: ...
trees.append(LeafTreebankNode(label, word)) while paren_count > 0: assert tokens[index] == ")" index += 1 paren_count -= 1 return trees, index trees, index = helper(0) assert index == len(tokens) if strip_top: f...
145
145
485
17
128
ebiggerr/malaya
session/constituency/src/trees_newline.py
Python
load_trees
load_trees
183
247
183
183
093af28e2f6cc938a6248b0d8f6b1fe10ed9d4e2
bigcode/the-stack
train
67329ea75204a0c9cdb280f3
train
class
class InternalTreebankNode(TreebankNode): def __init__(self, label, children): assert isinstance(label, str) self.label = label assert isinstance(children, collections.abc.Sequence) assert all(isinstance(child, TreebankNode) for child in children) assert children sel...
class InternalTreebankNode(TreebankNode):
def __init__(self, label, children): assert isinstance(label, str) self.label = label assert isinstance(children, collections.abc.Sequence) assert all(isinstance(child, TreebankNode) for child in children) assert children self.children = tuple(children) def line...
import collections.abc import gzip class TreebankNode(object): pass class InternalTreebankNode(TreebankNode):
26
69
232
9
16
ebiggerr/malaya
session/constituency/src/trees_newline.py
Python
InternalTreebankNode
InternalTreebankNode
7
39
7
7
90baf3cd93ee1bd5645b5cac3e0e49014dd9d336
bigcode/the-stack
train
268b11cd5bc1fbf2fdec9cbb
train
class
class InternalParseNode(ParseNode): def __init__(self, label, children, nocache=False): assert isinstance(label, tuple) assert all(isinstance(sublabel, str) for sublabel in label) assert label self.label = label assert isinstance(children, collections.abc.Sequence) a...
class InternalParseNode(ParseNode):
def __init__(self, label, children, nocache=False): assert isinstance(label, tuple) assert all(isinstance(sublabel, str) for sublabel in label) assert label self.label = label assert isinstance(children, collections.abc.Sequence) assert all(isinstance(child, ParseNod...
ache=nocache) class LeafTreebankNode(TreebankNode): def __init__(self, tag, word): assert isinstance(tag, str) self.tag = tag assert isinstance(word, str) self.word = word def linearize(self): return "({} {})".format(self.tag, self.word) def leaves(self): ...
117
117
391
7
109
ebiggerr/malaya
session/constituency/src/trees_newline.py
Python
InternalParseNode
InternalParseNode
61
113
61
61
e8e4e5267244299c7e4bf5c8d9451856295b4d0a
bigcode/the-stack
train
6c00ef9c99ce6aac1fc31873
train
function
def load_silver_trees(path, batch_size): batch = [] for tree in load_silver_trees_single(path): batch.append(tree) if len(batch) == batch_size: yield batch batch = []
def load_silver_trees(path, batch_size):
batch = [] for tree in load_silver_trees_single(path): batch.append(tree) if len(batch) == batch_size: yield batch batch = []
rees) == 1 tree = trees[0] # Strip the root S1 node assert tree.label == "S1" assert len(tree.children) == 1 tree = tree.children[0] yield tree def load_silver_trees(path, batch_size):
64
64
49
11
52
ebiggerr/malaya
session/constituency/src/trees_newline.py
Python
load_silver_trees
load_silver_trees
296
302
296
296
d04a646c6e77417c5d99fff3ed579c9763494d8f
bigcode/the-stack
train
9206f7d620c8d2df24d9d475
train
class
class ParseNode(object): pass
class ParseNode(object):
pass
str) self.word = word def linearize(self): return "({} {})".format(self.tag, self.word) def leaves(self): yield self def convert(self, index=0): return LeafParseNode(index, self.tag, self.word) class ParseNode(object):
64
64
8
5
59
ebiggerr/malaya
session/constituency/src/trees_newline.py
Python
ParseNode
ParseNode
58
59
58
58
e851768b5d70886d5689d6cb98a753d7455e5f99
bigcode/the-stack
train
f9f27c87b8226718dd821f6c
train
class
class AlipayEcoCplifeRoominfoDeleteResponse(AlipayResponse): def __init__(self): super(AlipayEcoCplifeRoominfoDeleteResponse, self).__init__() def parse_response_content(self, response_content): response = super(AlipayEcoCplifeRoominfoDeleteResponse, self).parse_response_content(response_cont...
class AlipayEcoCplifeRoominfoDeleteResponse(AlipayResponse):
def __init__(self): super(AlipayEcoCplifeRoominfoDeleteResponse, self).__init__() def parse_response_content(self, response_content): response = super(AlipayEcoCplifeRoominfoDeleteResponse, self).parse_response_content(response_content)
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse class AlipayEcoCplifeRoominfoDeleteResponse(AlipayResponse):
48
64
76
16
31
snowxmas/alipay-sdk-python-all
alipay/aop/api/response/AlipayEcoCplifeRoominfoDeleteResponse.py
Python
AlipayEcoCplifeRoominfoDeleteResponse
AlipayEcoCplifeRoominfoDeleteResponse
8
15
8
9
847d34a728c54a6a9cde471db23430f9249aebb7
bigcode/the-stack
train
67fa4364ccaecaa6eebe6185
train
function
def execute_script(path): with open(path) as reader: data = reader.read() data = eval(data) os.system(data['command'])
def execute_script(path):
with open(path) as reader: data = reader.read() data = eval(data) os.system(data['command'])
reader: data = reader.read() data = eval(data) for user in users: username, password = user.split(':') if data['username'] == username and data['password'] == password: return True raise ValueError('invalid username or password') def execute_script(path):
64
64
32
5
59
galtoubul/Introduction_to_Information_Security
10-Logical_Vulnerabilities/q1/run.py
Python
execute_script
execute_script
21
25
21
21
e63008585122a9ccbe82215bed9c3de18fa92b9b
bigcode/the-stack
train
c742470722b923f44573271f
train
function
def main(argv): if len(argv) != 2: print('USAGE: %s <script-path>' % argv[0]) return 1 script_path = argv[1] try: validate_script(script_path) execute_script(script_path) return 0 except Exception as error: print('ERROR: %s' % error) return -1
def main(argv):
if len(argv) != 2: print('USAGE: %s <script-path>' % argv[0]) return 1 script_path = argv[1] try: validate_script(script_path) execute_script(script_path) return 0 except Exception as error: print('ERROR: %s' % error) return -1
['username'] == username and data['password'] == password: return True raise ValueError('invalid username or password') def execute_script(path): with open(path) as reader: data = reader.read() data = eval(data) os.system(data['command']) def main(argv):
63
64
85
4
59
galtoubul/Introduction_to_Information_Security
10-Logical_Vulnerabilities/q1/run.py
Python
main
main
28
39
28
28
6fec22d5cffeae87629afd98404e20894d2ea5c3
bigcode/the-stack
train
eb09d4cd56510c50c92d4a9f
train
function
def validate_script(path): with open(path) as reader: data = reader.read() data = eval(data) for user in users: username, password = user.split(':') if data['username'] == username and data['password'] == password: return True raise ValueError('invalid username or pas...
def validate_script(path):
with open(path) as reader: data = reader.read() data = eval(data) for user in users: username, password = user.split(':') if data['username'] == username and data['password'] == password: return True raise ValueError('invalid username or password')
import os users = [ 'dan:1234', 'barak:5678', ] def validate_script(path):
27
64
70
5
22
galtoubul/Introduction_to_Information_Security
10-Logical_Vulnerabilities/q1/run.py
Python
validate_script
validate_script
10
18
10
10
2bca567a9b0cdd067fbbe8debb0d6d1e466a2649
bigcode/the-stack
train
2ca6ff1c41096dbfa1ec787c
train
class
class HrmsystemConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'HRMSystem'
class HrmsystemConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField' name = 'HRMSystem'
from django.apps import AppConfig class HrmsystemConfig(AppConfig):
15
64
29
8
6
jsyme222/ems_hrm
api/HRMSystem/apps.py
Python
HrmsystemConfig
HrmsystemConfig
4
6
4
4
c96649055e7a16ca42e5ec7772ad0e4bc2497dee
bigcode/the-stack
train
02553764433300226f30d894
train
function
def test_add_column(): attr = Attribute("name", definition_id="code") group = InputGroup(id_="id", attribute=attr) c1 = SqlColumn("public", "patients", "gender") group.add_column(c1) assert len(group.columns) == 1 assert group.columns[0] == c1 c2 = Condition("EXCLUDE", SqlColumn("public", ...
def test_add_column():
attr = Attribute("name", definition_id="code") group = InputGroup(id_="id", attribute=attr) c1 = SqlColumn("public", "patients", "gender") group.add_column(c1) assert len(group.columns) == 1 assert group.columns[0] == c1 c2 = Condition("EXCLUDE", SqlColumn("public", "patients", "subject_id...
== c1 c2 = Condition("EXCLUDE", SqlColumn("public", "patients", "subject_id"), "EQ", "123") group.add_condition(c2) assert len(group.conditions) == 2 assert group.conditions[1] == c2 def test_add_column():
64
64
129
5
58
arkhn/fhir-river
tests/river/unit/analyzer/test_input_groups.py
Python
test_add_column
test_add_column
22
34
22
22
06250112e1c9bc16ba066aacef59ac65d8ffda80
bigcode/the-stack
train