code
stringlengths
281
23.7M
() ('-wmt') ('-lang') ('-sys_name') ('-src_ref', help='src or ref') ('-loaded', type=bool, default=False) ('-ckpt_addr', help='LLama_finetune_april_8/checkpoint-148', default=None) ('-start_index', type=int) ('-end_index', type=int) ('-batch_size', type=int) ('-sample', type=bool) ('-num_ret', type=int) ('-task_mode', ...
def brush_stroke_mask(img, color=(255, 255, 255)): min_num_vertex = 8 max_num_vertex = 28 mean_angle = ((2 * math.pi) / 5) angle_range = ((2 * math.pi) / 15) min_width = 12 max_width = 80 def generate_mask(H, W, img=None): average_radius = (math.sqrt(((H * H) + (W * W))) / 8) ...
class DeformConv2dPackMore(DeformConv2d): def __init__(self, in_channels, out_channels, kernel_size, stride, padding, dilation=1, groups=1, deformable_groups=1, im2col_step=64, bias=True, lr_mult=0.1): super(DeformConv2dPackMore, self).__init__(in_channels, out_channels, kernel_size, stride, padding, dilati...
def main(_): if (not FLAGS.output_file): raise ValueError('You must supply the path to save to with --output_file') tf.logging.set_verbosity(tf.logging.INFO) with tf.Graph().as_default() as graph: dataset = dataset_factory.get_dataset(FLAGS.dataset_name, 'train', FLAGS.dataset_dir) n...
def test_repair_destroy_path(): (x, y, z) = inputs() e1 = transpose_view(transpose_view(x)) e2 = transpose_view(transpose_view(e1)) e3 = add_in_place(e2, y) e4 = add_in_place(e1, z) g = create_fgraph([x, y, z], [e3, e4], False) assert (not g.consistent()) g.replace(e2, transpose_view(x))...
def apply_to_tensor(f, sample): if (len(sample) == 0): return {} def _apply(x): if torch.is_tensor(x): return f(x) elif isinstance(x, dict): return {key: _apply(value) for (key, value) in x.items()} elif isinstance(x, list): return [_apply(x) f...
.end_to_end() def test_if_skipif_decorator_is_applied_skipping(tmp_path): source = '\n import pytask\n\n .skipif(condition=True, reason="bla")\n .produces("out.txt")\n def task_first():\n assert False\n\n .depends_on("out.txt")\n def task_second():\n assert False\n ' tmp_path....
class BooleanTest(object): def test_false(self): assert (inputs.boolean('False') is False) def test_0(self): assert (inputs.boolean('0') is False) def test_true(self): assert (inputs.boolean('true') is True) def test_1(self): assert (inputs.boolean('1') is True) def t...
class RollingVirtualStorage(Loadable, Drawable, _core.RollingVirtualStorage, metaclass=NodeMeta): __parameter_attributes__ = ('min_volume', 'max_volume') __node_attributes__ = ('nodes',) def __init__(self, model, name, nodes, **kwargs): min_volume = pop_kwarg_parameter(kwargs, 'min_volume', 0.0) ...
def adjust_assets(scenes): sim = None global_mapping_path = 'cos_eor/utils/global_mapping_v3_local.yaml' if (os.path.exists(global_mapping_path) and False): global_mapping = yaml.load(open(global_mapping_path, 'r'), Loader=yaml.BaseLoader) else: global_mapping = {'mapping_igib': {}, 'sce...
def get_price(plan, require_business_plan): if (not features.BILLING): return plan_found = None for plan_obj in PLANS: if (plan_obj['stripeId'] == plan): plan_found = plan_obj if ((not plan_found) or plan_found['deprecated']): logger.warning('Plan not found or depreca...
def test_transform_types_not_params_array(): data = {'attr': [1, 2, 3]} custom_types = {'attr': types.ArrayAttribute} (new_data, files) = utils._transform_types(data, custom_types, transform_data=False) assert (new_data is not data) assert (new_data == data) assert (files == {})
def create_report(seeds_dir: str, output_file: Path): def item_creator(): return collections.defaultdict(list) item_name_to_location = collections.defaultdict(item_creator) seed_files = list(Path(seeds_dir).glob(f'**/*.{LayoutDescription.file_extension()}')) seed_files.extend(Path(seeds_dir).glo...
def get_release_notes_template(template_dir: Path) -> str: fname = (template_dir / '.release_notes.md.j2') try: return fname.read_text(encoding='utf-8') except FileNotFoundError: return files('semantic_release').joinpath('data/templates/release_notes.md.j2').read_text(encoding='utf-8')
class RateLimitError(APIError): def __init__(self, *args, **kwargs): self.response_headers = kwargs.pop('response_headers', None) self.rl_limit = int(self.response_headers.get('X-Ratelimit-Limit')) self.rl_reset = datetime.fromtimestamp(int(self.response_headers.get('X-Ratelimit-Reset'))) ...
def ksboolean(value): try: if (value.lower() in ('on', 'yes', 'true', '1')): return True elif (value.lower() in ('off', 'no', 'false', '0')): return False else: raise ArgumentTypeError((_('invalid boolean value: %r') % value)) except AttributeError: ...
class EthicsUtilitarianism(Ethics): VERSION = 0 DATASET_NAME = 'utilitarianism' def training_docs(self): for doc in self.dataset['train']: (yield self._process_doc(doc)) def validation_docs(self): raise NotImplementedError def test_docs(self): for doc in self.data...
class ResAttNet(nn.Module): def __init__(self, channels, init_block_channels, attentions, att_scales, in_channels=3, in_size=(224, 224), num_classes=1000): super(ResAttNet, self).__init__() self.in_size = in_size self.num_classes = num_classes self.features = nn.Sequential() ...
(frozen=True) class AM2RPerGameOptions(PerGameOptions): input_path: (Path | None) = None output_path: (Path | None) = None def as_json(self) -> dict: return {**super().as_json, 'input_path': (str(self.input_path) if (self.input_path is not None) else None), 'output_path': (str(self.output_path) if (...
_torch _vision class GLPNImageProcessingTest(ImageProcessingSavingTestMixin, unittest.TestCase): image_processing_class = (GLPNImageProcessor if is_vision_available() else None) def setUp(self): self.image_processor_tester = GLPNImageProcessingTester(self) def image_processor_dict(self): ret...
def init(app_name): global APP_NAME, DBUS_IFACE APP_NAME = app_name name = 'org.freedesktop.Notifications' path = '/org/freedesktop/Notifications' interface = 'org.freedesktop.Notifications' mainloop = None if (DBusGMainLoop is not None): mainloop = DBusGMainLoop(set_as_default=True)...
def test_list_type(): test_dict = {'type': 'list', 'values': {'type': 'int', 'bits': 32}} recap_type = from_dict(test_dict) assert isinstance(recap_type, ListType) assert (recap_type.type_ == 'list') assert isinstance(recap_type.values, IntType) assert (recap_type.values.type_ == 'int') asse...
class DcardPost(Base, Timestamp): __tablename__ = 'dcard_posts' id = sa.Column(sa.Integer, primary_key=True) forum_id = sa.Column(sa.String(64), nullable=False) forum_name = sa.Column(sa.String(64), nullable=False) title = sa.Column(sa.String(64, collation='utf8mb4_unicode_ci'), nullable=False) ...
def test_parser(testcase: DataDrivenTestCase) -> None: options = Options() options.force_uppercase_builtins = True options.hide_error_codes = True if testcase.file.endswith('python310.test'): options.python_version = (3, 10) else: options.python_version = defaults.PYTHON3_VERSION ...
def boundary_err(y_pred, y_true, t, onsets_s, offsets_s, timebin_dur, n_timebin_from_onoffset, unlabeled_class=0): frame_err_vec = (y_true != y_pred) n_frame_err = int(frame_err_vec.sum().item()) unlabeled_err = np.logical_and(frame_err_vec, np.logical_or((y_true == unlabeled_class), (y_pred == unlabeled_cl...
def _input(): print('Enter the visa centre: ') visa_centre = input() print('Enter the category: ') category = input() print('Enter the sub category: ') sub_category = input() logging.debug('Visa centre: {}, Category: {}, Sub-Category: {}'.format(visa_centre, category, sub_category)) retu...
def initShaders(): global Shaders Shaders = [ShaderProgram(None, []), ShaderProgram('balloon', [VertexShader('\n varying vec3 normal;\n void main() {\n // compute here for use in fragment shader\n normal = normalize(gl_NormalMatrix * gl_Normal)...
class PD(nn.Module): def __init__(self, nf=64, groups=8): super(PD, self).__init__() self.L3_offset_conv2 = nn.Conv2d(nf, nf, 3, 1, 1, bias=True) self.L3_dcnpack = DCN(nf, nf, 3, stride=1, padding=1, dilation=1, deformable_groups=groups, extra_offset_mask=True) self.L2_offset_conv2 =...
class TestSequenceGeneratorBase(unittest.TestCase): def assertHypoTokens(self, hypo, tokens): self.assertTensorEqual(hypo['tokens'], torch.LongTensor(tokens)) def assertHypoScore(self, hypo, pos_probs, normalized=True, lenpen=1.0): pos_scores = torch.FloatTensor(pos_probs).log() self.ass...
class Detect(nn.Module): def __init__(self, num_classes=80, anchors=1, num_layers=3, inplace=True, head_layers=None, use_dfl=True, reg_max=16): super().__init__() assert (head_layers is not None) self.nc = num_classes self.no = (num_classes + 5) self.nl = num_layers i...
def fallback_version(root: _t.PathT, config: Configuration) -> (ScmVersion | None): if (config.parentdir_prefix_version is not None): (_, parent_name) = os.path.split(os.path.abspath(root)) if parent_name.startswith(config.parentdir_prefix_version): version = tag_to_version(parent_name[l...
('pypyr.venv.EnvBuilderWithExtraDeps') def test_venv_create(mock_builder): context = get_simple_context() mocked_builder = mock_builder.return_value mocked_builder.context = context venv.run_step(Context({'venv': '/arb'})) expected_path = str(Path('/arb').expanduser().resolve()) mocked_builder.c...
((os.name == 'nt'), 'BNG Console does not work on Windows') _model def test_simulate_network_console(): Monomer('A') Parameter('A_0', 1) Initial(A(), A_0) Parameter('k', 1) Rule('degrade', (A() >> None), k) with BngConsole(model) as bng: bng.generate_network() bng.action('simulat...
def convert_file_size_to_str(total: int) -> str: if (total < (1 << 10)): size = '{:.2f} B'.format(total) elif (total < (1 << 20)): size = '{:.2f} K'.format((total / (1 << 10))) elif (total < (1 << 30)): size = '{:.2f} M'.format((total / (1 << 20))) else: size = '{:.2f} G'...
def train(train_loader, model, criterions, optimizer, epoch): model.train() batch_time = AverageMeter() data_time = AverageMeter() loss_protest = AverageMeter() loss_v = AverageMeter() protest_acc = AverageMeter() violence_mse = AverageMeter() visattr_acc = AverageMeter() end = time....
class GPTNeoXJapaneseTokenizer(PreTrainedTokenizer): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES model_input_names = ['input_ids', 'attention_mask'] def __init__(self, vocab_file, emoji_f...
def unpack(compressed): uncompressed = np.zeros((compressed.shape[0] * 8), dtype=np.uint8) uncompressed[::8] = ((compressed[:] >> 7) & 1) uncompressed[1::8] = ((compressed[:] >> 6) & 1) uncompressed[2::8] = ((compressed[:] >> 5) & 1) uncompressed[3::8] = ((compressed[:] >> 4) & 1) uncompressed[4...
class IASIL2SO2BUFR(BaseFileHandler): def __init__(self, filename, filename_info, filetype_info, **kwargs): super(IASIL2SO2BUFR, self).__init__(filename, filename_info, filetype_info) (start_time, end_time) = self.get_start_end_date() sc_id = self.get_attribute('satelliteIdentifier') ...
class SawyerCoffeePullV1Policy(Policy): _fully_parsed def _parse_obs(obs): return {'hand_pos': obs[:3], 'mug_pos': obs[3:6], 'unused_info': obs[6:]} def get_action(self, obs): o_d = self._parse_obs(obs) action = Action({'delta_pos': np.arange(3), 'grab_effort': 3}) action['de...
def get_packer_mapping(packers, task): packer_mapping = {} for (rec_id, packer) in packers.items(): obj_keys = [task.sim_obj_id_to_obj_key[obj_key] for obj_key in list(packer.matches.keys())] rec_key = task.sim_obj_id_to_obj_key[rec_id] for obj_key in obj_keys: packer_mapping...
def evaluate(args, model, tokenizer, criterion, prefix=''): eval_output_dir = args.output_dir eval_dataset = load_examples(args, tokenizer, evaluate=True) if ((not os.path.exists(eval_output_dir)) and (args.local_rank in [(- 1), 0])): os.makedirs(eval_output_dir) args.eval_batch_size = (args.per...
class PluginMethods(PluginActions): def register_function(self, function, inputs, parameters, outputs, name, description, input_descriptions=None, parameter_descriptions=None, output_descriptions=None, citations=None, deprecated=False, examples=None): if (citations is None): citations = () ...
class RateLimiterBackendTests(): def setUp(self): self.allowance = 10 self.interval = 1 ratelimiter_factory = RateLimiterContextFactory(self.backend_factory, self.allowance, self.interval) self.baseplate_observer = TestBaseplateObserver() baseplate = Baseplate() basep...
def main(): parser = argparse.ArgumentParser() parser.add_argument('path', help='Path to result .json file as produced by 3D evaluation script. Can be downloaded from the evaluation server for test set results.') args = parser.parse_args() if (not os.path.exists(args.path)): raise Exception('Res...
class PytestArg(): def __init__(self, request: FixtureRequest) -> None: self._request = request def gethookrecorder(self, hook) -> 'HookRecorder': hookrecorder = HookRecorder(hook._pm) self._request.addfinalizer(hookrecorder.finish_recording) return hookrecorder
class StreamReset(Event): def __init__(self): self.stream_id = None self.error_code = None self.remote_reset = True def __repr__(self): return ('<StreamReset stream_id:%s, error_code:%s, remote_reset:%s>' % (self.stream_id, self.error_code, self.remote_reset))
class tensorboard_log_wrapper(progress_bar): def __init__(self, wrapped_bar, tensorboard_logdir, args): self.wrapped_bar = wrapped_bar self.tensorboard_logdir = tensorboard_logdir self.args = args try: from tensorboardX import SummaryWriter self.SummaryWriter ...
class TestParticleNumber(PropertyTest): def setUp(self): super().setUp() num_spatial_orbitals = 4 self.prop = ParticleNumber(num_spatial_orbitals) def test_second_q_ops(self): ops = self.prop.second_q_ops()['ParticleNumber'] expected = {'+_0 -_0': 1.0, '+_1 -_1': 1.0, '+_...
class TestTransformerStretch(unittest.TestCase): def test_default(self): tfm = new_transformer() tfm.stretch(1.1) actual_args = tfm.effects expected_args = ['stretch', '1.100000', '20.000000'] self.assertEqual(expected_args, actual_args) actual_log = tfm.effects_log ...
def abort_current_continuation(args, env, cont): from pycket.interpreter import return_multi_vals if (not args): raise SchemeException('abort-current-continuation: expected 1 or more args') (tag, args) = (args[0], args[1:]) if (not isinstance(tag, values.W_ContinuationPromptTag)): raise ...
class InceptionResnetV2(nn.Module): def __init__(self, num_classes=1000, in_chans=3, drop_rate=0.0, output_stride=32, global_pool='avg'): super(InceptionResnetV2, self).__init__() self.drop_rate = drop_rate self.num_classes = num_classes self.num_features = 1536 assert (outpu...
class ThriftContextFactory(ContextFactory): POOL_PREFIX = 'thrift_client_pool' POOL_LABELS = ['thrift_pool'] max_connections_gauge = Gauge(f'{POOL_PREFIX}_max_size', 'Maximum number of connections in this thrift pool before blocking', POOL_LABELS) active_connections_gauge = Gauge(f'{POOL_PREFIX}_active_...
class CellB(nn.Module): def __init__(self, in_planes, out_planes, stride=1): super(CellB, self).__init__() self.stride = stride self.sep_conv1 = SepConv(in_planes, out_planes, kernel_size=7, stride=stride) self.sep_conv2 = SepConv(in_planes, out_planes, kernel_size=3, stride=stride) ...
class Model(object): def __init__(self): self.history = False def present(self): return (self.conf['state']['imu.rate'] * self.conf['past']) def receive(self, name, value): if ((name in self.conf['sensors']) and self.enabled): self.inputs[name] = norm_sensor(name, value)
class LassoXmlLexer(DelegatingLexer): name = 'XML+Lasso' aliases = ['xml+lasso'] version_added = '1.6' alias_filenames = ['*.xml', '*.lasso', '*.lasso[89]', '*.incl', '*.inc', '*.las'] mimetypes = ['application/xml+lasso'] url = ' def __init__(self, **options): super().__init__(XmlLe...
class ModelArguments(): model_name_or_path: str = field(metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'}) config_name: Optional[str] = field(default=None, metadata={'help': 'Pretrained config name or path if not the same as model_name'}) tokenizer_name: Optional[s...
def test_search__with_annotations(requests_mock): requests_mock.get(f'{API_V1}/observations', json=SAMPLE_DATA['get_observation_with_ofvs'], status_code=200) requests_mock.get(f'{API_V1}/controlled_terms', json=SAMPLE_DATA['get_controlled_terms'], status_code=200) results = iNatClient().observations.search(...
def measure_peak_memory_cpu(function: Callable[([], None)], interval=0.5, device_idx=None) -> int: def get_cpu_memory(process_id: int) -> int: process = psutil.Process(process_id) try: meminfo_attr = ('memory_info' if hasattr(process, 'memory_info') else 'get_memory_info') me...
class BenchmarkMainComplex(): params = [['parallel', 'sequential'], ['basic', 'rule154', 'fig16'], ['local', 'redis']] param_names = ['mode', 'network', 'cache'] timer = timeit.default_timer number = 1 repeat = 1 timeout = 10000 def setup(self, mode, network, cache): if (network == '...
def evaluate(args): tokenizer = BertTokenizer.from_pretrained('bert-base-uncased', do_lower_case=True) model = BertAbs.from_pretrained('remi/bertabs-finetuned-extractive-abstractive-summarization') model.to(args.device) model.eval() symbols = {'BOS': tokenizer.vocab['[unused0]'], 'EOS': tokenizer.vo...
class GraphClassificationDataset(GraphDataset): def __init__(self, graphs, labels): super().__init__(graphs) self.labels = labels assert (len(graphs) == len(labels)) def __getitem__(self, index): return (self.graphs[index], self.labels[index]) def collate_fn(batch): (...
class UnetBottleneck(nn.Module): def __init__(self, inplanes, planes, kernel_size=3, dilation=1, act_type='relu'): super(UnetBottleneck, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=kernel_size, stride=1, padding=get_same_padding(kernel_size, dilation), dilation=dilation) ...
def test_opdm_to_ohdm_mapping(): db = opdm_to_ohdm_mapping(6) for dbe in db: assert isinstance(dbe, DualBasisElement) assert (set(dbe.primal_tensors_names) == {'ck', 'kc'}) if (len(dbe.primal_tensors_names) == 4): assert np.allclose(dbe.primal_coeffs, 0.5) assert ...
def log(s, with_prefix=True, with_timestamp=True, color=None): out = s if with_prefix: out = (_prefix_str + out) if with_timestamp: now = datetime.datetime.now(dateutil.tz.tzlocal()) timestamp = now.strftime('%Y-%m-%d %H:%M:%S.%f %Z') out = ('%s | %s' % (timestamp, out)) ...
class VAEAugExperiment(object): def __init__(self, config): self.config = config self.device = self._get_device() self.writer = SummaryWriter(os.path.join(self.config['save_dir'], self.config['vae_mode'], 'tensorboard')) self.nt_xent_criterion = NTXentLoss(self.device, **config['loss...
.parametrize(('metroids', 'stronger_metroids', 'bosses', 'artifacts'), [(False, False, True, 5), (False, True, False, 15), (True, False, True, 40), (True, True, True, 40)]) def test_msr_artifact_pool_should_throw_on_invalid_config(msr_game_description, metroids, stronger_metroids, bosses, artifacts): configuration ...
def set_app_menu(app_menu_list): class InternalMenu(): def __init__(self, title, parent): self.m = AppKit.NSMenu.alloc().init() self.item = AppKit.NSMenuItem.alloc().init() self.item.setSubmenu_(self.m) if (not isinstance(parent, self.__class__)): ...
class PLMInputFeatures(InputFeatures): def __init__(self, *_, perm_mask, target_mapping, **kwargs): super().__init__(**kwargs) self.perm_mask = perm_mask self.target_mapping = target_mapping def pretty_print(self, tokenizer): return (((super().pretty_print(tokenizer) + '\n') + f'...
class TaskSetTimeHandler(TaskNewHandler): .authenticated async def get(self, taskid): user = self.current_user task = self.check_permission((await self.db.task.get(taskid, fields=('id', 'userid', 'tplid', 'disabled', 'note', 'ontime', 'ontimeflg', 'newontime'))), 'w') newontime = json.lo...
class SelectOnRemove(MappingType): MAPPING = {'prev': (QTabBar.SelectionBehavior.SelectLeftTab, 'Select the tab which came before the closed one (left in horizontal, above in vertical).'), 'next': (QTabBar.SelectionBehavior.SelectRightTab, 'Select the tab which came after the closed one (right in horizontal, below ...
class FP16Optimizer(_FP16OptimizerMixin, optim.FairseqOptimizer): def __init__(self, args, params, fp32_optimizer, fp32_params): super().__init__(args) self.fp16_params = params self.fp32_optimizer = fp32_optimizer self.fp32_params = fp32_params if (getattr(args, 'fp16_scale_...
def find_extremes(cluster_list, dataset, jaccard_threshold): global _shared_dataset _shared_dataset = dataset extremes_list = [] f = partial(_find_cluster_extremes_shared, jaccard_threshold=jaccard_threshold) with mp.Pool() as pool: for extremes in tqdm(pool.imap_unordered(f, cluster_list), ...
class DefinitionWideFormat(sphinx_jsonschema.wide_format.WideFormat): def _objecttype(self, schema): rows = self._simpletype(schema) rows.extend(self._objectproperties(schema, 'definition')) rows.extend(self._objectproperties(schema, 'properties')) rows.extend(self._objectproperties(...
class SimclrInfoNCECriterion(nn.Module): def __init__(self, buffer_params, temperature: float): super(SimclrInfoNCECriterion, self).__init__() self.use_gpu = (get_cuda_device_index() > (- 1)) self.temperature = temperature self.num_pos = 2 self.buffer_params = buffer_params ...
class ReadInputRegistersRequest(ReadRegistersRequestBase): function_code = 4 function_code_name = 'read_input_registers' def __init__(self, address=None, count=None, slave=0, **kwargs): super().__init__(address, count, slave, **kwargs) def execute(self, context): if (not (1 <= self.count...
def deconv2D_layer(l0, name=None, filters=32, kernel_size=3, strides=2, padding='same', activation='relu', kernel_initializer='he_normal'): l = Conv2DTranspose(filters=filters, name=name, kernel_size=kernel_size, strides=strides, padding=padding, activation=activation, kernel_initializer=kernel_initializer)(l0) ...
def test_create_poetry_with_local_config(fixture_dir: FixtureDirGetter) -> None: poetry = Factory().create_poetry(fixture_dir('with_local_config')) assert (not poetry.config.get('virtualenvs.in-project')) assert (not poetry.config.get('virtualenvs.create')) assert (not poetry.config.get('virtualenvs.opt...
def DFOM(pattern, ItemS): count = 0 Nettree = [[[] for i in range(SeqNum)] for k in range(len(pattern))] unit = [[] for k in range(len(pattern))] for i in range(len(pattern)): unit[i] = ItemS[str(pattern[i])] for i in range(SeqNum): for m in range(len(unit[0][i])): bbb = ...
def main(): try: session = saga.Session() print('Connecting...') js = saga.job.Service('pbs+ssh://sierra.futuregrid.org', session=session) print('CONNECTED') jd = saga.job.Description() jd.queue = 'batch' jd.environment = {'RUNTIME': '5'} jd.wall_time_...
def main(): parser = argparse.ArgumentParser(description='Convert model keys') parser.add_argument('src', help='src detectron model path') parser.add_argument('dst', help='save path') parser.add_argument('depth', type=int, help='ResNet model depth') args = parser.parse_args() convert(args.src, a...
.parametrize('const_shape', [(), (1,), (5,), (1, 5), (2, 5)]) .parametrize('op, np_op', [(pt.pow, np.power), (pt.add, np.add)]) def test_local_inline_composite_constants(op, np_op, const_shape): const = np.full(shape=const_shape, fill_value=2.5).astype(config.floatX) x = vector('x') y = vector('y') out ...
class Conv8(nn.Module): def __init__(self): super(Conv8, self).__init__() builder = get_builder() self.convs = nn.Sequential(builder.conv3x3(3, 64, first_layer=True), nn.ReLU(), builder.conv3x3(64, 64), nn.ReLU(), nn.MaxPool2d((2, 2)), builder.conv3x3(64, 128), nn.ReLU(), builder.conv3x3(128...
class ChannelPutSchema(BaseSchema): token_address = AddressField(required=True) partner_address = AddressField(required=True) reveal_timeout = IntegerToStringField(missing=None) settle_timeout = IntegerToStringField(missing=None) total_deposit = IntegerToStringField(default=None, missing=None)
class Effect7074(BaseEffect): type = 'passive' def handler(fit, container, context, projectionRange, **kwargs): level = (container.level if ('skill' in context) else 1) fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Small Disintegrator Specialization')), 'damageMultiplier', (...
class Effect5622(BaseEffect): type = 'passive' def handler(fit, ship, context, projectionRange, **kwargs): fit.modules.filteredItemBoost((lambda mod: (mod.item.group.name == 'Missile Launcher Torpedo')), 'speed', ship.getModifiedItemAttr('shipBonusMB'), skill='Minmatar Battleship', **kwargs)
class RequiredImgAsset(RequiredAssetMixin, BaseRequiredImgAsset, BenefitFeature): class Meta(BaseRequiredImgAsset.Meta, BenefitFeature.Meta): verbose_name = 'Require Image' verbose_name_plural = 'Require Images' def __str__(self): return f'Require image' def as_form_field(self, **kwa...
class DomainGeometricParameters(BaseParameters): def __init__(self, domain, main_param): self.domain = domain self.main_param = main_param if (self.domain != 'separator'): self.prim = ParticleGeometricParameters(domain, 'primary', main_param) self.sec = ParticleGeomet...
def initial_wavefunction(particle): return (((np.exp((((- 1) / (4 * ( ** 2))) * (((particle.x + (100 * A)) ** 2) + (1 * ((particle.y - 250) ** 2))))) / np.sqrt(((2 * np.pi) * ( ** 2)))) * np.exp(((p1_x0 * particle.x) * 1j))) + ((np.exp((((- 1) / (4 * ( ** 2))) * (((particle.x + (100 * A)) ** 2) + (1 * ((particle.y ...
def plot(genotype, filename): g = Digraph(format='pdf', edge_attr=dict(fontsize='20', fontname='times'), node_attr=dict(style='filled', shape='rect', align='center', fontsize='20', height='0.5', width='0.5', penwidth='2', fontname='times'), engine='dot') g.body.extend(['rankdir=LR']) g.node('x_{t}', fillcol...
class Mlp(nn.Module): def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0): super().__init__() out_features = (out_features or in_features) hidden_features = (hidden_features or in_features) self.fc1 = nn.Conv2d(in_features, hidden_fea...
def render_notebook_cells(nbspec: NotebookSpec) -> NbCells: return NbCells(title_cell=_md_nbnode('\n'.join(_get_title_lines(title=nbspec.title, mod=nbspec.module)), cqid='title_cell'), top_imports=_code_nbnode(_IMPORTS, cqid='top_imports'), gate_cells={gspec.cqid: _GateCells(md=_md_nbnode('\n'.join(get_markdown_doc...
def get_extract_label(art_sents, abs_sents): extracted = [] scores = [] indices = list(range(len(art_sents))) for abst in abs_sents: rouges = list(map(compute_rouge_l(reference=abst, mode='r'), art_sents)) ext = max(indices, key=(lambda i: rouges[i])) indices.remove(ext) ...
class Testuser(): def test_min_threshold_dist_from_shapefile(self): f = examples.get_path('columbus.shp') min_d = user.min_threshold_dist_from_shapefile(f) assert (min_d == pytest.approx(0.)) def test_build_lattice_shapefile(self): of = 'lattice.shp' user.build_lattice_sh...
class PFSTS_With_Ksappend(ParserTest): def __init__(self, *args, **kwargs): ParserTest.__init__(self, *args, **kwargs) self.ks = '\nlang en_US\nkeyboard us\nautopart\n' self.ksappend = '\ntimezone America/New_York\n' def setUp(self): ParserTest.setUp(self) (handle, self._...
class Fraction(): def __init__(self, fraction=None, chntext=None): self.fraction = fraction self.chntext = chntext def chntext2fraction(self): (denominator, numerator) = self.chntext.split('') return ((chn2num(numerator) + '/') + chn2num(denominator)) def fraction2chntext(sel...
def evaluate_single_sub(sub_id): truth = nib.load(os.path.joint('../data/preprocessed/HGG', sub_id, 'truth.nii.gz')).get_data() prediction = nib.load(os.path.joint('prediction', sub_id, (sub_id + '.nii.gz'))).get_data() masking_functions = (get_whole_tumor_mask, get_tumor_core_mask, get_enhancing_tumor_mask...
def cast_tensor_type(inputs, src_type, dst_type): if isinstance(inputs, nn.Module): return inputs elif isinstance(inputs, torch.Tensor): return inputs.to(dst_type) elif isinstance(inputs, str): return inputs elif isinstance(inputs, np.ndarray): return inputs elif isin...
def compute_KMM(Xsamples, sigma, noise, l_vec): m = len(Xsamples) Xbar = np.multiply(Xsamples, np.array(np.sqrt(([l_vec] * m)))) Qbar = np.array(([np.sum(np.multiply(Xbar, Xbar), axis=1)] * m)).T distance = ((Qbar + Qbar.T) - (2 * np.dot(Xbar, Xbar.T))) result = ((sigma * np.exp(((- 0.5) * distance)...
def load_from_file(filename): vehicles_loaded = 0 try: with open(filename, 'r') as f: lines = f.readlines() for line in lines: index = 0 index = line.split(',') if (len(index) < 1): continue vehic...
def test_python_tags(wheelpath): newname = tags(str(wheelpath), python_tags='py3') assert (TESTWHEEL_NAME.replace('py2.py3', 'py3') == newname) output_file = (wheelpath.parent / newname) with WheelFile(str(output_file)) as f: output = f.read((f.dist_info_path + '/WHEEL')) assert (output == b...