code
stringlengths
281
23.7M
class DCGANGenerator(object): def __init__(self, hidden_dim=128, batch_size=64, hidden_activation=tf.nn.relu, output_activation=tf.nn.tanh, use_batch_norm=True, z_distribution='normal', scope='generator', **kwargs): self.hidden_dim = hidden_dim self.batch_size = batch_size self.hidden_activa...
('pypyr.moduleloader.get_module') (Step, 'invoke_step') def test_run_pipeline_steps_complex_with_run_str_false(mock_invoke_step, mock_get_module): step = Step({'name': 'step1', 'run': 'False'}) context = get_test_context() original_len = len(context) with patch_logger('pypyr.dsl', logging.INFO) as mock_...
class TDictMixin(TestCase): def setUp(self): self.fdict = FDict() self.rdict = {} self.fdict['foo'] = self.rdict['foo'] = 'bar' def test_getsetitem(self): self.failUnlessEqual(self.fdict['foo'], 'bar') self.failUnlessRaises(KeyError, self.fdict.__getitem__, 'bar') def...
class CustomCallback(TrainerCallback): def __init__(self, trainer) -> None: super().__init__() self._trainer = trainer def on_epoch_end(self, args, state, control, **kwargs): if control.should_evaluate: control_copy = deepcopy(control) self._trainer.evaluate(eval_...
class OrgProfileViewTest(TestCase): def setUpTestData(cls): add_default_data() def test_OrgProfileViewOk(self): response = self.client.get(reverse('org_profile', args=['rap'])) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'petition/org_profile.htm...
def spectral_response_all_junctions(solar_cell, incident_light=None, energy=None, V=0, verbose=False): science_reference('Nelson pin spectral response', 'Jenny: (Nelson. The Physics of Solar Cells. Imperial College Press (2003))') if (energy is None): if (incident_light is not None): energy ...
def _wraps(orig, glmfunc=None): if (glmfunc is None): glmfunc = orig def decorator(func): if ('PYUNITY_SPHINX_CHECK' in os.environ): return func if isinstance(orig, str): if GLM_SUPPORT: return getattr(glm, glmfunc) else: ...
def getDroneMult(drone, src, tgt, atkSpeed, atkAngle, distance, tgtSpeed, tgtAngle, tgtSigRadius): if ((distance is not None) and (((not GraphSettings.getInstance().get('ignoreDCR')) and (distance > src.item.extraAttributes['droneControlRange'])) or ((not GraphSettings.getInstance().get('ignoreLockRange')) and (dis...
class JointLoss(nn.Module): def __init__(self, args: Namespace, device: torch.device, criterion, size_average: bool=True, weights: dict=None, denomitor: float=1e-08): super(JointLoss, self).__init__() self.args = args self.device = device self.cross_entropy = criterion['ce'] ...
class GlobalAttention(nn.Module): def __init__(self, dim, coverage=False, attn_type='dot', attn_func='softmax'): super(GlobalAttention, self).__init__() self.dim = dim assert (attn_type in ['dot', 'general', 'mlp']), 'Please select a valid attention type (got {:s}).'.format(attn_type) ...
class DirLayout(): LAYOUT = ['folder0/file00', 'folder0/file01', 'folder1/folder10/file100', 'folder1/file10', 'folder1/file11', 'file0', 'file1'] def layout_folders(cls): folders = set() for path in cls.LAYOUT: parts = path.split('/') if (len(parts) > 1): ...
def random_lil(shape, dtype, nnz): sp = pytest.importorskip('scipy') rval = sp.sparse.lil_matrix(shape, dtype=dtype) huge = (2 ** 30) for k in range(nnz): idx = (np.random.default_rng().integers(1, (huge + 1), size=2) % shape) value = np.random.random() if (dtype in integer_dtype...
def main(): parser = argparse.ArgumentParser() parser.add_argument('--module', choices=['all', 'base', 'dplyr'], required=True, help='The module to test') parser.add_argument('--allow-conflict-names', action='store_true', help='Whether to allow conflict names', default=False) parser.add_argument('--geta...
class FakeNotificationAdapter(notification.AbstractNotificationAdapter): NAME = 'fake' def __init__(self) -> None: super().__init__() self.presented = [] self.id_gen = itertools.count(1) def present(self, qt_notification: 'QWebEngineNotification', *, replaces_id: Optional[int]) -> in...
class TestTag(): def test_expired_with_tag_expired_a_minute_ago(self): now_ms = get_epoch_timestamp_ms() one_hour_ago_ms = (now_ms - (3600 * 1000)) one_minute_ago_ms = (now_ms - (60 * 1000)) tag = Tag(name='latest', reversion=False, manifest_digest='abc123', lifetime_start_ts=(one_ho...
def clip_graphs_to_size(data, size_limit=5000): if hasattr(data, 'num_nodes'): N = data.num_nodes else: N = data.x.shape[0] if (N <= size_limit): return data else: logging.info(f' ...clip to {size_limit} a graph of size: {N}') if hasattr(data, 'edge_attr'): ...
def test_newtype_optionals(genconverter): Foo = NewType('Foo', str) genconverter.register_unstructure_hook(Foo, (lambda v: v.replace('foo', 'bar'))) class ModelWithFoo(): total_foo: Foo maybe_foo: Optional[Foo] assert (genconverter.unstructure(ModelWithFoo(Foo('foo'), Foo('is it a foo?')...
class TestHRITDecompress(unittest.TestCase): def test_xrit_cmd(self): old_env = os.environ.get('XRIT_DECOMPRESS_PATH', None) os.environ['XRIT_DECOMPRESS_PATH'] = '/path/to/my/bin' with pytest.raises(IOError, match='.* does not exist!'): get_xritdecompress_cmd() os.environ...
def tdm_fmcw_tx(): wavelength = (const.c / .0) tx_channel_1 = {'location': (0, ((- 4) * wavelength), 0), 'delay': 0} tx_channel_2 = {'location': (0, 0, 0), 'delay': 0.0001} return Transmitter(f=[(.0 - .0), (.0 + .0)], t=8e-05, tx_power=20, prp=0.0002, pulses=2, channels=[tx_channel_1, tx_channel_2])
def _lambert_conformal_conic__to_cf(conversion): params = _to_dict(conversion) if conversion.method_name.lower().endswith('(2sp)'): return {'grid_mapping_name': 'lambert_conformal_conic', 'standard_parallel': (params['latitude_of_1st_standard_parallel'], params['latitude_of_2nd_standard_parallel']), 'la...
class DarkBlock(nn.Module): def __init__(self, in_chs, out_chs, dilation=1, bottle_ratio=0.5, groups=1, act_layer=nn.ReLU, norm_layer=nn.BatchNorm2d, attn_layer=None, aa_layer=None, drop_block=None, drop_path=None): super(DarkBlock, self).__init__() mid_chs = int(round((out_chs * bottle_ratio))) ...
class UncaughtError(Redirect): def __init__(self, view, root_ui, target_ui, exception): error_source_bookmark = (view.as_bookmark(target_ui) if view else None) target_bookmark = root_ui.get_bookmark_for_error(str(exception), error_source_bookmark) super().__init__(target_bookmark)
def test_bitstruct_signals(): bs = mk_bitstruct('BitStructType', {'foo': Bits1, 'bar': Bits32}) class A2(Component): def construct(s): s.in0 = InPort(bs) s.in1 = InPort(Bits32) s.out = OutPort(Bits32) def add_upblk(): s.out = (s.in0.bar + s...
def plot_amplitudes_zpk(zpks, filename_pdf, fmin=0.001, fmax=100.0, nf=100, fnorm=None): from pyrocko.plot import gmtpy p = gmtpy.LogLogPlot(width=(30 * gmtpy.cm), yexp=0) for (i, (zeros, poles, constant)) in enumerate(zpks): (f, h) = evaluate(zeros, poles, constant, fmin, fmax, nf) if (fnor...
def squad_build_drqa_doc_encodings(out_dir, encoder_model, num_workers, all_squad=False): print('loading data...') corpus = SquadRelevanceCorpus() questions = corpus.get_dev() if all_squad: questions.extend(corpus.get_train()) relevant_titles = list(set([q.paragraph.doc_title for q in questi...
class TestQObjRepr(): .parametrize('obj', [QObject(), object(), None]) def test_simple(self, obj): assert (qtutils.qobj_repr(obj) == repr(obj)) def _py_repr(self, obj): r = repr(obj) if (r.startswith('<') and r.endswith('>')): return r[1:(- 1)] return r def te...
def test_phased_gaussian_single_particle(): chain = PhasedGaussianSingleParticle(k=(1.2 * 7), sigma=(1.2 / 7), position=(1.5 / 7)) amplitudes = chain.get_amplitudes(sites_count=8) np.testing.assert_allclose(amplitudes, [((- 0.) - 0.3883731j), (0. - 0.3186606j), (0. + 0.3186606j), ((- 0.) + 0.3883731j), ((- ...
class ThermalBuilder(BasicBuilder): def __init__(self, casePath, solverSettings=getDefaultHeatTransferSolverSettings(), templatePath=None, fluidProperties={'name': 'air', 'compressible': False, 'kinematicViscosity': 100000.0}, turbulenceProperties={'name': 'kEpsilon'}, boundarySettings=[], internalFields={}, transi...
class CLIPVisionConfig(PretrainedConfig): model_type = 'clip_vision_model' def __init__(self, hidden_size=768, intermediate_size=3072, num_hidden_layers=12, num_attention_heads=12, image_size=224, patch_size=32, hidden_act='quick_gelu', layer_norm_eps=1e-05, dropout=0.0, attention_dropout=0.0, initializer_range...
class CustomDatasetDataLoader(BaseDataLoader): def name(self): return 'CustomDatasetDataLoader' def initialize(self, opt): BaseDataLoader.initialize(self, opt) self.dataset = CreateDataset(opt) self.dataloader = torch.utils.data.DataLoader(self.dataset, batch_size=opt.batchSize, ...
def _replace_shared_variables(graph: List[TensorVariable]) -> List[TensorVariable]: shared_variables = [var for var in graph_inputs(graph) if isinstance(var, SharedVariable)] if any((isinstance(var.type, RandomType) for var in shared_variables)): raise ValueError('Graph contains shared RandomType variab...
def test_complete_package_does_not_merge_different_source_type_and_name(provider: Provider, root: ProjectPackage, fixture_dir: FixtureDirGetter) -> None: project_dir = fixture_dir('with_conditional_path_deps') path = (project_dir / 'demo_one').as_posix() dep_with_source_name = Factory.create_dependency('dem...
def setup(app): _directive = 'versionremoved' if (_directive not in versionlabels): versionlabels[_directive] = 'Removed in version %s' if (versionlabel_classes is not None): versionlabel_classes[_directive] = 'removed' app.add_directive(_directive, VersionChange) return ...
class NnetLatticeBiglmFasterRecognizer(NnetRecognizer): def __init__(self, transition_model, acoustic_model, decoder, symbols=None, allow_partial=True, decodable_opts=None, online_ivector_period=10): if (not isinstance(decoder, _dec.LatticeBiglmFasterDecoder)): raise TypeError('decoder argument ...
def train(data_dir='./data/', embedding_size=300, skipgram=False, siter=10, diter=10, negative_samples=10, window_size=5, output_path='./model', overwrite_compass=True, streamlit=False, component=None): if (streamlit and (component is None)): raise ValueError('`component` cannot be `None` when `streamlit` i...
def test_root_count(root, testapp, add_file_to_root): resp = testapp.get('/') resp.mustcontain('PyPI compatible package index serving 0 packages') add_file_to_root(root, 'Twisted-11.0.0.tar.bz2') resp = testapp.get('/') resp.mustcontain('PyPI compatible package index serving 1 packages')
class TestMultiCorpusDataset(unittest.TestCase): def setUp(self): d = mock_dict() tokens_1 = torch.LongTensor([i for i in range(1, 5000, 2)]).view(1, (- 1)) tokens_ds1 = TokenBlockDataset(tokens_1, sizes=[tokens_1.size((- 1))], block_size=1, pad=0, eos=1, include_targets=False) self....
class Solution(): def minDepth(self, root: Optional[TreeNode]) -> int: if (not root): return 0 nodes = [(root, 0)] depth = math.inf while nodes: (node, level) = nodes.pop() if ((not node.left) and (not node.right)): depth = min(leve...
def find_organization_invites(organization, user_obj): invite_check = (TeamMemberInvite.user == user_obj) if user_obj.verified: invite_check = (invite_check | (TeamMemberInvite.email == user_obj.email)) query = TeamMemberInvite.select().join(Team).where(invite_check, (Team.organization == organizati...
def parse_option(): parser = argparse.ArgumentParser() parser.add_argument('--width', default=1, type=int, help='backbone width') parser.add_argument('--num_target', type=int, default=256, help='Proposal number [default: 256]') parser.add_argument('--sampling', default='kps', type=str, help='Query point...
def find_all_i2c_power_monitor(i2c_path): power_sensor = {} if (not os.path.isdir(i2c_path)): logger.error("Folder {root_dir} doesn't exist".format(root_dir=i2c_path)) return power_sensor power_i2c_sensors = {} items = os.listdir(i2c_path) for item in items: path = '{base_pat...
def install_nvfancontrol(args): if (not os.path.isfile('/usr/bin/nvfancontrol')): shutil.copy('tests/nvfancontrol', '/usr/bin/nvfancontrol') print('Copied test/nvfancontrol') else: print('/usr/bin/nvfancontrol already exists') pytest.exit('I cannot install a fake nvfancontrol! nv...
class Processor(Iface, TProcessor): def __init__(self, handler): self._handler = handler self._processMap = {} self._processMap['example'] = Processor.process_example self._on_message_begin = None def on_message_begin(self, func): self._on_message_begin = func def pro...
class TFC_RNN(nn.Module): def __init__(self, in_channels, num_layers_tfc, gr, kt, kf, f, bn_factor_rnn, num_layers_rnn, bidirectional=True, min_bn_units_rnn=16, bias_rnn=True, bn_factor_tif=16, bias_tif=True, skip_connection=True, activation=nn.ReLU): super(TFC_RNN, self).__init__() self.skip_connec...
class TestQueryBestSize(EndianTest): def setUp(self): self.req_args_0 = {'drawable': , 'height': 64528, 'item_class': 1, 'width': 8620} self.req_bin_0 = b'a\x01\x03\x005\x8a\xb4u\xac!\x10\xfc' self.reply_args_0 = {'height': 2023, 'sequence_number': 41036, 'width': 35260} self.reply_b...
class CTOTrainer(NetworkTrainer): def __init__(self, opt): super().__init__(opt) def set_network(self): self.net = CTO(self.opt.train['num_class']) self.net = torch.nn.DataParallel(self.net, device_ids=self.opt.train['gpus']) self.net = self.net.cuda() def train(self, scaler,...
def test_float_image(): m = folium.Map([45.0, 3.0], zoom_start=4) url = ' szt = plugins.FloatImage(url, bottom=60, left=70, width='20%') m.add_child(szt) m._repr_html_() out = normalize(m._parent.render()) tmpl = Template('\n <img id="{{this.get_name()}}" alt="float_image"\n sr...
def check_accuracy(model, test, device): total = 0 correct_body = 0 correct_shirt = 0 correct_pant = 0 correct_hair = 0 correct_action = 0 with torch.no_grad(): for item in test: (body, shirt, pant, hair, action, image) = item image = image.to(device) ...
class TestPolicyInformation(): def test_invalid_policy_identifier(self): with pytest.raises(TypeError): x509.PolicyInformation('notanoid', None) def test_none_policy_qualifiers(self): pi = x509.PolicyInformation(x509.ObjectIdentifier('1.2.3'), None) assert (pi.policy_identifi...
def import_catalog(element, save=False, user=None): try: catalog = Catalog.objects.get(uri=element.get('uri')) except Catalog.DoesNotExist: catalog = Catalog() set_common_fields(catalog, element) catalog.order = (element.get('order') or 0) set_lang_field(catalog, 'title', element) ...
def parse_args(argv: List[str]) -> argparse.Namespace: parser = argparse.ArgumentParser(description='copies a file between fsspec locations') parser.add_argument('--src', type=str, help='fsspec location of the file to read from', required=True) parser.add_argument('--dst', type=str, help='fsspec location of...
def do_EQU(op, stack, state): reg = stack.pop() (val,) = pop_values(stack, state) tmp = get_value(reg, state) if (state.condition != None): val = z3.If(state.condition, val, tmp) state.registers[reg] = val state.esil['old'] = tmp state.esil['cur'] = val state.esil['lastsz'] = sta...
def test_debug_false_by_default(pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.delenv('DJANGO_SETTINGS_MODULE') pytester.makeconftest("\n from django.conf import settings\n\n def pytest_configure():\n settings.configure(SECRET_KEY='set from pytest_confi...
class CocoDistEvalRecallHook(DistEvalHook): def __init__(self, dataset, interval=1, proposal_nums=(100, 300, 1000), iou_thrs=np.arange(0.5, 0.96, 0.05)): super(CocoDistEvalRecallHook, self).__init__(dataset, interval=interval) self.proposal_nums = np.array(proposal_nums, dtype=np.int32) self...
def parse_versioned_line(line): if (line[0] == '#'): line = line[1:].strip() line = line.rsplit('#', maxsplit=1)[0] line = line.split(';')[0].strip() ops = ['==', '~=', '!=', '>', '<', '>=', '<='] if any(((op in line) for op in ops)): for op in ops: if (op in line): ...
class Telemetry(): def __init__(self, data, url, shard=None): self.shard = (shard or ('xbox' if ('xbox-' in url) else 'pc')) self.events = [Event.instance(event_data) for event_data in self.generate_events_data(data)] def generate_events_data(self, data): data_class = SHARD_DATA_MAP[self...
def completions(config: Config, autoimport_workspace: Workspace, request): (document, position) = request.param com_position = {'line': 0, 'character': position} autoimport_workspace.put_document(DOC_URI, source=document) doc = autoimport_workspace.get_document(DOC_URI) (yield pylsp_autoimport_compl...
class TestErrorTree(TestCase): def test_it_knows_how_many_total_errors_it_contains(self): errors = [exceptions.ValidationError('Something', validator=i) for i in range(8)] tree = exceptions.ErrorTree(errors) self.assertEqual(tree.total_errors, 8) def test_it_contains_an_item_if_the_item_...
def simple_loads(explode: bool, name: str, schema_type: str, location: Mapping[(str, Any)]) -> Any: value = location[name] if (schema_type == 'array'): return split(value, separator=',') explode_type = (explode, schema_type) if (explode_type == (False, 'object')): return dict(map(split, ...
class _BaseCore(): __metaclass__ = abc.ABCMeta def __init__(self, hash_func, default_params): self.default_params = default_params self.hash_func = hash_func def set_func(self, func): func_params = list(inspect.signature(func).parameters) self.func_is_method = (func_params an...
def get_diff(repo, base_commit, commits): print('\n### DIFF ###\n') code_diff = [] for commit in commits: for diff_obj in commit.diff(base_commit): if ((diff_obj.change_type == 'A') and diff_obj.b_path.endswith('.py')): code_diff.append(diff_obj.b_path) elif (...
class TestSubtype(unittest.TestCase): def test_bit(self) -> None: assert is_subtype(bit_rprimitive, bool_rprimitive) assert is_subtype(bit_rprimitive, int_rprimitive) assert is_subtype(bit_rprimitive, short_int_rprimitive) for rt in native_int_types: assert is_subtype(bit...
class TestVSCF(QiskitChemistryTestCase): def test_bitstring(self): bitstr = vscf_bitstring([2, 2]) self.assertTrue(all((bitstr[::(- 1)] == np.array([True, False, True, False])))) def test_qubits_4(self): basis = [2, 2] vscf = VSCF(basis) ref = QuantumCircuit(4) re...
.parametrize('testfile', ['bsrn-pay0616.dat.gz', 'bsrn-lr0100-pay0616.dat']) def test_read_bsrn(testfile, expected_index): (data, metadata) = read_bsrn((DATA_DIR / testfile)) assert_index_equal(expected_index, data.index) assert ('ghi' in data.columns) assert ('dni_std' in data.columns) assert ('dhi...
class TestLogFilter(): def _make_record(self, logger, name, level=logging.DEBUG): return logger.makeRecord(name, level=level, fn=None, lno=0, msg='', args=None, exc_info=None) .parametrize('filters, negated, category, logged', [(set(), False, 'eggs.bacon.spam', True), (set(), False, 'eggs', True), (set(...
def get_mult_function(mult_table, n_dims): non_zero_indices = mult_table.nonzero() k_list = non_zero_indices[0] l_list = non_zero_indices[1] m_list = non_zero_indices[2] mult_table_vals = np.array([mult_table[(k, l, m)] for (k, l, m) in np.transpose(non_zero_indices)], dtype=int) def mv_mult(val...
.parametrize('from_json', [True, False]) def test_from_json(from_json): json_path = os.path.join(os.path.dirname(__file__), 'models', 'demand_saving2_with_variables.json') if from_json: json_dict = pywr_json_to_d3_json(json_path, attributes=True) else: model = load_model('demand_saving2_with...
def test_do_deterministic(): rng = np.random.default_rng(seed=435) with pm.Model() as m: x = pm.Normal('x', 0, 0.001) y = pm.Deterministic('y', (x + 105)) z = pm.Normal('z', y, 0.001) do_m = do(m, {'z': (x - 105)}) assert (pm.draw(do_m['z'], random_seed=rng) < 100)
() def run(config: EvalConfig): print('Loading CLIP model...') device = torch.device(('cuda' if (torch.cuda.is_available() and (torch.cuda.device_count() > 0)) else 'cpu')) (model, preprocess) = clip.load('ViT-B/16', device) model.eval() print('Done.') prompts = [p.name for p in config.output_pa...
def node_location(caller): text = '\n The |cLocation|n of this object in the world. If not given, the object will spawn in the\n inventory of |c{caller}|n by default.\n\n {current}\n '.format(caller=caller.key, current=_get_current_value(caller, 'location')) helptext = '\n You get...
class PreviousStateRecorder(): def __init__(self): self.states = {} def add_state(self, data_item, slot_values): dialog_ID = data_item['dialogue_ID'] turn_id = data_item['turn_id'] if (dialog_ID not in self.states): self.states[dialog_ID] = {} self.states[dial...
def rdiff_backup_action(source_local, dest_local, src_dir, dest_dir, generic_opts, action, specific_opts, std_input=None, return_stdout=False, return_stderr=False): remote_exec = CMD_SEP.join([b'cd %s', b'%s server::%s']) is_remote = False if (src_dir and (not source_local)): src_dir = (remote_exec ...
class Environment(Singleton): def __init__(self, conf_dir=None, data_path=None): if (not hasattr(self, 'conf_dir')): if conf_dir: self.conf_dir = conf_dir else: self.conf_dir = get_platform().get_default_conf_dir() if (not hasattr(self, 'data_p...
def interpret_opcodes(iterable): vl = Values() nt = Notification() for (kind, data) in iterable: if (kind == TYPE_TIME): vl.time = nt.time = data elif (kind == TYPE_TIME_HR): vl.time = nt.time = (data / HR_TIME_DIV) elif (kind == TYPE_INTERVAL): vl...
def test_db_access_with_repr_in_report(django_pytester: DjangoPytester) -> None: django_pytester.create_test_module("\n import pytest\n\n from .app.models import Item\n\n def test_via_db_blocker(django_db_setup, django_db_blocker):\n with django_db_blocker.unblock():\n ...
def _safe_attr(attr, camel_killer=False, replacement_char='x'): allowed = ((string.ascii_letters + string.digits) + '_') attr = _safe_key(attr) if camel_killer: attr = _camel_killer(attr) attr = attr.replace(' ', '_') out = '' for character in attr: out += (character if (characte...
class Effect3036(BaseEffect): type = 'passive' def handler(fit, skill, context, projectionRange, **kwargs): fit.modules.filteredItemBoost((lambda mod: (mod.item.group.name == 'Missile Launcher Bomb')), 'moduleReactivationDelay', (skill.getModifiedItemAttr('reactivationDelayBonus') * skill.level), **kwar...
def might_extract_gz(path): path = Path(path) file_output_name = '.'.join(path.name.split('.')[:(- 1)]) file_name = path.name if (not (path.parent / file_output_name).exists()): logging.info('Extracting %s ...\n', file_name) with gzip.open(str(path), 'rb') as f_in: with open(...
def get_all_preds_for_execution(gold: str, pred: str) -> Tuple[(int, Iterator[str])]: (_, gold_values) = extract_query_values(gold) (pred_query_value_replaced, _) = extract_query_values(pred) num_slots = len([v for v in pred_query_value_replaced if (v == VALUE_NUM_SYMBOL.lower())]) num_alternatives = (l...
def test_pickups_to_solve_list_multiple(echoes_game_description, echoes_pickup_database, echoes_game_patches): db = echoes_game_description.resource_database missile_expansion = pickup_creator.create_ammo_pickup(echoes_pickup_database.ammo_pickups['Missile Expansion'], [5], False, db) pool = ([missile_expan...
_loss('weighted_cross_entropy') def weighted_cross_entropy(pred, true): if (cfg.model.loss_fun == 'weighted_cross_entropy'): V = true.size(0) n_classes = (pred.shape[1] if (pred.ndim > 1) else 2) label_count = torch.bincount(true) label_count = label_count[label_count.nonzero(as_tupl...
class MovingAverage(): def __init__(self, ema, oneminusema_correction=True): self.ema = ema self.ema_data = {} self._updates = 0 self._oneminusema_correction = oneminusema_correction def update(self, dict_data): ema_dict_data = {} for (name, data) in dict_data.ite...
def search_molecules_in_crystal(struc, tol=0.2, once=False, ignore_HH=True): def check_one_layer(struc, sites0, visited): new_members = [] for site0 in sites0: (sites_add, visited) = check_one_site(struc, site0, visited) new_members.extend(sites_add) return (new_membe...
def load_img_info(files): assert isinstance(files, tuple) (img_file, gt_file) = files assert (int(osp.basename(gt_file)[3:(- 4)]) == int(osp.basename(img_file)[2:(- 4)])) img = mmcv.imread(img_file, 'unchanged') img_info = dict(file_name=osp.join(osp.basename(img_file)), height=img.shape[0], width=i...
class DummyLM(LM): def __init__(self): pass def create_from_arg_string(cls, arg_string, additional_config=None): return cls() def loglikelihood(self, requests): res = [] for _ in requests: res.append(((- random.random()), False)) return res def greedy_...
def make_exe(filename): original_mode = filename.stat().st_mode levels = [S_IXUSR, S_IXGRP, S_IXOTH] for at in range(len(levels), 0, (- 1)): try: mode = original_mode for level in levels[:at]: mode |= level filename.chmod(mode) break ...
def convert_tensorflow(nlp: Pipeline, opset: int, output: Path): if (not is_tf_available()): raise Exception('Cannot convert because TF is not installed. Please install tensorflow first.') print("/!\\ Please note TensorFlow doesn't support exporting model > 2Gb /!\\") try: import tensorflow ...
_fixtures(WebFixture, CSRFFixture) def test_submit_form_with_expired_csrf_token(web_fixture, csrf_fixture): fixture = csrf_fixture wsgi_app = web_fixture.new_wsgi_app(child_factory=fixture.MyForm.factory(), enable_js=True) web_fixture.reahl_server.set_app(wsgi_app) browser = web_fixture.driver_browser ...
class EfficientNetMetrics(): def __init__(self, multiclass=True, weight=None, **kwargs): self.multiclass = multiclass self.weight = (weight is not None) self.metrics = {} self.metrics['loss'] = Average() self.metrics['accuracy'] = Accuracy(is_multilabel=(not multiclass)) ...
def operate_vocab(vocab_root_path, vocab_a_name, vocab_b_name, operator): assert (operator in ['intersect', 'sub']) vocab_a = load_vocab((vocab_root_path / vocab_a_name)) vocab_b = load_vocab((vocab_root_path / vocab_b_name)) vocab_a_set = set(vocab_a) vocab_b_set = set(vocab_b) print(f'''{vocab...
class DatoidCz(SimpleDownloader): __name__ = 'DatoidCz' __type__ = 'downloader' __version__ = '0.02' __status__ = 'testing' __pattern__ = ' __config__ = [('enabled', 'bool', 'Activated', True), ('use_premium', 'bool', 'Use premium account if available', True), ('fallback', 'bool', 'Fallback to f...
.parametrize('game', [RandovaniaGame.METROID_PRIME, RandovaniaGame.METROID_PRIME_ECHOES, RandovaniaGame.METROID_PRIME_CORRUPTION]) def test_on_preset_changed(skip_qtbot, preset_manager, game): base = preset_manager.default_preset_for_game(game).get_preset() preset = dataclasses.replace(base, uuid=uuid.UUID('b41...
class CosineDecayScheduler(object): def __init__(self, base_lr=1.0, last_iter=0, T_max=50): self.base_lr = base_lr self.last_iter = last_iter self.T_max = T_max self.cnt = 0 def decay_rate(self, step): self.last_iter = step decay_rate = (((self.base_lr * (1 + math...
class uvm_tlm_fifo(uvm_tlm_fifo_base): def __init__(self, name=None, parent=None, size=1): super().__init__(name, parent, size) def size(self): return self.queue.maxsize def used(self): return self.queue.qsize() def is_empty(self): return self.queue.empty() def is_ful...
class SlopePupil(Pupil): _type = 'slope' slope = None def __init__(self, slope, **kwargs): super().__init__(**kwargs) self.slope = slope def dict(self): dat = super().dict() dat['slope'] = float(self.slope) return dat def text(self): (yield from super(...
class Validator(Feature): pickle_rm_attr = ['validate', 'consistent'] def on_attach(self, fgraph): for attr in ('validate', 'validate_time'): if hasattr(fgraph, attr): raise AlreadyThere('Validator feature is already present or in conflict with another plugin.') fgrap...
class StackedResidualBlocks(nn.Module): def __init__(self, n_blocks: int, conv_op: Type[_ConvNd], input_channels: int, output_channels: Union[(int, List[int], Tuple[(int, ...)])], kernel_size: Union[(int, List[int], Tuple[(int, ...)])], initial_stride: Union[(int, List[int], Tuple[(int, ...)])], conv_bias: bool=Fal...
def display_constraints(ctr_entities, separator=''): for ce in ctr_entities: if (ce is not None): if hasattr(ce, 'entities'): print((separator + str(ce))) display_constraints(ce.entities, (separator + '\t')) else: print((separator + str...
def test_saving_the_same_answer_does_not_trigger_event(submission_factory, graphql_client, user, schedule_item_factory, slot_factory, day_factory, mocker): mock_event = mocker.patch('api.schedule.mutations.send_new_schedule_invitation_answer') graphql_client.force_login(user) submission = submission_factory...
def resolve_variants(node, rng: np.random.RandomState, variant_config, output_config): if isinstance(node, dict): if ('_variants' in node): var = node['_variants'] global_id = var['global_id'] if (var['type'] == 'options'): option_dict = var['options'] ...