code
stringlengths
281
23.7M
class LinearsolverResult(AlgorithmResult): def solution(self) -> np.ndarray: return self.get('solution') def solution(self, value: np.ndarray) -> None: self.data['solution'] = value def from_dict(a_dict: Dict) -> 'LinearsolverResult': return LinearsolverResult(a_dict)
class TestAdaroundOptimizer(unittest.TestCase): def _optimize_layer_rounding(self, warm_start): AimetLogger.set_level_for_all_areas(logging.DEBUG) model = TinyModel().eval() dummy_input = torch.randn(1, 3, 32, 32) sim = QuantizationSimModel(model, dummy_input=dummy_input, quant_schem...
class PathSeparatorTest(TestCase): def test_os_path_sep_matches_fake_filesystem_separator(self): filesystem = fake_filesystem.FakeFilesystem(path_separator='!') fake_os_module = fake_os.FakeOsModule(filesystem) self.assertEqual('!', fake_os_module.sep) self.assertEqual('!', fake_os_m...
def calculate_sentence_transformer_embedding(examples, embedding_model, mean_normal=False): text_to_encode = [f"The topic is {raw_item['activity_label']}. {raw_item['ctx_a']} {raw_item['ctx_b']} | {raw_item['endings'][0]} | {raw_item['endings'][1]} | {raw_item['endings'][2]} | {raw_item['endings'][3]}" for raw_item...
def is_literal_type_like(t: (Type | None)) -> bool: t = get_proper_type(t) if (t is None): return False elif isinstance(t, LiteralType): return True elif isinstance(t, UnionType): return any((is_literal_type_like(item) for item in t.items)) elif isinstance(t, TypeVarType): ...
class VisionEncoderDecoderDecoderOnnxConfig(OnnxConfig): def inputs(self) -> Mapping[(str, Mapping[(int, str)])]: common_inputs = OrderedDict() common_inputs['input_ids'] = {0: 'batch', 1: 'past_decoder_sequence + sequence'} common_inputs['attention_mask'] = {0: 'batch', 1: 'past_decoder_seq...
class GeneralDataset(data.Dataset): def __init__(self, root, transform=None, refname=True): self.root = root print(root) self.transform = transform self.retname = refname self.cam_intrinsic = np.float32(np.array([[582.64, 0, 313.04], [0, 582.69, 238.44], [0, 0, 1]])) ...
class TransparentCheckBox(QtWidgets.QCheckBox): def enterEvent(self, e): if (self.window().showhelp is True): QtWidgets.QToolTip.showText(e.globalPos(), '<h3>Frame transparency</h3>Toggle the transparency of the axis-frame.<p>If checked, the map will be exported with a transparent background.<p>...
class WriteSingleRegisterResponse(ModbusResponse): function_code = 6 _rtu_frame_size = 8 def __init__(self, address=None, value=None, **kwargs): super().__init__(**kwargs) self.address = address self.value = value def encode(self): return struct.pack('>HH', self.address, ...
def get_shortcuts_folder(): if (get_root_hkey() == winreg.HKEY_LOCAL_MACHINE): try: fldr = get_special_folder_path('CSIDL_COMMON_PROGRAMS') except OSError: fldr = get_special_folder_path('CSIDL_PROGRAMS') else: fldr = get_special_folder_path('CSIDL_PROGRAMS') ...
class AdaptiveBN(nn.Module): def __init__(self, max_nc, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True): super().__init__() num_features = max_nc self.num_features = max_nc self.eps = eps self.momentum = momentum self.affine = affine self.track...
def _notify_superusers(key): notification_metadata = {'name': key.name, 'kid': key.kid, 'service': key.service, 'jwk': key.jwk, 'metadata': key.metadata, 'created_date': timegm(key.created_date.utctimetuple())} if (key.expiration_date is not None): notification_metadata['expiration_date'] = timegm(key.e...
class ContactLabelGenerator(object): def __init__(self): pass def get_contact_labels(self, smpl, obj, num_samples, thres=0.02): object_points = obj.sample(num_samples) (dist, _, vertices) = igl.signed_distance(object_points, smpl.vertices, smpl.faces, return_normals=False) return...
class TextButton(DemoItem): BUTTON_WIDTH = 180 BUTTON_HEIGHT = 19 (LEFT, RIGHT) = range(2) (SIDEBAR, PANEL, UP, DOWN) = range(4) (ON, OFF, HIGHLIGHT, DISABLED) = range(4) def __init__(self, text, align=LEFT, userCode=0, parent=None, type=SIDEBAR): super(TextButton, self).__init__(parent)...
class HourGlassNetMultiScaleInt(nn.Module): def __init__(self, in_nc=3, out_nc=3, upscale=4, nf=64, res_type='res', n_mid=2, n_tail=2, n_HG=6, act_type='leakyrelu', inter_supervis=True, mscale_inter_super=False, share_upsample=False): super(HourGlassNetMultiScaleInt, self).__init__() self.n_HG = n_H...
def resolve_inout(input=None, output=None, files=None, overwrite=False, num_inputs=None): resolved_output = (output or (files[(- 1)] if files else None)) if ((not overwrite) and resolved_output and os.path.exists(resolved_output)): raise FileOverwriteError("file exists and won't be overwritten without u...
def pack_dbobj(item): _init_globals() obj = item natural_key = _FROM_MODEL_MAP[(hasattr(obj, 'id') and hasattr(obj, 'db_date_created') and hasattr(obj, '__dbclass__') and obj.__dbclass__.__name__.lower())] return ((natural_key and ('__packed_dbobj__', natural_key, _TO_DATESTRING(obj), _GA(obj, 'id'))) o...
def get_datasets(input_size: int, split_cache_path='split_cache.pkl'): mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] train_transform = transforms.Compose([transforms.Resize((input_size, input_size)), transforms.ToTensor(), transforms.Normalize(mean, std)]) test_transform = transforms.Compose(...
class FennelLexer(RegexLexer): name = 'Fennel' url = ' aliases = ['fennel', 'fnl'] filenames = ['*.fnl'] version_added = '2.3' special_forms = ('#', '%', '*', '+', '-', '->', '->>', '-?>', '-?>>', '.', '..', '/', '//', ':', '<', '<=', '=', '>', '>=', '?.', '^', 'accumulate', 'and', 'band', 'bnot...
class ExperimentPlanner3D_v21_customTargetSpacing_2x2x2(ExperimentPlanner3D_v21): def __init__(self, folder_with_cropped_data, preprocessed_output_folder): super(ExperimentPlanner3D_v21, self).__init__(folder_with_cropped_data, preprocessed_output_folder) self.data_identifier = 'nnFormerData_plans_v...
def activation(act_type, inplace=True, neg_slope=0.05, n_prelu=1): act_type = act_type.lower() if (act_type == 'relu'): layer = nn.ReLU(inplace) elif (act_type == 'lrelu'): layer = nn.LeakyReLU(neg_slope, inplace) elif (act_type == 'prelu'): layer = nn.PReLU(num_parameters=n_prel...
class While(_base_nodes.MultiLineWithElseBlockNode, _base_nodes.Statement): _astroid_fields = ('test', 'body', 'orelse') _multi_line_block_fields = ('body', 'orelse') test: NodeNG body: list[NodeNG] orelse: list[NodeNG] def postinit(self, test: NodeNG, body: list[NodeNG], orelse: list[NodeNG]) -...
def require_deepspeed_aio(test_case): if (not is_deepspeed_available()): return unittest.skip('test requires deepspeed')(test_case) import deepspeed from deepspeed.ops.aio import AsyncIOBuilder if (not deepspeed.ops.__compatible_ops__[AsyncIOBuilder.NAME]): return unittest.skip('test req...
(frozen=True) class StandardPickupDefinition(JsonDataclass): game: RandovaniaGame = dataclasses.field(metadata={'init_from_extra': True}) name: str = dataclasses.field(metadata={'init_from_extra': True}) pickup_category: PickupCategory = dataclasses.field(metadata={'init_from_extra': True}) broad_catego...
def get_survey_project_request_handler(request_type: str) -> Callable: handlers_dict = {'formEventMapping': handle_simple_project_form_event_mapping_request, 'metadata': handle_simple_project_metadata_request, 'record': handle_survey_project_records_request} return handlers_dict[request_type]
class FeatureListNet(FeatureDictNet): def __init__(self, model, out_indices=(0, 1, 2, 3, 4), out_map=None, feature_concat=False, flatten_sequential=False): super(FeatureListNet, self).__init__(model, out_indices=out_indices, out_map=out_map, feature_concat=feature_concat, flatten_sequential=flatten_sequenti...
def simplify_responses(responses): def unpack_multi(responses): for resp in responses: if isinstance(resp, MultiplyResponse): for sub in unpack_multi(resp.responses): (yield sub) else: (yield resp) def cancel_pzs(poles, zeros): ...
(frozen=True) class EventPaymentReceivedSuccess(Event): token_network_registry_address: TokenNetworkRegistryAddress token_network_address: TokenNetworkAddress identifier: PaymentID amount: PaymentAmount initiator: InitiatorAddress def __post_init__(self) -> None: if (self.amount < 0): ...
def PQDescPath(coll, f, lcs): f = (eval(f, globals(), lcs) if (f != '_') else None) stack = [] if isList(coll): stack = [i for i in flatten(coll)] elif isMap(coll): stack = [map_tuple(k, v) for (k, v) in coll.items()] while stack: i = stack.pop() if isinstance(i, map_...
def formatv(fwid, plusstr, pkstr, thresh, val): if (abs(val) < thresh): val1 = 0.0 else: val1 = val str = (pkstr % val1).strip() if re.match('^-0\\.0*$', str): str = str[1:] if (str[0] != '-'): str = (plusstr + str) str = str.replace('e', 'D') return (fwid % s...
.skipif((not dependencies.lvm.is_available), reason='lvm not available') def test_lvm_mount(): parser = ImageParser([fullpath('images/lvm.raw')]) volumes = [] for v in parser.init(): volumes.append(v) assert (len(volumes) == 2) assert (volumes[0].mountpoint is not None) assert (volumes[0...
class MypycNativeIntTests(TestCase): def test_construction(self): for native_int in native_int_types: self.assert_same(native_int(), 0) self.assert_same(native_int(0), 0) self.assert_same(native_int(1), 1) self.assert_same(native_int((- 3)), (- 3)) ...
def _check_shape(name, M, n, m, square=False, symmetric=False): if (square and (M.shape[0] != M.shape[1])): raise ControlDimension(('%s must be a square matrix' % name)) if (symmetric and (not _is_symmetric(M))): raise ControlArgument(('%s must be a symmetric matrix' % name)) if ((M.shape[0]...
class FancyFormatter(): def __init__(self, f_out: IO[str], f_err: IO[str], hide_error_codes: bool) -> None: self.hide_error_codes = hide_error_codes if (sys.platform not in ('linux', 'darwin', 'win32', 'emscripten')): self.dummy_term = True return if ((not should_forc...
def pass_orin_nano(engine): return [add_engine_in_list('APE', engine, 'APE', 'APE'), (add_engine_in_list('NVENC', engine, 'NVENC', 'NVENC') + add_engine_in_list('NVDEC', engine, 'NVDEC', 'NVDEC')), (add_engine_in_list('NVJPG', engine, 'NVJPG', 'NVJPG') + add_engine_in_list('NVJPG1', engine, 'NVJPG', 'NVJPG1')), (ad...
def parse_arguments(): parser = argparse.ArgumentParser(description='PyTorch ImageNet Training') parser.add_argument('--data', help='path to dataset base directory', default='dataset/') parser.add_argument('--optimizer', help='Which optimizer to use', default='sgd') parser.add_argument('--set', help='na...
(backend='memory', stale_after=timedelta(seconds=1), next_time=True) def _error_throwing_func(arg1): if (not hasattr(_error_throwing_func, 'count')): _error_throwing_func.count = 0 _error_throwing_func.count += 1 if (_error_throwing_func.count > 1): raise ValueError('Tiny Rick!') return ...
_criterion('cross_entropy') class CrossEntropyCriterion(FairseqCriterion): def __init__(self, args, task): super().__init__(args, task) def forward(self, model, sample, reduce=True): net_output = model(**sample['net_input']) (loss, _, sample_status) = self.compute_loss(model, net_output,...
.end_to_end() .parametrize('node_def', ["PathNode(path=Path('file.txt'))", "Path('file.txt')"]) def test_return_with_task_decorator(runner, tmp_path, node_def): source = f''' from pathlib import Path from typing_extensions import Annotated from pytask import task, PathNode (produces={node_def}) ...
(models.Proposal) class ProposalAdmin(TimeAuditAdmin, SimpleHistoryAdmin, ExportMixin): list_display = ('proposal_info', 'author_info', 'author_email', 'conference', 'status', 'review_status') list_filter = ['proposal_section__name', 'proposal_type', 'target_audience', 'conference', 'status', 'review_status'] ...
.parametrize('screenshot_manager', [{}, {'type': 'box'}, {'type': 'line'}, {'type': 'line', 'line_width': 1}, {'start_pos': 'top'}], indirect=True) def ss_hddgraph(screenshot_manager): widget = screenshot_manager.c.widget['hddgraph'] widget.eval(f'self.values={values}') widget.eval('self.maxvalue=400') ...
class SchemaValidator(KeywordValidator): def __init__(self, registry: 'KeywordValidatorRegistry'): super().__init__(registry) self.schema_ids_registry: Optional[List[int]] = [] def default_validator(self) -> ValueValidator: return cast(ValueValidator, self.registry['default']) def __...
def load_mnist(): (train, test) = tf.keras.datasets.mnist.load_data() (train_data, train_labels) = train (test_data, test_labels) = test train_data = (np.array(train_data, dtype=np.float32) / 255) test_data = (np.array(test_data, dtype=np.float32) / 255) train_labels = np.array(train_labels, dty...
def test_build_with_multiple_readme_files(fixture_dir: FixtureDirGetter, tmp_path: Path, tmp_venv: VirtualEnv, command_tester_factory: CommandTesterFactory) -> None: source_dir = fixture_dir('with_multiple_readme_files') target_dir = (tmp_path / 'project') shutil.copytree(str(source_dir), str(target_dir)) ...
class ReferenceFinder(mypy.mixedtraverser.MixedTraverserVisitor): def __init__(self) -> None: self.refs: set[str] = set() def visit_block(self, block: Block) -> None: if (not block.is_unreachable): super().visit_block(block) def visit_name_expr(self, e: NameExpr) -> None: ...
class MountainCarEnv(gym.Env): metadata = {'render.modes': ['human', 'rgb_array'], 'video.frames_per_second': 30} def __init__(self): self.min_position = (- 1.2) self.max_position = 0.6 self.max_speed = 0.07 self.goal_position = 0.5 self.low = np.array([self.min_position,...
.parametrize('selection_bitsize', [3, 4]) .parametrize('target_bitsize', [3, 5, 6]) def test_arctan(selection_bitsize, target_bitsize): gate = ArcTan(selection_bitsize, target_bitsize) maps = {} for x in range((2 ** selection_bitsize)): inp = f'0b_{x:0{selection_bitsize}b}_0_{0:0{target_bitsize}b}' ...
class ChangeEmail(LoginRequiredMixin, PasswordConfirmMixin, FormView): template_name = 'dictionary/user/preferences/email.html' form_class = ChangeEmailForm success_url = reverse_lazy('user_preferences') def form_valid(self, form): send_email_confirmation(self.request.user, form.cleaned_data.get...
def emit_yield(builder: IRBuilder, val: Value, line: int) -> Value: retval = builder.coerce(val, builder.ret_types[(- 1)], line) cls = builder.fn_info.generator_class next_block = BasicBlock() next_label = len(cls.continuation_blocks) cls.continuation_blocks.append(next_block) builder.assign(cls...
def calc_face_dimensions(face): horizontal_edges = filter_horizontal_edges(face.edges) vertical_edges = filter_vertical_edges(face.edges) width = (sum((e.calc_length() for e in horizontal_edges)) / 2) height = (sum((e.calc_length() for e in vertical_edges)) / 2) return (round(width, 4), round(height...
def monitor(steps): import re with open('train_log/DQN-REALDATA/mean_score.log', 'r') as file: c = file.read().splitlines() i = (- 1) while True: if ('Start Epoch' in c[i]): break i -= 1 assert ('Start Epoch' in c[i]) current_epoch = int(re...
def test_determine_ignored_lines(): f = incremental_coverage.determine_ignored_lines assert (f('a = 0 # coverage: ignore') == {1}) assert (f('\n a = 0 # coverage: ignore\n b = 0\n ') == {2}) assert (f('\n a = 0 \n b = 0 # coverage: ignore\n ') == {3}) assert (f(...
class TableModel(BaseTableModel): def __init__(self, client: Client, attachment: bool=True, **kwargs: Any): if attachment: self._attachment = AttachmentModel(client, table_name=kwargs.get('table_name')) super(TableModel, self).__init__(client, **kwargs) def _api_url(self) -> Any: ...
class ContextAuth(): clusterCertificate: str = None clusterCertificateData: str = None clusterHost: str = None clientCertificate: str = None clientCertificateData: str = None clientKey: str = None clientKeyData: str = None clusterName: str = None username: str = None password: st...
def local_property(name=None): if name: depr('local_property() is deprecated and will be removed.') ls = threading.local() def fget(self): try: return ls.var except AttributeError: raise RuntimeError('Request context not initialized.') def fset(self, value...
def parse_args(input_args=None): parser = argparse.ArgumentParser(description='Simple example of a training script.') parser.add_argument('--train', type=str, default='True', choices=['True', 'False']) parser.add_argument('--edit', type=str, default='True', choices=['True', 'False']) parser.add_argument...
def main(): pp.connect(use_gui=True) pp.add_data_path() p.resetDebugVisualizerCamera(cameraDistance=2, cameraPitch=(- 20), cameraYaw=80, cameraTargetPosition=[0, 0, 0]) p.loadURDF('plane.urdf') ri = reorientbot.pybullet.PandaRobotInterface() cube = pp.create_box(0.05, 0.05, 0.05, mass=0.1, color...
('evennia.server.portal.amp.amp.BinaryBoxProtocol.transport') class TestAMPClientRecv(_TestAMP): def test_msgportal2server(self, mocktransport): self._connect_server(mocktransport) self.amp_server.send_MsgPortal2Server(self.session, text={'foo': 'bar'}) wire_data = self._catch_wire_read(mock...
def test_ellipsoidal2dcs_to_cf(): ecs = Ellipsoidal2DCS(axis=Ellipsoidal2DCSAxis.LATITUDE_LONGITUDE) assert (ecs.to_cf() == [{'standard_name': 'latitude', 'long_name': 'latitude coordinate', 'units': 'degrees_north', 'axis': 'Y'}, {'standard_name': 'longitude', 'long_name': 'longitude coordinate', 'units': 'deg...
class Effect3201(BaseEffect): type = 'overheat' def handler(fit, module, context, projectionRange, **kwargs): module.boostItemAttr('duration', module.getModifiedItemAttr('overloadSelfDurationBonus')) module.boostItemAttr('shieldBonus', module.getModifiedItemAttr('overloadShieldBonus'), stackingP...
def test_shared_ptr_from_this_and_references(): s = m.SharedFromThisRef() stats = ConstructorStats.get(m.B) assert (stats.alive() == 2) ref = s.ref assert (stats.alive() == 2) assert s.set_ref(ref) assert s.set_holder(ref) bad_wp = s.bad_wp assert (stats.alive() == 2) assert s.se...
def test_protocol() -> None: tv = TypedValue(Proto) def fn() -> None: pass assert_cannot_assign(tv, KnownValue(fn)) fn.asynq = (lambda : None) assert_can_assign(tv, KnownValue(fn)) class X(): def asynq(self) -> None: pass assert_can_assign(tv, TypedValue(X)) a...
def join_simple(declaration: (Type | None), s: Type, t: Type) -> ProperType: declaration = get_proper_type(declaration) s = get_proper_type(s) t = get_proper_type(t) if ((s.can_be_true, s.can_be_false) != (t.can_be_true, t.can_be_false)): s = mypy.typeops.true_or_false(s) t = mypy.typeop...
def compute_sec_ver(remediations, packages: Dict[(str, Package)], secure_vulns_by_user, db_full): for pkg_name in remediations.keys(): pkg: Package = packages.get(pkg_name, None) secure_versions = [] if pkg: secure_versions = pkg.secure_versions analyzed = set(remediation...
def _orthographic__to_cf(conversion): params = _to_dict(conversion) return {'grid_mapping_name': 'orthographic', 'latitude_of_projection_origin': params['latitude_of_natural_origin'], 'longitude_of_projection_origin': params['longitude_of_natural_origin'], 'false_easting': params['false_easting'], 'false_northi...
class BsonConverter(Converter): def dumps(self, obj: Any, unstructure_as: Any=None, check_keys: bool=False, codec_options: CodecOptions=DEFAULT_CODEC_OPTIONS) -> bytes: return encode(self.unstructure(obj, unstructure_as=unstructure_as), check_keys=check_keys, codec_options=codec_options) def loads(self,...
class BellState(Bloq): _property def signature(self) -> 'Signature': return Signature([Register('q0', 1, side=Side.RIGHT), Register('q1', 1, side=Side.RIGHT)]) def build_composite_bloq(self, bb): q0 = bb.add(PlusState()) q1 = bb.add(ZeroState()) (q0, q1) = bb.add(CNOT(), ctrl...
.parametrize('url, expected_matches', [(' 1), (' 0), (' 0)]) def test_regex_includes_scripts_for(gm_manager, url, expected_matches): gh_dark_example = textwrap.dedent('\n // ==UserScript==\n // /^ // / // -at document-start\n // ==/UserScript==\n ') _save_script(g...
class SemiDataset(Dataset): def __init__(self, name, root, mode, size=None, id_path=None, nsample=None): self.name = name self.root = root self.mode = mode self.size = size if ((mode == 'train_l') or (mode == 'train_u')): with open(id_path, 'r') as f: ...
class ClusterRedisContextFactory(ContextFactory): def __init__(self, connection_pool: rediscluster.ClusterConnectionPool, name: str='redis', redis_client_name: str=''): self.connection_pool = connection_pool self.name = name self.redis_client_name = redis_client_name def report_runtime_m...
def sampling(imps, ratio=4): pos = [] neg = [] for imp in imps.split(): if (imp[(- 1)] == '1'): pos.append(imp) else: neg.append(imp) n_neg = (ratio * len(pos)) if (n_neg <= len(neg)): neg = random.sample(neg, n_neg) else: neg = random.samp...
class Adam(Optimizer): def __init__(self, lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0, **kwargs): super(Adam, self).__init__(**kwargs) with K.name_scope(self.__class__.__name__): self.iterations = K.variable(0, dtype='int64', name='iterations') self.lr = K.va...
def send_key_click(widget, accel, recursive=False): (key, mods) = Gtk.accelerator_parse(accel) assert (key is not None) assert (mods is not None) assert isinstance(widget, Gtk.Widget) handled = _send_key_click_event(widget, state=mods, keyval=key) if recursive: if isinstance(widget, Gtk....
def loadDataFile_with_groupseglabel(filename): f = h5py.File(filename) data = f['data'][:] group = f['pid'][:] if ('groupcategory' in f): cate = f['groupcategory'][:] else: cate = 0 seg = ((- 1) * np.ones_like(group)) for i in range(group.shape[0]): for j in range(gro...
.parametrize('genotype, expect', [([(- 1), 0], (- 1)), ([0, (- 1)], (- 1)), ([0, 0], 0), ([0, 1], 1), ([1, 0], 1), ([1, 1], 2), ([0, 0, 0], 0), ([0, 1, 0], 1), ([1, 1, 1], 3), ([0, 0, 0, 0], 0), ([0, 1, 0, 1], 2), ([1, 1, 0, 1], 3)]) def test__biallelic_genotype_index(genotype, expect): genotype = np.array(genotype...
class MLPBlockFC(nn.Module): def __init__(self, d_points, d_model, p_dropout): super(MLPBlockFC, self).__init__() self.mlp = nn.Sequential(nn.Linear(d_points, d_model, bias=False), nn.BatchNorm1d(d_model), nn.LeakyReLU(negative_slope=0.2), nn.Dropout(p=p_dropout)) def forward(self, x): r...
def main(): args = set_args() init(args) Tokenizer = eval_object(model_dict[args.model][0]) bert_path_or_name = model_dict[args.model][(- 1)] tokenizer = Tokenizer.from_pretrained(bert_path_or_name) print((20 * '='), ' Preparing for training ', (20 * '=')) print('\t* Loading training data......
class nnUNetTrainerDAOrd0(nnUNetTrainer): def get_dataloaders(self): patch_size = self.configuration_manager.patch_size dim = len(patch_size) deep_supervision_scales = self._get_deep_supervision_scales() (rotation_for_DA, do_dummy_2d_data_aug, initial_patch_size, mirror_axes) = self....
def prepare_ocp(biorbd_model_path, n_shooting, tf, ode_solver=OdeSolver.RK4(), use_sx=True, expand_dynamics=True): bio_model = BiorbdModel(biorbd_model_path) dynamics = Dynamics(DynamicsFcn.TORQUE_DRIVEN, expand_dynamics=expand_dynamics) x_bounds = BoundsList() x_bounds['q'] = bio_model.bounds_from_rang...
class SetData(namedtuple('SetData', 'path data version')): type = 5 def serialize(self): b = bytearray() b.extend(write_string(self.path)) b.extend(write_buffer(self.data)) b.extend(int_struct.pack(self.version)) return b def deserialize(cls, bytes, offset): r...
class OptUx(object): def __init__(self, formula, solver='g3', adapt=False, cover=None, dcalls=False, exhaust=False, minz=False, puresat=False, unsorted=False, trim=False, verbose=0): assert ((not puresat) or unsorted), "'unsorted' needs to be True for pure SAT mode" self.verbose = verbose se...
class VideoChunkIterator(): def __init__(self, video_features: np.ndarray, chunk_frames: int, num_border_frames: int) -> None: self.chunk_features_expanded = None self.valid_chunk_size = None self._output_start = None self._output_end = None self._result_start = None ...
def test_interpolation(): interp = Interpolate((0, 100), (0, 100)) for i in range(101): assert (interp(i) == i) interp = Interpolate((0, 50, 100), (0, 100, 200)) for i in range(101): assert (interp(i) == (2 * i)) interp = Interpolate((0, 50, 100), (0, (- 50), 50)) assert (interp(...
def burn_eth(rpc_client: JSONRPCClient, amount_to_leave: int=0) -> None: address = rpc_client.address web3 = rpc_client.web3 gas_price = web3.eth.gas_price amount_to_leave = (TRANSACTION_INTRINSIC_GAS + amount_to_leave) amount_to_burn = (web3.eth.get_balance(address) - (gas_price * amount_to_leave))...
class DebianControlLexer(RegexLexer): name = 'Debian Control file' url = ' aliases = ['debcontrol', 'control'] filenames = ['control'] version_added = '0.9' tokens = {'root': [('^(Description)', Keyword, 'description'), ('^(Maintainer|Uploaders)(:\\s*)', bygroups(Keyword, Text), 'maintainer'), (...
def test_upload_photos(requests_mock): requests_mock.post(f'{API_V0}/observation_photos', json=load_sample_data('post_observation_photos.json'), status_code=200) response = upload_photos(1234, BytesIO(), access_token='token') assert (response[0]['id'] == 1234) assert (response[0]['created_at'] == '2020-...
class NoOptionError(Error): def __init__(self, option: str, *, all_names: List[str]=None, deleted: bool=False, renamed: str=None) -> None: if deleted: assert (renamed is None) suffix = ' (this option was removed from qutebrowser)' elif (renamed is not None): suffi...
class TaggerModel(nn.Module): def __init__(self, args: Namespace, device: torch.device): super(TaggerModel, self).__init__() self.modelid = 'tagger_baseline' self.args = args self.device = device self.max_token = (args.max_generate + 1) self._encoder = PLM(args, devic...
def test_tc_bit_defers_last_response_missing(): zc = Zeroconf(interfaces=['127.0.0.1']) _wait_for_start(zc) type_ = '_knowndefer._tcp.local.' name = 'knownname' name2 = 'knownname2' name3 = 'knownname3' registration_name = f'{name}.{type_}' registration2_name = f'{name2}.{type_}' reg...
class GP(SingleTaskGP): def __init__(self, train_x, train_y, likelihood, lengthscale_constraint, outputscale_constraint, ard_dims, hyper=1.0, saas=True): covar_module = _prepare_covar_module(ard_dims, lengthscale_constraint, outputscale_constraint, hyper=hyper, saas=saas) super(GP, self).__init__(tr...
class GaussianBlur(object): def __init__(self, kernel_size, min=0.1, max=2.0): self.min = min self.max = max self.kernel_size = kernel_size def __call__(self, sample): sample = np.array(sample) prob = np.random.random_sample() if (prob < 0.5): sigma = ...
class FM(object): def __init__(self, formula, enc=EncType.pairwise, solver='m22', verbose=1): self.verbose = verbose self.solver = solver self.time = 0.0 self.topv = self.orig_nv = formula.nv self.hard = copy.deepcopy(formula.hard) self.soft = copy.deepcopy(formula.so...
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() centralWidget = QWidget() self.setCentralWidget(centralWidget) self.glWidget = GLWidget() self.pixmapLabel = QLabel() self.glWidgetArea = QScrollArea() self.glWidgetArea.setW...
class Effect5927(BaseEffect): runTime = 'early' type = ('projected', 'passive') def handler(fit, beacon, context, projectionRange, **kwargs): fit.modules.filteredChargeMultiply((lambda mod: mod.charge.requiresSkill('Bomb Deployment')), 'scanRadarStrengthBonus', beacon.getModifiedItemAttr('smartbombD...
_fixtures(WebFixture, ChoicesFixture) def test_choices_layout_applied_to_checkbox(web_fixture, choices_fixture): fixture = choices_fixture stacked_container = Div(web_fixture.view).use_layout(ChoicesLayout()) stacked_container.layout.add_choice(PrimitiveCheckboxInput(fixture.form, fixture.boolean_field)) ...
class Trainer(TrainerBase): def __init__(self, args, train_loader=None, val_loader=None, test_loader=None, train=True): super().__init__(args, train_loader=train_loader, val_loader=val_loader, test_loader=test_loader, train=train) if (not self.verbose): set_global_logging_level(logging.E...
class AsyncWorker(): _terminator = object() def __init__(self, shutdown_timeout=DEFAULT_TIMEOUT): check_threads() self._queue = Queue((- 1)) self._lock = threading.Lock() self._thread = None self._thread_for_pid = None self.options = {'shutdown_timeout': shutdown_...
_test def test_merge_average(): i1 = layers.Input(shape=(4, 5)) i2 = layers.Input(shape=(4, 5)) o = layers.average([i1, i2]) assert (o._keras_shape == (None, 4, 5)) model = models.Model([i1, i2], o) avg_layer = layers.Average() o2 = avg_layer([i1, i2]) assert (avg_layer.output_shape == (...
def test_offxml_combine_no_polar_lj(tmpdir, methanol, rfree_data, vs): with tmpdir.as_cwd(): alpha = rfree_data.pop('alpha') beta = rfree_data.pop('beta') lj = LennardJones612(free_parameters=rfree_data, alpha=alpha, beta=beta, lj_on_polar_h=False) lj.run(methanol) rfree_data...
def test_python_cmdline(testcase: DataDrivenTestCase, step: int) -> None: assert (testcase.old_cwd is not None), 'test was not properly set up' program = '_program.py' program_path = os.path.join(test_temp_dir, program) with open(program_path, 'w', encoding='utf8') as file: for s in testcase.inp...