code
stringlengths
281
23.7M
class Geod_NaN_Issue112_Test(unittest.TestCase): def test_geod_nans(self): g = Geod(ellps='clrk66') (azi1, azi2, s12) = g.inv(43, 10, float('nan'), 20) self.assertTrue((azi1 != azi1)) self.assertTrue((azi2 != azi2)) self.assertTrue((s12 != s12)) (azi1, azi2, s12) = g....
def get_environment_pseudosmiles_from_smarts(smarts): matches = list(_smarts_atom_pat.finditer(smarts)) matches.reverse() pat = Chem.MolFromSmarts(smarts) assert (pat.GetNumAtoms() == len(matches)), (smarts, matches) smiles = smarts for (match, pat_atom) in zip(matches, reversed(pat.GetAtoms()))...
def patch_forward_method(func, src_type, dst_type, convert_output=True): def new_forward(*args, **kwargs): output = func(*cast_tensor_type(args, src_type, dst_type), **cast_tensor_type(kwargs, src_type, dst_type)) if convert_output: output = cast_tensor_type(output, dst_type, src_type) ...
class FindBar(): def __init__(self, parent, finder, is_reg_expr=False): self.finder = finder self.context = [] self.last_value = None self.last_pattern = None label = QLabel('Find:') label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.textbox = QCom...
def get_placeholder_loop(placeholder_string, embedder, is_sd): new_placeholder = None while True: if (new_placeholder is None): new_placeholder = input(f'Placeholder string {placeholder_string} was already used. Please enter a replacement string: ') else: new_placeholder ...
class Document(_BaseThumbedMedium): __slots__ = ('file_name', 'mime_type') def __init__(self, file_id: str, file_unique_id: str, file_name: Optional[str]=None, mime_type: Optional[str]=None, file_size: Optional[int]=None, thumbnail: Optional[PhotoSize]=None, *, api_kwargs: Optional[JSONDict]=None): supe...
def ql_qnx_msg_io_lseek(ql: Qiling, coid, smsg, sparts, rmsg, rparts, *args, **kw): (type, combine_len, whence, zero, offset) = unpack('<HHhHQ', ql.mem.read(smsg, 16)) assert ((c_int32(sparts).value, c_int32(rparts).value) == ((- 16), (- 8))), 'input/output sizes are wrong' assert ((type, combine_len, zero)...
def silent(input_filepath: Union[(str, Path)], threshold: float=0.001) -> bool: validate_input_file(input_filepath) stat_dictionary = stat(input_filepath) mean_norm = stat_dictionary['Mean norm'] if (mean_norm is not float('nan')): if (mean_norm >= threshold): return False ...
class UniformPolicy(BasePolicy): def __init__(self, input_shapes, output_shape, action_range=((- 1.0), 1.0)): super(UniformPolicy, self).__init__() self._Serializable__initialize(locals()) self.inputs = [tf.keras.layers.Input(shape=input_shape) for input_shape in input_shapes] self._...
class UpvoteEntry(Action, Mutation): def mutate(_root, entry, sender, upvoted, downvoted, in_upvoted, in_downvoted, constants, exceeded, reason): response = UpvoteEntry(feedback=None) (karma, cost, downvote_rate, upvote_rate) = constants if in_upvoted: upvoted.remove(entry) ...
class ToggleButton(PushButton): def _get_release_image(self, x, y): return (self._hover_img if self._check_hit(x, y) else self._depressed_img) def on_mouse_press(self, x, y, buttons, modifiers): if ((not self.enabled) or (not self._check_hit(x, y))): return self._pressed = (n...
class UTCDateTimeAttribute(Attribute[datetime]): attr_type = STRING def serialize(self, value): if (value.tzinfo is None): value = value.replace(tzinfo=timezone.utc) fmt = value.astimezone(timezone.utc).strftime(DATETIME_FORMAT).zfill(31) return fmt def deserialize(self, ...
def create_repitched_txt_from_ultrastar_data(input_file: str, note_numbers: list[int], output_repitched_ultrastar: str) -> None: print('{PRINT_ULTRASTAR} Creating repitched ultrastar txt -> {input_file}_repitch.txt') with open(input_file, 'r', encoding=FILE_ENCODING) as file: txt = file.readlines() ...
_layout_config def test_window_types(manager): if ((manager.backend.name == 'wayland') and (not has_wayland_notifications)): pytest.skip('Notification tests for Wayland need gtk-layer-shell') manager.test_window('one') manager.test_window('dialog', floating=True) assert_focused(manager, 'dialog'...
def dual_ascent_step(model, X, lambda1, lambda2, rho, alpha, h, rho_max): h_new = None optimizer = LBFGSBScipy(model.parameters()) X_torch = torch.from_numpy(X) while (rho < rho_max): def closure(): optimizer.zero_grad() X_hat = model(X_torch) loss = squared_l...
class PresetChannel(Channel): values = values load_capacity = Instrument.control('GU\x00{ch:c}\x00\x00', 'TD{ch:c}\x01\x00%c', 'Control the percentage of full-scale value of the load capacity preset.', preprocess_reply=(lambda d: struct.unpack('>H', d[2:4])), validator=strict_discrete_set, values=range(101)) ...
def check_accumulator_overflow(model: torch.nn.Module, quant_bw: int, accum_bw: int): most_accum_range_used = 0 most_accum_range_used_layer = None for (layer_name, layer) in model.named_modules(): if isinstance(layer, torch.nn.Conv2d): (was_accum_range_exceeded, accum_range_used) = get_c...
class PuzzleWidget(QWidget): puzzleCompleted = pyqtSignal() def __init__(self, parent=None): super(PuzzleWidget, self).__init__(parent) self.piecePixmaps = [] self.pieceRects = [] self.pieceLocations = [] self.highlightedRect = QRect() self.inPlace = 0 sel...
class SigmoidFocalLoss(nn.Module): def __init__(self, gamma, alpha, weight=None, reduction='mean'): super(SigmoidFocalLoss, self).__init__() self.gamma = gamma self.alpha = alpha self.register_buffer('weight', weight) self.reduction = reduction def forward(self, input, ta...
def _start_kernel(): from IPython.zmq.ipkernel import IPKernelApp from zmq.eventloop import ioloop global _kernel_running, _ipython_app if _kernel_running: return _ipython_app if IPKernelApp.initialized(): app = IPKernelApp.instance() else: app = IPKernelApp.instance() ...
def attack_Linf_PGD_bin(input_v, ones, dis, Ld, steps, epsilon): dis.eval() adverse_v = input_v.data.clone() adverse_v = Variable(adverse_v, requires_grad=True) optimizer = Linf_SGD([adverse_v], lr=0.0078) for _ in range(steps): optimizer.zero_grad() dis.zero_grad() d_bin = d...
def print_progress(transferred_blocks, block_size, total_size): current_mb = (((transferred_blocks * block_size) / 1024) / 1024) total_mb = ((total_size / 1024) / 1024) percent = (current_mb / total_mb) progress_str = 'Progress: {:5.1f}M / {:5.1f}M ({:6.1%})' print(progress_str.format(current_mb, to...
class TestGroverConstructor(QiskitAquaTestCase): def setUp(self): super().setUp() oracle = QuantumCircuit(2) oracle.cz(0, 1) self._expected_grover_op = GroverOperator(oracle=oracle) def test_oracle_quantumcircuit(self): oracle = QuantumCircuit(2) oracle.cz(0, 1) ...
def solid_angle(v0: wp.vec3, v1: wp.vec3, v2: wp.vec3, p: wp.vec3): a = (v0 - p) b = (v1 - p) c = (v2 - p) a_len = wp.length(a) b_len = wp.length(b) c_len = wp.length(c) det = wp.dot(a, wp.cross(b, c)) den = (((((a_len * b_len) * c_len) + (wp.dot(a, b) * c_len)) + (wp.dot(b, c) * a_len))...
def target_df_rows_agg(spark_context, spark_session): data = [{'id': 1, 'timestamp': '2016-04-11 11:31:11', 'feature1': 200, 'feature2': 200, 'feature1__avg_over_2_events_row_windows': 200, 'feature1__avg_over_3_events_row_windows': 200}, {'id': 1, 'timestamp': '2016-04-11 11:44:12', 'feature1': 300, 'feature2': 30...
.fast .parametrize(('input_wavenumbers', 'expected_wavenumbers_cm1'), [[(((2000 * 1) / u.cm), ((230000 * 1) / u.m)), (2000, 2300)]]) def test_wavenumber_units_conversion(input_wavenumbers, expected_wavenumbers_cm1, verbose=True, *args, **kwargs): setup_test_line_databases() (wmin, wmax) = input_wavenumbers ...
class Routing(): def __init__(self, plugin: 'Plugin') -> None: self._rules: Dict[(Callable, List[UrlRule])] = {} self.plugin = plugin def route_for(self, path: str) -> Optional[Callable]: if path.startswith(self.plugin.PLUGIN_URL): path = path.split(self.plugin.PLUGIN_URL, 1)...
class PositionWeightedModuleCollectionEmbeddingBagCollectionTest(unittest.TestCase): def test_position_weighted_collection_module_ebc(self) -> None: features = KeyedJaggedTensor.from_offsets_sync(keys=['f1', 'f2'], values=torch.tensor([0, 1, 2, 3, 4, 5, 6, 7]), offsets=torch.tensor([0, 2, 2, 3, 4, 5, 8])) ...
def _lambertw_v_from_i(current, photocurrent, saturation_current, resistance_series, resistance_shunt, nNsVth): output_is_scalar = all(map(np.isscalar, (current, photocurrent, saturation_current, resistance_series, resistance_shunt, nNsVth))) conductance_shunt = (1.0 / resistance_shunt) (I, IL, I0, Rs, Gsh,...
class Msg15NativeTrailerRecord(object): def get(self): record = [('GP_PK_HEADER', GSDTRecords.gp_pk_header), ('GP_PK_SH1', GSDTRecords.gp_pk_sh1), ('15TRAILER', self.seviri_l15_trailer)] return np.dtype(record).newbyteorder('>') def seviri_l15_trailer(self): record = [('15TrailerVersion'...
def interpolate_bilinear(grid, query_points, indexing='ij', name=None): if ((indexing != 'ij') and (indexing != 'xy')): raise ValueError("Indexing mode must be 'ij' or 'xy'") with tf.name_scope((name or 'interpolate_bilinear')): grid = tf.convert_to_tensor(grid) query_points = tf.convert...
def new_npair_loss(labels, embedding_anchor, embedding_positive, reg_lambda, equal_shape=True, half_batch_size=64): reg_anchor = math_ops.reduce_mean(math_ops.reduce_sum(math_ops.square(embedding_anchor), 1)) reg_positive = math_ops.reduce_mean(math_ops.reduce_sum(math_ops.square(embedding_positive), 1)) l2...
class TestMakeTimeCdsDictionary(unittest.TestCase): def test_fun(self): tcds = {'Days': np.array(1), 'Milliseconds': np.array(2)} expected = datetime(1958, 1, 2, 0, 0, 0, 2000) assert (timecds2datetime(tcds) == expected) tcds = {'Days': np.array(1), 'Milliseconds': np.array(2), 'Micr...
def convert_pl_to_hf(pl_ckpt_path: str, hf_src_model_dir: str, save_path: str) -> None: hf_model = AutoModelForSeq2SeqLM.from_pretrained(hf_src_model_dir) if os.path.isfile(pl_ckpt_path): ckpt_files = [pl_ckpt_path] else: assert os.path.isdir(pl_ckpt_path) ckpt_files = list(Path(pl_c...
_cache(maxsize=200) def _calcMissileFactor(atkEr, atkEv, atkDrf, tgtSpeed, tgtSigRadius): factors = [1] if (atkEr > 0): factors.append((tgtSigRadius / atkEr)) if (tgtSpeed > 0): factors.append((((atkEv * tgtSigRadius) / (atkEr * tgtSpeed)) ** atkDrf)) totalMult = min(factors) return ...
class TestGoBack(BaseTestCase): async def test_back(self): (await self.page.goto((self.url + 'empty'))) (await self.page.goto((self.url + 'static/textarea.html'))) response = (await self.page.goBack()) self.assertTrue(response.ok) self.assertIn('empty', response.url) ...
def source(left, right, boundary=False): if isinstance(left, numbers.Number): left = pybamm.PrimaryBroadcast(left, 'current collector') if ((left.domain != ['current collector']) or (right.domain != ['current collector'])): raise pybamm.DomainError(f''''source' only implemented in the 'current c...
class TestNetwork(ElectrumTestCase): def setUpClass(cls): super().setUpClass() constants.set_regtest() def tearDownClass(cls): super().tearDownClass() constants.set_mainnet() def setUp(self): super().setUp() self.config = SimpleConfig({'electrum_path': self.el...
class CommandBase(object): def __init__(self, url: str='') -> None: self._url = url def __repr__(self) -> str: return f'{type(self).__name__}({self.__dict__})' def __eq__(self, other) -> bool: return ((self is other) or (self.__dict__ == other.__dict__)) def _method(self) -> str:...
class BuildingMenu(object): keys_go_back = [''] sep_keys = '.' joker_key = '*' min_shortcut = 1 def __init__(self, caller=None, obj=None, title='Building menu: {obj}', keys=None, parents=None, persistent=False): self.caller = caller self.obj = obj self.title = title s...
class GenerationConfig(FairseqDataclass): beam: int = field(default=5, metadata={'help': 'beam size'}) nbest: int = field(default=1, metadata={'help': 'number of hypotheses to output'}) max_len_a: float = field(default=0, metadata={'help': 'generate sequences of maximum length ax + b, where x is the source ...
class SplunkLogsModel(SharedModel, ActionLogsDataInterface): def __init__(self, producer, splunk_config, should_skip_logging=None): self._should_skip_logging = should_skip_logging self._logs_producer = LogProducerProxy() if (producer == 'splunk'): self._logs_producer.initialize(S...
def test_initialize_fresh(hatch, helpers, temp_dir): project_name = 'My.App' description = 'foo' with temp_dir.as_cwd(): result = hatch('new', project_name) assert (result.exit_code == 0), result.output path = (temp_dir / 'my-app') project_file = (path / 'pyproject.toml') project...
def set_player_object_material_text(player_id: int, object_id: int, text: str, material_index: int=0, material_size: int=OBJECT_MATERIAL_SIZE_256x128, font_face: str='Arial', font_size: int=24, bold: bool=True, font_color: int=, back_color: int=0, text_alignment: int=0) -> bool: return SetPlayerObjectMaterialText(p...
class CompDoc(object): def __init__(self, mem, logfile=sys.stdout, DEBUG=0, ignore_workbook_corruption=False): self.logfile = logfile self.ignore_workbook_corruption = ignore_workbook_corruption self.DEBUG = DEBUG if (mem[0:8] != SIGNATURE): raise CompDocError('Not an OLE...
def test_pool_no_package_from_specified_repository_raises_package_not_found() -> None: package = get_package('foo', '1.0.0') repo1 = Repository('repo1') repo2 = Repository('repo2', [package]) pool = RepositoryPool([repo1, repo2]) with pytest.raises(PackageNotFound): pool.package('foo', Versi...
class Lock(object): _NODE_NAME = '__lock__' _EXCLUDE_NAMES = ['__lock__'] def __init__(self, client, path, identifier=None, extra_lock_patterns=()): self.client = client self.path = path self._exclude_names = set((self._EXCLUDE_NAMES + list(extra_lock_patterns))) self._conten...
def test_update_catalogs(db, settings): xml_file = (((Path(settings.BASE_DIR) / 'xml') / 'elements') / 'catalogs.xml') root = read_xml_file(xml_file) version = root.attrib.get('version') elements = flat_xml_to_elements(root) elements = convert_elements(elements, version) elements = order_element...
class ElementProxy(): def __init__(self, element: BaseOxmlElement, parent: (t.ProvidesXmlPart | None)=None): self._element = element self._parent = parent def __eq__(self, other: object): if (not isinstance(other, ElementProxy)): return False return (self._element is ...
def save_an_icom_batch(date_pattern, ip_directory, data_to_save): if (not date_pattern.match(data_to_save[8:26])): raise ValueError('Unexpected iCOM stream format') counter = str(int(data_to_save[26])).zfill(3) filepath = ip_directory.joinpath(f'{counter}.txt') with open(filepath, 'bw+') as f: ...
class BiF_Att(nn.Module): def __init__(self, emodict, worddict, embedding, args): super(BiF_Att, self).__init__() self.num_classes = emodict.n_words self.embeddings = embedding self.gpu = args.gpu self.hops = args.hops self.wind_1 = args.wind1 self.utt_gru = G...
class F9_Raid(F7_Raid): removedKeywords = F7_Raid.removedKeywords removedAttrs = F7_Raid.removedAttrs def _getParser(self): op = F7_Raid._getParser(self) op.add_argument('--bytes-per-inode', deprecated=F9) op.add_argument('--fsprofile', version=F9, help='\n Spe...
def _prepare_connection_costs_per_link(n, costs, renewable_config, hvdc_as_lines, lines_length_factor): if n.links.empty: return {} connection_costs_per_link = {} if hvdc_as_lines: dc_lengths = n.lines.length unterwater_fractions = n.lines.underwater_fraction else: dc_len...
class FixScaleCrop(object): def __init__(self, crop_size): self.crop_size = crop_size def __call__(self, sample): img = sample['image'] mask = sample['label'] (w, h) = img.size if (w > h): oh = self.crop_size ow = int((((1.0 * w) * oh) / h)) ...
class SshConfig(config_parser.Config): def __init__(self, host, username, password=None, cfg_file=None): import paramiko self.ssh = paramiko.SSHClient() self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.ssh.connect(host, username=username, password=password) ...
def get_class_splits(spanning_leaves, valid_test_roots=None, **kwargs): if (valid_test_roots is not None): if ((valid_test_roots['valid'] is None) or (valid_test_roots['test'] is None)): raise ValueError('A root cannot be None.') if (valid_test_roots is None): valid_test_roots = prop...
class TokenClassificationEvaluator(ClassificationEvaluator): def __init__(self, model_args: ModelArguments, data_args: DataTrainingArguments, training_args: TrainingArguments, processor: DataProcessor, model: torch.nn.Module, trainer: Optional[HugTrainer]=None, eval_dataset: Optional[Dataset]=None, test_dataset: Op...
def DS_format_to_lines(context_mode, summ_mode, args): assert (summ_mode in ['final', 'user', 'agent']) assert (context_mode in ['both', 'user', 'agent']) corpora = {'train': [], 'val': [], 'test': []} read_root_path = Path(args.raw_path) save_root_path = ((Path(args.save_path) / f'{context_mode}') ...
def add_or_invite_to_team(inviter, team, user_obj=None, email=None, requires_invite=True): if (user_obj and requires_invite): orgname = team.organization.username if user_obj.robot: requires_invite = False if (not user_obj.username.startswith((orgname + '+'))): ...
def get(identifier): if isinstance(identifier, six.string_types): identifier = str(identifier) return deserialize(identifier) elif callable(identifier): return identifier else: raise ValueError('Could not interpret metric function identifier:', identifier)
class TestTypeAlias(TestNameCheckVisitorBase): _passes() def test_runtime(self): from typing_extensions import TypeAlias X: TypeAlias = int Y = X Z: 'TypeAlias' = int def capybara(x: X, y: Y, x_quoted: 'X', y_quoted: 'Y', z: Z) -> None: assert_is_value(x, Type...
class MultiProjectRefactoring(): def __init__(self, refactoring, projects, addpath=True): self.refactoring = refactoring self.projects = projects self.addpath = addpath def __call__(self, project, *args, **kwds): return _MultiRefactoring(self.refactoring, self.projects, self.addp...
class DiceLoss(nn.Module): def __init__(self, smooth=1.0, ignore_index=255): super(DiceLoss, self).__init__() self.ignore_index = ignore_index self.smooth = smooth def forward(self, output, target): if (self.ignore_index not in range(target.min(), target.max())): if (...
class KnownValues(unittest.TestCase): def test_ip_adc2(self): (e, t_amp1, t_amp2) = myadc.kernel_gs() self.assertAlmostEqual(e, (- 0.), 6) myadcip = adc.radc_ip.RADCIP(myadc) (e, v, p, x) = myadcip.kernel(nroots=3) self.assertAlmostEqual(e[0], 0., 6) self.assertAlmost...
class BitPackDecoder(): _data: bytes _offset: int def __init__(self, data: bytes): self._data = data self._offset = 0 def decode(self, *args: int) -> tuple[(int, ...)]: compiled = _compile_format(*args) offset = self._offset self._offset += compiled.calcsize() ...
class DebugConnectorBuilder(ConnectorBuilder): target_game: RandovaniaGame layout_uuid: uuid.UUID def __init__(self, game: str, layout_uuid: str=str(INVALID_UUID)): super().__init__() self.target_game = RandovaniaGame(game) self.layout_uuid = uuid.UUID(layout_uuid) def create(cls...
def _SetInformationProcess(ql: Qiling, address: int, params): process = params['ProcessHandle'] flag = params['ProcessInformationClass'] ibuf_ptr = params['ProcessInformation'] ibuf_len = params['ProcessInformationLength'] if (flag == ProcessDebugFlags): flag_name = 'ProcessDebugFlags' ...
def AutoDancefer(source, target, output_path=None, synch_video_beat=0, synch_audio_beat=0, beat_offset=0, **kwargs): sourcev = PullVideo(source_location=source) targetv = PullVideo(source_location=target) result = Dancefer(source_video=sourcev, target=targetv, output_path=output_path, force_recompute=True, ...
def pad(array, transform, pad_width, mode=None, **kwargs): import numpy as np transform = guard_transform(transform) padded_array = np.pad(array, pad_width, mode, **kwargs) padded_trans = list(transform) padded_trans[2] -= (pad_width * padded_trans[0]) padded_trans[5] -= (pad_width * padded_tran...
class CmdEvscapeRoom(Command): arg_regex = '(/\\w+?(\\s|$))|\\s|$' help_category = 'Evscaperoom' obj1_search = None obj2_search = None def _search(self, query, required): if (required is False): return (None, query) matches = self.caller.search(query, quiet=True) ...
class ToolsWizardPage2(BasePyzoWizardPage): _title = translate('wizard', 'Recommended tools') _image_filename = 'pyzo_tools2.png' _descriptions = [translate('wizard', 'We especially recommend the following tools:'), translate('wizard', 'The *Source structure tool* gives an outline of the source code.'), tra...
def change(file_name, file_out, dict_file, split_=' ', split_3=False): with open(file_name, 'r', encoding='utf-8') as f: data = [(i.split(split_) if (len(i.split(split_)) == 2) else ['###', '###']) for i in f.readlines()] document_pair = [[i[0], i[1].strip().replace('M-', 'I-').replace('E-', 'I-').r...
class UEM(MutableMapping): def __init__(self, *args, **kwargs): super(UEM, self).__init__() self.update(*args, **kwargs) def __setitem__(self, fid, score_regions): invalid_type_msg = ('Expected sequence of pairs. Received: %r (%s).' % (score_regions, type(score_regions))) try: ...
def generate_subset_of_filenames(subset=None, base_dir=''): if (subset is None): subset = _create_full_set() pattern = os.path.join(base_dir, FILENAME) files = [] for (channel, segments) in subset.items(): new_files = _generate_filenames(pattern, channel, segments) files.extend(n...
class MinMaxScaler(SKCMatrixAndWeightTransformerABC): _skcriteria_parameters = ['target', 'clip', 'criteria_range'] def __init__(self, target, *, clip=False, criteria_range=(0, 1)): super().__init__(target) self._clip = bool(clip) (self._cr_min, self._cr_max) = map(float, criteria_range)...
class DszCommandError(list): def __init__(self, timestamp, cmdid): self.timestamp = timestamp self.__cmdid = cmdid list.__init__(self) def __str__(self): msg = ('Error running command %d: %s\n' % (self.__cmdid, dsz.cmd.data.Get('commandmetadata::fullcommand', dsz.TYPE_STRING, cmd...
def total_intersect_and_union(results, gt_seg_maps, num_classes, ignore_index, label_map=dict(), reduce_zero_label=False): total_area_intersect = torch.zeros((num_classes,), dtype=torch.float64).cuda() total_area_union = torch.zeros((num_classes,), dtype=torch.float64).cuda() total_area_pred_label = torch.z...
.parametrize(['ops', 'error'], [pytest.param([qutip.basis(5, 0)], 'square', id='Not square'), pytest.param([qutip.qeye(5), qutip.qeye(3)], 'shape', id='shape mismatch'), pytest.param([qutip.destroy(5)], 'Hermitian', id='Non Hermitian'), pytest.param([qutip.sigmax(), qutip.sigmay()], 'commute', id='Not commuting')]) def...
class RobustNorm(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_range=True, power=0.2): nn.BatchNorm2d.__init__(self, num_features=num_features, eps=eps, momentum=momentum, affine=affine, track_running_stat...
def get_dataset(data_cfg): if isinstance(data_cfg['ann_file'], (list, tuple)): ann_files = data_cfg['ann_file'] num_dset = len(ann_files) else: ann_files = [data_cfg['ann_file']] num_dset = 1 if isinstance(data_cfg['img_prefix'], (list, tuple)): img_prefixes = data_cf...
def parse_key_part(src: str, pos: Pos) -> tuple[(Pos, str)]: try: char: (str | None) = src[pos] except IndexError: char = None if (char in BARE_KEY_CHARS): start_pos = pos pos = skip_chars(src, pos, BARE_KEY_CHARS) return (pos, src[start_pos:pos]) if (char == "'")...
def discriminator_loss(disc_real_outputs, disc_generated_outputs): loss = 0 r_losses = [] g_losses = [] for (dr, dg) in zip(disc_real_outputs, disc_generated_outputs): r_loss = torch.mean(((1 - dr) ** 2)) g_loss = torch.mean((dg ** 2)) loss += (r_loss + g_loss) r_losses.a...
class CWERMetric(tf.keras.metrics.Metric): def __init__(self, padding_token, name='CWER', **kwargs): super(CWERMetric, self).__init__(name=name, **kwargs) self.cer_accumulator = tf.Variable(0.0, name='cer_accumulator', dtype=tf.float32) self.wer_accumulator = tf.Variable(0.0, name='wer_accum...
class ArithmeticCoder(): def __init__(self, fo: tp.IO[bytes], total_range_bits: int=24): assert (total_range_bits <= 30) self.total_range_bits = total_range_bits self.packer = BitPacker(bits=1, fo=fo) self.low: int = 0 self.high: int = 0 self.max_bit: int = (- 1) ...
def test_help_subcommand_completion_multiple(sc_app): text = '' line = 'help base {}'.format(text) endidx = len(line) begidx = (endidx - len(text)) first_match = complete_tester(text, line, begidx, endidx, sc_app) assert ((first_match is not None) and (sc_app.completion_matches == ['bar', 'foo',...
class EngineGenerator(): def __init__(self, max_input_length: int=1024, max_total_tokens: int=2048): self.max_input_length = max_input_length self.max_total_tokens = max_total_tokens def create_engine_config(self): return VLLMEngineConfig(type='VLLMEngine', model_id=MODEL_ID, generation=...
class FileToMiscIter(IterWrappingFile): def __init__(self, file): IterWrappingFile.__init__(self, file) self.buf = b'' def __iter__(self): return self def __next__(self): if self.currently_in_file: self.currently_in_file.close() type = None while (...
class TPLPushHandler(BaseHandler): .authenticated async def get(self, tplid): user = self.current_user tpl = (await self.db.tpl.get(tplid, fields=('id', 'userid', 'sitename'))) if (not self.permission(tpl, 'w')): self.evil((+ 5)) (await self.finish(u'<span class="...
def test_standstillcondition(): cond = OSC.StandStillCondition(1) prettyprint(cond.get_element()) cond2 = OSC.StandStillCondition(1) cond3 = OSC.StandStillCondition(3) assert (cond == cond2) assert (cond != cond3) cond4 = OSC.StandStillCondition.parse(cond.get_element()) assert (cond == ...
class TextFrame(): def __init__(self, layout, border_width, border_color, pad_x, pad_y, highlight_color=None): self.layout = layout self.border_width = border_width self.border_color = border_color self.drawer = self.layout.drawer self.highlight_color = highlight_color ...
def _build_plain_hierarchy(hierarchy, is_root=False): all_children = set([]) all_keyed_parent = {} all_keyed_child = {} if ('Subcategory' in hierarchy): for node in hierarchy['Subcategory']: (keyed_parent, keyed_child, children) = _build_plain_hierarchy(node) _update_dict...
def merge_pos_pairs_into_dialog_file(data_folder, dialog_file): fout = open(dialog_file, 'w', encoding='utf-8') for partition in list(['train', 'valid']): with open(((data_folder + partition) + '.txt'), encoding='utf-8') as fin: for l in tqdm(fin): tokens = l.split('\t') ...
def test_state_wait_secretrequest_valid(): setup = setup_initiator_tests() state_change = ReceiveSecretRequest(payment_identifier=UNIT_TRANSFER_IDENTIFIER, amount=setup.lock.amount, expiration=setup.lock.expiration, secrethash=setup.lock.secrethash, sender=UNIT_TRANSFER_TARGET) iteration = initiator_manager...
def admin_session(user, session_id): session: MultiplayerSession = MultiplayerSession.get_by_id(session_id) rows = [] associations: list[WorldUserAssociation] = list(WorldUserAssociation.select().join(World).where((World.session == session))) for association in associations: inventory = [] ...
def mosek_solve_qp(P: Union[(np.ndarray, spa.csc_matrix)], q: np.ndarray, G: Optional[Union[(np.ndarray, spa.csc_matrix)]]=None, h: Optional[np.ndarray]=None, A: Optional[Union[(np.ndarray, spa.csc_matrix)]]=None, b: Optional[np.ndarray]=None, lb: Optional[np.ndarray]=None, ub: Optional[np.ndarray]=None, initvals: Opti...
class DevDataset(Dataset): def __init__(self, args, raw_datasets, cache_root): self.args = args self.raw_datasets = raw_datasets cache_path = os.path.join(cache_root, 'sql2text_dev.cache') if (os.path.exists(cache_path) and args.dataset.use_cache): self.data = torch.load(...
def test_biorbd_model_import(): from bioptim.examples.torque_driven_ocp import example_multi_biorbd_model as ocp_module bioptim_folder = os.path.dirname(ocp_module.__file__) biorbd_model_path = '/models/triple_pendulum.bioMod' biorbd_model_path_modified_inertia = '/models/triple_pendulum_modified_inerti...
class Delta(D.Distribution): arg_constraints: dict = {} def __init__(self, param: torch.Tensor, atol: float=1e-06, rtol: float=1e-06, batch_shape: ((torch.Size | Sequence[int]) | None)=None, event_shape: ((torch.Size | Sequence[int]) | None)=None) -> None: if (batch_shape is None): batch_sha...
(frozen=True) class BoundMethodSignature(): signature: ConcreteSignature self_composite: Composite return_override: Optional[Value] = None def check_call(self, args: Iterable[Argument], visitor: 'NameCheckVisitor', node: Optional[ast.AST]) -> Value: ret = self.signature.check_call([(self.self_co...
class EditInlineCaption(): async def edit_inline_caption(self: 'pyrogram.Client', inline_message_id: str, caption: str, parse_mode: Optional['enums.ParseMode']=None, reply_markup: 'types.InlineKeyboardMarkup'=None) -> bool: return (await self.edit_inline_text(inline_message_id=inline_message_id, text=captio...