code
stringlengths
281
23.7M
def rating_tamplate(pattern_identifier, context=None): return InlineKeyboardMarkup([[InlineButton(get_text('bad', context), callback_data=(pattern_identifier + str(BAD_RATING)))], [InlineButton(get_text('regular', context), callback_data=(pattern_identifier + str(REGULAR_RATING)))], [InlineButton(get_text('good', c...
def main(): print('initializing arduino') config = {'host': 'localhost', 'hat': {'arduino': {'device': '/dev/spidev0.1', 'resetpin': '26'}}, 'actions': {}, 'arduino.nmea.baud': 4800, 'arduino.nmea.in': False, 'arduino.nmea.out': False, 'arduino.ir': True, 'arduino.debug': True, 'arduino.adc_channels': []} a...
class UnexpectedPasswordHashVersion(InvalidPassword, WalletFileException): def __init__(self, version): self.version = version def __str__(self): return '{unexpected}: {version}\n{instruction}'.format(unexpected=_('Unexpected password hash version'), version=self.version, instruction=_('You are ...
def test_environment_only(hatch, helpers, temp_dir, config_file): config_file.model.template.plugins['default']['tests'] = False config_file.save() project_name = 'My.App' with temp_dir.as_cwd(): result = hatch('new', project_name) assert (result.exit_code == 0), result.output project_pa...
def _send_button_click_event(widget, **kwargs): assert widget.get_realized() assert widget.get_visible() ev = Gdk.Event() window = widget.get_window() ev.any.window = window ev.button.x = (window.get_width() / 2.0) ev.button.y = (window.get_height() / 2.0) for (key, value) in kwargs.item...
def FlagsForFile(filename, **kwargs): if database: compilation_info = GetCompilationInfoForFile(filename) if (not compilation_info): return None final_flags = MakeRelativePathsInFlagsAbsolute(compilation_info.compiler_flags_, compilation_info.compiler_working_dir_) else: ...
class MyTree(Tree): def set_index(self, ind=0): if (len(self.leaves()) == 1): self._i = (ind, (ind + 1)) if isinstance(self[0], MyTree): self[0].set_index(ind) return (ind + 1) else: self._i = (ind, (ind + 1)) for l in self: ...
class ASPP(nn.Module): def __init__(self, in_channels, out_channels, atrous_rates, separable=False): super(ASPP, self).__init__() modules = [] modules.append(nn.Sequential(nn.Conv2d(in_channels, out_channels, 1, bias=False), nn.BatchNorm2d(out_channels), nn.ReLU())) (rate1, rate2, ra...
class RemoteReceiveEvent(ModbusEvent): def __init__(self, **kwargs): self.overrun = kwargs.get('overrun', False) self.listen = kwargs.get('listen', False) self.broadcast = kwargs.get('broadcast', False) def encode(self) -> bytes: bits = ([False] * 3) bits += [self.overrun...
_train('PCQM4Mv2-inference') def ogblsc_inference(loggers, loaders, model, optimizer=None, scheduler=None): from ogb.lsc import PCQM4Mv2Evaluator evaluator = PCQM4Mv2Evaluator() num_splits = 3 split_names = ['valid', 'test-dev', 'test-challenge'] assert (len(loaders) == num_splits), 'Expecting 3 par...
def get_class(module, superclass=None): classes = get_classes(module, superclass) if (len(classes) == 1): return classes[0] desc = (('subclasses of %s' % superclass.__name__) if superclass else 'new-style classes') if (len(classes) > 1): names = ', '.join([cls.__name__ for cls in classes...
def docker_start(image, volumes={}, env_variables={}): client = docker.from_env() dvolumes = {host: {'bind': ctr, 'mode': 'rw'} for (ctr, host) in volumes.items()} logger.info('Starting container with image %r', image) con = client.containers.run(image, ['sleep', '10000'], detach=True, volumes=dvolumes,...
def test_order_dependencies_no_auto_mark(no_dep_marks): no_dep_marks.makefile('.ini', pytest='\n [pytest]\n automark_dependency = 0\n console_output_style = classic\n ') result = no_dep_marks.runpytest('-v', '--order-dependencies') result.assert_outcomes(passed=2,...
def parse(tokens): key = tokens.pop(0)[1:] parsed = {key: {}} while tokens: token = tokens.pop(0) if token.endswith(')'): if token[:(- 1)]: val = token[:(- 1)].strip('"') if (val.startswith('#') and val.endswith('#')): val = int...
class FractionalCloudCover(metaclass=_EnumMeta): zeroOktas = _OscEnum('FractionalCloudCover', 'zeroOktas', min_minor_version=2) oneOktas = _OscEnum('FractionalCloudCover', 'oneOktas', min_minor_version=2) twoOktas = _OscEnum('FractionalCloudCover', 'twoOktas', min_minor_version=2) threeOktas = _OscEnum(...
class TTCON(TestCase): def _g(self, s): return TCON(text=s).genres def test_empty(self): self.assertEquals(self._g(''), []) def test_num(self): for i in range(len(GENRES)): self.assertEquals(self._g(('%02d' % i)), [GENRES[i]]) def test_parened_num(self): for i...
def get_normalized_dependency(requirement: Requirement) -> str: from packaging.specifiers import SpecifierSet requirement.name = normalize_project_name(requirement.name) if requirement.specifier: requirement.specifier = SpecifierSet(str(requirement.specifier).lower()) if requirement.extras: ...
class BatchNorm(nn.BatchNorm2d): def __init__(self, num_features, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True, use_tracked_mean=True, use_tracked_var=True): nn.BatchNorm2d.__init__(self, num_features=num_features, eps=eps, momentum=momentum, affine=affine, track_running_stats=track_runnin...
class CustomRandomCrop(RandomCrop): def forward(self, img): (width, height) = F.get_image_size(img) (tar_h, tar_w) = self.size tar_h = min(tar_h, height) tar_w = min(tar_w, width) (i, j, h, w) = self.get_params(img, (tar_h, tar_w)) return F.crop(img, i, j, h, w)
class FinTSMessage(SegmentSequence): DIRECTION = None def __init__(self, dialog=None, *args, **kwargs): self.dialog = dialog self.next_segment_number = 1 super().__init__(*args, **kwargs) def __iadd__(self, segment: FinTS3Segment): if (not isinstance(segment, FinTS3Segment)):...
class Embedding(Layer): _embedding_support def __init__(self, input_dim, output_dim, embeddings_initializer='uniform', embeddings_regularizer=None, activity_regularizer=None, embeddings_constraint=None, mask_zero=False, input_length=None, **kwargs): if ('input_shape' not in kwargs): if input...
class TestAllForkSeq(uvm_sequence): async def body(self): seqr = ConfigDB().get(None, '', 'SEQR') random = RandomSeq('random') max = MaxSeq('max') random_task = cocotb.start_soon(random.start(seqr)) max_task = cocotb.start_soon(max.start(seqr)) (await Combine(Join(ran...
class Expanding(Window): def aggregate(self, agg): window = self.n diff = aggregations.diff_expanding return self.root.accumulate_partitions(aggregations.window_accumulator, diff=diff, window=window, agg=agg, start=self.start, returns_state=True, stream_type='updating', with_state=self.with_...
def multithread_compute_vali(): global vali_sum, vali_cnt vali_sum = [0.0, 0.0, 0.0] vali_cnt = 0 threads = [] for ii in xrange(cmd_args.num_thread): thread = threading.Thread(target=vali_eval, args=(1, ii)) thread.start() threads.append(thread) for thread in threads: ...
def _preprocess(data): for field in ['date', 'start', 'end']: date = data.get(field) if ((field == 'end') and (date == UNSET_INDICATOR)): continue if (date is not None): try: date = time.strftime(POCKET_DATE_FORMAT, du_parser.parse(date, yearfirst=True...
def set_question_optionset(apps, schema_editor): Question = apps.get_model('questions', 'Question') for question in Question.objects.all(): try: for optionset in question.attribute_entity.attribute.optionsets.all(): question.optionsets.add(optionset) except AttributeE...
def make_batches(lines, args, task, max_positions, encode_fn): def encode_fn_target(x): return encode_fn(x) if args.constraints: batch_constraints = [list() for _ in lines] for (i, line) in enumerate(lines): if ('\t' in line): (lines[i], *batch_constraints[i])...
class SeriesParser(Parser): _default_orient = 'index' _split_keys = ('name', 'index', 'data') def _parse_no_numpy(self): json = self.json orient = self.orient if (orient == 'split'): decoded = dict(((str(k), v) for (k, v) in compat.iteritems(loads(json, precise_float=self...
def test_arguments_default_value(): node = extract_node("def fruit(eat='please', *, peel='no', trim='yes', **kwargs): ...") assert (node.args.default_value('eat').value == 'please') node = extract_node("def fruit(seeds, flavor='good', *, peel='maybe'): ...") assert (node.args.default_value('flavor').val...
def binary_search2(fre, cand, level): (low, high) = (0, (len(fre) - 1)) if (low > high): return (- 1) while (low <= high): mid = int(((low + high) / 2)) if (cand == fre[mid][0:(level - 1)]): (slow, shigh) = (low, mid) if (cand == fre[low][0:(level - 1)]): ...
def call_with_extended_paramz(f, args, keys, vals, env, cont): from pycket.values import parameterization_key paramz = cont.get_mark_first(parameterization_key) assert isinstance(paramz, values_parameter.W_Parameterization) return paramz.extend(keys, vals, env, call_with_paramz_cont(f, args, env, cont))
class TestGridEngineCollector(CollectorTestCase): def setUp(self): config = get_collector_config('GridEngineCollector', {}) self.collector = GridEngineCollector(config, None) self.fixtures_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), 'fixtures')) def test_import(self): ...
def rtn_write(se: 'SymbolicExecutor', pstate: 'ProcessState'): logger.debug('write hooked') fd = pstate.get_argument_value(0) buf = pstate.get_argument_value(1) size = pstate.get_argument_value(2) data = pstate.memory.read(buf, size) if pstate.file_descriptor_exists(fd): fdesc = pstate.g...
() ('--filename', default='samples/sample_wind_poitiers.csv', help='Input filename') ('--filename_out', default='windrose.pdf', help='Output filename') ('--dpi', default=DPI_DEFAULT, help='Dot per inch for plot generation') ('--figsize', default=S_FIGSIZE_DEFAULT, help=('Figure size x,y - default=%s' % S_FIGSIZE_DEFAUL...
class BasicBlock(nn.Module): def __init__(self, in_channels, out_channels, expansion=1, stride=1, dilation=1, downsample=None, style='pytorch', with_cp=False, conv_cfg=None, norm_cfg=dict(type='BN')): norm_cfg = copy.deepcopy(norm_cfg) super().__init__() self.in_channels = in_channels ...
class ElectrodeSOHSolver(): def __init__(self, parameter_values, param=None, known_value='cyclable lithium capacity', options=None): self.parameter_values = parameter_values self.param = (param or pybamm.LithiumIonParameters(options)) self.known_value = known_value self.options = (op...
def test_arguments_marker(testdir): file_test = testdir.makepyfile("\n import pytest\n pytestmark = pytest.mark.firefox_arguments('baz')\n .nondestructive\n .firefox_arguments('foo', 'bar')\n def test_arguments(firefox_options):\n actual = sorted(firefox_options.argumen...
class PrologLexer(RegexLexer): name = 'Prolog' aliases = ['prolog'] filenames = ['*.ecl', '*.prolog', '*.pro', '*.pl'] mimetypes = ['text/x-prolog'] url = ' version_added = '' tokens = {'root': [('/\\*', Comment.Multiline, 'nested-comment'), ('%.*', Comment.Single), ("0\\'.", String.Char), (...
def _verify_patchelf() -> None: if (not which('patchelf')): raise ValueError('Cannot find required utility `patchelf` in PATH') try: version = check_output(['patchelf', '--version']).decode('utf-8') except CalledProcessError: raise ValueError('Could not call `patchelf` binary') m...
def _parse_set_implicit_union(source, info): items = [_parse_set_member(source, info)] while True: here = source.pos if (source.match(u']') or source.match(u'&&')): source.pos = here break items.append(_parse_set_member(source, info)) if ((len(items) == 1) and...
def get_data_loaders(cfg, transforms_3d, transforms_2d, transforms_val, transforms_img, rank, world_size, verbose=True): def get_2d_datasets(dataset_names): datasets = [] for dataset_name in dataset_names: db = VideoDataset(dataset_name=dataset_name, set='train', transforms=transforms_2d...
def calc_confusion_mat(predictions, data): exact = 0 one_of = 0 errs = [] err_mat = [] preds_mat = [] one_errs = 0 for (ind, (example, prediction)) in enumerate(zip(data, predictions)): example = json.loads(example) tokens = example['tokens'] y_hat = prediction['y_hat...
def construct_script(items: Sequence[Union[(str, int, bytes, opcodes)]]) -> str: script = '' for item in items: if isinstance(item, opcodes): script += item.hex() elif (type(item) is int): script += add_number_to_script(item).hex() elif isinstance(item, (bytes, by...
def test_slots_unpickle_after_attr_added(frozen): a = A(1, 2, 3) a_pickled = pickle.dumps(a) a_unpickled = pickle.loads(a_pickled) assert (a_unpickled == a) (slots=True, frozen=frozen) class NEW_A(): x = attr.ib() b = attr.ib() d = attr.ib() c = attr.ib() with...
_end_docstrings(CUSTOM_DPR_READER_DOCSTRING) class DPRReaderTokenizerFast(CustomDPRReaderTokenizerMixin, BertTokenizerFast): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = READER_PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES pretrain...
def parse_args(): parser = argparse.ArgumentParser(description='MMAction2 test (and eval) a model') parser.add_argument('config', help='test config file path') parser.add_argument('checkpoint', help='checkpoint file') parser.add_argument('--out', default=None, help='output result file in pickle format')...
def build_radare2(): if (not radare2_exists()): raise RuntimeError('Fail to detect radare2 repository. Do you forget to init submodules?') if (not meson_exists()): raise RuntimeError('Fail to detect meson. Do you forget to install meson?') os.chdir(RADARE2_DIR) DEBUG = os.getenv('DEBUG',...
class TestICDAR2015GWD(TestICDAR2015): def eval(self): txt_name = '{}.txt'.format(self.cfgs.VERSION) real_test_img_list = self.get_test_image() gwd = build_whole_network.DetectionNetworkGWD(cfgs=self.cfgs, is_training=False) self.test_icdar2015(det_net=gwd, real_test_img_list=real_te...
def check_dummies(overwrite=False): dummy_files = create_dummy_files() short_names = {'torch': 'pt'} path = os.path.join(PATH_TO_TRANSFORMERS, 'utils') dummy_file_paths = {backend: os.path.join(path, f'dummy_{short_names.get(backend, backend)}_objects.py') for backend in dummy_files.keys()} actual_d...
class BlenderbotSmallOnnxConfig(OnnxSeq2SeqConfigWithPast): def inputs(self) -> Mapping[(str, Mapping[(int, str)])]: if (self.task in ['default', 'seq2seq-lm']): common_inputs = OrderedDict([('input_ids', {0: 'batch', 1: 'encoder_sequence'}), ('attention_mask', {0: 'batch', 1: 'encoder_sequence'...
class Episode(): def __init__(self, info, max_len=30): self.info = info self.maxlen = max_len def render(self, exp_name=None): goal_names = [obj['class_name'] for obj in self.info['target'][1][0]] episode_info = 'Episode {}.'.format(self.info['episode']) episode_info2 = '...
def get_quotedrpath(rp, separate_basename=0): if separate_basename: assert (not rp.index), "Trying to start quoting '{rp}' in the middle.".format(rp=rp) (dirname, basename) = rp.dirsplit() return QuotedRPath(rp.conn, dirname, (unquote(basename),), rp.data) else: return QuotedRPat...
def main(client, config): (ss_ddf, ws_ddf, datedim_ddf) = benchmark(read_tables, config=config, compute_result=config['get_read_time']) datedim_ddf = datedim_ddf.map_partitions(convert_datestring_to_days) min_date = np.datetime64(q25_date, 'D').astype(int) valid_dates_ddf = datedim_ddf[(datedim_ddf['d_d...
class VoltageChannel(Channel): voltage_setpoint = Channel.control('VOLT? ({ch})', 'VOLT %g, ({ch})', 'Control the output voltage of this channel, range depends on channel.', validator=strict_range, values=[0, 25], dynamic=True) current_limit = Channel.control('CURR? ({ch})', 'CURR %g, ({ch})', 'Control the curr...
def format_callable_args(arg_types: list[Type], arg_kinds: list[ArgKind], arg_names: list[(str | None)], format: Callable[([Type], str)], verbosity: int) -> str: arg_strings = [] for (arg_name, arg_type, arg_kind) in zip(arg_names, arg_types, arg_kinds): if (((arg_kind == ARG_POS) and (arg_name is None)...
def mute_no_singing_parts(mono_output_path, mute_output_path): print(f'{ULTRASINGER_HEAD} Mute audio parts with no singing') silence_sections = get_silence_sections(mono_output_path) (y, sr) = librosa.load(mono_output_path, sr=None) for i in silence_sections: start_time = i[0] end_time =...
def load_model_and_checkpoint_files(folder, folds=None, mixed_precision=None, checkpoint_name='model_best'): if isinstance(folds, str): folds = [join(folder, 'all')] assert isdir(folds[0]), ('no output folder for fold %s found' % folds) elif isinstance(folds, (list, tuple)): if ((len(fol...
def _all_files(root: Union[(str, Path)], filter_function: Optional[Callable[([str], bool)]]=None) -> Set[str]: all_files = set() for (dirpath, _, filenames) in os.walk(root): for filename in filenames: if ((filter_function is not None) and (not filter_function(filename))): co...
def fuse_qkv(model, args): def fuse3(qq, qk, qv): for mod in [qq, qk, qv]: if (not hasattr(mod, '_amax')): print(' WARNING: NO AMAX BUFFER') return q = qq._amax.detach().item() k = qk._amax.detach().item() v = qv._amax.detach().ite...
class Karaoke(GStreamerPlugin): PLUGIN_ID = _PLUGIN_ID PLUGIN_NAME = _('Karaoke') PLUGIN_DESC = _('Removes main vocals from audio.') PLUGIN_ICON = Icons.AUDIO_INPUT_MICROPHONE def setup_element(cls): return Gst.ElementFactory.make('audiokaraoke', cls.PLUGIN_ID) def update_element(cls, el...
_torch _vision class GLPNFeatureExtractionTest(FeatureExtractionSavingTestMixin, unittest.TestCase): feature_extraction_class = (GLPNFeatureExtractor if is_vision_available() else None) def setUp(self): self.feature_extract_tester = GLPNFeatureExtractionTester(self) def feat_extract_dict(self): ...
class CpmBlock(nn.Module): def __init__(self, in_channels, channels=(128, 128, 128), kernels=(11, 11, 11), norm_cfg=None): super().__init__() assert (len(channels) == len(kernels)) layers = [] for i in range(len(channels)): if (i == 0): input_channels = in...
.patch('bot.exts.info.information.constants') class UserCommandTests(unittest.IsolatedAsyncioTestCase): def setUp(self): self.bot = helpers.MockBot() self.cog = information.Information(self.bot) self.moderator_role = helpers.MockRole(name='Moderators', id=2, position=10) self.flautis...
def freeze_model_weights(model): print('=> Freezing model weights') for (n, m) in model.named_modules(): if (hasattr(m, 'weight') and (m.weight is not None)): print(f'==> No gradient to {n}.weight') m.weight.requires_grad = False if (m.weight.grad is not None): ...
def generate_inference_command(dataset_name_or_id: Union[(int, str)], configuration_name: str, plans_identifier: str='nnUNetPlans', trainer_name: str='nnUNetTrainer', folds: Union[(List[int], Tuple[(int, ...)])]=(0, 1, 2, 3, 4), folder_with_segs_from_prev_stage: str=None, input_folder: str='INPUT_FOLDER', output_folder...
def test_get_username_keyring_runtime_error_logged(entered_username, monkeypatch, config, caplog): class FailKeyring(): def get_credential(system, username): raise RuntimeError('fail!') monkeypatch.setattr(auth, 'keyring', FailKeyring) assert (auth.Resolver(config, auth.CredentialInput()...
class CocoaAlternateEventLoop(EventLoop): def run(self, interval=(1 / 60)): if (not interval): self.clock.schedule(self._redraw_windows) else: self.clock.schedule_interval(self._redraw_windows, interval) self.has_exit = False from pyglet.window import Window ...
def _prepare_onnx_paddings(g, dim, pad): pad_len = torch.onnx.symbolic_opset9.size(g, pad, g.op('Constant', value_t=torch.tensor([0]))) extension = g.op('Sub', g.op('Mul', g.op('Constant', value_t=torch.tensor(dim, dtype=torch.int64)), g.op('Constant', value_t=torch.tensor(2, dtype=torch.int64))), pad_len) ...
def test_logout(flask_app, mocker: MockerFixture): mock_leave_all_rooms = mocker.patch('randovania.server.multiplayer.session_common.leave_all_rooms', autospec=True) session = {'user-id': 1234, 'discord-access-token': 'access_token'} sa = MagicMock() sa.session.return_value.__enter__.return_value = sess...
class Feed(list): def __init__(self, uri): self.name = _('Unknown') self.uri = uri self.changed = False self.website = '' self.__lastgot = 0 def get_age(self): return (time.time() - self.__lastgot) def __fill_af(feed, af): try: af['title'] ...
class MTL_Masker(): def __init__(self, sess, mask_dic, masks_dir, pruning_param_names, save_checkpoints_dir): self.masks = masks_dir self.weights = [] self._sess = sess self._log = Logger(__name__) self.pruning_names = set(pruning_param_names) self.backup_values = [] ...
class TestEmptyList(unittest.TestCase): def test_empty_data(self): data = list() schema = 'list' r = validator.validate(data, schema) self.assertTrue(r) schema = list() r = validator.validate(data, schema) self.assertTrue(r) schema = ['int'] r ...
class BotogramRunner(): def __init__(self, *bots, workers=2): self._bots = {bot._bot_id: bot.freeze() for bot in bots} self._updater_processes = {} self._worker_processes = [] self._ipc_process = None self.ipc = None self.running = False self._stop = False ...
def parse_markers(x: ((dict[(str, str)] | list[str]) | tuple[(str, ...)])) -> dict[(str, str)]: if isinstance(x, (list, tuple)): mapping = {name.strip(): '' for name in x} elif isinstance(x, dict): mapping = {name.strip(): description.strip() for (name, description) in x.items()} else: ...
def get_fingerprint(mol, hparams): length = hparams['fingerprint_length'] radius = hparams['fingerprint_radius'] if isinstance(mol, str): mol = Chem.MolFromSmiles(mol) if (mol is None): return np.zeros((length,)) fingerprint = AllChem.GetMorganFingerprintAsBitVect(mol, radius, length...
def balance_classes(dataset, num_classes=2): (inputs, targets) = dataset[:] num_train = inputs.size(0) (balanced_inputs, balanced_targets) = ([], []) for class_idx in range(num_classes): num_class_examples = (num_train // num_classes) mask = (targets == class_idx) (masked_inputs,...
def set_articulation_state(articulation: sapien.Articulation, state: np.ndarray): articulation.set_root_pose(Pose(state[0:3], state[3:7])) articulation.set_root_velocity(state[7:10]) articulation.set_root_angular_velocity(state[10:13]) (qpos, qvel) = np.split(state[13:], 2) articulation.set_qpos(qpo...
.parametrize('search, documents, k', [pytest.param((ranker_a | ranker_b), documents(), k, id=f'Union rankers: {ranker_a.__class__.__name__} | {ranker_b.__class__.__name__} k: {k}') for k in [None, 3, 4] for ranker_b in cherche_rankers(key='id', on='article') for ranker_a in cherche_rankers(key='id', on='title')]) def t...
def _ssim_3D(img1, img2, window, window_size, channel, size_average=True): mu1 = F.conv3d(img1, window, padding=(window_size // 2), groups=channel) mu2 = F.conv3d(img2, window, padding=(window_size // 2), groups=channel) mu1_sq = mu1.pow(2) mu2_sq = mu2.pow(2) mu1_mu2 = (mu1 * mu2) sigma1_sq = (...
def optimise_grid_point(geometry_optimiser: GeometryOptimiser, molecule: 'Ligand', qc_spec: 'QCOptions', local_options: 'LocalResource', coordinates: List[float], dihedral: Tuple[(int, int, int, int)], dihedral_angle: int, job_id: int) -> GridPointResult: with folder_setup(folder_name=f'grid_point_{dihedral_angle}_...
_dtype_float_test(only64=True, include_complex=True, additional_kwargs={'bias_is_tensor': [True, False]}) def test_rootfinder_with_params(dtype, device, bias_is_tensor): torch.manual_seed(100) random.seed(100) nr = 2 nbatch = 2 fwd_options = {'method': 'broyden1', 'f_tol': 1e-09, 'alpha': (- 0.5)} ...
def create_branch(version): repo = Repo.init('.') if repo.is_dirty(untracked_files=True): raise RuntimeError('Repository is dirty, please commit/stash your changes.') branch_name = f'release-{version}' print(f'{Fore.CYAN}Create {branch_name} branch from upstream main') upstream = get_upstrea...
.parametrize('golden', COFFEE_SLASH_GOLDEN) def test_coffee_slashes(lexer, golden): (input_str, slashes_are_regex_here) = golden output = list(lexer.get_tokens(input_str)) print(output) for (t, s) in output: if ('/' in s): is_regex = (t is Token.String.Regex) assert (is_r...
def format_data(value='', datatypes=int, nullable=True, pre_format_function=None, format_function=to_int, post_format_function=None, **kwargs) -> Any: if pre_format_function: value = pre_format_function(value) if (nullable and is_none_like(value)): value = None else: try: ...
def _zip_pseudo_fifty_mbytes(file_buffer_list: list, zip_bytes_io: io.BytesIO): bad_data = False file_count = 0 keywords = pseudonymisation_api.get_default_pseudonymisation_keywords() keywords.remove('PatientSex') strategy = pseudonymisation_api.pseudonymisation_dispatch zip_stream = zip_bytes_i...
def masks_to_bboxes(masks): masks = np.asarray(masks) assert (masks.dtype == bool) ndim = masks.ndim assert (ndim in [2, 3]), 'masks must be 2 or 3 dimensional' if (ndim == 2): masks = masks[None] bboxes = np.zeros((len(masks), 4), dtype=np.float64) for (i, mask) in enumerate(masks):...
class _packbits(Function): _fwd(cast_inputs=torch.float32) def forward(ctx, grid, thresh, bitfield=None): if (not grid.is_cuda): grid = grid.cuda() grid = grid.contiguous() C = grid.shape[0] H3 = grid.shape[1] N = ((C * H3) // 8) if (bitfield is None):...
_benchmark.command(name='collect') _option ('--force', '-f', help='Force collect results even if workflows are still running', default=False, is_flag=True) def collect_command(workflow: str, force: bool) -> NoReturn: try: collect(workflow, force) except Exception as e: logger.error(f'Something w...
class SubscriptionAddOn(Resource): schema = {'add_on': 'AddOnMini', 'add_on_source': str, 'created_at': datetime, 'expired_at': datetime, 'id': str, 'object': str, 'percentage_tiers': ['SubscriptionAddOnPercentageTier'], 'quantity': int, 'revenue_schedule_type': str, 'subscription_id': str, 'tier_type': str, 'tiers...
class _TzCache(): def __init__(self): self.initialised = (- 1) self.db = None self.dummy = False def get_db(self): if (self.db is not None): return self.db try: self.db = _TzDBManager.get_database() except _TzCacheException as err: ...
def test_doesnt_raise_deprecation_warning(): app = Flask(__name__) def provide_str(): return 'this is string' def configure(binder): binder.bind(str, to=CallableProvider(provide_str), scope=request) ('/') def index(s: str): return s FlaskInjector(app=app, modules=[configu...
class FatFileSystem(MountFileSystem): type = 'fat' aliases = ['efi system partition', 'vfat', 'fat12', 'fat16'] _mount_type = 'vfat' def detect(cls, source, description): res = super().detect(source, description) if ('DOS FAT' in description): res.update({VolumeSystemFileSyst...
class MappingPattern(Pattern): keys: list[Expression] values: list[Pattern] rest: (NameExpr | None) def __init__(self, keys: list[Expression], values: list[Pattern], rest: (NameExpr | None)) -> None: super().__init__() assert (len(keys) == len(values)) self.keys = keys se...
class CreateDatabase(Migration): def schedule_upgrades(self): self.orm_control.assert_dialect(self, 'postgresql') self.schedule('alter', op.create_table, 'sessiondata', Column('id', Integer(), nullable=False), Column('web_session_id', Integer(), nullable=True), Column('region_name', Text(), nullable...
def interleave(seqs): iters = itertools.cycle(map(iter, seqs)) while True: try: for itr in iters: (yield next(itr)) return except StopIteration: predicate = partial(operator.is_not, itr) iters = itertools.cycle(itertools.takewhile(p...
def _build_lambda_role(self, db: dynamodb.Table) -> iam.Role: return iam.Role(self, constants.SERVICE_ROLE, assumed_by=iam.ServicePrincipal('lambda.amazonaws.com'), inline_policies={'dynamic_configuration': iam.PolicyDocument(statements=[iam.PolicyStatement(actions=['appconfig:GetLatestConfiguration', 'appconfig:St...
def main(): (args, checkpoint_dir, writer, model_config) = setup(train=True) print(args) from predicate.demo_dataset_graph import get_dataset from predicate.demo_dataset_graph import collate_fn from predicate.demo_dataset_graph import to_cuda_fn (train_dset, test_dset, new_test_dset) = get_datas...
('beeref.selection.SelectableMixin.hoverMoveEvent') def test_hover_move_event_crop_mode_inside_edge(hover_mock, qapp, item): item.crop_mode = True item.crop_temp = QtCore.QRectF(0, 0, 100, 80) event = MagicMock() event.pos.return_value = QtCore.QPointF(5, 40) item.hoverMoveEvent(event) (item.cur...
def _assign_rank_write_loads(rank_to_write_loads: List[Dict[(str, List[_WriteLoad])]], rank_to_size: List[int], ranks_to_choose: List[int], logical_path: str, size: int, partition_result: List[List[_WriteLoad]]) -> None: chosen_rank = min(ranks_to_choose, key=(lambda rank: rank_to_size[rank])) partition_result[...
def _build(polygons, criterion='rook', ids=None): if (ids and (len(ids) != len(set(ids)))): raise ValueError('The argument to the ids parameter contains duplicate entries.') wttype = WT_TYPE[criterion.lower()] geo = polygons if issubclass(type(geo), FileIO): geo.seek(0) neighbor_data...