code
stringlengths
281
23.7M
def request_wrap_timeout(func, url): import requests for (attempt, timeout) in enumerate([10, 20, 40, 60, 60]): try: return func(timeout=timeout) except requests.exceptions.Timeout as e: logger.warning('Request for %s timed-out (attempt %d). Retrying with a timeout of %d ...
class SolverProcess(): automatic_call = False def __init__(self, *, name, command, cp): self.name = name self.command = command self.cp = cp self.options = '' self.stdout = None self.stderr = None self.last_command_wck = None self.log_filename_suff...
def transform_with_items(schema, template): items = template['with_items'] if isinstance(items, dict): if (set(items) == {'using'}): items = items['using'] elif (set(items) == {'from_stdout'}): items = from_stdout(items['from_stdout']) if hasattr(items, '__call__'): ...
def min_freItem(): global ww counter = dict() mine = '' my_dict['a'] = 3 my_dict['g'] = 6 my_dict['c'] = 6 my_dict['t'] = 4 for t in range(NumbS): S = sDB[t].S for s in S: mine = s if (counter.get(mine) == None): counter[mine] = 1 ...
class TestGetImage(EndianTest): def setUp(self): self.req_args_0 = {'drawable': , 'format': 2, 'height': 20170, 'plane_mask': , 'width': 282, 'x': (- 14814), 'y': (- 5449)} self.req_bin_0 = b'I\x02\x00\x053\xfbEj\xc6"\xea\xb7\x01\x1aN\xca$\xba\x96\xb6' self.reply_args_0 = {'data': b'\xeb?:\x...
class CollectionConfig(BaseModel, extra='forbid'): params: 'CollectionParams' = Field(..., description='') hnsw_config: 'HnswConfig' = Field(..., description='') optimizer_config: 'OptimizersConfig' = Field(..., description='') wal_config: 'WalConfig' = Field(..., description='') quantization_config...
def convert_all_pt_checkpoints_to_tf(args_model_type, tf_dump_path, model_shortcut_names_or_path=None, config_shortcut_names_or_path=None, compare_with_pt_model=False, use_cached_models=False, remove_cached_files=False, only_convert_finetuned_models=False): if (args_model_type is None): model_types = list(M...
def test_molecule_and_vsite_water(coumarin, tmpdir, water, rfree_data): coumarin_copy = coumarin.copy(deep=True) MBISCharges.apply_symmetrisation(coumarin_copy) with tmpdir.as_cwd(): alpha = rfree_data.pop('alpha') beta = rfree_data.pop('beta') lj = LennardJones612(free_parameters=rf...
def ft_setup(workers: List[int], num_rounds: int, die_round_factor: 0.25, comeback_round_factor: 0.75): if (workers is None): return None ft_manager = FaultToleranceManager.remote() die_round = int((die_round_factor * num_rounds)) comeback_round = int((comeback_round_factor * num_rounds)) fo...
class ExtraDuplicatesSettings(BaseModel): interval_description: ClassVar[str] = 'Look for rule violations in messages from the last `interval` number of seconds.' threshold_description: ClassVar[str] = 'Maximum number of duplicate messages before the filter is triggered.' interval: int = 10 threshold: i...
class KeyboardButton(TelegramObject): __slots__ = ('request_location', 'request_contact', 'request_poll', 'text', 'web_app', 'request_user', 'request_chat') def __init__(self, text: str, request_contact: Optional[bool]=None, request_location: Optional[bool]=None, request_poll: Optional[KeyboardButtonPollType]=N...
class CorruptionLayoutEditor(QtWidgets.QWidget, Ui_CorruptionLayoutEditor): def __init__(self): super().__init__() self.setupUi(self) self.game_description = default_database.game_description_for(RandovaniaGame.METROID_PRIME_CORRUPTION) pickup_database = default_database.pickup_datab...
def gen_back_to_back_test(): return '\n # Test backwards walk (back to back branch taken)\n\n csrr x3, mngr2proc < 1\n csrr x1, mngr2proc < 1\n\n bne x3, x0, X0\n csrw proc2mngr, x0\n nop\n a0:\n csrw proc2mngr, x1 > 1\n bne x3, x0, y0\n b0:\n bne x3, x0, a0\n c0:\...
class FeatQueue(nn.Module): def __init__(self, max_queue_size=30000): super(FeatQueue, self).__init__() self.max_queue_size = max_queue_size def append(self, queue, feat): if isinstance(feat, np.ndarray): queue = np.concatenate([queue, feat], axis=0) queue_size = ...
def directed_hausdorff(point_cloud_A, point_cloud_B): npoint = point_cloud_A.shape[1] A = tf.expand_dims(point_cloud_A, axis=2) A = tf.tile(A, (1, 1, npoint, 1)) B = tf.expand_dims(point_cloud_B, axis=1) B = tf.tile(B, (1, npoint, 1, 1)) distances = tf.squared_difference(B, A) distances = tf...
class MCHManagedCollisionModule(ManagedCollisionModule): def __init__(self, zch_size: int, device: torch.device, eviction_policy: MCHEvictionPolicy, eviction_interval: int, input_hash_size: int=(2 ** 63), input_hash_func: Optional[Callable[([torch.Tensor, int], torch.Tensor)]]=None, mch_size: Optional[int]=None, mc...
.parametrize('method, url, expected_result, strict', [('ls', 'bigquery://bigquery-url/path1/path2', ('bigquery://', ['path1', 'path2', None]), False), ('schema', 'bigquery://bigquery-url/path1/path2/path3', ('bigquery://', ['path1', 'path2', 'path3']), False), ('ls', 'invalidscheme://invalid-url', pytest.raises(ValueEr...
class SynonymProcessor(DataProcessor): def get_train_examples(self, data_dir): logger.info('LOOKING AT {} train'.format(data_dir)) return self._create_examples(self._read_csv(os.path.join(data_dir, 'mctrain.csv')), 'train') def get_dev_examples(self, data_dir): logger.info('LOOKING AT {}...
class Ksboolean_TestCase(ParserTest): def runTest(self): self.assertTrue(ksboolean('ON')) self.assertTrue(ksboolean('On')) self.assertTrue(ksboolean('YES')) self.assertTrue(ksboolean('Yes')) self.assertTrue(ksboolean('TRUE')) self.assertTrue(ksboolean('True')) ...
def write_html(filename, it, img_save_it, img_dir, all_size=1536): html_file = open(filename, 'w') html_file.write(('\n <!DOCTYPE html>\n <html>\n <head>\n <title>Experiment name = %s</title>\n <meta content="30">\n </head>\n <body>\n ' % os.path.basename(filename))) html_file.w...
class ConfigTestUtils(unittest.TestCase): def test_config_from_string(self): c = GPT2Config() n_embd = (c.n_embd + 1) resid_pdrop = (c.resid_pdrop + 1.0) scale_attn_weights = (not c.scale_attn_weights) summary_type = (c.summary_type + 'foo') c.update_from_string(f'n_e...
class TestSlonyCollector(CollectorTestCase): def setUp(self): config = get_collector_config('SlonyCollector', {}) self.collector = SlonyCollector(config, None) def test_import(self): self.assertTrue(SlonyCollector) _only_if_psycopg2_is_available (SlonyCollector, '_get_stats_by_da...
class PyramidNet(nn.Module): def __init__(self, dataset, depth, alpha, num_classes, bottleneck=False): super(PyramidNet, self).__init__() self.dataset = dataset if self.dataset.startswith('cifar'): self.inplanes = 16 if (bottleneck == True): n = int(((...
class Dialog(QDialog): def __init__(self, parent=None): super(Dialog, self).__init__(parent) self.server = FortuneServer() statusLabel = QLabel() statusLabel.setWordWrap(True) quitButton = QPushButton('Quit') quitButton.setAutoDefault(False) if (not self.serve...
class Multiply(ImageOnlyTransform): identity_param = 1 def __init__(self, factors: List[float]): if (self.identity_param not in factors): factors = ([self.identity_param] + list(factors)) super().__init__('factor', factors) def apply_aug_image(self, image, factor=1, **kwargs): ...
def encrypt(key: bytes, nonce: bytes, initial_block_counter: int, plaintext: bytes) -> bytes: full_nonce = (struct.pack('<Q', initial_block_counter) + nonce) encryptor = Cipher(algorithms.ChaCha20(key, full_nonce), mode=None).encryptor() plaintext_len_blocks = math.ceil((len(plaintext) / BLOCK_SIZE)) bl...
def available_instruments(inst_loc=None): def get_inst_id_dict(inst_module_name): try: module = importlib.import_module(inst_module_name) inst_ids = {inst_id: {tag: module.tags[tag] for tag in module.inst_ids[inst_id]} for inst_id in module.inst_ids.keys()} except ImportError...
def test_third2oct_2darray(): levels = np.array([[100, 95, 80, 55, 65, 85, 75, 70, 90, 95, 105, 110], [100, 95, 80, 55, 65, 85, 75, 70, 90, 95, 105, 110]]) generated = third2oct(levels, axis=1) real = np.array([[101., 85., 90., 111.], [101., 85., 90., 111.]]) assert_array_almost_equal(generated, real)
def _f1_score_param_check(num_classes: Optional[int], average: Optional[str]) -> None: average_options = ('micro', 'macro', 'weighted', None) if (average not in average_options): raise ValueError(f'`average` was not in the allowed value of {average_options}, got {average}.') if ((average != 'micro')...
def valid_tile_size(value, arg_name, min_power=4, logger=None): error = False if (not isinstance(value, int)): if logger: logger.error(f'''Invalid value for the argument {arg_name}: {value}. Enter an integer. ''') else: print(f'''ERROR: Invalid value for the argument {arg...
class DataPrefetcher(): def __init__(self, loader): self.loader = iter(loader) self.stream = torch.cuda.Stream() self.input_cuda = self._input_cuda_for_image self.record_stream = DataPrefetcher._record_stream_for_image self.preload() def preload(self): try: ...
def _migrate_v5(preset: dict) -> dict: excluded_item = {'include_copy_in_original_location': False, 'num_shuffled_pickups': 0, 'num_included_in_starting_items': 0, 'included_ammo': [], 'allowed_as_random_starting_item': True} included_item = {**excluded_item, 'num_included_in_starting_items': 1} shuffled_it...
class _Metadata(_PrimitiveTemplateBase): _valid_predicates = set() def is_element(self, value): return isinstance(value, metadata.Metadata) def decode(self, metadata): if (not self.is_element(metadata)): raise TypeError('`Metadata` must be provided by the interface directly.') ...
def unpack_archive(filename, extract_dir, progress_filter=default_filter, drivers=None): for driver in (drivers or extraction_drivers): try: driver(filename, extract_dir, progress_filter) except UnrecognizedFormat: continue else: return else: r...
def create_playlists(_request: WSGIRequest) -> HttpResponse: library_link = os.path.join(conf.SONGS_CACHE_DIR, 'local_library') if (not os.path.islink(library_link)): return HttpResponseBadRequest('No library set') _set_scan_progress('0 / 0 / 0') _create_playlists.delay() return HttpResponse...
def _selfdestruct(computation: ComputationAPI, beneficiary: Address) -> None: local_balance = computation.state.get_balance(computation.msg.storage_address) beneficiary_balance = computation.state.get_balance(beneficiary) computation.state.set_balance(beneficiary, (local_balance + beneficiary_balance)) ...
class FillLouver(bpy.types.PropertyGroup): louver_count: IntProperty(name='Louver Count', min=0, max=100, default=10, description='Number of louvers on to create face') louver_margin: FloatProperty(name='Louver Margin', step=1, min=get_scaled_unit(0.001), max=get_scaled_unit(100.0), default=get_scaled_unit(0.1)...
class ReportFormatter(Formatter): ACTIVITY_MAXLEN = 12 SPACING = ' ' CONTEXT_PREFIX = 'from' TARGET_PREFIX = 'to' def format(self, record): if hasattr(record, 'activity'): return self.format_report(record) return self.format_default(record) def create_padding(self, a...
def _get_aws_ip_ranges(): try: path = os.path.dirname(os.path.abspath(__file__)) file_path = os.path.join(path, 'aws-ip-ranges.json') with open(file_path, 'r') as f: return json.loads(f.read()) except IOError: logger.exception('Could not load AWS IP Ranges') r...
class FBCNet_old(nn.Module): def SCB(self, m, nChan, nBands, doWeightNorm=True, *args, **kwargs): return nn.Sequential(Conv2dWithConstraint(nBands, (m * nBands), (nChan, 1), groups=nBands, max_norm=2, doWeightNorm=doWeightNorm, padding=0), nn.BatchNorm2d((m * nBands)), nn.ELU()) def LastBlock(self, inF,...
_datapipe('load_from_zip') class ZipArchiveLoaderIterDataPipe(IterDataPipe[Tuple[(str, BufferedIOBase)]]): def __init__(self, datapipe: Iterable[Tuple[(str, BufferedIOBase)]], length: int=(- 1)) -> None: super().__init__() self.datapipe: Iterable[Tuple[(str, BufferedIOBase)]] = datapipe self...
class BehavioralRTLIRGenL1Pass(RTLIRPass): rtlir_upblks = MetadataKey() def __init__(s, translation_top): c = s.__class__ s.tr_top = translation_top if (not translation_top.has_metadata(c.rtlir_getter)): translation_top.set_metadata(c.rtlir_getter, RTLIRGetter(cache=True)) ...
_tokenizer('moses') class MosesTokenizer(object): def add_args(parser): parser.add_argument('--moses-source-lang', metavar='SRC', help='source language') parser.add_argument('--moses-target-lang', metavar='TARGET', help='target language') parser.add_argument('--moses-no-dash-splits', action=...
class MixConvBlock(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride, padding, dilation=1, groups=1, bias=False, use_bn=True, bn_eps=1e-05, activation=(lambda : nn.ReLU(inplace=True))): super(MixConvBlock, self).__init__() self.activate = (activation is not None) ...
def test_create_forbidden(db, client, settings): settings.PROJECT_CREATE_RESTRICTED = True client.login(username='user', password='user') url = reverse(urlnames['list']) data = {'title': 'Lorem ipsum dolor sit amet', 'description': 'At vero eos et accusam et justo duo dolores et ea rebum.', 'catalog': c...
def parse_date(datestring, default_timezone=UTC): if (not isinstance(datestring, _basestring)): raise ParseError(('Expecting a string %r' % datestring)) m = ISO8601_REGEX.match(datestring) if (not m): raise ParseError(('Unable to parse date string %r' % datestring)) groups = m.groupdict(...
class cached_property(Generic[R]): def __init__(self, wrapped: Callable[([Any], R)]): self.wrapped = wrapped functools.update_wrapper(self, wrapped) def __get__(self, instance: T, owner: Type[Any]) -> R: if (instance is None): return self ret = self.wrapped(instance) ...
class InventoryCommand(Command): def __init__(self, quals): super().__init__('INV', 'taking inventory') def help_description(): return 'INVENTORY or INV or I - lists what items you have' def _do_command(self, player): print(('You have %s.' % enumerate_items(player.inv)))
class TransposeLast(nn.Module): def __init__(self, deconstruct_idx=None): super().__init__() self.deconstruct_idx = deconstruct_idx def forward(self, x): if (self.deconstruct_idx is not None): x = x[self.deconstruct_idx] return x.transpose((- 2), (- 1))
def main(): saved_weights = None class_limit = None num_of_snip = 1 image_shape = (224, 224) load_to_memory = False batch_size = 512 nb_epoch = 500 name_str = None train(num_of_snip=num_of_snip, saved_weights=saved_weights, class_limit=class_limit, image_shape=image_shape, load_to_me...
class Fighter(HandledItem, HandledCharge, ItemAttrShortcut, ChargeAttrShortcut): DAMAGE_TYPES = ('em', 'kinetic', 'explosive', 'thermal') DAMAGE_TYPES2 = ('EM', 'Kin', 'Exp', 'Therm') def __init__(self, item): self.__item = item if self.isInvalid: raise ValueError('Passed item is...
def test_twocopy_seperates(tmpdir): learn_states_q.run_and_save(n=5, n_paulis=10, n_sweeps=250, n_shots=250, save_dir=tmpdir, use_engine=False) pauli_files = [f for f in os.listdir(tmpdir) if (os.path.isfile(os.path.join(tmpdir, f)) and ('basis' not in f))] exp_predictions = [] for fname in pauli_files:...
class TestMarkersWithParametrization(): def test_simple_mark(self, pytester: Pytester) -> None: s = '\n import pytest\n\n .foo\n .parametrize(("n", "expected"), [\n (1, 2),\n pytest.param(1, 3, marks=pytest.mark.bar),\n (2, 3),\n ...
def propagate_changes_from_baseline(baseline_dir, alternatives_dir, combi_dir, version_id='', comments=''): version_id += ('_' + datetime.now().strftime('%y%m%d%H%M%S')) model_dirs = [] for alt in os.listdir(alternatives_dir): for imp_level in os.listdir(os.path.join(alternatives_dir, alt)): ...
(tryfirst=True) def pytest_cmdline_main(config: Config) -> Optional[Union[(int, ExitCode)]]: import _pytest.config if config.option.markers: config._do_configure() tw = _pytest.config.create_terminal_writer(config) for line in config.getini('markers'): parts = line.split(':',...
class LinearDecayEnvelope(_Envelope): def __init__(self, peak=1.0): self.peak = max(min(1.0, peak), 0) def get_generator(self, sample_rate, duration): peak = self.peak total_bytes = int((sample_rate * duration)) for i in range(total_bytes): (yield (((total_bytes - i) ...
('/config', methods=['GET', 'OPTIONS']) (anonymous=False) def config(): response = jsonify({'config': frontend_visible_config(app.config), 'features': features.get_features(), 'oauth': get_oauth_config(), 'external_login': get_external_login_config(), 'registry_state': app.config.get('REGISTRY_STATE', 'normal'), 'a...
def sensitivity(tp: torch.LongTensor, fp: torch.LongTensor, fn: torch.LongTensor, tn: torch.LongTensor, reduction: Optional[str]=None, class_weights: Optional[List[float]]=None, zero_division: Union[(str, float)]=1.0) -> torch.Tensor: return _compute_metric(_sensitivity, tp, fp, fn, tn, reduction=reduction, class_w...
def sigmoid_focal_loss(pred, target, weight=None, gamma=2.0, alpha=0.25, reduction='mean', avg_factor=None): loss = _sigmoid_focal_loss(pred, target, gamma, alpha) if (weight is not None): weight = weight.view((- 1), 1) loss = weight_reduce_loss(loss, weight, reduction, avg_factor) return loss
class NamespaceGCWorker(QueueWorker): def process_queue_item(self, job_details): try: with GlobalLock('LARGE_GARBAGE_COLLECTION', lock_ttl=(NAMESPACE_GC_TIMEOUT + LOCK_TIMEOUT_PADDING)): self._perform_gc(job_details) except LockNotAcquiredException: logger.deb...
def get_contractreceivechannelnew_data_from_event(chain_state: ChainState, event: DecodedEvent) -> Optional[NewChannelDetails]: token_network_address = TokenNetworkAddress(event.originating_contract) data = event.event_data args = data['args'] participant1 = args['participant1'] participant2 = args[...
class Effect5308(BaseEffect): type = 'passive' def handler(fit, ship, context, projectionRange, **kwargs): fit.modules.filteredChargeBoost((lambda mod: mod.charge.requiresSkill('Light Missiles')), 'aoeVelocity', ship.getModifiedItemAttr('shipBonusCD2'), skill='Caldari Destroyer', **kwargs)
class SchedulePreviewSection(): id: strawberry.ID title: str primary_cta: (CTA | None) secondary_cta: (CTA | None) def from_block(cls, block) -> Self: primary_cta = block.value['primary_cta'] secondary_cta = block.value['secondary_cta'] return cls(id=block.id, title=block.val...
class ModelRes512(nn.Module): def __init__(self, res_base_model): super(ModelRes512, self).__init__() self.resnet_dict = {'resnet50': models.resnet50(pretrained=True)} self.resnet = self._get_res_basemodel(res_base_model) num_ftrs = int(self.resnet.fc.in_features) self.res_fe...
def test_jsonify_roundtrip_sequence(): yaml_string = " a: 1\n b: '1'\n c: !jsonify\n - v1\n - 22\n - 123.45\n - a: a value\n b: 123\n d: False\n " yaml = get_yaml_with_js...
def add_data_to_storage(storage_list, subject_data, brain_width, tumor_width, truth_dtype, modality_names): (modality_storage_list, truth_storage, brain_width_storage, tumor_width_storage) = storage_list for i in range(len(modality_names)): if (modality_storage_list[i].name != modality_names[i]): ...
.parametrize('projdir_type', [str, Path]) def test_get_data_dir__from_user(projdir_type, tmp_path): tmpdir = (tmp_path / 'proj') tmpdir.mkdir() tmpdir_env = (tmp_path / 'proj_env') tmpdir_env.mkdir() with proj_env(), patch.dict(os.environ, {'PROJ_DATA': str(tmpdir_env)}, clear=True), patch('pyproj.d...
def align_and_update_state_dicts(model_state_dict, loaded_state_dict): current_keys = sorted(list(model_state_dict.keys())) loaded_keys = sorted(list(loaded_state_dict.keys())) match_matrix = [(len(j) if i.endswith(j) else 0) for i in current_keys for j in loaded_keys] match_matrix = torch.as_tensor(mat...
.parametrize('val, offset', [(set_test_value(pt.matrix(), np.arange((10 * 10), dtype=config.floatX).reshape((10, 10))), 0), (set_test_value(pt.matrix(), np.arange((10 * 10), dtype=config.floatX).reshape((10, 10))), (- 1)), (set_test_value(pt.vector(), np.arange(10, dtype=config.floatX)), 0)]) def test_ExtractDiag(val, ...
def train(args, model, rank, world_size, train_loader, optimizer, epoch, sampler=None): model.train() local_rank = int(os.environ['LOCAL_RANK']) fsdp_loss = torch.zeros(2).to(local_rank) if sampler: sampler.set_epoch(epoch) if (rank == 0): inner_pbar = tqdm.tqdm(range(len(train_loade...
(scope='session') def browser_instance_getter(browser_patches, splinter_session_scoped_browser, splinter_browser_load_condition, splinter_browser_load_timeout, splinter_download_file_types, splinter_driver_kwargs, splinter_file_download_dir, splinter_firefox_profile_preferences, splinter_firefox_profile_directory, spli...
class Window(QWidget): NumRenderAreas = 9 def __init__(self): super(Window, self).__init__() rectPath = QPainterPath() rectPath.moveTo(20.0, 30.0) rectPath.lineTo(80.0, 30.0) rectPath.lineTo(80.0, 70.0) rectPath.lineTo(20.0, 70.0) rectPath.closeSubpath() ...
class ChannelRounder(CompRatioRounder): def __init__(self, multiplicity: int): self._multiplicity = multiplicity def round(self, layer: Layer, comp_ratio: Decimal, cost_metric: CostMetric) -> Decimal: if (self._multiplicity == 1): updated_comp_ratio = comp_ratio else: ...
class RTorrentMethod(object): NEEDS_FAKE_TARGET = set(('ui.current_view.set', 'view_filter')) def __init__(self, proxy, method_name): self._proxy = proxy self._method_name = method_name def __getattr__(self, attr): self._method_name += ('.' + attr) return self def __str__...
class PlayerOptions(GObject.Object): __gproperties__ = {'shuffle': (bool, '', '', False, (GObject.ParamFlags.READABLE | GObject.ParamFlags.WRITABLE)), 'repeat': (bool, '', '', False, (GObject.ParamFlags.READABLE | GObject.ParamFlags.WRITABLE)), 'single': (bool, '', '', False, (GObject.ParamFlags.READABLE | GObject....
def highlight_x(ax, highlight_range, highlight_color='magenta', label=None): rect = patches.Rectangle((highlight_range[0], 0), (highlight_range[1] - highlight_range[0]), ax.get_ylim()[1], facecolor=highlight_color, edgecolor='none', alpha=0.5) ax.add_patch(rect) if (label is not None): ax.text((high...
def monitor(subcommand, dormant_after: float, dormant_signal: int, kill_after: float, kill_signal: int) -> int: (parent_read, child_stdout_write) = os.pipe() child_stderr_write = os.dup(child_stdout_write) process = subprocess.Popen(subcommand, stdin=subprocess.DEVNULL, stdout=child_stdout_write, stderr=chi...
class UserViewSet(UserViewSetMixin, ReadOnlyModelViewSet): permission_classes = ((HasModelPermission | HasObjectPermission),) serializer_class = UserSerializer filter_backends = (DjangoFilterBackend,) filterset_fields = ('username', 'first_name', 'last_name', 'email', 'groups') def get_queryset(self...
def extract_declaration_for(function_name): code = list(reversed(_extract_code(function_name))) for line in code: if ((function_name in line) and (not is_comment_line(line))): pos = line.find(function_name) if ('=' in line[:pos]): break else: return No...
def test_param_storage(tmpdir): with tmpdir.as_cwd(): mol = Ligand.from_file(get_data('chloromethane.pdb')) OpenFF().run(mol) with pytest.raises(ValidationError): mol.NonbondedForce.create_parameter(atoms=(0,), charge=0.1) mol.NonbondedForce.create_parameter(atoms=(0,), c...
def train_image_parse_function(filename, *argv): image = read_image(filename) image = tf.image.random_flip_left_right(image) if FLAGS.augmentation: print('data augmentation') resized_image = resize_and_random_crop_image(image) else: resized_image = resize_image(image) resized...
def reorder_image(img, input_order='HWC'): if (input_order not in ['HWC', 'CHW']): raise ValueError(f"Wrong input_order {input_order}. Supported input_orders are 'HWC' and 'CHW'") if (len(img.shape) == 2): img = img[(..., None)] if (input_order == 'CHW'): img = img.transpose(1, 2, 0)...
class MultiResolutionExtractor(ExtractorBase): def __init__(self, features, patch_mode='replicate', max_scale_change=None): super().__init__(features) self.patch_mode = patch_mode self.max_scale_change = max_scale_change self.is_color = None def stride(self): return torch...
def test_cross_compiled_build(tmp_path): if (utils.platform != 'macos'): pytest.skip('this test is only relevant to macos') if (get_xcode_version() < (12, 2)): pytest.skip('this test only works with Xcode 12.2 or greater') project_dir = (tmp_path / 'project') basic_project.generate(proje...
def uc_refine_hardcode(binary_mask, uncertainty_map, img, threshold_uc=0.2, fn_alpha=0.5, fn_beta=0.7, fp_alpha=0.5, fp_beta=0.7): img_avg = np.mean(img, axis=2) mean_value = np.mean((img_avg * binary_mask[0])) print('the mean value is:', mean_value) uc_threshold = (np.min(uncertainty_map) + (threshold_...
def _build_line(colwidths, colaligns, linefmt): if (not linefmt): return None if hasattr(linefmt, '__call__'): return linefmt(colwidths, colaligns) else: (begin, fill, sep, end) = linefmt cells = [(fill * w) for w in colwidths] return _build_simple_row(cells, (begin, ...
.parametrize('input_type', [tuple, list]) def test_run_model_from_effective_irradiance_arrays(sapm_dc_snl_ac_system_Array, location, weather, total_irrad, input_type): data = weather.copy() data[['poa_global', 'poa_diffuse', 'poa_direct']] = total_irrad data['effective_irradiance'] = data['poa_global'] ...
def pipeThroughEspeak(inpt): assert (type(inpt) == bytes) bufsize = 8192 ret = [] while (len(inpt) > bufsize): splitAt = (inpt.rfind('\n', 0, bufsize) + 1) if (not splitAt): splitAt = (inpt.rfind(' ', 0, bufsize) + 1) if (not splitAt): sys.stderr.w...
def drop_path(x, drop_prob=0.0, training=False): if ((drop_prob == 0.0) or (not training)): return x keep_prob = (1 - drop_prob) shape = ((x.shape[0],) + ((1,) * (x.ndim - 1))) random_tensor = (keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)) output = (x.div(keep_prob) * random...
def test_one_item_host_limit(capsys, root_dir): memory_limit = sizeof(asproxy(one_item_array(), serializers=('dask', 'pickle'))) dhf = ProxifyHostFile(worker_local_directory=root_dir, device_memory_limit=one_item_nbytes, memory_limit=memory_limit) a1 = (one_item_array() + 1) a2 = (one_item_array() + 2) ...
class ResNet(nn.Module): def __init__(self, block, layers, strides, dilations, num_classes=1000): self.inplanes = 64 super(ResNet, self).__init__() self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = nn.BatchNorm2d(64) self.relu = nn.ReLU(...
class NYStylePepperoniPizza(Pizza): def __init__(self): self.name = 'NY Style Pepperoni Pizza' self.dough = 'Thin Crust Dough' self.sauce = 'Marinara Sauce' self.toppings = [] self.toppings.append('Grated Reggiano Cheese') self.toppings.append('Sliced Pepperoni') ...
class TestMultiProcessingReadingService(TestCase): _ctx_parametrize ('dp_fn', [subtest(_non_dispatching_dp, 'non_dispatch'), subtest(_dispatching_dp, 'dispatch')]) ('main_prefetch', [0, 10]) ('worker_prefetch', [0, 10]) def test_early_exit(self, ctx, dp_fn, main_prefetch, worker_prefetch) -> None: ...
(short_help='Show the contents of the config file') ('--all', '-a', 'all_keys', is_flag=True, help='Do not scrub secret fields') _obj def show(app, all_keys): if (not app.config_file.path.is_file()): app.display_critical('No config file found! Please try `hatch config restore`.') else: from rich...
class Discriminator(nn.Module): def __init__(self, sigmoid=False): super(Discriminator, self).__init__() self.sigmoid = sigmoid self.conv1 = nn.Conv2d(3, 64, 3, stride=1, padding=1) self.conv2 = nn.Conv2d(64, 64, 3, stride=2, padding=1) self.bn2 = nn.BatchNorm2d(64) s...
class AdditiveAttention2D(AdditiveAttention): def forward(self, s, h): s_attention = s.matmul(self.w_attention_matrix).unsqueeze(2) h_attention = h.matmul(self.u_attention_matrix).unsqueeze(1) seq_len = h.size(1) h_attention = h_attention.expand((- 1), seq_len, (- 1), (- 1)) ...
_model_architecture('hf_gpt2', 'hf_gpt2') def default_architecture(args): if (getattr(args, 'max_target_positions', None) is None): args.max_target_positions = getattr(args, 'tokens_per_sample', DEFAULT_MAX_TARGET_POSITIONS) args.embed_dim = getattr(args, 'embed_dim', 768) args.num_attention_heads =...
def capsule_sdf_grad(radius: float, half_width: float, p: wp.vec3): if (p[0] > half_width): return normalize(wp.vec3((p[0] - half_width), p[1], p[2])) if (p[0] < (0.0 - half_width)): return normalize(wp.vec3((p[0] + half_width), p[1], p[2])) return normalize(wp.vec3(0.0, p[1], p[2]))
class Subscrib_signup_repos_Handler(BaseHandler): .authenticated async def get(self, userid): user = self.current_user if ((user['id'] == int(userid)) and (user['role'] == u'admin')): (await self.render('pubtpl_register.html', userid=userid)) else: (await self.ren...
class TestQcQuantizeOp(): def test_update_stats_with_pymo(self): input_arr = np.random.rand(1, 3, 4, 4).astype(np.float32) tensor_quantizer = libpymo.TensorQuantizer(MAP_QUANT_SCHEME_TO_PYMO[QuantScheme.post_training_tf], MAP_ROUND_MODE_TO_PYMO['stochastic']) cpp_encodings = libpymo.TfEncodi...