code
stringlengths
281
23.7M
.parametrize('args', [{}, {'options': {'zticks': [1]}}, {'x_basis': [1, 2, 3, 4, 5]}, {'y_basis': [1, 2, 3, 4, 5]}, {'limits': [0, 1]}, {'color_limits': [0, 1]}, {'color_style': 'phase'}, {'options': {'threshold': 0.1}}, {'color_style': 'real', 'colorbar': True}, {'color_style': 'img', 'colorbar': True}, {'color_style'...
def test_pyproject_toml_invalid_priority() -> None: toml: dict[(str, Any)] = TOMLFile((FIXTURE_DIR / 'complete_invalid_priority.toml')).read() content = toml['tool']['poetry'] assert (Factory.validate(content) == {'errors': ["data.source[0].priority must be one of ['primary', 'default', 'secondary', 'supple...
(cc=STDCALL, params={'hDlg': HWND, 'nIDDlgItem': INT, 'lpString': LPSTR, 'cchMax': INT}) def hook_GetDlgItemTextA(ql: Qiling, address: int, params): lpString = params['lpString'] cchMax = params['cchMax'] ql.os.stdout.write(b'Input DlgItemText :\n') string = ql.os.stdin.readline().strip()[:cchMax] q...
def raw_checkboard(quality, metric='mse', pretrained=False, progress=True, **kwargs): if (metric not in ('mse', 'ms-ssim')): raise ValueError(f'Invalid metric "{metric}"') if ((quality < 1) or (quality > 8)): raise ValueError(f'Invalid quality "{quality}", should be between (1, 8)') return _...
class TxsETHAPPRSpider(TxsETHSpider): name = 'txs.eth.appr' def __init__(self, **kwargs): super().__init__(**kwargs) self.task_map = dict() self.alpha = float(kwargs.get('alpha', 0.15)) self.epsilon = float(kwargs.get('epsilon', 0.001)) def start_requests(self): if (s...
def test_hook_tracing(he_pm: PluginManager) -> None: saveindent = [] class api1(): def he_method1(self): saveindent.append(he_pm.trace.root.indent) class api2(): def he_method1(self): saveindent.append(he_pm.trace.root.indent) raise ValueError() he_pm....
_tokenizers class TokenizerVersioningTest(unittest.TestCase): def test_local_versioning(self): tokenizer = AutoTokenizer.from_pretrained('bert-base-cased') json_tokenizer = json.loads(tokenizer._tokenizer.to_str()) json_tokenizer['model']['vocab']['huggingface'] = len(tokenizer) with...
class TorchvisionDataset(Dataset): def __init__(self, cfg: AttrDict, data_source: str, path: str, split: str, dataset_name: str): super().__init__() assert PathManager.isdir(path), f'Directory {path} does not exist' self.dataset_name = dataset_name self.path = path self.split...
def _find_foldable_bn_pair_and_bn_picked_for_folding(connected_graph: ConnectedGraph) -> Tuple[(List[Tuple[(LayerType, BatchNormType)]], List[Tuple[(BatchNormType, LayerType)]], Set)]: conv_linear_bn_activation_info_dict = find_all_conv_bn_with_activation_in_graph(connected_graph) bn_picked_for_folding = set() ...
class TestRequestRepoBuild(ApiTestCase): def test_requestbuild_noidurl(self): self.login(ADMIN_ACCESS_USER) self.postResponse(RepositoryBuildList, params=dict(repository=(ADMIN_ACCESS_USER + '/simple')), data=dict(), expected_code=400) def test_requestbuild_invalidurls(self): self.login(...
class DistanceEmbed(nn.Module): def __init__(self, n_rbf, cutoff, feat_dim, dropout): super().__init__() rbf = PainnRadialBasis(n_rbf=n_rbf, cutoff=cutoff) dense = Dense(in_features=n_rbf, out_features=feat_dim, bias=True, dropout_rate=dropout) self.block = nn.Sequential(rbf, dense) ...
def mainopt_festival_dictionary_to_espeak(i): try: festival_location = sys.argv[(i + 1)] except IndexError: return 'Error: --festival-dictionary-to-espeak must be followed by the location of the festival OALD file (see help text)' try: open(festival_location) except: retu...
class IfElseIfElseIf(Op): def __init__(self, inplace=False): self.inplace = inplace assert (not self.inplace) def make_node(self, c1, t1, c2, t2, c3, t3, f3): assert (t1.type == f3.type) assert (t2.type == t3.type) assert (t3.type == f3.type) return Apply(self, [c...
class PreActResNet(nn.Module): def __init__(self, block, num_blocks, num_classes=10): super(PreActResNet, self).__init__() self.in_planes = 64 self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False) self.layer1 = self._make_layer(block, 64, num_blocks[0], stride...
class NC_ABI_BASE(BaseFileHandler): def __init__(self, filename, filename_info, filetype_info): super(NC_ABI_BASE, self).__init__(filename, filename_info, filetype_info) platform_shortname = filename_info['platform_shortname'] self.platform_name = PLATFORM_NAMES.get(platform_shortname.lower(...
def update_LD_LIBRARY_PATH(install_dir): export_statement = f'export LD_LIBRARY_PATH={install_dir}/lib:$LD_LIBRARY_PATH' venv_path = os.environ.get('VIRTUAL_ENV') if venv_path: script_path = os.path.join(venv_path, 'bin/activate') else: script_path = os.path.join(os.environ.get('HOME'), ...
def _encode_codepage(codepage, text): assert isinstance(text, text_type) if (not text): return b'' size = (len(text.encode('utf-16-le', _surrogatepass)) // ctypes.sizeof(winapi.WCHAR)) length = winapi.WideCharToMultiByte(codepage, 0, text, size, None, 0, None, None) if (length == 0): ...
class ConditionViewSet(ModelViewSet): permission_classes = ((HasModelPermission | HasObjectPermission),) serializer_class = ConditionSerializer queryset = Condition.objects.select_related('source', 'target_option').prefetch_related('optionsets', 'pages', 'questionsets', 'questions', 'tasks', 'editors') ...
def test_read_header(): keys = ('SatelliteId', 'NominalLongitude', 'SatelliteStatus') values = (324, 0.0, 1) expected = dict(zip(keys, values)) types = (np.uint16, np.float32, np.uint8) dtypes = np.dtype([(k, t) for (k, t) in zip(keys, types)]) hdr_data = np.array([values], dtype=dtypes) wit...
class FilterValidationTests(AuthenticatedAPITestCase): def test_filter_validation(self) -> None: test_sequences = get_test_sequences() base_filter = test_sequences['filter'] base_filter_list = test_sequences['filter_list1'] cases = (({'infraction_reason': 'hi'}, {}, 400), ({'infracti...
def override_eval_lm_args(args: Namespace) -> Tuple[(List[str], List[str])]: overrides = [] overrides.extend(_override_attr('params.common', CommonParams, args)) overrides.extend(_override_attr('params.dataset', DatasetParams, args)) overrides.extend(_override_attr('params.distributed_training', Distrib...
def detect_project_name(): logdir = dsz.lp.GetLogsDirectory() projectdir = os.path.split(logdir)[0] [logroot, project] = os.path.split(projectdir) if ((logroot.lower()[3:] != 'logs') or (not project)): print() dsz.ui.Echo('', dsz.ERROR) dsz.ui.Echo('ERROR: You did not correctly c...
class MDTextField(models.TextField): def __init__(self, *args, **kwargs): self.config_name = kwargs.pop('config_name', 'default') super(MDTextField, self).__init__(*args, **kwargs) def formfield(self, **kwargs): defaults = {'form_class': MDTextFormField, 'config_name': self.config_name} ...
def configure_converter(converter: BaseConverter): def gen_unstructure_mapping(cl: Any, unstructure_to=None): key_handler = str args = getattr(cl, '__args__', None) if args: if issubclass(args[0], str): key_handler = None elif issubclass(args[0], bytes...
def get_git_version() -> Optional[str]: dir = os.path.dirname(os.path.realpath(__file__)) try: version = subprocess.check_output(['git', 'describe', '--always', '--dirty'], cwd=dir) version = str(version, 'utf8').strip() except Exception: version = None return version
def convert_ndarray_to_list_in_data(data: np.ndarray): new_data = [] for item in data: if isinstance(item, np.ndarray): new_item = convert_ndarray_to_list_in_data(item) elif isinstance(item, dict): new_item = {} for (key, value) in item.items(): ...
def cl_parse(command, args, setup=None, details=None): usage = subcommand_usages[command] descr = subcommand_descriptions[command] if isinstance(usage, str): usage = [usage] susage = ('%s %s' % (program_name, usage[0])) for s in usage[1:]: susage += ('\n%s%s %s' % ((' ' * 7), program...
class Effect6054(BaseEffect): type = 'passive' def handler(fit, ship, context, projectionRange, **kwargs): fit.drones.filteredItemBoost((lambda drone: drone.item.requiresSkill('Heavy Drone Operation')), 'hp', ship.getModifiedItemAttr('shipBonusGC2'), skill='Gallente Cruiser', **kwargs)
def test_conftest_found_with_double_dash(pytester: Pytester) -> None: sub = pytester.mkdir('sub') sub.joinpath('conftest.py').write_text(textwrap.dedent(' def pytest_addoption(parser):\n parser.addoption("--hello-world", action="store_true")\n '), encoding='utf-8') p = s...
def test_do_cleanups_on_setup_failure(pytester: Pytester) -> None: testpath = pytester.makepyfile('\n import unittest\n class MyTestCase(unittest.TestCase):\n values = []\n def setUp(self):\n def cleanup():\n self.values.append(1)\n ...
def test_slowfast(): config = get_recognizer_cfg('slowfast/slowfast_r50_4x16x1_256e_kinetics400_rgb.py') recognizer = build_recognizer(config.model) recognizer.cfg = config input_shape = (1, 1, 3, 32, 32, 32) target_layer_name = 'backbone/slow_path/layer4/1/relu' _do_test_3D_models(recognizer, t...
class Depth(): def __init__(self, depth_to_copy=None, direction=1): self.depth_to_copy = depth_to_copy self.direction = direction self.gate_list = [] def add_gate(self, gate): self.gate_list.append(gate) def add_gate_list(self, gate_list): self.gate_list.extend(gate_l...
def test_get_decimal_symbol(): assert (numbers.get_decimal_symbol('en_US') == '.') assert (numbers.get_decimal_symbol('en_US', numbering_system='default') == '.') assert (numbers.get_decimal_symbol('en_US', numbering_system='latn') == '.') assert (numbers.get_decimal_symbol('sv_SE') == ',') assert (...
def adjust_learning_rate(p, optimizer, epoch): lr = p['optimizer_kwargs']['lr'] if (p['scheduler'] == 'step'): steps = np.sum((epoch > np.array(p['scheduler_kwargs']['lr_decay_epochs']))) if (steps > 0): lr = (lr * (p['scheduler_kwargs']['lr_decay_rate'] ** steps)) elif (p['sched...
def test_sort_by_keywords(): keywords = {'KEY1': 2, 'KEY2': 0, 'KEY3': 1} args = 'aaaa bbbb KEY2 KEY1 kkk10 kkk11 ccc ddd KEY3 kkk3 eee'.split() (flat, spec) = sort_by_keywords(keywords, args) assert (flat == ['aaaa', 'bbbb', 'ccc', 'ddd', 'eee']) assert (spec == {'KEY1': ['kkk10', 'kkk11'], 'KEY2':...
class Loss(object): __metaclass__ = ABCMeta def __call__(self, prediction_tensor, target_tensor, ignore_nan_targets=True, scope=None, **params): with tf.name_scope(scope, 'Loss', [prediction_tensor, target_tensor, params]) as scope: if ignore_nan_targets: target_tensor = tf.w...
def dropout_sparse(x, keep_prob, num_nonzero_elems): noise_shape = [num_nonzero_elems] random_tensor = keep_prob random_tensor += tf.random_uniform(noise_shape) dropout_mask = tf.cast(tf.floor(random_tensor), dtype=tf.bool) pre_out = tf.sparse_retain(x, dropout_mask) return (pre_out * (1.0 / kee...
((not torch.cuda.is_available()), 'test requires a GPU') class TestQuantization(unittest.TestCase): def setUp(self): logging.disable(logging.CRITICAL) def tearDown(self): logging.disable(logging.NOTSET) def test_quantization(self): with contextlib.redirect_stdout(StringIO()): ...
def test_background_plotting_add_callback(qtbot, monkeypatch, plotting): class CallBack(object): def __init__(self, sphere): self.sphere = weakref.ref(sphere) def __call__(self): self.sphere().points[:] = (self.sphere().points * 0.5) update_count = [0] orig_update_app...
def optimizer_kwargs_gf(parsed_args): return {'optim': parsed_args.optim, 'lr': parsed_args.lr_gf, 'weight_decay': parsed_args.weight_decay, 'momentum': parsed_args.momentum, 'sgd_dampening': parsed_args.sgd_dampening, 'sgd_nesterov': parsed_args.sgd_nesterov, 'rmsprop_alpha': parsed_args.rmsprop_alpha, 'adam_beta1...
class ResBlock(nn.Module): def __init__(self, num_channels, kernel_size=3, bias=True, bn=False, act=nn.ReLU(True), res_scale=1, **kwargs): super(ResBlock, self).__init__() m = [] for i in range(2): m.append(nn.Conv2d(num_channels, num_channels, kernel_size, stride=1, padding=1, b...
class VOCDataset(BaseDataSet): def __init__(self, **kwargs): self.num_classes = 21 self.palette = palette.get_voc_palette(self.num_classes) super(VOCDataset, self).__init__(**kwargs) def _set_files(self): self.root = os.path.join(self.root, 'VOCdevkit/VOC2012') self.image...
def get_norm(norm, out_channels, **kwargs): if isinstance(norm, str): if (len(norm) == 0): return None norm = {'BN': BatchNorm, 'syncBN': SyncBatchNorm, 'GhostBN': GhostBatchNorm, 'FrozenBN': FrozenBatchNorm, 'GN': (lambda channels, **args: nn.GroupNorm(32, channels))}[norm] return n...
def state_dict() -> Dict[(str, Any)]: state = base.state_dict() musiq_state: Dict[(str, Any)] = {} musiq_state['paused'] = storage.get('paused') musiq_state['shuffle'] = storage.get('shuffle') musiq_state['repeat'] = storage.get('repeat') musiq_state['autoplay'] = storage.get('autoplay') mus...
def convert_to_one_fraction_group(dicom_dataset, fraction_group_number): created_dicom = deepcopy(dicom_dataset) (beam_sequence, _) = get_fraction_group_beam_sequence_and_meterset(dicom_dataset, fraction_group_number) created_dicom.BeamSequence = beam_sequence fraction_group_index = get_fraction_group_i...
def generate_stub_for_py_module(mod: StubSource, target: str, *, parse_only: bool=False, inspect: bool=False, include_private: bool=False, export_less: bool=False, include_docstrings: bool=False, doc_dir: str='', all_modules: list[str]) -> None: if inspect: ngen = InspectionStubGenerator(module_name=mod.mod...
class Effect4490(BaseEffect): dealsDamage = True type = 'active' def handler(fit, mod, context, projectionRange, **kwargs): fit.ship.boostItemAttr('maxVelocity', mod.getModifiedItemAttr('speedFactor'), stackingPenalties=True, **kwargs) fit.ship.increaseItemAttr('warpScrambleStatus', mod.getM...
class AddressType(): def __init__(self): self.hot = {} hot_file = os.environ.get('PYUNIT_ADDRESS_HOT_FILE', None) if hot_file: with open(hot_file, encoding='utf-8') as fp: for line in fp.readlines(): (name, addr) = line.strip().split() ...
class TestIndex(): def test_sanity_check(self): mySymbolicMatricesList = TypedListType(TensorType(pytensor.config.floatX, shape=(None, None)))() myMatrix = matrix() z = Index()(mySymbolicMatricesList, myMatrix) f = pytensor.function([mySymbolicMatricesList, myMatrix], z) x = ...
class TestTreeItem(unittest.TestCase): def test_init(self): widget = gui.TreeItem('test tree item') widget.append(gui.TreeItem('2nd tree item')) self.assertIn('test tree item', widget.repr()) self.assertIn('2nd tree item', widget.repr()) assertValidHTML(widget.repr())
def smart_contract_filters_from_node_state(chain_state: ChainState, secret_registry_address: SecretRegistryAddress, service_registry: Optional[ServiceRegistry]) -> RaidenContractFilter: token_network_registries = chain_state.identifiers_to_tokennetworkregistries.values() token_networks = [tn for tnr in token_ne...
class BirthdayParty(QObject): Q_CLASSINFO('DefaultProperty', 'guests') partyStarted = pyqtSignal(QTime, arguments=['time']) def __init__(self, parent=None): super(BirthdayParty, self).__init__(parent) self._host = None self._guests = [] hostChanged = pyqtSignal() (Person, not...
def write_file(path: str, contents: str) -> None: encoded_contents = contents.encode('utf-8') try: with open(path, 'rb') as f: old_contents: (bytes | None) = f.read() except OSError: old_contents = None if (old_contents != encoded_contents): os.makedirs(os.path.dirnam...
def augment_and_mix_transform(config_str, hparams): magnitude = 3 width = 3 depth = (- 1) alpha = 1.0 blended = False config = config_str.split('-') assert (config[0] == 'augmix') config = config[1:] for c in config: cs = re.split('(\\d.*)', c) if (len(cs) < 2): ...
def begin_level(options): global level_stack, level_list, bgcolor if (not level_stack): level_list = [] default_level_color = None default_level_style = None default_level_fill = bgcolor else: default_level_color = level_stack[(- 1)].get('color', None) default...
_task('fasthubert_pretraining', dataclass=FastHubertPretrainingConfig) class HubertFbankPretrainingTask(HubertPretrainingTask): cfg: FastHubertPretrainingConfig def __init__(self, cfg: FastHubertPretrainingConfig) -> None: super().__init__(cfg) def setup_task(cls, cfg: FastHubertPretrainingConfig, *...
class WithFutureMinuteBarData(WithAssetFinder, WithTradingCalendars): FUTURE_MINUTE_BAR_LOOKBACK_DAYS = 0 FUTURE_MINUTE_BAR_START_DATE = alias('START_DATE') FUTURE_MINUTE_BAR_END_DATE = alias('END_DATE') def make_future_minute_bar_data(cls): trading_calendar = get_calendar('us_futures') ...
def clip_grad_norm_dp(named_parameters, target_params, max_norm, norm_type=2): parameters = list(filter((lambda p: (p[1] - target_params[p[0]])), named_parameters)) max_norm = float(max_norm) norm_type = float(norm_type) if (norm_type == float('inf')): total_norm = max((p.grad.data.abs().max() f...
class TestAdamWOptimizer(TestOptimizer, unittest.TestCase): def _check_momentum_buffer(self): return False def _get_config(self): return {'name': 'adamw', 'num_epochs': 90, 'lr': 0.1, 'betas': (0.9, 0.99), 'eps': 1e-08, 'weight_decay': 0.0001, 'amsgrad': False} def _instance_to_test(self): ...
class ComplexWebQuestions(datasets.GeneratorBasedBuilder): VERSION = datasets.Version('1.0.0') BUILDER_CONFIGS = [datasets.BuilderConfig(name='compwebq', version=VERSION, description='ComplexWebQuestions Dataset')] def __init__(self, *args, writer_batch_size=None, **kwargs): super().__init__(*args, ...
class WindowCreateFullScreenEventSequenceTest(EventSequenceTest, unittest.TestCase): last_sequence = 3 def on_resize(self, width, height): self.check_sequence(1, 'on_resize') def on_show(self): self.check_sequence(2, 'on_show') def on_expose(self): self.check_sequence(3, 'on_expo...
def main(): parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) if ((len(sys.argv) == 2) and sys.argv[1].endswith('.json')): (model_args, data_args, training_args) = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: (model_args, data_args,...
def model_fn_builder(bert_config, num_labels, init_checkpoint, learning_rate, num_train_steps, num_warmup_steps, use_tpu, use_one_hot_embeddings): def model_fn(features, labels, mode, params): tf.logging.info('*** Features ***') for name in sorted(features.keys()): tf.logging.info((' na...
def gable_process_box(bm, roof_faces, prop): top_faces = [f for f in roof_faces if f.normal.z] result = bmesh.ops.extrude_face_region(bm, geom=top_faces).get('geom') bmesh.ops.translate(bm, verts=filter_geom(result, BMVert), vec=(0, 0, prop.thickness)) bmesh.ops.delete(bm, geom=top_faces, context='FACES...
def _getsafeword(agearg): targetgmt = ops.system.clocks.gmtime() ageseconds = ops.timehelper.get_seconds_from_age(agearg) afterdatetime = (targetgmt - timedelta(seconds=ageseconds)) beforedatetime = (targetgmt + timedelta(seconds=0)) return (afterdatetime.strftime('%Y-%m-%d %H:%M:%S'), beforedatetim...
class Parser(object): _extensions = [] _shebangKeywords = [] _keywords = [] def getParserName(cls): name = cls.__name__ if (name.endswith('Parser') and (len(name) >= 6)): name = name[:(- 6)].lower() return name def disambiguate(cls, text): return cls.getPa...
class StaffAdvertiserReportView(BaseReportView): impression_model = AdvertiserImpression report = OptimizedAdvertiserReport template_name = 'adserver/reports/staff-advertisers.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) impressions = self.get_...
def test_one_accumulator_while_loop() -> None: number = 10 test_list = [10, 20, 30] sum_so_far = 0 with AccumulationTable(['number', 'sum_so_far']) as table: while (number in test_list): sum_so_far = (sum_so_far + number) number += 10 assert (table.loop_accumulators =...
class MCTCTFeatureExtractor(SequenceFeatureExtractor): model_input_names = ['input_features', 'attention_mask'] def __init__(self, feature_size=80, sampling_rate=16000, padding_value=0.0, hop_length=10, win_length=25, win_function='hamming_window', frame_signal_scale=32768.0, preemphasis_coeff=0.97, mel_floor=1...
class AsmCmdBase(with_metaclass(AsmCmdManager, object)): _id = (- 1) _active = None _toolbarName = 'Assembly3' _menuGroupName = '' _contextMenuName = 'Assembly' _accel = None _cmdType = None _iconName = None def checkActive(cls): cls._active = True def getIconName(cls): ...
def get_possible_variants(typ: Type) -> list[Type]: typ = get_proper_type(typ) if isinstance(typ, TypeVarType): if (len(typ.values) > 0): return typ.values else: return [typ.upper_bound] elif isinstance(typ, ParamSpecType): return [typ.upper_bound] elif is...
def test_export_compound_crs(): crs = CRS('urn:ogc:def:crs,crs:EPSG::2393,crs:EPSG::5717') expected_cf = {'semi_major_axis': 6378388.0, 'semi_minor_axis': crs.ellipsoid.semi_minor_metre, 'inverse_flattening': 297.0, 'reference_ellipsoid_name': 'International 1924', 'longitude_of_prime_meridian': 0.0, 'prime_mer...
class Baseline(object): def wrap_dataset(self, dataset): return dataset def unwrap_batch(self, batch): return (batch, None) def eval(self, x, c): raise NotImplementedError('Override this method') def get_learnable_parameters(self): return [] def epoch_callback(self, m...
class RestoreFormerModel(pl.LightningModule): def __init__(self, ddconfig, lossconfig, ckpt_path=None, ignore_keys=[], image_key='lq', colorize_nlabels=None, monitor=None, special_params_lr_scale=1.0, comp_params_lr_scale=1.0, schedule_step=[80000, 200000]): super().__init__() self.image_key = image...
def test_color_yes_collection_on_non_atty(pytester, request) -> None: tr = request.config.pluginmanager.getplugin('terminalreporter') if (not hasattr(tr, 'isatty')): pytest.skip('only valid for newer pytest versions') pytester.makepyfile("\n import pytest\n .parametrize('i', range(10))...
def create_cancel_build_in_queue(build_phase, build_queue_id, build_queue): def cancel_build(): cancelled = False if (build_queue_id is not None): cancelled = build_queue.cancel(build_queue_id) if (build_phase != BUILD_PHASE.WAITING): return False return cance...
class Solution(): def dig_sum(self, n): total = 0 while (n > 0): rem = (n % 10) total += rem n = (n // 10) return total def countLargestGroup(self, n: int) -> int: from collections import Counter d = dict() for i in range(1, (n ...
class ScopeTimer(): def __init__(self, name): self.name = name def __enter__(self): self.start = time.time() return self def __exit__(self, *args): self.end = time.time() self.interval = (self.end - self.start) print('{} {:.3E}'.format(self.name, self.interval...
.script def _multilabel_recall_at_fixed_precision_compute(input: torch.Tensor, target: torch.Tensor, num_labels: int, min_precision: float) -> Tuple[(List[torch.Tensor], List[torch.Tensor])]: (precision, recall, thresholds) = _multilabel_precision_recall_curve_compute(input, target, num_labels) (max_recall, bes...
class WebRTCManager(Runnable): def __init__(self, node_address: Address, process_messages: Callable[([List[ReceivedRaidenMessage]], None)], signaling_send: Callable[([Address, str], None)], stop_event: GEvent) -> None: super().__init__() self.node_address = node_address self._process_message...
class Solution(object): def backspaceCompare(self, S, T): if (S == T): return True s_stack = [] t_stack = [] for c in S: if (c != '#'): s_stack.append(c) elif (len(s_stack) != 0): s_stack.pop((- 1)) for c in ...
def print_timer(rb_node, idx): timerqueue = utils.container_of(rb_node, timerqueue_node_type.pointer(), 'node') timer = utils.container_of(timerqueue, hrtimer_type.pointer(), 'node') function = str(timer['function']).split(' ')[1].strip('<>') softexpires = timer['_softexpires'] expires = timer['node...
class _BlockInfo(object): def __init__(self, seen_open_brace): self.seen_open_brace = seen_open_brace self.open_parentheses = 0 self.inline_asm = _NO_ASM def CheckBegin(self, filename, clean_lines, linenum, error): pass def CheckEnd(self, filename, clean_lines, linenum, error...
class TestMongoDBCollectorWithReplica(CollectorTestCase): def setUp(self): config = get_collector_config('MongoDBCollector', {'host': 'localhost:27017', 'databases': '^db', 'replica': True}) self.collector = MongoDBCollector(config, None) self.connection = MagicMock() def test_import(sel...
def _run(main_wrapper: Callable[([TextIO, TextIO], None)]) -> tuple[(str, str, int)]: stdout = StringIO() stderr = StringIO() try: main_wrapper(stdout, stderr) exit_status = 0 except SystemExit as system_exit: assert isinstance(system_exit.code, int) exit_status = system_...
def get_app_from_path(request_path, base, index, reload=False): path = valid_and_norm_path(base, request_path) if (path is None): return ('error', 403) if os.path.isdir(path): if (not request_path.endswith('/')): return ('error', 404) if os.path.isfile(os.path.join(path, ...
class Generator(nn.Module): def __init__(self, G_ch=64, dim_z=128, bottom_width=4, resolution=128, G_kernel_size=3, G_attn='64', n_classes=1000, num_G_SVs=1, num_G_SV_itrs=1, G_shared=True, shared_dim=0, hier=False, cross_replica=False, mybn=False, G_activation=nn.ReLU(inplace=False), G_lr=5e-05, G_B1=0.0, G_B2=0.9...
class PooledEmbeddingsAllToAllTest(MultiProcessTestBase): def _run_test_dist(cls, rank: int, world_size: int, _input: torch.Tensor, output: torch.Tensor, backend: str, dim_sum_per_rank: List[int], batch_size_per_rank: List[int], qcomms_config: Optional[QCommsConfig]=None) -> None: dist.init_process_group(ra...
def group_norm(out_channels, affine=True, divisor=1): out_channels = (out_channels // divisor) dim_per_gp = (config.MODEL.GROUP_NORM.DIM_PER_GP // divisor) num_groups = (config.MODEL.GROUP_NORM.NUM_GROUPS // divisor) eps = config.MODEL.GROUP_NORM.EPSILON return torch.nn.GroupNorm(get_group_gn(out_ch...
.parametrize('recap_type, expected_proto_type', [(NullType(name='some_field'), 'google.protobuf.NullValue'), (BoolType(name='some_field'), 'bool'), (IntType(signed=True, bits=32, name='some_field'), 'int32'), (IntType(signed=True, bits=64, name='some_field'), 'int64'), (IntType(signed=False, bits=32, name='some_field')...
def _msg_sendv(ql: Qiling, coid, smsg, sparts, rmsg, rparts, *args, **kw): assert (coid in ql.os.connections), 'Connection Id must exist in connections mapping' conn = ql.os.connections[coid] if ((conn.pid == SYSMGR_PID) and (conn.chid == SYSMGR_CHID)): sbody = get_message_body(ql, smsg, sparts) ...
def test_mult_multiplication() -> None: assert (parse('(a{2,3}){1,1}').reduce() == parse('a{2,3}').reduce()) assert (parse('(a{2,3}){1}').reduce() == parse('a{2,3}').reduce()) assert (parse('(a{2,3})').reduce() == parse('a{2,3}').reduce()) assert (parse('(a{2,3}){4,5}').reduce() == parse('a{8,15}').redu...
def xdg_get_system_data_dirs(): ' if (os.name == 'nt'): from gi.repository import GLib dirs = [] for dir_ in GLib.get_system_data_dirs(): dirs.append(dir_) return dirs data_dirs = os.getenv('XDG_DATA_DIRS') if data_dirs: return [os.path.abspath(d) for ...
class LossValley(SWADBase): def __init__(self, n_converge, n_tolerance, tolerance_ratio): self.n_converge = n_converge self.n_tolerance = n_tolerance self.tolerance_ratio = tolerance_ratio self.converge_Q = deque(maxlen=n_converge) self.smooth_Q = deque(maxlen=n_tolerance) ...
class Effect6076(BaseEffect): type = 'passive' def handler(fit, module, context, projectionRange, **kwargs): fit.modules.filteredChargeMultiply((lambda mod: mod.charge.requiresSkill('Missile Launcher Operation')), 'maxVelocity', (1 / module.getModifiedItemAttr('modeMaxRangePostDiv')), stackingPenalties=...
def print_array_diagnostics(array, indices, comparator=(lambda a, b: (a < b))): ordered_array = reindex_array(array, indices) info = [('Original array', array), ('Ordered array', ordered_array), ('Is sorted?', is_sorted(array, indices, comparator)), ('Sort score', sort_score(array, indices, comparator)), ('Has ...
def get_test_dependencies(test_fname): with open(os.path.join(PATH_TO_TRANFORMERS, test_fname), 'r', encoding='utf-8') as f: content = f.read() relative_imports = re.findall('from\\s+(\\.\\S+)\\s+import\\s+([^\\n]+)\\n', content) relative_imports = [test for (test, imp) in relative_imports if ('# te...
def shape_text_hb(text, font_filename, direction=None): ref_size = REF_GLYPH_SIZE buf = uharfbuzz.Buffer() buf.add_str(text) buf.guess_segment_properties() is_horizontal = True if (direction is not None): buf.direction = direction is_horizontal = (direction in ('ltr', 'rtl')) ...
class BILSTMONLY(object): def __init__(self, params: dict): self.char_embedding = tf.Variable(np.load(params['embedding_path']), dtype=tf.float32, name='input_char_embedding') self.word_embedding = tf.Variable(np.load(params['word_embedding_path']), dtype=tf.float32, name='input_word_embedding') ...
class LazyString(object): def __init__(self, func, *args, **kwargs): self._func = func self._args = args self._kwargs = kwargs def __getattr__(self, attr): if (attr == '__setstate__'): raise AttributeError(attr) string = str(self) if hasattr(string, at...