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
a1ae39cd409a29ca99529597
train
function
def _get_fuzz_targets(project_name): """Return names of fuzz targest build in the project's /out directory.""" fuzz_targets = [] for name in os.listdir(_get_output_dir(project_name)): if name.startswith('afl-'): continue path = os.path.join(_get_output_dir(project_name), name) if os.path.isfile...
def _get_fuzz_targets(project_name):
"""Return names of fuzz targest build in the project's /out directory.""" fuzz_targets = [] for name in os.listdir(_get_output_dir(project_name)): if name.startswith('afl-'): continue path = os.path.join(_get_output_dir(project_name), name) if os.path.isfile(path) and os.access(path, os.X_OK): ...
args.fuzzer_name)] else: run_args.append('test_all') exit_code = docker_run(run_args) if exit_code == 0: print('Check build passed.') else: print('Check build failed.') return exit_code def _get_fuzz_targets(project_name):
64
64
97
9
54
devtty1er/oss-fuzz
infra/helper.py
Python
_get_fuzz_targets
_get_fuzz_targets
620
631
620
620
fb81aaee9ac13f476ee83a0750dd8961ddc68330
bigcode/the-stack
train
b3ee341ee37025b3face0e58
train
function
def _env_to_docker_args(env_list): """Turn envirnoment variable list into docker arguments.""" return sum([['-e', v] for v in env_list], [])
def _env_to_docker_args(env_list):
"""Turn envirnoment variable list into docker arguments.""" return sum([['-e', v] for v in env_list], [])
no_cache: build_args.append('--no-cache') build_args += [ '-t', 'gcr.io/%s/%s' % (image_project, image_name), dockerfile_dir ] return docker_build(build_args, pull=pull) def _env_to_docker_args(env_list):
64
64
40
10
54
devtty1er/oss-fuzz
infra/helper.py
Python
_env_to_docker_args
_env_to_docker_args
358
360
358
358
a1eaa878368e20e8f4c0ce494ff332a88d961663
bigcode/the-stack
train
03ac15a5f3c9a62d27fd610c
train
function
def workdir_from_lines(lines, default='/src'): """Get the WORKDIR from the given lines.""" for line in reversed(lines): # reversed to get last WORKDIR. match = re.match(WORKDIR_REGEX, line) if match: workdir = match.group(1) workdir = workdir.replace('$SRC', '/src') if not os.path.isabs(...
def workdir_from_lines(lines, default='/src'):
"""Get the WORKDIR from the given lines.""" for line in reversed(lines): # reversed to get last WORKDIR. match = re.match(WORKDIR_REGEX, line) if match: workdir = match.group(1) workdir = workdir.replace('$SRC', '/src') if not os.path.isabs(workdir): workdir = os.path.join('/src'...
_list): """Turn envirnoment variable list into docker arguments.""" return sum([['-e', v] for v in env_list], []) WORKDIR_REGEX = re.compile(r'\s*WORKDIR\s*([^\s]+)') def workdir_from_lines(lines, default='/src'):
63
64
112
11
53
devtty1er/oss-fuzz
infra/helper.py
Python
workdir_from_lines
workdir_from_lines
366
379
366
366
a7e9d7c4969ca14703b8c1ae250844d1ef1c8af6
bigcode/the-stack
train
2f6e99c88df02d4862102216
train
function
def pull_images(_): """Pull base images.""" for base_image in BASE_IMAGES: if not docker_pull(base_image): return 1 return 0
def pull_images(_):
"""Pull base images.""" for base_image in BASE_IMAGES: if not docker_pull(base_image): return 1 return 0
_dir, '-v', '%s:/work' % _get_work_dir(args.project_name), '-t', 'gcr.io/%s/%s' % (image_project, args.project_name), '/bin/bash' ]) docker_run(run_args) return 0 def pull_images(_):
64
64
37
5
58
devtty1er/oss-fuzz
infra/helper.py
Python
pull_images
pull_images
938
944
938
938
39d0febfcdd9cbb01486445ae0e92a734e4f0e1e
bigcode/the-stack
train
39f3fb942dd7660109a733e1
train
function
def _get_absolute_path(path): """Returns absolute path with user expansion.""" return os.path.abspath(os.path.expanduser(path))
def _get_absolute_path(path):
"""Returns absolute path with user expansion.""" return os.path.abspath(os.path.expanduser(path))
% fuzzer_name]) try: subprocess.check_call(command) except subprocess.CalledProcessError: print(fuzzer_name, 'does not seem to exist. Please run build_fuzzers first.', file=sys.stderr) return False return True def _get_absolute_path(path):
64
64
27
7
56
devtty1er/oss-fuzz
infra/helper.py
Python
_get_absolute_path
_get_absolute_path
254
256
254
254
8217e51596c7a3c062b58d8da13f89dcf6884e44
bigcode/the-stack
train
cd51302c61211df68fc839a5
train
function
def _get_corpus_dir(project_name=''): """Returns path to /corpus directory for the given project (if specified).""" return os.path.join(BUILD_DIR, 'corpus', project_name)
def _get_corpus_dir(project_name=''):
"""Returns path to /corpus directory for the given project (if specified).""" return os.path.join(BUILD_DIR, 'corpus', project_name)
.""" return os.path.join(OSS_FUZZ_DIR, 'projects', project_name) def get_dockerfile_path(project_name): """Returns path to the project Dockerfile.""" return os.path.join(_get_project_dir(project_name), 'Dockerfile') def _get_corpus_dir(project_name=''):
64
64
44
10
54
devtty1er/oss-fuzz
infra/helper.py
Python
_get_corpus_dir
_get_corpus_dir
274
276
274
274
4a27949d90ee3428203b7820e43c545eb8ec7c6a
bigcode/the-stack
train
5c9a39836fa7b476b24fb72a
train
function
def _add_engine_args(parser, choices=('libfuzzer', 'afl', 'honggfuzz', 'dataflow', 'none')): """Add common engine args.""" parser.add_argument('--engine', default='libfuzzer', choices=choices)
def _add_engine_args(parser, choices=('libfuzzer', 'afl', 'honggfuzz', 'dataflow', 'none')):
"""Add common engine args.""" parser.add_argument('--engine', default='libfuzzer', choices=choices)
86_64', 'i386')): """Add common architecture args.""" parser.add_argument('--architecture', default='x86_64', choices=choices) def _add_engine_args(parser, choices=('libfuzzer', 'afl', 'honggfuzz', 'dataflow', 'none')):
64
64
55
31
33
devtty1er/oss-fuzz
infra/helper.py
Python
_add_engine_args
_add_engine_args
308
312
308
310
b694ff2193eacb508ec878ab22fe80414639901b
bigcode/the-stack
train
43bc1d3f4fe4cfa4fe40dea0
train
function
def coverage(args): """Generate code coverage using clang source based code coverage.""" if args.corpus_dir and not args.fuzz_target: print( 'ERROR: --corpus-dir requires specifying a particular fuzz target ' 'using --fuzz-target', file=sys.stderr) return 1 if not check_project_ex...
def coverage(args):
"""Generate code coverage using clang source based code coverage.""" if args.corpus_dir and not args.fuzz_target: print( 'ERROR: --corpus-dir requires specifying a particular fuzz target ' 'using --fuzz-target', file=sys.stderr) return 1 if not check_project_exists(args.project_na...
_target(fuzz_target): try: _get_latest_corpus(args.project_name, fuzz_target, corpus_dir) return True except Exception as error: # pylint:disable=broad-except print('ERROR: corpus download for %s failed: %s' % (fuzz_target, str(error)), file=sys.stderr) return Fa...
132
132
442
4
128
devtty1er/oss-fuzz
infra/helper.py
Python
coverage
coverage
715
774
715
715
b434f075124f2920590e3c0729c37e507a091006
bigcode/the-stack
train
3191dae59da2d416a80ca844
train
function
def _get_work_dir(project_name=''): """Returns path to /work directory for the given project (if specified).""" return os.path.join(BUILD_DIR, 'work', project_name)
def _get_work_dir(project_name=''):
"""Returns path to /work directory for the given project (if specified).""" return os.path.join(BUILD_DIR, 'work', project_name)
os.path.join(BUILD_DIR, 'corpus', project_name) def _get_output_dir(project_name=''): """Returns path to /out directory for the given project (if specified).""" return os.path.join(BUILD_DIR, 'out', project_name) def _get_work_dir(project_name=''):
64
64
41
9
55
devtty1er/oss-fuzz
infra/helper.py
Python
_get_work_dir
_get_work_dir
284
286
284
284
336cbe887be40718a0f98903edb4c67e2b394ea6
bigcode/the-stack
train
67e5ead669fc3683eaa100e7
train
function
def check_build(args): """Checks that fuzzers in the container execute without errors.""" if not check_project_exists(args.project_name): return 1 if (args.fuzzer_name and not _check_fuzzer_exists(args.project_name, args.fuzzer_name)): return 1 env = [ 'FUZZING_ENGINE=' + args.engine, ...
def check_build(args):
"""Checks that fuzzers in the container execute without errors.""" if not check_project_exists(args.project_name): return 1 if (args.fuzzer_name and not _check_fuzzer_exists(args.project_name, args.fuzzer_name)): return 1 env = [ 'FUZZING_ENGINE=' + args.engine, 'SANITIZER=' + args.s...
-base/base-msan-builder', 'patch_build.py', '/out']) return 0 def build_fuzzers(args): """Build fuzzers.""" return build_fuzzers_impl(args.project_name, args.clean, args.engine, args.sanitizer, args.architecture, args.e, args.source_path) def check_build(...
72
72
243
5
67
devtty1er/oss-fuzz
infra/helper.py
Python
check_build
check_build
583
617
583
583
93e06e8648ec02da307c4a0dc35bdd6ff344b6e2
bigcode/the-stack
train
b2259e6f9b7c3781752845f4
train
function
def build_image(args): """Build docker image.""" if args.pull and args.no_pull: print('Incompatible arguments --pull and --no-pull.') return 1 if args.pull: pull = True elif args.no_pull: pull = False else: y_or_n = raw_input('Pull latest base images (compiler/runtime)? (y/N): ') pull...
def build_image(args):
"""Build docker image.""" if args.pull and args.no_pull: print('Incompatible arguments --pull and --no-pull.') return 1 if args.pull: pull = True elif args.no_pull: pull = False else: y_or_n = raw_input('Pull latest base images (compiler/runtime)? (y/N): ') pull = y_or_n.lower() == 'y...
.""" command = ['docker', 'pull', image] print('Running:', _get_command_string(command)) try: subprocess.check_call(command) except subprocess.CalledProcessError: print('docker pull failed.', file=sys.stderr) return False return True def build_image(args):
64
64
161
5
58
devtty1er/oss-fuzz
infra/helper.py
Python
build_image
build_image
447
470
447
447
5a900ebefb8c6b133a1ed0a6b4dd7d1aac276ad7
bigcode/the-stack
train
3cc531f0f80140b6b714a33e
train
function
def _add_environment_args(parser): """Add common environment args.""" parser.add_argument('-e', action='append', help="set environment variable e.g. VAR=value")
def _add_environment_args(parser):
"""Add common environment args.""" parser.add_argument('-e', action='append', help="set environment variable e.g. VAR=value")
undefined', 'coverage', 'dataflow')): """Add common sanitizer args.""" parser.add_argument( '--sanitizer', default=None, choices=choices, help='the default is "address"; "dataflow" for "dataflow" engine') def _add_environment_args(parser):
64
64
38
7
57
devtty1er/oss-fuzz
infra/helper.py
Python
_add_environment_args
_add_environment_args
326
330
326
326
6bce552ff76667dd28c1324f75ddc3f34c0326c5
bigcode/the-stack
train
5fdcc63270500818bf9624a7
train
function
def _add_sanitizer_args(parser, choices=('address', 'memory', 'undefined', 'coverage', 'dataflow')): """Add common sanitizer args.""" parser.add_argument( '--sanitizer', default=None, choices=choices, help='the default is "address"; "d...
def _add_sanitizer_args(parser, choices=('address', 'memory', 'undefined', 'coverage', 'dataflow')):
"""Add common sanitizer args.""" parser.add_argument( '--sanitizer', default=None, choices=choices, help='the default is "address"; "dataflow" for "dataflow" engine')
honggfuzz', 'dataflow', 'none')): """Add common engine args.""" parser.add_argument('--engine', default='libfuzzer', choices=choices) def _add_sanitizer_args(parser, choices=('address', 'memory', 'undefined', 'coverage', 'dataflo...
64
64
75
28
36
devtty1er/oss-fuzz
infra/helper.py
Python
_add_sanitizer_args
_add_sanitizer_args
315
323
315
317
455138526fab30ae909bd278ddb1e50ffe8498cf
bigcode/the-stack
train
e70a1421af8ec8a8ac572aaf
train
class
class Migration(migrations.Migration): dependencies = [ ('push_notifications', '0003_auto_20191114_0024'), ] operations = [ migrations.AddField( model_name='pushnotificationtoken', name='api_key', field=common.models.RequiredCharField(default='omitted', ...
class Migration(migrations.Migration):
dependencies = [ ('push_notifications', '0003_auto_20191114_0024'), ] operations = [ migrations.AddField( model_name='pushnotificationtoken', name='api_key', field=common.models.RequiredCharField(default='omitted', max_length=50, validators=[push_notifica...
# Generated by Django 3.0.4 on 2020-04-21 17:59 import common.models from django.db import migrations import push_notifications.validation class Migration(migrations.Migration):
45
64
84
7
37
pg-irc/pathways-backend
push_notifications/migrations/0004_pushnotificationtoken_api_key.py
Python
Migration
Migration
8
20
8
9
ba183bc526e61259bb467a853491c02a10778784
bigcode/the-stack
train
6bf55f145a5647a41a91e0f6
train
class
class Migration(migrations.Migration): dependencies = [ ('playground', '0011_temporaryimage'), ] operations = [ migrations.AddField( model_name='image', name='user_id', field=models.CharField(default=3, max_length=100), preserve_default=False...
class Migration(migrations.Migration):
dependencies = [ ('playground', '0011_temporaryimage'), ] operations = [ migrations.AddField( model_name='image', name='user_id', field=models.CharField(default=3, max_length=100), preserve_default=False, ), ]
# Generated by Django 3.2.5 on 2021-07-20 19:51 from django.db import migrations, models class Migration(migrations.Migration):
38
64
69
7
30
malithbc/Mole-AR-Stage1
src/playground/migrations/0012_image_user_id.py
Python
Migration
Migration
6
19
6
7
6add5a68235240acbf4511c4167de67687f41f5c
bigcode/the-stack
train
d9ae5d7a3b02ef68fb6d8f03
train
function
def loadimgs(path, n=0): # if data not already unzipped, unzip it. if not os.path.exists(path): print("unzipping") os.chdir(data_path) os.system("unzip {}".format(path+".zip")) X = [] y = [] cat_dict = {} lang_dict = {} curr_y = n # we load every alphabet seperate...
def loadimgs(path, n=0): # if data not already unzipped, unzip it.
if not os.path.exists(path): print("unzipping") os.chdir(data_path) os.system("unzip {}".format(path+".zip")) X = [] y = [] cat_dict = {} lang_dict = {} curr_y = n # we load every alphabet seperately so we can isolate them later for alphabet in os.listdir(path): ...
plt """Script to preprocess the omniglot dataset and pickle it into an array that's easy to index my character type""" data_path = os.path.join('data/') train_folder = os.path.join(data_path, 'images_background') valpath = os.path.join(data_path, 'images_evaluation') save_path = 'data/' lang_dict = {} def load...
96
96
322
22
74
rahulgurnani/Siamese-Networks
load_data.py
Python
loadimgs
loadimgs
19
55
19
20
a3568d5b2d91a86e8c835cdfdb6282817c869514
bigcode/the-stack
train
80c471b0f20e59a56396ac23
train
function
def get_segmentation_names(seg_folder, patient_names_file): with open(patient_names_file) as f: content = f.readlines() patient_names = [x.strip() for x in content] full_seg_names = [] for patient_name in patient_names: seg_name = os.path.join(seg_folder, patient_name + '.nii...
def get_segmentation_names(seg_folder, patient_names_file):
with open(patient_names_file) as f: content = f.readlines() patient_names = [x.strip() for x in content] full_seg_names = [] for patient_name in patient_names: seg_name = os.path.join(seg_folder, patient_name + '.nii.gz') full_seg_names.append(seg_name) return ful...
break else: if 'seg.' in img_name: gt_name = img_name break gt_name = os.path.join(patient_dir, gt_name) full_gt_names.append(gt_name) return full_gt_names def get_segmentation_names(seg_folder, patient_names_fil...
64
64
86
12
51
MohamedHeshamMustafa/Brain-Tumor-Automatic-Detection-and-Segmentation-
util/evaluation.py
Python
get_segmentation_names
get_segmentation_names
41
49
41
41
4086095930c9c841a8d1940312dcf7013aef653e
bigcode/the-stack
train
2e268dcdf7196f2113749079
train
function
def dice_of_brats_data_set(gt_names, seg_names, type_idx): assert(len(gt_names) == len(seg_names)) dice_all_data = [] for i in range(len(gt_names)): g_volume = load_3d_volume_as_array(gt_names[i]) s_volume = load_3d_volume_as_array(seg_names[i]) dice_one_volume = [] if(type_i...
def dice_of_brats_data_set(gt_names, seg_names, type_idx):
assert(len(gt_names) == len(seg_names)) dice_all_data = [] for i in range(len(gt_names)): g_volume = load_3d_volume_as_array(gt_names[i]) s_volume = load_3d_volume_as_array(seg_names[i]) dice_one_volume = [] if(type_idx ==0): # whole tumor temp_dice = binary_dice3...
= f.readlines() patient_names = [x.strip() for x in content] full_seg_names = [] for patient_name in patient_names: seg_name = os.path.join(seg_folder, patient_name + '.nii.gz') full_seg_names.append(seg_name) return full_seg_names def dice_of_brats_data_set(gt_names, seg_names,...
78
78
261
16
61
MohamedHeshamMustafa/Brain-Tumor-Automatic-Detection-and-Segmentation-
util/evaluation.py
Python
dice_of_brats_data_set
dice_of_brats_data_set
51
71
51
51
ccf79e483e55256b413a0d84a9a668239bb6da74
bigcode/the-stack
train
3122b1cd3ac999fb01386c9a
train
function
def get_ground_truth_names(g_folder, patient_names_file, year = 15): assert(year==15 or year == 17) with open(patient_names_file) as f: content = f.readlines() patient_names = [x.strip() for x in content] full_gt_names = [] for patient_name in patient_names: patient_dir =...
def get_ground_truth_names(g_folder, patient_names_file, year = 15):
assert(year==15 or year == 17) with open(patient_names_file) as f: content = f.readlines() patient_names = [x.strip() for x in content] full_gt_names = [] for patient_name in patient_names: patient_dir = os.path.join(g_folder, patient_name) img_names = os.listdi...
# from __future__ import absolute_import, print_function import os import sys sys.path.append('./') import numpy as np from util.data_process import load_3d_volume_as_array, binary_dice3d def get_ground_truth_names(g_folder, patient_names_file, year = 15):
64
64
192
17
46
MohamedHeshamMustafa/Brain-Tumor-Automatic-Detection-and-Segmentation-
util/evaluation.py
Python
get_ground_truth_names
get_ground_truth_names
18
39
18
18
35f676f1e95ec504bc5570cfb5f8017aee496d51
bigcode/the-stack
train
0b43fc9a9ff93f5e76021d3c
train
function
def generate_fake_batch( batch_size: int, channels=83, bins=1024, ) -> List[Tuple[tf.Tensor, Tuple[tf.Tensor, tf.Tensor]]]: example_batch = [] for _ in range(batch_size): input_example, ( target_phons_example, target_mask_example) = generate_fake_example( channels=channels, bins=bins) ...
def generate_fake_batch( batch_size: int, channels=83, bins=1024, ) -> List[Tuple[tf.Tensor, Tuple[tf.Tensor, tf.Tensor]]]:
example_batch = [] for _ in range(batch_size): input_example, ( target_phons_example, target_mask_example) = generate_fake_example( channels=channels, bins=bins) input_example = tf.expand_dims(input_example, axis=0) target_phons_example = tf.expand_dims(target_phons_example, axis=0) ...
val=1, dtype=tf.float32) return (example_input, (example_target_phons, example_target_mask)) def generate_fake_batch( batch_size: int, channels=83, bins=1024, ) -> List[Tuple[tf.Tensor, Tuple[tf.Tensor, tf.Tensor]]]:
64
64
153
38
26
Xtuden-com/korvapuusti
listening_test_summer_2020/modelling/end_to_end_model/neural_model/test_helpers.py
Python
generate_fake_batch
generate_fake_batch
21
35
21
23
e7d3f76e3e82b642badd8c545f4a74f49c3606dc
bigcode/the-stack
train
d2a604c3be134f3de1358fdb
train
function
def generate_fake_example(bins=1024, channels=83 ) -> Tuple[tf.Tensor, Tuple[tf.Tensor, tf.Tensor]]: example_input = tf.random.uniform(shape=[channels, bins, 2], dtype=tf.float32) example_target_phons = tf.random.uniform(shape=[b...
def generate_fake_example(bins=1024, channels=83 ) -> Tuple[tf.Tensor, Tuple[tf.Tensor, tf.Tensor]]:
example_input = tf.random.uniform(shape=[channels, bins, 2], dtype=tf.float32) example_target_phons = tf.random.uniform(shape=[bins, 1], dtype=tf.float32) example_target_mask = tf.random.uniform(shape=[bins, 1], ...
# Lint as: python3 """Helper functions for testing""" from typing import Tuple, List import tensorflow.compat.v2 as tf def generate_fake_example(bins=1024, channels=83 ) -> Tuple[tf.Tensor, Tuple[tf.Tensor, tf.Tensor]]:
60
64
123
31
28
Xtuden-com/korvapuusti
listening_test_summer_2020/modelling/end_to_end_model/neural_model/test_helpers.py
Python
generate_fake_example
generate_fake_example
8
18
8
10
f4c84fe61c71fadd20f9166e24b7437a38e33d48
bigcode/the-stack
train
78f3778ad351e9164ba0b869
train
class
class Module_six_moves_urllib_request(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_request"""
class Module_six_moves_urllib_request(_LazyModule):
"""Lazy loading of moved objects in six.moves.urllib_request"""
_error._moved_attributes = _urllib_error_moved_attributes _importer._add_module( Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"), "moves.urllib_error", "moves.urllib.error", ) class Module_six_moves_urllib_request(_LazyModule):
64
64
26
12
52
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
Python
Module_six_moves_urllib_request
Module_six_moves_urllib_request
399
401
399
400
b17a17c77d9996158f3c5e31303756fdeb42b6e8
bigcode/the-stack
train
903e859d625006b8f8af186d
train
function
def ensure_text(s, encoding="utf-8", errors="strict"): """Coerce *s* to six.text_type. For Python 2: - `unicode` -> `unicode` - `str` -> `unicode` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str` """ if isinstance(s, binary_type): return s.decode(encodin...
def ensure_text(s, encoding="utf-8", errors="strict"):
"""Coerce *s* to six.text_type. For Python 2: - `unicode` -> `unicode` - `str` -> `unicode` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str` """ if isinstance(s, binary_type): return s.decode(encoding, errors) elif isinstance(s, text_type): r...
type(s)) if PY2 and isinstance(s, text_type): s = s.encode(encoding, errors) elif PY3 and isinstance(s, binary_type): s = s.decode(encoding, errors) return s def ensure_text(s, encoding="utf-8", errors="strict"):
64
64
126
15
48
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
Python
ensure_text
ensure_text
964
980
964
964
2136b8e4fafefd7e80174063ec8bfa40de7fd9ee
bigcode/the-stack
train
c9335d3a39378b6a5be9f503
train
class
class _SixMetaPathImporter(object): """ A meta path importer to import six.moves and its submodules. This class implements a PEP302 finder and loader. It should be compatible with Python 2.5 and all existing versions of Python3 """ def __init__(self, six_module_name): self.name = six_...
class _SixMetaPathImporter(object):
""" A meta path importer to import six.moves and its submodules. This class implements a PEP302 finder and loader. It should be compatible with Python 2.5 and all existing versions of Python3 """ def __init__(self, six_module_name): self.name = six_module_name self.known_module...
if PY3: if new_mod is None: new_mod = name self.mod = new_mod if new_attr is None: if old_attr is None: new_attr = name else: new_attr = old_attr self.attr = new_attr e...
123
123
410
8
115
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
Python
_SixMetaPathImporter
_SixMetaPathImporter
165
226
165
166
8fce6e7f8d8671b123eda2d91474ca150dac52f9
bigcode/the-stack
train
0ae792d5f245dbfc7ada97b5
train
class
class Module_six_moves_urllib_robotparser(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_robotparser"""
class Module_six_moves_urllib_robotparser(_LazyModule):
"""Lazy loading of moved objects in six.moves.urllib_robotparser"""
._moved_attributes = _urllib_response_moved_attributes _importer._add_module( Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"), "moves.urllib_response", "moves.urllib.response", ) class Module_six_moves_urllib_robotparser(_LazyModule):
64
64
28
13
51
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
Python
Module_six_moves_urllib_robotparser
Module_six_moves_urllib_robotparser
478
480
478
479
6f7bf67bb4c1db331acc4f2957a61378ac0299e3
bigcode/the-stack
train
0e98e52bb529fbabfcc809ca
train
class
class _LazyDescr(object): def __init__(self, name): self.name = name def __get__(self, obj, tp): result = self._resolve() setattr(obj, self.name, result) # Invokes __set__. try: # This is a bit ugly, but it avoids running this again by # removing this de...
class _LazyDescr(object):
def __init__(self, name): self.name = name def __get__(self, obj, tp): result = self._resolve() setattr(obj, self.name, result) # Invokes __set__. try: # This is a bit ugly, but it avoids running this again by # removing this descriptor. dela...
del X def _add_doc(func, doc): """Add documentation to a function.""" func.__doc__ = doc def _import_module(name): """Import module, returning the module after the last dot.""" __import__(name) return sys.modules[name] class _LazyDescr(object):
64
64
103
6
58
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
Python
_LazyDescr
_LazyDescr
91
104
91
91
1c7aa2c96363f9a8e38f5585d5616979e546e924
bigcode/the-stack
train
df9e98009ee63a8e47d19096
train
class
class Module_six_moves_urllib_response(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_response"""
class Module_six_moves_urllib_response(_LazyModule):
"""Lazy loading of moved objects in six.moves.urllib_response"""
_request._moved_attributes = _urllib_request_moved_attributes _importer._add_module( Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"), "moves.urllib_request", "moves.urllib.request", ) class Module_six_moves_urllib_response(_LazyModule):
64
64
26
12
52
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
Python
Module_six_moves_urllib_response
Module_six_moves_urllib_response
454
456
454
455
e8864c1d3767fc0ed99295044f5ecd06628a7ff1
bigcode/the-stack
train
7b35902f68453b027bb2ea35
train
function
def ensure_str(s, encoding="utf-8", errors="strict"): """Coerce *s* to `str`. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str` """ if not isinstance(s, (text_type, binary_type)): raise TypeEr...
def ensure_str(s, encoding="utf-8", errors="strict"):
"""Coerce *s* to `str`. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str` """ if not isinstance(s, (text_type, binary_type)): raise TypeError("not expecting type '%s'" % type(s)) if PY2 an...
""" if isinstance(s, text_type): return s.encode(encoding, errors) elif isinstance(s, binary_type): return s else: raise TypeError("not expecting type '%s'" % type(s)) def ensure_str(s, encoding="utf-8", errors="strict"):
64
64
154
15
49
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
Python
ensure_str
ensure_str
944
961
944
944
47c62edf5ed5ced7a97856d54d9928a6424b9257
bigcode/the-stack
train
bd5b8a9613c5205c1e066287
train
function
def add_move(move): """Add an item to six.moves.""" setattr(_MovedItems, move.name, move)
def add_move(move):
"""Add an item to six.moves.""" setattr(_MovedItems, move.name, move)
.urllib_robotparser") def __dir__(self): return ["parse", "error", "request", "response", "robotparser"] _importer._add_module( Module_six_moves_urllib(__name__ + ".moves.urllib"), "moves.urllib" ) def add_move(move):
64
64
25
5
59
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
Python
add_move
add_move
521
523
521
521
986b5b8038a88bf6bb306b00d3c53d16dde881f1
bigcode/the-stack
train
838a27d5ee9e6313b6270deb
train
function
def assertRegex(self, *args, **kwargs): return getattr(self, _assertRegex)(*args, **kwargs)
def assertRegex(self, *args, **kwargs):
return getattr(self, _assertRegex)(*args, **kwargs)
Equal(self, *args, **kwargs): return getattr(self, _assertCountEqual)(*args, **kwargs) def assertRaisesRegex(self, *args, **kwargs): return getattr(self, _assertRaisesRegex)(*args, **kwargs) def assertRegex(self, *args, **kwargs):
64
64
26
11
53
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
Python
assertRegex
assertRegex
727
728
727
727
610b6125c41b1d9a9a1cd6fe8e40a9afaa9673fd
bigcode/the-stack
train
eb7305e335169287e7a80182
train
function
def assertRaisesRegex(self, *args, **kwargs): return getattr(self, _assertRaisesRegex)(*args, **kwargs)
def assertRaisesRegex(self, *args, **kwargs):
return getattr(self, _assertRaisesRegex)(*args, **kwargs)
= "assertRegexpMatches" _add_doc(b, """Byte literal""") _add_doc(u, """Text literal""") def assertCountEqual(self, *args, **kwargs): return getattr(self, _assertCountEqual)(*args, **kwargs) def assertRaisesRegex(self, *args, **kwargs):
64
64
28
12
52
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
Python
assertRaisesRegex
assertRaisesRegex
723
724
723
723
5c8ca5469ba672b723941982c31534e1ccc41dbb
bigcode/the-stack
train
0c3a51fd0aa9ecb90b126b41
train
class
class MovedAttribute(_LazyDescr): def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None): super(MovedAttribute, self).__init__(name) if PY3: if new_mod is None: new_mod = name self.mod = new_mod if new_attr is None: ...
class MovedAttribute(_LazyDescr):
def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None): super(MovedAttribute, self).__init__(name) if PY3: if new_mod is None: new_mod = name self.mod = new_mod if new_attr is None: if old_attr is None: ...
__.__doc__ def __dir__(self): attrs = ["__doc__", "__name__"] attrs += [attr.name for attr in self._moved_attributes] return attrs # Subclasses should override this _moved_attributes = [] class MovedAttribute(_LazyDescr):
63
64
158
8
55
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
Python
MovedAttribute
MovedAttribute
141
162
141
141
ebb57c4dbce2d82ca596a9d5ee3de60c38125a0c
bigcode/the-stack
train
d24e8dcf339be2cdc8579525
train
class
class MovedModule(_LazyDescr): def __init__(self, name, old, new=None): super(MovedModule, self).__init__(name) if PY3: if new is None: new = name self.mod = new else: self.mod = old def _resolve(self): return _import_module(se...
class MovedModule(_LazyDescr):
def __init__(self, name, old, new=None): super(MovedModule, self).__init__(name) if PY3: if new is None: new = name self.mod = new else: self.mod = old def _resolve(self): return _import_module(self.mod) def __getattr__(se...
) # Invokes __set__. try: # This is a bit ugly, but it avoids running this again by # removing this descriptor. delattr(obj.__class__, self.name) except AttributeError: pass return result class MovedModule(_LazyDescr):
64
64
118
8
55
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
Python
MovedModule
MovedModule
107
124
107
107
38b3453284e3b4bd66a08b89cf8ab084157a5e3e
bigcode/the-stack
train
52c59c2ee045081efc58fa09
train
function
def ensure_binary(s, encoding="utf-8", errors="strict"): """Coerce **s** to six.binary_type. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> encoded to `bytes` - `bytes` -> `bytes` """ if isinstance(s, text_type): return s.enc...
def ensure_binary(s, encoding="utf-8", errors="strict"):
"""Coerce **s** to six.binary_type. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> encoded to `bytes` - `bytes` -> `bytes` """ if isinstance(s, text_type): return s.encode(encoding, errors) elif isinstance(s, binary_type)...
weakref__", None) if hasattr(cls, "__qualname__"): orig_vars["__qualname__"] = cls.__qualname__ return metaclass(cls.__name__, cls.__bases__, orig_vars) return wrapper def ensure_binary(s, encoding="utf-8", errors="strict"):
64
64
128
15
48
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
Python
ensure_binary
ensure_binary
925
941
925
925
a542b0bc983139dde3d51f14cebe46f0a1408302
bigcode/the-stack
train
39427e09dfd55fc72c7c204e
train
function
def python_2_unicode_compatible(klass): """ A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class. """ if PY2: ...
def python_2_unicode_compatible(klass):
""" A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class. """ if PY2: if "__str__" not in klass.__dict_...
decoded to `str` """ if isinstance(s, binary_type): return s.decode(encoding, errors) elif isinstance(s, text_type): return s else: raise TypeError("not expecting type '%s'" % type(s)) def python_2_unicode_compatible(klass):
64
64
164
10
54
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
Python
python_2_unicode_compatible
python_2_unicode_compatible
983
999
983
983
63206b705e253b5cff3a77a9ae742ba1fa856bf3
bigcode/the-stack
train
c8d052b4f89bf310a7568f5b
train
function
def _add_doc(func, doc): """Add documentation to a function.""" func.__doc__ = doc
def _add_doc(func, doc):
"""Add documentation to a function.""" func.__doc__ = doc
(X()) except OverflowError: # 32-bit MAXSIZE = int((1 << 31) - 1) else: # 64-bit MAXSIZE = int((1 << 63) - 1) del X def _add_doc(func, doc):
64
64
24
8
55
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
Python
_add_doc
_add_doc
80
82
80
80
10af6525f55dbf28b7cb4a4e4dbcf766d06f5d9f
bigcode/the-stack
train
5632f7ac38ad3183a9fe7d6d
train
function
def remove_move(name): """Remove item from six.moves.""" try: delattr(_MovedItems, name) except AttributeError: try: del moves.__dict__[name] except KeyError: raise AttributeError("no such move, %r" % (name,))
def remove_move(name):
"""Remove item from six.moves.""" try: delattr(_MovedItems, name) except AttributeError: try: del moves.__dict__[name] except KeyError: raise AttributeError("no such move, %r" % (name,))
", "robotparser"] _importer._add_module( Module_six_moves_urllib(__name__ + ".moves.urllib"), "moves.urllib" ) def add_move(move): """Add an item to six.moves.""" setattr(_MovedItems, move.name, move) def remove_move(name):
64
64
62
5
59
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
Python
remove_move
remove_move
526
534
526
526
90bd20b0c46f106d3d72be0a6ec9aca2c9a68084
bigcode/the-stack
train
760dd0e2487ee8f85610d49d
train
class
class _MovedItems(_LazyModule): """Lazy loading of moved objects""" __path__ = [] # mark as package
class _MovedItems(_LazyModule):
"""Lazy loading of moved objects""" __path__ = [] # mark as package
"""Return None Required, if is_package is implemented""" self.__get_module(fullname) # eventually raises ImportError return None get_source = get_code # same as get_code _importer = _SixMetaPathImporter(__name__) class _MovedItems(_LazyModule):
64
64
28
8
56
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
Python
_MovedItems
_MovedItems
232
236
232
233
663590dce0989fc25691c036acbf7a062fcb808f
bigcode/the-stack
train
d8816c3973a43e52d49a8fa2
train
class
class Module_six_moves_urllib_parse(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_parse"""
class Module_six_moves_urllib_parse(_LazyModule):
"""Lazy loading of moved objects in six.moves.urllib_parse"""
er._add_module(attr, "moves." + attr.name) del attr _MovedItems._moved_attributes = _moved_attributes moves = _MovedItems(__name__ + ".moves") _importer._add_module(moves, "moves") class Module_six_moves_urllib_parse(_LazyModule):
64
64
26
12
52
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
Python
Module_six_moves_urllib_parse
Module_six_moves_urllib_parse
329
331
329
330
7dd8be1b058526edaec7c485be737e3766e0f074
bigcode/the-stack
train
6545187480f177db233a8cdf
train
class
class Module_six_moves_urllib(types.ModuleType): """Create a six.moves.urllib namespace that resembles the Python 3 namespace""" __path__ = [] # mark as package parse = _importer._get_module("moves.urllib_parse") error = _importer._get_module("moves.urllib_error") request = _importer._get_module(...
class Module_six_moves_urllib(types.ModuleType):
"""Create a six.moves.urllib namespace that resembles the Python 3 namespace""" __path__ = [] # mark as package parse = _importer._get_module("moves.urllib_parse") error = _importer._get_module("moves.urllib_error") request = _importer._get_module("moves.urllib_request") response = _importer._...
_urllib_robotparser_moved_attributes ) _importer._add_module( Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"), "moves.urllib_robotparser", "moves.urllib.robotparser", ) class Module_six_moves_urllib(types.ModuleType):
64
64
142
11
53
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
Python
Module_six_moves_urllib
Module_six_moves_urllib
501
513
501
502
9cb682da420ee452af3bcc2f4becce6640182772
bigcode/the-stack
train
ec09a13a489444b23f45beb3
train
function
def assertCountEqual(self, *args, **kwargs): return getattr(self, _assertCountEqual)(*args, **kwargs)
def assertCountEqual(self, *args, **kwargs):
return getattr(self, _assertCountEqual)(*args, **kwargs)
IO _assertCountEqual = "assertItemsEqual" _assertRaisesRegex = "assertRaisesRegexp" _assertRegex = "assertRegexpMatches" _add_doc(b, """Byte literal""") _add_doc(u, """Text literal""") def assertCountEqual(self, *args, **kwargs):
64
64
28
12
52
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
Python
assertCountEqual
assertCountEqual
719
720
719
719
2ad00806a09be1e00cc54fca6ea51aa0a0bf76df
bigcode/the-stack
train
77a9c9ca696bbd3d37597ba3
train
function
def _import_module(name): """Import module, returning the module after the last dot.""" __import__(name) return sys.modules[name]
def _import_module(name):
"""Import module, returning the module after the last dot.""" __import__(name) return sys.modules[name]
31) - 1) else: # 64-bit MAXSIZE = int((1 << 63) - 1) del X def _add_doc(func, doc): """Add documentation to a function.""" func.__doc__ = doc def _import_module(name):
64
64
31
6
57
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
Python
_import_module
_import_module
85
88
85
85
8f5221e7c9c5ff2ee6928972e85913dee2076c18
bigcode/the-stack
train
224d6fdf56f3ac9c2a9c0544
train
function
def add_metaclass(metaclass): """Class decorator for creating a class with a metaclass.""" def wrapper(cls): orig_vars = cls.__dict__.copy() slots = orig_vars.get("__slots__") if slots is not None: if isinstance(slots, str): slots = [slots] for sl...
def add_metaclass(metaclass):
"""Class decorator for creating a class with a metaclass.""" def wrapper(cls): orig_vars = cls.__dict__.copy() slots = orig_vars.get("__slots__") if slots is not None: if isinstance(slots, str): slots = [slots] for slots_var in slots: ...
ases, d): return meta(name, bases, d) @classmethod def __prepare__(cls, name, this_bases): return meta.__prepare__(name, bases) return type.__new__(metaclass, "temporary_class", (), {}) def add_metaclass(metaclass):
63
64
145
8
55
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
Python
add_metaclass
add_metaclass
905
922
905
905
c8bbc7a982d483e4906c7393927e019d705452d9
bigcode/the-stack
train
1806fa0fe8fc097de3f35347
train
class
class _LazyModule(types.ModuleType): def __init__(self, name): super(_LazyModule, self).__init__(name) self.__doc__ = self.__class__.__doc__ def __dir__(self): attrs = ["__doc__", "__name__"] attrs += [attr.name for attr in self._moved_attributes] return attrs # Sub...
class _LazyModule(types.ModuleType):
def __init__(self, name): super(_LazyModule, self).__init__(name) self.__doc__ = self.__class__.__doc__ def __dir__(self): attrs = ["__doc__", "__name__"] attrs += [attr.name for attr in self._moved_attributes] return attrs # Subclasses should override this _mov...
= old def _resolve(self): return _import_module(self.mod) def __getattr__(self, attr): _module = self._resolve() value = getattr(_module, attr) setattr(self, attr, value) return value class _LazyModule(types.ModuleType):
64
64
93
8
55
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
Python
_LazyModule
_LazyModule
127
138
127
127
b8671b31b10f8140504813f604fd52f02b396509
bigcode/the-stack
train
07433ba7a17c945822e6b55c
train
function
def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(type): def __new__(cls, nam...
def with_metaclass(meta, *bases):
"""Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(type): def __new__(cls, name, this_bases, d): ret...
functools.WRAPPER_UPDATES, ): def wrapper(f): f = functools.wraps(wrapped, assigned, updated)(f) f.__wrapped__ = wrapped return f return wrapper else: wraps = functools.wraps def with_metaclass(meta, *bases):
64
64
133
9
54
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
Python
with_metaclass
with_metaclass
889
902
889
889
12f1c0361a4175c0f9a971a60b78e9d26d9172b0
bigcode/the-stack
train
8b8c7d3534e5fe2f3eaaaafa
train
class
class Module_six_moves_urllib_error(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_error"""
class Module_six_moves_urllib_error(_LazyModule):
"""Lazy loading of moved objects in six.moves.urllib_error"""
_parse._moved_attributes = _urllib_parse_moved_attributes _importer._add_module( Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"), "moves.urllib_parse", "moves.urllib.parse", ) class Module_six_moves_urllib_error(_LazyModule):
64
64
26
12
52
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
Python
Module_six_moves_urllib_error
Module_six_moves_urllib_error
376
378
376
377
e51c1db135d29317c9362290da18556e5be78b35
bigcode/the-stack
train
ac8576efc72d31bac1f63b07
train
function
def before_all(context): """ Executed once before all tests """ # context.driver = webdriver.PhantomJS() # context.driver.manage().timeouts().pageLoadTimeout(WAIT_SECONDS, TimeUnit.SECONDS); # context.driver.manage().timeouts().setScriptTimeout(WAIT_SECONDS, TimeUnit.SECONDS); # context.driver.impli...
def before_all(context):
""" Executed once before all tests """ # context.driver = webdriver.PhantomJS() # context.driver.manage().timeouts().pageLoadTimeout(WAIT_SECONDS, TimeUnit.SECONDS); # context.driver.manage().timeouts().setScriptTimeout(WAIT_SECONDS, TimeUnit.SECONDS); # context.driver.implicitly_wait(WAIT_SECONDS) ...
""" Environment for Behave Testing """ import os from behave import * from selenium import webdriver WAIT_SECONDS = 120 BASE_URL = os.getenv('BASE_URL', 'http://localhost:5000') def before_all(context):
49
87
293
5
44
nyu-devops-shopcarts/shopcarts
features/environment.py
Python
before_all
before_all
12
36
12
12
7df60e32d258d97acb2de5ada4f736b83055a0e5
bigcode/the-stack
train
3be4f4c4427650ca566bc656
train
function
def after_all(context): """ Executed after all tests """ context.driver.quit()
def after_all(context):
""" Executed after all tests """ context.driver.quit()
) # seconds # context.driver.set_window_size(1200, 600) context.base_url = BASE_URL # -- SET LOG LEVEL: behave --logging-level=ERROR ... # on behave command-line or in "behave.ini" context.config.setup_logging() def after_all(context):
64
64
18
5
59
nyu-devops-shopcarts/shopcarts
features/environment.py
Python
after_all
after_all
39
41
39
39
1a03e72b4eab7afcba6ab14e004ffb447704601e
bigcode/the-stack
train
ef1a041852a2be10773d5596
train
function
def sitemap_app(environ, start_response): status = '200 OK' headers = [('Content-type', 'text/plain')] start_response(status, headers) requested_url = environ['PATH_INFO'] if requested_url == '/sleep': time.sleep(2) response = 'Done' else: response = sitemap_app.sitemap...
def sitemap_app(environ, start_response):
status = '200 OK' headers = [('Content-type', 'text/plain')] start_response(status, headers) requested_url = environ['PATH_INFO'] if requested_url == '/sleep': time.sleep(2) response = 'Done' else: response = sitemap_app.sitemap.get(requested_url) log.debug('Request...
status = '200 OK' headers = [('Content-type', 'text/plain')] start_response(status, headers) ret = ["%s: %s\n" % (key, value) for key, value in environ.iteritems()] return ret def sitemap_app(environ, start_response):
64
64
152
9
54
ahlinc/pomp
tests/mockserver.py
Python
sitemap_app
sitemap_app
49
67
49
49
396ddc4934a7dc9e6cdc0cd3fcb67c3e7472652a
bigcode/the-stack
train
47b774009ecd755cad5c46d9
train
class
class HttpServer(object): def __init__(self, host='localhost', port=None, app=None, sitemap=None): app = app or sitemap_app self.sitemap = sitemap or {} # inject sitemap to app app.sitemap = self.sitemap self.host = host self.port = port or 0 self.httpd = ...
class HttpServer(object):
def __init__(self, host='localhost', port=None, app=None, sitemap=None): app = app or sitemap_app self.sitemap = sitemap or {} # inject sitemap to app app.sitemap = self.sitemap self.host = host self.port = port or 0 self.httpd = make_server(self.host, self...
child_url = '%s/%s' % (entry, child) make_entry(child_url, sitemap, links_on_page if level > 1 else 0) make_sitemap(level=level - 1, sitemap=sitemap, entry=child_url) return sitemap class HttpServer(object):
64
64
213
5
58
ahlinc/pomp
tests/mockserver.py
Python
HttpServer
HttpServer
100
129
100
101
7ea7ac1008736d45ce905bf2be58a22936f07521
bigcode/the-stack
train
28be5cf22156129bb1fced13
train
function
def make_reponse_body(items, links): return { 'items': items, 'links': links, }
def make_reponse_body(items, links):
return { 'items': items, 'links': links, }
response) try: ret = [json.dumps(response).encode('utf-8')] except Exception: log.exception("bla-bla") log.debug('Requested url: %s, ret: %s', requested_url, ret) return ret def make_reponse_body(items, links):
64
64
26
9
54
ahlinc/pomp
tests/mockserver.py
Python
make_reponse_body
make_reponse_body
70
74
70
70
ac2292ad473f349b57593d4353a1e2534bf5d66b
bigcode/the-stack
train
2bbfbb77bda6f5f3da9f866a
train
class
class RedirectStdStreams(object): def __init__(self, stdout=None, stderr=None): self._stdout = stdout or sys.stdout self._stderr = stderr or sys.stderr def __enter__(self): self.old_stdout, self.old_stderr = sys.stdout, sys.stderr self.old_stdout.flush() self.old_stderr....
class RedirectStdStreams(object):
def __init__(self, stdout=None, stderr=None): self._stdout = stdout or sys.stdout self._stderr = stderr or sys.stderr def __enter__(self): self.old_stdout, self.old_stderr = sys.stdout, sys.stderr self.old_stdout.flush() self.old_stderr.flush() sys.stdout, sys.st...
import json import logging import multiprocessing from wsgiref.util import setup_testing_defaults from wsgiref.simple_server import make_server logging.basicConfig(level=logging.DEBUG) log = logging.getLogger('mockserver') devnull = open(os.devnull, 'w') class RedirectStdStreams(object):
64
64
134
6
58
ahlinc/pomp
tests/mockserver.py
Python
RedirectStdStreams
RedirectStdStreams
18
33
18
18
93c94900a6206f478bdf613b2274089f77429ab3
bigcode/the-stack
train
e45817a3dc82bb44d830a98f
train
function
def make_sitemap(level=3, links_on_page=3, sitemap=None, entry='/root'): sitemap = sitemap if sitemap else {} if level == 0: return sitemap def make_entry(url, sitemap, links_on_page): sitemap.update({ url: make_reponse_body( ['a', 'b'], ['%s/%s' ...
def make_sitemap(level=3, links_on_page=3, sitemap=None, entry='/root'):
sitemap = sitemap if sitemap else {} if level == 0: return sitemap def make_entry(url, sitemap, links_on_page): sitemap.update({ url: make_reponse_body( ['a', 'b'], ['%s/%s' % (url, i) for i in range(0, links_on_page)], ) }) ...
%s, ret: %s', requested_url, ret) return ret def make_reponse_body(items, links): return { 'items': items, 'links': links, } def make_sitemap(level=3, links_on_page=3, sitemap=None, entry='/root'):
64
64
191
21
43
ahlinc/pomp
tests/mockserver.py
Python
make_sitemap
make_sitemap
77
97
77
77
f33f54741a6981c9dce2a7bcfc8dd565b7f76e6f
bigcode/the-stack
train
f50eed5646f8e7a1c33c237a
train
function
def simple_app(environ, start_response): setup_testing_defaults(environ) status = '200 OK' headers = [('Content-type', 'text/plain')] start_response(status, headers) ret = ["%s: %s\n" % (key, value) for key, value in environ.iteritems()] return ret
def simple_app(environ, start_response):
setup_testing_defaults(environ) status = '200 OK' headers = [('Content-type', 'text/plain')] start_response(status, headers) ret = ["%s: %s\n" % (key, value) for key, value in environ.iteritems()] return ret
sys.stderr = self._stdout, self._stderr def __exit__(self, exc_type, exc_value, traceback): self._stdout.flush() self._stderr.flush() sys.stdout = self.old_stdout sys.stderr = self.old_stderr def simple_app(environ, start_response):
64
64
72
9
54
ahlinc/pomp
tests/mockserver.py
Python
simple_app
simple_app
36
46
36
36
2e62c9cdbe51a3c1ba916a4eaeced6599903e58f
bigcode/the-stack
train
d4966f2ad3224c57e1e55be3
train
class
class TestEmbedding(AllenNlpTestCase): # pylint: disable=protected-access def test_get_embedding_layer_uses_correct_embedding_dim(self): vocab = Vocabulary() vocab.add_token_to_namespace('word1') vocab.add_token_to_namespace('word2') embeddings_filename = str(self.TEST_DIR / "emb...
class TestEmbedding(AllenNlpTestCase): # pylint: disable=protected-access
def test_get_embedding_layer_uses_correct_embedding_dim(self): vocab = Vocabulary() vocab.add_token_to_namespace('word1') vocab.add_token_to_namespace('word2') embeddings_filename = str(self.TEST_DIR / "embeddings.gz") with gzip.open(embeddings_filename, 'wb') as embeddings_f...
# pylint: disable=no-self-use,invalid-name import gzip import warnings import numpy import pytest import torch with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=FutureWarning) import h5py from allennlp.common import Params from allennlp.common.checks import ConfigurationError from all...
149
256
2,279
19
130
MaxMotovilov/allennlp
allennlp/tests/modules/token_embedders/embedding_test.py
Python
TestEmbedding
TestEmbedding
23
221
23
24
a200c7c60854a4f86018073f19fc2050fc84443b
bigcode/the-stack
train
b623e67bd74c542307fc7b03
train
class
class UnalignedDataset(BaseDataset): @staticmethod def modify_commandline_options(parser, is_train): return parser def initialize(self, opt): self.opt = opt self.root = opt.dataroot self.dir_A = os.path.join(opt.dataroot, opt.phase + 'A') self.dir_B = os.path.join(op...
class UnalignedDataset(BaseDataset): @staticmethod
def modify_commandline_options(parser, is_train): return parser def initialize(self, opt): self.opt = opt self.root = opt.dataroot self.dir_A = os.path.join(opt.dataroot, opt.phase + 'A') self.dir_B = os.path.join(opt.dataroot, opt.phase + 'B') self.A_paths = ma...
import os.path from data.base_dataset import BaseDataset, get_transform from data.image_folder import make_dataset from PIL import Image import random class UnalignedDataset(BaseDataset): @staticmethod
42
148
495
11
30
chuxiuhong/ganilla
data/unaligned_dataset.py
Python
UnalignedDataset
UnalignedDataset
8
61
8
9
1e916fbe50c39f7d13896d91ae5b18036a29b52a
bigcode/the-stack
train
a50ad9b9e67177b81dc5a566
train
class
class Test(unittest.TestCase): def testStringConversion(self): s = None self.assertIsNone(utils.to_binary(s)) self.assertIsNone(utils.to_str(s)) self.assertIsNone(utils.to_text(s)) s = 'abcdefg' self.assertIsInstance(utils.to_binary(s), bytes) self.assertEqua...
class Test(unittest.TestCase):
def testStringConversion(self): s = None self.assertIsNone(utils.to_binary(s)) self.assertIsNone(utils.to_str(s)) self.assertIsNone(utils.to_text(s)) s = 'abcdefg' self.assertIsInstance(utils.to_binary(s), bytes) self.assertEqual(utils.to_binary(s), b'abcdefg...
# -*- coding: utf-8 -*- # Copyright 1999-2020 Alibaba Group Holding Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless require...
230
256
3,101
6
223
ueshin/mars
mars/tests/test_utils.py
Python
Test
Test
38
359
38
38
179058e6a79934f8384a0396b5ebe3641b6d731f
bigcode/the-stack
train
e9b6b943680edd56e4c6ec3e
train
class
class ExtremelyFastDecisionTreeClassifier(HoeffdingTreeClassifier): """ Extremely Fast Decision Tree classifier. Parameters ---------- max_byte_size: int (default=33554432) Maximum memory consumed by the tree. memory_estimate_period: int (default=1000000) Number of instances between...
class ExtremelyFastDecisionTreeClassifier(HoeffdingTreeClassifier):
""" Extremely Fast Decision Tree classifier. Parameters ---------- max_byte_size: int (default=33554432) Maximum memory consumed by the tree. memory_estimate_period: int (default=1000000) Number of instances between memory consumption checks. grace_period: int (default=200) ...
tie_threshold=0.05, binary_split=False, stop_mem_management=False, leaf_prediction='nba', nb_threshold=0, nominal_attributes=None): # pragma: no cover warnings.warn("'HATT' has been renamed to 'ExtremelyFastDecisionTreeClassifier' in v0.5.0.\n" "The old name will be removed in v0.7.0", ...
256
256
5,817
13
243
imran-salim/scikit-multiflow
src/skmultiflow/trees/extremely_fast_decision_tree.py
Python
ExtremelyFastDecisionTreeClassifier
ExtremelyFastDecisionTreeClassifier
42
736
42
42
077898108d1bc5602ee06c390102276399dba090
bigcode/the-stack
train
afd4d5e24037dd985da7919e
train
function
def HATT(max_byte_size=33554432, memory_estimate_period=1000000, grace_period=200, min_samples_reevaluate=20, split_criterion='info_gain', split_confidence=0.0000001, tie_threshold=0.05, binary_split=False, stop_mem_management=False, leaf_prediction='nba', nb_threshold=0, nominal_attributes=None): # ...
def HATT(max_byte_size=33554432, memory_estimate_period=1000000, grace_period=200, min_samples_reevaluate=20, split_criterion='info_gain', split_confidence=0.0000001, tie_threshold=0.05, binary_split=False, stop_mem_management=False, leaf_prediction='nba', nb_threshold=0, nominal_attributes=None): # ...
warnings.warn("'HATT' has been renamed to 'ExtremelyFastDecisionTreeClassifier' in v0.5.0.\n" "The old name will be removed in v0.7.0", category=FutureWarning) return ExtremelyFastDecisionTreeClassifier(max_byte_size=max_byte_size, memory_estimate...
def HATT(max_byte_size=33554432, memory_estimate_period=1000000, grace_period=200, min_samples_reevaluate=20, split_criterion='info_gain', split_confidence=0.0000001, tie_threshold=0.05, binary_split=False, stop_mem_management=False, leaf_prediction='nba', nb_threshold=0, nominal_attributes=None): # ...
89
74
247
89
0
imran-salim/scikit-multiflow
src/skmultiflow/trees/extremely_fast_decision_tree.py
Python
HATT
HATT
17
33
17
19
203d3516cdba7298051024349995585b1c9c43d3
bigcode/the-stack
train
3eaf5aeea26b5aaffa3e044e
train
function
def search_correspond_LM_ID(xAug, PAug, zi): """ Landmark association with Mahalanobis distance """ nLM = calc_n_LM(xAug) mdist = [] for i in range(nLM): lm = get_LM_Pos_from_state(xAug, i) y, S, H = calc_innovation(lm, xAug, PAug, zi, i) mdist.append(y.T @ np.linalg.i...
def search_correspond_LM_ID(xAug, PAug, zi):
""" Landmark association with Mahalanobis distance """ nLM = calc_n_LM(xAug) mdist = [] for i in range(nLM): lm = get_LM_Pos_from_state(xAug, i) y, S, H = calc_innovation(lm, xAug, PAug, zi, i) mdist.append(y.T @ np.linalg.inv(S) @ y) mdist.append(M_DIST_TH) # ne...
1]) return zp def get_LM_Pos_from_state(x, ind): lm = x[STATE_SIZE + LM_SIZE * ind: STATE_SIZE + LM_SIZE * (ind + 1), :] return lm def search_correspond_LM_ID(xAug, PAug, zi):
64
64
133
15
48
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
Python
search_correspond_LM_ID
search_correspond_LM_ID
148
166
148
148
a7a337f6efbe064551498e34bf2ddf20f0c8d450
bigcode/the-stack
train
c5039d2d0d236eeb23cc1c63
train
function
def calc_LM_Pos(x, z): zp = np.zeros((2, 1)) zp[0, 0] = x[0, 0] + z[0] * math.cos(x[2, 0] + z[1]) zp[1, 0] = x[1, 0] + z[0] * math.sin(x[2, 0] + z[1]) #zp[0, 0] = x[0, 0] + z[0, 0] * math.cos(x[2, 0] + z[0, 1]) #zp[1, 0] = x[1, 0] + z[0, 0] * math.sin(x[2, 0] + z[0, 1]) return zp
def calc_LM_Pos(x, z):
zp = np.zeros((2, 1)) zp[0, 0] = x[0, 0] + z[0] * math.cos(x[2, 0] + z[1]) zp[1, 0] = x[1, 0] + z[0] * math.sin(x[2, 0] + z[1]) #zp[0, 0] = x[0, 0] + z[0, 0] * math.cos(x[2, 0] + z[0, 1]) #zp[1, 0] = x[1, 0] + z[0, 0] * math.sin(x[2, 0] + z[0, 1]) return zp
u[0] * math.cos(x[2, 0])], [0.0, 0.0, 0.0]]) G = np.eye(STATE_SIZE) + Fx.T * jF * Fx return G, Fx, def calc_LM_Pos(x, z):
64
64
182
9
55
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
Python
calc_LM_Pos
calc_LM_Pos
130
138
130
130
d9e3524916cc80e9d7f337c45a0bc50b7cdfc34f
bigcode/the-stack
train
2d437a4ff3273382edc59920
train
function
def calc_innovation(lm, xEst, PEst, z, LMid): delta = lm - xEst[0:2] q = (delta.T @ delta)[0, 0] zangle = math.atan2(delta[1, 0], delta[0, 0]) - xEst[2, 0] zp = np.array([[math.sqrt(q), pi_2_pi(zangle)]]) y = (z - zp).T y[1] = pi_2_pi(y[1]) H = jacobH(q, delta, xEst, LMid + 1) S = H @ PE...
def calc_innovation(lm, xEst, PEst, z, LMid):
delta = lm - xEst[0:2] q = (delta.T @ delta)[0, 0] zangle = math.atan2(delta[1, 0], delta[0, 0]) - xEst[2, 0] zp = np.array([[math.sqrt(q), pi_2_pi(zangle)]]) y = (z - zp).T y[1] = pi_2_pi(y[1]) H = jacobH(q, delta, xEst, LMid + 1) S = H @ PEst @ H.T + Cx[0:2, 0:2] return y, S, H
i) mdist.append(y.T @ np.linalg.inv(S) @ y) mdist.append(M_DIST_TH) # new landmark minid = mdist.index(min(mdist)) return minid def calc_innovation(lm, xEst, PEst, z, LMid):
64
64
166
18
45
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
Python
calc_innovation
calc_innovation
169
179
169
169
a91e4e31487c7a3446dadec89264e802a2208158
bigcode/the-stack
train
9aee475d0df6824c8b038ce7
train
function
def calc_input(): v = 1.0 # [m/s] yawrate = 0.1 # [rad/s] u = np.array([[v, yawrate]]).T return u
def calc_input():
v = 1.0 # [m/s] yawrate = 0.1 # [rad/s] u = np.array([[v, yawrate]]).T return u
.inv(S) xEst = xEst + (K @ y) PEst = (np.eye(len(xEst)) - (K @ H)) @ PEst xEst[2] = pi_2_pi(xEst[2]) return xEst, PEst def calc_input():
64
64
49
4
59
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
Python
calc_input
calc_input
62
66
62
62
d5a1187d20d7d66da11e36d3f10dd2b09876c079
bigcode/the-stack
train
aa13b7b2a8a12c04c9cfee7e
train
function
def jacobH(q, delta, x, i): sq = math.sqrt(q) G = np.array([[-sq * delta[0, 0], - sq * delta[1, 0], 0, sq * delta[0, 0], sq * delta[1, 0]], [delta[1, 0], - delta[0, 0], - 1.0, - delta[1, 0], delta[0, 0]]]) G = G / q nLM = calc_n_LM(x) F1 = np.hstack((np.eye(3), np.zeros((3, 2 * nL...
def jacobH(q, delta, x, i):
sq = math.sqrt(q) G = np.array([[-sq * delta[0, 0], - sq * delta[1, 0], 0, sq * delta[0, 0], sq * delta[1, 0]], [delta[1, 0], - delta[0, 0], - 1.0, - delta[1, 0], delta[0, 0]]]) G = G / q nLM = calc_n_LM(x) F1 = np.hstack((np.eye(3), np.zeros((3, 2 * nLM)))) F2 = np.hstack((np...
(y[1]) H = jacobH(q, delta, xEst, LMid + 1) S = H @ PEst @ H.T + Cx[0:2, 0:2] return y, S, H def jacobH(q, delta, x, i):
66
66
221
12
53
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
Python
jacobH
jacobH
182
197
182
182
aad1b58013021ac0b2a45788485d040482fe3b57
bigcode/the-stack
train
ff37468fef6b746d2bcced7a
train
function
def ekf_slam(xEst, PEst, u, z): # Predict S = STATE_SIZE xEst[0:S] = motion_model(xEst[0:S], u) G, Fx = jacob_motion(xEst[0:S], u) PEst[0:S, 0:S] = G.T * PEst[0:S, 0:S] * G + Fx.T * Cx * Fx initP = np.eye(2) # Update for iz in range(len(z[:, 0])): # for each observation minid ...
def ekf_slam(xEst, PEst, u, z): # Predict
S = STATE_SIZE xEst[0:S] = motion_model(xEst[0:S], u) G, Fx = jacob_motion(xEst[0:S], u) PEst[0:S, 0:S] = G.T * PEst[0:S, 0:S] * G + Fx.T * Cx * Fx initP = np.eye(2) # Update for iz in range(len(z[:, 0])): # for each observation minid = search_correspond_LM_ID(xEst, PEst, z[iz, 0:2...
DT = 0.1 # time tick [s] SIM_TIME = 50.0 # simulation time [s] MAX_RANGE = 20.0 # maximum observation range M_DIST_TH = 2.0 # Threshold of Mahalanobis distance for data association. STATE_SIZE = 3 # State size [x,y,yaw] LM_SIZE = 2 # LM state size [x,y] show_animation = True def ekf_slam(xEst, PEst, u, z): ...
114
114
383
19
94
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
Python
ekf_slam
ekf_slam
28
59
28
30
76aa3532f3468e41182b2aad4075a6bdbbf0037b
bigcode/the-stack
train
a9c1943c9e8e57781f87d45c
train
function
def main(): print(__file__ + " start!!") time = 0.0 # RFID positions [x, y] RFID = np.array([[10.0, -2.0], [15.0, 10.0], [3.0, 15.0], [-5.0, 20.0]]) # State Vector [x y yaw v]' xEst = np.zeros((STATE_SIZE, 1)) xTrue = np.zeros...
def main():
print(__file__ + " start!!") time = 0.0 # RFID positions [x, y] RFID = np.array([[10.0, -2.0], [15.0, 10.0], [3.0, 15.0], [-5.0, 20.0]]) # State Vector [x y yaw v]' xEst = np.zeros((STATE_SIZE, 1)) xTrue = np.zeros((STATE_SIZE...
G / q nLM = calc_n_LM(x) F1 = np.hstack((np.eye(3), np.zeros((3, 2 * nLM)))) F2 = np.hstack((np.zeros((2, 3)), np.zeros((2, 2 * (i - 1))), np.eye(2), np.zeros((2, 2 * nLM - 2 * i)))) F = np.vstack((F1, F2)) H = G @ F return H def pi_2_pi(angle): return (angle + math...
142
142
474
3
138
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
Python
main
main
204
261
204
204
ae88bbaee1eacde6ab89ec181aba7572806fc47f
bigcode/the-stack
train
2f5cc4114b6246fe6779cded
train
function
def calc_n_LM(x): n = int((len(x) - STATE_SIZE) / LM_SIZE) return n
def calc_n_LM(x):
n = int((len(x) - STATE_SIZE) / LM_SIZE) return n
([[DT * math.cos(x[2, 0]), 0], [DT * math.sin(x[2, 0]), 0], [0.0, DT]]) x = (F @ x) + (B @ u) return x def calc_n_LM(x):
64
64
27
7
56
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
Python
calc_n_LM
calc_n_LM
111
113
111
111
7fb989ad8d4bb57cdb22b8da9a3bfa907577d879
bigcode/the-stack
train
7e507578587551412140e8fa
train
function
def motion_model(x, u): F = np.array([[1.0, 0, 0], [0, 1.0, 0], [0, 0, 1.0]]) B = np.array([[DT * math.cos(x[2, 0]), 0], [DT * math.sin(x[2, 0]), 0], [0.0, DT]]) x = (F @ x) + (B @ u) return x
def motion_model(x, u):
F = np.array([[1.0, 0, 0], [0, 1.0, 0], [0, 0, 1.0]]) B = np.array([[DT * math.cos(x[2, 0]), 0], [DT * math.sin(x[2, 0]), 0], [0.0, DT]]) x = (F @ x) + (B @ u) return x
.randn() * Rsim[0, 0], u[1, 0] + np.random.randn() * Rsim[1, 1]]]).T xd = motion_model(xd, ud) return xTrue, z, xd, ud def motion_model(x, u):
64
64
109
7
56
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
Python
motion_model
motion_model
97
108
97
98
ef4a6b954f5f7407023184c02635a5616fb4870a
bigcode/the-stack
train
07c0d37e6455da054ad71740
train
function
def pi_2_pi(angle): return (angle + math.pi) % (2 * math.pi) - math.pi
def pi_2_pi(angle):
return (angle + math.pi) % (2 * math.pi) - math.pi
((2, 2 * (i - 1))), np.eye(2), np.zeros((2, 2 * nLM - 2 * i)))) F = np.vstack((F1, F2)) H = G @ F return H def pi_2_pi(angle):
64
64
26
7
56
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
Python
pi_2_pi
pi_2_pi
200
201
200
200
0cc2394ef135d4f8f000657cb582cbffd8d4190d
bigcode/the-stack
train
3ed00a84573e319ea00ba306
train
function
def observation(xTrue, xd, u, RFID): xTrue = motion_model(xTrue, u) # add noise to gps x-y z = np.zeros((0, 3)) for i in range(len(RFID[:, 0])): dx = RFID[i, 0] - xTrue[0, 0] dy = RFID[i, 1] - xTrue[1, 0] d = math.sqrt(dx**2 + dy**2) angle = pi_2_pi(math.atan2(dy, dx)...
def observation(xTrue, xd, u, RFID):
xTrue = motion_model(xTrue, u) # add noise to gps x-y z = np.zeros((0, 3)) for i in range(len(RFID[:, 0])): dx = RFID[i, 0] - xTrue[0, 0] dy = RFID[i, 1] - xTrue[1, 0] d = math.sqrt(dx**2 + dy**2) angle = pi_2_pi(math.atan2(dy, dx) - xTrue[2, 0]) if d <= MAX_RA...
Est xEst[2] = pi_2_pi(xEst[2]) return xEst, PEst def calc_input(): v = 1.0 # [m/s] yawrate = 0.1 # [rad/s] u = np.array([[v, yawrate]]).T return u def observation(xTrue, xd, u, RFID):
86
86
287
11
74
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
Python
observation
observation
69
94
69
70
0cd3a17a24107609cac56286bf06bf28275d6850
bigcode/the-stack
train
02e13c6b8f37c9f3953aaed1
train
function
def jacob_motion(x, u): Fx = np.hstack((np.eye(STATE_SIZE), np.zeros( (STATE_SIZE, LM_SIZE * calc_n_LM(x))))) jF = np.array([[0.0, 0.0, -DT * u[0] * math.sin(x[2, 0])], [0.0, 0.0, DT * u[0] * math.cos(x[2, 0])], [0.0, 0.0, 0.0]]) G = np.eye(STATE_SIZE) + Fx.T...
def jacob_motion(x, u):
Fx = np.hstack((np.eye(STATE_SIZE), np.zeros( (STATE_SIZE, LM_SIZE * calc_n_LM(x))))) jF = np.array([[0.0, 0.0, -DT * u[0] * math.sin(x[2, 0])], [0.0, 0.0, DT * u[0] * math.cos(x[2, 0])], [0.0, 0.0, 0.0]]) G = np.eye(STATE_SIZE) + Fx.T * jF * Fx return G,...
0], [0.0, DT]]) x = (F @ x) + (B @ u) return x def calc_n_LM(x): n = int((len(x) - STATE_SIZE) / LM_SIZE) return n def jacob_motion(x, u):
64
64
141
8
55
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
Python
jacob_motion
jacob_motion
116
127
116
117
3e3dd19d5e707300c9676439d94de1beaa496468
bigcode/the-stack
train
3803e5c82743f67fb1d64573
train
function
def get_LM_Pos_from_state(x, ind): lm = x[STATE_SIZE + LM_SIZE * ind: STATE_SIZE + LM_SIZE * (ind + 1), :] return lm
def get_LM_Pos_from_state(x, ind):
lm = x[STATE_SIZE + LM_SIZE * ind: STATE_SIZE + LM_SIZE * (ind + 1), :] return lm
[0, 1]) #zp[1, 0] = x[1, 0] + z[0, 0] * math.sin(x[2, 0] + z[0, 1]) return zp def get_LM_Pos_from_state(x, ind):
64
64
42
11
52
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
Python
get_LM_Pos_from_state
get_LM_Pos_from_state
141
145
141
142
8a26aecf1e67ee2aeb2e296a6ab7a859dd0d1c08
bigcode/the-stack
train
eb8a65f7efebbc0d3caa966f
train
function
def login_user(test_cls): user = ModelFactory.create_user() password = "custom password" user.set_password(password) user.save() group = Group(name="officer") group.save() group.user_set.add(user) group.save() test_cls.client.login(username=user.username, password=password)
def login_user(test_cls):
user = ModelFactory.create_user() password = "custom password" user.set_password(password) user.save() group = Group(name="officer") group.save() group.user_set.add(user) group.save() test_cls.client.login(username=user.username, password=password)
ester=icsr_semester, **kwargs, ) @staticmethod def create_user(**kwargs): default_kwargs = { "username": "default username", } kwargs = {**default_kwargs, **kwargs} return User.objects.create(**kwargs) def login_user(test_cls):
64
64
67
6
58
jyxzhang/hknweb
hknweb/academics/tests/utils.py
Python
login_user
login_user
151
162
151
151
99dd1c78060eb52c278cb31d67677f16ef3269d5
bigcode/the-stack
train
d36cd388948c2332838ca86b
train
class
class ModelFactory: @staticmethod def create_course(**kwargs): return Course.objects.create(**kwargs) @staticmethod def create_department(**kwargs): default_kwargs = { "name": "default name", "abbr": "default abbr", } kwargs = {**default_kwargs, *...
class ModelFactory: @staticmethod
def create_course(**kwargs): return Course.objects.create(**kwargs) @staticmethod def create_department(**kwargs): default_kwargs = { "name": "default name", "abbr": "default abbr", } kwargs = {**default_kwargs, **kwargs} return Department.obj...
from datetime import datetime from django.contrib.auth.models import User, Group from hknweb.academics.models import ( Course, Department, Instructor, Semester, Question, Rating, Survey, ICSR, ) class ModelFactory: @staticmethod
59
256
868
8
51
jyxzhang/hknweb
hknweb/academics/tests/utils.py
Python
ModelFactory
ModelFactory
17
148
17
18
7e9e752e1c53595a046adff59a45cd45e0ea3d18
bigcode/the-stack
train
f16270ea410f5eab3eb6fe5b
train
class
class CITestRealTimePerformance(base.TestBaseTestCase, testtools.TestCase): """Test Performance REST calls.""" def setUp(self): """setUp.""" super(CITestRealTimePerformance, self).setUp() self.perf = self.conn.performance self.rt = self.perf.real_time self.p_data...
class CITestRealTimePerformance(base.TestBaseTestCase, testtools.TestCase):
"""Test Performance REST calls.""" def setUp(self): """setUp.""" super(CITestRealTimePerformance, self).setUp() self.perf = self.conn.performance self.rt = self.perf.real_time self.p_data = pd.PerformanceData() self.time_now = int(time.time() * 1000) ...
# Copyright (c) 2020 Dell Inc. or its subsidiaries. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
248
256
4,313
17
230
dell/PyU4V
PyU4V/tests/ci_tests/test_pyu4v_ci_performance_real_time.py
Python
CITestRealTimePerformance
CITestRealTimePerformance
29
511
29
29
855fffd3f8df11d84f20bcee0bcbc17316d954f9
bigcode/the-stack
train
3d158063f17070436ef011fe
train
function
def itemize(metrics): return [m.item() for m in metrics]
def itemize(metrics):
return [m.item() for m in metrics]
of training losses at the end of each training epoch." np_losses = [to_np(l).item() for l in learn.recorder.losses] batch_size = len(learn.data.train_dl) return [batch[-1] for batch in partition(np_losses, batch_size)] def itemize(metrics):
64
64
16
5
59
jeffrwells/fastai
tests/test_callbacks_csv_logger.py
Python
itemize
itemize
33
34
33
33
b4806212f2171d650a88a5d415d4443a2ee590a2
bigcode/the-stack
train
a2d4e7f2b1894cd7f98f15a9
train
function
@pytest.fixture(scope="module", autouse=True) def cleanup(request): """Cleanup the autogenerated file once we are finished.""" def remove_history_csv(): file = "history.csv" if os.path.exists(file): os.remove(file) request.addfinalizer(remove_history_csv)
@pytest.fixture(scope="module", autouse=True) def cleanup(request):
"""Cleanup the autogenerated file once we are finished.""" def remove_history_csv(): file = "history.csv" if os.path.exists(file): os.remove(file) request.addfinalizer(remove_history_csv)
_less_precise=True (or better =3), until then using =2 as it works, but this check is less good. pd.testing.assert_frame_equal(csv_df, recorder_df, check_exact=False, check_less_precise=2) @pytest.fixture(scope="module", autouse=True) def cleanup(request):
63
64
58
14
49
jeffrwells/fastai
tests/test_callbacks_csv_logger.py
Python
cleanup
cleanup
52
58
52
53
5af927dbff30acb5d7f5bf076d8752daa6ccfcdb
bigcode/the-stack
train
fe4738dc6959880838e4df1d
train
function
def get_train_losses(learn): "Returns list of training losses at the end of each training epoch." np_losses = [to_np(l).item() for l in learn.recorder.losses] batch_size = len(learn.data.train_dl) return [batch[-1] for batch in partition(np_losses, batch_size)]
def get_train_losses(learn):
"Returns list of training losses at the end of each training epoch." np_losses = [to_np(l).item() for l in learn.recorder.losses] batch_size = len(learn.data.train_dl) return [batch[-1] for batch in partition(np_losses, batch_size)]
line.split()[:-1]] for line in lines] records = [dict(zip(header, metrics_list)) for metrics_list in floats] df = pd.DataFrame(records, columns=header) df['epoch'] = df['epoch'].astype(int) return df def get_train_losses(learn):
64
64
70
7
56
jeffrwells/fastai
tests/test_callbacks_csv_logger.py
Python
get_train_losses
get_train_losses
27
31
27
27
43a8983d219ac694a591b76ff5f71aaa52e4c73f
bigcode/the-stack
train
9c9846400060f2dac2cc1340
train
function
def convert_into_dataframe(buffer): "Converts data captured from `fastprogress.ConsoleProgressBar` into dataframe." lines = buffer.split('\n') header, *lines = [l.strip() for l in lines if l and not l.startswith('Total')] header = header.split()[:-1] floats = [[float(x) for x in line.split()[:-1]] f...
def convert_into_dataframe(buffer):
"Converts data captured from `fastprogress.ConsoleProgressBar` into dataframe." lines = buffer.split('\n') header, *lines = [l.strip() for l in lines if l and not l.startswith('Total')] header = header.split()[:-1] floats = [[float(x) for x in line.split()[:-1]] for line in lines] records = [dic...
)] for i, (loss, val_loss, epoch_metrics) in enumerate(zip( get_train_losses(learn), learn.recorder.val_losses, learn.recorder.metrics), 1)] return pd.DataFrame(records, columns=learn.recorder.names[:-1]) def convert_into_dataframe(buffer):
64
64
130
6
58
jeffrwells/fastai
tests/test_callbacks_csv_logger.py
Python
convert_into_dataframe
convert_into_dataframe
16
25
16
16
6e05126c036aefa44a599b6ccf446d234407883f
bigcode/the-stack
train
73eb738aa83d0a6b83c8d65d
train
function
def test_logger(): learn = fake_learner() learn.metrics = [accuracy, error_rate] learn.callback_fns.append(callbacks.CSVLogger) with CaptureStdout() as cs: learn.fit_one_cycle(3) csv_df = learn.csv_logger.read_logged_file() stdout_df = convert_into_dataframe(cs.out) csv_df.drop(columns=['tim...
def test_logger():
learn = fake_learner() learn.metrics = [accuracy, error_rate] learn.callback_fns.append(callbacks.CSVLogger) with CaptureStdout() as cs: learn.fit_one_cycle(3) csv_df = learn.csv_logger.read_logged_file() stdout_df = convert_into_dataframe(cs.out) csv_df.drop(columns=['time'], axis=1, inplac...
_losses = [to_np(l).item() for l in learn.recorder.losses] batch_size = len(learn.data.train_dl) return [batch[-1] for batch in partition(np_losses, batch_size)] def itemize(metrics): return [m.item() for m in metrics] def test_logger():
66
66
223
4
62
jeffrwells/fastai
tests/test_callbacks_csv_logger.py
Python
test_logger
test_logger
36
50
36
36
c46adc49f555120c1fa5e60db227bc5ca7e47d23
bigcode/the-stack
train
427e7c3fe5aa0260cf632a91
train
function
def create_metrics_dataframe(learn): "Converts metrics stored in `Recorder` into dataframe." records = [ [i, loss, val_loss, *itemize(epoch_metrics)] for i, (loss, val_loss, epoch_metrics) in enumerate(zip( get_train_losses(learn), learn.recorder.val_losses, ...
def create_metrics_dataframe(learn):
"Converts metrics stored in `Recorder` into dataframe." records = [ [i, loss, val_loss, *itemize(epoch_metrics)] for i, (loss, val_loss, epoch_metrics) in enumerate(zip( get_train_losses(learn), learn.recorder.val_losses, learn.recorder.metrics), 1)] ...
import pytest, re from utils.fakes import * from utils.text import CaptureStdout def create_metrics_dataframe(learn):
26
64
96
7
18
jeffrwells/fastai
tests/test_callbacks_csv_logger.py
Python
create_metrics_dataframe
create_metrics_dataframe
5
14
5
5
b66595bf454aaca427cd9592529a1523fa108def
bigcode/the-stack
train
814981454d0dbe08b41c78a9
train
class
class IdObject(AttrDict): def __init__(self, id=None): # Set ID self.id = id # Set Defaults self.bip32_enabled = False self.bip70_static_amount = None self.bip70_enabled = False self.wallet_address = None self.expires = None self.memo = None...
class IdObject(AttrDict):
def __init__(self, id=None): # Set ID self.id = id # Set Defaults self.bip32_enabled = False self.bip70_static_amount = None self.bip70_enabled = False self.wallet_address = None self.expires = None self.memo = None self.master_public...
# bip70_static_amount # bip70_enabled # last_generated_index # last_used_index # master_public_key # master_public_key_source # private_key # private_key_source # private_key_id # x509_cert # x509_cert_source class IdObject(AttrDict):
64
64
143
7
56
voisine/addressimo
addressimo/data.py
Python
IdObject
IdObject
21
42
21
22
496d869ad8c6e9c0682cd9086871e10e42fd67a1
bigcode/the-stack
train
ad299073609e186db8087d62
train
class
class CharsAndStringsTest(unittest.TestCase): def test_char_fields(self): Test = autoclass('org.jnius.CharsAndStrings', include_protected=False, include_private=False) test = Test() self.assertEqual(test.testChar1, 'a') self.assertEqual(test.testChar2, 'ä')...
class CharsAndStringsTest(unittest.TestCase):
def test_char_fields(self): Test = autoclass('org.jnius.CharsAndStrings', include_protected=False, include_private=False) test = Test() self.assertEqual(test.testChar1, 'a') self.assertEqual(test.testChar2, 'ä') self.assertEqual(test.testChar3, '☺') ...
# -*- coding: utf-8 -*- # from __future__ import print_function from __future__ import division from __future__ import absolute_import import unittest from jnius.reflect import autoclass, JavaException class CharsAndStringsTest(unittest.TestCase):
56
256
1,367
10
45
panda3d/pyjnius
tests/test_chars_and_strings.py
Python
CharsAndStringsTest
CharsAndStringsTest
9
131
9
10
4cade18c3a1dfb8278b38dbc8c1c72740ab4ad1c
bigcode/the-stack
train
5a1c9ed79fc82f32da3867af
train
function
def test_validate_documentation_existence(): from moler.util.cmds_events_doc import _validate_documentation_existence fake_cmd = import_module('conftest') test_data = {'_ver_execute': {'COMMAND_OUTPUT': '', 'COMMAND_KWARGS': {}, 'COMMAND_RESULT': {}}, '_ver_test': {'COMMAND_OUTPUT': '', 'C...
def test_validate_documentation_existence():
from moler.util.cmds_events_doc import _validate_documentation_existence fake_cmd = import_module('conftest') test_data = {'_ver_execute': {'COMMAND_OUTPUT': '', 'COMMAND_KWARGS': {}, 'COMMAND_RESULT': {}}, '_ver_test': {'COMMAND_OUTPUT': '', 'COMMAND_KWARGS': {}, 'COMMAND_RESULT': {}}} ...
(fake_cmd_from_conftest['_ver_nice']['COMMAND_OUTPUT'], str) assert isinstance(fake_cmd_from_conftest['_ver_nice']['COMMAND_KWARGS'], dict) assert isinstance(fake_cmd_from_conftest['_ver_nice']['COMMAND_RESULT'], dict) def test_validate_documentation_existence():
64
64
153
8
56
carr-elagheb/moler
test/test_cmds_events_doc.py
Python
test_validate_documentation_existence
test_validate_documentation_existence
159
169
159
159
127fa6bb50f372ee14fa666682b43477c992e0ad
bigcode/the-stack
train
f0e782e890944e0cc51c8f01
train
function
def test_create_command_raise_exception_when_object_takes_no_params(fake_cmd): from moler.util.cmds_events_doc import _create_command, _buffer_connection with raises(Exception) as exc: _create_command(fake_cmd, _buffer_connection().moler_connection, {}) assert "via FakeCommand() : object() takes n...
def test_create_command_raise_exception_when_object_takes_no_params(fake_cmd):
from moler.util.cmds_events_doc import _create_command, _buffer_connection with raises(Exception) as exc: _create_command(fake_cmd, _buffer_connection().moler_connection, {}) assert "via FakeCommand() : object() takes no parameters" or "via FakeCommand() : this constructor takes no arguments" in s...
_variant(test_data, '_ver_test2', "COMMAND") assert result1 == ('out1', {1: 1}, {1: 1}) assert result2 == ('out2', {}, {2: 2}) def test_create_command_raise_exception_when_object_takes_no_params(fake_cmd):
64
64
92
15
49
carr-elagheb/moler
test/test_cmds_events_doc.py
Python
test_create_command_raise_exception_when_object_takes_no_params
test_create_command_raise_exception_when_object_takes_no_params
209
216
209
209
b63d7af08a0f0dde9fd8396f327220dac6d6df7d
bigcode/the-stack
train
74eaaa4b845518ee463d0f4d
train
function
def _load_obj(func_name): """ Load instance from module. :param func_name: function name as string :return: object instance :rtype: type """ return getattr(import_module('moler.util.cmds_events_doc'), func_name)
def _load_obj(func_name):
""" Load instance from module. :param func_name: function name as string :return: object instance :rtype: type """ return getattr(import_module('moler.util.cmds_events_doc'), func_name)
_list = [f for root, dirs, files in walk(abs_test_path) for f in files if isfile(join(root, f)) and '__init__' not in f and '.pyc' not in f and f.endswith('.py')] return file_list def _load_obj(func_name):
64
64
58
7
56
carr-elagheb/moler
test/test_cmds_events_doc.py
Python
_load_obj
_load_obj
45
53
45
45
54177f7974625bcc23f8ef438f01b711905d26e5
bigcode/the-stack
train
891919fd8933081d1fad9cbb
train
function
def test_documentation_exists(): from moler.util.cmds_events_doc import check_if_documentation_exists dir_path = path.dirname(path.realpath(__file__)) moler_dir_path = path.dirname(dir_path) cmd_path = path.join(moler_dir_path, "moler", "cmd") events_path = path.join(moler_dir_path, "moler", "event...
def test_documentation_exists():
from moler.util.cmds_events_doc import check_if_documentation_exists dir_path = path.dirname(path.realpath(__file__)) moler_dir_path = path.dirname(dir_path) cmd_path = path.join(moler_dir_path, "moler", "cmd") events_path = path.join(moler_dir_path, "moler", "events") assert check_if_document...
""" Load instance from module. :param func_name: function name as string :return: object instance :rtype: type """ return getattr(import_module('moler.util.cmds_events_doc'), func_name) # --------------- helper functions --------------- def test_documentation_exists():
63
64
107
6
57
carr-elagheb/moler
test/test_cmds_events_doc.py
Python
test_documentation_exists
test_documentation_exists
59
68
59
59
ddbcea1e55eb4ea117357ef99264b7b0bafdfb23
bigcode/the-stack
train
80f670d789556f43ce3926e6
train
function
@mark.parametrize('func2test,method_param,base_class, expected', [ ('_walk_moler_python_files', cmd_dir_under_test, "COMMAND", True), ('_walk_moler_commands', cmd_dir_under_test, Command, True), ('_walk_moler_nonabstract_commands', cmd_dir_under_test, Command, True)]) def test_functions_are_generators(func2...
@mark.parametrize('func2test,method_param,base_class, expected', [ ('_walk_moler_python_files', cmd_dir_under_test, "COMMAND", True), ('_walk_moler_commands', cmd_dir_under_test, Command, True), ('_walk_moler_nonabstract_commands', cmd_dir_under_test, Command, True)]) def test_functions_are_generators(func2...
from inspect import isgenerator, isgeneratorfunction func_obj = _load_obj(func_name=func2test) generator_obj = func_obj(method_param, base_class) assert isgeneratorfunction(func_obj) is expected assert isgenerator(generator_obj) is expected
@mark.parametrize('func2test,method_param,base_class, expected', [ ('_walk_moler_python_files', cmd_dir_under_test, "COMMAND", True), ('_walk_moler_commands', cmd_dir_under_test, Command, True), ('_walk_moler_nonabstract_commands', cmd_dir_under_test, Command, True)]) def test_functions_are_generators(func2...
90
64
148
90
0
carr-elagheb/moler
test/test_cmds_events_doc.py
Python
test_functions_are_generators
test_functions_are_generators
81
92
81
85
ee9fab8cf4e71c9c0bf32ce9435a3731c9e48bac
bigcode/the-stack
train
51afb10c37ded1a13c91c137
train
function
def test_buffer_connection_returns_threadconnection_with_moler_conn(): from moler.io.raw.memory import ThreadedFifoBuffer from moler.observable_connection import ObservableConnection from moler.util.cmds_events_doc import _buffer_connection buff_conn = _buffer_connection() assert isinstance(buff_co...
def test_buffer_connection_returns_threadconnection_with_moler_conn():
from moler.io.raw.memory import ThreadedFifoBuffer from moler.observable_connection import ObservableConnection from moler.util.cmds_events_doc import _buffer_connection buff_conn = _buffer_connection() assert isinstance(buff_conn, ThreadedFifoBuffer) is True assert isinstance(buff_conn.moler_c...
, "moler", "cmd") events_path = path.join(moler_dir_path, "moler", "events") assert check_if_documentation_exists(cmd_path) is True assert check_if_documentation_exists(events_path) is True def test_buffer_connection_returns_threadconnection_with_moler_conn():
64
64
88
12
51
carr-elagheb/moler
test/test_cmds_events_doc.py
Python
test_buffer_connection_returns_threadconnection_with_moler_conn
test_buffer_connection_returns_threadconnection_with_moler_conn
71
78
71
71
9a5cdb7081d9b0ca8b7bf7abc43a3c8612600c55
bigcode/the-stack
train
911749472a5ed68d70b2d143
train
function
def _list_in_path(listing_type): """ Quick and dirty function to return list of strings depends on parameter: - allfiles - list all file without path - fullpath - list only py files with path - only_py - list only py file without path :param listing_type: :return: list of files :rtype...
def _list_in_path(listing_type):
""" Quick and dirty function to return list of strings depends on parameter: - allfiles - list all file without path - fullpath - list only py files with path - only_py - list only py file without path :param listing_type: :return: list of files :rtype: list(str) """ abs_test_...
Michal Ernst' __copyright__ = 'Copyright (C) 2018-2019, Nokia' __email__ = 'michal.plichta@nokia.com, michal.ernst@nokia.com' cmd_dir_under_test = 'moler/cmd/' repo_path = abspath(join(dirname(__file__), '..')) # --------------- helper functions --------------- def _list_in_path(listing_type):
86
86
289
9
77
carr-elagheb/moler
test/test_cmds_events_doc.py
Python
_list_in_path
_list_in_path
19
42
19
19
6ba92394c5bfc6c8166fd69016e799a795b295f3
bigcode/the-stack
train
9824e10de59142c4ef4433b5
train
function
def test_get_doc_variant(): from moler.util.cmds_events_doc import _get_doc_variant test_data = {'_ver_test1': {'COMMAND_OUTPUT': 'out1', 'COMMAND_KWARGS': {1: 1}, 'COMMAND_RESULT': {1: 1}}, '_ver_test2': {'COMMAND_OUTPUT': 'out2', 'COMMAND_RESULT': {2: 2}}} result1 = _get_doc_variant(test...
def test_get_doc_variant():
from moler.util.cmds_events_doc import _get_doc_variant test_data = {'_ver_test1': {'COMMAND_OUTPUT': 'out1', 'COMMAND_KWARGS': {1: 1}, 'COMMAND_RESULT': {1: 1}}, '_ver_test2': {'COMMAND_OUTPUT': 'out2', 'COMMAND_RESULT': {2: 2}}} result1 = _get_doc_variant(test_data, '_ver_test1', "COMMAN...
_ver_test2' in result2[1] assert '> has COMMAND_OUTPUT_ver_test3 but no COMMAND_RESULT_ver_test3' in result3[0] assert '> has COMMAND_KWARGS_ver_test3 but no COMMAND_RESULT_ver_test3' in result3[1] def test_get_doc_variant():
64
64
161
6
58
carr-elagheb/moler
test/test_cmds_events_doc.py
Python
test_get_doc_variant
test_get_doc_variant
197
206
197
197
06ffeadd9b64113075314ec9a20645a0e80dc783
bigcode/the-stack
train
b6e6b88e035a4829c17c1b6c
train
function
def test_walk_moler_nonabstract_commands_raise_exception_when_called(fake_cmd): from moler.util.cmds_events_doc import _walk_moler_nonabstract_commands with mock.patch('moler.util.cmds_events_doc._walk_moler_commands', return_value=(None, fake_cmd)): with raises(Exception): next(_walk_moler...
def test_walk_moler_nonabstract_commands_raise_exception_when_called(fake_cmd):
from moler.util.cmds_events_doc import _walk_moler_nonabstract_commands with mock.patch('moler.util.cmds_events_doc._walk_moler_commands', return_value=(None, fake_cmd)): with raises(Exception): next(_walk_moler_nonabstract_commands(cmd_dir_under_test, Command))
) generator_obj = func_obj(method_param, base_class) file_list = _list_in_path(listing_type='allfiles') with raises(StopIteration): for _ in range(len(file_list)): next(generator_obj) def test_walk_moler_nonabstract_commands_raise_exception_when_called(fake_cmd):
64
64
80
15
49
carr-elagheb/moler
test/test_cmds_events_doc.py
Python
test_walk_moler_nonabstract_commands_raise_exception_when_called
test_walk_moler_nonabstract_commands_raise_exception_when_called
140
145
140
140
17b3339abc9fa38b814d4a78d2d91370a5144564
bigcode/the-stack
train
5b676c9ddf4dd4d87c532ca7
train
function
@mark.parametrize('func2test,method_param,base_class', [ ('_walk_moler_python_files', cmd_dir_under_test, Command), ('_walk_moler_commands', cmd_dir_under_test, Command), ('_walk_moler_nonabstract_commands', cmd_dir_under_test, Command)]) def test_genertors_return_files_without_dunder_init(func2test, method...
@mark.parametrize('func2test,method_param,base_class', [ ('_walk_moler_python_files', cmd_dir_under_test, Command), ('_walk_moler_commands', cmd_dir_under_test, Command), ('_walk_moler_nonabstract_commands', cmd_dir_under_test, Command)]) def test_genertors_return_files_without_dunder_init(func2test, method...
func_obj = _load_obj(func_name=func2test) generator_obj = func_obj(method_param, base_class) file_list = _list_in_path(listing_type='allfiles') with raises(StopIteration): for _ in range(len(file_list)): next(generator_obj)
@mark.parametrize('func2test,method_param,base_class', [ ('_walk_moler_python_files', cmd_dir_under_test, Command), ('_walk_moler_commands', cmd_dir_under_test, Command), ('_walk_moler_nonabstract_commands', cmd_dir_under_test, Command)]) def test_genertors_return_files_without_dunder_init(func2test, method...
84
64
146
84
0
carr-elagheb/moler
test/test_cmds_events_doc.py
Python
test_genertors_return_files_without_dunder_init
test_genertors_return_files_without_dunder_init
126
137
126
130
09b476204d0d59d825efbec42b4cd4bad8c64b2b
bigcode/the-stack
train
bb9220cec62e916b195bfaa7
train
function
def test_validate_documentation_consistency(): from moler.util.cmds_events_doc import _validate_documentation_consistency fake_cmd = import_module('conftest') test_data = {'_ver_test1': {'COMMAND_KWARGS': {}, 'COMMAND_RESULT': {}}, '_ver_test2': {'COMMAND_OUTPUT': '', 'COMMAND_RESULT': {}}...
def test_validate_documentation_consistency():
from moler.util.cmds_events_doc import _validate_documentation_consistency fake_cmd = import_module('conftest') test_data = {'_ver_test1': {'COMMAND_KWARGS': {}, 'COMMAND_RESULT': {}}, '_ver_test2': {'COMMAND_OUTPUT': '', 'COMMAND_RESULT': {}}, '_ver_test3': {'COMMAND_OUTP...
est') test_data = {'_ver_execute': {'COMMAND_OUTPUT': '', 'COMMAND_KWARGS': {}, 'COMMAND_RESULT': {}}, '_ver_test': {'COMMAND_OUTPUT': '', 'COMMAND_KWARGS': {}, 'COMMAND_RESULT': {}}} assert _validate_documentation_existence(fake_cmd, test_data, "COMMAND") == '' missing = _validate_docume...
127
127
425
8
118
carr-elagheb/moler
test/test_cmds_events_doc.py
Python
test_validate_documentation_consistency
test_validate_documentation_consistency
172
194
172
172
16bb3961ce97e92978dacb2104d2b56dce6a5ca3
bigcode/the-stack
train
e74b900a7428608c519bec43
train
function
def test_retrieve_command_documentation_as_dict(): from moler.util.cmds_events_doc import _retrieve_command_documentation fake_cmd_from_conftest = _retrieve_command_documentation(import_module('conftest'), "COMMAND") assert isinstance(fake_cmd_from_conftest, dict) assert isinstance(fake_cmd_from_confte...
def test_retrieve_command_documentation_as_dict():
from moler.util.cmds_events_doc import _retrieve_command_documentation fake_cmd_from_conftest = _retrieve_command_documentation(import_module('conftest'), "COMMAND") assert isinstance(fake_cmd_from_conftest, dict) assert isinstance(fake_cmd_from_conftest['_ver_nice'], dict) assert isinstance(fake_c...
walk_moler_nonabstract_commands with mock.patch('moler.util.cmds_events_doc._walk_moler_commands', return_value=(None, fake_cmd)): with raises(Exception): next(_walk_moler_nonabstract_commands(cmd_dir_under_test, Command)) def test_retrieve_command_documentation_as_dict():
64
64
136
10
54
carr-elagheb/moler
test/test_cmds_events_doc.py
Python
test_retrieve_command_documentation_as_dict
test_retrieve_command_documentation_as_dict
148
156
148
148
7353bef7c8f5faa67235e02f728daeb454ea6caf
bigcode/the-stack
train
85620b382533f4cffd1a84d3
train
function
def test_walk_moler_commands_is_generator_return_all_files_in_dir(): from moler.util.cmds_events_doc import _walk_moler_commands from six.moves import zip file_list = _list_in_path(listing_type='only_py') abs_test_path = join(repo_path, cmd_dir_under_test) walker = _walk_moler_commands(abs_test_pa...
def test_walk_moler_commands_is_generator_return_all_files_in_dir():
from moler.util.cmds_events_doc import _walk_moler_commands from six.moves import zip file_list = _list_in_path(listing_type='only_py') abs_test_path = join(repo_path, cmd_dir_under_test) walker = _walk_moler_commands(abs_test_path, Command) list_from_generator = [] for cmd, file in zip(w...
_in_path(listing_type='fullpath') walker = _walk_moler_python_files(abs_test_path) list_from_generator = [] for file in walker: list_from_generator.append(file) assert list_from_generator == file_list def test_walk_moler_commands_is_generator_return_all_files_in_dir():
64
64
127
14
49
carr-elagheb/moler
test/test_cmds_events_doc.py
Python
test_walk_moler_commands_is_generator_return_all_files_in_dir
test_walk_moler_commands_is_generator_return_all_files_in_dir
109
123
109
109
6d912f000c67d52ce4b16f85cec2d05e0faf10a2
bigcode/the-stack
train
871847f888aee87bf2ab4972
train
function
def test_walk_moler_python_files_is_generator_return_all_files_in_dir(): from moler.util.cmds_events_doc import _walk_moler_python_files abs_test_path = join(repo_path, cmd_dir_under_test) file_list = _list_in_path(listing_type='fullpath') walker = _walk_moler_python_files(abs_test_path) list_fro...
def test_walk_moler_python_files_is_generator_return_all_files_in_dir():
from moler.util.cmds_events_doc import _walk_moler_python_files abs_test_path = join(repo_path, cmd_dir_under_test) file_list = _list_in_path(listing_type='fullpath') walker = _walk_moler_python_files(abs_test_path) list_from_generator = [] for file in walker: list_from_generator.appe...
function func_obj = _load_obj(func_name=func2test) generator_obj = func_obj(method_param, base_class) assert isgeneratorfunction(func_obj) is expected assert isgenerator(generator_obj) is expected def test_walk_moler_python_files_is_generator_return_all_files_in_dir():
64
64
102
15
48
carr-elagheb/moler
test/test_cmds_events_doc.py
Python
test_walk_moler_python_files_is_generator_return_all_files_in_dir
test_walk_moler_python_files_is_generator_return_all_files_in_dir
95
106
95
95
40486e34c6cdee8cdf755ab7cab73d8206a3a46c
bigcode/the-stack
train
ad8cd4400b4fe2ecefd3f008
train
function
def test_run_command_parsing_test_success(nice_cmd): # ToDo: not finished from moler.util.cmds_events_doc import _run_command_parsing_test, _buffer_connection, _get_doc_variant, _create_command buffer_io = _buffer_connection() variant = '_ver_nice' test_data = { variant: {'COMMAND_OUTPUT': '...
def test_run_command_parsing_test_success(nice_cmd): # ToDo: not finished
from moler.util.cmds_events_doc import _run_command_parsing_test, _buffer_connection, _get_doc_variant, _create_command buffer_io = _buffer_connection() variant = '_ver_nice' test_data = { variant: {'COMMAND_OUTPUT': 'nice', 'COMMAND_KWARGS': {'nice': 'nice'}, 'COMMAND_RESULT': {'nice': 'nice'}}...
(nice_cmd, _buffer_connection().moler_connection, {'nice': 'nice'}) assert isinstance(result[0], nice_cmd) assert result[1] == 'NiceCommand(nice=nice)' def test_run_command_parsing_test_success(nice_cmd): # ToDo: not finished
63
64
180
20
43
carr-elagheb/moler
test/test_cmds_events_doc.py
Python
test_run_command_parsing_test_success
test_run_command_parsing_test_success
227
237
227
228
69ceaedba55ce53444f93e38e90507c9155b0bb2
bigcode/the-stack
train
d9aa85bb3ac9e85e79dec82c
train
function
def test_create_command_success(nice_cmd): from moler.util.cmds_events_doc import _create_command, _buffer_connection result = _create_command(nice_cmd, _buffer_connection().moler_connection, {'nice': 'nice'}) assert isinstance(result[0], nice_cmd) assert result[1] == 'NiceCommand(nice=nice)'
def test_create_command_success(nice_cmd):
from moler.util.cmds_events_doc import _create_command, _buffer_connection result = _create_command(nice_cmd, _buffer_connection().moler_connection, {'nice': 'nice'}) assert isinstance(result[0], nice_cmd) assert result[1] == 'NiceCommand(nice=nice)'
) as exc: _create_command(fake_cmd, _buffer_connection().moler_connection, {}) assert "via FakeCommand() : object() takes no parameters" or "via FakeCommand() : this constructor takes no arguments" in str( exc.value) def test_create_command_success(nice_cmd):
64
64
76
9
55
carr-elagheb/moler
test/test_cmds_events_doc.py
Python
test_create_command_success
test_create_command_success
219
224
219
219
6ee9a3117d112127bfe9909cb1bb71d44bc35009
bigcode/the-stack
train
d3c7474cd09d4b7e81d52a99
train
function
def bias_and_activation(x,b = None, activation = ''): if b is not None: x = tf.nn.bias_add(x, b) if activation == 'relu': x = tf.nn.relu(x) return x
def bias_and_activation(x,b = None, activation = ''):
if b is not None: x = tf.nn.bias_add(x, b) if activation == 'relu': x = tf.nn.relu(x) return x
d(x, w, strides=[1, strides, strides, 1], padding=padding, dilations=dilations) s = sx * weight_scale x = x * s return x, x_max, x_min def bias_and_activation(x,b = None, activation = ''):
64
64
50
13
50
krishnateja95/Quantization-Test_bed
Vgg16.py
Python
bias_and_activation
bias_and_activation
40
45
40
40
4f4c6cee2f6b6cf14ca046fd9d6e97ffa439845f
bigcode/the-stack
train