code
stringlengths
281
23.7M
def test_create_lane_links_normalroad1(): planview = [] lanec = [] lanel = [] laner = [] lanesec = [] lanes = [] rm = pyodrx.RoadMark(pyodrx.RoadMarkType.solid, 0.2, rule=pyodrx.MarkRule.no_passing) geom = [] geom.append(pyodrx.Line(50)) geom.append(pyodrx.Arc(0.01, angle=(np.pi ...
def _pickup_assignment_to_item_locations(region_list: RegionList, pickup_assignment: PickupAssignment, num_players: int) -> dict[(str, dict[(str, str)])]: items_locations: collections.defaultdict[(str, dict[(str, str)])] = collections.defaultdict(dict) for (region, area, node) in region_list.all_regions_areas_n...
class PopcornPopper(): description: str def __init__(self, description: str): self.description = description def on(self) -> None: print(f'{self.description} on') def off(self) -> None: print(f'{self.description} off') def pop(self) -> None: print(f'{self.description}...
class EnsurePackagesDiscovered(): def __init__(self, distribution: 'Distribution'): self._dist = distribution self._called = False def __call__(self): if (not self._called): self._called = True self._dist.set_defaults(name=False) def __enter__(self): r...
class GodelTNormSolver(TNormSolver): def gettnorm(self, args, function, probs): def AND(t, dim): return (t.min(dim)[0] if (dim is not None) else t.min()) def OR(t, dim): return (t.max(dim)[0] if (dim is not None) else t.max()) (tnorm_dict, lv, rv) = self.base_tnorm(ar...
def get_bn_params(model: ModelProto, bn: NodeProto, channels: int) -> libpymo.BNParams: bn_params = libpymo.BNParams() gamma = numpy_helper.to_array(ParamUtils.get_param(model, bn, WEIGHT_INDEX)).reshape((- 1)) resize = (channels / len(gamma)) bn_params.gamma = np.repeat(gamma, resize) bn_params.bet...
_new_faces(MaterialGroup.WALLS) def create_window_split(bm, face, prop): (wall_w, wall_h) = calc_face_dimensions(face) (width, height, offset) = (*prop.size, prop.offset) h_widths = [(((wall_w / 2) - offset.x) - (width / 2)), width, (((wall_w / 2) + offset.x) - (width / 2))] h_faces = subdivide_face_hor...
def _version_logger(save_dir, logger_name=''): if logger_name: path = os.path.join(save_dir, logger_name) else: path = save_dir if ((not os.path.exists(path)) or (not os.listdir(path))): version = 0 else: try: versions = [int(v.split('_')[(- 1)]) for v in os.l...
def get_random_ddf(chunk_size, num_chunks, frac_match, chunk_type, args): parts = [chunk_size for _ in range(num_chunks)] device_type = (True if (args.type == 'gpu') else False) meta = generate_chunk(0, 4, 1, chunk_type, None, device_type) divisions = ([None] * (len(parts) + 1)) name = ('generate-da...
class DebertaV2Tokenizer(PreTrainedTokenizer): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__(self, vocab_file, do_...
class Scope(): default: ty.ClassVar['Scope'] default_config: ty.Dict = {'device': 'cpu', 'tracing': False, 'types_to_trace': []} def __init__(self, config: ty.Union[(dict, str, None)]=None): if (config is None): self.config = type(self).default_config elif isinstance(config, str)...
class HVT(nn.Module): def __init__(self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4.0, qkv_bias=False, qk_scale=None, drop_rate=0.0, attn_drop_rate=0.0, drop_path_rate=0.0, norm_layer=nn.LayerNorm, **kwargs): super().__init__() self....
class Slither(ProblemDetector): name: str = 'slither' docker_image: str dockerCl: Any threadPool: ClassVar[concurrent.futures.ThreadPoolExecutor] = concurrent.futures.ThreadPoolExecutor() titleVulDict: ClassVar[Dict[(str, str)]] = {'reentrancy-eth': 'reentrancy', 'reentrancy-no-eth': 'reentrancy', '...
(tryfirst=True) def pytest_load_initial_conftests(args: list[str], early_config: pytest.Config, parser: pytest.Parser) -> None: for entry in _load_values(early_config): if (entry.skip_if_set and (entry.key in os.environ)): continue os.environ[entry.key] = (entry.value.format(**os.environ...
def define_G(opt): gpu_ids = opt['gpu_ids'] opt_net = opt['network_G'] which_model = opt_net['which_model_G'] if (which_model == 'sr_resnet'): netG = arch.SRResNet(in_nc=opt_net['in_nc'], out_nc=opt_net['out_nc'], nf=opt_net['nf'], nb=opt_net['nb'], upscale=opt_net['scale'], norm_type=opt_net['n...
class XdgStatic(Static[XdgSurface]): def __init__(self, core: Core, qtile: Qtile, win: XdgWindow, idle_inhibitor_count: int): surface = win.surface Static.__init__(self, core, qtile, surface, win.wid, idle_inhibitor_count=idle_inhibitor_count) if surface.toplevel.title: self.name...
def generate_app(appname, force=False, outpath='..', dbtype='sql', update_only=False, view_type=None): print((' generating app:' + str(appname))) import os, sys base = os.path.normpath(outpath) print((' base for app: ' + base)) root = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'start...
def get_parser(): parser = argparse.ArgumentParser(allow_abbrev=True, description='pypyr pipeline runner', formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('pipeline_name', help=wrap('Name of pipeline to run. Don`t add the .yaml at the end.')) parser.add_argument(dest='context_args', nargs...
class TransformerSentenceEncoderLayer(nn.Module): def __init__(self, embedding_dim: float=768, ffn_embedding_dim: float=3072, num_attention_heads: float=8, dropout: float=0.1, attention_dropout: float=0.1, activation_dropout: float=0.1, activation_fn: str='relu', layer_norm_first: bool=False) -> None: super...
class Migration(migrations.Migration): dependencies = [('adserver', '0086_region_topic_pricing')] operations = [migrations.AddField(model_name='historicalpublisher', name='allow_multiple_placements', field=models.BooleanField(default=False, help_text='Can this publisher have multiple placements on the same page...
def filter_rop(ops): addr = 0 gadgets = r2p.cmdj(('/Rj %s' % ops[0])) gadgets.reverse() for gadget in gadgets: instrs = gadget['opcodes'] for (i, instr) in enumerate(instrs): rest = [x['opcode'] for x in instrs[i:]] if (rest == ops): addr = instr['...
def save_trees(trees, path, mode='all', replace_newline=True, joiner='***', short_long_sep=''): assert (mode in ['all', 'final_long', 'final_short']) num_iterations = max([root.max_depth_from_self() for root in trees]) os.makedirs(os.path.dirname(path), exist_ok=True) with open(path, 'w') as wf: ...
def build_discriminator(): cnn = Sequential() cnn.add(Conv2D(32, 3, padding='same', strides=2, input_shape=(1, 28, 28))) cnn.add(LeakyReLU()) cnn.add(Dropout(0.3)) cnn.add(Conv2D(64, 3, padding='same', strides=1)) cnn.add(LeakyReLU()) cnn.add(Dropout(0.3)) cnn.add(Conv2D(128, 3, padding=...
class BotShortDescription(TelegramObject): __slots__ = ('short_description',) def __init__(self, short_description: str, *, api_kwargs: Optional[JSONDict]=None): super().__init__(api_kwargs=api_kwargs) self.short_description: str = short_description self._id_attrs = (self.short_descripti...
class Voxelization_Idx(Function): def forward(ctx, coords, batchsize, mode=4): assert coords.is_contiguous() N = coords.size(0) output_coords = coords.new() input_map = torch.IntTensor(N).zero_() output_map = input_map.new() PG_OP.voxelize_idx(coords, output_coords, i...
class TooManyStoppingSequences(ErrorReason): def __init__(self, num_stopping_sequences: int, max_num_stopping_sequences: int) -> None: self.num_stopping_sequences = num_stopping_sequences self.max_num_stopping_sequences = max_num_stopping_sequences def get_message(self) -> str: return f'...
class NNVFunction(MLPFunction): def __init__(self, env_spec, hidden_layer_sizes=(100, 100), name='vf', batchnormvf=False, dropoutvf_keep_prob=1.0): Serializable.quick_init(self, locals()) self._Do = env_spec.observation_space.flat_dim self._obs_pl = tf.placeholder(tf.float32, shape=[None, se...
def train(model, train_loader, myloss, optimizer, epoch): model.train() for (batch_idx, train_data) in enumerate(train_loader): train_data = Variable(train_data).type(torch.cuda.DoubleTensor).squeeze().view(175, 50, 34).permute(1, 0, 2) optimizer.zero_grad() output = model(train_data) ...
_attention('dot') class DotAttention(BaseAttention): def __init__(self, decoder_hidden_state_dim, context_dim, **kwargs): super().__init__(decoder_hidden_state_dim, context_dim) self.input_proj = None force_projection = kwargs.get('force_projection', False) if (force_projection or (d...
def _get_text_feedback(schedule_item): questions = TextFeedbackQuestion.objects.filter(schedule_item_type__title=schedule_item.type) text = [{'question': question, 'values': ScheduleItemTextFeedback.objects.filter(question=question, schedule_item=schedule_item)} for question in questions] return text
class BatchEasyHardMiner(BaseTupleMiner): HARD = 'hard' SEMIHARD = 'semihard' EASY = 'easy' ALL = 'all' all_batch_mining_strategies = [HARD, SEMIHARD, EASY, ALL] def __init__(self, pos_strategy=EASY, neg_strategy=SEMIHARD, allowed_pos_range=None, allowed_neg_range=None, **kwargs): super(...
class ColorShape(tc.nn.Module): ColorBiased = [(0.125, 'color', 0.1, 1.9), (0.125, 'brightness', 0.5, 1.9), (0.125, 'contrast', 0.5, 1.9), (0.125, 'sharpness', 0.1, 1.9), (0.125, 'autocontrast'), (0.125, 'equalize'), (0.125, 'shear', 0.05, 0.15), (0.125, 'rotate', 1, 11)] ShapeBiased = [(0.08, 'color', 0.1, 1.9...
def read_output(meteor_output_path, n_repeats): n_combinations = (math.factorial(n_repeats) / (math.factorial(2) * math.factorial((n_repeats - 2)))) raw_scores = [] average_scores = [] for line in open(meteor_output_path): if (not line.startswith('Segment ')): continue score ...
def decode_dxt1_rgb(data, width, height): out = (ctypes.c_uint16 * (width * height))() image_offset = 0 for (c0_lo, c0_hi, c1_lo, c1_hi, b0, b1, b2, b3) in split_8byte.findall(data): color0 = (ord(c0_lo) | (ord(c0_hi) << 8)) color1 = (ord(c1_lo) | (ord(c1_hi) << 8)) bits = (((ord(b0)...
def _get_new_season_streams(config, db): handlers = services.get_service_handlers() for service in db.get_services(): if (service.key not in handlers): warning('Service handler for {} not installed'.format(service.key)) continue if service.enabled: handler = h...
def parse_args(): parser = argparse.ArgumentParser(description='mmrotate benchmark a model') parser.add_argument('config', help='test config file path') parser.add_argument('checkpoint', help='checkpoint file') parser.add_argument('--repeat-num', type=int, default=1, help='number of repeat times of meas...
def main() -> None: application = Application.builder().token('TOKEN').build() application.add_handler(CommandHandler('start', start)) application.add_handler(CommandHandler('help', help_command)) application.add_handler(MessageHandler((filters.TEXT & (~ filters.COMMAND)), echo)) application.run_pol...
class CeilingFan(): HIGH: Final[int] = 3 MEDIUM: Final[int] = 2 LOW: Final[int] = 1 OFF: Final[int] = 0 location: str = '' speed: int = 0 def __init__(self, location: str): self.location = location def high(self) -> None: self.speed = self.HIGH print(f'{self.locat...
.slow def test_pinnacle_cli_missing_trial(data): output_path = tempfile.mkdtemp() for pinn_dir in data.joinpath('Pt1').joinpath('Pinnacle').iterdir(): command = (([str(pmp_test_utils.get_executable_even_when_embedded()), '-m'] + 'pymedphys pinnacle export'.split()) + ['-o', output_path, '-t', 'nonexiste...
class HarmonicPotential(PotentialBase): def __init__(self, molecule: Molecule) -> None: self.k = 0.0 self.m_shift = 0.0 self.r_0 = 0.0 self.d_e: Optional[float] = None if (molecule.masses is not None): self._m_a = molecule.masses[0] self._m_b = molecul...
((not torch.cuda.is_available()), 'test requires a GPU') class TestTranslationGPU(unittest.TestCase): def setUp(self): logging.disable(logging.CRITICAL) def tearDown(self): logging.disable(logging.NOTSET) def test_fp16_multigpu(self): with contextlib.redirect_stdout(StringIO()): ...
def main(): torch.set_default_dtype(torch.double) np.set_printoptions(precision=3) import notears.utils as ut ut.set_random_seed(123) (n, d, s0, graph_type, sem_type) = (200, 5, 9, 'ER', 'mim') B_true = ut.simulate_dag(d, s0, graph_type) np.savetxt('W_true.csv', B_true, delimiter=',') X ...
def test_import_visitor(): source = 'import operator\nimport itertools as itools\n\nimport urllib.parse\nimport tests.arbpack.arbmod as z\n\n# from mod import submod\nfrom tests.arbpack import arbmod2\nfrom tests.arbpack import arbmod3 as ab3\nfrom tests.arbpack import arbmod4_avoid\n\n# from mod import attr\nfrom ...
class LoginForm(Form): def __init__(self, view, login_session): super().__init__(view, 'login') self.use_layout(FormLayout()) if self.exception: self.layout.add_alert_for_domain_exception(self.exception) self.layout.add_input(TextInput(self, login_session.fields.email_add...
class APISession(requests.Session): base_url = ' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.headers.update({'Accept': 'application/json', 'User-Agent': f'pythondotorg/create_initial_data ({requests.utils.default_user_agent()})'}) def request(self, method, url...
def _dataclass_from_dict(klass, in_val): if is_dataclass(klass): fieldtypes = {f.name: f.type for f in fields(klass)} val = {} for dict_key in in_val: if ((dict_key in fieldtypes) and hasattr(fieldtypes[dict_key], 'from_dict')): val[dict_key] = fieldtypes[dict_key...
def find_dynamicsymbols(expression, exclude=None): t_set = set([dynamicsymbols._t]) if exclude: if iterable(exclude): exclude_set = set(exclude) else: raise TypeError('exclude kwarg must be iterable') else: exclude_set = set() return (set([i for i in expre...
def json_content(): return [{'id': 102, 'project': {'id': 2, 'name': 'Gitlab Ce', 'name_with_namespace': 'Gitlab Org / Gitlab Ce', 'path': 'gitlab-ce', 'path_with_namespace': 'gitlab-org/gitlab-ce'}, 'author': {'name': 'Administrator', 'username': 'root', 'id': 1}, 'action_name': 'marked', 'target_type': 'MergeRequ...
class PythonCause(IncompatibilityCause): def __init__(self, python_version: str, root_python_version: str) -> None: self._python_version = python_version self._root_python_version = root_python_version def python_version(self) -> str: return self._python_version def root_python_versi...
class CalcAddCargoCommand(wx.Command): def __init__(self, fitID, cargoInfo): wx.Command.__init__(self, True, 'Add Cargo') self.fitID = fitID self.cargoInfo = cargoInfo def Do(self): pyfalog.debug('Doing addition of cargo {} to fit {}'.format(self.cargoInfo, self.fitID)) f...
class ShardedTensorIOPreparerTest(unittest.TestCase): def _verify_subdivided_shards(self, subdivided: List[Tuple[(torch.Tensor, List[int], List[int])]], dim: int, expected_num_sub_shards: int, expected_combined: torch.Tensor, expected_offsets: List[int], expected_sizes: List[int]) -> None: (_, offsets, size...
def create_new_database(game_enum: RandovaniaGame, output_path: Path) -> GameDescription: items = [ItemResourceInfo(0, 'Powerful Weapon', 'Weapon', 1), ItemResourceInfo(1, 'Victory Key', 'VictoryKey', 1), ItemResourceInfo(2, 'Health', 'Health', 500)] resource_database = ResourceDatabase(game_enum=game_enum, ite...
class Effect6701(BaseEffect): type = 'passive' def handler(fit, src, context, projectionRange, **kwargs): lvl = src.level fit.modules.filteredItemBoost((lambda mod: (mod.item.group.name == 'Rig Projectile Weapon')), 'drawback', (src.getModifiedItemAttr('rigDrawbackBonus') * lvl), **kwargs)
def test_refund_transfer_with_reroute(): transfer_amount = TokenAmount(1000) block_number = BlockNumber(10) our_address = factories.ADDR (refund_pkey, refund_address) = factories.make_privkey_address() prng = random.Random() transfer_description = create(TransferDescriptionProperties(secret=UNIT...
def measure_with_final_permutation(circuit: cirq.Circuit, qubits: List[cirq.Qid], *, mutate=False) -> Tuple[(cirq.Circuit, List[cirq.Qid])]: if mutate: c2 = circuit else: c2 = circuit.copy() (mom_classes, stats) = validate_well_structured(c2, allow_terminal_permutations=True) if stats.ha...
def test_CheckParameter(): mu = pt.constant(0) sigma = pt.scalar('sigma') x_rv = pt.random.normal(mu, sigma, name='x') x_vv = pt.constant(0) x_logp = logp(x_rv, x_vv) x_logp_fn = function([sigma], x_logp) with pytest.raises(ParameterValueError, match='sigma > 0'): x_logp_fn((- 1))
def test_tree_set(): tree = SumSegmentTree(4) tree[2] = 1.0 tree[3] = 3.0 assert np.isclose(tree.sum(), 4.0) assert np.isclose(tree.sum(0, 2), 0.0) assert np.isclose(tree.sum(0, 3), 1.0) assert np.isclose(tree.sum(2, 3), 1.0) assert np.isclose(tree.sum(2, (- 1)), 1.0) assert np.isclo...
def get_dataset(dataset: str, split: str) -> Dataset: if (dataset == 'imagenet'): return _imagenet(split) elif (dataset == 'imagenet32'): return _imagenet32(split) elif (dataset == 'cifar10'): return _cifar10(split) elif (dataset == 'cifar10_vit'): return _cifar10vit(spli...
class FloorplanGenerator(): _props = None def __init__(self): self.context = bpy.context self.scene = bpy.context.scene self._register() def __del__(self): self._unregister() def _unregister(): del bpy.types.Scene.prop_floorplan def _register(self): tr...
_traceback def pq_compute_single_core(proc_id, annotation_set, gt_folder, pred_folder, categories, ow_eval, simi_matrix_path): pq_stat = PQStat() idx = 0 if ow_eval: simiAccess = SIMIaccess(simi_matrix_path) '\n\n file = os.path.join("/home/xp4/open-metrics/fc-clip/output/", "per_image_pq-sq-...
class PhoneDecoder(): def __init__(self, model_path, inference_config): self.model_path = Path(model_path) self.config = inference_config self.inventory = Inventory(model_path, inference_config) self.unit = self.inventory.unit def compute(self, logits, lang_id=None, topk=1, emit=...
def tokenize(sentence, regex=SENTENCE_SPLIT_REGEX, keep=["'s"], remove=[',', '?']): sentence = sentence.lower() for token in keep: sentence = sentence.replace(token, (' ' + token)) for token in remove: sentence = sentence.replace(token, '') tokens = regex.split(sentence) tokens = [t....
def get_data_loaders(dataset, data_root=None, augment=False, batch_size=64, num_workers=8, shuffle=True, load_in_mem=False, hdf5=False, pin_memory=True, drop_last=True, start_itr=0, num_epochs=500, use_multiepoch_sampler=False, **kwargs): data_root += ('/%s' % root_dict[dataset]) print(('Using dataset root loca...
class FitSpawner(gui.multiSwitch.TabSpawner): def __init__(self, multiSwitch): self.multiSwitch = multiSwitch self.mainFrame = mainFrame = gui.mainFrame.MainFrame.getInstance() mainFrame.Bind(EVT_FIT_SELECTED, self.fitSelected) self.multiSwitch.tabs_container.handleDrag = self.handle...
(scope='module') def test_image_rgba_merc(test_area_merc): arr = xr.DataArray(_get_fake_da((- 80), 40, (test_area_merc.shape + (4,))), dims=('y', 'x', 'bands'), coords={'bands': ['R', 'G', 'B', 'A']}, attrs={'name': 'test-rgba', 'start_time': datetime.datetime(2013, 2, 22, 12, 0), 'area': test_area_merc, 'mode': 'R...
def print_platform_version_info(): import scipy import platform import matplotlib from visualqc import __version__ print('version info: visualqc {}'.format(__version__)) print('numpy {} / scipy {} / matplotlib {}\npython {}'.format(np.__version__, scipy.__version__, matplotlib.__version__, sys.v...
class ResNet(nn.Module): def __init__(self, depth=28, widen_factor=10, dropout_rate=0): super(ResNet, self).__init__() self.in_planes = 16 assert (((depth - 4) % 6) == 0), 'Wide-resnet depth should be 6n+4' n = int(((depth - 4) / 6)) k = widen_factor print(('Wide-Resn...
def objective(x_train, y_train, W1, b1, z1, a1, W2, b2, z2, a2, W3, b3, z3, u, v1, v2, rho): r1 = torch.sum((((z1 - torch.matmul(W1, x_train)) - b1) * ((z1 - torch.matmul(W1, x_train)) - b1))) r2 = torch.sum((((z2 - torch.matmul(W2, a1)) - b2) * ((z2 - torch.matmul(W2, a1)) - b2))) r3 = torch.sum((((z3 - to...
def initialize(forced_gui: (GUIType | None)=None): def import_gtk(): global guilib try: import webview.platforms.gtk as guilib logger.debug('Using GTK') return True except (ImportError, ValueError): logger.exception('GTK cannot be loaded') ...
class WID2Section(Section): wid2 = WID2.T() sta2 = STA2.T(optional=True) eid2s = List.T(EID2.T()) bea2 = BEA2.T(optional=True) dat2 = DAT2.T() chk2 = CHK2.T() def read(cls, reader): blocks = dict(eid2s=[]) expect = [(b'WID2 ', WID2, 1)] if (reader.version_dialect[0] =...
_REGISTRY.register() class DANN(TrainerXU): def __init__(self, cfg): super().__init__(cfg) self.build_critic() self.ce = nn.CrossEntropyLoss() self.bce = nn.BCEWithLogitsLoss() def build_critic(self): cfg = self.cfg print('Building critic network') fdim = ...
class PreActBlock(nn.Module): expansion = 1 def __init__(self, in_planes, planes, stride=1): super(PreActBlock, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) nn.init.kaiming_normal_(self.conv1.weight, mode='fan_out') ...
def test_replace_alphabet_2() -> None: fsm1 = Fsm(alphabet={Charclass('z'), (~ Charclass('z'))}, states={0, 1, 2}, initial=0, finals={1}, map={0: {Charclass('z'): 2, (~ Charclass('z')): 1}, 1: {Charclass('z'): 2, (~ Charclass('z')): 1}, 2: {Charclass('z'): 2, (~ Charclass('z')): 2}}) fsm2 = fsm1.replace_alphabe...
class BatteryIcon(base._TextBox): orientations = base.ORIENTATION_HORIZONTAL defaults = [('battery', 0, 'Which battery should be monitored'), ('update_interval', 60, 'Seconds between status updates'), ('theme_path', default_icon_path(), 'Path of the icons')] icon_names = ('battery-missing', 'battery-caution...
def traj_segment_generator(pi, env, horizon, nenvs, stochastic, dropoutpi_keep_prob, dropoutvf_keep_prob, isbnpitrainmode, isbnvftrainmode): t = 0 ac = ([env.action_space.sample()] * nenvs) new = ([True] * nenvs) rew = ([0.0] * nenvs) ob = env.reset() cur_ep_ret = [] cur_ep_len = [] ep_r...
class RotationLogarithmicModel(RotationCostModel): slope: float overhead: float gateset: Optional[str] = None approximation_protocol: Optional[str] = None reference: Optional[str] = None def rotation_cost(self, error_budget: float) -> AlgorithmSummary: return AlgorithmSummary(t_gates=mat...
.parametrize(('local_config', 'fresh'), [({}, True), ({'dependencies': [uuid.uuid4().hex]}, True), ({'dependencies': [uuid.uuid4().hex], 'dev-dependencies': [uuid.uuid4().hex]}, True), ({'dependencies': [uuid.uuid4().hex], 'dev-dependencies': None}, True), ({'dependencies': [uuid.uuid4().hex], 'groups': [uuid.uuid4().h...
def test_music_settings(skip_qtbot: pytestqt.qtbot.QtBot) -> None: cosmetic_patches = SuperMetroidCosmeticPatches() dialog = SuperCosmeticPatchesDialog(None, cosmetic_patches) skip_qtbot.addWidget(dialog) for (music_mode, radio_button) in dialog.radio_buttons.items(): assert ((music_mode == dial...
class DuckFactory(AbstractDuckFactory): def createMallardDuck(self) -> Quackable: return MallardDuck() def createRedheadDuck(self) -> Quackable: return RedheadDuck() def createDuckCall(self) -> Quackable: return DuckCall() def createRubberDuck(self) -> Quackable: return R...
class GRU_encoder(nn.Module): def __init__(self, hidden_states=256): super(GRU_encoder, self).__init__() self.encoder = nn.GRU(342, 64, num_layers=1) self.mapping = nn.Linear(64, hidden_states) self.bn = nn.BatchNorm1d(hidden_states) def forward(self, x, flag='unsupervised'): ...
def visualize_detection_results(result_dict, tag, global_step, categories, summary_dir='', export_dir='', agnostic_mode=False, show_groundtruth=False, min_score_thresh=0.2, max_num_predictions=20): if (not set(['original_image', 'detection_boxes', 'detection_scores', 'detection_classes']).issubset(set(result_dict.k...
class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, bn_norm, with_ibn, baseWidth, cardinality, stride=1, downsample=None): super(Bottleneck, self).__init__() D = int(math.floor((planes * (baseWidth / 64)))) C = cardinality self.conv1 = nn.Conv2d(inplan...
def _get_callee_type(call: CallExpr) -> (CallableType | None): callee_node: (Node | None) = call.callee if isinstance(callee_node, RefExpr): callee_node = callee_node.node if isinstance(callee_node, Decorator): callee_node = callee_node.func if (isinstance(callee_node, (Var, SYMBOL_FUNCB...
def act_quantization(b, grid, power=True): def uniform_quant(x, b=3): xdiv = x.mul(((2 ** b) - 1)) xhard = xdiv.round().div(((2 ** b) - 1)) return xhard def power_quant(x, grid): shape = x.shape xhard = x.view((- 1)) value_s = grid.type_as(x) idxs = (xhard...
def from_ieee_block(block: Union[(bytes, bytearray)], datatype: BINARY_DATATYPES='f', is_big_endian: bool=False, container: Callable[([Iterable[Union[(int, float)]]], Sequence[Union[(int, float)]])]=list) -> Sequence[Union[(int, float)]]: (offset, data_length) = parse_ieee_block_header(block) if (data_length ==...
.requires_user_action class CaretColorInitTestCase(InteractiveTestCase, _DRYHelperMixin): def test_caret_color_init_rgb(self): color = (255, 0, 0) self.build_window(color) app.run() self.ask_color(color) def test_caret_color_init_rgba(self): color = (255, 0, 0, 80) ...
def get_checkpoint_id(key): if (key in all_methods): setting = 'hr_to_lr' method = key elif ((key in [(method + '-inst') for method in all_methods]) or (key in [(method + '-instruction') for method in all_methods])): setting = 'hr_to_lr_inst_all' method = '-'.join(key.split('-')[...
(name='help-analysis') _readme_flag def help_analysis(readme): get_wrapper(readme)('\nThe overall process is:\n\n1) Fragment structures in a SMILES file, to produce fragments.\n\n2) Index the fragments to produces matched molecular pairs.\n(you might include property information at this point)\n\n3) Load property i...
class TInternetRadio(TestCase): def setUp(self): quodlibet.config.init() self.bar = InternetRadio(SongLibrary()) def test_can_filter(self): self.assertTrue(self.bar.can_filter('foo')) self.assertTrue(self.bar.can_filter_text()) def test_status_bar_text(self): self.ass...
class CallContext(): __slots__ = ('args', 'keywords', 'callee') def __init__(self, args: list[NodeNG], keywords: (list[Keyword] | None)=None, callee: (InferenceResult | None)=None): self.args = args if keywords: arg_value_pairs = [(arg.arg, arg.value) for arg in keywords] els...
def _validate_setting(setting, value): if (setting == SettingCodes.ENABLE_PUSH): if (value not in (0, 1)): return ErrorCodes.PROTOCOL_ERROR elif (setting == SettingCodes.INITIAL_WINDOW_SIZE): if (not (0 <= value <= )): return ErrorCodes.FLOW_CONTROL_ERROR elif (settin...
class _BaseMedium(TelegramObject): __slots__ = ('file_id', 'file_size', 'file_unique_id') def __init__(self, file_id: str, file_unique_id: str, file_size: Optional[int]=None, *, api_kwargs: Optional[JSONDict]=None): super().__init__(api_kwargs=api_kwargs) self.file_id: str = str(file_id) ...
class M4CDecodingBCEWithMaskLoss(nn.Module): def __init__(self): super().__init__() self.one = torch.Tensor([1.0]) def forward(self, scores, targets, loss_mask): assert ((scores.dim() == 3) and (loss_mask.dim() == 2)) losses = F.binary_cross_entropy_with_logits(scores, targets, r...
class KeyMapper(QtCore.QObject): keyMappingChanged = QtCore.Signal() def setShortcut(self, action): if (action.menuPath in pyzo.config.shortcuts2): shortcuts = pyzo.config.shortcuts2[action.menuPath] action.setShortcuts(shortcuts.split(',')) pyzo.main.addAction(action...
def main(): with open(FLAGS.hq_replay_set) as f: replay_list = sorted(json.load(f)) race_vs_race = os.path.basename(FLAGS.hq_replay_set).split('.')[0] global_feature_vec_path = os.path.join(FLAGS.parsed_replay_path, 'SpatialFeatureTensor', race_vs_race) races = set(race_vs_race.split('_vs_')) ...
class CollectiveUtilsTest(unittest.TestCase): _and_log def setUp(self) -> None: os.environ['MASTER_ADDR'] = str(MASTER_ADDR) os.environ['MASTER_PORT'] = str(get_free_port()) os.environ['GLOO_DEVICE_TRANSPORT'] = 'TCP' os.environ['NCCL_SOCKET_IFNAME'] = 'lo' self.WORLD_SIZ...
_fixtures(WebFixture, DisclosedInputFixture) def test_input_values_retained_upon_domain_exception(web_fixture, disclosed_input_fixture): fixture = disclosed_input_fixture fixture.raise_domain_exception_on_submit = True fixture.default_trigger_field_value = False wsgi_app = web_fixture.new_wsgi_app(enabl...
def get_func_target(builder: IRBuilder, fdef: FuncDef) -> AssignmentTarget: if fdef.original_def: return builder.lookup(fdef.original_def) if (builder.fn_info.is_generator or builder.fn_info.add_nested_funcs_to_env): return builder.lookup(fdef) return builder.add_local_reg(fdef, object_rprim...
def do_parse(file_path): try: with io.open(file_path, 'rb') as fp: json_data = fp.read() except Exception as e: return (str(e), None) h = {} h['encoding'] = 'unknown' try: h = chardet.detect(json_data) try: with io.open(file_path, 'r', encoding...
class TestConnTrackCollector(CollectorTestCase): def setUp(self): config = get_collector_config('ConnTrackCollector', {'interval': 10, 'bin': 'true', 'dir': self.getFixtureDirPath()}) self.collector = ConnTrackCollector(config, None) def test_import(self): self.assertTrue(ConnTrackCollec...