code
stringlengths
281
23.7M
def _prepare_yaml_file(filename, obj_type, include_all_score_objs): if isinstance(filename, dict): yaml_content = filename else: _yaml = init_yaml() with open(filename, 'r') as yaml_file: yaml_content = _yaml.load(yaml_file) yaml_content_eql = _traverse_modify_date(yaml_c...
_caches def test_split_mechanism_mice_is_not_reusable(redis_cache): s = examples.basic_subsystem() mechanism = (0, 1) mice = s.find_mice(Direction.CAUSE, mechanism) assert (s._mice_cache.size() == 1) assert (mice.purview == (1, 2)) cut = models.Cut((0,), (1, 2)) cut_s = Subsystem(s.network, ...
def attack_Linf_PGD(input_v, ones, label_v, dis, Ld, steps, epsilon): dis.eval() adverse_v = input_v.data.clone() adverse_v = Variable(adverse_v, requires_grad=True) optimizer = Linf_SGD([adverse_v], lr=0.0078) for _ in range(steps): optimizer.zero_grad() dis.zero_grad() (d_b...
def check_solution_satisfiability(sol, list_of_subsets): n = len(list_of_subsets) U = [] for sub in list_of_subsets: U.extend(sub) U = np.unique(U) U2 = [] selected_subsets = [] for i in range(n): if (sol[i] == 1): selected_subsets.append(list_of_subsets[i]) ...
def get_grasp_poses(env): segm = env.obs['segm'] depth = env.obs['depth'] K = env.obs['K'] mask = ((segm == env.obs['target_instance_id']) & (~ np.isnan(depth))) pcd_in_camera = reorientbot.geometry.pointcloud_from_depth(depth, fx=K[(0, 0)], fy=K[(1, 1)], cx=K[(0, 2)], cy=K[(1, 2)]) normals_in_c...
.parametrize('iam_model,model_params', [('ashrae', {'b': 0.05}), ('physical', {'K': 4, 'L': 0.002, 'n': 1.526}), ('martin_ruiz', {'a_r': 0.16})]) def test_PVSystem_get_iam(mocker, iam_model, model_params): m = mocker.spy(_iam, iam_model) system = pvsystem.PVSystem(module_parameters=model_params) thetas = 1 ...
def test_validate_workflow(acetone): model0 = get_workflow_protocol(workflow_protocol='0') model0.qc_options.program = 'rdkit' model0.qc_options.method = 'uff' model0.qc_options.basis = None run_order = WorkFlow.get_running_order(skip_stages=['charges']) model0.validate_workflow(workflow=run_ord...
def cheng2020_anchor(quality, metric='mse', pretrained=False, progress=True, **kwargs): if (metric not in ('mse',)): raise ValueError(f'Invalid metric "{metric}"') if ((quality < 1) or (quality > 6)): raise ValueError(f'Invalid quality "{quality}", should be between (1, 6)') return _load_mod...
_dataframe_method def inflate_currency(df: pd.DataFrame, column_name: str=None, country: str=None, currency_year: int=None, to_year: int=None, make_new_column: bool=False) -> pd.DataFrame: inflator = _inflate_currency(country, currency_year, to_year) if make_new_column: new_column_name = ((column_name +...
def test_run_model_solar_position_weather(pvwatts_dc_pvwatts_ac_system, location, weather, mocker): mc = ModelChain(pvwatts_dc_pvwatts_ac_system, location, aoi_model='no_loss', spectral_model='no_loss') weather['pressure'] = 90000 weather['temp_air'] = 25 m = mocker.spy(location, 'get_solarposition') ...
def typo_fix(slot_values, ontology, version='2.1'): named_entity_slots = ['hotel-name', 'train-destination', 'train-departure', 'attraction-type', 'attraction-name', 'restaurant-name', 'taxi-departure', 'taxi-destination', 'restaurant-food'] fixed = {} for (slot, value) in slot_values.items(): value...
def format_xc_code(description): description = description.replace(' ', '').replace('\n', '').upper() if ('RSH' not in description): return description frags = description.split('RSH') out = [frags[0]] for frag in frags[1:]: (rsh_key, rest) = frag.split(')') if (',' in rsh_ke...
class TMid3cp(_TTools): TOOL_NAME = u'mid3cp' def setUp(self): super(TMid3cp, self).setUp() original = os.path.join(DATA_DIR, 'silence-44-s.mp3') (fd, self.filename) = mkstemp(suffix='oau.mp3') os.close(fd) shutil.copy(original, self.filename) (fd, self.blank_file...
def _check_has_no_phase_dynamics_shared_during_the_phase(problem_type, **kwargs): if (not isinstance(problem_type, SocpType.COLLOCATION)): if ('phase_dynamics' in kwargs): if (kwargs['phase_dynamics'] == PhaseDynamics.SHARED_DURING_THE_PHASE): raise ValueError('The dynamics canno...
def test_geth_discover_next_available_nonce_concurrent_transactions(deploy_client: JSONRPCClient, skip_if_parity: bool) -> None: def send_transaction(to: Address) -> None: deploy_client.transact(EthTransfer(to_address=to, value=0, gas_price=gas_price_for_fast_transaction(deploy_client.web3))) greenlets ...
def cross_layer_equalization_depthwise_layers(): model = MobileNetV2().to(torch.device('cpu')) model.eval() layer_list = [(model.features[0][0], model.features[0][1]), (model.features[1].conv[0], model.features[1].conv[1]), (model.features[1].conv[3], model.features[1].conv[4])] bn_dict = {} for con...
def run_experiments(config, files, aws): os.environ['RXGB_ALLOW_ELASTIC_TUNE'] = '1' condition = config['condition'] num_boost_round = config['num_boost_round'] num_workers = config['num_workers'] num_affected_workers = config['affected_workers'] regression = config['regression'] use_gpu = c...
def main(argv): tf.config.experimental.set_visible_devices([], 'GPU') os.environ['XLA_PYTHON_CLIENT_PREALLOCATE'] = 'false' if (FLAGS.mode == 'train'): tf.io.gfile.makedirs(FLAGS.workdir) gfile_stream = tf.io.gfile.GFile(os.path.join(FLAGS.workdir, 'stdout.txt'), 'w') handler = loggi...
def test_rename_keys(): results = dict(joints_3d=np.ones([17, 3]), joints_3d_visible=np.ones([17, 3])) pipeline = dict(type='RenameKeys', key_pairs=[('joints_3d', 'target'), ('joints_3d_visible', 'target_weight')]) pipeline = build_from_cfg(pipeline, PIPELINES) results = pipeline(results) assert ('j...
class Path(metaclass=AsyncAutoWrapperType): _forward: ClassVar[list[str]] _wraps: ClassVar[type] = pathlib.Path _forwards: ClassVar[type] = pathlib.PurePath _forward_magic: ClassVar[list[str]] = ['__str__', '__bytes__', '__truediv__', '__rtruediv__', '__eq__', '__lt__', '__le__', '__gt__', '__ge__', '__...
def setup_logger(level: int=logging.ERROR, log_filename: Optional[str]=None) -> None: fmt = '[%(asctime)s] %(levelname)s in %(module)s: %(message)s' date_fmt = '%H:%M:%S' formatter = logging.Formatter(fmt, datefmt=date_fmt) logger = logging.getLogger('pytube') logger.setLevel(level) stream_handl...
class F21Handler(BaseHandler): version = F21 commandMap = {'auth': commands.authconfig.FC3_Authconfig, 'authconfig': commands.authconfig.FC3_Authconfig, 'autopart': commands.autopart.F21_AutoPart, 'autostep': commands.autostep.FC3_AutoStep, 'bootloader': commands.bootloader.F21_Bootloader, 'btrfs': commands.btr...
def score_all_questions(num_workers): print('Loading data...') corpus = HotpotQuestions() train = corpus.get_train() dev = corpus.get_dev() workers = ProcessPool(num_workers, initializer=init, initargs=[]) print('Scoring train...') new_train = [] with tqdm(total=len(train)) as pbar: ...
def validate_test(kw): def get_list(key): return deserialize_list(kw.get(key, '')) errors = [] if (kw.get('SCRIPT-REL-PATH') == 'boost.test'): project_path = kw.get('BUILD-FOLDER-PATH', '') if ((not project_path.startswith('maps')) and (not project_path.startswith('devtools'))): ...
def plot_table(tbl, columns=None, title='', title_loc='left', header=True, colWidths=None, rowLoc='right', colLoc='right', colLabels=None, edges='horizontal', orient='horizontal', figsize=(5.5, 6), savefig=None, show=False): if (columns is not None): try: tbl.columns = columns except Exc...
def test_calibration_mat_alpha_3(): (lc, dict_nom, betaT) = setup3() calib3 = ra.Calibration(lc, target_beta=betaT, dict_nom_vals=dict_nom, calib_var='z', est_method='matrix', calib_method='alpha', print_output=False) calib3.run() dfXst = pd.DataFrame(data=[[0.6194, 1.0194, 1.8722, 1.2591, 1.6108, 3.504...
def evaluate(dataset, LOG, **kwargs): if (dataset in ['Inaturalist', 'sop', 'cars196', 'cub']): ret = evaluate_one_dataset(LOG, **kwargs) elif (dataset in ['vehicle_id']): ret = evaluate_multiple_datasets(LOG, **kwargs) else: raise Exception('No implementation for dataset {} availabl...
def gen_filelist(fname, fileList, folderName=''): with open(fname, 'w') as f: for it in fileList: if (len(it) == 1): f.write((('\n\n**' + it[FileName]) + '**\n\n')) else: f.write((((('- ' + gen_url(it[FileName], folderName)) + '\t\t') + it[Summary]) + ...
(scope='function') def terminal(radian_command): with Terminal.open(radian_command) as t: (yield t) t.sendintr() t.write('q()\n') start_time = time.time() while t.isalive(): if ((time.time() - start_time) > 15): raise Exception("radian didn't quit ...
class WorldbytezCom(XFSAccount): __name__ = 'WorldbytezCom' __type__ = 'account' __version__ = '0.06' __status__ = 'testing' __description__ = 'Worldbytez.com account plugin' __license__ = 'GPLv3' __authors__ = [('Walter Purcaro', '')] PLUGIN_DOMAIN = 'worldbytez.com'
class CustomCalloutItemDirective(Directive): option_spec = {'header': directives.unchanged, 'description': directives.unchanged, 'button_link': directives.unchanged, 'button_text': directives.unchanged} def run(self): try: if ('description' in self.options): description = sel...
def create_balcony(options: BalconyOptions): from ...btools.building.array import ArrayProperty from ...btools.building.sizeoffset import SizeOffsetProperty from ...btools.building.railing import RailProperty, RailFillProperty, PostFillProperty, WallFillProperty register_property(ArrayProperty) regi...
def sync_random_seed(seed=None, device='cuda'): if (seed is None): seed = np.random.randint((2 ** 31)) assert isinstance(seed, int) (rank, world_size) = get_dist_info() if (world_size == 1): return seed if (rank == 0): random_num = torch.tensor(seed, dtype=torch.int32, device...
def _binary_precision_update_input_check(input: torch.Tensor, target: torch.Tensor) -> None: if (input.shape != target.shape): raise ValueError(f'The `input` and `target` should have the same dimensions, got shapes {input.shape} and {target.shape}.') if (target.ndim != 1): raise ValueError(f'tar...
def create_dataloader(opt, world_size, rank): dataset = find_dataset_using_name(opt.dataset_mode) instance = dataset() instance.initialize(opt) print(('dataset [%s] of size %d was created' % (type(instance).__name__, len(instance)))) if opt.isTrain: train_sampler = torch.utils.data.distribut...
class Critic(nn.Module): def __init__(self, backbone, device='cpu'): super().__init__() self.device = torch.device(device) self.backbone = backbone.to(device) latent_dim = getattr(backbone, 'output_dim') self.last = nn.Linear(latent_dim, 1).to(device) def forward(self, ob...
.parametrize('rlo,rhi', [(1, 2), ('a', 'b')]) def test_valueholder_ordering(rlo, rhi): (vlo, vhi) = (ValueHolder(rlo), ValueHolder(rhi)) for lo in (rlo, vlo): for hi in (rhi, vhi): assert (lo < hi) assert (hi > lo) assert (lo <= lo) assert (not (lo < lo)) ...
class ChainStateStateMachine(RuleBasedStateMachine): def __init__(self): self.replay_path: bool = False self.address_to_privkey: Dict[(Address, PrivateKey)] = {} self.address_to_client: Dict[(Address, Client)] = {} self.transfer_order = TransferOrder() super().__init__() ...
def find_matching_team_invite(code, user_obj): found = lookup_team_invite(code) if ((found.user is not None) and (found.user != user_obj)): message = ('This invite is intended for user "%s".\n Please login to that account and try again.' % found.user.username) raise DataModelExce...
def setup_database_for_testing(testcase): if ((not IS_TESTING_REAL_DATABASE) and (not isinstance(db.obj, SqliteDatabase))): raise RuntimeError('Attempted to wipe production database!') if (not db_initialized_for_testing.is_set()): logger.debug('Setting up DB for testing.') if (os.environ...
def cycleGetFreElem(preFixData, e, minsup): copyPreFixData = list(copy.deepcopy(preFixData)) allFreSequence = [] allElem = getElem(copyPreFixData) (freElem, notFreElem) = useCycleGetFreElem(copyPreFixData, e, allElem, minsup) deleteNotFreElem(copyPreFixData, notFreElem) thisAllPrefixData = getAl...
def create_masked_lm_predictions(tokens, masked_lm_prob, max_predictions_per_seq, vocab_words, rng): cand_indexes = [] for (i, token) in enumerate(tokens): if ((token == '[CLS]') or (token == '[SEP]')): continue cand_indexes.append(i) rng.shuffle(cand_indexes) output_tokens =...
class Migration(migrations.Migration): dependencies = [('core', '0002_auto__1707')] operations = [migrations.CreateModel(name='ArchivedPlaylist', fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('list_id', models.CharField(max_length=200, unique=True)),...
def _set_tensors(obj, all_params, max_depth=20): def action(elmt, name, objdict, key): objdict[key] = all_params.pop(0) crit = (lambda elmt: (isinstance(elmt, torch.Tensor) and (elmt.dtype in torch_float_type))) _traverse_obj(obj, action=action, crit=crit, prefix='', max_depth=max_depth)
class Project(PymiereBaseObject): def __init__(self, pymiere_id=None): super(Project, self).__init__(pymiere_id) def documentID(self): return self._eval_on_this_object('documentID') def documentID(self, documentID): raise AttributeError("Attribute 'documentID' is read-only") def ...
class ChoiceFeedbackSerializer(serializers.Serializer): id = serializers.IntegerField() value_id = serializers.IntegerField() def validate(self, data): if object_exists(ChoiceFeedbackQuestion, pk=data['id']): if ChoiceFeedbackQuestionValue.objects.filter(question_id=data['id'], pk=data['...
class AverageMeter(): def __init__(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += (val * n) self.count += n self.avg = (self.sum / self.count) def clear(self): self.va...
def extract_few_shot_feature(cfg, clip_model, train_loader_cache): cache_keys = [] cache_values = [] with torch.no_grad(): for augment_idx in range(cfg['augment_epoch']): train_features = [] print('Augment Epoch: {:} / {:}'.format(augment_idx, cfg['augment_epoch'])) ...
def _find_chrome_win() -> Optional[str]: import winreg as reg reg_path = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe' chrome_path: Optional[str] = None for install_type in (reg.HKEY_CURRENT_USER, reg.HKEY_LOCAL_MACHINE): try: reg_key = reg.OpenKey(install_typ...
def getExceptionMessage(exceptionDetails: dict) -> str: exception = exceptionDetails.get('exception') if exception: return (exception.get('description') or exception.get('value')) message = exceptionDetails.get('text', '') stackTrace = exceptionDetails.get('stackTrace', dict()) if stackTrace...
class CIFARSEPreResNet(nn.Module): def __init__(self, channels, init_block_channels, bottleneck, in_channels=3, in_size=(32, 32), num_classes=10): super(CIFARSEPreResNet, self).__init__() self.in_size = in_size self.num_classes = num_classes self.features = nn.Sequential() se...
def test_aws_session_class_unsigned_noboto3(monkeypatch): import rasterio.session monkeypatch.setenv('AWS_NO_SIGN_REQUEST', 'YES') monkeypatch.setattr(rasterio.session, 'boto3', None) assert (rasterio.session.boto3 is None) sesh = AWSSession() assert (sesh.unsigned is True) assert (sesh.get_...
class TestSAFEGRD(unittest.TestCase): ('rasterio.open') def setUp(self, mocked_rio_open): from satpy.readers.sar_c_safe import SAFEGRD filename_info = {'mission_id': 'S1A', 'dataset_name': 'foo', 'start_time': 0, 'end_time': 0, 'polarization': 'vv'} filetype_info = 'bla' self.noi...
_module() class I3DHead(BaseHead): def __init__(self, num_classes, in_channels, loss_cls=dict(type='CrossEntropyLoss'), spatial_type='avg', dropout_ratio=0.5, init_std=0.01, **kwargs): super().__init__(num_classes, in_channels, loss_cls, **kwargs) self.spatial_type = spatial_type self.dropou...
class SyncProgress(): def __init__(self, response_queue: NotifyingQueue[Tuple[(UUID, JSONResponse, datetime)]]) -> None: self.synced_event = SyncEvent() self.processed_event = SyncEvent() self.sync_iteration = 0 self.processed_iteration = 0 self.last_synced: Optional[UUID] = ...
class FunctionEmitterVisitor(OpVisitor[None]): def __init__(self, emitter: Emitter, declarations: Emitter, source_path: str, module_name: str) -> None: self.emitter = emitter self.names = emitter.names self.declarations = declarations self.source_path = source_path self.modul...
def _handle_first_parameter(pyobject, parameters): kind = pyobject.get_kind() if (not parameters): if (not pyobject.get_param_names(special_args=False)): return parameters.append(pyobjects.get_unknown()) if (kind == 'method'): parameters[0] = pyobjects.PyObject(pyobject.p...
def upload_to_pypi(version: str, dry_run: bool=True) -> None: assert re.match('v?[1-9]\\.[0-9]+\\.[0-9](\\+\\S+)?$', version) if ('dev' in version): assert dry_run, 'Must use --dry-run with dev versions of mypy' if version.startswith('v'): version = version[1:] target_dir = tempfile.mkdt...
class FittingsTreeView(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent, id=wx.ID_ANY) self.parent = parent pmainSizer = wx.BoxSizer(wx.VERTICAL) tree = self.fittingsTreeCtrl = wx.TreeCtrl(self, wx.ID_ANY, style=(wx.TR_DEFAULT_STYLE | wx.TR_HIDE_ROOT)) pm...
def test_folding(workspace): doc = Document(DOC_URI, workspace, DOC) ranges = pylsp_folding_range(doc) expected = [{'startLine': 1, 'endLine': 6}, {'startLine': 2, 'endLine': 3}, {'startLine': 5, 'endLine': 6}, {'startLine': 8, 'endLine': 11}, {'startLine': 12, 'endLine': 20}, {'startLine': 13, 'endLine': 1...
def create(config_file: str) -> TrackerBase: config = _read_config(config_file) if (('protocol' not in config) or ('root_path' not in config)): raise Exception(f"Please specify 'protocol' and 'root_path' in {config_file}") protocol = config['protocol'] del config['protocol'] root = config['r...
class MJVGEOM(Structure): _fields_ = [('type', c_int), ('dataid', c_int), ('objtype', c_int), ('objid', c_int), ('category', c_int), ('texid', c_int), ('texuniform', c_int), ('texrepeat', (c_float * 2)), ('size', (c_float * 3)), ('pos', (c_float * 3)), ('mat', (c_float * 9)), ('rgba', (c_float * 4)), ('emission', c...
_HEADS_REGISTRY.register() class EmbeddingHead(nn.Module): def __init__(self, cfg): super().__init__() feat_dim = cfg.MODEL.BACKBONE.FEAT_DIM embedding_dim = cfg.MODEL.HEADS.EMBEDDING_DIM num_classes = cfg.MODEL.HEADS.NUM_CLASSES neck_feat = cfg.MODEL.HEADS.NECK_FEAT ...
_series_method def logit(s: 'Series', error: str='warn') -> 'Series': import numpy as np import scipy s = s.copy() outside_support = ((s <= 0) | (s >= 1)) if outside_support.any(): msg = f'{outside_support.sum()} value(s) are outside of (0, 1)' if (error.lower() == 'warn'): ...
def _migrate_v7(json_dict: dict) -> dict: renamed_items = {'3HP Life Capsule': 'Small Life Capsule', '4HP Life Capsule': 'Medium Life Capsule', '5HP Life Capsule': 'Large Life Capsule', 'Missile Expansion (24)': 'Large Missile Expansion'} for game in json_dict['game_modifications']: if (game['game'] != ...
(scope='session') def unicode_images(): parent_bytes = layer_bytes_for_contents(b'parent contents') image_bytes = layer_bytes_for_contents(b'some contents') return [Image(id='parentid', bytes=parent_bytes, parent_id=None), Image(id='someid', bytes=image_bytes, parent_id='parentid', config={'comment': 'the P...
class Sampler(torch.utils.data.sampler.Sampler): def __init__(self, opt, image_dict, image_list, **kwargs): self.pars = opt self.image_dict = image_dict self.image_list = image_list self.classes = list(self.image_dict.keys()) self.batch_size = opt.bs self.samples_per_...
def get_parser(): parser = argparse.ArgumentParser() parser.add_argument('root', metavar='DIR', help='root directory containing flac files to index') parser.add_argument('--valid-percent', default=0.01, type=float, metavar='D', help='percentage of data to use as validation set (between 0 and 1)') parser...
def configure_output() -> None: rich.reconfigure(force_terminal=True, no_color=getattr(args, 'no_color', False), highlight=False, theme=rich.theme.Theme({'logging.level.debug': 'green', 'logging.level.info': 'blue', 'logging.level.warning': 'yellow', 'logging.level.error': 'red', 'logging.level.critical': 'reverse ...
class Definition(): def __init__(self, definition: (Sequence[(Argument | Option)] | None)=None) -> None: self._arguments: dict[(str, Argument)] = {} self._required_count = 0 self._has_list_argument = False self._has_optional = False self._options: dict[(str, Option)] = {} ...
def run_step(context): logger.debug('started') context.assert_key_has_value(key='add', caller=__name__) step_input = context.get_formatted('add') assert_key_is_truthy(obj=step_input, key='set', caller=__name__, parent='add') assert_key_exists(obj=step_input, key='addMe', caller=__name__, parent='add...
class TestImageFolder(): def test_init_ok(self, tmpdir): tmpdir.mkdir('train') tmpdir.mkdir('test') train_dataset = ImageFolder(tmpdir, split='train') test_dataset = ImageFolder(tmpdir, split='test') assert (len(train_dataset) == 0) assert (len(test_dataset) == 0) ...
class TestVariable(QiskitOptimizationTestCase): def test_init(self): quadratic_program = QuadraticProgram() name = 'variable' lowerbound = 0 upperbound = 10 vartype = Variable.Type.INTEGER variable = Variable(quadratic_program, name, lowerbound, upperbound, vartype) ...
class TestInlineQueryResultCachedAudioBase(): id_ = 'id' type_ = 'audio' audio_file_id = 'audio file id' caption = 'caption' parse_mode = 'HTML' caption_entities = [MessageEntity(MessageEntity.ITALIC, 0, 7)] input_message_content = InputTextMessageContent('input_message_content') reply_m...
class Scenario(ScenarioGenerator): def __init__(self): super().__init__() def road(self, **kwargs): road = xodr.create_road([xodr.Line(1000)], 0, 2, 2) odr = xodr.OpenDrive('myroad') odr.add_road(road) odr.adjust_roads_and_lanes() guardrail = xodr.Object(0, 0, hei...
def startredir(redirport, target, port): dsz.control.echo.Off() cmd = ('redirect -tcp -lplisten %s -target %s %s' % (redirport, target, port)) dsz.control.echo.On() (succ, redircmdid) = dsz.cmd.RunEx(cmd, dsz.RUN_FLAG_RECORD) if (not succ): dsz.ui.Echo(('Failed: redirect -tcp -lplisten %s -t...
def test_doc_inherit(): chars = tuple((string.ascii_letters + string.digits)) random = np.random.default_rng(seed=42) doc = ''.join(random.choice(chars, 1000)) def func_a(): ... func_a.__doc__ = doc _inherit(func_a) def func_b(): ... _inherit(doc) def func_c(): ...
def override_module_args(args: Namespace) -> Tuple[(List[str], List[str])]: overrides = [] deletes = [] if (args is not None): assert (hasattr(args, 'task') and hasattr(args, 'criterion') and hasattr(args, 'optimizer') and hasattr(args, 'lr_scheduler')) if (args.task in TASK_DATACLASS_REGIST...
(context_settings={'help_option_names': ['-h', '--help'], 'max_content_width': 120}, invoke_without_command=True) ('--env', '-e', 'env_name', envvar=AppEnvVars.ENV, default='default', help='The name of the environment to use [env var: `HATCH_ENV`]') ('--project', '-p', envvar=ConfigEnvVars.PROJECT, help='The name of th...
def main(): global logger args = get_args() args = set_seed_logger(args) (device, n_gpu) = init_device(args, args.local_rank) tokenizer = ClipTokenizer() assert (args.task_type == 'retrieval') model = init_model(args, device, n_gpu, args.local_rank) assert ((args.freeze_layer_num <= 12) ...
class Buhne(): def __init__(self): self._core = CoreStage() self._core.facade = self self._core.sprite_facade_class = Figur def fuge_eine_figur_hinzu(self, costume='default'): return self._core.pystage_createsprite(costume=costume) def abspielen(self): self._core.pyst...
class AnswerSerializer(serializers.ModelSerializer): author = serializers.StringRelatedField() created_at = serializers.SerializerMethodField() likes_count = serializers.SerializerMethodField() user_has_liked_answer = serializers.SerializerMethodField() question_slug = serializers.SerializerMethodFi...
class Migration(migrations.Migration): dependencies = [('options', '0027_meta')] operations = [migrations.AlterModelOptions(name='option', options={'ordering': ('uri',), 'verbose_name': 'Option', 'verbose_name_plural': 'Options'}), migrations.RenameField(model_name='optionset', old_name='key', new_name='uri_pat...
def iterate_tfrecord_file(data: BufferedIOBase) -> Iterator[memoryview]: length_bytes = bytearray(8) crc_bytes = bytearray(4) data_bytes = bytearray(1024) while True: bytes_read = data.readinto(length_bytes) if (bytes_read == 0): break elif (bytes_read != 8): ...
class SaveEditorHandler(webBase.BaseHandler): def post(self): action = self.get_argument('action', default=None, strip=False) logging.info(action) table_name = self.get_argument('table_name', default=None, strip=False) stockWeb = stock_web_dic.STOCK_WEB_DATA_MAP[table_name] p...
def NASNet(input_shape=None, penultimate_filters=4032, num_blocks=6, stem_block_filters=96, skip_reduction=True, filter_multiplier=2, include_top=True, weights=None, input_tensor=None, pooling=None, classes=1000, default_size=None, params=PARAM_NONE, **kwargs): global backend, layers, models, keras_utils (backe...
class ProjectCommitDiscussionManager(RetrieveMixin, CreateMixin, RESTManager): _path = '/projects/{project_id}/repository/commits/{commit_id}/discussions' _obj_cls = ProjectCommitDiscussion _from_parent_attrs = {'project_id': 'project_id', 'commit_id': 'id'} _create_attrs = RequiredOptional(required=('b...
_small_list(immutable=True, attrname='vals', factoryname='_make', unbox_num=True, nonull=True) class ConsEnv(Env): _immutable_ = True _immutable_fields_ = ['_prev'] _attrs_ = ['_prev'] def __init__(self, prev): assert isinstance(prev, Env) self._prev = prev def consenv_get_size(self)...
_fixtures(FieldFixture) def test_required_constraint(fixture): selector = 'find me' required_constraint = RequiredConstraint(dependency_expression=selector) assert (required_constraint.parameters == selector) with expected(RequiredConstraint): required_constraint.validate_input('') with expe...
(jax.pmap, axis_name='batch') def train_step(state, drp_rng, **model_inputs): def loss_fn(params): start_labels = model_inputs.pop('start_labels') end_labels = model_inputs.pop('end_labels') pooled_labels = model_inputs.pop('pooled_labels') outputs = state.apply_fn(**model_inputs, pa...
class YieldExpr(Expression): __slots__ = ('expr',) __match_args__ = ('expr',) expr: (Expression | None) def __init__(self, expr: (Expression | None)) -> None: super().__init__() self.expr = expr def accept(self, visitor: ExpressionVisitor[T]) -> T: return visitor.visit_yield_...
def test_upload_generic_package(tmp_path, gitlab_cli, project): path = (tmp_path / file_name) path.write_text(file_content) cmd = ['-v', 'generic-package', 'upload', '--project-id', project.id, '--package-name', package_name, '--path', path, '--package-version', package_version, '--file-name', file_name] ...
class Transformation(): def __init__(self, transform_type=None): self.transform_types = ['cholesky', 'svd'] self.transform_type = transform_type if (self.transform_type is None): self.transform_type = 'cholesky' if (self.transform_type not in self.transform_types): ...
def main(argv): args = parseArgs(argv) args.pathQuantizedUnits = abspath(args.pathQuantizedUnits) args.pathOutputFile = abspath(args.pathOutputFile) args.pathLSTMCheckpoint = abspath(args.pathLSTMCheckpoint) if (args.dict is not None): args.dict = abspath(args.dict) print('') print(f...
def _cap_fees(x_list: List[Fraction], y_list: List[Fraction]) -> Tuple[(List[Fraction], List[Fraction])]: x_list = copy(x_list) y_list = copy(y_list) for i in range((len(x_list) - 1)): (y1, y2) = y_list[i:(i + 2)] if ((sign(y1) * sign(y2)) == (- 1)): (x1, x2) = x_list[i:(i + 2)] ...
class AttrVI_ATTR_USB_BULK_IN_STATUS(RangeAttribute): resources = [(constants.InterfaceType.usb, 'RAW')] py_name = '' visa_name = 'VI_ATTR_USB_BULK_IN_STATUS' visa_type = 'ViInt16' default = NotAvailable (read, write, local) = (True, True, True) (min_value, max_value, values) = ((- 32768), 3...
def id_to_probs(probs, ids, id_to_vocab, SOFTMAX=False): if SOFTMAX: probs = softmax(probs) else: pass product = 1 for id in ids: if (id_to_vocab[id] == '</s>'): break elif (id_to_vocab[id] == '<s>'): pass elif id: product *= pr...
class Effect2734(BaseEffect): type = 'passive' def handler(fit, ship, context, projectionRange, **kwargs): for type in ('Gravimetric', 'Ladar', 'Radar', 'Magnetometric'): fit.modules.filteredItemBoost((lambda mod: (mod.item.group.name == 'ECM')), 'scan{0}StrengthBonus'.format(type), ship.get...
def input_fn_builder(features, seq_length, is_training, drop_remainder): all_input_ids = [] all_input_mask = [] all_segment_ids = [] all_label_ids = [] for feature in features: all_input_ids.append(feature.input_ids) all_input_mask.append(feature.input_mask) all_segment_ids.a...
class FixFilter(fixer_base.ConditionalFix): BM_compatible = True PATTERN = "\n filter_lambda=power<\n 'filter'\n trailer<\n '('\n arglist<\n lambdef< 'lambda'\n (fp=NAME | vfpdef< '(' fp=NAME ')'> ) ':' xp=any\n >\n ...