code
stringlengths
281
23.7M
.parametrize('prefer_grpc', [False, True]) def test_qdrant_client_integration_update_collection(prefer_grpc): client = QdrantClient(prefer_grpc=prefer_grpc, timeout=TIMEOUT) client.recreate_collection(collection_name=COLLECTION_NAME, vectors_config={'text': VectorParams(size=DIM, distance=Distance.DOT)}, timeou...
class ProxyFactory(QNetworkProxyFactory): def get_error(self): proxy = config.val.content.proxy if isinstance(proxy, pac.PACFetcher): return proxy.fetch_error() else: return None def _set_capabilities(self, proxy): if (proxy.type() == QNetworkProxy.ProxyTy...
class IndexedDataset(FairseqDataset): _HDR_MAGIC = b'TNTIDX\x00\x00' def __init__(self, path, fix_lua_indexing=False): super().__init__() self.path = path self.fix_lua_indexing = fix_lua_indexing self.data_file = None self.read_index(path) def read_index(self, path): ...
class TestMongoMultiHostDBCollector(CollectorTestCase): def setUp(self): config = get_collector_config('TokuMXCollector', {'hosts': ['localhost:27017', 'localhost:27057'], 'databases': '^db'}) self.collector = TokuMXCollector(config, None) self.connection = MagicMock() def test_import(se...
def test_collectignore_via_conftest(pytester: Pytester) -> None: tests = pytester.mkpydir('tests') tests.joinpath('conftest.py').write_text("collect_ignore = ['ignore_me']", encoding='utf-8') ignore_me = tests.joinpath('ignore_me') ignore_me.mkdir() ignore_me.joinpath('__init__.py').touch() igno...
class PrepareAnonTerminals(Transformer_InPlace): def __init__(self, terminals): self.terminals = terminals self.term_set = {td.name for td in self.terminals} self.term_reverse = {td.pattern: td for td in terminals} self.i = 0 self.rule_options = None _args def pattern...
class TestEncryptionBuilder(): def test_unsupported_format(self): f = PrivateFormat.PKCS8 with pytest.raises(ValueError): f.encryption_builder() def test_duplicate_kdf_rounds(self): b = PrivateFormat.OpenSSH.encryption_builder().kdf_rounds(12) with pytest.raises(Value...
class BotUpdateTest(TestCase): def test_branch_is_none(self): bot = bot_factory() bot.provider.get_default_branch.return_value = 'the foo' bot.provider.get_file.return_value = (None, None) bot.get_all_requirements = Mock() bot.apply_updates = Mock() bot.update() ...
class TmpfsUsage_TestCase(CommandSequenceTest): def runTest(self): self.assert_parse('part /foo --size=100 --fstype=tmpfs --fsoptions="noexec"') self.assert_parse('part /ham --fstype=tmpfs --fsoptions="size=250%"') self.assert_parse('part /tmp --size=20000 --fstype=tmpfs') self.asser...
_equal.register(list, list) _equal.register(tuple, tuple) def assert_sequence_equal(result, expected, path=(), msg='', **kwargs): result_len = len(result) expected_len = len(expected) assert (result_len == expected_len), ('%s%s lengths do not match: %d != %d\n%s' % (_fmt_msg(msg), type(result).__name__, res...
def get_growing_subgraphs(device_graph: nx.Graph, central_qubit: cirq.Qid, min_size=2, max_size=None) -> Dict[(int, Tuple[cirq.Qid])]: by_radius = defaultdict(list) for (q, distance) in nx.shortest_path_length(device_graph, source=central_qubit).items(): by_radius[distance].append(q) by_radius = {k:...
class DirectionalLight(Light): def __init__(self, Ldir, color): self.Ldir = Ldir self.color = color def get_L(self): return self.Ldir def get_distance(self, M): return SKYBOX_DISTANCE def get_irradiance(self, dist_light, NdotL): return (self.color * NdotL)
class SegmentationDataset(Dataset): def __init__(self, images_root, masks_root, crop=True, size=None, mask_thr=0.5): self.mask_thr = mask_thr images_ds = UnannotatedDataset(images_root, transform=None) masks_ds = UnannotatedDataset(masks_root, transform=None) masks_ds.align_names(ima...
class BrowserWidget(QtWidgets.QWidget): def __init__(self, *args, parent=None): super().__init__(parent) self.browser_args = args self._setup_ui() self._layout() def _setup_ui(self): self.browser = Browser(*self.browser_args, parent=self) self.clear_button = QtWid...
def __match_identation_stack(identation_stack, level, level_limits, folding_ranges, current_line): upper_level = identation_stack.pop(0) while (upper_level >= level): level_start = level_limits.pop(upper_level) folding_ranges.append((level_start, current_line)) upper_level = identation_s...
class RRDB(nn.Module): def __init__(self, nf, gc=32): super(RRDB, self).__init__() self.RDB1 = ResidualDenseBlock_5C(nf, gc) self.RDB2 = ResidualDenseBlock_5C(nf, gc) self.RDB3 = ResidualDenseBlock_5C(nf, gc) def forward(self, x): out = self.RDB1(x) out = self.RDB...
_grad() def convert_wav2vec2_checkpoint(checkpoint_path, pytorch_dump_folder_path, config_path=None, dict_path=None, is_finetuned=True): if (config_path is not None): config = Wav2Vec2Config.from_pretrained(config_path) else: config = Wav2Vec2Config() if is_finetuned: if dict_path: ...
class Effect6636(BaseEffect): type = 'passive' def handler(fit, src, context, projectionRange, **kwargs): fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Capital Hybrid Turret')), 'damageMultiplier', src.getModifiedItemAttr('shipBonusTitanG1'), skill='Gallente Titan', **kwargs)
def main(argv): parser = argparse.ArgumentParser(description='Config file') parser.add_argument('--config_file', type=str, default='./configs/catcher.json', help='Configuration file for the chosen model') parser.add_argument('--config_idx', type=int, default=1, help='Configuration index') parser.add_arg...
class Migration(migrations.Migration): dependencies = [('questions', '0055_catalog_locked')] operations = [migrations.AddField(model_name='question', name='is_optional', field=models.BooleanField(default=False, help_text='Designates whether this question is optional.', verbose_name='is optional'))]
_grad() def evaluation(model, data_loader, device, config): model.eval() model_without_ddp = model if hasattr(model, 'module'): model_without_ddp = model.module metric_logger = utils.MetricLogger(delimiter=' ') header = 'Caption generation:' print_freq = 50 result = [] for batch...
() def empty_database(): old_db = database.db try: test_db = SqliteDatabase(':memory:') database.db = test_db with test_db.bind_ctx(database.all_classes): test_db.connect(reuse_if_open=True) (yield test_db) finally: database.db = old_db
def get_last_checkpoint(work_dir, steps=None): checkpoint = None last_ckpt_path = None ckpt_paths = get_all_ckpts(work_dir, steps) if (len(ckpt_paths) > 0): last_ckpt_path = ckpt_paths[0] checkpoint = torch.load(last_ckpt_path, map_location='cpu') logging.info(f'load module from ...
class GRAMLoss(BaseLoss): def __init__(self, runner, d_loss_kwargs=None, g_loss_kwargs=None): self.d_loss_kwargs = (d_loss_kwargs or dict()) self.g_loss_kwargs = (g_loss_kwargs or dict()) self.r1_gamma = self.d_loss_kwargs.get('r1_gamma', 10.0) self.camera_gamma = self.d_loss_kwargs....
.parametrize('use_path', [True, False], ids=['Path', 'str']) .parametrize('suffix', ['', '.qu', '.dat']) def test_qsave_qload(use_path, suffix): ops_in = [qutip.sigmax(), qutip.num(_dimension), qutip.coherent_dm(_dimension, 1j)] filename = (_random_file_name() + suffix) if use_path: filename = (Path...
def load_data_for_all_tasks(json_files): data_dict = {} for json_file in json_files: dataset_json = json.load(open(json_file)) logging.info(f"loading dataset file: {json_file} for {dataset_json['task']} task") print(f"loading dataset file: {json_file} for {dataset_json['task']} task") ...
_options_exempt def pp_inst(request, inst_index): try: inst_index = int(inst_index) except ValueError: return Http404() html_path = (PROJECT_APP_PATH + '/frontend/templates/frontend/particle-picking-inst/inst{}.html'.format(inst_index)) if (not os.path.exists(html_path)): return ...
class CustomIcon(Icon): _template = Template('\n {% macro script(this, kwargs) %}\n var {{ this.get_name() }} = L.icon({{ this.options|tojson }});\n {{ this._parent.get_name() }}.setIcon({{ this.get_name() }});\n {% endmacro %}\n ') def __init__(self, icon_image: Any, icon_siz...
def _check_required_metadata(metadata): for md in PLUGIN_REQUIRED_METADATA: if ((md not in dict(metadata)) or (not dict(metadata)[md])): raise ValidationError((_('Cannot find metadata <strong>%s</strong> in metadata source <code>%s</code>.<br />For further informations about metadata, please see...
class CustomTestSet(qpbenchmark.TestSet): def description(self) -> str: return 'Unit test test set' def title(self) -> str: return 'Unit test test set' def sparse_only(self) -> bool: return False def __iter__(self): (yield custom_problem(name='custom'))
def add_player_class_ex(teamid: int, model_id: int, spawn_x: float, spawn_y: float, spawn_z: float, z_angle: float, weapon1: int, weapon1_ammo: int, weapon2: int, weapon2_ammo: int, weapon3: int, weapon3_ammo: int) -> int: return AddPlayerClassEx(teamid, model_id, spawn_x, spawn_y, spawn_z, z_angle, weapon1, weapon...
class VERSE(): def __init__(self, cpath=None): path = (os.path.dirname(os.path.realpath(__file__)) if (cpath is None) else cpath) try: sofile = (glob.glob(os.path.join(path, 'verse*.so')) + glob.glob(os.path.join(path, '*verse*.dll')))[0] self.C = ctypes.cdll.LoadLibrary(os.p...
class nnUNetTrainerDA5_10epochs(nnUNetTrainerDA5): def __init__(self, plans: dict, configuration: str, fold: int, dataset_json: dict, unpack_dataset: bool=True, device: torch.device=torch.device('cuda')): super().__init__(plans, configuration, fold, dataset_json, unpack_dataset, device) self.num_epo...
class SneakerSchema(BaseModel): brand_name: str = Field(example='Nike') name: str = Field(example="Nike Air Force 1 '07") description: str = Field(example=DESC_EXAMPLE) size: conint(ge=38, le=53) = Field(example=42) color: str = Field(example='White') free_delivery: Optional[bool] = Field(exampl...
def test_licenses_deprecated(dummy_dist, monkeypatch, tmp_path): dummy_dist.joinpath('setup.cfg').write_text('[metadata]\nlicense_file=licenses/DUMMYFILE', encoding='utf-8') monkeypatch.chdir(dummy_dist) subprocess.check_call([sys.executable, 'setup.py', 'bdist_wheel', '-b', str(tmp_path), '--universal']) ...
.parametrize('template, expected', [('{{ func1(conf.aliases) }} {{ func2(conf.backend) }}', ['aliases', 'backend']), ('{{ conf.aliases["a"].propname }}', ['aliases']), ('{{ conf.auto_save.interval + conf.hints.min_chars }}', ['auto_save.interval', 'hints.min_chars']), ('{{ notconf.a.b.c }}', [])]) def test_template_con...
class UserInterfacePluginHandler(PluginHandler): def __init__(self): self.__plugins = {} self.__sidebars = {} def plugin_handle(self, plugin): return issubclass(plugin.cls, UserInterfacePlugin) def plugin_enable(self, plugin): self.__plugins[plugin.cls] = pl_obj = plugin.get_...
def _link_objs(value): result = '' delims = '(\\s*[\\[\\]\\(\\),]\\s*)' delims_re = re.compile(delims) sub_targets = re.split(delims, value.strip()) for sub_target in sub_targets: sub_target = sub_target.strip() if delims_re.match(sub_target): result += f'{sub_target}' ...
.usefixtures('config_tmpdir') class TestFile(): (params=[configtypes.File, unrequired_class]) def klass(self, request): return request.param def test_to_py_does_not_exist_file(self, os_mock): os_mock.path.isfile.return_value = False with pytest.raises(configexc.ValidationError): ...
def test_volume_sample_i(volume: wp.uint64, points: wp.array(dtype=wp.vec3)): tid = wp.tid() p = points[tid] i = round(p[0]) j = round(p[1]) k = round(p[2]) expected = int(((i * j) * k)) if ((abs(i) > 10.0) or (abs(j) > 10.0) or (abs(k) > 10.0)): expected = 10 expect_eq(wp.volume...
def get_config(): config = get_default_configs() training = config.training training.batch_size = 64 training.n_iters = 2400001 training.snapshot_sampling = True training.sde = 'vesde' training.continuous = True evaluate = config.eval evaluate.num_samples = 50000 evaluate.ckpt_id...
def init_distributed_device(args): args.distributed = False args.world_size = 1 args.rank = 0 args.local_rank = 0 dist_backend = getattr(args, 'dist_backend', 'nccl') dist_url = getattr(args, 'dist_url', 'env://') if is_distributed_env(): if ('SLURM_PROCID' in os.environ): ...
def transform_all_binary_images(root_path): if os.path.isdir(root_path): files = os.listdir(root_path) files = [file for file in files if ((file[0] != '.') and (file[:2] != '__'))] for file in files: try: transform_all_binary_images(os.path.join(root_path, file)) ...
def calculate_jaccard_index(R1, R2): subset_overlap = [] for n in range(len(R1)): sim_per_pair = [] for i in range(len(R1[n])): s1 = R1[n][i] s2 = R2[n][i] sim = jaccard_similarity(s1, s2) sim_per_pair.append(sim) subset_overlap.append(sim_...
class Net(nn.Module): def __init__(self) -> None: super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 32, 3, 1) self.conv2 = nn.Conv2d(32, 64, 3, 1) self.dropout1 = nn.Dropout(0.25) self.dropout2 = nn.Dropout(0.5) self.fc1 = nn.Linear(9216, 128) self.fc2 = n...
def build_auth(xpaths, username, password): auth = {} try: auth['username'] = [xpaths.pop('username'), username] except: raise ValueError('username not in predefined') try: auth['password'] = [xpaths.pop('password'), password] except: raise ValueError('password not in...
class H2Protocol(Protocol): def __init__(self, root): config = H2Configuration(client_side=False) self.conn = H2Connection(config=config) self.known_proto = None self.root = root self._flow_control_deferreds = {} def connectionMade(self): self.conn.initiate_connec...
class ImportNodeTest(resources.SysPathSetup, unittest.TestCase): def setUp(self) -> None: super().setUp() self.module = resources.build_file('data/module.py', 'data.module') self.module2 = resources.build_file('data/module2.py', 'data.module2') def test_import_self_resolve(self) -> None:...
_cache(maxsize=1000, typed=False) def eight_band_strain_hamiltonian(kx, ky, kz, Ev0, Ec0, exx, ezz, me_eff, gamma1, gamma2, gamma3, a0, Delta, ac, av, b, Ep): 'Hamiltonian to calculate cb, hh, lh, so bands and include strain for the biaxial (along [001]) special case.\n \n See Hamiltonian in ref. but remove r...
class IdentityObservationsData(ground_truth_data.GroundTruthData): def num_factors(self): return 10 def observation_shape(self): return 10 def factors_num_values(self): return ([1] * 10) def sample_factors(self, num, random_state): return random_state.random_integers(10, ...
class ISC(EarthquakeCatalog): def __init__(self, catalog=None): self.events = {} def flush(self): self.events = {} def append_time_params(self, a, time_range): (date_start_s, tstart_s) = util.time_to_str(time_range[0], format='%Y-%m-%d %H:%M:%S').split() (date_end_s, tend_s) ...
def _warn_incorrect_binary_bitness(exe_name): if (os.path.isabs(exe_name) and os.path.isfile(exe_name) and handleprops.is64bitbinary(exe_name) and (not is_x64_Python())): warnings.warn('64-bit binary from 32-bit Python may work incorrectly (please use 64-bit Python instead)', UserWarning, stacklevel=2)
class TBRangeCharacter(DefaultCharacter): def at_object_creation(self): self.db.max_hp = 100 self.db.hp = self.db.max_hp def at_before_move(self, destination): if is_in_combat(self): self.msg("You can't exit a room while in combat!") return False if (self....
def test_box_on_line(): box1 = [0, 0, 1, 0, 1, 1, 0, 1] box2 = [2, 0.5, 3, 0.5, 3, 1.5, 2, 1.5] box3 = [4, 0.8, 5, 0.8, 5, 1.8, 4, 1.8] assert is_on_same_line(box1, box2, 0.5) assert (not is_on_same_line(box1, box3, 0.5)) box4 = [0, 0, 1, 1, 1, 2, 0, 1] box5 = [2, 1.5, 3, 1.5, 3, 2.5, 2, 2.5...
_fixtures(WebFixture, PopupAFixture) def test_customising_dialog_buttons(web_fixture, popup_a_fixture): class PopupTestPanel(Div): def __init__(self, view): super().__init__(view) popup_a = self.add_child(PopupA(view, view.as_bookmark(), '#contents')) popup_a.add_js_butto...
def get_payer_channel(channelidentifiers_to_channels: Dict[(ChannelID, NettingChannelState)], transfer_pair: MediationPairState) -> Optional[NettingChannelState]: payer_channel_identifier = transfer_pair.payer_transfer.balance_proof.channel_identifier return channelidentifiers_to_channels.get(payer_channel_iden...
def test_vf_row_ground_2d(test_system_fixed_tilt): (ts, _, _) = test_system_fixed_tilt vf = utils.vf_row_ground_2d(ts['surface_tilt'], ts['gcr'], 0.0) expected = (0.5 * (1.0 - cosd(ts['surface_tilt']))) assert np.isclose(vf, expected) fx = np.array([0.0, 0.5, 1.0]) vf = utils.vf_row_ground_2d(ts...
def test_cof_list_input(): with pytest.raises(Call) as err: cof_func(name='blah', instruction_type=Call, context=Context({'key': ['b', 'c']}), context_key='key') cof = err.value assert isinstance(cof, Call) assert (cof.groups == ['b', 'c']) assert (not cof.success_group) assert (not cof....
class PointCloudField(): def __init__(self, file_name): self.file_name = file_name def load(self, model_path): file_path = os.path.join(model_path, self.file_name) pointcloud_dict = np.load(file_path) points = pointcloud_dict['points'].astype(np.float32) data = {'cloud': ...
.skipif((sys.version_info[0] < 3), reason='Python 3+ required for timezone support') def test_flexible_datetime_with_timezone_that_has_colons(): from datetime import timezone r = parse.parse('{dt:%Y-%m-%d %H:%M:%S %z}', '2023-11-21 13:23:27 +00:00:00') assert (r.named['dt'] == datetime(2023, 11, 21, 13, 23,...
def create_qr_from_map(design, url, mode, error): (bits, version) = get_raw_qr_data(design, error, mode) string = (bitstring_to_bin(bits) if (mode == 'binary') else bitstring_to_alphanumeric(bits)) with_url = ((url + '/') + string[(len(url) + 1):]) qr = pyqrcode.create(with_url, error=error, mode=mode, ...
def convert_xlnet_checkpoint_to_pytorch(tf_checkpoint_path, bert_config_file, pytorch_dump_folder_path, finetuning_task=None): config = XLNetConfig.from_json_file(bert_config_file) finetuning_task = (finetuning_task.lower() if (finetuning_task is not None) else '') if (finetuning_task in GLUE_TASKS_NUM_LABE...
def draw_sample(font_file): HEIGHT = 500 WIDTH = 800 background = Image.new('RGBA', (WIDTH, HEIGHT), ImageColor.getrgb('white')) foreground = Image.new('RGBA', (WIDTH, HEIGHT), (255, 255, 255, 0)) draw_b = ImageDraw.Draw(background) draw_f = ImageDraw.Draw(foreground) label_font = ImageFont....
class Repo(common.Common, unittest.TestCase): def test_full(self): self.run_test('test/demoapp', False, '.', False) def test_script_only(self): self.run_test('test/demoapp-script-only', True, '.', False) def test_project_in_subdir(self): self.run_test('test/demoapp', False, 'project'...
def _click_through_rate_input_check(input: torch.Tensor, weights: Union[(torch.Tensor, float, int)], *, num_tasks: int) -> None: if ((input.ndim != 1) and (input.ndim != 2)): raise ValueError(f'`input` should be a one or two dimensional tensor, got shape {input.shape}.') if (isinstance(weights, torch.Te...
def convert_batchnorm_parameters(model: torch.nn.Module, bn: Union[(torch.nn.BatchNorm1d, torch.nn.BatchNorm2d)]): with utils.in_eval_mode(model), torch.no_grad(): gamma = bn.weight beta = bn.bias running_mean = bn.running_mean inv_sigma = torch.rsqrt((bn.running_var + bn.eps)) ...
.fast def test_spectrum_get_methods(verbose=True, plot=True, close_plots=True, *args, **kwargs): from radis.test.utils import getTestFile from radis.tools.database import load_spec from radis.tools.slit import get_FWHM if (plot and close_plots): import matplotlib.pyplot as plt plt.close(...
class Edges(): def __init__(self): self.edges = [] def e(self, source, target, label, color, italicize=False, weight=1): if italicize: quoted_label = f'<<i>{label}</i>>' else: quoted_label = f'<{label}>' self.edges.append(f'''{source} -> {target} [ label...
def sum_regularizer(regularizer_list, scope=None): regularizer_list = [reg for reg in regularizer_list if (reg is not None)] if (not regularizer_list): return None def sum_reg(weights): with ops.name_scope(scope, 'sum_regularizer', [weights]) as name: regularizer_tensors = [] ...
def read_config(filename, fail): devices = [] if os.path.exists((pypilot_dir + filename)): try: f = open((pypilot_dir + filename), 'r') while True: device = f.readline() if (not device): break devices.append(devi...
class PresetStartingArea(PresetTab, Ui_PresetStartingArea, NodeListHelper): starting_area_quick_fill_default: QtWidgets.QPushButton _starting_location_for_region: dict[(str, QtWidgets.QCheckBox)] _starting_location_for_area: dict[(AreaIdentifier, QtWidgets.QCheckBox)] _starting_location_for_node: dict[(...
_auth def pull_asset(request): if (request.method == 'POST'): test_auth = request.POST.get('test_auth') conf_ids = request.POST.get('conf_ids') if test_auth: access_id = request.POST.get('access_id') access_key = request.POST.get('access_key') cloud_region...
class CatalogNestedSerializer(CatalogSerializer): elements = serializers.SerializerMethodField() class Meta(CatalogSerializer.Meta): fields = (*CatalogSerializer.Meta.fields, 'elements') def get_elements(self, obj): for element in obj.elements: (yield SectionNestedSerializer(elem...
def test_L3_ifc_view_index(): a = CaseArrayBits32IfcInComp.DUT() a.elaborate() a.apply(StructuralRTLIRGenL3Pass(gen_connections(a))) connections = a.get_metadata(StructuralRTLIRGenL2Pass.connections) comp = CurComp(a, 's') assert (connections == [(InterfaceAttr(InterfaceViewIndex(CurCompAttr(com...
def test_token_network_registry_max_token_networks(deploy_client, token_network_registry_address, contract_manager): proxy_manager = ProxyManager(rpc_client=deploy_client, contract_manager=contract_manager, metadata=ProxyManagerMetadata(token_network_registry_deployed_at=GENESIS_BLOCK_NUMBER, filters_start_at=GENES...
class LRUCache(object): def __init__(self, capacity): self.capacity = capacity self.cache = {} self.queue = [] def updateQueue(self, key): self.queue.remove(key) self.queue.insert(0, key) def get(self, key): if (key in self.cache): self.updateQueue...
.parametrize('store_graph', [False, True]) def test_tracker_candidate_graph(test_real_objects, store_graph): tracker = full_tracker_example(test_real_objects, store_candidate_graph=store_graph) assert (tracker.store_candidate_graph == store_graph) edges = tracker.candidate_graph_edges() assert (bool(edg...
class Effect2056(BaseEffect): type = 'passive' def handler(fit, skill, context, projectionRange, **kwargs): fit.modules.filteredItemBoost((lambda mod: (mod.item.group.name == 'Shield Resistance Amplifier')), 'thermalDamageResistanceBonus', (skill.getModifiedItemAttr('hardeningBonus') * skill.level), **k...
class TCN_GCN_unit_7(nn.Module): def __init__(self, in_channels, out_channels, A, stride=1, residual=True): super(TCN_GCN_unit_7, self).__init__() self.gcn1 = unit_gtcn_7(in_channels, out_channels, A) self.tcn1 = unit_tcn(out_channels, out_channels, stride=stride) self.relu = nn.ReLU...
def add_defaults(cfg: DictConfig) -> None: from fairseq.registry import REGISTRIES from fairseq.tasks import TASK_DATACLASS_REGISTRY from fairseq.models import ARCH_MODEL_NAME_REGISTRY, MODEL_DATACLASS_REGISTRY from fairseq.dataclass.utils import merge_with_parent from typing import Any OmegaCon...
class LossFunction(nn.Module): def __init__(self, gpu, init_w=10.0, init_b=(- 5.0), **kwargs): super(LossFunction, self).__init__() self.gpu = gpu self.w = nn.Parameter(torch.tensor(init_w)) self.b = nn.Parameter(torch.tensor(init_b)) self.w.requires_grad = True self....
def file_based_input_fn_builder(input_file, seq_length, is_training, drop_remainder): name_to_features = {'input_ids': tf.FixedLenFeature([seq_length], tf.int64), 'input_mask': tf.FixedLenFeature([seq_length], tf.int64), 'segment_ids': tf.FixedLenFeature([seq_length], tf.int64), 'label_ids': tf.FixedLenFeature([], ...
class DataModuleFromConfig(pl.LightningDataModule): def __init__(self, batch_size, train=None, validation=None, test=None, predict=None, wrap=False, num_workers=None, shuffle_test_loader=False, use_worker_init_fn=False, shuffle_val_dataloader=False): super().__init__() self.batch_size = batch_size ...
def main(): logging.basicConfig(level=logging.WARNING) parser = argparse.ArgumentParser() parser.add_argument('path', help='path to file(s) to reserialize') parser.add_argument('-a', '--all', action='store_true', help='reserialize all JSON files under path') args = parser.parse_args() if args.al...
def get_user_inputs(onnx_input_names, input_info, inputs, kwargs, device): def _expand_inputs(current_input, non_none_inputs): if ((current_input is None) or isinstance(current_input, str)): return if isinstance(current_input, abc.Sequence): for inp in current_input: ...
class strtr(): def st(self): while True: if (system == 'termux'): Ux() print("\x07\n\n\n\n\n\n\n\n\n\x1b[01;32m __ __ ____\n | \\/ |_ _/ ___| ___ _ \x1b[01;31m____ _____ \x1b[01;32m_ __\n | |\\/| | | | \\___ \\ / _ \\ '__\x1b[01;31m\\ \\ / / \...
class TestTruncatedNormalLowerTau(BaseTestDistributionRandom): pymc_dist = pm.TruncatedNormal (lower, upper, mu, tau) = ((- 2.0), np.inf, 0, 1.0) (tau, sigma) = get_tau_sigma(tau=tau, sigma=None) pymc_dist_params = {'mu': mu, 'tau': tau, 'lower': lower} expected_rv_op_params = {'mu': mu, 'sigma': si...
class Cfengine3Lexer(RegexLexer): name = 'CFEngine3' url = ' aliases = ['cfengine3', 'cf3'] filenames = ['*.cf'] mimetypes = [] version_added = '1.5' tokens = {'root': [('#.*?\\n', Comment), ('(body)(\\s+)(\\S+)(\\s+)(control)', bygroups(Keyword, Whitespace, Keyword, Whitespace, Keyword)), (...
(qssp.have_backend(), 'backend qssp not available') class QSSPTestCase(unittest.TestCase): def setUp(self): self.tmpdir = tempfile.mkdtemp(prefix='pyrocko.qssp') def tearDown(self): shutil.rmtree(self.tmpdir) (('qssp.2010' in qssp.have_backend()), 'backend qssp.2010 not available') def t...
def test_select_eof(select_app, monkeypatch): read_input_mock = mock.MagicMock(name='read_input', side_effect=[EOFError, 2]) monkeypatch.setattr('cmd2.Cmd.read_input', read_input_mock) food = 'fish' (out, err) = run_cmd(select_app, 'eat {}'.format(food)) arg = 'Sauce? ' calls = [mock.call(arg), ...
class RawRecipeSearcher(RecipeSearcher): def __init__(self, recipe: Sequence[Provider]): self.recipe = recipe def search_candidates(self, search_offset: int, request: Request) -> Iterable[SearchResult]: for (i, provider) in enumerate(islice(self.recipe, search_offset, None), start=search_offset)...
def get_state_dict(net_type: str='alex', version: str='0.1'): old_state_dict = torch.load('pretrained_models/alex.pth', map_location=(None if torch.cuda.is_available() else torch.device('cpu'))) new_state_dict = OrderedDict() for (key, val) in old_state_dict.items(): new_key = key new_key = ...
.end_to_end() .xfail((sys.platform == 'win32'), reason='Decoding issues in Gitlab Actions.') def test_execute_tasks_via_functional_api(tmp_path): source = '\n import sys\n from pathlib import Path\n from typing_extensions import Annotated\n from pytask import PathNode\n import pytask\n from pytask...
def identity_block(input_tensor, kernel_size, filters, stage, block, trainable=True): (nb_filter1, nb_filter2, nb_filter3) = filters if (K.image_dim_ordering() == 'tf'): bn_axis = 3 else: bn_axis = 1 conv_name_base = ((('res' + str(stage)) + block) + '_branch') bn_name_base = ((('bn'...
class _Actors(VersionBase): def __init__(self, selectTriggeringEntities=False): self.actors = [] self.select = convert_bool(selectTriggeringEntities) def __eq__(self, other): if isinstance(other, _Actors): if ((self.get_attributes() == other.get_attributes()) and (self.actors...
def get_subnets_info(regions): clients = [] for region in regions: client = boto3.client('ec2', region_name=region, aws_access_key_id=config.AWS_ACCESS_KEY, aws_secret_access_key=config.AWS_ACCESS_SECRET) client.region = region clients.append(client) subnet_info = OrderedDict() f...
(short_help='Remove build artifacts') ('location', required=False) ('--target', '-t', 'targets', multiple=True, help='The target with which to remove artifacts, overriding project defaults. This may be selected multiple times e.g. `-t sdist -t wheel`') ('--hooks-only', is_flag=True, help='Whether or not to only remove ...
class PythonLSPServer(MethodDispatcher): def __init__(self, rx, tx, check_parent_process=False, consumer=None, *, endpoint_cls=None): self.workspace = None self.config = None self.root_uri = None self.watching_thread = None self.workspaces = {} self.uri_workspace_mapp...
def test_bad_alphabets() -> None: with pytest.raises(ValueError, match='has overlaps'): Fsm(alphabet={Charclass('a'), Charclass('ab')}, states={0}, initial=0, finals=(), map={0: {Charclass('a'): 0, Charclass('ab'): 0}}) with pytest.raises(ValueError, match='not a proper partition'): Fsm(alphabet...
class Visualizer(): def __init__(self, opt): self.use_html = (opt.isTrain and (not opt.no_html)) self.win_size = opt.display_winsize self.name = opt.name self.opt = opt self.saved = False if self.use_html: self.web_dir = os.path.join(opt.checkpoints_dir, o...