code
stringlengths
281
23.7M
class _TopologicalLattice(Generic[TQubit], metaclass=ABCMeta): def H(self) -> int: return DH def W(self) -> int: return DW def SYNX(self) -> int: return 0 def SYNZ(self) -> int: return 1 def __init__(self, params: Dict[(str, Any)], name: str, circ: QuantumCircuit): ...
_factory def factory(): search = SerpAPIWrapper() tools = [Tool(name='Search', func=search.run, description='useful for when you need to answer questions about current events. You should ask targeted questions')] llm = OpenAI(temperature=0, model_name='gpt-3.5-turbo') agent = initialize_agent(tools, llm...
def inference_run(model, hparams, output_dir): tf.logging.info('Build Model...') model_fn_inference = model_builder_inference(model, hparams=hparams) tf.logging.info('Build Graph...') checkpoint_path = saver.latest_checkpoint(output_dir) if (not checkpoint_path): raise NotFittedError(("Could...
class AttrVI_ATTR_SRC_INCREMENT(RangeAttribute): resources = [(constants.InterfaceType.pxi, 'INSTR'), (constants.InterfaceType.pxi, 'MEMACC'), (constants.InterfaceType.vxi, 'INSTR'), (constants.InterfaceType.vxi, 'MEMACC')] py_name = 'source_increment' visa_name = 'VI_ATTR_SRC_INCREMENT' visa_type = 'Vi...
def orthoFrames2Versor_dist(A, B, eps=None): A = A[:] B = B[:] if (len(A) != len(B)): raise ValueError('len(A)!=len(B)') if (eps is None): eps = global_eps() r_list = [] dist = [abs(((a - b) ** 2)) for (a, b) in zip(A, B)] k = dist.index(max(dist)) while (dist[k] >= eps):...
.fast def test_Morse_Potential_effect_CO(T=3000, rtol=0.0001, verbose=True, warnings=True, *args, **kwargs): vmax = 11 vmax_morse = 48 jmax = 300 iso = 1 S = Molecules['CO'][iso]['X'] db = PartFunc_Dunham(S, vmax=vmax, vmax_morse=0, Jmax=jmax, use_cached=False) Q_nomorse = db.at(T) db = ...
class Effect5757(BaseEffect): type = 'overheat' def handler(fit, module, context, projectionRange, **kwargs): module.boostItemAttr('maxTargetRangeBonus', module.getModifiedItemAttr('overloadSensorModuleStrengthBonus'), **kwargs) module.boostItemAttr('scanResolutionBonus', module.getModifiedItemA...
def DenseNet201(pretrained=False, **kwargs): model = DenseNet(num_init_features=64, growth_rate=32, block_config=(6, 12, 48, 32), **kwargs) if pretrained: pattern = re.compile('^(.*denselayer\\d+\\.(?:norm|relu|conv))\\.((?:[12])\\.(?:weight|bias|running_mean|running_var))$') state_dict = model_...
class SawyerHandlePullV1Policy(Policy): _fully_parsed def _parse_obs(obs): return {'hand_pos': obs[:3], 'handle_pos': obs[3:6], 'unused_info': obs[6:]} def get_action(self, obs): o_d = self._parse_obs(obs) action = Action({'delta_pos': np.arange(3), 'grab_effort': 3}) action[...
class OrbitController(PanZoomController): _default_controls = {'mouse1': ('rotate', 'drag', (0.005, 0.005)), 'mouse2': ('pan', 'drag', (1, 1)), 'mouse4': ('quickzoom', 'peek', 2), 'wheel': ('zoom', 'push', (- 0.001)), 'alt+wheel': ('fov', 'push', (- 0.01))} def rotate(self, delta: Tuple, rect: Tuple, *, animate...
def simxLoadModel(clientID, modelPathAndName, options, operationMode): baseHandle = ct.c_int() if ((sys.version_info[0] == 3) and (type(modelPathAndName) is str)): modelPathAndName = modelPathAndName.encode('utf-8') return (c_LoadModel(clientID, modelPathAndName, options, ct.byref(baseHandle), opera...
.parametrize('names,expect', [([1, 2, 3], ['1', '2', '3']), (['', np.nan], ['', '']), (['', np.nan], ['', '']), (['', '', np.nan], ['', '', '']), (repair_names(['', '', np.nan], repair='minimal'), ['', '', ''])]) def test_minimal(names, expect): assert (repair_names(names, repair='minimal') == expect)
class IPTest(object): .parametrize('value', ['200.8.9.10', '127.0.0.1', '2001:db8:85a3::8a2e:370:7334', '::1']) def test_valid_value(self, value): assert (inputs.ip(value) == value) .parametrize('value', ['foo', ' ' ' ' ' ' ' ' 'foo bar baz', 'foo ', ' ' ' '127.0']) def test_bad_value(self, valu...
class Path(object): def __init__(self, label_name, fold_id): self.label_name = label_name self.fold_id = fold_id self.phase_path = {} a_root = '/media/newssd/Aff-Wild_experiments/phase_diff_5_fold/valence_loss_type:ccc_batch_size:64_alpha:1.0/model' v_root = '/media/newssd/Af...
def get_semanal_options(program_text: str, testcase: DataDrivenTestCase) -> Options: options = parse_options(program_text, testcase, 1) options.use_builtins_fixtures = True options.semantic_analysis_only = True options.show_traceback = True options.python_version = PYTHON3_VERSION options.force_...
.parametrize('screen,location,attribute', parameters) def test_default_settings(manager_nospawn, minimal_conf_noscreen, screen, location, attribute): config = minimal_conf_noscreen config.screens = [screen] manager_nospawn.start(config) bar = manager_nospawn.c.bar[location] info = bar.info() for...
class TanhBlurBlock(nn.Module): def __init__(self, in_filters, temp=10.0, sfilter=(1, 1), pad_mode='constant', **kwargs): super(TanhBlurBlock, self).__init__() self.temp = temp self.relu = layers.relu() self.tanh = nn.Tanh() self.blur = layers.blur(in_filters, sfilter=sfilter...
.parametrize('properties', [{}, create_test_properties()]) def test_object_features(properties: dict): (obj, _) = create_test_object() obj.properties = properties assert (obj.n_features == 0) keys = list(properties.keys()) obj.set_features(keys) n_keys = sum((np.asarray(p).size for p in properti...
def test_select_column_in_subquery_with_two_parenthesis_and_union_v2(): sql = 'INSERT INTO tab1\nSELECT col1\nFROM (\n SELECT col1 FROM tab2\n UNION ALL\n SELECT col1 FROM tab3\n) dt' assert_column_lineage_equal(sql, [(ColumnQualifierTuple('col1', 'tab2'), ColumnQualifierTuple('col1', 'tab1')), (Column...
def tar_archive(context_tar): logger.debug('start') mode = get_file_mode_for_writing(context_tar) for item in context_tar['archive']: destination = item['out'] source = item['in'] with tarfile.open(destination, mode) as archive_me: logger.debug("Archiving '%s' to '%s'", s...
def setup_checkpoint_file_name_prefix(args): checkpoint_file_name_prefix = '' for (i, name) in enumerate(args.checkpoint_file_name_save_list): checkpoint_file_name_prefix += str(getattr(args, name)) if (i != (len(args.checkpoint_file_name_save_list) - 1)): checkpoint_file_name_prefix...
def makeUpdateMatrixDis(qnnArch, qnnArchGen, unitaries, storedStates, storedStatesDis, lda, ep, l, j, trainingData): numInputQubits = qnnArch[(l - 1)] summ = 0 for x in range(len(storedStates)): firstPart = updateMatrixFirstPartDis(qnnArch, qnnArchGen, unitaries, storedStates, storedStatesDis, l, j,...
def fill_template(template, *args): parts = TEMPLATE_PATTERN.findall(template) kids = [] for p in parts: if (p == ''): continue elif (p in '\x01\x02\x03\x04\x05'): p = args[(ord(p) - 1)] p.prefix = '' else: p = Name(p) kids.appe...
class ListSponsorsTemplateTag(TestCase): def test_filter_sponsorship_with_logo_placement_benefits(self): sponsorship = baker.make_recipe('sponsors.tests.finalized_sponsorship') baker.make_recipe('sponsors.tests.logo_at_download_feature', sponsor_benefit__sponsorship=sponsorship) context = li...
def infer_conv_output_attrs(module, input_channels, input_dim, batch_size=1, max_length=8): input = torch.randn(batch_size, input_channels, max_length, input_dim) output = module(input) output_channels = output.shape[1] output_dim = output.shape[(- 1)] return (output_channels, output_dim)
class RectROI(ROI): def __init__(self, pos, size, centered=False, sideScalers=False, **args): ROI.__init__(self, pos, size, **args) if centered: center = [0.5, 0.5] else: center = [0, 0] self.addScaleHandle([1, 1], center) if sideScalers: s...
def _add_perm(caller, perm, **kwargs): if perm: perm_low = perm.lower() perms = _caller_permissions(caller) perms_low = [prm.lower() for prm in perms] if ('delete' in kwargs): try: ind = perms_low.index(perm_low) del perms[ind] ...
class IPTW(): def __init__(self, df, treatment, outcome, weights=None, standardize='population'): self.treatment = treatment self.outcome = outcome self._missing_indicator = '__missing_indicator__' (self.df, self._miss_flag, self._continuous_outcome) = check_input_data(data=df, expos...
def test_back_and_forth_ito(): (f, g, b, y0, ts, dt) = make_example_sde(dt=0.0001) (fr, gr, br, tr) = time_reflect_ito(f, g, b, ts) ys = ito_integrate(f, g, y0, ts, b, dt) rys = ito_integrate(fr, gr, ys[(- 1)], tr, br, dt)[::(- 1)] assert np.allclose(ys[0], rys[0], rtol=0.001, atol=0.001)
def extra_english(corpus_path, split): split_type_file_path = os.path.join(corpus_path, f'all_talks_{split}.tsv') output_split_type_file_path = os.path.join(corpus_path, f'all_talks_{split}.en') with io.open(split_type_file_path, 'r', encoding='utf8') as fp, io.open(output_split_type_file_path, 'w', encodin...
.parametrize('setting, third_party, accepted', [('all', False, True), ('never', False, False), ('no-3rdparty', False, True), ('no-3rdparty', True, False)]) def test_accept_cookie(config_stub, filter_request, setting, third_party, accepted): config_stub.val.content.cookies.accept = setting filter_request.thirdPa...
def setup(args): cfg = get_cfg() add_deeplab_config(cfg) add_maskformer2_config(cfg) cfg.merge_from_file(args.config_file) cfg.merge_from_list(args.opts) cfg.freeze() default_setup(cfg, args) setup_logger(output=cfg.OUTPUT_DIR, distributed_rank=comm.get_rank(), name='mask2former') re...
def _accuracy_param_check(average: Optional[str], num_classes: Optional[int], k: int) -> None: average_options = ('micro', 'macro', 'none', None) if (average not in average_options): raise ValueError(f'`average` was not in the allowed value of {average_options}, got {average}.') if ((average != 'mic...
def get_normalize_layer(dataset: str, diff=None, vit=None) -> torch.nn.Module: if diff: return NormalizeLayer(_DIFF_MEAN, _DIFF_STD) if vit: return NormalizeLayer(_CIFAR10_MEAN_VIT, _CIFAR10_STDDEV_VIT) if (dataset == 'imagenet'): return NormalizeLayer(_IMAGENET_MEAN, _IMAGENET_STDDE...
def prettify_print_name(name): if ((name is None) or ('{' in name) or ('\\' in name)): return name subscripts = [] superscripts = [] average = False processing = True while processing: processing = False for superscript in ['init', 'ref', 'typ', 'max', '0', 'surf']: ...
def ComputeCoverage(p, bias, norm): q = quaternion.vec2vec2quat(norm, [0, 0, 1]) def ang(p): c = quaternion.rotvecquat(vector.sub(p[:3], bias), q) d = quaternion.rotvecquat(p[3:6], q) v = quaternion.rotvecquat(c, quaternion.vec2vec2quat(d, [0, 0, 1])) v = vector.normalize(v) ...
class CeleryRouterConfigTest(harness.CustomRouterMixin, TestCase): router_class = 'rapidsms.router.celery.CeleryRouter' def test_eager_invalid_backend(self): self.backends = {'mockbackend': {'ENGINE': harness.MockBackend}} self.set_backends() router = get_router() self.assertFals...
def ceaf(clusters, gold_clusters, phi_similarity): scores = np.zeros((len(gold_clusters), len(clusters))) for i in range(len(gold_clusters)): for j in range(len(clusters)): scores[(i, j)] = phi_similarity(gold_clusters[i], clusters[j]) (row_ind, col_ind) = linear_sum_assignment((- scores...
def filter_lines(lines, n_jobs, isomeric): logger.info('Filtering SMILES') with Pool(n_jobs) as pool: process_molecule_p = partial(process_molecule, isomeric=isomeric) dataset = [x for x in tqdm(pool.imap_unordered(process_molecule_p, lines), total=len(lines), miniters=1000) if (x is not None)] ...
class linear_attribute_model(nn.Module): def __init__(self, args, input_dim=1536, output_dim=128): super().__init__() self.fc1 = nn.Linear(input_dim, 1024, True) self.fc2 = nn.Linear(1024, 512, True) self.fc3 = nn.Linear(512, 256, True) self.fc4 = nn.Linear(256, output_dim, T...
_machine.travel('2020-10-10 10:00:00', tick=False) def test_send_voucher_via_email(rf, grant_factory, conference_factory, mocker): mocker.patch('grants.admin.messages') mock_send_email = mocker.patch('grants.admin.send_grant_voucher_email') conference = conference_factory(pretix_speaker_voucher_quota_id=123...
def as_tuple(tr, dataquality='D'): from pyrocko import mseed_ext itmin = int(round((tr.tmin * mseed_ext.HPTMODULUS))) itmax = int(round((tr.tmax * mseed_ext.HPTMODULUS))) srate = (1.0 / tr.deltat) return (tr.network, tr.station, tr.location, tr.channel, itmin, itmax, srate, dataquality, tr.get_ydata...
class TerminusFindTerminalMixin(): def find_terminal(self, window, tag=None, panel_only=False, visible_only=False): if tag: terminal = Terminal.from_tag(tag) if terminal: return terminal view = None recency_manager = RecencyManager.from_window(window) ...
class ResNet(nn.Module): def __init__(self, block, num_blocks, num_classes=10, num_of_channels=3): super(ResNet, self).__init__() self.in_planes = 64 self.conv1 = nn.Conv2d(num_of_channels, 64, kernel_size=3, stride=1, padding=1, bias=False) self.bn1 = nn.BatchNorm2d(64) self...
def test_emit_warning_when_event_loop_is_explicitly_requested_in_coroutine_method(pytester: Pytester): pytester.makepyfile(dedent(' import pytest\n\n class TestEmitsWarning:\n .asyncio\n async def test_coroutine_emits_warning(self, event_loop):\n ...
class GroundStateTest(unittest.TestCase): def test_get_ground_state_hermitian(self): ground = get_ground_state(get_sparse_operator((QubitOperator('Y0 X1') + QubitOperator('Z0 Z1')))) expected_state = csc_matrix(([1j, 1], ([1, 2], [0, 0])), shape=(4, 1), dtype=numpy.complex128).A expected_sta...
def _get_layer_input(layer: tf.keras.layers.Layer, model_layers_connections: ModelLayerConnectionsProperties.TYPE) -> tf.keras.layers.Layer: try: layer_input = [model_layers_connections[ModelLayerConnectionsProperties.OUTPUT_TENSORS][layer_aux] for layer_aux in model_layers_connections[ModelLayerConnections...
class SplitAttentionConv2d(nn.Module): def __init__(self, in_channels, channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, radix=2, reduction_factor=4, conv_cfg=None, norm_cfg=dict(type='BN')): super().__init__() inter_channels = max(((in_channels * radix) // reduction_factor), 32) ...
def load_resnet_encoder(checkpoint_path, device): model = ResNetModel(512).eval().to(device) checkpoint = torch.load(checkpoint_path, map_location=device) new_state_dict = {} for (k, v) in checkpoint.items(): try: new_state_dict[k[6:]] = checkpoint[k] except KeyError: ...
def nice_time_diff(time_base: datetime, time_now: datetime) -> Tuple[(str, float)]: delta = (time_now - time_base) total_seconds = delta.total_seconds() if (total_seconds < 0.001): return (f'+ {delta.microseconds: 10.0f} s', total_seconds) if (total_seconds < 1): return (f'+ {(delta.micr...
def convert_label_map_to_categories(label_map, max_num_classes, use_display_name=True): categories = [] list_of_ids_already_added = [] if (not label_map): label_id_offset = 1 for class_id in range(max_num_classes): categories.append({'id': (class_id + label_id_offset), 'name': 'c...
def get_parser(parser=None): if (parser is None): parser = argparse.ArgumentParser() model_arg = parser.add_argument_group('Model') model_arg.add_argument('--q_cell', type=str, default='gru', choices=['gru'], help='Encoder rnn cell type') model_arg.add_argument('--q_bidir', default=False, action...
def _interpolate_get_scales(g, scale_factor, dim): offsets = g.op('Constant', value_t=torch.ones(2, dtype=torch.float32)) if isinstance(scale_factor.type(), torch._C.ListType): return g.op('Concat', offsets, scale_factor, axis_i=0) else: scale_factor = _unsqueeze_helper(g, scale_factor, 0) ...
class Migration(migrations.Migration): dependencies = [('questions', '0091_alter_questionset_options')] operations = [migrations.RemoveField(model_name='page', name='verbose_name_plural_lang1'), migrations.RemoveField(model_name='page', name='verbose_name_plural_lang2'), migrations.RemoveField(model_name='page'...
def make_recursive_list(fn): def recursive_map(tensors): if (tensors is None): return tensors elif (isinstance(tensors[0], list) or isinstance(tensors[0], tuple)): return type(tensors[0])(map(recursive_map, zip(*tensors))) elif isinstance(tensors[0], dict): ...
_fixtures(WebFixture, QueryStringFixture, ResponsiveWidgetScenarios) def test_focus_location_after_refresh_without_tabbing(web_fixture, query_string_fixture, responsive_widget_scenarios): fixture = responsive_widget_scenarios wsgi_app = web_fixture.new_wsgi_app(enable_js=True, child_factory=fixture.MainWidget.f...
def init_distributed_mode(args): if args.dist_on_itp: args.rank = int(os.environ['OMPI_COMM_WORLD_RANK']) args.world_size = int(os.environ['OMPI_COMM_WORLD_SIZE']) args.gpu = int(os.environ['OMPI_COMM_WORLD_LOCAL_RANK']) args.dist_url = ('tcp://%s:%s' % (os.environ['MASTER_ADDR'], os...
class Migration(migrations.Migration): dependencies = [('questions', '0076_questionset_remove_section')] operations = [migrations.AlterModelOptions(name='question', options={'ordering': ('uri',), 'verbose_name': 'Question', 'verbose_name_plural': 'Questions'}), migrations.AlterModelOptions(name='questionset', o...
class DebertaV2OnnxConfig(OnnxConfig): def inputs(self) -> Mapping[(str, Mapping[(int, str)])]: if (self.task == 'multiple-choice'): dynamic_axis = {0: 'batch', 1: 'choice', 2: 'sequence'} else: dynamic_axis = {0: 'batch', 1: 'sequence'} if (self._config.type_vocab_si...
def voc_eval(result_file, dataset, iou_thr=0.5): det_results = mmcv.load(result_file) gt_bboxes = [] gt_labels = [] gt_ignore = [] for i in range(len(dataset)): ann = dataset.get_ann_info(i) bboxes = ann['bboxes'] labels = ann['labels'] if ('bboxes_ignore' in ann): ...
class Effect4044(BaseEffect): runTime = 'early' type = ('projected', 'passive') def handler(fit, module, context, projectionRange, **kwargs): fit.modules.filteredItemMultiply((lambda mod: ('overloadSpeedFactorBonus' in mod.itemModifiedAttributes)), 'overloadSpeedFactorBonus', module.getModifiedItemA...
def load_archive_file(archive_file): try: resolved_archive_file = cached_path(archive_file, cache_dir=None) except EnvironmentError: logger.info("Archive name '{}' was not found in archive name list. We assumed '{}' was a path or URL but couldn't find any file associated to this path or URL.".fo...
def annotate_value(origin: Value, metadata: Sequence[Union[(Value, Extension)]]) -> Value: if (not metadata): return origin if isinstance(origin, AnnotatedValue): metadata = (*origin.metadata, *metadata) origin = origin.value hashable_vals = {} unhashable_vals = [] for item i...
def main(opt): if opt.disable_cudnn: torch.backends.cudnn.enabled = False print('Cudnn is disabled.') logger = Logger(opt) opt.device = torch.device('cuda:{}'.format(opt.gpus[0])) Dataset = dataset_factory[opt.dataset] (train, val) = task_factory[opt.task] (model, optimizer, star...
def test_fib_ycombinator(): Y = '\n (lambda (f)\n ((lambda (x) (x x))\n (lambda (g)\n (f (lambda (z) ((g g) z))))))\n' fac = '\n (lambda (f)\n (lambda (x)\n (if (< x 2)\n 1\n (* x (f (- x 1))))))\n ' fib = '\n (lambda (f)\n (lambda (x)\n (if ...
class PancakeHouseMenu(Menu): menuItems: List[MenuItem] def __init__(self): self.menuItems = [] self.addItem("K&B's Pancake Breakfast", 'Pancakes with scrambled eggs and toast', True, 2.99) self.addItem('Regular Pancake Breakfast', 'Pancakes with fried eggs, sausage', False, 2.99) ...
class Kernel(W): def __init__(self, data, bandwidth=None, fixed=True, k=2, function='triangular', eps=1.0000001, ids=None, diagonal=False, distance_metric='euclidean', radius=None, **kwargs): if (radius is not None): distance_metric = 'arc' if isKDTree(data): self.kdtree = da...
class CenterCrop(object): def __init__(self, size): if isinstance(size, numbers.Number): self.size = (int(size), int(size)) else: self.size = size def __call__(self, img): (w, h) = img.size (th, tw) = self.size x1 = int(round(((w - tw) / 2.0))) ...
class PreOCIModel(RepoEmailDataInterface): def get_email_authorized_for_repo(self, namespace_name, repository_name, email): return _return_none_or_data(model.repository.get_email_authorized_for_repo, namespace_name, repository_name, email) def create_email_authorization_for_repo(self, namespace_name, re...
def encode_path(value): if (value is None): return None if (not isinstance(value, (str, bytes))): value = (repr(value) if isinstance(value, type) else repr(type(value))) if isinstance(value, bytes): value = value.decode(sys.getfilesystemencoding()) return value
class CifarResNet(nn.Module): def __init__(self, block, depth, channels=3): super(CifarResNet, self).__init__() assert (((depth - 2) % 6) == 0), 'depth should be one of 20, 32, 44, 56, 110' layer_blocks = ((depth - 2) // 6) self.conv_1_3x3 = nn.Conv2d(channels, 16, kernel_size=3, str...
class UDPServer(Server): def __init__(self, host, prog, vers, port): Server.__init__(self, host, prog, vers, port) self.connect() def connect(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.prot = IPPROTO_UDP self.sock.bind((self.host, self.port))...
class Isothermal(BaseThermal): def __init__(self, param, options=None): super().__init__(param, options=options) def get_fundamental_variables(self): y = pybamm.standard_spatial_vars.y z = pybamm.standard_spatial_vars.z T_x_av = self.param.T_amb(y, z, pybamm.t) T_dict = {...
def test_demand_saving_with_indexed_array_from_hdf(): model = load_model('demand_saving_hdf.json') model.timestepper.end = pd.Timestamp('2016-01-31') rec_demand = NumpyArrayNodeRecorder(model, model.nodes['Demand']) rec_storage = NumpyArrayStorageRecorder(model, model.nodes['Reservoir']) model.check...
.parametrize('x_val, unique_axis, repeats, repeat_axis', [(np.array([[(- 10), (- 3)], [(- 10), 2]], dtype=np.int64), None, (1, 2), 0)]) .parametrize('return_index', [False]) .parametrize('return_counts', [False]) .parametrize('return_inverse', [False]) def test_local_Unique_Repeat(x_val, unique_axis, repeats, repeat_ax...
class TestClientSubscription(ClientTestCase): def setUp(self): super(TestClientSubscription, self).setUp() self.base_url = '{}/subscriptions'.format(self.base_url) self.subscription_id = 'sub_8RlLljfA4AnDVx' def test_subscription_fetch_all(self): result = mock_file('subscription_...
class SawyerButtonPressTopdownEnvV2(SawyerXYZEnv): def __init__(self): hand_low = ((- 0.5), 0.4, 0.05) hand_high = (0.5, 1, 0.5) obj_low = ((- 0.1), 0.8, 0.115) obj_high = (0.1, 0.9, 0.115) super().__init__(self.model_name, hand_low=hand_low, hand_high=hand_high) self...
_cache() def setup_logger(output=None, distributed_rank=0, *, color=True, name='imagenet', abbrev_name=None): logger = logging.getLogger(name) logger.setLevel(logging.DEBUG) logger.propagate = False if (abbrev_name is None): abbrev_name = name plain_formatter = logging.Formatter('[%(asctime)...
class SupportsCompositeMetricCompute(Protocol): composite_metric_name: str requires_metric: List[str] requires_validator: List[str] def compute(self, metric_results: Dict[(str, torch.Tensor)], validation_results: Dict[(str, validators.ValidatorOutput)], simulation_output: SimulationOutputCLE) -> float: ...
class MNISTInstance(datasets.MNIST): def __getitem__(self, index): if self.train: (img, target) = (self.train_data[index], self.train_labels[index]) else: (img, target) = (self.test_data[index], self.test_labels[index]) img = Image.fromarray(img.numpy(), mode='L') ...
def create_generators(args): common_args = {'batch_size': args.batch_size, 'phi': args.phi, 'detect_text': args.detect_text, 'detect_quadrangle': args.detect_quadrangle} if args.random_transform: misc_effect = MiscEffect() visual_effect = VisualEffect() else: misc_effect = None ...
def compose_transform(R=None, t=None): xp = cuda.get_array_module(R, t) if (R is None): Rs = xp.eye(3)[None] else: Rs = R[None] if (t is None): ts = xp.zeros((1, 3)) else: ts = t[None] with chainer.no_backprop_mode(): Ts = compose_transform_function(Rs, ts...
class TCOMM(TestCase): def test_default(self): frame = COMM() self.assertEqual(frame.encoding, 1) self.assertEqual(frame.lang, u'XXX') self.assertEqual(frame.desc, u'') self.assertEqual(frame.text, []) def test_hash(self): frame = COMM(encoding=0, lang='foo', desc...
class _EnsurePackagesDiscovered(_expand.EnsurePackagesDiscovered): def __init__(self, distribution: 'Distribution', project_cfg: dict, setuptools_cfg: dict): super().__init__(distribution) self._project_cfg = project_cfg self._setuptools_cfg = setuptools_cfg def __enter__(self): ...
def check_unix_fs_mocked(tmpdir: Any, mocker: MockerFixture) -> Callable[([Any, Any], None)]: def check(mocked_rm, mocked_ls): assert (mocked_rm is os.remove) assert (mocked_ls is os.listdir) file_name = (tmpdir / 'foo.txt') file_name.ensure() UnixFS.rm(str(file_name)) ...
def test_python_nodes_are_unique(tmp_path): tmp_path.joinpath('a').mkdir() tmp_path.joinpath('a', 'task_example.py').write_text('def task_example(a=1): pass') tmp_path.joinpath('b').mkdir() tmp_path.joinpath('b', 'task_example.py').write_text('def task_example(a=2): pass') session = build(paths=tmp_...
def test_return_on_hover(page: Page): page.get_by_role('link', name='simple popup').click() page.get_by_role('link', name='simple popup').click() expect(page.get_by_text('Popup: None')).to_be_visible() expect(page.get_by_text('Tooltip: None')).to_be_visible() page.get_by_text('Return on hover?').cli...
class Effect7062(BaseEffect): runTime = 'early' type = ('projected', 'passive', 'gang') def handler(fit, beacon, context, projectionRange, **kwargs): for x in range(1, 3): if beacon.getModifiedItemAttr('warfareBuff{}ID'.format(x)): value = beacon.getModifiedItemAttr('warf...
def test_joined_validators(): tst_validator = joined_validators(strict_discrete_set, strict_range) values = [['ON', 'OFF'], range(10)] assert (tst_validator(5, values) == 5) assert (tst_validator(5.1, values) == 5.1) assert (tst_validator('ON', values) == 'ON') with pytest.raises(ValueError): ...
class CalcToggleCommandFitStatesCommand(wx.Command): def __init__(self, fitID, mainCommandFitID, commandFitIDs, forceStates=None): wx.Command.__init__(self, True, 'Toggle Command Fit States') self.fitID = fitID self.mainCommandFitID = mainCommandFitID self.commandFitIDs = commandFitI...
class KsymAdaptedKRKS(krks.KRKS, khf_ksymm.KRHF): get_veff = get_veff get_rho = get_rho kpts = khf_ksymm.KsymAdaptedKSCF.kpts get_ovlp = khf_ksymm.KsymAdaptedKSCF.get_ovlp get_hcore = khf_ksymm.KsymAdaptedKSCF.get_hcore get_jk = khf_ksymm.KsymAdaptedKSCF.get_jk get_occ = khf_ksymm.KsymAdapte...
def test_slope_aware_backtracking(): index = pd.date_range('2019-01-01T08:00', '2019-01-01T17:00', freq='h') index = index.tz_localize('Etc/GMT+5') expected_data = pd.DataFrame(index=index, data=[(2.404287, 122.79177, (- 84.44), (- 10.899)), (11.263058, 133.288729, (- 72.604), (- 25.747)), (18.733558, 145.2...
class TestKeyedOptimizer(unittest.TestCase): def _assert_state_dict_equals(self, dict1: Dict[(str, Any)], dict2: Dict[(str, Any)]) -> None: self.assertEqual(dict1['param_groups'], dict2['param_groups']) self.assertEqual(dict1['state']['param_2'], dict2['state']['param_2']) torch.testing.asse...
def has_aer(): if (not _PROVIDER_CHECK.checked_aer): try: from qiskit.providers.aer import AerProvider _PROVIDER_CHECK.has_aer = True except Exception as ex: _PROVIDER_CHECK.has_aer = False logger.debug("AerProvider not loaded: '%s'", str(ex)) ...
class TestBmshj2018Factorized(): def test_params(self): for i in range(1, 6): net = bmshj2018_factorized(i, metric='mse') assert isinstance(net, FactorizedPrior) assert (net.state_dict()['g_a.0.weight'].size(0) == 128) assert (net.state_dict()['g_a.6.weight']....
def usymeig(A: LinearOperator, neig: Optional[int]=None, M: Optional[LinearOperator]=None, bck_options: Mapping[(str, Any)]={}, method: Union[(str, Callable, None)]=None, **fwd_options) -> Tuple[(torch.Tensor, torch.Tensor)]: return symeig(A, neig, 'uppest', M, method=method, bck_options=bck_options, **fwd_options)
(*specs) def test_env_semantics(spec): with open(ROLLOUT_FILE) as data_file: rollout_dict = json.load(data_file) if (spec.id not in rollout_dict): if ((not spec.nondeterministic) or should_skip_env_spec_for_tests(spec)): logger.warn('Rollout does not exist for {}, run generate_json.p...
def ranolazine_mpo() -> GoalDirectedBenchmark: ranolazine = 'COc1ccccc1OCC(O)CN2CCN(CC(=O)Nc3c(C)cccc3C)CC2' modifier = ClippedScoreModifier(upper_x=0.7) similar_to_ranolazine = TanimotoScoringFunction(ranolazine, fp_type='AP', score_modifier=modifier) logP_under_4 = RdkitScoringFunction(descriptor=logP...
class SPP(nn.Module): def __init__(self): super(SPP, self).__init__() def forward(self, x): x_1 = torch.nn.functional.max_pool2d(x, 5, stride=1, padding=2) x_2 = torch.nn.functional.max_pool2d(x, 9, stride=1, padding=4) x_3 = torch.nn.functional.max_pool2d(x, 13, stride=1, paddin...
def test_create(): builder = NintendontConnectorBuilder('102.168.1.1') assert (builder.configuration_params() == {'ip': '102.168.1.1'}) assert (builder.connector_builder_choice == ConnectorBuilderChoice.NINTENDONT) assert (builder.pretty_text == 'Nintendont: 102.168.1.1') executor = builder.create_e...