code stringlengths 281 23.7M |
|---|
def predict_from_folder(model: str, input_folder: str, output_folder: str, folds: Union[(Tuple[int], List[int])], save_npz: bool, num_threads_preprocessing: int, num_threads_nifti_save: int, lowres_segmentations: Union[(str, None)], part_id: int, num_parts: int, tta: bool, mixed_precision: bool=True, overwrite_existing... |
class TrackItemCollection(PymiereBaseCollection):
def __init__(self, pymiere_id):
super(TrackItemCollection, self).__init__(pymiere_id, 'numItems')
def __getitem__(self, index):
return TrackItem(**super(TrackItemCollection, self).__getitem__(index))
def __iter__(self):
return iter([s... |
(wrapper=True)
def pytest_runtest_makereport(item: Item, call: CallInfo[None]) -> Generator[(None, TestReport, TestReport)]:
rep = (yield)
xfailed = item.stash.get(xfailed_key, None)
if item.config.option.runxfail:
pass
elif (call.excinfo and isinstance(call.excinfo.value, xfail.Exception)):
... |
class AllGatherGrad(torch.autograd.Function):
def forward(ctx: Any, tensor: torch.Tensor, group: Optional['torch.distributed.ProcessGroup']=None) -> torch.Tensor:
ctx.group = group
gathered_tensor = [torch.zeros_like(tensor) for _ in range(torch.distributed.get_world_size())]
torch.distribut... |
def _generate_sequential_enc_asset(file, model, image, precision=2):
model.eval()
input_image = image.clone()
enc_keys = {}
for (layer, module) in model.named_children():
image = module(image)
enc_keys[layer] = pystiche.TensorKey(image, precision=precision)
input = {'image': input_im... |
class _EvalSession():
def __init__(self, title: str, quantsim_factory: Callable, eval_func: Callable[([ort.InferenceSession], float)], results_dir: str, strict_validation: bool, ptq: bool):
self.title = title
self._quantsim_factory = quantsim_factory
self._eval_func = eval_func
self.... |
def parse_args():
parser = argparse.ArgumentParser(description='Generate training and test set of FUNSD ')
parser.add_argument('root_path', help='Root dir path of FUNSD')
parser.add_argument('--nproc', default=1, type=int, help='Number of process')
args = parser.parse_args()
return args |
def ValidateFormats(argFormat, argName, errors):
if (argFormat == 'xywh'):
return BBFormat.XYWH
elif (argFormat == 'xyrb'):
return BBFormat.XYX2Y2
elif (argFormat is None):
return BBFormat.XYWH
else:
errors.append(("argument %s: invalid value. It must be either 'xywh' or ... |
class TestConnectedGraphUtils(unittest.TestCase):
def test_get_module_act_func_pair_with_modules(self):
model = test_models.TinyModel().eval()
inp_tensor_list = [torch.randn(1, 3, 32, 32)]
module_act_func_pair = connectedgraph_utils.get_module_act_func_pair(model, inp_tensor_list)
se... |
def _recat_pooled_embedding_grad_out(grad_output: Tensor, num_features_per_rank: List[int]) -> Tensor:
grad_outputs_by_rank = grad_output.split(num_features_per_rank, dim=1)
return torch.cat([grad_output_by_rank.contiguous().view((- 1)) for grad_output_by_rank in grad_outputs_by_rank], dim=0) |
class TestFileScope():
def test_by_module(self, pytester: pytest.Pytester) -> None:
test_file = "\n import pytest\n class TestA:\n .parametrize('i', range(10))\n def test(self, i):\n pass\n\n class TestB:\n .par... |
class Trainer_t3():
def __init__(self, net, t_net, train_loader, test_loader, optimizer, optimizer_t, lr_scheduler, lr_scheduler_t, model_name, train_loger=None, pruned=False):
self.net = net
self.t_net = t_net
self.train_loader = train_loader
self.test_loader = test_loader
s... |
_bad_gc_old_pyvista
.allow_bad_gc_pyside
.parametrize('close_event', ['plotter_close', 'window_close', pytest.param('q_key_press', marks=pytest.mark.allow_bad_gc), 'menu_exit', 'del_finalizer'])
.parametrize('empty_scene', [True, False])
def test_background_plotting_close(qtbot, close_event, empty_scene, plotting, ensu... |
def test_slots_unpickle_after_attr_removed():
a = A(1, 2, 3)
a_pickled = pickle.dumps(a)
a_unpickled = pickle.loads(a_pickled)
assert (a_unpickled == a)
(slots=True)
class NEW_A():
x = attr.ib()
c = attr.ib()
with mock.patch(f'{__name__}.A', NEW_A):
new_a = pickle.loa... |
class Sheet(tk.Frame):
def __init__(self, parent, name: str='!sheet', show_table: bool=True, show_top_left: bool=True, show_row_index: bool=True, show_header: bool=True, show_x_scrollbar: bool=True, show_y_scrollbar: bool=True, width: int=None, height: int=None, headers: List=None, header: List=None, default_header... |
class EbnfLexer(RegexLexer):
name = 'EBNF'
aliases = ['ebnf']
filenames = ['*.ebnf']
mimetypes = ['text/x-ebnf']
url = '
version_added = '2.0'
tokens = {'root': [include('whitespace'), include('comment_start'), include('identifier'), ('=', Operator, 'production')], 'production': [include('wh... |
def AllDifferent(term, *others, excepting=None, matrix=False):
excepting = (list(excepting) if isinstance(excepting, (tuple, set)) else ([excepting] if isinstance(excepting, int) else excepting))
checkType(excepting, ([int], type(None)))
if matrix:
assert (len(others) == 0)
matrix = [flatten... |
class Market1501(BaseImageDataset):
dataset_dir = 'market1501/Market-1501-v19.09.15'
def __init__(self, root='your_dataset_path', verbose=True, **kwargs):
super(Market1501, self).__init__()
self.dataset_dir = osp.join(root, self.dataset_dir)
self.train_dir = osp.join(self.dataset_dir, 'b... |
.skipif((shutil.which('notify-send') is None), reason='notify-send not installed.')
.usefixtures('dbus')
def test_notifications(manager_nospawn, minimal_conf_noscreen):
def background(obj):
(_, bground) = obj.eval('self.background')
return bground
notify.Notify.timeout_add = log_timeout
widg... |
class MultiHopContextsOnlyModel(MultipleContextModel):
def __init__(self, encoder: QuestionsAndParagraphsEncoder, word_embed: Optional[WordEmbedder], char_embed: Optional[CharWordEmbedder], embed_mapper: Optional[SequenceMapper], context_to_context_attention: Optional[AttentionWithPostMapper], sequence_encoder: Seq... |
class Speech2TextConfig(PretrainedConfig):
model_type = 'speech_to_text'
keys_to_ignore_at_inference = ['past_key_values']
attribute_map = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'}
def __init__(self, vocab_size=10000, encoder_layers=12, encoder_ffn_dim=2048, encoder_at... |
class InlineMixin():
def _get_call_args(result_type, title, attach, content):
args = {'id': None, 'type': result_type}
if (title is not None):
args['title'] = title
if (attach is not None):
if (not hasattr(attach, '_serialize_attachment')):
raise Value... |
class IntegrationTests(fixtures.DistInfoPkg, unittest.TestCase):
def test_package_spec_installed(self):
def is_installed(package_spec):
req = packaging.requirements.Requirement(package_spec)
return (version(req.name) in req.specifier)
assert is_installed('distinfo-pkg==1.0')
... |
def test_handshake_rejection_with_body() -> None:
events = _make_handshake_rejection(400, b'Hello')
assert (events == [RejectConnection(headers=[(b'content-length', b'5')], has_body=True, status_code=400), RejectData(body_finished=False, data=b'Hello'), RejectData(body_finished=True, data=b'')]) |
class ResNetBase(nn.Module):
def __init__(self, block, layers):
self.inplanes = 64
super(ResNetBase, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
self.max... |
def model_processing(model, src_dir, dest_dir, timeseq_len):
train_dir = os.path.join(src_dir, 'train')
test_dir = os.path.join(src_dir, 'test')
if os.path.exists(dest_dir):
print(dest_dir, 'already exists')
else:
os.mkdir(dest_dir)
print(dest_dir, 'created')
dest_train_dir =... |
.parametrize('v, dtype', [(set_test_value(pt.iscalar(), np.array(10, dtype='int32')), psb.float64)])
def test_reciprocal(v, dtype):
g = psb.reciprocal(v)
g_fg = FunctionGraph(outputs=[g])
compare_numba_and_py(g_fg, [i.tag.test_value for i in g_fg.inputs if (not isinstance(i, (SharedVariable, Constant)))]) |
class KnownValues(unittest.TestCase):
def test_KUKSpU_high_cost(self):
kmesh = [2, 1, 1]
kpts = cell.make_kpts(kmesh, wrap_around=True)
U_idx = ['1 C 2p']
U_val = [5.0]
mf = pdft.KUKSpU(cell, kpts, U_idx=U_idx, U_val=U_val, C_ao_lo='minao', minao_ref='gth-szv')
mf.con... |
def sstore_eip2200(computation: BaseComputation) -> None:
gas_remaining = computation.get_gas_remaining()
if (gas_remaining <= 2300):
raise OutOfGas('Net-metered SSTORE always fails below 2300 gas, per EIP-2200', gas_remaining)
else:
return net_sstore(GAS_SCHEDULE_EIP2200, computation) |
class Metric(object):
def __init__(self, args: Namespace):
self.args = args
self.denom = 1e-08
def __call__(self, gts, preds, mask: list) -> dict:
raise NotImplementedError
def _cal_token_level(self, gts, preds, mask: list):
raise NotImplementedError
def _cal_sentence_lev... |
_pytesseract
_sentencepiece
_tokenizers
class LayoutXLMProcessorTest(unittest.TestCase):
tokenizer_class = LayoutXLMTokenizer
rust_tokenizer_class = LayoutXLMTokenizerFast
def setUp(self):
feature_extractor_map = {'do_resize': True, 'size': 224, 'apply_ocr': True}
self.tmpdirname = tempfile.... |
class TableLocator(Locator, dict):
def of(namespace_locator: Optional[NamespaceLocator], table_name: Optional[str]) -> TableLocator:
table_locator = TableLocator()
table_locator.namespace_locator = namespace_locator
table_locator.table_name = table_name
return table_locator
def a... |
class AsyncApis(Generic[AsyncClientT]):
def __init__(self, host: str=None, **kwargs: Any):
self.client = AsyncApiClient(host, **kwargs)
self.cluster_api = AsyncClusterApi(self.client)
self.collections_api = AsyncCollectionsApi(self.client)
self.points_api = AsyncPointsApi(self.client... |
class TestEarlyInit():
def test_config_py_path(self, args, init_patch, config_py_arg):
config_py_arg.write('\n'.join(['config.load_autoconfig()', 'c.colors.hints.bg = "red"']))
configinit.early_init(args)
expected = 'colors.hints.bg = red'
assert (config.instance.dump_userconfig() ==... |
def biwrap(wrapper):
(wrapper)
def enhanced(*args, **kwargs):
is_bound_method = (hasattr(args[0], wrapper.__name__) if args else False)
if is_bound_method:
count = 1
else:
count = 0
if (len(args) > count):
newfn = wrapper(*args, **kwargs)
... |
class ArchivedSong(models.Model):
url = models.CharField(max_length=2000, unique=True)
artist = models.CharField(max_length=1000)
title = models.CharField(max_length=1000)
duration = models.FloatField()
counter = models.IntegerField()
cached = models.BooleanField()
def __str__(self) -> str:
... |
def train_model(train_source, train_target, dev_source, dev_target, experiment_directory, resume=False):
train = Seq2SeqDataset.from_file(train_source, train_target)
train.build_vocab(300, 6000)
dev = Seq2SeqDataset.from_file(dev_source, dev_target, share_fields_from=train)
input_vocab = train.src_field... |
def prepare_exp_name(stats_dict):
exp_name = []
output_dir = stats_dict.pop('output_dir', None)
if (output_dir is not None):
output_dir = Path(output_dir)
if output_dir.stem.startswith('version_'):
exp_name += [output_dir.parent.stem, output_dir.stem.replace('_', '-')]
el... |
def local_files(code):
pathname = os.path.join(dictionary_dir(), '{}*.bdic'.format(code))
matching_dicts = glob.glob(pathname)
versioned_dicts = []
for matching_dict in matching_dicts:
parsed_version = version(matching_dict)
if (parsed_version is not None):
filename = os.path... |
def write_tfrecord_from_npy_single_channel(class_npy_file, class_label, output_path):
def load_image(img):
side = int(np.sqrt(img.shape[0]))
img = Image.fromarray(img.reshape((side, side)))
img = img.convert('RGB')
return img
with tf.io.gfile.GFile(class_npy_file, 'rb') as f:
... |
def mock_layout():
_layout = NonCallableMock(spec=layout.TextLayout)
_layout.foreground_decoration_group = NonCallableMock()
_layout.attach_mock(Mock(), 'push_handlers')
program = NonCallableMock(spec=ShaderProgram)
_layout.foreground_decoration_group.attach_mock(program, 'program')
def _fake_ve... |
class AdvertisementMixin():
MAX_IMAGE_WIDTH = 120
def ad_image(self, obj):
if (not obj.image):
return ''
return mark_safe(f'<img src="{obj.image.url}" style="max-width: {self.MAX_IMAGE_WIDTH}px" />')
def ctr(self, obj):
return '{:.3f}%'.format(obj.ctr())
def get_query... |
def _get_data_from_provider(inputs, batch_size, split_name, is_training=True, load_image=False):
input_tuple = [inputs['landmarks']]
if load_image:
input_tuple.append(inputs['images'])
tmp_outputs = tf.train.batch(input_tuple, batch_size=batch_size, num_threads=64, capacity=(batch_size * 4), name=('... |
class NameExpr(RefExpr):
__slots__ = ('name', 'is_special_form')
__match_args__ = ('name', 'node')
def __init__(self, name: str) -> None:
super().__init__()
self.name = name
self.is_special_form = False
def accept(self, visitor: ExpressionVisitor[T]) -> T:
return visitor.... |
class GuiImportCargosCommand(wx.Command):
def __init__(self, fitID, cargos):
wx.Command.__init__(self, True, 'Import Cargos')
self.internalHistory = InternalCommandHistory()
self.fitID = fitID
self.cargos = {}
for (itemID, amount, mutation) in cargos:
if (itemID n... |
_module()
class ResNet3dSlowOnly(ResNet3dPathway):
def __init__(self, *args, lateral=False, conv1_kernel=(1, 7, 7), conv1_stride_t=1, pool1_stride_t=1, inflate=(0, 0, 1, 1), **kwargs):
super().__init__(*args, lateral=lateral, conv1_kernel=conv1_kernel, conv1_stride_t=conv1_stride_t, pool1_stride_t=pool1_str... |
class PlaySteerVehicle(Packet):
id = 29
to = 0
def __init__(self, sideways: float, forward: float, flags: int) -> None:
super().__init__()
self.sideways = sideways
self.forward = forward
self.flags = flags
def decode(cls, buf: Buffer) -> PlaySteerVehicle:
return c... |
class Command(LabelCommand):
label = 'Organization name'
def handle_label(self, label, **options):
(org, created) = Organization.objects.get_or_create(name=label)
if created:
logger.info('%s organization created.', org)
else:
logger.info('%s organization already c... |
class mit_b2(MixVisionTransformer):
def __init__(self, **kwargs):
super(mit_b2, self).__init__(patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-06), depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1], drop_rate=0.0... |
class FastSelfAttnFunc(torch.autograd.Function):
def forward(ctx, input, cu_seqlens, p_dropout, max_s, is_training, num_heads, head_dim, recompute, in_proj_weight, in_proj_bias, out_proj_weight, out_proj_bias):
batch_size = (cu_seqlens.numel() - 1)
total_bsz = input.size(0)
if (batch_size < ... |
def Casestudy(model, data_loader, emodict, args, path='Data'):
model.eval()
(feats, labels) = (data_loader['feat'], data_loader['label'])
label_preds = []
for bz in range(len(labels)):
(feat, lens) = Utils.ToTensor(feats[bz], is_len=True)
label = Utils.ToTensor(labels[bz])
feat =... |
class ResNet(container.SequentialDiffEq):
def __init__(self, dim, intermediate_dim, n_resblocks, conv_block=None):
super(ResNet, self).__init__()
if (conv_block is None):
conv_block = basic.ConcatCoordConv2d
self.dim = dim
self.intermediate_dim = intermediate_dim
... |
def test_create_project(gl, user):
admin_project = gl.projects.create({'name': 'admin_project'})
assert isinstance(admin_project, gitlab.v4.objects.Project)
assert (admin_project in gl.projects.list(search='admin_project'))
sudo_project = gl.projects.create({'name': 'sudo_project'}, sudo=user.id)
cr... |
def get_task_head(cfg):
(loss_obj, task) = build_loss(cfg)
if (task == 'metric'):
head = Metric(loss_obj, cfg.MODEL.INITIAL_NORMALIZATION_FACTOR)
elif (task == 'regression'):
head = Regression(loss_obj, cfg.MODEL.EMBED_DIM)
else:
head = Classification(loss_obj, embed_dim=cfg.MODE... |
def write_result_q05(results_dict, output_directory='./', filetype=None):
with open(f'{output_directory}q05-metrics-results.txt', 'w') as outfile:
outfile.write(('Precision: %f\n' % results_dict['precision']))
outfile.write(('AUC: %f\n' % results_dict['auc']))
outfile.write('Confusion Matrix... |
def compute_cost(num_spin_orbs: int, lambda_tot: float, num_aux: int, kmesh: list[int], dE_for_qpe: float=0.0016, chi: int=10) -> ResourceEstimates:
init_cost = _compute_cost(num_spin_orbs, lambda_tot, num_aux, dE_for_qpe, chi, 20000, kmesh[0], kmesh[1], kmesh[2])
steps = init_cost[0]
final_cost = _compute_... |
class ScannerSubscriptionSamples(Object):
def HotUSStkByVolume():
scanSub = ScannerSubscription()
scanSub.instrument = 'STK'
scanSub.locationCode = 'STK.US.MAJOR'
scanSub.scanCode = 'HOT_BY_VOLUME'
return scanSub
def TopPercentGainersIbis():
scanSub = ScannerSubsc... |
class STS17Crosslingual(AbsTaskSTS, CrosslingualTask):
def description(self):
return {'name': 'STS17', 'hf_hub_name': 'mteb/sts17-crosslingual-sts', 'description': 'STS 2017 dataset', 'reference': ' 'type': 'STS', 'category': 's2s', 'eval_splits': ['test'], 'eval_langs': _LANGUAGES, 'main_score': 'cosine_sp... |
def insert_import(import_stmt, test_case, file_input):
import_nodes = get_import_nodes(file_input)
if import_nodes:
last_import_stmt = import_nodes[(- 1)].parent
i = (file_input.children.index(last_import_stmt) + 1)
else:
i = file_input.children.index(test_case)
import_stmt.p... |
class CurComp(BaseSignalExpr):
def __init__(s, comp, comp_id):
super().__init__(comp.get_metadata(StructuralRTLIRGenL0Pass.rtlir_type))
s.comp_id = comp_id
def __eq__(s, other):
return (isinstance(other, CurComp) and (s.rtype == other.rtype) and (s.comp_id == other.comp_id))
def __ha... |
def test_dialog_checkboxes(skip_qtbot: pytestqt.qtbot.QtBot) -> None:
cosmetic_patches = SuperMetroidCosmeticPatches()
dialog = SuperCosmeticPatchesDialog(None, cosmetic_patches)
skip_qtbot.addWidget(dialog)
default_settings = SuperMetroidCosmeticPatches()
for (field_name, checkbox) in dialog.checkb... |
def _get_stage_fn(stage_args):
stage_type = stage_args.pop('stage_type')
assert (stage_type in ('dark', 'csp', 'cs3'))
if (stage_type == 'dark'):
stage_args.pop('expand_ratio', None)
stage_args.pop('cross_linear', None)
stage_args.pop('down_growth', None)
stage_fn = DarkStage... |
class TestEncodingComparisonOperator():
def test_set_target_guide(self):
class TestOperator(ops.EncodingComparisonOperator):
def target_enc_to_repr(self, image):
repr = (image * 2.0)
ctx = torch.norm(image)
return (repr, ctx)
def input_... |
def let_me_upload(file_path):
file_size = ((os.path.getsize(file_path) / 1024) / 1024)
file_name = os.path.basename(file_path)
big_file_suffix = ['zip', 'rar', 'apk', 'ipa', 'exe', 'pdf', '7z', 'tar', 'deb', 'dmg', 'rpm', 'flac']
small_file_suffix = (big_file_suffix + ['doc', 'epub', 'mobi', 'mp3', 'ppt... |
class FixedFieldTest(BaseFieldTestMixin, NumberTestMixin, FieldTestCase):
field_class = fields.Fixed
def test_defaults(self):
field = fields.Fixed()
assert (not field.required)
assert (field.__schema__ == {'type': 'number'})
def test_with_default(self):
field = fields.Fixed(d... |
def test_complex(tmpdir):
name = str(tmpdir.join('complex.tif'))
arr1 = np.ones((2, 2), dtype=complex_)
profile = dict(driver='GTiff', width=2, height=2, count=1, dtype=complex_)
with rasterio.open(name, 'w', **profile) as dst:
dst.write(arr1, 1)
with rasterio.open(name) as src:
arr2... |
def main(options=None, args=None):
tdb = ops.db.get_tdb()
if (options is None):
maxage = datetime.timedelta(seconds=0)
else:
maxage = datetime.timedelta(seconds=options.maxage)
last_ifconfig = ops.networking.ifconfig.get_ifconfig(maxage=datetime.timedelta.max)
cur_ifconfig = ops.netw... |
def calculate_d_to_volume(dose_grid, label, volume, volume_in_cc=False):
dose_grid = sitk.Resample(dose_grid, label, sitk.Transform(), sitk.sitkLinear)
dose_array = sitk.GetArrayFromImage(dose_grid)
mask_array = sitk.GetArrayFromImage(label)
if volume_in_cc:
volume = (((volume * 1000) / ((mask_a... |
class JsonLexer(Lexer):
name = 'JSON'
url = '
aliases = ['json', 'json-object']
filenames = ['*.json', '*.jsonl', '*.ndjson', 'Pipfile.lock']
mimetypes = ['application/json', 'application/json-object', 'application/x-ndjson', 'application/jsonl', 'application/json-seq']
version_added = '1.5'
... |
def main(unused_argv):
a = 0.0
f = 0.1
l = 3.6
train_coc = 1
config = utils.load_config()
dataset = datasets.get_dataset('test', FLAGS.data_dir, config)
(model, init_variables) = models.construct_mipnerf(random.PRNGKey(), dataset.peek())
optimizer = flax.optim.Adam(config.lr_init).create... |
class loss_mse(nn.Module):
def __init__(self):
super(loss_mse, self).__init__()
def forward(self, pred, truth):
c = pred.shape[1]
h = pred.shape[2]
w = pred.shape[3]
pred = pred.view((- 1), ((c * h) * w))
truth = truth.view((- 1), ((c * h) * w))
return tor... |
class TIconTheme(TestCase):
def test_icon_theme(self):
theme = Gtk.IconTheme.get_default()
theme.append_search_path(quodlibet.get_image_dir())
for i in ['io.github.quodlibet.QuodLibet', 'io.github.quodlibet.ExFalso', 'quodlibet-missing-cover']:
self.assertTrue(theme.has_icon(i)) |
class FTDataArguments():
train_file: str = dataclasses.field(default=None, metadata={'help': 'A csv or a json file containing the training data.'})
eval_file: Optional[str] = dataclasses.field(default=None, metadata={'help': 'A csv or a json file containing the validation data.'})
test_file: Optional[str] =... |
def add_imported_function_or_module(self, item):
if inspect.isfunction(item):
self.add_function(item)
elif inspect.isclass(item):
for (k, v) in item.__dict__.items():
if inspect.isfunction(v):
self.add_function(v)
elif inspect.ismodule(item):
self.add_modu... |
class DefaultWildcard():
def __init__(self, project):
self.project = project
def get_name(self):
return 'default'
def matches(self, suspect, arg=''):
args = parse_arg(arg)
if (not self._check_exact(args, suspect)):
return False
if (not self._check_object(a... |
def load_svhns(data_dir, use_augmentation='base', use_consistency=False, aux_take_amount=None, aux_data_filename='/cluster/scratch/rarade/svhns/ti_500K_pseudo_labeled.pickle', validation=False):
data_dir = re.sub('svhns', 'svhn', data_dir)
test_transform = transforms.Compose([transforms.ToTensor()])
train_t... |
def run_and_save(n: int, n_paulis: int, n_sweeps: int, n_shots: int, save_dir: str, use_engine: bool) -> None:
logging.info('Beginning quantum-enhanced circuit generation.')
system_pairs = run_config.qubit_pairs()
system_pairs = system_pairs[:n]
rand_source = np.random.RandomState(1234)
logging.info... |
class Dancer():
states = ['start', 'left_food_left', 'left', 'right_food_right']
def __init__(self, name, beat):
self.my_name = name
self.my_beat = beat
self.moves_done = 0
async def on_enter_start(self):
self.moves_done += 1
async def wait(self):
print(f'{self.my... |
class TMP4HasTags64Bit(TMP4, TMP4HasTagsMixin):
original = os.path.join(DATA_DIR, 'truncated-64bit.mp4')
def test_has_covr(self):
pass
def test_bitrate(self):
self.failUnlessEqual(self.audio.info.bitrate, 128000)
def test_length(self):
self.failUnlessAlmostEqual(0.325, self.audio... |
_dtype_float_test(only64=True, additional_kwargs={'method_tol': [('rk4', (1e-08, 1e-05)), ('rk38', (1e-08, 1e-05)), ('rk45', (1e-08, 1e-05)), ('rk23', (1e-06, 0.0001)), ('euler', (0.05, 0.0001))], 'clss': [IVPModule, IVPNNModule]})
def test_ivp_methods(dtype, device, method_tol, clss):
torch.manual_seed(100)
ra... |
class TestPdbBreakpoint(utt.InferShapeTester):
def setup_method(self):
super().setup_method()
self.input1 = fmatrix()
self.input2 = fscalar()
self.output = dot((self.input1 - self.input2), (self.input1 - self.input2).transpose())
self.breakpointOp = PdbBreakpoint('Sum of outp... |
class InputDataFields(object):
image = 'image'
original_image = 'original_image'
key = 'key'
source_id = 'source_id'
filename = 'filename'
groundtruth_image_classes = 'groundtruth_image_classes'
groundtruth_boxes = 'groundtruth_boxes'
groundtruth_classes = 'groundtruth_classes'
groun... |
def fcn8sd_resnetd101b_voc(pretrained_backbone=False, num_classes=21, aux=True, **kwargs):
backbone = resnetd101b(pretrained=pretrained_backbone, ordinary_init=False, multi_output=True).features
del backbone[(- 1)]
return get_fcn8sd(backbone=backbone, num_classes=num_classes, aux=aux, model_name='fcn8sd_res... |
def test_copy(caplog):
caplog.set_level(logging.INFO)
lg = logger.copy()
nesting = lg.nesting
count = 3
with lg.indent(count):
logger2 = lg.copy()
name = uniqstr()
with lg.indent(7):
lg.report('make', '/some/report')
logger2.report('call', name)
assert (logger... |
class Position(object):
__slots__ = ('_underlying_position',)
def __init__(self, underlying_position):
object.__setattr__(self, '_underlying_position', underlying_position)
def __getattr__(self, attr):
return getattr(self._underlying_position, attr)
def __setattr__(self, attr, value):
... |
def _find_vc2017():
root = (os.environ.get('ProgramFiles(x86)') or os.environ.get('ProgramFiles'))
if (not root):
return (None, None)
try:
path = subprocess.check_output([os.path.join(root, 'Microsoft Visual Studio', 'Installer', 'vswhere.exe'), '-latest', '-prerelease', '-requires', 'Micros... |
def venv_health_check(venv: Venv, package_name: Optional[str]=None) -> Tuple[(VenvProblems, str)]:
venv_dir = venv.root
python_path = venv.python_path.resolve()
if (package_name is None):
package_name = venv.main_package_name
if (not python_path.is_file()):
return (VenvProblems(invalid_i... |
class BetaLayer(nn.Module):
def __init__(self, latent_size, stock_size, factor_size, hidden_size=64):
super(BetaLayer, self).__init__()
self.factor_size = factor_size
self.stock_size = stock_size
self.beta_layer = MLP(input_size=latent_size, output_size=factor_size, hidden_size=hidde... |
.parametrize('case', [CaseReducesInx3OutComp, CaseIfBasicComp, CaseIfDanglingElseInnerComp, CaseIfDanglingElseOutterComp, CaseElifBranchComp, CaseNestedIfComp, CaseForLoopEmptySequenceComp, CaseForRangeLowerUpperStepPassThroughComp, CaseIfExpInForStmtComp, CaseIfExpBothImplicitComp, CaseIfBoolOpInForStmtComp, CaseIfTmp... |
def load_model_weights(weights_collection, model, dataset, classes, include_top):
weights = find_weights(weights_collection, model.name, dataset, include_top)
if weights:
weights = weights[0]
if (include_top and (weights['classes'] != classes)):
raise ValueError('If using `weights` a... |
def make_seg_list(utt_index_list, utt_list, utt_len_list, seg_len, seg_shift, if_seg_rand, utt2label=None):
seg_list = []
for utt_index in utt_index_list:
utt_id = utt_list[utt_index]
utt_len = utt_len_list[utt_index]
label = (utt2label[utt_id] if utt2label else None)
n_segs = ((... |
class GCM(ModeWithInitializationVector, ModeWithAuthenticationTag):
name = 'GCM'
_MAX_ENCRYPTED_BYTES = (((2 ** 39) - 256) // 8)
_MAX_AAD_BYTES = ((2 ** 64) // 8)
def __init__(self, initialization_vector: bytes, tag: (bytes | None)=None, min_tag_length: int=16):
utils._check_byteslike('initializ... |
_cache(maxsize=2)
def make_unicode_string(archbits: int):
native_type = struct.get_native_type(archbits)
Struct = struct.get_aligned_struct(archbits)
class UNICODE_STRING(Struct):
_fields_ = (('Length', ctypes.c_uint16), ('MaximumLength', ctypes.c_uint16), ('Buffer', native_type))
return UNICODE... |
.parametrize('command_and_args, text, output_contains, first_match', [('mutex', '', 'the optional positional', None), ('mutex', '--fl', '', '--flag '), ('mutex --flag', '', 'the flag arg', None), ('mutex pos_val', '--fl', '', None), ('mutex pos_val --flag', '', 'f/--flag: not allowed with argument optional_pos', None),... |
def test_builder_no_amd():
existing = DockerSchema2ManifestList(Bytes.for_string_or_unicode(MANIFESTLIST_BYTES))
builder = DockerSchema2ManifestListBuilder()
for (index, manifest) in enumerate(existing.manifests(retriever)):
builder.add_manifest(manifest.manifest_obj, 'intel386', 'os')
built = b... |
class TestPower(TestCase):
def test_power_ttest(self):
assert np.isclose(power_ttest(d=0.5, n=20, contrast='one-sample', alternative='greater'), 0.6951493)
assert np.isclose(power_ttest(d=0.5, n=20, contrast='paired', alternative='greater'), 0.6951493)
assert np.isclose(power_ttest(d=0.5, po... |
class ResNet101vd(nn.Module):
def __init__(self, cout=64, idx=0):
super(ResNet101vd, self).__init__()
self.cout = cout
self.idx = idx
self.resnet101vd = ResNet(channels=[64, 128, 256, 512], cout=cout, idx=idx, block=Bottleneck, layers=[3, 4, 23, 3], stem_width=32, stem_type='deep', a... |
.parametrize('language, feature_keyword, scenario_keyword', [('en', 'Feature', 'Scenario'), ('de', 'Funktionalitat', 'Szenario')])
def test_creating_language_agnostic_parser(language, feature_keyword, scenario_keyword, core):
parser = FeatureParser(core, '/', 1, language=language)
assert (parser.keywords.featur... |
def main(data_dir, client, bc, config):
benchmark(read_tables, data_dir, bc, dask_profile=config['dask_profile'])
query_1 = '\n SELECT\n CAST(wcs_user_sk AS INTEGER) AS wcs_user_sk,\n CAST(wcs_item_sk AS INTEGER) AS wcs_item_sk,\n (wcs_click_date_sk * 86400 + wcs_click_ti... |
.route('/items/<content_type>/<heading>/')
def items(content_type: str, heading: str) -> None:
if (heading == 'alphabet'):
alphabet(content_type)
elif (heading == 'genres'):
genres(content_type)
elif (heading == 'search'):
search(content_type)
else:
data = {'type': (None ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.