code stringlengths 281 23.7M |
|---|
.skipif(IS_WIN, reason='Flaky on Windows')
def test_initialize(client_server_pair):
(client, server) = client_server_pair
response = send_initialize_request(client)
assert (server.workspace is not None)
selector = response['capabilities']['notebookDocumentSync']['notebookSelector']
assert isinstance... |
def copy_codebase(args):
from shutil import copytree, ignore_patterns
new_code_path = os.path.join(args.output_dir, args.logs, args.name, 'code')
if os.path.exists(new_code_path):
print(f'Error. Experiment already exists at {new_code_path}. Use --name to specify a new experiment.')
return (-... |
def get_account_and_private_key(account_manager: AccountManager, address: Optional[Address], password_file: Optional[TextIO]) -> Tuple[(Address, PrivateKey)]:
if (not address):
address_hex = prompt_account(account_manager)
else:
address_hex = to_checksum_address(address)
if password_file:
... |
class ConfigFile(pg_api.Settings):
_e_factors = ('path',)
_e_label = 'CONFIGFILE'
def _e_metas(self):
(yield (None, len(self.keys())))
def __init__(self, path, open=open):
self.path = path
self._open = open
self._store = []
self._restore = {}
def __repr__(self... |
class RepBlock(nn.Module):
def __init__(self, input_channel, output_channel, kernel_size=3, groups=1, stride=1, deploy=False, use_se=False):
super().__init__()
self.use_se = use_se
self.input_channel = input_channel
self.output_channel = output_channel
self.deploy = deploy
... |
def test_runresult_assertion_on_xfail(pytester: Pytester) -> None:
pytester.makepyfile('\n import pytest\n\n pytest_plugins = "pytester"\n\n .xfail\n def test_potato():\n assert False\n ')
result = pytester.runpytest()
result.assert_outcomes(xfailed=1)
assert (r... |
def decimalToBinaryFixLength(_length, _decimal):
binNum = bin(int(_decimal))[2:]
outputNum = [int(item) for item in binNum]
if (len(outputNum) < _length):
outputNum = np.concatenate((np.zeros(((_length - len(outputNum)),)), np.array(outputNum)))
else:
outputNum = np.array(outputNum)
... |
_module()
class MaskScoringRCNN(TwoStageDetector):
def __init__(self, backbone, rpn_head, roi_head, train_cfg, test_cfg, neck=None, pretrained=None):
super(MaskScoringRCNN, self).__init__(backbone=backbone, neck=neck, rpn_head=rpn_head, roi_head=roi_head, train_cfg=train_cfg, test_cfg=test_cfg, pretrained=p... |
_fixtures(WebFixture)
def test_column_slots(web_fixture):
fixture = web_fixture
widget = Div(fixture.view).use_layout(ColumnLayout('column_name_a', 'column_name_b').with_slots())
(column_a, column_b) = widget.layout.columns.values()
assert ('column_name_a' in column_a.available_slots)
assert ('colum... |
class Version():
def __init__(self, vstring=None):
if vstring:
self.parse(vstring)
warnings.warn('distutils Version classes are deprecated. Use packaging.version instead.', DeprecationWarning, stacklevel=2)
def __repr__(self):
return "{} ('{}')".format(self.__class__.__name__... |
def test_popup_sticky():
m = Map()
popup = Popup('Some text.', sticky=True).add_to(m)
rendered = popup._template.render(this=popup, kwargs={})
expected = '\n var {popup_name} = L.popup({{\n "autoClose": false, "closeOnClick": false, "maxWidth": "100%"\n }});\n var {html_name} = $(`<div i... |
def parallel_apply(fct, model, inputs, device_ids):
modules = nn.parallel.replicate(model, device_ids)
assert (len(modules) == len(inputs))
lock = threading.Lock()
results = {}
grad_enabled = torch.is_grad_enabled()
def _worker(i, module, input):
torch.set_grad_enabled(grad_enabled)
... |
def crop_face(image, rotate=True, quiet_mode=True):
(height, width, channels) = image.shape
detections = detector.detect_faces(image)
image = PIL_image_convert(image)
if ((detections == None) or (len(detections) == 0)):
if (not quiet_mode):
print('***No Face detected. ***')
r... |
class Poly(_LRScheduler):
def __init__(self, optimizer, num_epochs, iters_per_epoch=0, warmup_epochs=0, last_epoch=(- 1)):
self.iters_per_epoch = iters_per_epoch
self.cur_iter = 0
self.N = (num_epochs * iters_per_epoch)
self.warmup_iters = (warmup_epochs * iters_per_epoch)
su... |
class TestTransformerConvert(unittest.TestCase):
def test_default(self):
tfm = new_transformer()
tfm.convert()
actual_args = tfm.output_format
expected_args = {}
self.assertEqual(expected_args, actual_args)
actual_res = tfm.build(INPUT_FILE, OUTPUT_FILE)
expec... |
class Solution(object):
def threeSumClosest(self, nums, target):
ls = len(nums)
sort_nums = sorted(nums)
res = ((nums[0] + nums[1]) + nums[2])
for i in range((ls - 2)):
(j, k) = ((i + 1), (ls - 1))
while (j < k):
temp = ((sort_nums[i] + sort_nu... |
class StereoDepthCamera(Camera):
def __init__(self, camera_cfg: StereoDepthCameraConfig, scene: sapien.Scene, renderer_type: str, articulation: sapien.Articulation=None):
self.camera_cfg = camera_cfg
assert (renderer_type == 'sapien'), renderer_type
self.renderer_type = renderer_type
... |
def attach_player_object_to_player(objectplayer: int, object_id: int, attachplayer: int, offset_x: float, offset_y: float, offset_z: float, rotation_x: float, rotation_y: float, rotation_z: float) -> bool:
return AttachPlayerObjectToPlayer(objectplayer, object_id, attachplayer, offset_x, offset_y, offset_z, rotatio... |
class ParseSelectionArgsTest(unittest.TestCase):
root = None
def ParseTest(self, tuplelist, indices, filelists=[]):
def tuple_fsencode(filetuple):
return tuple(map(os.fsencode, filetuple))
if (not self.root):
self.root = rpath.RPath(Globals.local_connection, 'rdiff-backup... |
class PalTrainer(_baseTrainer):
def __init__(self, config: Config, tmpFile: Optional[StrPath], modelFn: Callable[([], Tuple[(BaseCompressor, Distortion)])], optimizer: Type[torch.optim.Optimizer], scheduler: Type[torch.optim.lr_scheduler._LRScheduler], saver: Saver):
if (dist.get_rank() == 0):
r... |
def test_lazy_arguments(manager_nospawn):
def test_func(qtile, value, multiplier=1):
qtile.test_func_output = (value * multiplier)
config = ServerConfig
config.keys = [libqtile.config.Key(['control'], 'j', test_func(10)), libqtile.config.Key(['control'], 'k', test_func(5, multiplier=100))]
manag... |
class YesPornPleaseCom(BaseDownloader):
__name__ = 'YesPornPleaseCom'
__type__ = 'downloader'
__version__ = '0.02'
__status__ = 'testing'
__pattern__ = '
__config__ = [('enabled', 'bool', 'Activated', True), ('quality', '240p;360p;480p;720p', 'Quality', '720p')]
__description__ = 'YesPornPle... |
def get_matching_robots(name_prefix, username, limit=10):
admined_orgs = _basequery.get_user_organizations(username).switch(Team).join(TeamRole).where((TeamRole.name == 'admin'))
prefix_checks = False
for org in admined_orgs:
org_search = prefix_search(User.username, ((org.username + '+') + name_pre... |
def get_bpm_from_data(data, sampling_rate):
onset_env = librosa.onset.onset_strength(y=data, sr=sampling_rate)
wav_tempo = librosa.beat.tempo(onset_envelope=onset_env, sr=sampling_rate)
print(f'{ULTRASINGER_HEAD} BPM is {blue_highlighted(str(round(wav_tempo[0], 2)))}')
return wav_tempo[0] |
def main(old_args=False):
if old_args:
from .config.compat import compat_setup
(cfg, args) = compat_setup()
else:
args = parse_opt()
append_datetime = ((args.resume is None) and args.timestamp)
cfg = setup(args, modify_exp_name=append_datetime)
if (args.resume is not ... |
def format_script_list(scripts):
if (not scripts):
return '<No scripts>'
table = EvTable('|wdbref|n', '|wobj|n', '|wkey|n', '|wintval|n', '|wnext|n', '|wrept|n', '|wdb', '|wtypeclass|n', '|wdesc|n', align='r', border='tablecols')
for script in scripts:
nextrep = script.time_until_next_repeat... |
def get_points_array(iterable):
(first_choice, backup) = tee(iterable)
try:
if HAS_SHAPELY:
data = np.vstack([(np.array(shape.centroid.coords)[0] if isinstance(shape, BaseGeometry) else np.array(shape.centroid)) for shape in first_choice])
else:
data = np.vstack([np.array... |
def RegisterCalibration(client, name, default):
calibration = client.register(CalibrationProperty(name, default))
calibration.age = client.register(AgeValue((name + '.calibration.age')))
calibration.locked = client.register(BooleanProperty((name + '.calibration.locked'), False, persistent=True))
calibra... |
def test_emoji():
vol = Volume(emoji=True)
vol.volume = (- 1)
vol._update_drawer()
assert (vol.text == '')
vol.volume = 29
vol._update_drawer()
assert (vol.text == '')
vol.volume = 79
vol._update_drawer()
assert (vol.text == '')
vol.volume = 80
vol._update_drawer()
as... |
class Server(_EventDispatcher):
def __init__(self, address, port):
self._address = address
self._port = port
self._server = None
self._thread = _threading.Thread(target=self._run, daemon=True)
self._thread.start()
blurb = f'Server listening on {address}:{port}'
... |
def write_multi_ref(refdir, docid, summary):
def write(outfile, sents):
with open(outfile, 'w', encoding=ENCODE) as fout:
fout.write('\n'.join(sents))
fout.write('\n')
summary_line = ((' ' + SENT_SEP) + ' ').join(summary)
summaries = summary_line.strip().split(((' ' + SUM_SEP... |
class TestHAProxyCollector(CollectorTestCase):
def setUp(self):
config = get_collector_config('HAProxyCollector', {'interval': 10})
self.collector = HAProxyCollector(config, None)
def test_import(self):
self.assertTrue(HAProxyCollector)
(Collector, 'publish')
def test_should_work... |
def get_data():
test1 = 'I am very happy to see you again!'
test2 = 'Durian model is a very good speech synthesis!'
test3 = 'When I was twenty, I fell in love with a girl.'
test4 = 'I remove attention module in decoder and use average pooling to implement predicting r frames at once'
test5 = 'You ca... |
class SliceObjectAction(BaseAction):
valid_actions = {'SliceObject', 'OpenObject', 'CloseObject'}
def get_reward(self, state, prev_state, expert_plan, goal_idx):
if (state.metadata['lastAction'] not in self.valid_actions):
(reward, done) = (self.rewards['invalid_action'], False)
... |
def hrnet_w18(pretrained=False):
import yaml
hrnet_cfg = os.path.join('./models', 'model_info', 'hrnet_w18.yml')
with open(hrnet_cfg, 'r') as stream:
hrnet_cfg = yaml.safe_load(stream)
model = HighResolutionNet(hrnet_cfg)
if pretrained:
pretrained_weights = os.path.join(PROJECT_ROOT_... |
_module()
class GlobalAveragePooling(nn.Module):
def __init__(self):
super().__init__()
self.gap = nn.AdaptiveAvgPool2d((1, 1))
def init_weights(self):
pass
def forward(self, inputs):
if isinstance(inputs, tuple):
outs = tuple([self.gap(x) for x in inputs])
... |
class PyGameLCD1602Render():
def __init__(self, caption='LCD 1602'):
self.unit = 10
self.letter_size = (5, 8)
self.text_scale = (16, 2)
(self.space, self.gap) = ((self.unit * 4), (self.unit // 2))
size = ((width := ((((2 * self.space) + (self.gap * self.text_scale[0])) - self... |
def test_add_existing_plugin_updates_if_requested(tester: CommandTester, repo: TestRepository, installed: TestRepository) -> None:
pyproject = SelfCommand.get_default_system_pyproject_file()
with open(pyproject, 'w', encoding='utf-8', newline='') as f:
f.write(f'''[tool.poetry]
name = "poetry-instance"
... |
('pickle')
def test_frame_wise_torch_data_loader():
import torch
from torch.utils import data as data_utils
(X, Y) = _get_small_datasets(padded=False)
lengths = np.array([len(x) for x in X], dtype=int)
X = MemoryCacheFramewiseDataset(X, lengths, cache_size=len(X))
Y = MemoryCacheFramewiseDataset... |
class Mobile_Wallet(Imported_Wallet):
wallet_type = 'mobile'
def __init__(self, db: 'WalletDB', storage: WalletStorage, *, config: SimpleConfig):
if (not hasattr(db, 'imported_addresses')):
db.imported_addresses = {}
Imported_Wallet.__init__(self, db, storage, config=config)
... |
class Wav2Vec2PreTrainer(Trainer):
def __init__(self, *args, max_gumbel_temp=1, min_gumbel_temp=0, gumbel_temp_decay=1.0, **kwargs):
super().__init__(*args, **kwargs)
self.num_update_step = 0
self.max_gumbel_temp = max_gumbel_temp
self.min_gumbel_temp = min_gumbel_temp
self.g... |
class EmbedCancel(discord.ui.Button):
view: EmbedBuilder
def __init__(self):
super().__init__(label='Cancel', style=discord.ButtonStyle.red)
async def callback(self, interaction: discord.Interaction) -> T.Any:
(await interaction.response.send_message(f'{emote.xmark} | Embed sending cancelled... |
def download_PF_willow(dest='datasets/proposal-flow-willow'):
print('Fetching PF Willow dataset ')
url = '
file_path = join(dest, basename(url))
download_and_uncompress(url, file_path)
print('Downloading image pair list \n')
url = '
file_path = join(dest, basename(url))
download_and_unco... |
def select_device(device='', batch_size=None):
s = f'YOLOv5 {(git_describe() or date_modified())} torch {torch.__version__} '
device = str(device).strip().lower().replace('cuda:', '')
cpu = (device == 'cpu')
if cpu:
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
elif device:
os.environ['... |
class DummyStatefulDataLoader():
def __init__(self, dataloader: DataLoader) -> None:
self.dataloader = dataloader
self.state_dict_call_count = 0
self.load_state_dict_call_count = 0
def state_dict(self) -> Dict[(str, Any)]:
self.state_dict_call_count += 1
return {}
def... |
def test_specific_unknown(hatch, helpers, temp_dir, config_file):
config_file.model.template.plugins['default']['tests'] = False
config_file.save()
project_name = 'My.App'
with temp_dir.as_cwd():
result = hatch('new', project_name)
assert (result.exit_code == 0), result.output
project_pa... |
def pin_memory_batch(batch):
if torch.is_tensor(batch):
return batch.pin_memory()
elif isinstance(batch, string_classes):
return batch
elif isinstance(batch, collections.Mapping):
return {k: pin_memory_batch(sample) for (k, sample) in batch.items()}
elif isinstance(batch, collect... |
def test_ignored_extension(monkeypatch):
config = {'ignore': ['--option'], 'comment': []}
monkeypatch.setattr(interactive, 'get_config', (lambda x: config[x]))
parser = ArgumentParser()
fake_extension = Mock(flag='--option')
action = parser.add_argument('--option', dest='extensions', action='append_... |
class OrientedPushOracle(py_policy.PyPolicy):
def __init__(self, env, action_noise_std=0.0):
super(OrientedPushOracle, self).__init__(env.time_step_spec(), env.action_spec())
self._env = env
self._np_random_state = np.random.RandomState(0)
self.phase = 'move_to_pre_block'
sel... |
def pjit_with_cpu_fallback(fun: Callable, in_axis_resources, out_axis_resources, static_argnums: Union[(int, Sequence[int])]=(), donate_argnums: Union[(int, Sequence[int])]=(), backend: Optional[str]=None):
if (jax.devices(backend)[0].platform == 'cpu'):
return jax.jit(fun, static_argnums=static_argnums, do... |
class BalancedPositiveNegativeSamplerTest(tf.test.TestCase):
def test_subsample_all_examples(self):
numpy_labels = np.random.permutation(300)
indicator = tf.constant((np.ones(300) == 1))
numpy_labels = ((numpy_labels - 200) > 0)
labels = tf.constant(numpy_labels)
sampler = ba... |
def load_data_train(opt):
dataset = dset.ImageFolder(root=((opt.data_path + '/') + opt.normal_class), transform=transforms.Compose([transforms.Grayscale(), transforms.Resize((45, 45)), transforms.ToTensor(), transforms.Normalize([0.5], [0.5])]))
dataloader = torch.utils.data.DataLoader(dataset, batch_size=opt.b... |
def main(args):
pdf = pdfium.PdfDocument.new()
for fp in args.images:
image_obj = pdfium.PdfImage.new(pdf)
if (fp.suffix.lower() in ('.jpg', '.jpeg')):
image_obj.load_jpeg(fp, inline=args.inline)
else:
pil_image = PIL.Image.open(fp)
bitmap = pdfium.Pdf... |
class FakeScreenConfig(Config):
auto_fullscreen = True
groups = [libqtile.config.Group('a'), libqtile.config.Group('b'), libqtile.config.Group('c'), libqtile.config.Group('d')]
layouts = [layout.Max(), layout.RatioTile(), layout.Tile()]
floating_layout = libqtile.resources.default_config.floating_layout... |
class RandomMixing(nn.Module):
def __init__(self, num_tokens=196, **kwargs):
super().__init__()
self.random_matrix = nn.parameter.Parameter(data=torch.softmax(torch.rand(num_tokens, num_tokens), dim=(- 1)), requires_grad=False)
def forward(self, x):
(B, H, W, C) = x.shape
x = x.r... |
class ParserSuite(DataSuite):
required_out_section = True
base_path = '.'
files = find_test_files(pattern='parse*.test', exclude=['parse-errors.test'])
if (sys.version_info < (3, 10)):
files.remove('parse-python310.test')
def run_case(self, testcase: DataDrivenTestCase) -> None:
test... |
.grid
def test_transformer__only_best():
with (nullcontext() if PROJ_GTE_92 else pytest.raises(NotImplementedError, match='only_best requires PROJ 9.2')):
transformer = Transformer.from_crs(4326, 2964, only_best=True)
if (not grids_available('ca_nrc_ntv2_0.tif')):
with pytest.raises(Proj... |
def main():
make_warnings_comments()
parser = ArgumentParser(prog="prog='python -m lark.tools.standalone'", description='Lark Stand-alone Generator Tool', parents=[lalr_argparser], epilog='Look at the Lark documentation for more info on the options')
parser.add_argument('-c', '--compress', action='store_tru... |
class TestAssertUsageVarType(TestCaseUsage):
def test_success(self):
var = usage.UsageVariable('a', (lambda : None), 'artifact', None)
usage.assert_usage_var_type(var, 'artifact')
self.assertTrue(True)
def test_failure(self):
var = usage.UsageVariable('a', (lambda : None), 'artif... |
def cached_property(func: typing.Callable) -> property:
cached_name = f'_cached_{func}'
sentinel = object()
def inner(instance: object):
cache = getattr(instance, cached_name, sentinel)
if (cache is not sentinel):
return cache
result = func(instance)
setattr(insta... |
def test_waitid_eintr() -> None:
from .._subprocess_platform import wait_child_exiting
if (TYPE_CHECKING and ((sys.platform == 'win32') or (sys.platform == 'darwin'))):
return
if (not wait_child_exiting.__module__.endswith('waitid')):
pytest.skip('waitid only')
from .._subprocess_platfor... |
class File():
fileHeader: FileHeader
contents: List[bytes]
def FileHeader(self):
return self.fileHeader
def Content(self):
return self.contents
def serialize(self) -> bytes:
thisFile: dict = FileSchema().dump(self)
return msgpack.packb(thisFile, use_bin_type=True)
... |
def list_all_i2c_ports(path):
sensor_name = {}
for item in os.listdir(path):
power_label_path = '{path}/{item}'.format(path=path, item=item)
if item.endswith('_label'):
raw_name = cat(power_label_path).strip()
if ('NC' in raw_name):
logger.warn('Skipped NC... |
def test_interhand_3d_head():
N = 4
input_shape = (N, 2048, 8, 8)
inputs = torch.rand(input_shape, dtype=torch.float32)
target = [inputs.new_zeros(N, 42, 64, 64, 64), inputs.new_zeros(N, 1), inputs.new_zeros(N, 2)]
target_weight = [inputs.new_ones(N, 42, 1), inputs.new_ones(N, 1), inputs.new_ones(N)... |
def html(title=None, extra_content=''):
html = ('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"\n " <head>\n <meta content="text/html; charset=ISO-8859-1">\n <title>mechanize</title>\n </head>\n <body><a href=" % extra_content)
if (title is not None):
html = re.sub('<title>(.*)</titl... |
class Migrate():
def __init__(self, pipelines: Set[FeatureSetPipeline]) -> None:
self.pipelines = pipelines
def _send_logs_to_s3(self, file_local: bool, debug_mode: bool) -> None:
file_name = '../logging.json'
if ((not file_local) and os.path.exists(file_name)):
s3_client = b... |
.unit()
.parametrize(('markers', 'marker_name', 'expected_markers', 'expected_others'), [(None, 'not_found', [], []), ([], 'not_found', [], []), ([pytask.mark.produces(), pytask.mark.depends_on()], 'produces', [pytask.mark.produces()], [pytask.mark.depends_on()]), ([pytask.mark.produces(), pytask.mark.produces(), pytas... |
class TestCuDevice(unittest.TestCase):
def testCudaMatrixResize(self):
size_multiples = [1, 2, 4, 8, 16, 32]
num_matrices = 256
time_in_secs = 0.2
for size_multiple in size_multiples:
sizes = []
for i in range(num_matrices):
num_rows = kaldi_ma... |
def from_pretrained(model_name_or_path, checkpoint_file='model.pt', data_name_or_path='.', archive_map=None, **kwargs):
from fairseq import checkpoint_utils, file_utils
if (archive_map is not None):
if (model_name_or_path in archive_map):
model_name_or_path = archive_map[model_name_or_path]
... |
class Migration(migrations.Migration):
dependencies = [('conditions', '0022_condition_locked'), ('domain', '0048_meta'), ('questions', '0068_meta')]
operations = [migrations.CreateModel(name='Page', fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('crea... |
def test_logging_broken_makereport(testdir):
testdir.makepyfile(conftest='\n import pytest\n\n (hookwrapper=True, tryfirst=True)\n def pytest_runtest_makereport(call):\n if call.when == \'call\':\n raise Exception("This should not be hidden")\n yield\n ')... |
class DevDataset(Dataset):
def __init__(self, args, raw_datasets, cache_root):
self.raw_datasets = raw_datasets
cache_path = os.path.join(cache_root, 'ottqa_dev.cache')
if (os.path.exists(cache_path) and args.dataset.use_cache):
self.extended_data = torch.load(cache_path)
... |
def produce_pred_data(save_path, output_path):
test_word = np.load('data/testall_word.npy')
test_pos1 = np.load('data/testall_pos1.npy')
test_pos2 = np.load('data/testall_pos2.npy')
test_y = np.load('data/testall_y.npy')
with open('origin_data/test.txt', 'r', encoding='utf-8') as input:
test... |
class testsFromCommandLine(unittest.TestCase):
def setUp(self):
pynag.Model.ObjectDefinition.objects.get_all()
def tearDown(self):
self.assertEqual(False, pynag.Model.config.needs_reparse(), 'Seems like nagios configuration changed while running the unittests. Some of the tests might have made c... |
def test_bookmarks_folder(kodi):
resp = kodi.Files.GetDirectory(directory='plugin://video.kino.pub/bookmarks/161701/', properties=['country', 'year', 'rating', 'duration', 'director', 'trailer', 'plot', 'cast', 'imdbnumber', 'votes', 'fanart'])
assert (expected_results.BOOKMARK_FOLDER_CONTENT == resp['result'][... |
def test_dequantize():
levels = 20
qarr = np.random.randint(levels, size=(10, 10))
arr = mmcv.dequantize(qarr, (- 1), 1, levels)
assert (arr.shape == qarr.shape)
assert (arr.dtype == np.dtype('float64'))
for i in range(qarr.shape[0]):
for j in range(qarr.shape[1]):
assert (ar... |
def regex(pattern: Union[(str, Pattern)], flags: int=0):
async def func(flt, _, update: Update):
if isinstance(update, Message):
value = (update.text or update.caption)
elif isinstance(update, CallbackQuery):
value = update.data
elif isinstance(update, InlineQuery):
... |
def load_trec():
datasets = load_dataset('trec')
train_dataset = datasets['train']
test_dataset = datasets['test']
idxs = list(range(len(train_dataset)))
random.shuffle(idxs)
num_reserve = int((len(train_dataset) * 0.1))
dev_dataset = [{'text': train_dataset[i]['text'], 'label': train_datase... |
class GrabButton(rq.Request):
_request = rq.Struct(rq.Opcode(28), rq.Bool('owner_events'), rq.RequestLength(), rq.Window('grab_window'), rq.Card16('event_mask'), rq.Set('pointer_mode', 1, (X.GrabModeSync, X.GrabModeAsync)), rq.Set('keyboard_mode', 1, (X.GrabModeSync, X.GrabModeAsync)), rq.Window('confine_to', (X.NO... |
def parser_options():
parser = argparse.ArgumentParser()
parser.add_argument('--path_opt', default='option/RSITMD_AMFMN.yaml', type=str, help='path to a yaml options file')
parser.add_argument('--resume', default='checkpoint/rsitmd_aba/0/AMFMN_best.pth.tar', type=str, help='path to a yaml options file')
... |
def assert_none_blocked(ad_blocker):
assert_urls(ad_blocker, (NOT_OKAY_URLS + OKAY_URLS), False)
def assert_not_blocked(url, source_url, resource_type):
nonlocal ad_blocker
assert (not ad_blocker._is_blocked(url, source_url, resource_type))
run_function_on_dataset(assert_not_blocked) |
def torch_dtype_from_trt(dtype):
if (dtype == trt.bool):
return torch.bool
elif (dtype == trt.int8):
return torch.int8
elif (dtype == trt.int32):
return torch.int32
elif (dtype == trt.float16):
return torch.float16
elif (dtype == trt.float32):
return torch.flo... |
def test():
make_path(FLAGS)
config = load_config(FLAGS.config_file)
with open(FLAGS.map_file, 'rb') as f:
(char_to_id, id_to_char, tag_to_id, id_to_tag) = pickle.load(f)
test_sentences = load_sentences(FLAGS.test_file, FLAGS.lower, FLAGS.zeros)
update_tag_scheme(test_sentences, FLAGS.tag_sc... |
class TestIPTW():
def data(self):
df = pd.DataFrame()
df['A'] = [1, 1, 1, 1, 1, 0, 0, 0, 0, 0]
df['Y'] = [1, 0, 0, 0, 1, 1, 1, 0, 0, 1]
df['L'] = [1, 1, 0, 0, 0, 1, 1, 1, 1, 0]
return df
def test_unstabilized_weights(self, data):
ipt = IPTW(data, treatment='A', ou... |
class MoleculeDataset(Dataset):
def __init__(self, data: List[MoleculeDatapoint]):
self._data = data
self._scaler = None
self._batch_graph = None
self._random = Random()
def smiles(self, flatten: bool=False) -> Union[(List[str], List[List[str]])]:
if flatten:
... |
class Rumor_Data(Dataset):
def __init__(self, dataset):
self.text = torch.from_numpy(np.array(dataset['post_text']))
self.mask = torch.from_numpy(np.array(dataset['mask']))
self.label = torch.from_numpy(np.array(dataset['label']))
self.event_label = torch.from_numpy(np.array(dataset[... |
def test_hourglass_ae_backbone():
with pytest.raises(AssertionError):
HourglassAENet(num_stacks=0)
with pytest.raises(AssertionError):
HourglassAENet(downsample_times=5, stage_channels=[256, 256, 384, 384, 384])
model = HourglassAENet(num_stacks=1)
model.init_weights()
model.train()
... |
def _add_ancillary_variables_attrs(data_arr: xr.DataArray) -> None:
list_ancillary_variable_names = [da_ancillary.attrs['name'] for da_ancillary in data_arr.attrs.get('ancillary_variables', [])]
if list_ancillary_variable_names:
data_arr.attrs['ancillary_variables'] = ' '.join(list_ancillary_variable_na... |
class UpBlock2D(nn.Module):
def __init__(self, in_channels: int, prev_output_channel: int, out_channels: int, temb_channels: int, dropout: float=0.0, num_layers: int=1, resnet_eps: float=1e-06, resnet_time_scale_shift: str='default', resnet_act_fn: str='swish', resnet_groups: int=32, resnet_pre_norm: bool=True, out... |
class TestMarketplace():
('requests.request')
def test_timeout_exception(self, requests_mock):
requests_mock.side_effect = requests.exceptions.ReadTimeout()
user_api = RedHatUserApi(app_config)
subscription_api = RedHatSubscriptionApi(app_config)
customer_id = user_api.lookup_cus... |
class MultiHeadAttention(nn.Module):
def __init__(self, h, d_model, attn_p=0.1, static=False, share=3):
super(MultiHeadAttention, self).__init__()
self.h = h
self.d = d_model
self.share = share
assert ((d_model % h) == 0)
self.d_head = (d_model // h)
self.fc_q... |
def waitForEvent(emitter: EventEmitter, eventName: str, predicate: Callable[([Any], bool)], timeout: float, loop: asyncio.AbstractEventLoop) -> Awaitable:
promise = loop.create_future()
def resolveCallback(target: Any) -> None:
promise.set_result(target)
def rejectCallback(exception: Exception) -> N... |
def bleu_score(input: Union[(str, Sequence[str])], target: Sequence[Union[(str, Sequence[str])]], n_gram: int=4, weights: Optional[torch.Tensor]=None, device: Optional[torch.device]=None) -> torch.Tensor:
(input_len, target_len, matches_by_order, possible_matches_by_order) = _bleu_score_update(input, target, n_gram... |
.parametrize('manager, expected', zip(managers(), list(LEN.values())))
def test_get_compressed_output_size(manager, expected):
length = 10000
dtype = cupy.uint8
data = cupy.array(np.arange(0, (length // cupy.dtype(dtype).type(0).itemsize), dtype=dtype))
compressor_instance = manager()
compressed = c... |
class KaggleDataModel(DataModel):
def get_llm_side_data(self, serialize_method: str='tsv', num_visible_rows: int=3) -> Any:
formatted_tables = []
for _raw_data_path in self.raw_data_path:
table_data = self.raw_data[_raw_data_path]
table_name = self.raw_data_name[_raw_data_pat... |
def is_valid_balanceproof_signature(balance_proof: BalanceProofSignedState, sender_address: Address) -> SuccessOrError:
balance_hash = hash_balance_data(balance_proof.transferred_amount, balance_proof.locked_amount, balance_proof.locksroot)
data_that_was_signed = pack_balance_proof(nonce=balance_proof.nonce, ba... |
def test_validate_tpm_conditional_independence():
tpm = ExplicitTPM(np.array([[1, 0.0, 0.0, 0], [0, 0.5, 0.5, 0], [0, 0.5, 0.5, 0], [0, 0.0, 0.0, 1]]))
with pytest.raises(exceptions.ConditionallyDependentError):
tpm.conditionally_independent()
with pytest.raises(exceptions.ConditionallyDependentErro... |
def _get_n_and_p(bitwidth: tf.Variable, use_symmetric_encoding: tf.Variable) -> Tuple[(tf.Variable, tf.Variable)]:
bitwidth = tf.cast(bitwidth, tf.float32)
two_pow_bw = tf.cast(tf.pow(tf.cast(tf.constant(2), tf.float32), bitwidth), tf.float32)
two_pow_bw_minus_1 = tf.cast(tf.pow(tf.cast(tf.constant(2), tf.f... |
class Cityscapes(VisionDataset):
CityscapesClass = namedtuple('CityscapesClass', ['name', 'id', 'train_id', 'category', 'category_id', 'has_instances', 'ignore_in_eval', 'color'])
classes = [CityscapesClass('unlabeled', 0, 255, 'void', 0, False, True, (0, 0, 0)), CityscapesClass('ego vehicle', 1, 255, 'void', 0... |
_db
def test_get_conference_voucher_with_invalid_code(graphql_client, conference, mocker, requests_mock):
requests_mock.get(' status_code=404)
response = graphql_client.query('query($code: String!, $voucherCode: String!) {\n conference(code: $code) {\n voucher(code: $voucherCode) {\n ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.