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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
19c120c764fcbf0779c92928 | train | function | def angular_checker(d):
script = """
if(
!!window.angular ||
!!document.querySelector('script[src*="angular.js"], script[src*="angular.min.js"]') ||
document.querySelector('.ng-binding, [ng-app], [data-ng-app], [ng-controller], [data-ng-controller], [ng-repeat], [data-ng-repeat]')
)
{
... | def angular_checker(d):
| script = """
if(
!!window.angular ||
!!document.querySelector('script[src*="angular.js"], script[src*="angular.min.js"]') ||
document.querySelector('.ng-binding, [ng-app], [data-ng-app], [ng-controller], [data-ng-controller], [ng-repeat], [data-ng-repeat]')
)
{
return true;
} el... | (d):
script = """
if(!!window.%s)
{
return true;
} else {
return false;
}
""" % framework
o = d.execute_script(script)
d.implicitly_wait(1)
return o
return fun
def angular_checker(d):
| 64 | 64 | 115 | 5 | 58 | mmalter/x_is_dead | x_is_dead/frameworks.py | Python | angular_checker | angular_checker | 16 | 32 | 16 | 16 | fef43e661b89f218aa04d6d35ab0a4b77d766a84 | bigcode/the-stack | train |
421e04932d3d99df79ca849e | train | function | def react_checker(d):
script = """
if(
!!window.React ||
!!document.querySelector('[data-reactroot], [data-reactid]')
)
{
return true;
} else {
return false;
}
"""
o = d.execute_script(script)
d.implicitly_wait(1)
return o
| def react_checker(d):
| script = """
if(
!!window.React ||
!!document.querySelector('[data-reactroot], [data-reactid]')
)
{
return true;
} else {
return false;
}
"""
o = d.execute_script(script)
d.implicitly_wait(1)
return o
| ], [ng-controller], [data-ng-controller], [ng-repeat], [data-ng-repeat]')
)
{
return true;
} else {
return false;
}
"""
o = d.execute_script(script)
d.implicitly_wait(1)
return o
def react_checker(d):
| 64 | 64 | 72 | 5 | 58 | mmalter/x_is_dead | x_is_dead/frameworks.py | Python | react_checker | react_checker | 34 | 49 | 34 | 34 | 48616aaaac62b7a1b8702f628bfc0497a02dcbcd | bigcode/the-stack | train |
c8f525aff3e264fa99bf18b2 | train | function | def default_checker(framework):
def fun(d):
script = """
if(!!window.%s)
{
return true;
} else {
return false;
}
""" % framework
o = d.execute_script(script)
d.implicitly_wait(1)
return o
return fun
| def default_checker(framework):
| def fun(d):
script = """
if(!!window.%s)
{
return true;
} else {
return false;
}
""" % framework
o = d.execute_script(script)
d.implicitly_wait(1)
return o
return fun
| def default_checker(framework):
| 6 | 64 | 68 | 6 | 0 | mmalter/x_is_dead | x_is_dead/frameworks.py | Python | default_checker | default_checker | 1 | 14 | 1 | 1 | 56efe66e2e13ed267db032cda6c794249c7cbfb9 | bigcode/the-stack | train |
e26dd1c55c5df974f42e0baf | train | function | @typed
def expect_iterable_of_ints(a: Iterable[int]):
pass
| @typed
def expect_iterable_of_ints(a: Iterable[int]):
| pass
| from typing import Iterable
from unittest import TestCase
from runtime_typing import typed, RuntimeTypingError
@typed
def expect_iterable(a: Iterable):
pass
@typed
def expect_iterable_of_ints(a: Iterable[int]):
| 51 | 64 | 18 | 15 | 35 | jonathan-scholbach/runtime_typing | tests/test_types/test_iterable.py | Python | expect_iterable_of_ints | expect_iterable_of_ints | 12 | 14 | 12 | 13 | 365cedda417819ef1de3cf2544cd586ccea4260c | bigcode/the-stack | train |
01ab667d64cbe2a4d0f8dda7 | train | class | class TestIterable(TestCase):
def test_expect_iterable(self):
with self.assertRaises(TypeError):
expect_iterable()
with self.assertRaises(RuntimeTypingError):
expect_iterable(1)
expect_iterable([1, 2, 3])
expect_iterable((1, 2, 3))
expect_iterable({1... | class TestIterable(TestCase):
| def test_expect_iterable(self):
with self.assertRaises(TypeError):
expect_iterable()
with self.assertRaises(RuntimeTypingError):
expect_iterable(1)
expect_iterable([1, 2, 3])
expect_iterable((1, 2, 3))
expect_iterable({1, 2, 3})
expect_iterab... | from typing import Iterable
from unittest import TestCase
from runtime_typing import typed, RuntimeTypingError
@typed
def expect_iterable(a: Iterable):
pass
@typed
def expect_iterable_of_ints(a: Iterable[int]):
pass
class TestIterable(TestCase):
| 60 | 64 | 202 | 6 | 53 | jonathan-scholbach/runtime_typing | tests/test_types/test_iterable.py | Python | TestIterable | TestIterable | 17 | 41 | 17 | 17 | c079e2dcda9be9efe33e5712b0565c5b56f8b130 | bigcode/the-stack | train |
b5d45ededaf8d6742ed50598 | train | function | @typed
def expect_iterable(a: Iterable):
pass
| @typed
def expect_iterable(a: Iterable):
| pass
| from typing import Iterable
from unittest import TestCase
from runtime_typing import typed, RuntimeTypingError
@typed
def expect_iterable(a: Iterable):
| 33 | 64 | 14 | 11 | 21 | jonathan-scholbach/runtime_typing | tests/test_types/test_iterable.py | Python | expect_iterable | expect_iterable | 7 | 9 | 7 | 8 | eb22aefc0dd1208791de005c25dc8794526b0850 | bigcode/the-stack | train |
a3618e2f724ec3876e89de5f | train | class | class MsMarcoConfig(nlp.BuilderConfig):
"""BuilderConfig for MS MARCO."""
def __init__(self, **kwargs):
"""BuilderConfig for MS MARCO
Args:
**kwargs: keyword arguments forwarded to super.
"""
super(MsMarcoConfig, self).__init__(**kwargs)
| class MsMarcoConfig(nlp.BuilderConfig):
| """BuilderConfig for MS MARCO."""
def __init__(self, **kwargs):
"""BuilderConfig for MS MARCO
Args:
**kwargs: keyword arguments forwarded to super.
"""
super(MsMarcoConfig, self).__init__(**kwargs)
| dev": "https://msmarco.blob.core.windows.net/msmsarcov1/dev_v1.1.json.gz",
"test": "https://msmarco.blob.core.windows.net/msmsarcov1/test_hidden_v1.1.json",
}
class MsMarcoConfig(nlp.BuilderConfig):
| 64 | 64 | 66 | 9 | 55 | yonigottesman/nlp | datasets/ms_marco/ms_marco.py | Python | MsMarcoConfig | MsMarcoConfig | 81 | 90 | 81 | 81 | 5342da8f4d666f345a1a18176a3bfbc7a8a07014 | bigcode/the-stack | train |
93be075d8d7a632487d679e1 | train | class | class MsMarco(nlp.GeneratorBasedBuilder):
BUILDER_CONFIGS = [
MsMarcoConfig(
name="v1.1",
description="""version v1.1""",
version=nlp.Version("1.1.0", "New split API (https://tensorflow.org/datasets/splits)"),
),
MsMarcoConfig(
name="v2.1",
... | class MsMarco(nlp.GeneratorBasedBuilder):
| BUILDER_CONFIGS = [
MsMarcoConfig(
name="v1.1",
description="""version v1.1""",
version=nlp.Version("1.1.0", "New split API (https://tensorflow.org/datasets/splits)"),
),
MsMarcoConfig(
name="v2.1",
description="""version v2.1""",
... | .
"""
_V2_URLS = {
"train": "https://msmarco.blob.core.windows.net/msmarco/train_v2.1.json.gz",
"dev": "https://msmarco.blob.core.windows.net/msmarco/dev_v2.1.json.gz",
"test": "https://msmarco.blob.core.windows.net/msmarco/eval_v2.1_public.json.gz",
}
_V1_URLS = {
"train": "https://msmarco.blob.core.... | 256 | 256 | 959 | 10 | 246 | yonigottesman/nlp | datasets/ms_marco/ms_marco.py | Python | MsMarco | MsMarco | 93 | 196 | 93 | 94 | 50ba159180fb9e13670f58d74177569643d9e5a7 | bigcode/the-stack | train |
dc22cc411bac1f6fea929c46 | train | function | def FDST_collate_multibatch(batch):
transposed = list(zip(*batch)) # imgs and dens
imgs, dens = [transposed[0], transposed[1]]
error_msg = "batch must contain tensors; found {}"
if isinstance(imgs[0], torch.Tensor) and isinstance(dens[0], torch.Tensor):
min_ht, min_wd = get_min_size(imgs)
... | def FDST_collate_multibatch(batch):
| transposed = list(zip(*batch)) # imgs and dens
imgs, dens = [transposed[0], transposed[1]]
error_msg = "batch must contain tensors; found {}"
if isinstance(imgs[0], torch.Tensor) and isinstance(dens[0], torch.Tensor):
min_ht, min_wd = get_min_size(imgs)
cropped_imgs = []
cropp... | , label_x1:label_x2]
def share_memory(batch):
out = None
if False:
# If we're in a background process, concatenate directly into a
# shared memory tensor to avoid an extra copy
numel = sum([x.numel() for x in batch])
storage = batch[0].storage()._new_shared(numel)
out =... | 102 | 102 | 340 | 10 | 91 | Fang-Lansheng/C-3-Framework | datasets/FDST/loading_data.py | Python | FDST_collate_multibatch | FDST_collate_multibatch | 53 | 83 | 53 | 53 | b482e7ae026e8812c10e63ca00b0770d4e03e608 | bigcode/the-stack | train |
c2e674c06998d579da4fddd3 | train | function | def loading_data():
mean_std = cfg_data.MEAN_STD
log_para = cfg_data.LOG_PARA
train_main_transform = own_transforms.Compose([
own_transforms.RandomHorizontallyFlip()
])
img_transform = standard_transforms.Compose([
standard_transforms.ToTensor(),
standard_transforms.Normalize... | def loading_data():
| mean_std = cfg_data.MEAN_STD
log_para = cfg_data.LOG_PARA
train_main_transform = own_transforms.Compose([
own_transforms.RandomHorizontallyFlip()
])
img_transform = standard_transforms.Compose([
standard_transforms.ToTensor(),
standard_transforms.Normalize(*mean_std)
])
... | img)
# cropped_dens.append(_den)
#
#
# cropped_imgs = torch.stack(cropped_imgs, 0, out=share_memory(cropped_imgs))
# cropped_dens = torch.stack(cropped_dens, 0, out=share_memory(cropped_dens))
#
# return [cropped_imgs,cropped_dens]
#
# raise TypeError((error_msg.format(type(batch... | 93 | 93 | 313 | 4 | 89 | Fang-Lansheng/C-3-Framework | datasets/FDST/loading_data.py | Python | loading_data | loading_data | 144 | 187 | 144 | 144 | 42e6dcb7b7e221b3ee1f1056f6b7fbcb61f88891 | bigcode/the-stack | train |
25dbc9970f2dd79589da3fac | train | function | def random_crop(img, den, dst_size):
# dst_size: ht, wd
_, ts_hd, ts_wd = img.shape
x1 = random.randint(0, ts_wd - dst_size[1]) // cfg_data.LABEL_FACTOR * cfg_data.LABEL_FACTOR
y1 = random.randint(0, ts_hd - dst_size[0]) // cfg_data.LABEL_FACTOR * cfg_data.LABEL_FACTOR
x2 = x1 + dst_size[1]
y2... | def random_crop(img, den, dst_size):
# dst_size: ht, wd
| _, ts_hd, ts_wd = img.shape
x1 = random.randint(0, ts_wd - dst_size[1]) // cfg_data.LABEL_FACTOR * cfg_data.LABEL_FACTOR
y1 = random.randint(0, ts_hd - dst_size[0]) // cfg_data.LABEL_FACTOR * cfg_data.LABEL_FACTOR
x2 = x1 + dst_size[1]
y2 = y1 + dst_size[0]
label_x1 = x1 // cfg_data.LABEL_FACT... | ht, wd = i_sample.shape
if ht < min_ht:
min_ht = ht
if wd < min_wd:
min_wd = wd
return min_ht, min_wd
def random_crop(img, den, dst_size):
# dst_size: ht, wd
| 64 | 64 | 203 | 19 | 44 | Fang-Lansheng/C-3-Framework | datasets/FDST/loading_data.py | Python | random_crop | random_crop | 24 | 39 | 24 | 26 | eca92fb79accd20cecd6cce909b346e7101af0a6 | bigcode/the-stack | train |
05c82ac306f09354b8ae560d | train | function | def share_memory(batch):
out = None
if False:
# If we're in a background process, concatenate directly into a
# shared memory tensor to avoid an extra copy
numel = sum([x.numel() for x in batch])
storage = batch[0].storage()._new_shared(numel)
out = batch[0].new(storage)
... | def share_memory(batch):
| out = None
if False:
# If we're in a background process, concatenate directly into a
# shared memory tensor to avoid an extra copy
numel = sum([x.numel() for x in batch])
storage = batch[0].storage()._new_shared(numel)
out = batch[0].new(storage)
return out
| label_x2 = x2 // cfg_data.LABEL_FACTOR
label_y2 = y2 // cfg_data.LABEL_FACTOR
return img[:, y1:y2, x1:x2], den[label_y1:label_y2, label_x1:label_x2]
def share_memory(batch):
| 64 | 64 | 83 | 5 | 59 | Fang-Lansheng/C-3-Framework | datasets/FDST/loading_data.py | Python | share_memory | share_memory | 42 | 50 | 42 | 42 | b76caa5d6051eea411ecc4d998da22e10d108300 | bigcode/the-stack | train |
2c1c1547d4b4d9286234695b | train | function | def FDST_collate_onebatch(batch):
transposed = list(zip(*batch)) # imgs and dens
imgs, dens = [transposed[0], transposed[1]]
error_msg = "batch must contain tensors; found {}"
if isinstance(imgs[0], torch.Tensor) and isinstance(dens[0], torch.Tensor):
cropped_imgs = []
cropped_dens = ... | def FDST_collate_onebatch(batch):
| transposed = list(zip(*batch)) # imgs and dens
imgs, dens = [transposed[0], transposed[1]]
error_msg = "batch must contain tensors; found {}"
if isinstance(imgs[0], torch.Tensor) and isinstance(dens[0], torch.Tensor):
cropped_imgs = []
cropped_dens = []
for i_sample in range(l... | cropped_imgs = torch.stack(cropped_imgs, 0, out=share_memory(cropped_imgs))
cropped_dens = torch.stack(cropped_dens, 0, out=share_memory(cropped_dens))
return [cropped_imgs, cropped_dens]
raise TypeError((error_msg.format(type(batch[0]))))
def FDST_collate_onebatch(batch):
| 78 | 78 | 262 | 9 | 69 | Fang-Lansheng/C-3-Framework | datasets/FDST/loading_data.py | Python | FDST_collate_onebatch | FDST_collate_onebatch | 86 | 112 | 86 | 86 | 1d570960f720656d24aeed03680098bc752525d5 | bigcode/the-stack | train |
dd8bdfc5fc0b7a57aae541cc | train | function | def get_min_size(batch):
min_ht = cfg_data.TRAIN_SIZE[0]
min_wd = cfg_data.TRAIN_SIZE[1]
for i_sample in batch:
_, ht, wd = i_sample.shape
if ht < min_ht:
min_ht = ht
if wd < min_wd:
min_wd = wd
return min_ht, min_wd
| def get_min_size(batch):
| min_ht = cfg_data.TRAIN_SIZE[0]
min_wd = cfg_data.TRAIN_SIZE[1]
for i_sample in batch:
_, ht, wd = i_sample.shape
if ht < min_ht:
min_ht = ht
if wd < min_wd:
min_wd = wd
return min_ht, min_wd
| import torchvision.transforms as standard_transforms
from torch.utils.data import DataLoader
import misc.transforms as own_transforms
from .FDST import FDST
from .setting import cfg_data
import torch
import random
def get_min_size(batch):
| 51 | 64 | 85 | 6 | 44 | Fang-Lansheng/C-3-Framework | datasets/FDST/loading_data.py | Python | get_min_size | get_min_size | 10 | 21 | 10 | 10 | de6c691ebea902da871fb3468c79407ceb16b004 | bigcode/the-stack | train |
582394f9ebdad0fea2c04c5b | train | class | class Migration(migrations.Migration):
dependencies = [
('correlator', '0004_auto_20191120_2024'),
]
operations = [
migrations.RemoveField(
model_name='correlator',
name='type',
),
]
| class Migration(migrations.Migration):
| dependencies = [
('correlator', '0004_auto_20191120_2024'),
]
operations = [
migrations.RemoveField(
model_name='correlator',
name='type',
),
]
| # Generated by Django 2.2.5 on 2019-11-22 23:19
from django.db import migrations
class Migration(migrations.Migration):
| 36 | 64 | 57 | 7 | 28 | callat-qcd/lattedb | lattedb/correlator/migrations/0005_remove_correlator_type.py | Python | Migration | Migration | 6 | 17 | 6 | 7 | 6471392e1acce14dda77493c953358988d7cb564 | bigcode/the-stack | train |
3e54ce470995ad930eebf100 | train | class | class TestAPPO(unittest.TestCase):
@classmethod
def setUpClass(cls):
ray.init()
@classmethod
def tearDownClass(cls):
ray.shutdown()
def test_appo_compilation(self):
"""Test whether an APPOTrainer can be built with both frameworks."""
config = ppo.appo.DEFAULT_CONFIG... | class TestAPPO(unittest.TestCase):
@classmethod
| def setUpClass(cls):
ray.init()
@classmethod
def tearDownClass(cls):
ray.shutdown()
def test_appo_compilation(self):
"""Test whether an APPOTrainer can be built with both frameworks."""
config = ppo.appo.DEFAULT_CONFIG.copy()
config["num_workers"] = 1
nu... | unittest
import ray
import ray.rllib.agents.ppo as ppo
from ray.rllib.utils.framework import try_import_tf
from ray.rllib.utils.test_utils import check_compute_single_action, \
framework_iterator
tf = try_import_tf()
class TestAPPO(unittest.TestCase):
@classmethod
| 64 | 64 | 212 | 12 | 52 | acmore/ray | rllib/agents/ppo/tests/test_appo.py | Python | TestAPPO | TestAPPO | 12 | 39 | 12 | 13 | 2eaaded4c74aa13126522d2d6d895cd97ea43d18 | bigcode/the-stack | train |
4ba79ef927062ba0f3fa4fab | train | function | @pytest.mark.parametrize("scene", _test_scenes)
def test_semantic_scene(scene, make_cfg_settings):
if not osp.exists(scene):
pytest.skip("Skipping {}".format(scene))
make_cfg_settings = {k: v for k, v in make_cfg_settings.items()}
make_cfg_settings["semantic_sensor"] = False
make_cfg_settings["... | @pytest.mark.parametrize("scene", _test_scenes)
def test_semantic_scene(scene, make_cfg_settings):
| if not osp.exists(scene):
pytest.skip("Skipping {}".format(scene))
make_cfg_settings = {k: v for k, v in make_cfg_settings.items()}
make_cfg_settings["semantic_sensor"] = False
make_cfg_settings["scene"] = scene
cfg = make_cfg(make_cfg_settings)
cfg.agents[0].sensor_specifications = []
... | (__file__),
"../data/scene_datasets/mp3d/ur6pFq6Qu1A/ur6pFq6Qu1A.glb",
)
),
]
@pytest.mark.parametrize("scene", _test_scenes)
def test_semantic_scene(scene, make_cfg_settings):
| 64 | 64 | 194 | 22 | 42 | narekvslife/habitat-sim | tests/test_semantic_scene.py | Python | test_semantic_scene | test_semantic_scene | 32 | 60 | 32 | 33 | 541d75cb19cd9f7a117529ecfe269456b1bd1c3d | bigcode/the-stack | train |
6f30b36dfc2d080d982e475b | train | function | def main():
starttime = time.time()
parser = set_up_parser()
(options, args) = parser.parse_args()
if len(args) < 1:
print("ERROR: you must give a CNF input file as a parameter")
exit(-1)
inputfile = args[0]
indvars = mis(inputfile, options.outputfile, options.useind, options.... | def main():
| starttime = time.time()
parser = set_up_parser()
(options, args) = parser.parse_args()
if len(args) < 1:
print("ERROR: you must give a CNF input file as a parameter")
exit(-1)
inputfile = args[0]
indvars = mis(inputfile, options.outputfile, options.useind, options.maxiter,
... | gmusFile))
return min_indvars
def parseOutput(fileName):
with open(fileName, 'r') as f:
lines = f.readlines()
f.close()
for line in lines:
if (line.strip().startswith('v')):
return line
return ''
def main():
| 64 | 64 | 177 | 3 | 61 | marcionicolau/mis | mis.py | Python | main | main | 149 | 166 | 149 | 149 | 50ee6a8cee986810eb88e35630930b9a52220bc2 | bigcode/the-stack | train |
2b40faa363eba383ac50e227 | train | function | def mis(inputfile=None, outputfile=None, useind=False, maxiter=1, use_glucose=False,
muser2_bin=PATH+"/muser2-dir/src/tools/muser2/muser2", timeout=0, verbosity=0,
noclean=False):
if outputfile is None:
outputfile = inputfile + ".ind"
mytime = time.time()
gmusFile = outputfile +... | def mis(inputfile=None, outputfile=None, useind=False, maxiter=1, use_glucose=False,
muser2_bin=PATH+"/muser2-dir/src/tools/muser2/muser2", timeout=0, verbosity=0,
noclean=False):
| if outputfile is None:
outputfile = inputfile + ".ind"
mytime = time.time()
gmusFile = outputfile + '.gcnf'
tempOutFile = outputfile + '.tcnf'
togmus_cmd = "%s/togmus %s %s %s" % (PATH, inputfile, gmusFile, useind)
if verbosity > 0:
print("Running togmus: '%s'" % togmus_cmd... | Default: 'inputfile.ind'")
parser.add_option("--maxiter", dest="maxiter", type=int, default=1,
help="up to 'max' number of minimal independent supports will be generated. Default: %default")
parser.add_option("--useind", dest="useind", action="store_true",
default=Fa... | 224 | 224 | 748 | 58 | 165 | marcionicolau/mis | mis.py | Python | mis | mis | 63 | 138 | 63 | 65 | 2977609028117bb53225be3665c9416f7870c2cf | bigcode/the-stack | train |
5c7e3c96c82e64eb2b4c8444 | train | function | def parseOutput(fileName):
with open(fileName, 'r') as f:
lines = f.readlines()
f.close()
for line in lines:
if (line.strip().startswith('v')):
return line
return ''
| def parseOutput(fileName):
| with open(fileName, 'r') as f:
lines = f.readlines()
f.close()
for line in lines:
if (line.strip().startswith('v')):
return line
return ''
| os.unlink(tempOutFile)
os.unlink(gmusFile)
else:
if verbosity > 1:
print("noclean selected")
print("Leaving temporary files:\n%s\n%s" % (tempOutFile, gmusFile))
return min_indvars
def parseOutput(fileName):
| 64 | 64 | 51 | 6 | 57 | marcionicolau/mis | mis.py | Python | parseOutput | parseOutput | 140 | 147 | 140 | 140 | bbb119542447366b394ef4b9f389a548ee4869fd | bigcode/the-stack | train |
d3187a9d504d3a754052f412 | train | function | def set_up_parser():
parser = optparse.OptionParser(usage=usage, description=desc)
parser.add_option("--timeout", metavar="TOUT", dest="timeout", type=int,
default=0, help="timeout for each iteration in seconds. Default: %default. 0 = no timeout")
parser.add_option("-v", default=0, typ... | def set_up_parser():
| parser = optparse.OptionParser(usage=usage, description=desc)
parser.add_option("--timeout", metavar="TOUT", dest="timeout", type=int,
default=0, help="timeout for each iteration in seconds. Default: %default. 0 = no timeout")
parser.add_option("-v", default=0, type=int,
de... | if we're imported elsewhere, make local binaries find-able
PATH = sys.modules[__name__].__file__
PATH = PATH[:PATH.index("/mis.py")]
except:
# otherwise, we're being run directly. Assume togmus & muser2 are available
PATH = "."
usage = "usage: %prog [options] <input.cnf>"
desc = """Gives the minimal i... | 96 | 96 | 323 | 5 | 91 | marcionicolau/mis | mis.py | Python | set_up_parser | set_up_parser | 41 | 61 | 41 | 41 | 39ca9771c8d4b2718f158a9eecf7bdf692a45f9b | bigcode/the-stack | train |
c8dba851c8a379bb5832cca0 | train | class | class TestDtSampler:
batch_size = 13
def test_get_params_dict(self, dt_sampler):
param_dict = dt_sampler.get_params_dict()
assert isinstance(param_dict, dict)
assert "dt" in param_dict
assert "critic_score" in param_dict
assert "dtype" in param_dict["dt"]
def test_... | class TestDtSampler:
| batch_size = 13
def test_get_params_dict(self, dt_sampler):
param_dict = dt_sampler.get_params_dict()
assert isinstance(param_dict, dict)
assert "dt" in param_dict
assert "critic_score" in param_dict
assert "dtype" in param_dict["dt"]
def test_calculate(self, dt_sam... | _dt():
return UniformDt(min_dt=1, max_dt=3)
dt_samplers = [constant_dt, gaussian_dt, uniform_dt]
@pytest.fixture(params=dt_samplers, scope="class")
def dt_sampler(request) -> BaseDtSampler:
return request.param()
class TestDtSampler:
| 64 | 64 | 187 | 5 | 59 | sergio-hcsoft/fragile-1 | tests/core/test_dt_sampler.py | Python | TestDtSampler | TestDtSampler | 28 | 49 | 28 | 29 | fb5e523438062b319c0ee00edd333771e1e0539e | bigcode/the-stack | train |
b5fe7a99e60f5ca74ee00ec9 | train | function | @pytest.fixture(params=dt_samplers, scope="class")
def dt_sampler(request) -> BaseDtSampler:
return request.param()
| @pytest.fixture(params=dt_samplers, scope="class")
def dt_sampler(request) -> BaseDtSampler:
| return request.param()
| =3, scale_dt=0)
def uniform_dt():
return UniformDt(min_dt=1, max_dt=3)
dt_samplers = [constant_dt, gaussian_dt, uniform_dt]
@pytest.fixture(params=dt_samplers, scope="class")
def dt_sampler(request) -> BaseDtSampler:
| 64 | 64 | 28 | 23 | 41 | sergio-hcsoft/fragile-1 | tests/core/test_dt_sampler.py | Python | dt_sampler | dt_sampler | 23 | 25 | 23 | 24 | 322b2f0cf23301473e0fd41058366364353c863d | bigcode/the-stack | train |
d8c23ac20c7ecf86d9fb26f8 | train | function | def gaussian_dt():
return GaussianDt(min_dt=1, max_dt=10, loc_dt=3, scale_dt=0)
| def gaussian_dt():
| return GaussianDt(min_dt=1, max_dt=10, loc_dt=3, scale_dt=0)
| import numpy
import pytest
from fragile.core.dt_samplers import BaseDtSampler, ConstantDt, GaussianDt, UniformDt
from fragile.core.states import States
def constant_dt():
return ConstantDt(2)
def gaussian_dt():
| 49 | 64 | 28 | 4 | 45 | sergio-hcsoft/fragile-1 | tests/core/test_dt_sampler.py | Python | gaussian_dt | gaussian_dt | 12 | 13 | 12 | 12 | 38c9cc977cab923e031dd9d3a14e2afd9c764295 | bigcode/the-stack | train |
07a7c1e30394111eaaf68c56 | train | function | def uniform_dt():
return UniformDt(min_dt=1, max_dt=3)
| def uniform_dt():
| return UniformDt(min_dt=1, max_dt=3)
| import BaseDtSampler, ConstantDt, GaussianDt, UniformDt
from fragile.core.states import States
def constant_dt():
return ConstantDt(2)
def gaussian_dt():
return GaussianDt(min_dt=1, max_dt=10, loc_dt=3, scale_dt=0)
def uniform_dt():
| 64 | 64 | 18 | 4 | 60 | sergio-hcsoft/fragile-1 | tests/core/test_dt_sampler.py | Python | uniform_dt | uniform_dt | 16 | 17 | 16 | 16 | 6ba5367952da2b0eb925663e54503f70c0a61c45 | bigcode/the-stack | train |
f5dc559771d38565b0679556 | train | function | def constant_dt():
return ConstantDt(2)
| def constant_dt():
| return ConstantDt(2)
| import numpy
import pytest
from fragile.core.dt_samplers import BaseDtSampler, ConstantDt, GaussianDt, UniformDt
from fragile.core.states import States
def constant_dt():
| 38 | 64 | 11 | 4 | 33 | sergio-hcsoft/fragile-1 | tests/core/test_dt_sampler.py | Python | constant_dt | constant_dt | 8 | 9 | 8 | 8 | dde662c4b32eab062ed3c54eb2c5546b65f6206b | bigcode/the-stack | train |
3a18e627805e59712304deda | train | class | class PCoATests(unittest.TestCase):
def setUp(self):
axes = ['PC1', 'PC2', 'PC3', 'PC4', 'PC5', 'PC6']
eigvals = pd.Series(np.array([1.5, 0.75, 0.3, 0.15, 0.15, 0.15]),
index=axes)
samples = np.array([[0, 3, 4, 4, 0, 0],
[1, 2, 1, 4, 3... | class PCoATests(unittest.TestCase):
| def setUp(self):
axes = ['PC1', 'PC2', 'PC3', 'PC4', 'PC5', 'PC6']
eigvals = pd.Series(np.array([1.5, 0.75, 0.3, 0.15, 0.15, 0.15]),
index=axes)
samples = np.array([[0, 3, 4, 4, 0, 0],
[1, 2, 1, 4, 3, 3],
[2,... | # ----------------------------------------------------------------------------
# Copyright (c) 2016-2020, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... | 92 | 256 | 1,275 | 9 | 82 | ChrisKeefe/q2-diversity | q2_diversity/tests/test_procrustes.py | Python | PCoATests | PCoATests | 18 | 114 | 18 | 19 | 5d1cd5d71eeb03e0c05e3374886b343fa668b727 | bigcode/the-stack | train |
681075e3a8cd302e6b86b6e3 | train | class | class BitfinexGateway(BaseGateway):
"""
VN Trader Gateway for bitfineX connection.
"""
default_setting = {
"key": "",
"secret": "",
"session": 3,
"proxy_host": "127.0.0.1",
"proxy_port": 1080,
}
exchanges = [Exchange.BITFINEX]
def __init__(self, eve... | class BitfinexGateway(BaseGateway):
| """
VN Trader Gateway for bitfineX connection.
"""
default_setting = {
"key": "",
"secret": "",
"session": 3,
"proxy_host": "127.0.0.1",
"proxy_port": 1080,
}
exchanges = [Exchange.BITFINEX]
def __init__(self, event_engine):
"""Constructor""... | }
DIRECTION_VT2BITFINEX = {
Direction.LONG: "Buy",
Direction.SHORT: "Sell",
}
DIRECTION_BITFINEX2VT = {
"Buy": Direction.LONG,
"Sell": Direction.SHORT,
}
INTERVAL_VT2BITFINEX = {
Interval.MINUTE: "1m",
Interval.HOUR: "1h",
Interval.DAILY: "1D",
}
TIMEDELTA_MAP = {
Interval.MINUTE: time... | 133 | 133 | 445 | 8 | 125 | HY-Scatterer/vnpy | vnpy/gateway/bitfinex/bitfinex_gateway.py | Python | BitfinexGateway | BitfinexGateway | 78 | 153 | 78 | 78 | 7a54c377233ee3b4c7af8552dfd87b94b05f5231 | bigcode/the-stack | train |
3443410fe222024b48db6874 | train | class | class BitfinexRestApi(RestClient):
"""
BitfineX REST API
"""
def __init__(self, gateway: BaseGateway):
""""""
super(BitfinexRestApi, self).__init__()
self.gateway = gateway
self.gateway_name = gateway.gateway_name
self.key = ""
self.secret = ""
... | class BitfinexRestApi(RestClient):
| """
BitfineX REST API
"""
def __init__(self, gateway: BaseGateway):
""""""
super(BitfinexRestApi, self).__init__()
self.gateway = gateway
self.gateway_name = gateway.gateway_name
self.key = ""
self.secret = ""
self.order_count = 1_000_000
... | proxy_port = setting["proxy_port"]
self.rest_api.connect(key, secret, session, proxy_host, proxy_port)
self.ws_api.connect(key, secret, proxy_host, proxy_port)
self.event_engine.register(EVENT_TIMER, self.process_timer_event)
def subscribe(self, req: SubscribeRequest):
"""... | 256 | 256 | 1,169 | 9 | 247 | HY-Scatterer/vnpy | vnpy/gateway/bitfinex/bitfinex_gateway.py | Python | BitfinexRestApi | BitfinexRestApi | 156 | 349 | 156 | 156 | f966bb208ed4ac4231f32d685d7c369566d00e7a | bigcode/the-stack | train |
6015956e1279c1bfd4200352 | train | class | class BitfinexWebsocketApi(WebsocketClient):
""""""
def __init__(self, gateway):
""""""
super(BitfinexWebsocketApi, self).__init__()
self.gateway = gateway
self.gateway_name = gateway.gateway_name
self.order_id = 1_000_000
self.trade_id = 1_000_000
self.... | class BitfinexWebsocketApi(WebsocketClient):
| """"""
def __init__(self, gateway):
""""""
super(BitfinexWebsocketApi, self).__init__()
self.gateway = gateway
self.gateway_name = gateway.gateway_name
self.order_id = 1_000_000
self.trade_id = 1_000_000
self.key = ""
self.secret = ""
se... | else:
data = resp.json()
if not data:
msg = f"获取历史数据为空,开始时间:{start_time}"
break
buf = []
for l in data:
ts, o, h, l, c, v = l
dt = datetime.fromtimestamp(ts / 1000)
... | 256 | 256 | 3,174 | 11 | 244 | HY-Scatterer/vnpy | vnpy/gateway/bitfinex/bitfinex_gateway.py | Python | BitfinexWebsocketApi | BitfinexWebsocketApi | 352 | 832 | 352 | 352 | 1af13e70077d21d3e1ce6ceadfc902e2ce231918 | bigcode/the-stack | train |
080941520c4d98bb4b3d1f60 | train | function | def replace(word):
"""
Replace the polar word with their antonym
Args:
word (str): a word
Returns:
the antonym of the input word
"""
syn = list()
ant = list()
for synset in wordnet.synsets(word):
for lemma in synset.lemmas():
syn.append(lemma.name())
... | def replace(word):
| """
Replace the polar word with their antonym
Args:
word (str): a word
Returns:
the antonym of the input word
"""
syn = list()
ant = list()
for synset in wordnet.synsets(word):
for lemma in synset.lemmas():
syn.append(lemma.name())
if lemma... | _score()
neg_score = synset.neg_score()
if (pola=='pos' and pos_score>0 and neg_score==0)\
or (pola=='neg' and neg_score>0 and pos_score==0):
return True
else:
return False
def replace(word):
| 64 | 64 | 153 | 4 | 59 | laihuiyuan/Generic-resources-for-TST | utils/pair_wordnet.py | Python | replace | replace | 64 | 85 | 64 | 64 | 37a1a40570db5e2329f456c728284cb5b0790556 | bigcode/the-stack | train |
f8abfb368bc979d58e01dbde | train | function | def check(word, pola='pos'):
"""
Check it to see if it is a polar word
Args:
word (str): a word
pola: the polarity
Returns:
bool
"""
synset_forms = list(swn.senti_synsets(word))
if not synset_forms:
return False
synset = synset_forms[0]
pos_score = syn... | def check(word, pola='pos'):
| """
Check it to see if it is a polar word
Args:
word (str): a word
pola: the polarity
Returns:
bool
"""
synset_forms = list(swn.senti_synsets(word))
if not synset_forms:
return False
synset = synset_forms[0]
pos_score = synset.pos_score()
neg_score... | TreebankWordDetokenizer().detokenize(tokens)
tokens = line.split()
line = ''
for token in tokens:
if token not in punc:
line += (' '+token)
else:
line += token
return line.strip()
def check(word, pola='pos'):
| 64 | 64 | 150 | 8 | 56 | laihuiyuan/Generic-resources-for-TST | utils/pair_wordnet.py | Python | check | check | 40 | 61 | 40 | 40 | 6f1d7a91cbd8cb8365e0988b50b2efa5e39fbc4f | bigcode/the-stack | train |
1d6e995b30dd3d813389645c | train | function | def detokenize(tokens):
"""
The detokenizer that is used to generate the sentence from tokens
Args:
tokens (list): the list of tokens
Returns:
the string of a sequence
"""
line = TreebankWordDetokenizer().detokenize(tokens)
tokens = line.split()
line = ''
for token i... | def detokenize(tokens):
| """
The detokenizer that is used to generate the sentence from tokens
Args:
tokens (list): the list of tokens
Returns:
the string of a sequence
"""
line = TreebankWordDetokenizer().detokenize(tokens)
tokens = line.split()
line = ''
for token in tokens:
if tok... | .tokenize.treebank import TreebankWordDetokenizer
punc = string.punctuation
punc += "n't,《。》、?;:‘”【「】」、|·~!@#¥%……&*()-——+='s'm'll''``"
def detokenize(tokens):
| 64 | 64 | 107 | 6 | 58 | laihuiyuan/Generic-resources-for-TST | utils/pair_wordnet.py | Python | detokenize | detokenize | 20 | 37 | 20 | 20 | 3065fb11b2736c9ca8af6ff60b094a078e975270 | bigcode/the-stack | train |
9e10596c12e03c5221a5e7a5 | train | function | def eval_qscoring_gbe(iv_file, class2int_file, test_file,
preproc_file,
model_file, score_file, vector_score_file,
normalize, **kwargs):
if preproc_file is not None:
preproc = TransformList.load(preproc_file)
else:
preproc = ... | def eval_qscoring_gbe(iv_file, class2int_file, test_file,
preproc_file,
model_file, score_file, vector_score_file,
normalize, **kwargs):
| if preproc_file is not None:
preproc = TransformList.load(preproc_file)
else:
preproc = None
tdr_args = TDR.filter_args(**kwargs)
tdr = TDR(iv_file, class2int_file, test_file, preproc, **tdr_args)
x, ndx = tdr.read()
model = GBE.load(model_file)
t1 = time.time()
sc... | .helpers import ClassifTrialDataReader as TDR
from hyperion.transforms import TransformList
from hyperion.classifiers import QScoringHomoGBE as GBE
def eval_qscoring_gbe(iv_file, class2int_file, test_file,
preproc_file,
model_file, score_file, vector_score_file,
... | 77 | 77 | 259 | 41 | 35 | jsalt2019-diadet/hyperion | hyperion/bin/eval-q-scoring-homo-gbe.py | Python | eval_qscoring_gbe | eval_qscoring_gbe | 31 | 60 | 31 | 35 | 9a38f06471f408639bd6c7fbc0de1d04f5bb0727 | bigcode/the-stack | train |
68f37ffd67c3d507803e80a2 | train | class | class BaseModel(torch.nn.Module):
def load(self, path):
"""Load model from file.
Args:
path (str): file path
"""
parameters = torch.load(path, map_location=torch.device("cpu"))
if "optimizer" in parameters:
parameters = parameters["model"]
s... | class BaseModel(torch.nn.Module):
| def load(self, path):
"""Load model from file.
Args:
path (str): file path
"""
parameters = torch.load(path, map_location=torch.device("cpu"))
if "optimizer" in parameters:
parameters = parameters["model"]
self.load_state_dict(parameters, st... | import torch
class BaseModel(torch.nn.Module):
| 10 | 64 | 73 | 7 | 2 | chriswxho/dynamic-inference | dpt/base_model.py | Python | BaseModel | BaseModel | 4 | 16 | 4 | 4 | 5445fd0614f3a3513385d81c9668f98b39443127 | bigcode/the-stack | train |
b83c8a8fdd3f04190e4f11ac | train | class | class ModelSpeedup:
"""
This class is to speedup the model with provided weight mask.
Parameters
----------
model : pytorch model
The model user wants to speedup
dummy_input : pytorch tensor, tuple of tensor, list of tensor
Note: The first dimension of the dummy_input should be ... | class ModelSpeedup:
| """
This class is to speedup the model with provided weight mask.
Parameters
----------
model : pytorch model
The model user wants to speedup
dummy_input : pytorch tensor, tuple of tensor, list of tensor
Note: The first dimension of the dummy_input should be the batchsize.
... | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import copy
import logging
from pathlib import Path
import queue
import torch
import torch.nn as nn
from nni.common.graph_utils import build_module_graph
from nni.compression.pytorch.utils.mask_conflict import fix_mask_conflict
from nni.compres... | 136 | 256 | 5,350 | 5 | 131 | Microsoft/nni | nni/compression/pytorch/speedup/compressor.py | Python | ModelSpeedup | ModelSpeedup | 25 | 545 | 25 | 25 | 862af6118599d1d509035d82535cb65924c76609 | bigcode/the-stack | train |
c21bf71f99eec79af30cb998 | train | class | class Gazebo2Rviz:
def __init__(self):
self.rate = rospy.get_param('~rate', 10.0) # the rate at which to publish the transform
self.submodelsToBeIgnored = rospy.get_param('~ignore_submodels_of', '').split(';')
self.tfBroadcaster = tf.TransformBroadcaster()
self.link_states_msg = No... | class Gazebo2Rviz:
| def __init__(self):
self.rate = rospy.get_param('~rate', 10.0) # the rate at which to publish the transform
self.submodelsToBeIgnored = rospy.get_param('~ignore_submodels_of', '').split(';')
self.tfBroadcaster = tf.TransformBroadcaster()
self.link_states_msg = None
self.mo... | #!/usr/bin/env python
# based on: gazebo2rviz - Developed by: andreasBihlmaier
# source: https://github.com/andreasBihlmaier/gazebo2rviz
import rospy
import tf
from gazebo_msgs.msg import ModelStates
from visualization_msgs.msg import Marker
from geometry_msgs.msg import Pose
from gazebo_msgs.msg import LinkStates
im... | 116 | 256 | 1,174 | 7 | 108 | SiChiTong/autonomous_bicycle | scripts/gazebo2rviz.py | Python | Gazebo2Rviz | Gazebo2Rviz | 18 | 121 | 18 | 18 | c1f6238ceb83f0dd315cb16b42abef880ef63015 | bigcode/the-stack | train |
4eec527101667a7a794dd6ff | train | class | class ProtocolConsumer(EventHandler):
"""The consumer of data for a server or client :class:`.Connection`.
It is responsible for receiving incoming data from an end point via the
:meth:`Connection.data_received` method, decoding (parsing) and,
possibly, writing back to the client or server via
the ... | class ProtocolConsumer(EventHandler):
| """The consumer of data for a server or client :class:`.Connection`.
It is responsible for receiving incoming data from an end point via the
:meth:`Connection.data_received` method, decoding (parsing) and,
possibly, writing back to the client or server via
the :attr:`transport` attribute.
.. n... | import asyncio
from pulsar.utils.internet import nice_address, format_address
from .futures import task, Future, ensure_future
from .events import EventHandler, AbortEvent
from .mixins import FlowControl, Timeout
__all__ = ['ProtocolConsumer',
'Protocol',
'DatagramProtocol',
'Connec... | 112 | 256 | 1,658 | 6 | 105 | goodboy/pulsar | pulsar/async/protocols.py | Python | ProtocolConsumer | ProtocolConsumer | 27 | 249 | 27 | 27 | 30cec9e9f83b943a0505821eab4ae268e24930f6 | bigcode/the-stack | train |
ad78b0e93b866245211dab93 | train | class | class DatagramServer(Producer):
"""An :class:`.Producer` for serving UDP sockets.
.. attribute:: _transports
A list of :class:`.DatagramTransport`.
Available once the :meth:`create_endpoint` method has returned.
"""
_transports = None
_started = None
ONE_TIME_EVENTS = ('start... | class DatagramServer(Producer):
| """An :class:`.Producer` for serving UDP sockets.
.. attribute:: _transports
A list of :class:`.DatagramTransport`.
Available once the :meth:`create_endpoint` method has returned.
"""
_transports = None
_started = None
ONE_TIME_EVENTS = ('start', 'stop')
MANY_TIMES_EVENTS... | # INTERNALS
def _connection_made(self, connection, exc=None):
if not exc:
self._concurrent_connections.add(connection)
def _connection_lost(self, connection, exc=None):
self._concurrent_connections.discard(connection)
def _close_connections(self, connection=None, timeout=5)... | 212 | 212 | 708 | 6 | 206 | goodboy/pulsar | pulsar/async/protocols.py | Python | DatagramServer | DatagramServer | 768 | 864 | 768 | 768 | 41f9160714d4f665ac9a0e451abc4993af59b30a | bigcode/the-stack | train |
c60d1869130e0b8b17b5a430 | train | class | class DatagramProtocol(PulsarProtocol, asyncio.DatagramProtocol):
"""An ``asyncio.DatagramProtocol`` with events`
"""
| class DatagramProtocol(PulsarProtocol, asyncio.DatagramProtocol):
| """An ``asyncio.DatagramProtocol`` with events`
"""
| t._buffer.extend(data)
else:
self.fire_event('before_write')
t.write(data)
self.fire_event('after_write')
return self._write_waiter
else:
raise ConnectionResetError('No Transport')
class DatagramProtocol(PulsarPr... | 64 | 64 | 28 | 13 | 51 | goodboy/pulsar | pulsar/async/protocols.py | Python | DatagramProtocol | DatagramProtocol | 431 | 433 | 431 | 431 | 5af07fd0d199e555e82d1b3f64bcaff7be9045f3 | bigcode/the-stack | train |
0e6a9f0f9b8759c8e49f5606 | train | class | class Connection(Protocol, Timeout):
"""A :class:`.FlowControl` to handle multiple TCP requests/responses.
It is a class which acts as bridge between a
:ref:`transport <asyncio-transport>` and a :class:`.ProtocolConsumer`.
It routes data arriving from the transport to the
:meth:`current_consumer`.
... | class Connection(Protocol, Timeout):
| """A :class:`.FlowControl` to handle multiple TCP requests/responses.
It is a class which acts as bridge between a
:ref:`transport <asyncio-transport>` and a :class:`.ProtocolConsumer`.
It routes data arriving from the transport to the
:meth:`current_consumer`.
.. attribute:: _consumer_factory... | ', self)
self.abort()
class Protocol(PulsarProtocol, asyncio.Protocol):
"""An :class:`asyncio.Protocol` with :ref:`events <event-handling>`
"""
_data_received_count = 0
def write(self, data):
"""Write ``data`` into the wire.
Returns an empty tuple or a :class:`~asyncio.Fu... | 253 | 254 | 847 | 7 | 246 | goodboy/pulsar | pulsar/async/protocols.py | Python | Connection | Connection | 436 | 541 | 436 | 436 | affbfd37ea584feaf0933b302a81a71c210c5e85 | bigcode/the-stack | train |
893a196a31b16ade67b7d1d5 | train | class | class TcpServer(Producer):
"""A :class:`.Producer` of server :class:`Connection` for TCP servers.
.. attribute:: _server
A :class:`.Server` managed by this Tcp wrapper.
Available once the :meth:`start_serving` method has returned.
"""
ONE_TIME_EVENTS = ('start', 'stop')
MANY_TIMES... | class TcpServer(Producer):
| """A :class:`.Producer` of server :class:`Connection` for TCP servers.
.. attribute:: _server
A :class:`.Server` managed by this Tcp wrapper.
Available once the :meth:`start_serving` method has returned.
"""
ONE_TIME_EVENTS = ('start', 'stop')
MANY_TIMES_EVENTS = ('connection_made... |
def sessions(self):
"""Total number of protocols created by the :class:`Producer`.
"""
return self._sessions
@property
def requests_processed(self):
"""Total number of requests processed.
"""
return self._requests_processed
def create_protocol(self, **k... | 256 | 256 | 1,218 | 6 | 249 | goodboy/pulsar | pulsar/async/protocols.py | Python | TcpServer | TcpServer | 605 | 765 | 605 | 605 | a81d22b5bd35d729fdeb9aa3e8ffd4a81d5e12ed | bigcode/the-stack | train |
0ec1e474515d6920dadafa6f | train | class | class Producer(EventHandler):
"""An Abstract :class:`.EventHandler` class for all producers of
socket (client and servers)
"""
protocol_factory = None
"""A callable producing protocols.
The signature of the protocol factory callable must be::
protocol_factory(session, producer, **param... | class Producer(EventHandler):
| """An Abstract :class:`.EventHandler` class for all producers of
socket (client and servers)
"""
protocol_factory = None
"""A callable producing protocols.
The signature of the protocol factory callable must be::
protocol_factory(session, producer, **params)
"""
def __init__(s... | consumer.connection_made(self)
def _connection_lost(self, _, exc=None):
"""It performs these actions in the following order:
* Fires the ``connection_lost`` :ref:`one time event <one-time-event>`
if not fired before, with ``exc`` as event data.
* Cancel the idle timeout if set.
... | 124 | 124 | 415 | 5 | 119 | goodboy/pulsar | pulsar/async/protocols.py | Python | Producer | Producer | 544 | 602 | 544 | 544 | 4094e421a6d7761fe56dbcd3ca116b2ede230e2e | bigcode/the-stack | train |
023419facbe04bcc39efbdc0 | train | class | class Protocol(PulsarProtocol, asyncio.Protocol):
"""An :class:`asyncio.Protocol` with :ref:`events <event-handling>`
"""
_data_received_count = 0
def write(self, data):
"""Write ``data`` into the wire.
Returns an empty tuple or a :class:`~asyncio.Future` if this
protocol has p... | class Protocol(PulsarProtocol, asyncio.Protocol):
| """An :class:`asyncio.Protocol` with :ref:`events <event-handling>`
"""
_data_received_count = 0
def write(self, data):
"""Write ``data`` into the wire.
Returns an empty tuple or a :class:`~asyncio.Future` if this
protocol has paused writing.
"""
t = self._trans... | info
async def _close(self):
try:
await asyncio.wait_for(
self.event('connection_lost'),
CLOSE_TIMEOUT
)
except asyncio.TimeoutError:
self.logger.warning('Abort connection %s', self)
self.abort()
class Protocol(PulsarP... | 64 | 64 | 211 | 10 | 54 | goodboy/pulsar | pulsar/async/protocols.py | Python | Protocol | Protocol | 401 | 428 | 401 | 401 | dedc2c965ddce083424c14738b1a8682479abfb5 | bigcode/the-stack | train |
1bff30b98b33ded8b156eb11 | train | class | class AbortRequest(AbortEvent):
pass
| class AbortRequest(AbortEvent):
| pass
| mixins import FlowControl, Timeout
__all__ = ['ProtocolConsumer',
'Protocol',
'DatagramProtocol',
'Connection',
'Producer',
'TcpServer',
'DatagramServer',
'AbortRequest']
CLOSE_TIMEOUT = 3
class AbortRequest(AbortEvent):
| 64 | 64 | 10 | 7 | 56 | goodboy/pulsar | pulsar/async/protocols.py | Python | AbortRequest | AbortRequest | 23 | 24 | 23 | 23 | 3d3d4e3e2314534ceaadc2512ec525739508ea9b | bigcode/the-stack | train |
f1562603e2a70ecd5313f807 | train | class | class PulsarProtocol(EventHandler, FlowControl):
"""A mixin class for both :class:`.Protocol` and
:class:`.DatagramProtocol`.
A :class:`PulsarProtocol` is an :class:`.EventHandler` which has
two :ref:`one time events <one-time-event>`:
* ``connection_made``
* ``connection_lost``
"""
ON... | class PulsarProtocol(EventHandler, FlowControl):
| """A mixin class for both :class:`.Protocol` and
:class:`.DatagramProtocol`.
A :class:`PulsarProtocol` is an :class:`.EventHandler` which has
two :ref:`one time events <one-time-event>`:
* ``connection_made``
* ``connection_lost``
"""
ONE_TIME_EVENTS = ('connection_made', 'connection_l... | except AbortEvent:
self.logger.debug('Abort request %s', self.request)
else:
if self._request is not None:
try:
self.start_request()
except Exception as exc:
self.finished(exc=exc)
def _data_received(self, data... | 256 | 256 | 967 | 10 | 245 | goodboy/pulsar | pulsar/async/protocols.py | Python | PulsarProtocol | PulsarProtocol | 252 | 398 | 252 | 252 | 93cf19ce2a5e8e1589483e8e966354b53d800e26 | bigcode/the-stack | train |
914dff5e1d472f21073354b0 | train | function | def main(argv):
if len(argv) > 1:
raise tf.app.UsageError("Too many command-line arguments.")
writer = tf.python_io.TFRecordWriter(FLAGS.output_file)
feature_list = {}
frame_list = []
for _ in range(20):
# generate 20 frames.
png_image = six.StringIO()
png.from_array(
np.random.randi... | def main(argv):
| if len(argv) > 1:
raise tf.app.UsageError("Too many command-line arguments.")
writer = tf.python_io.TFRecordWriter(FLAGS.output_file)
feature_list = {}
frame_list = []
for _ in range(20):
# generate 20 frames.
png_image = six.StringIO()
png.from_array(
np.random.randint(
... | _file=valid.tfrecords
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import png
import six
import tensorflow as tf
flags = tf.flags
FLAGS = flags.FLAGS
flags.DEFINE_integer("resolution", 64, "Resolution of the video.")
flags.DEFINE... | 96 | 97 | 326 | 4 | 92 | undeadinu/datasets | tensorflow_datasets/testing/starcraft.py | Python | main | main | 41 | 79 | 41 | 41 | 035d09c90a335bf868ef99a9531f190ff6942e72 | bigcode/the-stack | train |
ad5b20fe412d1df0167bad4e | train | class | class SharedConfig(BaseModel):
class Config:
allow_mutation = False
service: Optional[str]
@root_validator(pre=True)
def _initial_validation(cls, values):
return validation.core.initialize_config(getattr(validators, 'initialize_shared', identity)(values))
@validator('*', pre=True,... | class SharedConfig(BaseModel):
| class Config:
allow_mutation = False
service: Optional[str]
@root_validator(pre=True)
def _initial_validation(cls, values):
return validation.core.initialize_config(getattr(validators, 'initialize_shared', identity)(values))
@validator('*', pre=True, always=True)
def _ensure_d... | TEGRATION_NAME>
from __future__ import annotations
from typing import Optional
from pydantic import BaseModel, root_validator, validator
from datadog_checks.base.utils.functions import identity
from datadog_checks.base.utils.models import validation
from . import defaults, validators
class SharedConfig(BaseModel):... | 64 | 64 | 198 | 6 | 57 | kjmadscience/integrations-core | traffic_server/datadog_checks/traffic_server/config_models/shared.py | Python | SharedConfig | SharedConfig | 22 | 48 | 22 | 22 | 06dcd050faa14914540dfbd05e273364614b9dda | bigcode/the-stack | train |
6500065ea03368b25073fff1 | train | class | class ExampleForm(forms.Form):
comment = forms.CharField()
| class ExampleForm(forms.Form):
| comment = forms.CharField()
| password']
def __init__(self, *args, **kwargs):
super(TestForm3, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
class TestForm4(forms.ModelForm):
class Meta:
model = CrispyTestModel
class ExampleForm(forms.Form):
| 64 | 64 | 13 | 6 | 57 | radicalgraphics/django-crispy-forms | crispy_forms/tests/forms.py | Python | ExampleForm | ExampleForm | 94 | 95 | 94 | 94 | 29cae1384c1e4e7e09d534f487613211b28a328d | bigcode/the-stack | train |
1076c89457fe2e2f1ffa7398 | train | class | class TestForm3(forms.ModelForm):
class Meta:
model = CrispyTestModel
fields = ['email', 'password']
exclude = ['password']
def __init__(self, *args, **kwargs):
super(TestForm3, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
| class TestForm3(forms.ModelForm):
| class Meta:
model = CrispyTestModel
fields = ['email', 'password']
exclude = ['password']
def __init__(self, *args, **kwargs):
super(TestForm3, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
| ('option_two', "Option two"),
),
widget = forms.RadioSelect,
initial = 'option_two',
)
class CrispyTestModel(models.Model):
email = models.CharField(max_length=20)
password = models.CharField(max_length=20)
class TestForm3(forms.ModelForm):
| 64 | 64 | 71 | 8 | 56 | radicalgraphics/django-crispy-forms | crispy_forms/tests/forms.py | Python | TestForm3 | TestForm3 | 78 | 86 | 78 | 78 | bea98c87326c31a31f365d7df81451b8f97c2487 | bigcode/the-stack | train |
09ed81a2121a852b447dfba3 | train | class | class TestForm2(TestForm):
def __init__(self, *args, **kwargs):
super(TestForm2, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
| class TestForm2(TestForm):
| def __init__(self, *args, **kwargs):
super(TestForm2, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
| = self.cleaned_data.get('password1', None)
password2 = self.cleaned_data.get('password2', None)
if not password1 and not password2 or password1 != password2:
raise forms.ValidationError("Passwords dont match")
return self.cleaned_data
class TestForm2(TestForm):
| 64 | 64 | 43 | 7 | 56 | radicalgraphics/django-crispy-forms | crispy_forms/tests/forms.py | Python | TestForm2 | TestForm2 | 26 | 29 | 26 | 26 | c1a8e295a80744a797f37bae743ec56d54154765 | bigcode/the-stack | train |
30b6004920662b742b7cd720 | train | class | class TestForm5(forms.Form):
choices = [
(1, 1),
(2, 2),
(1000, 1000),
]
checkbox_select_multiple = forms.MultipleChoiceField(
widget=forms.CheckboxSelectMultiple,
choices=choices)
radio_select = forms.ChoiceField(
widget=forms.RadioSelect,
choic... | class TestForm5(forms.Form):
| choices = [
(1, 1),
(2, 2),
(1000, 1000),
]
checkbox_select_multiple = forms.MultipleChoiceField(
widget=forms.CheckboxSelectMultiple,
choices=choices)
radio_select = forms.ChoiceField(
widget=forms.RadioSelect,
choices=choices)
pk = forms.In... | TestForm4(forms.ModelForm):
class Meta:
model = CrispyTestModel
class ExampleForm(forms.Form):
comment = forms.CharField()
class FormWithMeta(TestForm):
class Meta:
fields = ('email', 'first_name', 'last_name')
class TestForm5(forms.Form):
| 64 | 64 | 89 | 7 | 57 | radicalgraphics/django-crispy-forms | crispy_forms/tests/forms.py | Python | TestForm5 | TestForm5 | 103 | 115 | 103 | 103 | 1b924bd2b0ea27639f3f42561f3252f36af6fd5b | bigcode/the-stack | train |
dea34e5da8c8a809276e7314 | train | class | class FormWithMeta(TestForm):
class Meta:
fields = ('email', 'first_name', 'last_name')
| class FormWithMeta(TestForm):
| class Meta:
fields = ('email', 'first_name', 'last_name')
| ):
super(TestForm3, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
class TestForm4(forms.ModelForm):
class Meta:
model = CrispyTestModel
class ExampleForm(forms.Form):
comment = forms.CharField()
class FormWithMeta(TestForm):
| 64 | 64 | 25 | 7 | 57 | radicalgraphics/django-crispy-forms | crispy_forms/tests/forms.py | Python | FormWithMeta | FormWithMeta | 98 | 100 | 98 | 98 | cd00b8611d25ce8a7c75c1f53904713b9b88e934 | bigcode/the-stack | train |
6bf8c07566eb5be7fa182b16 | train | class | class CheckboxesTestForm(forms.Form):
checkboxes = forms.MultipleChoiceField(
choices = (
(1, "Option one"),
(2, "Option two"),
(3, "Option three")
),
initial = (1,),
widget = forms.CheckboxSelectMultiple,
)
alphacheckboxes = forms.Multipl... | class CheckboxesTestForm(forms.Form):
| checkboxes = forms.MultipleChoiceField(
choices = (
(1, "Option one"),
(2, "Option two"),
(3, "Option three")
),
initial = (1,),
widget = forms.CheckboxSelectMultiple,
)
alphacheckboxes = forms.MultipleChoiceField(
choices = (
... | password1 != password2:
raise forms.ValidationError("Passwords dont match")
return self.cleaned_data
class TestForm2(TestForm):
def __init__(self, *args, **kwargs):
super(TestForm2, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
class CheckboxesTestForm(forms.... | 73 | 73 | 244 | 8 | 65 | radicalgraphics/django-crispy-forms | crispy_forms/tests/forms.py | Python | CheckboxesTestForm | CheckboxesTestForm | 32 | 70 | 32 | 32 | a80e60417368857d8eaefa659bb037df85c3d381 | bigcode/the-stack | train |
9a6c45865b679c89849c5f18 | train | class | class CrispyTestModel(models.Model):
email = models.CharField(max_length=20)
password = models.CharField(max_length=20)
| class CrispyTestModel(models.Model):
| email = models.CharField(max_length=20)
password = models.CharField(max_length=20)
| boxSelectMultiple,
)
inline_radios = forms.ChoiceField(
choices = (
('option_one', "Option one"),
('option_two', "Option two"),
),
widget = forms.RadioSelect,
initial = 'option_two',
)
class CrispyTestModel(models.Model):
| 64 | 64 | 30 | 8 | 56 | radicalgraphics/django-crispy-forms | crispy_forms/tests/forms.py | Python | CrispyTestModel | CrispyTestModel | 73 | 75 | 73 | 73 | fa286de1478733a3b9fe9908b9d9c98e58d28eb5 | bigcode/the-stack | train |
dfe31366a7120370ab96023f | train | class | class TestForm(forms.Form):
is_company = forms.CharField(label="company", required=False, widget=forms.CheckboxInput())
email = forms.EmailField(label="email", max_length=30, required=True, widget=forms.TextInput(), help_text="Insert your email")
password1 = forms.CharField(label="password", max_length=30, ... | class TestForm(forms.Form):
| is_company = forms.CharField(label="company", required=False, widget=forms.CheckboxInput())
email = forms.EmailField(label="email", max_length=30, required=True, widget=forms.TextInput(), help_text="Insert your email")
password1 = forms.CharField(label="password", max_length=30, required=True, widget=forms.... | from django import forms
from django.db import models
from crispy_forms.helper import FormHelper
class TestForm(forms.Form):
| 25 | 75 | 250 | 6 | 18 | radicalgraphics/django-crispy-forms | crispy_forms/tests/forms.py | Python | TestForm | TestForm | 7 | 23 | 7 | 7 | 5e6eca0b6f53546f70890911f20ef3775efa6900 | bigcode/the-stack | train |
04405cb3ce4d198b17674534 | train | class | class TestForm4(forms.ModelForm):
class Meta:
model = CrispyTestModel
| class TestForm4(forms.ModelForm):
| class Meta:
model = CrispyTestModel
| CrispyTestModel
fields = ['email', 'password']
exclude = ['password']
def __init__(self, *args, **kwargs):
super(TestForm3, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
class TestForm4(forms.ModelForm):
| 64 | 64 | 20 | 8 | 56 | radicalgraphics/django-crispy-forms | crispy_forms/tests/forms.py | Python | TestForm4 | TestForm4 | 89 | 91 | 89 | 89 | 36de66b2cecb057b49989e6167c0012778304a34 | bigcode/the-stack | train |
fbe0e211114dca8b090a928e | train | class | class TemplateRepo(BaseRepo):
"""Template repository for easy subclassing
Parameters
----------
model : Type
Class of an item in the repository.
Commonly dict or subclass of Pydantic
BaseModel. By default dict
id_field : str, optional
Attribute or key that identifies... | class TemplateRepo(BaseRepo):
| """Template repository for easy subclassing
Parameters
----------
model : Type
Class of an item in the repository.
Commonly dict or subclass of Pydantic
BaseModel. By default dict
id_field : str, optional
Attribute or key that identifies each item
in the repo... | given"
if __values is not None:
kwargs.update(__values)
try:
return self.repo.query_replace(self.query_, kwargs)
except NotImplementedError:
# Has no custom replace implemented, using
# default alternative (delete, add)
return super()... | 256 | 256 | 1,326 | 6 | 249 | Miksus/red-base | redbird/templates.py | Python | TemplateRepo | TemplateRepo | 64 | 335 | 64 | 64 | ec8a7bf049b61ffd9ff3efed81073b6801fb7731 | bigcode/the-stack | train |
b019125ea67180454f5c1e37 | train | class | class TemplateResult(BaseResult):
repo: 'TemplateRepo'
def query_data(self) -> Iterator[Data]:
"Get actual result"
return self.repo.query_read(self.query_)
def update(self, **kwargs):
return self.repo.query_update(self.query_, kwargs)
def delete(self):
return self.repo... | class TemplateResult(BaseResult):
| repo: 'TemplateRepo'
def query_data(self) -> Iterator[Data]:
"Get actual result"
return self.repo.query_read(self.query_)
def update(self, **kwargs):
return self.repo.query_update(self.query_, kwargs)
def delete(self):
return self.repo.query_delete(self.query_)
de... |
from abc import abstractmethod
from typing import Any, ClassVar, Iterator
from .base import BaseRepo, BaseResult, Data
class TemplateResult(BaseResult):
| 35 | 104 | 347 | 6 | 28 | Miksus/red-base | redbird/templates.py | Python | TemplateResult | TemplateResult | 6 | 61 | 6 | 6 | ceae42e8073219cc82cb9a3da5629b636a53b8d3 | bigcode/the-stack | train |
035b432ebc63bed9ffb7b101 | train | function | def denoise(image, n_scales=4):
"""Denoise.
This function provides a denoised version of the input image.
Parameters
----------
image : np.ndarray
Input image
n_scales : int
Number of wavelet scales to use
Returns
-------
np.ndarray
Denoised image
Exam... | def denoise(image, n_scales=4):
| """Denoise.
This function provides a denoised version of the input image.
Parameters
----------
image : np.ndarray
Input image
n_scales : int
Number of wavelet scales to use
Returns
-------
np.ndarray
Denoised image
Examples
--------
>>> import... | .info/licences/Licence_CeCILL-B_V1-en.html
# for details.
##########################################################################
"""Galaxy Image Denoising."""
import numpy as np
from modopt.signal.noise import thresh
from pysap.plugins.astro.denoising.noise import noise_est, sigma_scales
from pysap.plugins.astro.... | 91 | 91 | 306 | 11 | 79 | CEA-COSMIC/pysap-astro | astro/denoising/denoise.py | Python | denoise | denoise | 18 | 56 | 18 | 18 | f17ee54c5b8be3f1dcd00890674fbf434bf6075d | bigcode/the-stack | train |
469ed6163af3ad6e2b5b763d | train | function | def _onenorm_matrix_power_nnm(A, p):
"""
Compute the 1-norm of a non-negative integer power of a non-negative matrix.
Parameters
----------
A : a square ndarray or matrix or sparse matrix
Input matrix with non-negative entries.
p : non-negative integer
The power to which the mat... | def _onenorm_matrix_power_nnm(A, p):
| """
Compute the 1-norm of a non-negative integer power of a non-negative matrix.
Parameters
----------
A : a square ndarray or matrix or sparse matrix
Input matrix with non-negative entries.
p : non-negative integer
The power to which the matrix is to be raised.
Returns
... | March 2002
# Anthony Scopatz, August 2012 (Sparse Updates)
# Jake Vanderplas, August 2012 (Sparse Updates)
#
from __future__ import division, print_function, absolute_import
import math
import numpy as np
import torch
import scipy.special
def _onenorm_matrix_power_nnm(A, p):
| 75 | 75 | 253 | 12 | 62 | WangYuNeng/EvolutionaryGAN-pytorch | models/networks/expm/expm32.py | Python | _onenorm_matrix_power_nnm | _onenorm_matrix_power_nnm | 20 | 50 | 20 | 20 | dece088d1e44141cfe656db6ef383fbc5e1a3bcd | bigcode/the-stack | train |
1eb18eeade886fe2abe64e93 | train | function | def _expm(A):
# Core of expm, separated to allow testing exact and approximate
# algorithms.
# Avoid indiscriminate asarray() to allow sparse or other strange arrays.
if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
raise ValueError('expected a square matrix')
# Trivial case
if A.shap... | def _expm(A):
# Core of expm, separated to allow testing exact and approximate
# algorithms.
# Avoid indiscriminate asarray() to allow sparse or other strange arrays.
| if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
raise ValueError('expected a square matrix')
# Trivial case
if A.shape == (1, 1):
return torch.exp(A)
# Track functions of A to help compute the matrix exponential.
h = _ExpmPadeHelper(A)
# Try Pade order 3.
eta_1 = max(h.d... | .. [1] Awad H. Al-Mohy and Nicholas J. Higham (2009)
"A New Scaling and Squaring Algorithm for the Matrix Exponential."
SIAM Journal on Matrix Analysis and Applications.
31 (3). pp. 970-989. ISSN 1095-7162
"""
return _expm(A)
def _expm(A):
# Core of expm, separated to a... | 120 | 120 | 400 | 42 | 78 | WangYuNeng/EvolutionaryGAN-pytorch | models/networks/expm/expm32.py | Python | _expm | _expm | 220 | 256 | 220 | 224 | e2d8d8469fd9aa6b72e4f2b3d440385f21948d8b | bigcode/the-stack | train |
aed665ecf12d4a3056a579fe | train | class | class _ExpmPadeHelper(object):
"""
Help lazily evaluate a matrix exponential.
The idea is to not do more work than we need for high expm precision,
so we lazily compute matrix powers and store or precompute
other properties of the matrix.
"""
def __init__(self, A):
"""
Init... | class _ExpmPadeHelper(object):
| """
Help lazily evaluate a matrix exponential.
The idea is to not do more work than we need for high expm precision,
so we lazily compute matrix powers and store or precompute
other properties of the matrix.
"""
def __init__(self, A):
"""
Initialize the object.
Par... | Input matrix with non-negative entries.
p : non-negative integer
The power to which the matrix is to be raised.
Returns
-------
out : float
The 1-norm of the matrix power p of A.
"""
# check input
if int(p) != p or p < 0:
raise ValueError('expected non-negative int... | 256 | 256 | 1,040 | 9 | 247 | WangYuNeng/EvolutionaryGAN-pytorch | models/networks/expm/expm32.py | Python | _ExpmPadeHelper | _ExpmPadeHelper | 60 | 186 | 60 | 60 | 1cfc207ac7f9d40152a8555b9ea7ea089a4ce0d5 | bigcode/the-stack | train |
eaa8a734563c705be6cef792 | train | function | def _ell(A, m):
"""
A helper function for expm_2009.
Parameters
----------
A : linear operator
A linear operator whose norm of power we care about.
m : int
The power of the linear operator
Returns
-------
value : int
A value related to a bound.
"""
... | def _ell(A, m):
| """
A helper function for expm_2009.
Parameters
----------
A : linear operator
A linear operator whose norm of power we care about.
m : int
The power of the linear operator
Returns
-------
value : int
A value related to a bound.
"""
if len(A.shape) ... | 2(eta_3 / theta_7))), 0)
s += _ell(2**-s * h.A, 7)
U, V = h.pade7_scaled(s)
X = _solve_P_Q(U, V)
return torch.matrix_power(X, 2**s)
def _solve_P_Q(U, V):
P = U + V
Q = -U + V
return torch.solve(P, Q)[0]
def _ell(A, m):
| 106 | 106 | 354 | 7 | 99 | WangYuNeng/EvolutionaryGAN-pytorch | models/networks/expm/expm32.py | Python | _ell | _ell | 265 | 304 | 265 | 265 | 0835e23bede896197ae204588da49199f54488fe | bigcode/the-stack | train |
e8af284384e8b7f56ac5ea27 | train | function | def _ident_like(A):
return torch.eye(A.shape[0], A.shape[1], dtype=A.dtype, device=A.device)
| def _ident_like(A):
| return torch.eye(A.shape[0], A.shape[1], dtype=A.dtype, device=A.device)
| 0], 1), dtype=A.dtype, device=A.device)
M = A.t()
for _ in range(p):
v = M.mm(v)
return torch.max(v).item()
def _onenorm(A):
return torch.norm(A, 1).item()
def _ident_like(A):
| 64 | 64 | 28 | 6 | 58 | WangYuNeng/EvolutionaryGAN-pytorch | models/networks/expm/expm32.py | Python | _ident_like | _ident_like | 57 | 58 | 57 | 57 | e44af96b72821270f8ee1d7699c2b4daab357b78 | bigcode/the-stack | train |
b62e2579e54a21da1a4fc954 | train | function | def expm32(A):
"""
Compute the matrix exponential using Pade approximation.
Parameters
----------
A : (M,M) array_like or sparse matrix
2D Array or Matrix (sparse or dense) to be exponentiated
Returns
-------
expA : (M,M) ndarray
Matrix exponential of `A`
Notes
... | def expm32(A):
| """
Compute the matrix exponential using Pade approximation.
Parameters
----------
A : (M,M) array_like or sparse matrix
2D Array or Matrix (sparse or dense) to be exponentiated
Returns
-------
expA : (M,M) ndarray
Matrix exponential of `A`
Notes
-----
This... | b[5]*B4 + b[3]*B2 + b[1]*self.ident)
V = b[6]*B6 + b[4]*B4 + b[2]*B2 + b[0]*self.ident
return U, V
def expm32(A):
| 64 | 64 | 199 | 6 | 57 | WangYuNeng/EvolutionaryGAN-pytorch | models/networks/expm/expm32.py | Python | expm32 | expm32 | 189 | 217 | 189 | 189 | 6088c5e19a705d12b2b64c53632ccf1a5b97bf45 | bigcode/the-stack | train |
3bafab178424fe4496ade829 | train | function | def _onenorm(A):
return torch.norm(A, 1).item()
| def _onenorm(A):
| return torch.norm(A, 1).item()
| in addition to ndarray and sparse matrix).
v = torch.ones((A.shape[0], 1), dtype=A.dtype, device=A.device)
M = A.t()
for _ in range(p):
v = M.mm(v)
return torch.max(v).item()
def _onenorm(A):
| 64 | 64 | 17 | 6 | 58 | WangYuNeng/EvolutionaryGAN-pytorch | models/networks/expm/expm32.py | Python | _onenorm | _onenorm | 53 | 54 | 53 | 53 | ce7381b82dd2206daa1151a5b7e34ee2b637c0a0 | bigcode/the-stack | train |
af74122fdb457bc03cdadcc0 | train | function | def _solve_P_Q(U, V):
P = U + V
Q = -U + V
return torch.solve(P, Q)[0]
| def _solve_P_Q(U, V):
| P = U + V
Q = -U + V
return torch.solve(P, Q)[0]
| 0)
s += _ell(2**-s * h.A, 7)
U, V = h.pade7_scaled(s)
X = _solve_P_Q(U, V)
return torch.matrix_power(X, 2**s)
def _solve_P_Q(U, V):
| 64 | 64 | 34 | 9 | 55 | WangYuNeng/EvolutionaryGAN-pytorch | models/networks/expm/expm32.py | Python | _solve_P_Q | _solve_P_Q | 259 | 262 | 259 | 259 | 13af4d8b6be18602a5a993eaa1afc641ab67faf2 | bigcode/the-stack | train |
b3d05db5bfcd069a16a16a80 | train | function | def test_merge2_sql_semantics_rightjoin_multi_keep_firstNone():
"""
Test that merge2 matches the following SQL query:
select
f.id as foo_id,
f.col1 as foo_col1,
f.col2 as foo_col2,
b.id as bar_id,
b.col1 as bar_col1,
b.col2 as bar_col2,
b.s... | def test_merge2_sql_semantics_rightjoin_multi_keep_firstNone():
| """
Test that merge2 matches the following SQL query:
select
f.id as foo_id,
f.col1 as foo_col1,
f.col2 as foo_col2,
b.id as bar_id,
b.col1 as bar_col1,
b.col2 as bar_col2,
b.strcol as bar_strcol
from (
select *
from s... | | NULL | NULL | NULL |
# +--------+----------+----------+--------+----------+----------+------------+
# 6 rows in set (0.0009 sec)
inv = rt.int32.inv
# Intersection cols (the 'on' cols)
assert_array_equal(result.col1, rt.FA([5, 5, 8, inv, 10, inv], dtype=np.int32))
assert_... | 255 | 256 | 927 | 14 | 241 | 972d5defe3218bd62b741e6a2f11f5b3/riptable | riptable/tests/test_merge.py | Python | test_merge2_sql_semantics_rightjoin_multi_keep_firstNone | test_merge2_sql_semantics_rightjoin_multi_keep_firstNone | 5,241 | 5,336 | 5,241 | 5,241 | 406fcc7a6e8245ece69a80c8695bc035375399cc | bigcode/the-stack | train |
bc57d12b6ae769235ba3d267 | train | class | class TestDataset:
"""
Helper methods for creating Dataset instances used by merge / merge_asof tests.
"""
class HockeyDataset(NamedTuple):
"""
Test data taken from: http://doc.nuodb.com/Latest/Default.htm#About-Join-Operations-Supported-by-NuoDB.htm
"""
teams... | class TestDataset:
| """
Helper methods for creating Dataset instances used by merge / merge_asof tests.
"""
class HockeyDataset(NamedTuple):
"""
Test data taken from: http://doc.nuodb.com/Latest/Default.htm#About-Join-Operations-Supported-by-NuoDB.htm
"""
teams: rt.Dataset
... | uple[str, str, str]"
),
pytest.param([('foo',)], None, True, False, ['foo'], id="on_List[Tuple[str]]"),
pytest.param(
['foo', ('bar', 'baz')],
None,
True,
False,
['foo', 'bar'],
id="on_List[str; Tuple[str, str]]--le... | 256 | 256 | 2,254 | 4 | 251 | 972d5defe3218bd62b741e6a2f11f5b3/riptable | riptable/tests/test_merge.py | Python | TestDataset | TestDataset | 1,190 | 1,516 | 1,190 | 1,190 | bd0540b066eb523641505c4c77f82b33b6d73923 | bigcode/the-stack | train |
185d7e7eaeef53f2fc2a1046 | train | function | def test_merge2_sql_semantics_leftjoin_multi():
"""
Test that merge2 matches the following SQL query:
select
f.id as foo_id,
f.col1 as foo_col1,
f.col2 as foo_col2,
b.id as bar_id,
b.col1 as bar_col1,
b.col2 as bar_col2,
b.strcol as bar_str... | def test_merge2_sql_semantics_leftjoin_multi():
| """
Test that merge2 matches the following SQL query:
select
f.id as foo_id,
f.col1 as foo_col1,
f.col2 as foo_col2,
b.id as bar_id,
b.col1 as bar_col1,
b.col2 as bar_col2,
b.strcol as bar_strcol
from
sql_semantics.foo as f
... | , rt.FA([8, 9, 11, 3, inv, 1, 2, inv, inv, 4, 5, 6, 7, 10, 12], dtype=np.int32))
assert_array_equal(result.col2_bar, rt.FA([5, 5, 5, 8, inv, 10, 10, inv, inv, inv, inv, inv, inv, 14, -15], dtype=np.int32))
assert_array_equal(result.strcol, rt.FA([b'Lombard', b'Sansom', b'Arch', b'Walnut', b'', b'Chestnut', b'... | 203 | 204 | 680 | 11 | 192 | 972d5defe3218bd62b741e6a2f11f5b3/riptable | riptable/tests/test_merge.py | Python | test_merge2_sql_semantics_leftjoin_multi | test_merge2_sql_semantics_leftjoin_multi | 4,158 | 4,218 | 4,158 | 4,158 | 2eecb2124e67a8abc08e2a88bca3a454e0e1ec23 | bigcode/the-stack | train |
42ee4ceb51e5cbdf05756ca4 | train | function | def test_merge2_sql_semantics_leftjoin_multi_keep_Nonelast():
"""
Test that merge2 matches the following SQL query:
select
f.id as foo_id,
f.col1 as foo_col1,
f.col2 as foo_col2,
b.id as bar_id,
b.col1 as bar_col1,
b.col2 as bar_col2,
b.str... | def test_merge2_sql_semantics_leftjoin_multi_keep_Nonelast():
| """
Test that merge2 matches the following SQL query:
select
f.id as foo_id,
f.col1 as foo_col1,
f.col2 as foo_col2,
b.id as bar_id,
b.col1 as bar_col1,
b.col2 as bar_col2,
b.strcol as bar_strcol
from
sql_semantics.foo as f
... | # 6 rows in set (0.0016 sec)
inv = rt.int32.inv
# Intersection cols (the 'on' cols)
assert_array_equal(result.col1, rt.FA([5, 5, 8, inv, 10, inv], dtype=np.int32))
assert_array_equal(result.col2, rt.FA([inv, 5, inv, 1, 1, 4], dtype=np.int32))
# Cols from the left Dataset.
assert_array... | 228 | 229 | 764 | 16 | 212 | 972d5defe3218bd62b741e6a2f11f5b3/riptable | riptable/tests/test_merge.py | Python | test_merge2_sql_semantics_leftjoin_multi_keep_Nonelast | test_merge2_sql_semantics_leftjoin_multi_keep_Nonelast | 4,518 | 4,588 | 4,518 | 4,518 | 1256ec4746acfa8de9be18636489203ea53db7c5 | bigcode/the-stack | train |
a7855ca7ef598c3a6051e4b2 | train | function | def test_merge2_nonempty_symmetric_diff():
ds1 = rt.Dataset({'a': [1, 2, 3]})
ds2 = rt.Dataset({'a': [1, 3, 4], 'b': [10, 30, 40]})
ds = rt.merge2(ds1, ds2, on='a', how='left')
assert_array_equal(ds['a'], rt.FastArray([1, 2, 3]))
expected_b_arr = rt.FastArray([10, 0, 30])
expected_b_arr[1]... | def test_merge2_nonempty_symmetric_diff():
| ds1 = rt.Dataset({'a': [1, 2, 3]})
ds2 = rt.Dataset({'a': [1, 3, 4], 'b': [10, 30, 40]})
ds = rt.merge2(ds1, ds2, on='a', how='left')
assert_array_equal(ds['a'], rt.FastArray([1, 2, 3]))
expected_b_arr = rt.FastArray([10, 0, 30])
expected_b_arr[1] = rt.nan
assert_array_equal(ds['b'], e... | for the Categorical's underlying array instead of the
# Categorical's base index (if it has one).
assert np.all(result['InkColor']._fa >= 0)
assert np.all(result['PurchaseDate']._fa >= 0)
def test_merge2_nonempty_symmetric_diff():
| 64 | 64 | 140 | 10 | 54 | 972d5defe3218bd62b741e6a2f11f5b3/riptable | riptable/tests/test_merge.py | Python | test_merge2_nonempty_symmetric_diff | test_merge2_nonempty_symmetric_diff | 1,857 | 1,864 | 1,857 | 1,857 | 30745f01f21092068259eccdb3b613647381c7bf | bigcode/the-stack | train |
42638e9e598dc12cc58340af | train | function | def test_merge2_sql_semantics_rightjoin_single_keep_Nonefirst():
"""
Test that merge2 matches the following SQL query:
select
f.id as foo_id,
f.col1 as foo_col1,
f.col2 as foo_col2,
b.id as bar_id,
b.col1 as bar_col1,
b.col2 as bar_col2,
b.... | def test_merge2_sql_semantics_rightjoin_single_keep_Nonefirst():
| """
Test that merge2 matches the following SQL query:
select
f.id as foo_id,
f.col1 as foo_col1,
f.col2 as foo_col2,
b.id as bar_id,
b.col1 as bar_col1,
b.col2 as bar_col2,
b.strcol as bar_strcol
from
sql_semantics.foo as f
... | 5, 8, inv, 10, inv], dtype=np.int32))
# Cols from the left Dataset.
assert_array_equal(result.id_foo, rt.FA([1, 2, 3, 4, 5, 6], dtype=np.int32))
assert_array_equal(result.col2_foo, rt.FA([inv, 5, inv, 1, 1, 4], dtype=np.int32))
# Cols from the right Dataset.
assert_array_equal(result.id_ba... | 225 | 226 | 755 | 14 | 211 | 972d5defe3218bd62b741e6a2f11f5b3/riptable | riptable/tests/test_merge.py | Python | test_merge2_sql_semantics_rightjoin_single_keep_Nonefirst | test_merge2_sql_semantics_rightjoin_single_keep_Nonefirst | 2,726 | 2,795 | 2,726 | 2,726 | f7807089834d11d553cd29709a2e6c7e005a7ef6 | bigcode/the-stack | train |
da2e8523f06e548ebbd4755b | train | function | def test_merge2_sql_semantics_innerjoin_multi_keep_Nonelast():
"""
Test that merge2 matches the following SQL query:
select
f.id as foo_id,
f.col1 as foo_col1,
f.col2 as foo_col2,
b.id as bar_id,
b.col1 as bar_col1,
b.col2 as bar_col2,
b.st... | def test_merge2_sql_semantics_innerjoin_multi_keep_Nonelast():
| """
Test that merge2 matches the following SQL query:
select
f.id as foo_id,
f.col1 as foo_col1,
f.col2 as foo_col2,
b.id as bar_id,
b.col1 as bar_col1,
b.col2 as bar_col2,
b.strcol as bar_strcol
from
sql_semantics.foo as f
... | +----------+----------+------------+
# 1 row in set (0.0031 sec)
inv = rt.int32.inv
# Intersection cols (the 'on' cols)
assert_array_equal(result.col1, rt.FA([5], dtype=np.int32))
assert_array_equal(result.col2, rt.FA([5], dtype=np.int32))
# Cols from the left Dataset.
assert_arra... | 169 | 170 | 568 | 16 | 153 | 972d5defe3218bd62b741e6a2f11f5b3/riptable | riptable/tests/test_merge.py | Python | test_merge2_sql_semantics_innerjoin_multi_keep_Nonelast | test_merge2_sql_semantics_innerjoin_multi_keep_Nonelast | 4,847 | 4,911 | 4,847 | 4,847 | c834d9eafbce4b5735231537e5f7271169f560d9 | bigcode/the-stack | train |
bd38592ebac81d67bbbf9876 | train | function | @pytest.mark.parametrize(
"left,right,left_grp,right_grp,on",
[
pytest.param(*TestDataset.hockey(), id="hockey"),
pytest.param(
*TestDataset.sql_semantics_data('col1'), id="sql_semantics_singlekey"
),
],
)
@pytest.mark.parametrize(
"how", [
'left', ... | @pytest.mark.parametrize(
"left,right,left_grp,right_grp,on",
[
pytest.param(*TestDataset.hockey(), id="hockey"),
pytest.param(
*TestDataset.sql_semantics_data('col1'), id="sql_semantics_singlekey"
),
],
)
@pytest.mark.parametrize(
"how", [
'left', ... | """
Verify the output (merged) Dataset returned by merge2 has the same
number of rows as the computed fancy indexes for the join.
"""
from riptable.rt_merge import (
JoinIndices,
_create_merge_fancy_indices,
_create_column_valid_mask,
_normalize_keep,
)
... | the same number of rows as the original result?
assert len(expand_merge_result) == len(merge_result)
@pytest.mark.parametrize(
"left,right,left_grp,right_grp,on",
[
pytest.param(*TestDataset.hockey(), id="hockey"),
pytest.param(
*TestDataset.sql_semantics_data('col1'), id=... | 256 | 256 | 1,524 | 232 | 24 | 972d5defe3218bd62b741e6a2f11f5b3/riptable | riptable/tests/test_merge.py | Python | test_merge_create_fancy_indices_with_invalids | test_merge_create_fancy_indices_with_invalids | 1,578 | 1,732 | 1,578 | 1,609 | eac3b535997482e1dea0e70c89111a4a04c82c1d | bigcode/the-stack | train |
9ca7caa5d7f4f476d33447fd | train | function | @xfail_rip260_outermerge_left_keep
def test_merge2_sql_semantics_outerjoin_multi_keep_firstlast():
"""
Test that merge2 matches the following SQL query:
select
f.id as foo_id,
f.col1 as foo_col1,
f.col2 as foo_col2,
f.team_name as foo_teamname,
b.id as bar_... | @xfail_rip260_outermerge_left_keep
def test_merge2_sql_semantics_outerjoin_multi_keep_firstlast():
| """
Test that merge2 matches the following SQL query:
select
f.id as foo_id,
f.col1 as foo_col1,
f.col2 as foo_col2,
f.team_name as foo_teamname,
b.id as bar_id,
b.col1 as bar_col1,
b.col2 as bar_col2,
b.strcol as bar_strcol
fr... | bar'),
keep=('first', 'last'),
indicator=True,
)
assert result.get_nrows() == 1
# "foo_id","foo_col1","foo_col2","foo_teamname","bar_id","bar_col1","bar_col2","bar_strcol"
# 2,5,5,"Eagles",11,5,5,"Arch"
inv = rt.int32.inv
# Intersection cols (the 'on' cols)
ass... | 255 | 256 | 1,146 | 25 | 230 | 972d5defe3218bd62b741e6a2f11f5b3/riptable | riptable/tests/test_merge.py | Python | test_merge2_sql_semantics_outerjoin_multi_keep_firstlast | test_merge2_sql_semantics_outerjoin_multi_keep_firstlast | 6,019 | 6,119 | 6,019 | 6,020 | b440579eaf2048db76df40220c0e262d4701a388 | bigcode/the-stack | train |
20311956dda8c11882bf7fc5 | train | function | @pytest.mark.parametrize("copy", [False, True])
def test_merge2_copy_data_sharing(copy):
"""Test how the 'copy' parameter of merge2 influences data-sharing between the input and output Datasets."""
foo, bar = TestDataset.sql_semantics()
# By definition, a left join/merge where we keep exactly one row ... | @pytest.mark.parametrize("copy", [False, True])
def test_merge2_copy_data_sharing(copy):
| """Test how the 'copy' parameter of merge2 influences data-sharing between the input and output Datasets."""
foo, bar = TestDataset.sql_semantics()
# By definition, a left join/merge where we keep exactly one row per key
# on the right side means the output columns from the left Dataset will be
... | ['a'], rt.FastArray([1, 2, 3]))
expected_b_arr = rt.FastArray([10, 0, 30])
expected_b_arr[1] = rt.nan
assert_array_equal(ds['b'], expected_b_arr)
@pytest.mark.parametrize("copy", [False, True])
def test_merge2_copy_data_sharing(copy):
| 76 | 76 | 254 | 21 | 55 | 972d5defe3218bd62b741e6a2f11f5b3/riptable | riptable/tests/test_merge.py | Python | test_merge2_copy_data_sharing | test_merge2_copy_data_sharing | 1,867 | 1,892 | 1,867 | 1,868 | 3a62c75e9eb2ab1694b5198c5697cd00b4976f37 | bigcode/the-stack | train |
bce76799ef51a157eb20363e | train | function | @pytest.mark.parametrize("left_on", ['Foo', ['Foo']])
@pytest.mark.parametrize("right_on", ['Baz', ['Baz']])
def test_merge_requires_columns_right_columns_present(left_on, right_on):
# Test that `merge` raises a ValueError if a user calls it and specifies
# a column name in 'columns_right' which does not ex... | @pytest.mark.parametrize("left_on", ['Foo', ['Foo']])
@pytest.mark.parametrize("right_on", ['Baz', ['Baz']])
def test_merge_requires_columns_right_columns_present(left_on, right_on):
# Test that `merge` raises a ValueError if a user calls it and specifies
# a column name in 'columns_right' which does not ex... | (ds1, ds2) = _create_merge_paramverify_dsets()
bad_colname = 'Hello'
assert (
bad_colname not in ds2.keys()
) # Make sure the bad key really isn't in the Dataset
with pytest.raises(ValueError):
rt.merge(
ds1, ds2, left_on=left_on, right_on=right_on, columns_ri... | @pytest.mark.parametrize("left_on", ['Foo', ['Foo']])
@pytest.mark.parametrize("right_on", ['Baz', ['Baz']])
def test_merge_requires_columns_right_columns_present(left_on, right_on):
# Test that `merge` raises a ValueError if a user calls it and specifies
# a column name in 'columns_right' which does not ex... | 82 | 75 | 252 | 82 | 0 | 972d5defe3218bd62b741e6a2f11f5b3/riptable | riptable/tests/test_merge.py | Python | test_merge_requires_columns_right_columns_present | test_merge_requires_columns_right_columns_present | 609 | 634 | 609 | 613 | 3df1ef983584618f3a696f7a9c22aca8d8509c76 | bigcode/the-stack | train |
d50ecf915009331febe12a1d | train | function | @xfail_rip260_outermerge_left_keep
def test_merge2_sql_semantics_outerjoin_single_keep_lastNone():
"""
Test that merge2 matches the following SQL query:
select
f.id as foo_id,
f.col1 as foo_col1,
f.col2 as foo_col2,
f.team_name as foo_teamname,
b.id as bar_... | @xfail_rip260_outermerge_left_keep
def test_merge2_sql_semantics_outerjoin_single_keep_lastNone():
| """
Test that merge2 matches the following SQL query:
select
f.id as foo_id,
f.col1 as foo_col1,
f.col2 as foo_col2,
f.team_name as foo_teamname,
b.id as bar_id,
b.col1 as bar_col1,
b.col2 as bar_col2,
b.strcol as bar_strcol
fr... | ers', b'Union', b'Union', b'Fusion', b'Fight', b'', b'', b'', b'', b'', b''])
)
# Cols from the right Dataset.
assert_array_equal(result.id_bar, rt.FA([8, 9, 11, 3, inv, 1, 2, inv, inv, 4, 5, 6, 7, 10, 12], dtype=np.int32))
assert_array_equal(result.col2_bar, rt.FA([5, 5, 5, 8, inv, 10, 10, inv, i... | 255 | 256 | 1,226 | 25 | 230 | 972d5defe3218bd62b741e6a2f11f5b3/riptable | riptable/tests/test_merge.py | Python | test_merge2_sql_semantics_outerjoin_single_keep_lastNone | test_merge2_sql_semantics_outerjoin_single_keep_lastNone | 3,740 | 3,827 | 3,740 | 3,741 | f28ab977c08193b55bbfb49e494b24b5d64bfd8a | bigcode/the-stack | train |
8d14e1ec64a47a73ecf34a1f | train | function | def test_merge2_sql_semantics_innerjoin_single_keep_Nonefirst():
"""
Test that merge2 matches the following SQL query:
select
f.id as foo_id,
f.col1 as foo_col1,
f.col2 as foo_col2,
b.id as bar_id,
b.col1 as bar_col1,
b.col2 as bar_col2,
b.... | def test_merge2_sql_semantics_innerjoin_single_keep_Nonefirst():
| """
Test that merge2 matches the following SQL query:
select
f.id as foo_id,
f.col1 as foo_col1,
f.col2 as foo_col2,
b.id as bar_id,
b.col1 as bar_col1,
b.col2 as bar_col2,
b.strcol as bar_strcol
from
sql_semantics.foo as f
... | .FA([10, 8, inv, 5, 5], dtype=np.int32))
# Cols from the left Dataset.
assert_array_equal(result.id_foo, rt.FA([5, 3, inv, 1, 2], dtype=np.int32))
assert_array_equal(result.col2_foo, rt.FA([1, inv, inv, inv, 5], dtype=np.int32))
# Cols from the right Dataset.
assert_array_equal(result.id_ba... | 212 | 213 | 710 | 14 | 198 | 972d5defe3218bd62b741e6a2f11f5b3/riptable | riptable/tests/test_merge.py | Python | test_merge2_sql_semantics_innerjoin_single_keep_Nonefirst | test_merge2_sql_semantics_innerjoin_single_keep_Nonefirst | 2,871 | 2,938 | 2,871 | 2,871 | a2c4661b5d0574c6e6e8bd2394891f3c6ef39c02 | bigcode/the-stack | train |
1821af250a88b60789200f70 | train | function | def test_merge2_sql_semantics_leftjoin_single_keep_Nonelast():
"""
Test that merge2 matches the following SQL query:
select
f.id as foo_id,
f.col1 as foo_col1,
f.col2 as foo_col2,
b.id as bar_id,
b.col1 as bar_col1,
b.col2 as bar_col2,
b.st... | def test_merge2_sql_semantics_leftjoin_single_keep_Nonelast():
| """
Test that merge2 matches the following SQL query:
select
f.id as foo_id,
f.col1 as foo_col1,
f.col2 as foo_col2,
b.id as bar_id,
b.col1 as bar_col1,
b.col2 as bar_col2,
b.strcol as bar_strcol
from
sql_semantics.foo as f
... | (result.col1, rt.FA([5, 5, 8, inv, 10, inv], dtype=np.int32))
# Cols from the left Dataset.
assert_array_equal(result.id_foo, rt.FA([1, 2, 3, 4, 5, 6], dtype=np.int32))
assert_array_equal(result.col2_foo, rt.FA([inv, 5, inv, 1, 1, 4], dtype=np.int32))
# Cols from the right Dataset.
assert_a... | 237 | 238 | 796 | 16 | 221 | 972d5defe3218bd62b741e6a2f11f5b3/riptable | riptable/tests/test_merge.py | Python | test_merge2_sql_semantics_leftjoin_single_keep_Nonelast | test_merge2_sql_semantics_leftjoin_single_keep_Nonelast | 2,650 | 2,723 | 2,650 | 2,650 | e8d87a739d54083042e4f378c8e629fa796b5761 | bigcode/the-stack | train |
804c51b20b0d30069f50ee8f | train | function | @pytest.mark.parametrize(
"left,right,on,check_sorted,should_fail",
[
pytest.param(
rt.Dataset(
{'A': [1, 5, 10], 'left_val': ['a', 'b', 'c'], 'left_grp': [1, 1, 1]}
),
rt.Dataset(
{
'X': [1, 2, 3, 6, 7],
... | @pytest.mark.parametrize(
"left,right,on,check_sorted,should_fail",
[
pytest.param(
rt.Dataset(
{'A': [1, 5, 10], 'left_val': ['a', 'b', 'c'], 'left_grp': [1, 1, 1]}
),
rt.Dataset(
{
'X': [1, 2, 3, 6, 7],
... | """
Test for verifying 'merge_asof' checks the sortedness of the 'on' columns before merging.
"""
# Unpack the 'on' parameter (if needed) until 'merge_asof' has been
# modified to allow a tuple to be passed for the 'on' parameter (instead of left_on+right_on).
left_on, right_on = on if isin... | @pytest.mark.parametrize(
"left,right,on,check_sorted,should_fail",
[
pytest.param(
rt.Dataset(
{'A': [1, 5, 10], 'left_val': ['a', 'b', 'c'], 'left_grp': [1, 1, 1]}
),
rt.Dataset(
{
'X': [1, 2, 3, 6, 7],
... | 933 | 256 | 1,144 | 933 | 0 | 972d5defe3218bd62b741e6a2f11f5b3/riptable | riptable/tests/test_merge.py | Python | test_merge_asof_unsorted_fails | test_merge_asof_unsorted_fails | 6,513 | 6,648 | 6,513 | 6,620 | a0a58a478643409fa3bf5c74a2e5e396877a1501 | bigcode/the-stack | train |
c339ed02e8a5dbb5237d2909 | train | function | @pytest.mark.xfail(
reason="RIP-260: Result of this test is generally correct, but the ordering of the rows is "
"slightly different (and incorrect) so even though the data is correct the test fails.",
strict=True
)
def test_merge2_sql_semantics_rightjoin_multi_keep_firstlast():
"""
Te... | @pytest.mark.xfail(
reason="RIP-260: Result of this test is generally correct, but the ordering of the rows is "
"slightly different (and incorrect) so even though the data is correct the test fails.",
strict=True
)
def test_merge2_sql_semantics_rightjoin_multi_keep_firstlast():
| """
Test that merge2 matches the following SQL query:
select
f.id as foo_id,
f.col1 as foo_col1,
f.col2 as foo_col2,
f.team_name as foo_teamname,
b.id as bar_id,
b.col1 as bar_col1,
b.col2 as bar_col2,
b.strcol as bar_strcol
fr... | 9], dtype=np.int32))
# Cols from the left Dataset.
assert_array_equal(result.id_foo, rt.FA([1, 2, 3, 4, 5, 6, 7, 8], dtype=np.int32))
assert_array_equal(
result.team_name,
rt.FA([b'Phillies', b'Eagles', b'76ers', b'Flyers', b'Union', b'Wings', b'Fusion', b'Fight'])
)
# Col... | 255 | 256 | 952 | 68 | 187 | 972d5defe3218bd62b741e6a2f11f5b3/riptable | riptable/tests/test_merge.py | Python | test_merge2_sql_semantics_rightjoin_multi_keep_firstlast | test_merge2_sql_semantics_rightjoin_multi_keep_firstlast | 5,843 | 5,937 | 5,843 | 5,848 | 415ede0d99acf65ec2d93b984e7e3d713ab25fe1 | bigcode/the-stack | train |
f98fc244ef51d7d69fc4b06a | train | function | @pytest.mark.parametrize("right_on", ['Baz', ['Baz']])
def test_merge_on_xor_left_on_required(right_on):
# Test that `merge` raises a ValueError if a user calls it without specifying
# either the 'on' or 'left_on' parameters.
(ds1, ds2) = _create_merge_paramverify_dsets()
with pytest.raises(Value... | @pytest.mark.parametrize("right_on", ['Baz', ['Baz']])
def test_merge_on_xor_left_on_required(right_on):
# Test that `merge` raises a ValueError if a user calls it without specifying
# either the 'on' or 'left_on' parameters.
| (ds1, ds2) = _create_merge_paramverify_dsets()
with pytest.raises(ValueError):
rt.merge(ds1, ds2, right_on=right_on)
| _on='Baz')
@pytest.mark.parametrize("right_on", ['Baz', ['Baz']])
def test_merge_on_xor_left_on_required(right_on):
# Test that `merge` raises a ValueError if a user calls it without specifying
# either the 'on' or 'left_on' parameters.
| 63 | 64 | 98 | 59 | 4 | 972d5defe3218bd62b741e6a2f11f5b3/riptable | riptable/tests/test_merge.py | Python | test_merge_on_xor_left_on_required | test_merge_on_xor_left_on_required | 530 | 537 | 530 | 533 | f66d41cb7b9d598d937833556379ccf609286d4f | bigcode/the-stack | train |
3409b294d3b3492a6e755cfa | train | function | @pytest.mark.parametrize(
"left,right,left_grp,right_grp,on",
[
pytest.param(*TestDataset.hockey(), id="hockey"),
pytest.param(
*TestDataset.sql_semantics_data('col1'), id="sql_semantics_singlekey"
),
],
)
@pytest.mark.parametrize(
"how", [
'left', ... | @pytest.mark.parametrize(
"left,right,left_grp,right_grp,on",
[
pytest.param(*TestDataset.hockey(), id="hockey"),
pytest.param(
*TestDataset.sql_semantics_data('col1'), id="sql_semantics_singlekey"
),
],
)
@pytest.mark.parametrize(
"how", [
'left', ... | """
Verify the output (merged) Dataset returned by merge2 has the same
number of rows as the computed fancy indexes for the join.
"""
# Call the merge function with the Datasets to give us a baseline for comparison.
merge_result = rt.merge2(
left, right, on=on, how=how, keep=keep, ... | how == 'outer':
# TODO: Need to determine bounds for outer joins.
pytest.skip("Need to determine bounds for outer joins.")
#assert filt_filt_len <= filt_unfilt_len
#assert filt_filt_len <= unfilt_filt_len
else:
assert filt_filt_len <= filt_unfilt_len
assert fi... | 256 | 256 | 886 | 170 | 85 | 972d5defe3218bd62b741e6a2f11f5b3/riptable | riptable/tests/test_merge.py | Python | test_merge2_handles_invalids | test_merge2_handles_invalids | 1,735 | 1,830 | 1,735 | 1,759 | ea2dd082a43289ce0d3835c5f4bdd989a517f57b | bigcode/the-stack | train |
99b18524ef7943b6bca72407 | train | function | def test_merge2_sql_semantics_outerjoin_multi_keep_Nonelast():
"""
Test that merge2 matches the following SQL query:
select
f.id as foo_id,
f.col1 as foo_col1,
f.col2 as foo_col2,
f.team_name as foo_teamname,
b.id as bar_id,
b.col1 as bar_col1,
... | def test_merge2_sql_semantics_outerjoin_multi_keep_Nonelast():
| """
Test that merge2 matches the following SQL query:
select
f.id as foo_id,
f.col1 as foo_col1,
f.col2 as foo_col2,
f.team_name as foo_teamname,
b.id as bar_id,
b.col1 as bar_col1,
b.col2 as bar_col2,
b.strcol as bar_strcol
fr... | , inv, inv, inv, inv, inv, inv, inv], dtype=np.int32))
assert_array_equal(
result.team_name,
rt.FA([b'Phillies', b'Eagles', b'76ers', b'Flyers', b'Union', b'Wings', b'Fusion', b'Fight', b'', b'', b'', b'', b'', b'', b'', b'', b'']))
# Cols from the right Dataset.
assert_array_equal(
... | 255 | 256 | 1,065 | 16 | 239 | 972d5defe3218bd62b741e6a2f11f5b3/riptable | riptable/tests/test_merge.py | Python | test_merge2_sql_semantics_outerjoin_multi_keep_Nonelast | test_merge2_sql_semantics_outerjoin_multi_keep_Nonelast | 5,003 | 5,090 | 5,003 | 5,003 | 8d51d7492574eadffbf67a582c74e8def96001dc | bigcode/the-stack | train |
c8bb6b308ade67ef6e9e55ce | train | function | def test_merge2_sql_semantics_rightjoin_single():
"""
Test that merge2 matches the following SQL query:
select
f.id as foo_id,
f.col1 as foo_col1,
f.col2 as foo_col2,
b.id as bar_id,
b.col1 as bar_col1,
b.col2 as bar_col2,
b.strcol as bar_s... | def test_merge2_sql_semantics_rightjoin_single():
| """
Test that merge2 matches the following SQL query:
select
f.id as foo_id,
f.col1 as foo_col1,
f.col2 as foo_col2,
b.id as bar_id,
b.col1 as bar_col1,
b.col2 as bar_col2,
b.strcol as bar_strcol
from
sql_semantics.foo as f
... | .
assert_array_equal(
result.id_bar, rt.FA([8, 9, 8, 9, 3, inv, 1, 2, inv], dtype=np.int32)
)
assert_array_equal(
result.col2_bar, rt.FA([5, inv, 5, inv, inv, inv, 4, inv, inv], dtype=np.int32)
)
assert_array_equal(
result.strcol,
rt.FA(
[
... | 170 | 171 | 572 | 11 | 159 | 972d5defe3218bd62b741e6a2f11f5b3/riptable | riptable/tests/test_merge.py | Python | test_merge2_sql_semantics_rightjoin_single | test_merge2_sql_semantics_rightjoin_single | 2,311 | 2,385 | 2,311 | 2,311 | d7260673705f2d2e8422a408c74780594e723917 | bigcode/the-stack | train |
54e5cb29241ed2475ccb1f2d | train | function | def test_merge2_sql_semantics_leftjoin_multi_keep_lastNone():
"""
Test that merge2 matches the following SQL query:
select
f.id as foo_id,
f.col1 as foo_col1,
f.col2 as foo_col2,
b.id as bar_id,
b.col1 as bar_col1,
b.col2 as bar_col2,
b.str... | def test_merge2_sql_semantics_leftjoin_multi_keep_lastNone():
| """
Test that merge2 matches the following SQL query:
select
f.id as foo_id,
f.col1 as foo_col1,
f.col2 as foo_col2,
b.id as bar_id,
b.col1 as bar_col1,
b.col2 as bar_col2,
b.strcol as bar_strcol
from (
select *
from s... | # 6 rows in set (0.0019 sec)
inv = rt.int32.inv
# Intersection cols (the 'on' cols)
assert_array_equal(result.col1, rt.FA([5, 5, 8, inv, 10, inv], dtype=np.int32))
assert_array_equal(result.col2, rt.FA([inv, 5, inv, 1, 1, 4], dtype=np.int32))
# Cols from the left Dataset.
assert_ar... | 227 | 228 | 761 | 14 | 213 | 972d5defe3218bd62b741e6a2f11f5b3/riptable | riptable/tests/test_merge.py | Python | test_merge2_sql_semantics_leftjoin_multi_keep_lastNone | test_merge2_sql_semantics_leftjoin_multi_keep_lastNone | 5,168 | 5,238 | 5,168 | 5,168 | 1ed823f7cc1a6d30c7a163959ed77035f6c8365e | bigcode/the-stack | train |
7677510da754ec195fc690d8 | train | function | def test_merge2_sql_semantics_leftjoin_multi_keep_firstlast():
"""
Test that merge2 matches the following SQL query:
select
f.id as foo_id,
f.col1 as foo_col1,
f.col2 as foo_col2,
f.team_name as foo_teamname,
b.id as bar_id,
b.col1 as bar_col1,
... | def test_merge2_sql_semantics_leftjoin_multi_keep_firstlast():
| """
Test that merge2 matches the following SQL query:
select
f.id as foo_id,
f.col1 as foo_col1,
f.col2 as foo_col2,
f.team_name as foo_teamname,
b.id as bar_id,
b.col1 as bar_col1,
b.col2 as bar_col2,
b.strcol as bar_strcol
fr... | _array_equal(
result.team_name,
rt.FA([b'Phillies', b'Eagles', b'Eagles', b'76ers', b'Flyers', b'Union', b'Wings', b'Fusion', b'Fight', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'']))
# Cols from the right Dataset.
assert_array_equal(
result.id_bar, rt.FA([inv, 8, 11, inv, inv... | 252 | 253 | 845 | 14 | 238 | 972d5defe3218bd62b741e6a2f11f5b3/riptable | riptable/tests/test_merge.py | Python | test_merge2_sql_semantics_leftjoin_multi_keep_firstlast | test_merge2_sql_semantics_leftjoin_multi_keep_firstlast | 5,751 | 5,840 | 5,751 | 5,751 | eda8431dcd44c97e673254985179e9b4e26e5b48 | bigcode/the-stack | train |
bf6505b15f645d19a3ef1782 | train | function | def test_merge2_sql_semantics_outerjoin_multi_keep_Nonefirst():
"""
Test that merge2 matches the following SQL query:
select
f.id as foo_id,
f.col1 as foo_col1,
f.col2 as foo_col2,
f.team_name as foo_teamname,
b.id as bar_id,
b.col1 as bar_col1,
... | def test_merge2_sql_semantics_outerjoin_multi_keep_Nonefirst():
| """
Test that merge2 matches the following SQL query:
select
f.id as foo_id,
f.col1 as foo_col1,
f.col2 as foo_col2,
f.team_name as foo_teamname,
b.id as bar_id,
b.col1 as bar_col1,
b.col2 as bar_col2,
b.strcol as bar_strcol
fr... | # | foo_id | foo_col1 | foo_col2 | bar_id | bar_col1 | bar_col2 | bar_strcol |
# +--------+----------+----------+--------+----------+----------+------------+
# | 2 | 5 | 5 | 8 | 5 | 5 | Lombard |
# +--------+----------+----------+--------+----------+----------... | 255 | 256 | 1,054 | 14 | 241 | 972d5defe3218bd62b741e6a2f11f5b3/riptable | riptable/tests/test_merge.py | Python | test_merge2_sql_semantics_outerjoin_multi_keep_Nonefirst | test_merge2_sql_semantics_outerjoin_multi_keep_Nonefirst | 4,914 | 5,000 | 4,914 | 4,914 | 838c145ba55a6d8894556b0e8c32b6ad20528bfb | bigcode/the-stack | train |
e33ea99c264d13d9e4578ba7 | train | function | @pytest.mark.parametrize(
"left,right,left_grp,right_grp,on",
[pytest.param(*TestDataset.hockey(), id="hockey")],
)
@pytest.mark.parametrize(
"how", [
'left', 'right', 'inner',
pytest.param('outer', marks=xfail_rip260_outermerge_left_keep)
]
)
@pytest.mark.parametrize("keep", [... | @pytest.mark.parametrize(
"left,right,left_grp,right_grp,on",
[pytest.param(*TestDataset.hockey(), id="hockey")],
)
@pytest.mark.parametrize(
"how", [
'left', 'right', 'inner',
pytest.param('outer', marks=xfail_rip260_outermerge_left_keep)
]
)
@pytest.mark.parametrize("keep", [... | """
Verify the output (merged) Dataset returned by merge2 has the same
number of rows as the computed fancy indexes for the join.
"""
from riptable.rt_merge import JoinIndices, _create_merge_fancy_indices, _normalize_keep
# Test #1: Calculate the fancy-indices for the join.
_keep = _... | foo, bar, foo_grouping, bar_grouping, on_col_name
)
@pytest.mark.parametrize(
"left,right,left_grp,right_grp,on",
[pytest.param(*TestDataset.hockey(), id="hockey")],
)
@pytest.mark.parametrize(
"how", [
'left', 'right', 'inner',
pytest.param('outer', marks=xfail_rip260_outer... | 164 | 165 | 551 | 146 | 18 | 972d5defe3218bd62b741e6a2f11f5b3/riptable | riptable/tests/test_merge.py | Python | test_merge2_result_matches_computed_fancyindex | test_merge2_result_matches_computed_fancyindex | 1,519 | 1,575 | 1,519 | 1,538 | b4df23867ee3073e53e983ea6d4cb9c14b65a287 | bigcode/the-stack | train |
06328fe24459cb88c69801f7 | train | function | @pytest.mark.parametrize("left_on", ['Foo', ['Foo']])
@pytest.mark.parametrize("right_on", ['Baz', ['Baz']])
def test_merge_columns_overlap_no_suffix(left_on, right_on):
# Test that `merge` raises a ValueError if it detects a naming collision between
# the left and right datasets and no suffix was specified... | @pytest.mark.parametrize("left_on", ['Foo', ['Foo']])
@pytest.mark.parametrize("right_on", ['Baz', ['Baz']])
def test_merge_columns_overlap_no_suffix(left_on, right_on):
# Test that `merge` raises a ValueError if it detects a naming collision between
# the left and right datasets and no suffix was specified... | (ds1, ds2) = _create_merge_paramverify_dsets()
with pytest.raises(ValueError):
rt.merge(ds1, ds2, left_on=left_on, right_on=right_on, suffixes=('', ''))
| @pytest.mark.parametrize("left_on", ['Foo', ['Foo']])
@pytest.mark.parametrize("right_on", ['Baz', ['Baz']])
def test_merge_columns_overlap_no_suffix(left_on, right_on):
# Test that `merge` raises a ValueError if it detects a naming collision between
# the left and right datasets and no suffix was specified... | 76 | 64 | 127 | 76 | 0 | 972d5defe3218bd62b741e6a2f11f5b3/riptable | riptable/tests/test_merge.py | Python | test_merge_columns_overlap_no_suffix | test_merge_columns_overlap_no_suffix | 637 | 645 | 637 | 641 | ddda4172694bad587890ebcd757b1fa28d9e8045 | bigcode/the-stack | train |
7e0c31a82db8100646431447 | train | function | def test_merge2_sql_semantics_innerjoin_multi():
"""
Test that merge2 matches the following SQL query:
select
f.id as foo_id,
f.col1 as foo_col1,
f.col2 as foo_col2,
b.id as bar_id,
b.col1 as bar_col1,
b.col2 as bar_col2,
b.strcol as bar_st... | def test_merge2_sql_semantics_innerjoin_multi():
| """
Test that merge2 matches the following SQL query:
select
f.id as foo_id,
f.col1 as foo_col1,
f.col2 as foo_col2,
b.id as bar_id,
b.col1 as bar_col1,
b.col2 as bar_col2,
b.strcol as bar_strcol
from
sql_semantics.foo as f
... | )
# Cols from the right Dataset.
assert_array_equal(
result.id_bar, rt.FA([1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=np.int32)
)
assert_array_equal(
result.strcol,
rt.FA(
[
b'Chestnut',
b'Pine',
b'Walnut',
... | 143 | 144 | 481 | 11 | 132 | 972d5defe3218bd62b741e6a2f11f5b3/riptable | riptable/tests/test_merge.py | Python | test_merge2_sql_semantics_innerjoin_multi | test_merge2_sql_semantics_innerjoin_multi | 4,309 | 4,362 | 4,309 | 4,309 | fdd4f455d3a59bda9850edaf25a488b5769f967b | bigcode/the-stack | train |
531defcb6c31404e80f86926 | train | function | def test_merge2_sql_semantics_rightjoin_single_keep_firstlast():
"""
Test that merge2 matches the following SQL query:
select
f.id as foo_id,
f.col1 as foo_col1,
f.col2 as foo_col2,
b.id as bar_id,
b.col1 as bar_col1,
b.col2 as bar_col2,
b.... | def test_merge2_sql_semantics_rightjoin_single_keep_firstlast():
| """
Test that merge2 matches the following SQL query:
select
f.id as foo_id,
f.col1 as foo_col1,
f.col2 as foo_col2,
b.id as bar_id,
b.col1 as bar_col1,
b.col2 as bar_col2,
b.strcol as bar_strcol
from (
select *
from s... | rows in set (0.0016 sec)
inv = rt.int32.inv
# Intersection cols (the 'on' cols)
assert_array_equal(result.col1, rt.FA([5, 8, inv, 10], dtype=np.int32))
# Cols from the left Dataset.
assert_array_equal(result.id_foo, rt.FA([1, 3, 4, 5], dtype=np.int32))
assert_array_equal(result.col2_f... | 227 | 228 | 763 | 14 | 213 | 972d5defe3218bd62b741e6a2f11f5b3/riptable | riptable/tests/test_merge.py | Python | test_merge2_sql_semantics_rightjoin_single_keep_firstlast | test_merge2_sql_semantics_rightjoin_single_keep_firstlast | 3,907 | 3,983 | 3,907 | 3,907 | b2cecabefef5a3a710cc0e602588c87d3d42401f | bigcode/the-stack | train |
797f15477fb861bfb7317b89 | train | function | def test_merge_lookup_inplace_multi():
foo, bar = TestDataset.sql_semantics()
foo.merge_lookup(
bar,
on=[('col1', 'col1'), ('col2', 'col2')],
suffix='_bar',
keep='first',
inplace=True
)
assert foo.get_nrows() == 6
# +--------+----------+-------... | def test_merge_lookup_inplace_multi():
| foo, bar = TestDataset.sql_semantics()
foo.merge_lookup(
bar,
on=[('col1', 'col1'), ('col2', 'col2')],
suffix='_bar',
keep='first',
inplace=True
)
assert foo.get_nrows() == 6
# +--------+----------+----------+--------+----------+----------+-----... | dtype=np.int32))
assert_array_equal(foo.col2, rt.FA([inv, 5, inv, 1, 1, 4], dtype=np.int32))
# Cols from the right Dataset.
assert_array_equal(foo.id_bar, rt.FA([8, 8, 3, inv, 1, inv], dtype=np.int32))
assert_array_equal(foo.col2_bar, rt.FA([5, 5, inv, inv, 4, inv], dtype=np.int32))
assert_a... | 158 | 159 | 530 | 8 | 150 | 972d5defe3218bd62b741e6a2f11f5b3/riptable | riptable/tests/test_merge.py | Python | test_merge_lookup_inplace_multi | test_merge_lookup_inplace_multi | 6,319 | 6,356 | 6,319 | 6,319 | 49ed79b7af1914b441046c5bede679e87a584830 | bigcode/the-stack | train |
7b5ec0a6f06c761d3091052e | train | function | @pytest.mark.parametrize("left_on", ['Foo', ['Foo']])
@pytest.mark.parametrize("right_on", ['Baz', ['Baz']])
def test_merge_columns_overlap_same_suffixes(left_on, right_on):
# Test that `merge` raises a ValueError if it detects a naming collision between
# the left and right datasets and the same suffix was... | @pytest.mark.parametrize("left_on", ['Foo', ['Foo']])
@pytest.mark.parametrize("right_on", ['Baz', ['Baz']])
def test_merge_columns_overlap_same_suffixes(left_on, right_on):
# Test that `merge` raises a ValueError if it detects a naming collision between
# the left and right datasets and the same suffix was... | (ds1, ds2) = _create_merge_paramverify_dsets()
with pytest.raises(ValueError):
rt.merge(ds1, ds2, left_on=left_on, right_on=right_on, suffixes=('_x', '_x'))
| @pytest.mark.parametrize("left_on", ['Foo', ['Foo']])
@pytest.mark.parametrize("right_on", ['Baz', ['Baz']])
def test_merge_columns_overlap_same_suffixes(left_on, right_on):
# Test that `merge` raises a ValueError if it detects a naming collision between
# the left and right datasets and the same suffix was... | 78 | 64 | 132 | 78 | 0 | 972d5defe3218bd62b741e6a2f11f5b3/riptable | riptable/tests/test_merge.py | Python | test_merge_columns_overlap_same_suffixes | test_merge_columns_overlap_same_suffixes | 648 | 656 | 648 | 652 | 568f35681e832354135a27dbf51aa4170ed31fac | bigcode/the-stack | train |
5d5f4f30fd7464045d73bf79 | train | class | class MergeTest(unittest.TestCase):
def test_merge_single(self):
error_tol = 0.00001
ds1 = rt.Dataset({'A': [0, 1, 6, 7], 'B': [1.2, 3.1, 9.6, 21]})
ds2 = rt.Dataset({'X': [0, 1, 6, 9], 'C': [2.4, 6.2, 19.2, 53]})
ds = rt.merge(ds1, ds2, left_on='A', right_on='X', how='inner')... | class MergeTest(unittest.TestCase):
| def test_merge_single(self):
error_tol = 0.00001
ds1 = rt.Dataset({'A': [0, 1, 6, 7], 'B': [1.2, 3.1, 9.6, 21]})
ds2 = rt.Dataset({'X': [0, 1, 6, 9], 'C': [2.4, 6.2, 19.2, 53]})
ds = rt.merge(ds1, ds2, left_on='A', right_on='X', how='inner')
self.assertIsInstance(ds,... | .int32), arange(3, dtype=np.int64)
)
assert d1.dtype == d2.dtype
# should force float upcasting
[d1], [d2] = normalize_keys(
arange(10, dtype=np.int32), arange(3, dtype=np.uint64)
)
assert d1.dtype == d2.dtype
# should convert string to cat... | 256 | 256 | 3,711 | 7 | 248 | 972d5defe3218bd62b741e6a2f11f5b3/riptable | riptable/tests/test_merge.py | Python | MergeTest | MergeTest | 83 | 398 | 83 | 83 | 5d21b935cf566ae7a037d7b306337e6b50118256 | bigcode/the-stack | train |
77703b3249be641f0ff81ca0 | train | function | @pytest.mark.parametrize(
"on,side_on,for_left,is_error,expected",
[
# Cases covering the "old-style" 'on'/'left_on'/'right_on' parameter parsing.
# Note that the 'for_left' parameter is irrelevant for this parsing mode.
pytest.param('foo', None, True, False, ['foo'], id="on_str"),
... | @pytest.mark.parametrize(
"on,side_on,for_left,is_error,expected",
[
# Cases covering the "old-style" 'on'/'left_on'/'right_on' parameter parsing.
# Note that the 'for_left' parameter is irrelevant for this parsing mode.
pytest.param('foo', None, True, False, ['foo'], id="on_str"),
... | """
Basic input/output checks for the private _extract_on_columns() function.
"""
if is_error:
with pytest.raises(ValueError):
rt.rt_merge._extract_on_columns(on, side_on, for_left, 'on', is_optional=False)
else:
result = rt.rt_merge._extract_on_columns(on, side_... | @pytest.mark.parametrize(
"on,side_on,for_left,is_error,expected",
[
# Cases covering the "old-style" 'on'/'left_on'/'right_on' parameter parsing.
# Note that the 'for_left' parameter is irrelevant for this parsing mode.
pytest.param('foo', None, True, False, ['foo'], id="on_str"),
... | 467 | 166 | 555 | 467 | 0 | 972d5defe3218bd62b741e6a2f11f5b3/riptable | riptable/tests/test_merge.py | Python | test_merge_extract_on_columns | test_merge_extract_on_columns | 1,133 | 1,187 | 1,133 | 1,177 | fd3e7e857d030fcc28e3b06c0e83c87814c6a537 | bigcode/the-stack | train |
6cbe1a5011191397b75acd80 | train | class | class ConversionUtilityTest:
def test_normalize(self):
c1 = Cat(['A', 'B', 'C'])
c2 = Cat(arange(3) + 1, ['A', 'B', 'C'])
[d1], [d2] = normalize_keys(c1, c2)
assert d1.dtype == d2.dtype
[d1], [d2] = normalize_keys(
arange(10, dtype=np.int32), arange(3, ... | class ConversionUtilityTest:
| def test_normalize(self):
c1 = Cat(['A', 'B', 'C'])
c2 = Cat(arange(3) + 1, ['A', 'B', 'C'])
[d1], [d2] = normalize_keys(c1, c2)
assert d1.dtype == d2.dtype
[d1], [d2] = normalize_keys(
arange(10, dtype=np.int32), arange(3, dtype=np.int64)
)
... | times for one or both Datasets.
# For example: rt.merge2(left_ds, right_ds, on=['a', 'b', ('c', 'a')], how='left')
xfail_rip260_outermerge_left_keep = pytest.mark.xfail(
reason="RIP-260: 'keep' for the 'left' Dataset in a multi-column outer merge is broken and needs to be fixed.",
raises=ValueErr... | 104 | 104 | 348 | 5 | 99 | 972d5defe3218bd62b741e6a2f11f5b3/riptable | riptable/tests/test_merge.py | Python | ConversionUtilityTest | ConversionUtilityTest | 47 | 80 | 47 | 47 | 8846addc767376c97591f4db5e85288367cf54fc | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.