code
stringlengths
281
23.7M
def convert_to_nominalization(thought): if ('Shawn started' in thought): return "Shawn's initial possession of 5 toys and his receipt of 4 more toys from his parents results in a total of 9 toys. 5 + 4 = 9." if ('There are originally 3 cars' in thought): return 'The original count of 3 cars, wit...
class IBMCloudStorage(_CloudStorage): def __init__(self, context, hostname, is_secure, storage_path, access_key, secret_key, bucket_name, port=None, maximum_chunk_size_mb=None): upload_params = {} connect_kwargs = {'endpoint_url': _build_endpoint_url(hostname, port=port, is_secure=is_secure)} ...
() def daily_update_keywords(day=None): (start_date, end_date) = get_day(day) log.info('Updating KeywordImpression for %s-%s', start_date, end_date) KeywordImpression.objects.using('default').filter(date__gte=start_date, date__lt=end_date).delete() keyword_mapping = defaultdict((lambda : {'decisions': 0...
class ResNet_Auxiliary(nn.Module): def __init__(self, block, num_blocks, num_classes=100): super(ResNet_Auxiliary, self).__init__() self.backbone = CIFAR_ResNet(block, num_blocks, num_classes) self.auxiliary_classifier = Auxiliary_Classifier(block, num_blocks, num_classes) self.final...
def last_n_checkpoints(paths, n, update_based, upper_bound=None): assert (len(paths) == 1) path = paths[0] if update_based: pt_regexp = re.compile('checkpoint_\\d+_(\\d+)\\.pt') else: pt_regexp = re.compile('checkpoint(\\d+)\\.pt') files = PathManager.ls(path) entries = [] fo...
def _check_new_episode_scores(config, db, update_db): info('Checking for new episode scores') shows = db.get_shows(enabled=True) for show in shows: latest_episode = db.get_latest_episode(show) if (latest_episode is not None): info('For show {} ({}), episode {}'.format(show.name, ...
def get_config(): config = get_default_configs() training = config.training training.batch_size = 64 training.n_iters = 2400001 training.snapshot_sampling = True training.sde = 'vesde' training.continuous = True evaluate = config.eval evaluate.num_samples = 50000 evaluate.ckpt_id...
def importGetMutationData(lines): mutaLinesMap = {} currentMutaRef = None currentMutaLines = [] consumedIndices = set() def completeMutaLines(): if ((currentMutaRef is not None) and currentMutaLines): mutaLinesMap[currentMutaRef] = currentMutaLines for (i, line) in enumerate(...
def train_video_predictor(cfg): training_steps = 200000 frames = read_frames_from_dir(f'./images/video/{cfg.image_name}') crop_size = (int((frames[0].shape[(- 2)] * 0.95)), int((frames[0].shape[(- 1)] * 0.95))) train_dataset = FrameSet(frames=frames, crop_size=crop_size) train_loader = DataLoader(tr...
class GaussianMLPPolicy(StochasticPolicy, LasagnePowered, Serializable): def __init__(self, env_spec, hidden_sizes=(32, 32), learn_std=True, init_std=1.0, adaptive_std=False, std_share_network=False, std_hidden_sizes=(32, 32), min_std=1e-06, std_hidden_nonlinearity=NL.tanh, hidden_nonlinearity=NL.tanh, output_nonli...
def test_win_vars_set(windows, xdg_envs): pp = platform.get_platform_paths('pypyr', 'config.yaml') assert (pp == platform.PlatformPaths(config_user=Path('/ch//pypyr/config.yaml'), config_common=[Path('/cc/pypyr/config.yaml'), Path('/cc2/pypyr/config.yaml')], data_dir_user=Path('/dh/pypyr'), data_dir_common=[Pat...
def test_finalize_strict_too_many_args(): (bb, x, y) = _get_bb() (x2, y2) = bb.add(TestTwoBitOp(), ctrl=x, target=y) bb.add_register_allowed = False with pytest.raises(BloqError, match='Finalizing does not accept Soquets.*z.*'): bb.finalize(x=x2, y=y2, z=Soquet(RightDangle, Register('asdf', 1)))
.parametrize('filename, expected', [('foo.bar', 'foo.bar'), ('foo"bar', 'foo%22bar'), ('foo\x00bar', 'foo%00bar'), ('foobar");alert("attack!");', 'foobar%22);alert(%22attack!%22);')]) def test_generate_pdfjs_script(filename, expected): expected_open = 'open("qute://pdfjs/file?filename={}");'.format(expected) ac...
def downsample_conv(in_channels, out_channels, kernel_size, stride=1, dilation=1, first_dilation=None, norm_layer=None): norm_layer = (norm_layer or nn.BatchNorm2d) kernel_size = (1 if ((stride == 1) and (dilation == 1)) else kernel_size) first_dilation = ((first_dilation or dilation) if (kernel_size > 1) e...
def exec_tests(linux: kunit_kernel.LinuxSourceTree, request: KunitExecRequest) -> KunitResult: kunit_parser.print_with_timestamp('Starting KUnit Kernel ...') test_start = time.time() result = linux.run_kernel(args=request.kernel_args, timeout=(None if request.alltests else request.timeout), filter_glob=requ...
_model_spec('named_tuple', 'attrs') def test_generic_mixed_inheritance(model_spec): _spec.decorator class Parent1(*model_spec.bases): a: int _spec.decorator class Parent2(*model_spec.bases, Generic[T]): b: T _spec.decorator class Child12(Parent1, Parent2[str]): c: bool ...
class _Definition(): def __init__(self, *args: _Setting, mandatory: Set[str], prefix: str, switch_names: Mapping[(Optional[str], str)]=None) -> None: self._settings = args self.mandatory = mandatory self.prefix = prefix if (switch_names is not None): self._switch_names = ...
_on_failure .parametrize('number_of_nodes', [3]) .parametrize('channels_per_node', [CHAIN]) def test_receive_lockedtransfer_invalidnonce(raiden_network: List[RaidenService], number_of_nodes, deposit, token_addresses, reveal_timeout, network_wait): (app0, app1, app2) = raiden_network token_address = token_addres...
def get_cast_class(orig_cls, new_base_cls): orig_module = inspect.getmodule(orig_cls) new_cls_name = f'{CAST_CLASS_PREFIX}{orig_cls.__name__}' if hasattr(orig_module, new_cls_name): new_cls = getattr(orig_module, new_cls_name) else: new_cls = type(new_cls_name, (new_base_cls, orig_cls), ...
class Image(SensorData): def __init__(self, frame_number, width, height, image_type, fov, raw_data): super(Image, self).__init__(frame_number=frame_number) assert (len(raw_data) == ((4 * width) * height)) self.width = width self.height = height self.type = image_type ...
_model def resmlp_big_24_224(pretrained=False, **kwargs): model_args = dict(patch_size=8, num_blocks=24, embed_dim=768, mlp_ratio=4, block_layer=partial(ResBlock, init_values=1e-06), norm_layer=Affine, **kwargs) model = _create_mixer('resmlp_big_24_224', pretrained=pretrained, **model_args) return model
class Solution(): def checkSubarraySum(self, nums: List[int], k: int) -> bool: remainders = dict() remainders[0] = 0 pre_sum = 0 for (idx, item) in enumerate(nums): pre_sum += item remaind = (pre_sum % k) if (remaind not in remainders): ...
class Spinner(tqdm): prefixes = ['/', '-', '\\', '|'] def __init__(self, title: str, refresh_interval: float=0.5): def refresh_in_loop(): while (not self._stop.is_set()): with self._lock: self._index = ((self._index + 1) % len(self.prefixes)) ...
class Logger(object): def __init__(self, fpath=None): self.console = sys.stdout self.file = None if (fpath is not None): mkdir_if_missing(osp.dirname(fpath)) self.file = open(fpath, 'w') def __del__(self): self.close() def __enter__(self): pass...
def dumpAST(obj, ind=0, topnode=False): indChar = ((('\t' * ind) + '-> ') if ind else '') print((((indChar + '[') + obj.t) + ']')) if (not (obj.title == '')): print(((('\t' + indChar) + 'Title: ') + (obj.title or ''))) if (not (obj.info == '')): print(((('\t' + indChar) + 'Info: ') + (ob...
def concat_into_splits(dl_dataset, src, tgt, extracted_folders, to_folder, debug): to_folder_tmp = f'{to_folder}_tmp' os.makedirs(to_folder_tmp, exist_ok=True) concat_files('train', src, tgt, extracted_folders, split_urls=dl_dataset.train_urls, path_patterns=dl_dataset.train_files_patterns, to_folder=to_fol...
class TestObject(TestCase): def test_dump_object(self): obj = AllDumpable(AllDumpable()) exp = {'_par_c': 10, 'par_v': None, 'par_p': 12, 'c': 1, '_c': 2, 'c_n': None, '_c_n': None, 'child': None, 'v': 3, '_v': 4, 'v_n': None, '_v_n': None, 'p': 5, '_p': 5, 'p_n': None, '_p_n': None} exp['ch...
class BertCrfForSequenceLabeling(BertPreTrainedModel): def __init__(self, config): super(BertCrfForSequenceLabeling, self).__init__(config) self.bert = BertModel(config) if self.config.use_freezing: self.bert = freezer.freeze_lm(self.bert) self.dropout = nn.Dropout(config...
class Logger(object): def __init__(self, file_name: str=None, file_mode: str='w', should_flush: bool=True): self.file = None if (file_name is not None): self.file = open(file_name, file_mode) self.should_flush = should_flush self.stdout = sys.stdout self.stderr = ...
class File(): def __init__(self, pathspec, *, format=None, optional=False): if (format is None): raise TypeError('Must provide a format.') self.pathspec = pathspec self.format = format self.optional = optional def __get__(self, obj, cls=None): if (obj is None)...
class Test_ab13bd(): A = np.array([[0.0, 1.0], [(- 0.5), (- 0.1)]]) B = np.array([[0.0], [1.0]]) C = np.eye(2) D = np.zeros((2, 1)) (Ad, Bd, Cd, Dd, dt) = signal.cont2discrete((A, B, C, D), 0.1, method='zoh') def test_no_change_args_ccase(self): acopy = self.A.copy() bcopy = self...
class LuksFileSystem(LoopbackFileSystemMixin, FileSystem): type = 'luks' guids = ['CA7D7CCB-63ED-4C53-861C-CC'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.luks_name = None def detect(cls, source, description): res = super().detect(source, descript...
def test_error_message_with_parametrized_fixtures(pytester: Pytester) -> None: pytester.copy_example('unittest/test_parametrized_fixture_error_message.py') result = pytester.runpytest() result.stdout.fnmatch_lines(['*test_two does not support fixtures*', '*TestSomethingElse::test_two', '*Function type: Test...
class TFMobileViTInvertedResidual(tf.keras.layers.Layer): def __init__(self, config: MobileViTConfig, in_channels: int, out_channels: int, stride: int, dilation: int=1, **kwargs) -> None: super().__init__(**kwargs) expanded_channels = make_divisible(int(round((in_channels * config.expand_ratio))), 8...
class EDMLoss(nn.Module): def __init__(self): super(EDMLoss, self).__init__() def forward(self, p_target, p_estimate): assert (p_target.shape == p_estimate.shape) cdf_target = torch.cumsum(p_target, dim=1) cdf_estimate = torch.cumsum(p_estimate, dim=1) cdf_diff = (cdf_est...
class SymmetricButlerVolmer(BaseKinetics): def __init__(self, param, domain, reaction, options, phase='primary'): super().__init__(param, domain, reaction, options, phase) def _get_kinetics(self, j0, ne, eta_r, T, u): Feta_RT = ((self.param.F * eta_r) / (self.param.R * T)) return (((2 * ...
.parametrize('dtype', ['f2', 'f4', 'f8']) def test_read_bgen__gp_dtype(shared_datadir, dtype): path = (shared_datadir / 'example.bgen') ds = read_bgen(path, gp_dtype=dtype) dtype = np.dtype(dtype) assert (ds['call_genotype_probability'].dtype == dtype) assert (ds['call_dosage'].dtype == dtype)
class TargetExtractor(): def __init__(self, delimiter='', targets_string=None, targets_file=None, exclude_private_ips=False, sort_targets=False, exclude_cdn_ip_networks=False, retrieve_new_cdn_ip_data=False, write_to_disk=False): self.delimiter = delimiter self.targets_string = str(targets_string).s...
def test_logq_mini_2_sample_2_var(parametric_grouped_approxes, three_var_model): (cls, kw) = parametric_grouped_approxes approx = cls([three_var_model.one, three_var_model.two], model=three_var_model, **kw) logq = approx.logq logq = approx.set_size_and_deterministic(logq, 2, 0) logq.eval()
_module() class ConvFCBBoxHead(BBoxHead): def __init__(self, num_shared_convs=0, num_shared_fcs=0, num_cls_convs=0, num_cls_fcs=0, num_reg_convs=0, num_reg_fcs=0, conv_out_channels=256, fc_out_channels=1024, conv_cfg=None, norm_cfg=None, *args, **kwargs): super(ConvFCBBoxHead, self).__init__(*args, **kwargs...
def test_dataframes(): pd = pytest.importorskip('pandas') from streamz.dataframe import DataFrame data = [{'x': i, 'y': (2 * i)} for i in range(10)] s = Batch(example=[{'x': 0, 'y': 0}]) sdf = s.map((lambda d: toolz.assoc(d, 'z', (d['x'] + d['y'])))).to_dataframe() assert isinstance(sdf, DataFra...
def test_pype_args_with_out(mock_pipe): context = Context({'parentkey': 'parentvalue', 'pype': {'name': 'pipe name', 'args': {'a': 'b'}, 'out': 'a'}}) context.parent = 'arb/dir' with patch_logger('pypyr.steps.pype', logging.INFO) as mock_logger_info: with get_arb_pipeline_scope(context): ...
def kafka_service(): TOPIC = ('test-%i' % random.randint(0, 10000)) if (_kafka[0] is None): if LAUNCH_KAFKA: launch_kafka() else: raise pytest.skip.Exception('Kafka not available. To launch kafka use `export STREAMZ_LAUNCH_KAFKA=true`') producer = ck.Producer({'bo...
class BpfHeaderExtractor(FileExtractor): filename = os.path.join(LINUX_ROOT, 'tools/include/uapi/linux/bpf.h') def get_prog_types(self): return self.get_enum('bpf_prog_type') def get_map_types(self): return self.get_enum('bpf_map_type') def get_attach_types(self): return self.get...
def analyze_results(lm_results: Dict, patterns_graph) -> None: total = 0 points = 0 total_syn = 0 total_lex = 0 total_both = 0 total_no = 0 points_syn = 0 points_lex = 0 points_both = 0 points_no = 0 points_by_edge = defaultdict(list) edges_out = defaultdict(list) avg...
def _match_list(module_rule: Tuple[(List[str], str)], logger_name: str) -> Tuple[(int, Optional[str])]: logger_modules_split = (logger_name.split('.') if logger_name else []) modules_split: List[str] = module_rule[0] level: str = module_rule[1] if (logger_modules_split == modules_split): return ...
_manager.tracked def index(request: WSGIRequest) -> HttpResponse: from core import urls context = base.context(request) context['urls'] = urls.musiq_paths context['additional_keywords'] = storage.get('additional_keywords') context['forbidden_keywords'] = storage.get('forbidden_keywords') context...
class ObjectModel(BaseModel): states: int emission: npt.NDArray transition: npt.NDArray start: npt.NDArray name: str = 'Default' ('emission', 'transition', 'start', pre=True) def parse_array(cls, v, values): return np.asarray(v, dtype=float) ('emission', 'transition', 'start', pr...
def test_window_by_interval__multiple_contigs(): ds = simulate_genotype_call_dataset(n_variant=10, n_sample=3, n_contig=2) ds['variant_position'] = (['variants'], np.array([1, 4, 6, 8, 12, 1, 21, 25, 40, 55])) assert (not has_windows(ds)) ds['interval_contig_name'] = (['intervals'], np.array(['0', '0', ...
class WindowWriteTest(unittest.TestCase): def setUp(self): self.tempdir = tempfile.mkdtemp() def tearDown(self): shutil.rmtree(self.tempdir) .gdalbin def test_write_window(self): name = os.path.join(self.tempdir, 'test_write_window.tif') a = (np.ones((50, 50), dtype=raste...
def create_datasets(args): div2k = DIV2K(os.path.join(args.data_path, 'DIV2K/DIV2K_train_HR'), os.path.join(args.data_path, 'DIV2K/DIV2K_train_LR_bicubic'), os.path.join(args.data_path, 'div2k_cache'), train=True, augment=args.data_augment, scale=args.scale, colors=args.colors, patch_size=args.patch_size, repeat=ar...
class TranslationRoutingTest(TranslationTestMixin, RapidTest): apps = [app.TranslationApp] def test_translation_override(self): en_conn = self.create_lang_connection('', 'en') es_conn = self.create_lang_connection('', 'es') self.receive('lang-hello', en_conn) self.receive('lang-h...
class AttrVI_ATTR_PXI_DEST_TRIG_BUS(RangeAttribute): resources = [(constants.InterfaceType.pxi, 'BACKPLANE')] py_name = '' visa_name = 'VI_ATTR_PXI_DEST_TRIG_BUS' visa_type = 'ViInt16' default = (- 1) (read, write, local) = (True, True, True) (min_value, max_value, values) = (1, 3, [(- 1)])
class _NameAttributeMapping(MutableMapping): def __init__(self, name: Name) -> None: self._name = name def __getitem__(self, key: t.Union[(bytes, str)]) -> tuples.GetNameAttributeResult: if isinstance(key, str): key = key.encode(_utils._get_encoding()) res = rname_rfc6680.get...
def test_create_right_lane_split_second_lane(): lanedef = xodr.LaneDef(10, 20, 1, 2, 2) lanes = xodr.create_lanes_merge_split([lanedef], 0, 30, xodr.std_roadmark_solid_solid(), 3, 3) assert (len(lanes.lanesections) == 3) assert (lanes.lanesections[0].s == 0) assert (lanes.lanesections[1].s == 10) ...
def test_add_timer(bot): global_bot = bot timer1_calls = 0 timer2_calls = 0 timer3_calls = 0 def timer1(): nonlocal timer1_calls timer1_calls += 1 def timer2(): nonlocal timer2_calls timer2_calls += 1 def timer3(bot): nonlocal timer3_calls time...
class _ZipPkgWriter(PhysPkgWriter): def __init__(self, pkg_file): super(_ZipPkgWriter, self).__init__() self._zipf = ZipFile(pkg_file, 'w', compression=ZIP_DEFLATED) def close(self): self._zipf.close() def write(self, pack_uri, blob): self._zipf.writestr(pack_uri.membername, ...
.filterwarnings('ignore:Constructing a DIA matrix') class TestExpm(UnaryOpMixin): def op_numpy(self, matrix): return scipy.linalg.expm(matrix) shapes = shapes_square() bad_shapes = shapes_not_square() specialisations = [pytest.param(data.expm_csr, CSR, CSR), pytest.param(data.expm_csr_dense, CSR...
def gen_property_setter_ir(builder: IRBuilder, func_decl: FuncDecl, cdef: ClassDef, is_trait: bool) -> FuncIR: name = func_decl.name builder.enter(name) self_reg = builder.add_argument('self', func_decl.sig.args[0].type) value_reg = builder.add_argument('value', func_decl.sig.args[1].type) assert na...
def merge_sim_episode_with_object_config(sim_config, episode): sim_config = merge_sim_episode_config(sim_config, episode) sim_config.defrost() object_templates = {} for template in episode.object_templates: object_templates[template['object_key']] = template['object_template'] objects = [] ...
class MlpWithDepthwiseConv(nn.Module): def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0, extra_relu=False): super().__init__() out_features = (out_features or in_features) hidden_features = (hidden_features or in_features) self.fc1 ...
def _summary(self, to_stdout=True, return_df=False): lengths = {} total_lengths = {} lengths['pyrange'] = self.lengths(as_dict=True) total_lengths['pyrange'] = [self.length] if self.stranded: c = self.merge(strand=True) lengths['coverage_forward'] = c['+'].lengths(as_dict=True) ...
class FDCapture(FDCaptureBinary): EMPTY_BUFFER = '' def snap(self) -> str: self._assert_state('snap', ('started', 'suspended')) self.tmpfile.seek(0) res = self.tmpfile.read() self.tmpfile.seek(0) self.tmpfile.truncate() return res def writeorg(self, data: str)...
def scatter_kwargs(inputs, kwargs, target_gpus, dim=0): inputs = (scatter(inputs, target_gpus, dim) if inputs else []) kwargs = (scatter(kwargs, target_gpus, dim) if kwargs else []) if (len(inputs) < len(kwargs)): inputs.extend([() for _ in range((len(kwargs) - len(inputs)))]) elif (len(kwargs) ...
class _LazyDescr(object): def __init__(self, name): self.name = name def __get__(self, obj, tp): result = self._resolve() setattr(obj, self.name, result) try: delattr(obj.__class__, self.name) except AttributeError: pass return result
class fashion200k(): def __init__(self, path, split='train'): super() self.split = split self.path = path label_path = 'datasets/fashion200k/labels/' print('Processing {} set'.format(split)) label_files = glob.glob((((label_path + '*_') + split) + '_*.txt')) l...
class MAGNA(nn.Module): def __init__(self, g: DGLGraph, num_layers: int, input_dim: int, hidden_dim: int, hop_num: int, alpha: float, num_classes: int, heads: list, top_k: int, feat_drop: float, attn_drop: float, negative_slope: float, edge_drop: float, topk_type: str, self_loop_number: int, undirected_graph=True, ...
def main(): (n_actors, replay_ip) = get_environ() args = argparser() batch_queue = Queue(maxsize=args.queue_size) prios_queue = Queue(maxsize=args.prios_queue_size) param_queue = Queue(maxsize=3) procs = [Process(target=train, args=(args, n_actors, batch_queue, prios_queue, param_queue)), Proces...
() def notify_of_completed_flights(): cutoff = (get_ad_day() - datetime.timedelta(days=1)) completed_flights_by_advertiser = defaultdict(list) for flight in Flight.objects.filter(live=True).select_related(): if (flight.hard_stop and (flight.end_date <= cutoff.date())): log.info('Flight %...
def _wasserstein_compute(x: torch.Tensor, y: torch.Tensor, x_weights: Optional[torch.Tensor], y_weights: Optional[torch.Tensor]) -> torch.Tensor: device = x.device x_sorter = torch.argsort(x) y_sorter = torch.argsort(y) all_values = torch.concatenate((x, y)) (all_values, _) = torch.sort(all_values) ...
class GradientEditorItem(TickSliderItem): sigGradientChanged = QtCore.Signal(object) sigGradientChangeFinished = QtCore.Signal(object) def __init__(self, *args, **kargs): self.currentTick = None self.currentTickColor = None self.rectSize = 15 self.gradRect = QtWidgets.QGraphi...
class BugzillaError(Exception): def get_bugzilla_error_string(exc): return getattr(exc, 'faultString', str(exc)) def get_bugzilla_error_code(exc): for propname in ['faultCode', 'code']: if hasattr(exc, propname): return getattr(exc, propname) return None d...
class BaseDataset(data.Dataset): def __init__(self): super(BaseDataset, self).__init__() def name(self): return 'BaseDataset' def modify_commandline_options(parser, is_train): return parser def initialize(self, opt): pass def __len__(self): return 0
def construct_jacobian(y, x, retain_graph=False): x_grads = [] for (idx, y_element) in enumerate(y.flatten()): if (x.grad is not None): x.grad.zero_() y_element.backward(retain_graph=(retain_graph or (idx < (y.numel() - 1)))) x_grads.append(x.grad.clone()[1]) return torch...
.skipif((not JSON5_ENABLED), reason='test requires json5') .parametrize('passing_data', [True, False]) def test_json5_reference(run_line, tmp_path, passing_data): main_schemafile = (tmp_path / 'main_schema.json') main_schemafile.write_text(json.dumps(JSON5_REF_MAIN_SCHEMA)) ref_schema = (tmp_path / 'title_s...
class BatchNorm(nn.BatchNorm2d): def __init__(self, num_features, eps=1e-05, momentum=0.1, weight_freeze=False, bias_freeze=False, weight_init=1.0, bias_init=0.0, **kwargs): super().__init__(num_features, eps=eps, momentum=momentum) if (weight_init is not None): nn.init.constant_(self.we...
class RuleEnvironment(object): __slots__ = ('idx', 'property_value_lists') def __init__(self, idx, property_value_lists): self.idx = idx self.property_value_lists = property_value_lists def append_pair_properties(self, property_values1, property_values2): if (not (property_values1 an...
class UnpackType(ProperType): __slots__ = ['type', 'from_star_syntax'] def __init__(self, typ: Type, line: int=(- 1), column: int=(- 1), from_star_syntax: bool=False) -> None: super().__init__(line, column) self.type = typ self.from_star_syntax = from_star_syntax def accept(self, vis...
def derivatives_in_toroidal_coordinates(): Print_Function() a = symbols('a', real=True) coords = (u, v, phi) = symbols('u v phi', real=True) (t3d, eu, ev, ephi) = Ga.build('e_u e_v e_phi', X=[(((a * sinh(v)) * cos(phi)) / (cosh(v) - cos(u))), (((a * sinh(v)) * sin(phi)) / (cosh(v) - cos(u))), ((a * sin(...
def get_sentiment(df, emotions, other_emotions, min_len=1): data = [] for sentiment in tqdm(emotions): res = df[df['text'].str.contains(sentiment, na=False)] for ind in range(len(res)): try: t = normalize_text(res.iloc[ind].text) if (not set(t).isdisjo...
class FlaxCodeGenRLForCausalLMModule(FlaxCodeGenForCausalLMModule): config: CodeGenRLConfig dtype: jnp.dtype = jnp.float32 def setup(self): self.transformer = FlaxCodeGenModule(self.config, dtype=self.dtype) self.lm_head = pnn.Dense(self.config.vocab_size, dtype=self.dtype, kernel_init=jax.n...
_fixtures(MigrateFixture) def test_how_migration_works(fixture): some_object = fixture.some_object class Migration1(Migration): def schedule_upgrades(self): self.schedule('drop_fk', some_object.do_something, 'drop_fk-1') self.schedule('data', some_object.do_something, 'data-1') ...
(frozen=True) class Mark(): name: str args: Tuple[(Any, ...)] kwargs: Mapping[(str, Any)] _param_ids_from: Optional['Mark'] = dataclasses.field(default=None, repr=False) _param_ids_generated: Optional[Sequence[str]] = dataclasses.field(default=None, repr=False) def __init__(self, name: str, args...
class DistillationTrainer(Trainer): def compute_loss(self, model, inputs, return_outputs=False): target_p = inputs['labels'] outputs = model(inputs['input_ids'], attention_mask=inputs['attention_mask']) logits = outputs[0] loss = (- torch.sum((target_p * logits.log_softmax(dim=(- 1))...
def add_kernel_test(cls, kernel, dim, name=None, expect=None, inputs=None, devices=['cpu']): for device in devices: def test_func(self): args = [] if inputs: args.extend(inputs) if expect: result = wp.array(expect, dtype=int, device=device)...
class StreamInfo(MetadataBlock, mutagen.StreamInfo): code = 0 bitrate = 0 def __eq__(self, other): try: return ((self.min_blocksize == other.min_blocksize) and (self.max_blocksize == other.max_blocksize) and (self.sample_rate == other.sample_rate) and (self.channels == other.channels) an...
class GeoLocalizedModel(models.Model): latitude = models.DecimalField(_('latitude'), max_digits=9, decimal_places=6, blank=True, null=True) longitude = models.DecimalField(_('longitude'), max_digits=9, decimal_places=6, blank=True, null=True) map_link = models.URLField(_('map link'), blank=True) class M...
class bdist_rpm(orig.bdist_rpm): def run(self): SetuptoolsDeprecationWarning.emit('Deprecated command', '\n bdist_rpm is deprecated and will be removed in a future version.\n Use bdist_wheel (wheel packages) instead.\n ', see_url=' due_date=(2023, 10, 30)) self.run_c...
class DSAKey(common.PK): keyType = 0 def __init__(self, key=None, private=False): self.priv = self.pub = None if (not isinstance(key, tuple)): raise TypeError('4/5-tuple required for key') if ((len(key) == 5) and private): self.priv = DSA.construct(key) ...
def test_inheritance_then_decorate(): calls = [] class Inheriting(MethodBasedConfigurable): pass def Concrete(*args, **kwargs): calls.append((args, kwargs)) assert callable(Concrete.handler) t = Concrete('foo', bar='baz') assert callable(t.handler) assert (len(calls) == 0) ...
class Power_Widgets(object): def left_grey(self): return Image(scale=True, filename='~/.config/qtile/power/bar01.png') def right_grey(self): return Image(scale=True, filename='~/.config/qtile/power/bar06.png') def black_red(self): return Image(scale=True, filename='~/.config/qtile/po...
.patch(PATCH_METHOD) .patch('pynamodb.connection.base.uuid') def test_signal_exception_post_signal(mock_uuid, mock_req): pre_recorded = [] UUID = '123-abc' def record_pre_dynamodb_send(sender, operation_name, table_name, req_uuid): pre_recorded.append((operation_name, table_name, req_uuid)) def ...
def response_factory(): def create_response(data, status_code=200, content_type='application/json'): fp = BytesIO(data) raw = HTTPResponse(fp, preload_content=False) resp = Response() resp.headers = CaseInsensitiveDict({'Content-Type': content_type}) resp.status_code = status...
class Request(object): def __init__(self, client: CDPSession, requestId: Optional[str], interceptionId: Optional[str], isNavigationRequest: bool, allowInterception: bool, url: str, resourceType: str, payload: dict, frame: Optional[Frame], redirectChain: List['Request']) -> None: self._client = client ...
def handle_action_init_mediator(chain_state: ChainState, state_change: ActionInitMediator) -> TransitionResult[ChainState]: transfer = state_change.from_transfer secrethash = transfer.lock.secrethash token_network_address = transfer.balance_proof.token_network_address return subdispatch_mediatortask(cha...
def main(args): with open(args.dataset_info, 'rb') as rf: dataset_info = pickle.load(rf) tokenizer = MarianTokenizer.from_pretrained(args.model_string) tokenizer.add_special_tokens({'pad_token': PAD_TOKEN}) pad_id = tokenizer.encode(PAD_TOKEN)[0] model = MarianMTModel.from_pretrained(args.mo...
def backupJson(gen_data_dir, sp): sp_dir = ((gen_data_dir + sp) + '/') task_fds = os.listdir(sp_dir) for task in task_fds: task_dir = ((sp_dir + task) + '/') trial_fds = os.listdir(task_dir) for trial in trial_fds: new_fn = ((task_dir + trial) + '/traj_data_backup.json') ...
class KJTInputWrapper(torch.nn.Module): def __init__(self, module_kjt_input: torch.nn.Module) -> None: super().__init__() self._module_kjt_input = module_kjt_input self.add_module('_module_kjt_input', self._module_kjt_input) def forward(self, keys: List[str], values: torch.Tensor, weight...
class MovingBatchNormNd(nn.Module): def __init__(self, num_features, eps=0.0001, decay=0.1, bn_lag=0.0, affine=True, sync=False): super(MovingBatchNormNd, self).__init__() self.num_features = num_features self.sync = sync self.affine = affine self.eps = eps self.decay...
class DisplayOptionalPage(DisplayPage): def __init__(self, parent, tabname, helptext, waittime, command=None): logger.debug('%s: OptionalPage args: (waittime: %s, command: %s)', self.__class__.__name__, waittime, command) DisplayPage.__init__(self, parent, tabname, helptext) self.command = c...