code
stringlengths
281
23.7M
def project(x, original_x, epsilon, _type='linf'): if (_type == 'linf'): max_x = (original_x + epsilon) min_x = (original_x - epsilon) x = torch.max(torch.min(x, max_x), min_x) elif (_type == 'l2'): dist = (x - original_x) dist = dist.view(x.shape[0], (- 1)) dist_...
('/task_operate', methods=['POST']) def task_operate(): if (not session.get('logged_in')): return redirect(url_for('login')) global handle task_name = str(request.form['name']) if (request.form['key'] == ''): try: g.db.execute(('drop table if exists "%s";' % task_name)) ...
class Effect5619(BaseEffect): type = 'passive' def handler(fit, ship, context, projectionRange, **kwargs): fit.modules.filteredItemBoost((lambda mod: (mod.item.group.name == 'Missile Launcher Rapid Heavy')), 'speed', ship.getModifiedItemAttr('shipBonusCB'), skill='Caldari Battleship', **kwargs)
class BaseTaskHandle(ABC): def stop(self) -> None: pass def current_jobset(self) -> Optional[BaseJobSet]: pass def add_observer(self) -> None: pass def is_stopped(self) -> bool: pass def get_jobsets(self) -> Sequence[BaseJobSet]: pass def create_jobset(sel...
class DripOAuthTest(OAuth2Test): backend_path = 'social_core.backends.drip.DripOAuth' user_data_url = ' expected_username = '' access_token_body = json.dumps({'access_token': '822bbf7cd12243df', 'token_type': 'bearer', 'scope': 'public'}) user_data_body = json.dumps({'users': [{'email': '', 'name': ...
class Migration(migrations.Migration): dependencies = [('adserver', '0058_view_time')] operations = [migrations.AddField(model_name='historicalpublisher', name='skip_payouts', field=models.BooleanField(default=False, help_text='Enable this to temporarily disable payouts. They will be processed again once you un...
class TestReconfig(KazooTestCase): def setUp(self): KazooTestCase.setUp(self) if CI_ZK_VERSION: version = CI_ZK_VERSION else: version = self.client.server_version() if ((not version) or (version < (3, 5))): pytest.skip('Must use Zookeeper 3.5 or ab...
def get_active_space_integrals(one_body_integrals, two_body_integrals, occupied_indices=None, active_indices=None): occupied_indices = ([] if (occupied_indices is None) else occupied_indices) if (len(active_indices) < 1): raise ValueError('Some active indices required for reduction.') core_constant ...
_sample_fn.register(ptr.BernoulliRV) _sample_fn.register(ptr.CategoricalRV) def jax_sample_fn_no_dtype(op): name = op.name jax_op = getattr(jax.random, name) def sample_fn(rng, size, dtype, *parameters): rng_key = rng['jax_state'] (rng_key, sampling_key) = jax.random.split(rng_key, 2) ...
def custom_vdom_constructor(func: _CustomVdomDictConstructor) -> VdomDictConstructor: (func) def wrapper(*attributes_and_children: Any) -> VdomDict: (attributes, children) = separate_attributes_and_children(attributes_and_children) key = attributes.pop('key', None) (attributes, event_han...
def generate_df_tasks(c_code, mem_read_limit_per_process, WorldPop_inputfile): task_list = [] with rasterio.open(WorldPop_inputfile) as src: (worldpop_y_dim, worldpop_x_dim) = src.shape transform = src.meta['transform'] (block_y_dim, block_x_dim) = [int(i) for i in src.block_shapes[0]] ...
def mime_type_codec(mime_type_codec: str) -> Tuple[(str, List[str])]: pattern = '(\\w+\\/\\w+)\\;\\scodecs=\\"([a-zA-Z-0-9.,\\s]*)\\"' regex = re.compile(pattern) results = regex.search(mime_type_codec) if (not results): raise RegexMatchError(caller='mime_type_codec', pattern=pattern) (mime_...
.end_to_end() def test_skip_unchanged_w_dependencies_and_products(tmp_path): source = '\n import pytask\n\n .depends_on("in.txt")\n .produces("out.txt")\n def task_dummy(depends_on, produces):\n produces.write_text(depends_on.read_text())\n ' tmp_path.joinpath('task_module.py').write_text(...
class TestKeypoints(unittest.TestCase): def test_cat_keypoints(self): keypoints1 = Keypoints(torch.rand(2, 21, 3)) keypoints2 = Keypoints(torch.rand(4, 21, 3)) cat_keypoints = keypoints1.cat([keypoints1, keypoints2]) self.assertTrue(torch.all((cat_keypoints.tensor[:2] == keypoints1.t...
def test_maincli_interactive_all_yes(tmpdir): runner = CliRunner() result = runner.invoke(yadage.steering.main, [os.path.join(str(tmpdir), 'workdir'), 'workflow.yml', '-t', 'tests/testspecs/local-helloworld', '-g', 'interactive', '-p', 'par=value'], input='y\ny\ny\ny\ny\ny\n') assert tmpdir.join('workdir/he...
class ModbusSocketFramer(ModbusFramer): method = 'socket' def __init__(self, decoder, client=None): super().__init__(decoder, client) self._hsize = 7 def checkFrame(self): if self.isFrameReady(): (self._header['tid'], self._header['pid'], self._header['len'], self._header...
def test_add_with_single_string(): context = Context({'arbset': {1, 2}, 'add': {'set': PyString('arbset'), 'addMe': 'three'}}) add.run_step(context) context['add']['addMe'] = 'four' add.run_step(context) assert (context['arbset'] == {1, 2, 'three', 'four'}) assert (len(context) == 2)
class TetrixWindow(QWidget): def __init__(self): super(TetrixWindow, self).__init__() self.board = TetrixBoard() nextPieceLabel = QLabel() nextPieceLabel.setFrameStyle((QFrame.Box | QFrame.Raised)) nextPieceLabel.setAlignment(Qt.AlignCenter) self.board.setNextPieceLab...
def transition(xs, out_channels, name=''): n_branch_pre = len(xs) n_branch_cur = len(out_channels) xs_next = [] for i in range(n_branch_cur): if (i < n_branch_pre): x = xs[i] if (x.shape[(- 1)] != out_channels[i]): x = Conv2D(out_channels[i], 3, 1, 'same',...
def GenerateProject(name, force=True): path = Path(name).resolve() if os.path.exists(path): if force: if os.path.isfile(path): os.remove(path) else: shutil.rmtree(path) elif os.path.isfile(path): raise PyUnityException(f'File ex...
def test_pip_install(temporary_directory: Path, project_source_root: Path, python: str) -> None: temp_pep_517_backend_path = (temporary_directory / 'pep_517_backend') shutil.copytree((Path(__file__).parent.parent / 'fixtures/pep_517_backend'), temp_pep_517_backend_path) with open((temp_pep_517_backend_path ...
class TarRankSelectAlgo(CompRatioSelectAlgo): def __init__(self, layer_db: LayerDatabase, pruner: Pruner, cost_calculator: cc.CostCalculator, eval_func: EvalFunction, eval_iterations, cost_metric: CostMetric, num_rank_indices: int, use_cuda: bool, pymo_utils_lib): CompRatioSelectAlgo.__init__(self, layer_db...
class Model_inter_pad_without_BN(torch.nn.Module): def __init__(self): super(Model_inter_pad_without_BN, self).__init__() self.except_shape = (2, 3, 32, 32) self.conv1 = torch.nn.Conv2d(3, 32, kernel_size=2, stride=2, padding=2, bias=False) self.relu1 = torch.nn.ReLU() self.c...
class FastPath(): _cache() def __new__(cls, root): return super().__new__(cls) def __init__(self, root): self.root = root def joinpath(self, child): return pathlib.Path(self.root, child) def children(self): with suppress(Exception): return os.listdir((self...
def parse_args(): parser = argparse.ArgumentParser(description='Finetune a transformers model on a Masked Language Modeling task') parser.add_argument('--dataset_name', type=str, default=None, help='The name of the dataset to use (via the datasets library).') parser.add_argument('--dataset_config_name', typ...
def test_run_installs_with_local_poetry_file_transitive(installer: Installer, locker: Locker, repo: Repository, package: ProjectPackage, tmpdir: str, fixture_dir: FixtureDirGetter) -> None: root_dir = fixture_dir('directory') package.root_dir = root_dir locker.set_lock_path(root_dir) directory = fixture...
_content class WaveformPromise(Object): codes = CodesNSLCE.T() tmin = Timestamp.T() tmax = Timestamp.T() deltat = Float.T(optional=True) source_hash = String.T() def __init__(self, **kwargs): kwargs['codes'] = CodesNSLCE(kwargs['codes']) Object.__init__(self, **kwargs) def ti...
def print_help() -> None: help_string = '\n UltraSinger.py [opt] [mode] [transcription] [pitcher] [extra]\n \n [opt]\n -h This help text.\n -i Ultrastar.txt\n audio like .mp3, .wav, youtube link\n -o Output folder\n \n [mode]\n ## INPUT is audio ##\n default ...
def test_hookwrapper() -> None: out = [] (hookwrapper=True) def m1(): out.append('m1 init') (yield None) out.append('m1 finish') def m2(): out.append('m2') return 2 res = MC([m2, m1], {}) assert (res == [2]) assert (out == ['m1 init', 'm2', 'm1 finish'...
class VideoTestDUFDataset(VideoTestDataset): def __getitem__(self, index): folder = self.data_info['folder'][index] (idx, max_idx) = self.data_info['idx'][index].split('/') (idx, max_idx) = (int(idx), int(max_idx)) border = self.data_info['border'][index] lq_path = self.data_...
class PollViewTests(TestCase): def test_index_view_with_no_polls(self): response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, 'No polls are available.') self.assertQuerysetEqual(response.context['latest_poll_list'...
class AsmCmdGotoRelation(AsmCmdBase): _id = 16 _menuText = QT_TRANSLATE_NOOP('asm3', 'Go to relation') _tooltip = QT_TRANSLATE_NOOP('asm3', 'Select the corresponding part object in the relation group') _iconName = 'Assembly_GotoRelation.svg' _accel = 'A, R' _toolbarName = '' _cmdType = 'NoTr...
def test_run_with_custom_runner(): pipeline = dedent(' steps:\n - name: pypyr.steps.set\n in:\n set:\n test: 1\n ') context = pipelinerunner.run(pipeline_name=pipeline, loader='pypyr.loaders.string') assert (context['test'] == 1)
def convert_roberta_checkpoint_to_pytorch(roberta_checkpoint_path: str, pytorch_dump_folder_path: str, classification_head: bool): roberta = FairseqRobertaModel.from_pretrained(roberta_checkpoint_path) roberta.eval() roberta_sent_encoder = roberta.model.encoder.sentence_encoder config = RobertaConfig(vo...
def _create_args_parser(cmpnt_fn: Callable[(..., AppDef)], cmpnt_defaults: Optional[Dict[(str, str)]]=None) -> argparse.ArgumentParser: parameters = inspect.signature(cmpnt_fn).parameters (function_desc, args_desc) = get_fn_docstring(cmpnt_fn) script_parser = argparse.ArgumentParser(prog=f'torchx run <run a...
class SaveDataAction(Action): mandatoryparams = ['attribute', 'value'] optionalparams = ['display', 'pspid', 'config'] def __init__(self, params, **kwargs): Action.__init__(self, execparams=params, **kwargs) def Execute(self): Action.Execute(self) attrib = self.execparams['attrib...
class StrideWrapper(Dataset): def __init__(self, dataset, stride): self.dataset = dataset self.index2old_index = [(idx * stride) for idx in range((len(self.dataset) // stride))] def __getitem__(self, index): old_index = self.index2old_index[index] return self.dataset[old_index] ...
class FileTransferSpeed(ProgressBarWidget): def __init__(self): self.fmt = '%6.2f %s' self.units = ['B', 'K', 'M', 'G', 'T', 'P'] def update(self, pbar): if (pbar.seconds_elapsed < 2e-06): bps = 0.0 else: bps = (float(pbar.currval) / pbar.seconds_elapsed) ...
class ModelParallelSparseOnlyBase(unittest.TestCase): def tearDown(self) -> None: dist.destroy_process_group() def test_sharding_ebc_as_top_level(self) -> None: os.environ['RANK'] = '0' os.environ['WORLD_SIZE'] = '1' os.environ['LOCAL_WORLD_SIZE'] = '1' os.environ['MASTER...
def main(): args = get_parser().parse_args() errs = 0 count = 0 with open(args.hypo, 'r') as hf, open(args.reference, 'r') as rf: for (h, r) in zip(hf, rf): h = h.rstrip().split() r = r.rstrip().split() errs += editdistance.eval(r, h) count += len(...
def test_run_job(): js = None cfg = config() try: js = rs.job.Service(cfg.job_service_url, cfg.session) j = js.run_job('/bin/sleep 10') assert j.id except rs.NotImplemented as ni: assert cfg.notimpl_warn_only, ('%s ' % ni) if cfg.notimpl_warn_only: pri...
class Translation(CGAThing): def __init__(self, cga, *args) -> None: super().__init__(cga) if (len(args) == 0): mv = (1 - ((self.cga.base_vector() * self.cga.einf) / 2.0)) elif (len(args) == 1): arg = args[0] if isinstance(arg, MultiVector): ...
def warning(): def _warnformat(msg, category, filename, lineno, file=None, line=None): return ('%s:%s: %s: %s\n' % (filename, lineno, category.__name__, msg)) default_warn_format = warnings.formatwarning try: warnings.formatwarning = _warnformat warnings.filterwarnings('always') ...
class VendingMachine(VendingMachineStateMixin): def __init__(self): self.initialize_state(Idle) self._pressed = None self._alpha_pressed = None self._digit_pressed = None def press_button(self, button): if (button in 'ABCD'): self._pressed = button ...
def custom_pdb_calls() -> List[str]: called = [] class _CustomPdb(): quitting = False def __init__(self, *args, **kwargs): called.append('init') def reset(self): called.append('reset') def interaction(self, *args): called.append('interaction') ...
def test_nd_scan_sit_sot_with_carry(): x0 = pt.vector('x0', shape=(3,)) A = pt.matrix('A', shape=(3, 3)) def step(x, A): return ((A x), x.sum()) (xs, _) = scan(step, outputs_info=[x0, None], non_sequences=[A], n_steps=10, mode=get_mode('JAX')) fg = FunctionGraph([x0, A], xs) x0_val = np...
def test_insert_with_custom_columns(): sql = 'INSERT INTO tgt_tbl(random1, random2) (SELECT col1,col2 FROM src_tbl)' assert_column_lineage_equal(sql, [(ColumnQualifierTuple('col1', 'src_tbl'), ColumnQualifierTuple('random1', 'tgt_tbl')), (ColumnQualifierTuple('col2', 'src_tbl'), ColumnQualifierTuple('random2', ...
def ValidateImageSize(arg, argName, argInformed, errors): errorMsg = ('argument %s: required argument if %s is relative' % (argName, argInformed)) ret = None if (arg is None): errors.append(errorMsg) else: arg = arg.replace('(', '').replace(')', '') args = arg.split(',') ...
class MatchFirst(ParseExpression): def __init__(self, exprs: typing.Iterable[ParserElement], savelist: bool=False): super().__init__(exprs, savelist) if self.exprs: self.mayReturnEmpty = any((e.mayReturnEmpty for e in self.exprs)) self.skipWhitespace = all((e.skipWhitespace f...
def se_resnet101(num_classes, loss, pretrained='imagenet', **kwargs): model = SENet(num_classes=num_classes, loss=loss, block=SEResNetBottleneck, layers=[3, 4, 23, 3], groups=1, reduction=16, dropout_p=None, inplanes=64, input_3x3=False, downsample_kernel_size=1, downsample_padding=0, last_stride=2, fc_dims=None, *...
.skipif((sys.platform == 'win32'), reason='Windows raises `OSError: [Errno 22] Invalid argument` instead') def test_no_brokenpipeerror_message(pytester: Pytester) -> None: popen = pytester.popen((*pytester._getpytestargs(), '--help')) popen.stdout.close() ret = popen.wait() assert (popen.stderr.read() =...
def create_pod(body, namespace, timeout=120): try: pod_stat = None pod_stat = cli.create_namespaced_pod(body=body, namespace=namespace) end_time = (time.time() + timeout) while True: pod_stat = cli.read_namespaced_pod(name=body['metadata']['name'], namespace=namespace) ...
.parametrize('input,constraint', [('*', AnyConstraint()), ('win32', Constraint('win32', '=')), ('=win32', Constraint('win32', '=')), ('==win32', Constraint('win32', '=')), ('!=win32', Constraint('win32', '!=')), ('!= win32', Constraint('win32', '!='))]) def test_parse_constraint(input: str, constraint: (AnyConstraint |...
def upgrade(op, tables, tester): inspector = Inspector.from_engine(op.get_bind()) table_names = inspector.get_table_names() if ('uploadedblob' not in table_names): op.create_table('uploadedblob', sa.Column('id', sa.BigInteger(), nullable=False), sa.Column('repository_id', sa.Integer(), nullable=Fals...
.skip _db def test_unsubscribe_not_registered_mail_to_newsletter(graphql_client): email = '' variables = {'email': email} query = '\n mutation($email: String!) {\n unsubscribeToNewsletter(input: {\n email: $email\n }) {\n __typename\...
def test_jax_compile_ops(): x = DeepCopyOp()(pt.as_tensor_variable(1.1)) x_fg = FunctionGraph([], [x]) compare_jax_and_py(x_fg, []) x_np = np.zeros((20, 1, 1)) x = Unbroadcast(0, 2)(pt.as_tensor_variable(x_np)) x_fg = FunctionGraph([], [x]) compare_jax_and_py(x_fg, []) x = ViewOp()(pt.as...
def to_bool(val: ((bool | int) | str)) -> bool: if isinstance(val, bool): return val if (isinstance(val, int) or (isinstance(val, str) and val.isdigit())): return bool(int(val)) if isinstance(val, str): if (val.lower() == 'true'): return True return False
class DistributedLossWrapper(torch.nn.Module): def __init__(self, loss, **kwargs): super().__init__() has_parameters = (len([p for p in loss.parameters()]) > 0) self.loss = (DDP(loss, **kwargs) if has_parameters else loss) def forward(self, embeddings, labels, *args, **kwargs): (...
class StringValue(Value): def __init__(self, name, initial, **kwargs): super(StringValue, self).__init__(name, initial, **kwargs) def get_msg(self): if (type(self.value) == type(False)): strvalue = ('true' if self.value else 'false') else: strvalue = (('"' + self....
class MvpTokenizer(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, merges_file, errors...
def compute_valid_depth_mask(d1, d2=None, min_thred=0.3, max_thred=5.0): if (d2 is None): valid_mask = (((d1 < max_thred) & (d1 > min_thred)) & np.isfinite(d1)) else: valid_mask = ((d1 < max_thred) & (d2 < max_thred)) valid_mask[valid_mask] = ((d1[valid_mask] > min_thred) & (d2[valid_mas...
class QlWindowsThread(QlThread): ID = 0 def __init__(self, ql: Qiling, status: THREAD_STATUS=THREAD_STATUS.RUNNING): super().__init__(ql) self.ql = ql self.id = QlWindowsThread.ID QlWindowsThread.ID += 1 self.status = status self.waitforthreads = [] self.t...
class NoisyNetDQN(): def __init__(self, env, config): self.sess = tf.InteractiveSession() self.config = config self.replay_buffer = deque(maxlen=self.config.replay_buffer_size) self.time_step = 0 self.state_dim = env.observation_space.shape self.action_dim = env.actio...
class WebRequestHandler(BaseHTTPRequestHandler): def _set_headers(self): self.send_response(200) self.send_header('Content-type', 'application/json') self.end_headers() def do_GET(self): try: logger.debug('Got GET request') self._set_headers() ...
def check_channel(app1: RaidenService, app2: RaidenService, token_network_address: TokenNetworkAddress, settle_timeout: BlockTimeout, deposit_amount: TokenAmount) -> None: channel_state1 = get_channelstate_by_token_network_and_partner(chain_state=state_from_raiden(app1), token_network_address=token_network_address,...
class WindowEventsTestCase(InteractiveTestCase): window_size = (400, 200) window = None question = None def setUp(self): self.finished = False self.failure = None self.label = None def fail_test(self, failure): self.failure = failure self.finished = True d...
class TPanedPreferences(TestCase): def setUp(self): config.init() def tearDown(self): config.quit() def test_editor(self): x = PatternEditor() x.headers = x.headers x.destroy() x.destroy() def test_button(self): PreferencesButton(None).destroy() ...
def business_hours_back(end, delta): delta = datetime.timedelta(seconds=(delta.total_seconds() / 3)) estimate = delta start = (end - estimate) while (business_hours(start, end) < delta): estimate = datetime.timedelta(seconds=(estimate.total_seconds() * 2)) start = (end - estimate) se...
def replace_modules_of_type1_using_constructor(model, type1, constructor): for (module_name, module_ref) in model.named_children(): if isinstance(module_ref, type1): setattr(model, module_name, constructor(module_ref)) children_module_list = list(module_ref.modules()) if (len(chi...
def test_annotation_fail_runpath(testdir): testdir.makepyfile("\n import pytest\n pytest_plugins = 'pytest_github_actions_annotate_failures'\n\n def test_fail():\n assert 0\n ") testdir.monkeypatch.setenv('GITHUB_ACTIONS', 'true') testdir.monkeypatch.setenv('PYTEST_RUN...
def test_transform_pipeline_radians(): trans = Transformer.from_pipeline('+proj=pipeline +step +inv +proj=cart +ellps=WGS84 +step +proj=unitconvert +xy_in=rad +xy_out=deg') assert_almost_equal(trans.transform((- 2704026.01), (- 4253051.81), 3895878.82, radians=True), ((- 2.), 0., (- 20.))) assert_almost_equ...
def find_app_name(config_to_check: Optional[AppConfig], app_list: List[Dict[(str, Any)]]) -> str: if (not config_to_check): return NO_APP_RUNNING for app_def in app_list: if isinstance(app_def['config'], list): for config in app_def['config']: if ((config['APP_ID'] ==...
def select_algorithm(): global flag s = v.get() if (s == 'HANP-Miner'): flag = 1 v2.set(2500) v3.set(0) v4.set(3) print(('Function: ' + s)) elif (s == 'HANP-df'): flag = 2 v2.set(2500) v3.set(0) v4.set(3) print(('Function: '...
def test_ScanArgs_remove_nonseq_inner_input(): hmm_model_env = create_test_hmm() scan_args = hmm_model_env['scan_args'] hmm_model_env['scan_op'] hmm_model_env['Y_t'] hmm_model_env['Y_rv'] mus_in = hmm_model_env['mus_in'] mus_t = hmm_model_env['mus_t'] sigmas_in = hmm_model_env['sigmas_in...
class SpecField(SemVerField): default_error_messages = {'invalid': _('Enter a valid version number spec list in ==X.Y.Z,>=A.B.C format.')} description = _('Version specification list') def __init__(self, *args, **kwargs): self.syntax = kwargs.pop('syntax', base.DEFAULT_SYNTAX) super(SpecFiel...
def list_triggers(name, location='\\'): pythoncom.CoInitialize() task_service = win32com.client.Dispatch('Schedule.Service') task_service.Connect() task_folder = task_service.GetFolder(location) task_definition = task_folder.GetTask(name).Definition triggers = task_definition.Triggers ret = ...
class DiskCOW(COW): def __init__(self, addr, imagefd, logger, seek_lock): self.addr = addr self.imagefd = imagefd self.seek_lock = seek_lock self.logger = helpers.get_child_logger(logger, 'FS') self.logger.info('Copy-On-Write for {addr} in PyPXE_NBD_COW_{addr[0]}_{addr[1]}'.f...
def process_prom_query(query): if prom_cli: try: return prom_cli.custom_query(query=query, params=None) except Exception as e: logging.error(('Failed to get the metrics: %s' % e)) else: logging.info("Skipping the prometheus query as the prometheus client couldn't ...
def _get_base_template(name, description, platform, sorting, domain, layer_settings): layer = dict() layer['name'] = name layer['versions'] = {'navigator': ATTACK_NAVIGATOR_VERSION, 'layer': ATTACK_LAYER_VERSION} if (('includeAttackVersion' in layer_settings.keys()) and (layer_settings['includeAttackVer...
() ('-test-dep', is_flag=True, help='If to install test dependecies') ('-doc-dep', is_flag=True, help='If to install test dependecies') def install_dependencies(test_dep=False, doc_dep=False): config = util.get_config() default_dependencies = config['project']['dependencies'] print('Installing dependencies'...
class PerturbationConfidenceMetric(): def __init__(self, perturbation): self.perturbation = perturbation def __call__(self, input_tensor: torch.Tensor, cams: np.ndarray, targets: List[Callable], model: torch.nn.Module, return_visualization=False, return_diff=True): if return_diff: wi...
def __getdirlist(path, cache_tag, maxage, mask): try: result = ops.files.dirs.get_dirlisting(path, cache_tag=cache_tag, maxage=maxage, mask=mask) except OpsCommandException: psplog.debug(('Dir list failed (%s).' % path), exc_info=True) result = None except: psplog.debug(('Une...
class SepConvGRU(nn.Module): def __init__(self, hidden_dim=128, input_dim=(192 + 128)): super(SepConvGRU, self).__init__() self.convz1 = nn.Conv2d((hidden_dim + input_dim), hidden_dim, (1, 5), padding=(0, 2)) self.convr1 = nn.Conv2d((hidden_dim + input_dim), hidden_dim, (1, 5), padding=(0, 2...
def forwards(apps, schema_editor): Flight = apps.get_model('adserver', 'Flight') for flight in Flight.objects.all().annotate(flight_total_clicks=models.Sum(models.F('advertisements__impressions__clicks')), flight_total_views=models.Sum(models.F('advertisements__impressions__views'))): flight.total_click...
def render_pep440_old(pieces: Dict[(str, Any)]) -> str: if pieces['closest-tag']: rendered = pieces['closest-tag'] if (pieces['distance'] or pieces['dirty']): rendered += ('.post%d' % pieces['distance']) if pieces['dirty']: rendered += '.dev0' else: ...
def main(): args = parse_args() if args.distributed: torch.cuda.set_device(args.local_rank) dist.init_process_group(backend='nccl', init_method='env://') assert dist.is_initialized(), 'distributed is not initialized' if (dist.get_rank() == 0): make_folder(cfg.model_dir) ...
def conv_init(m): classname = m.__class__.__name__ if (classname.find('Conv') != (- 1)): init.xavier_uniform(m.weight, gain=np.sqrt(2)) init.constant(m.bias, 0) elif (classname.find('BatchNorm') != (- 1)): init.constant(m.weight, 1) init.constant(m.bias, 0)
def check_new_shows(config, db, update_db=True): info('Checking for new shows') for raw_show in _get_new_season_shows(config, db): if ((raw_show.show_type is not ShowType.UNKNOWN) and (raw_show.show_type not in config.new_show_types)): debug(" Show isn't an allowed type ({})".format(raw_sho...
class WireMessage(Message): def __init__(self, typ_data): self.type = message_types[typ_data[0][0]] self.data = typ_data[1] def serialize(self): return self[1] def parse(typ, data): if (ulong_unpack(data[1:5]) != (len(data) - 1)): raise ValueError(('invalid wire m...
def run(command): p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) (output, err) = p.communicate() rc = p.returncode enc = locale.getpreferredencoding() output = output.decode(enc) err = err.decode(enc) return (rc, output.strip(), err.strip())
_ignore_inferred def infer_parameter_objects(pyfunction): object_info = pyfunction.pycore.object_info result = object_info.get_parameter_objects(pyfunction) if (result is None): result = _parameter_objects(pyfunction) _handle_first_parameter(pyfunction, result) return result
def floquet_master_equation_rates(f_modes_0, f_energies, c_op, H, T, args, J_cb, w_th, kmax=5, f_modes_table_t=None): warnings.warn(FutureWarning('`floquet_master_equation_rates` is deprecated.')) floquet_basis = FloquetBasis(H, T, args=args) energy = floquet_basis.e_quasi delta = floquet_delta_tensor(e...
def fit_to_rect(frame, size, halign='center', valign='center'): (fl, ft, fw, fh) = to_rect(frame) (rw, rh) = (size.width(), size.height()) ft += 1 fh -= 1 fl += 1 fw -= 1 fa = (fh / fw) ra = (rh / rw) if (fa <= ra): rh = fh rw = (rh / ra) if (halign == 'left')...
class ChannelShuffle2(nn.Module): def __init__(self, channels, groups): super(ChannelShuffle2, self).__init__() if ((channels % groups) != 0): raise ValueError('channels must be divisible by groups') self.groups = groups def forward(self, x): return channel_shuffle2(x...
def make_valid_xml_name(key, attr): LOG.info(('Inside make_valid_xml_name(). Testing key "%s" with attr "%s"' % (unicode_me(key), unicode_me(attr)))) key = escape_xml(key) attr = escape_xml(attr) if key_is_valid_xml(key): return (key, attr) if str(key).isdigit(): return (('n%s' % key...
_safe def impersonate_vector_reference_cont(f, extra, inner, idx, app, env, cont, _vals): numargs = _vals.num_values() args = ([None] * (numargs + 2)) args[0] = inner args[1] = idx for i in range(numargs): args[(i + 2)] = _vals.get_value(i) if (extra is None): return f.call_with_...
def show_banner(): colors = ['bright_red', 'bright_green', 'bright_blue', 'cyan', 'magenta'] try: click.style('color test', fg='bright_red') except: colors = ['red', 'green', 'blue', 'cyan', 'magenta'] try: columns = get_terminal_size().columns if (columns >= len(banner.s...
def test_request_scope_covers_blueprint_teardown_request_handlers(): app = Flask(__name__) UserID = NewType('UserID', int) blueprint = Blueprint('blueprint', __name__) ('/') def index(): return 'hello' _request def on_teardown(exc, user_id: UserID): assert (user_id == 321) ...
def intraday_volatility(returns: ReturnsSeries, interval_in_minutes: int) -> float: unannualized_volatility = std(returns.values) minutes_in_trading_day = 390 intervals_in_day = (minutes_in_trading_day / interval_in_minutes) business_days_per_year = 252 return (unannualized_volatility * sqrt((interv...
def test_structuring_unstructuring_unknown_subclass(): class A(): a: int class A1(A): a1: int converter = Converter() include_subclasses(A, converter) class A2(A1): a2: int assert (converter.unstructure(A2(1, 2, 3), unstructure_as=A) == {'a': 1, 'a1': 2, 'a2': 3}) ass...