code
stringlengths
281
23.7M
class downResBlock_3x3(nn.Module): def __init__(self, in_c, out_c, hid_c=None, conv2d=None, norm_layer=None, non_linear=None): super(downResBlock_3x3, self).__init__() if (hid_c is None): hid_c = in_c if (conv2d is None): conv2d = nn.Conv2d if (norm_layer is N...
def main(): parser = build_parser() args = parser.parse_args() files_by_sample = collections.defaultdict(list) for fname in args.files: samplename = get_file_samplename(fname, strip_rep=True) files_by_sample[samplename].append(os.path.abspath(fname)) for (samplename, files) in files_...
def calculate_coordinates_shell(distance, num_dimensions, distance_step_size): if (num_dimensions == 1): return calculate_coordinates_shell_1d(distance) if (num_dimensions == 2): return calculate_coordinates_shell_2d(distance, distance_step_size) if (num_dimensions == 3): return calc...
class TestCLIIntegration(TestCase): def test_license(self): output = subprocess.check_output([sys.executable, '-m', 'pip', 'show', 'jsonschema'], stderr=subprocess.STDOUT) self.assertIn(b'License: MIT', output) def test_version(self): version = subprocess.check_output([sys.executable, '-...
class Discriminator_VGG_Patch(nn.Module): def __init__(self, in_nc, base_nf, norm_type='batch', act_type='leakyrelu', mode='CNA'): super(Discriminator_VGG_Patch, self).__init__() conv0 = B.conv_block(in_nc, base_nf, kernel_size=3, norm_type=None, act_type=act_type, mode=mode) conv1 = B.conv_...
class TupletMarginLoss(GenericPairLoss): def __init__(self, margin=5.73, scale=64, **kwargs): super().__init__(mat_based_loss=False, **kwargs) c_f.assert_distance_type(self, CosineSimilarity) self.margin = np.radians(margin) self.scale = scale self.add_to_recordable_attribute...
def extract_args(detector, aligner, in_path, out_path, args=None): py_exe = sys.executable _extract_args = ('%s faceswap.py extract -i %s -o %s -D %s -A %s' % (py_exe, in_path, out_path, detector, aligner)) if args: _extract_args += (' %s' % args) return _extract_args.split()
class Configurable(): global_defaults = {} def __init__(self, **config): self._variable_defaults = {} self._user_config = config def add_defaults(self, defaults): self._variable_defaults.update(((d[0], copy.copy(d[1])) for d in defaults)) def __getattr__(self, name): if (...
def test_user_avatar(api, mock_req): mock_req({'getUserProfilePhotos': {'ok': True, 'result': {'total_count': 1, 'photos': [[{'file_id': 'aaaaaa', 'width': 50, 'height': 50, 'file_size': 128}, {'file_id': 'bbbbbb', 'width': 25, 'height': 25, 'file_size': 64}]]}}}) user = botogram.objects.User({'id': 123, 'first...
_fixtures(WebFixture, FileInputButtonFixture) def test_file_upload_button(web_fixture, file_input_button_fixture): fixture = file_input_button_fixture wsgi_app = web_fixture.new_wsgi_app(child_factory=file_input_button_fixture.FileUploadForm.factory(), enable_js=True) web_fixture.reahl_server.set_app(wsgi_a...
def vgg_face_dag(weights_path=None, return_layer='fc8', **kwargs): model = Vgg_face_dag(return_layer) if weights_path: state_dict = torch.load(weights_path, map_location=torch.device('cuda')) try: model.load_state_dict(state_dict) except: from collections import O...
def initlogging(logfile): logging.shutdown() logger = logging.getLogger() logger.handlers = [] logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', filename=logfile, filemode='w') ch = logging.StreamHandler() ch.setLevel(logging.CRITICAL) ch.setFormatte...
def _parse_string(data: str, type_comments: bool=True) -> tuple[(ast.Module, ParserModule)]: parser_module = get_parser_module(type_comments=type_comments) try: parsed = parser_module.parse((data + '\n'), type_comments=type_comments) except SyntaxError as exc: if ((exc.args[0] != MISPLACED_T...
_tokenizer('moses', dataclass=MosesTokenizerConfig) class MosesTokenizer(object): def __init__(self, cfg: MosesTokenizerConfig): self.cfg = cfg try: from sacremoses import MosesTokenizer, MosesDetokenizer self.tok = MosesTokenizer(cfg.source_lang) self.detok = Mos...
class GlobalAttention(nn.Module): def __init__(self, dim, heads=8, dim_head=64, dropout=0.0, k=7): super().__init__() inner_dim = (dim_head * heads) self.heads = heads self.scale = (dim_head ** (- 0.5)) self.to_q = nn.Conv2d(dim, inner_dim, 1, bias=False) self.to_kv =...
class ConnectionItem(GraphicsObject): def __init__(self, source, target=None): GraphicsObject.__init__(self) self.setFlags((self.GraphicsItemFlag.ItemIsSelectable | self.GraphicsItemFlag.ItemIsFocusable)) self.source = source self.target = target self.length = 0 self....
class TestDiverseSiblingsSearch(TestDiverseBeamSearch): def assertHypoScore(self, hypo, pos_probs, sibling_rank, diversity_rate, normalized=True, lenpen=1.0): pos_scores = torch.FloatTensor(pos_probs).log() pos_scores.sub_((torch.Tensor(sibling_rank) * diversity_rate)) self.assertAlmostEqual...
def test_setup_show_with_KeyboardInterrupt_in_test(pytester: Pytester) -> None: p = pytester.makepyfile('\n import pytest\n \n def arg():\n pass\n def test_arg(arg):\n raise KeyboardInterrupt()\n ') result = pytester.runpytest('--setup-show', p, no_reraise_ct...
def prune_episodes(episodes, scene, metrics, num_good_episodes): good_episodes = [] for episode in episodes: episode_full_id = f"{scene}_{episode['episode_id']}" try: episode_stats = metrics.loc[episode_full_id] except KeyError: continue if (not math.isclo...
def convert_classification(base_model_name, hf_config, downstream_dict): model = WavLMForSequenceClassification.from_pretrained(base_model_name, config=hf_config) model.projector.weight.data = downstream_dict['projector.weight'] model.projector.bias.data = downstream_dict['projector.bias'] model.classif...
class HacktoberStats(commands.Cog): linked_accounts = RedisCache() def __init__(self, bot: Bot): self.bot = bot _month(Month.SEPTEMBER, Month.OCTOBER, Month.NOVEMBER) (name='hacktoberstats', aliases=('hackstats',), invoke_without_command=True) async def hacktoberstats_group(self, ctx: comman...
class ForRange(ForGenerator): def init(self, start_reg: Value, end_reg: Value, step: int) -> None: builder = self.builder self.start_reg = start_reg self.end_reg = end_reg self.step = step self.end_target = builder.maybe_spill(end_reg) if (is_short_int_rprimitive(star...
class TestIPython(unittest.TestCase): def test_init(self): try: from IPython.testing.globalipapp import get_ipython except ImportError: import pytest pytest.skip() ip = get_ipython() ip.run_line_magic('load_ext', 'line_profiler') ip.run_cel...
class NewWindow(QtWidgets.QMainWindow): def __init__(self, *args, m=None, title=None, on_close=None, **kwargs): super().__init__(*args, **kwargs) self.m = m self.setWindowTitle('OpenFile') self.showhelp = False self.toolbar = ToolBar(title=title, on_close=on_close) se...
def _do_query(bz, opt, parser): q = {} u = opt.from_url if u: q = bz.url_to_query(u) if opt.components_file: clist = [] f = open(opt.components_file, 'r') for line in f.readlines(): line = line.rstrip('\n') clist.append(line) opt.component ...
class SubModules(): def CryptUnprotectData(encrypted_data: bytes, optional_entropy: str=None) -> bytes: class DATA_BLOB(ctypes.Structure): _fields_ = [('cbData', ctypes.c_ulong), ('pbData', ctypes.POINTER(ctypes.c_ubyte))] pDataIn = DATA_BLOB(len(encrypted_data), ctypes.cast(encrypted_da...
def test_signature(workspace): sig_position = {'line': 10, 'character': 5} doc = Document(DOC_URI, workspace, DOC) sig_info = signature.pylsp_signature_help(doc._config, doc, sig_position) sigs = sig_info['signatures'] assert (len(sigs) == 1) assert (sigs[0]['label'] == 'main(param1, param2)') ...
class SendEnterKeyTest(unittest.TestCase): def setUp(self): Timings.fast() self.app = Application() self.app.start(_notepad_exe()) self.dlg = self.app.UntitledNotepad self.ctrl = HwndWrapper(self.dlg.Edit.handle) def tearDown(self): self.dlg.menu_select('File -> E...
def pad_if_smaller(img, size, fill=0): size = ((size, size) if isinstance(size, int) else size) (original_width, original_height) = img.size pad_height = ((size[1] - original_height) if (original_height < size[1]) else 0) pad_width = ((size[0] - original_width) if (original_width < size[0]) else 0) ...
def test_pages_site_not_found(graphql_client): query = '\n query Page ($hostname: String!, $language: String!) {\n cmsPages(hostname: $hostname, language: $language){\n body {\n ...on TextSection {\n title\n }\n }\n }\n }\n ...
def process_ground_paras(retrieved='../data/wq_finetuneq_train_10000.txt', save_path='../data/wq_ft_train_matched.txt', raw_data='../data/wq-train.txt', num_workers=40, debug=False, k=10000, match='string'): retrieved = [json.loads(l) for l in open(retrieved).readlines()] raw_data = [json.loads(l) for l in open...
def add_idol_config(cfg): cfg.MODEL.IDOL = CN() cfg.MODEL.IDOL.NUM_CLASSES = 80 cfg.INPUT.SAMPLING_FRAME_NUM = 1 cfg.INPUT.SAMPLING_FRAME_RANGE = 10 cfg.INPUT.SAMPLING_INTERVAL = 1 cfg.INPUT.SAMPLING_FRAME_SHUFFLE = False cfg.INPUT.AUGMENTATIONS = [] cfg.INPUT.COCO_PRETRAIN = False c...
def try_load_beams(data): try: from radio_beam import Beam except ImportError: warnings.warn('radio_beam is not installed. No beam can be created.', ImportError) if isinstance(data, fits.BinTableHDU): if ('BPA' in data.data.names): beam_table = data.data retur...
def _get_pixel_navigation_parameters(point, im_nav_params): obs_time = get_observation_time(point, im_nav_params.static.scan_params) (attitude, orbit) = interpolate_navigation_prediction(attitude_prediction=im_nav_params.predicted.attitude, orbit_prediction=im_nav_params.predicted.orbit, observation_time=obs_ti...
def test_connect_plain(): class Top(ComponentLevel3): def construct(s): s.src = TestSource(Bits32, [4, 3, 2, 1, 4, 3, 2, 1]) s.sink = TestSink(Bits32, [5, 4, 3, 2, 5, 4, 3, 2]) s.wire0 = Wire(32) def up_from_src(): s.wire0 = (s.src.out + 1) ...
def add_object(model_path, rot_mat=((1, 0, 0), (0, 1, 0), (0, 0, 1)), trans_vec=(0, 0, 0), scale=1, name=None): if model_path.endswith('.obj'): bpy.ops.import_scene.obj(filepath=model_path, axis_forward='-Z', axis_up='Y') else: raise NotImplementedError('Importing model of this type') obj_li...
class BigBirdConfig(PretrainedConfig): model_type = 'big_bird' def __init__(self, vocab_size=50358, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu_new', hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=4096, type_vocab_si...
def test_set(func, qtbot): throttled = throttle.Throttle(func, DELAY) throttled.set_delay(DELAY) throttled('foo') throttled('foo') throttled('foo') throttled('bar') func.assert_called_once_with('foo') func.reset_mock() qtbot.wait(int((1.5 * DELAY))) func.assert_called_once_with('...
class DCUN_TFC_GPoCM_TDF_Framework(DenseCUNet_GPoCM_Framework): def __init__(self, n_fft, hop_length, num_frame, spec_type, spec_est_mode, optimizer, lr, auto_lr_schedule, train_loss, val_loss, **kwargs): valid_kwargs = inspect.signature(DCUN_TFC_GPoCM_TDF.__init__).parameters tfc_tdf_net_kwargs = d...
def moving_code_with_imports(project, resource, source): import_tools = importutils.ImportTools(project) pymodule = libutils.get_string_module(project, source, resource) lines = codeanalyze.SourceLinesAdapter(source) start = 1 while ((start < lines.length()) and lines.get_line(start).startswith('#')...
def add_image_net_computational_nodes_in_graph(session: tf.compat.v1.Session, logits_name: str, num_classes: int): with session.graph.as_default(): y_hat = session.graph.get_tensor_by_name(logits_name) y_hat_argmax = tf.compat.v1.argmax(y_hat, axis=1) y = tf.compat.v1.placeholder(tf.compat.v...
def test_get_all_speakers_user_ids(schedule_item_factory, submission_factory, conference_factory, schedule_item_additional_speaker_factory): schedule_item_1 = schedule_item_factory(type='talk', submission=submission_factory()) schedule_item_2 = schedule_item_factory(type='talk', conference=schedule_item_1.confe...
def importESI(string): sMkt = Market.getInstance() fitobj = Fit() refobj = json.loads(string) items = refobj['items'] fitobj.name = refobj['name'] fitobj.notes = refobj['description'] try: ship = refobj['ship_type_id'] try: fitobj.ship = Ship(sMkt.getItem(ship)) ...
class Solution(): def titleToNumber(self, s: str) -> int: char = {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5, 'F': 6, 'G': 7, 'H': 8, 'I': 9, 'J': 10, 'K': 11, 'L': 12, 'M': 13, 'N': 14, 'O': 15, 'P': 16, 'Q': 17, 'R': 18, 'S': 19, 'T': 20, 'U': 21, 'V': 22, 'W': 23, 'X': 24, 'Y': 25, 'Z': 26} length = ...
class nnUNetTrainerDA5Segord0(nnUNetTrainerDA5): def get_dataloaders(self): patch_size = self.configuration_manager.patch_size dim = len(patch_size) deep_supervision_scales = self._get_deep_supervision_scales() (rotation_for_DA, do_dummy_2d_data_aug, initial_patch_size, mirror_axes) ...
class VolumeShareSlippageTestCase(WithCreateBarData, WithSimParams, WithDataPortal, ZiplineTestCase): START_DATE = pd.Timestamp('2006-01-05 14:31', tz='utc') END_DATE = pd.Timestamp('2006-01-05 14:36', tz='utc') SIM_PARAMS_CAPITAL_BASE = 100000.0 SIM_PARAMS_DATA_FREQUENCY = 'minute' SIM_PARAMS_EMISS...
def test_main_prefix(fancy_wheel, tmp_path): destdir = (tmp_path / 'dest') main([str(fancy_wheel), '-d', str(destdir), '-p', '/foo'], 'python -m installer') installed_py_files = list(destdir.rglob('*.py')) for f in installed_py_files: assert str(f.parent).startswith(str((destdir / 'foo'))), f'pa...
def testHistogramLUTWidget(): pg.mkQApp() win = QtWidgets.QMainWindow() win.show() cw = QtWidgets.QWidget() win.setCentralWidget(cw) l = QtWidgets.QGridLayout() cw.setLayout(l) l.setSpacing(0) v = pg.GraphicsView() vb = pg.ViewBox() vb.setAspectLocked() v.setCentralItem(v...
class TestInstallRequires(): def test_setup_install_includes_dependencies(self, tmp_path, mock_index): project_root = (tmp_path / 'project') project_root.mkdir(exist_ok=True) install_root = (tmp_path / 'install') install_root.mkdir(exist_ok=True) self.create_project(project_r...
def main(opt: argparse.Namespace) -> None: utils.set_gpu(opt.gpu) device = torch.device('cuda') run_name = datetime.now().strftime('%Y-%m-%d_%H-%M-%S') run_path = os.path.join(opt.output_root, run_name) print(f'Start training {run_path}') print(vars(opt)) os.makedirs(run_path, exist_ok=True)...
class Migration(migrations.Migration): dependencies = [('sponsors', '0094_sponsorship_locked')] operations = [migrations.AlterModelOptions(name='benefitfeatureconfiguration', options={'base_manager_name': 'non_polymorphic', 'verbose_name': 'Benefit Feature Configuration', 'verbose_name_plural': 'Benefit Feature...
class WebhookResponseValidator(BaseWebhookResponseValidator): def iter_errors(self, request: WebhookRequest, response: Response) -> Iterator[Exception]: try: (_, operation, _, _, _) = self._find_path(request) except PathError as exc: (yield exc) return (yi...
class SignIn(): async def sign_in(self: 'pyrogram.Client', phone_number: str, phone_code_hash: str, phone_code: str) -> Union[('types.User', 'types.TermsOfService', bool)]: phone_number = phone_number.strip(' +') r = (await self.invoke(raw.functions.auth.SignIn(phone_number=phone_number, phone_code_...
class TestDagMethods(unittest.TestCase): def test_exists_trek(self): node_names = ['x1', 'x2', 'x3', 'x4'] nodes = [] for name in node_names: node = GraphNode(name) nodes.append(node) dag = Dag(nodes) node1 = dag.get_node('x1') node2 = dag.get_...
def model_with_legacy_bn_layers_is_training_bool(is_training, is_fused): inputs = tf.keras.Input(shape=(32, 32, 3)) x = tf.keras.layers.Conv2D(32, (3, 3))(inputs) layer = normalization_layers.BatchNormalization(momentum=0.3, epsilon=0.65, fused=is_fused) x = layer.apply(x, training=is_training) x = ...
def solve(): problem = Problem() problem.addVariables(range(1, 21), ['A', 'B', 'C', 'D', 'E']) problem.addConstraint(SomeInSetConstraint(['A'], 4, True)) problem.addConstraint(SomeInSetConstraint(['B'], 4, True)) problem.addConstraint(SomeInSetConstraint(['C'], 4, True)) problem.addConstraint(So...
def featurize(smi, fingerprint, radius, length) -> Optional[np.ndarray]: mol = Chem.MolFromSmiles(smi) if (mol is None): return None if (fingerprint == 'morgan'): fp = rdmd.GetMorganFingerprintAsBitVect(mol, radius=radius, nBits=length, useChirality=True) elif (fingerprint == 'pair'): ...
class inp(SWMMIOFile): def __init__(self, file_path): self._options_df = None self._files_df = None self._raingages_df = None self._evaporation_df = None self._losses_df = None self._report_df = None self._conduits_df = None self._xsections_df = None ...
_optimizer('adafactor') class FairseqAdafactor(LegacyFairseqOptimizer): def __init__(self, args, params): super().__init__(args) print('using adafactor') self._optimizer = Adafactor(params, **self.optimizer_config) def add_args(parser): parser.add_argument('--adafactor-eps', defa...
def build_model(cfg, isTrain=True, dataset_num_overwrite=None): if (dataset_num_overwrite is None): dataset_num_overwrite = len(cfg.DATASETS.TRAIN) if isTrain: model = Generatic_Model(cfg, cfg.INPUT.SIZE_TRAIN[0], cfg.INPUT.SIZE_TRAIN[1], cfg.MODEL.FEATURE_DIM, use_dir=cfg.INPUT.USE_DIR, dataset...
class TwilioViewTestCase(TestCase): def setUp(self): self.regular_caller = G(Caller, phone_number='+', blacklisted=False) self.blocked_caller = G(Caller, phone_number='+', blacklisted=True) self.factory = TwilioRequestFactory(token=settings.TWILIO_AUTH_TOKEN, enforce_csrf_checks=True) ...
class DependenciesModel(QtCore.QAbstractTableModel): _headers = ('Dependency', 'Version', 'License') def __init__(self, parent): super().__init__(parent) self._packages = [(dist.name, dist.version, _get_license(dist)) for dist in importlib.metadata.distributions()] def columnCount(self, pare...
def validate(val_list, model, criterion): print('begin test') test_loader = torch.utils.data.DataLoader(dataset.listDataset(val_list, shuffle=False, transform=transforms.Compose([transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])]), train=False), batch_size=args.b...
class _BaseAutoModelClass(): _model_mapping = None def __init__(self, *args, **kwargs): raise EnvironmentError(f'{self.__class__.__name__} is designed to be instantiated using the `{self.__class__.__name__}.from_pretrained(pretrained_model_name_or_path)` or `{self.__class__.__name__}.from_config(config)...
def override_json(args, json_path, check_consistency=False): json_params = json.load(open(json_path)) params = vars(args) if check_consistency: missing_keys = [] for key in json_params: if (key not in params): missing_keys.append(key) assert (not missing_k...
def test_json_skipped_dep(vuln_data_skipped_dep): json_format = format.JsonFormat(False) expected_json = {'dependencies': [{'name': 'foo', 'version': '1.0', 'vulns': [{'id': 'VULN-0', 'fix_versions': ['1.1', '1.4']}]}, {'name': 'bar', 'skip_reason': 'skip-reason'}], 'fixes': []} assert (json_format.format(v...
class GumballMachine(): soldOutState: State noQuarterState: State hasQuarterState: State soldState: State winnerState: State state: State = SoldOutState count: int = 0 def __init__(self, numberGumballs: int): self.soldOutState = SoldOutState(self) self.noQuarterState = No...
def _apply_min_max(df: pd.DataFrame, old_min: ((int | float) | pd.Series), old_max: ((int | float) | pd.Series), new_min: ((int | float) | pd.Series), new_max: ((int | float) | pd.Series)) -> pd.DataFrame: old_range = (old_max - old_min) new_range = (new_max - new_min) return ((((df - old_min) * new_range) ...
class Timer(): def __init__(self, name='task', verbose=True): self.name = name self.verbose = verbose def __enter__(self): self.start = time.time() return self def __exit__(self, exc_type, exc_val, exc_tb): if self.verbose: print('[Time] {} consumes {:.4f}...
class PairAccumulator(Accumulator): def __init__(self): super().__init__() self._labels = [] self._pairs = [] self._subgroups = [] self._accumulated_size = 0 def state(self) -> Dict[(str, torch.Tensor)]: state = super().state state.update({'labels': self.l...
def zenodo_api_with_helpful_fallback(url, method, **kwargs): hostname = urllib.parse.urlparse(url).hostname access_token = get_zenodo_access_token(hostname) kwargs['params'] = {'access_token': access_token} r = getattr(requests, method)(url, **kwargs) if (r.status_code == 401): print('The ac...
def counting_context_manager(): nitems = 50 with progress.task('counting (context manager)', nitems, logger=logger) as task: for iitem in range(nitems): if (iitem > (nitems // 2)): message = 'over half already done!' else: message = None ...
class ResourceBaseDeleteView(LoginRequiredMixin, ResourceBaseContextMixin, DeleteView): context_object_file = 'object' template_name = 'base/confirm_delete.html' def dispatch(self, request, *args, **kwargs): object = self.get_object() user = self.request.user if (not check_resources_...
class StateWrapper(object): def __init__(self, state, workflow): self.state = state self.workflow = workflow for st in workflow.states: setattr(self, ('is_%s' % st.name), (st.name == self.state.name)) def __eq__(self, other): if isinstance(other, self.__class__): ...
def test_unsupported_not_forwarded() -> None: class FakeFile(io.RawIOBase): def unsupported_attr(self) -> None: pass async_file = trio.wrap_file(FakeFile()) assert hasattr(async_file.wrapped, 'unsupported_attr') with pytest.raises(AttributeError): async_file.unsupported_attr
class PotentialPair1plus1D(BasePotentialPair): def __init__(self, param): super().__init__(param) def set_boundary_conditions(self, variables): phi_s_cn = variables['Negative current collector potential [V]'] phi_s_cp = variables['Positive current collector potential [V]'] param ...
def eval_metrics(results, gt_seg_maps, num_classes, ignore_index, metrics=['mIoU'], nan_to_num=None, label_map=dict(), reduce_zero_label=False, beta=1): if isinstance(metrics, str): metrics = [metrics] allowed_metrics = ['mIoU', 'mDice', 'mFscore'] if (not set(metrics).issubset(set(allowed_metrics))...
def assert_focus_path(self, *names): for i in names: self.c.group.next_window() assert_focused(self, i) for i in names: self.c.group.next_window() assert_focused(self, i) for i in reversed(names): assert_focused(self, i) self.c.group.prev_window() for i in...
def draw_pareto_changing_b(b_set, num_classes, max=1000, min=1, head=0.0, tail=0.99, save_name='./pareto_ref.jpg'): (fig, ax) = plt.subplots(1, 1) classes = np.linspace(0, num_classes, (10 * num_classes)) for (i, b) in enumerate(b_set): rv = pareto(b) classes_x = np.linspace(pareto.ppf(head,...
def get_micronet_score(net, weight_bits, activation_bits, weight_strategy=None, activation_strategy=None, input_res=(3, 224, 224), baseline_params=6900000, baseline_MAC=): flops_model = add_flops_counting_methods(net) flops_model.eval().start_flops_count() batch = torch.ones(()).new_empty((1, *input_res), d...
class UnivariatePiecewiseLinearObjective(CircuitFactory): def __init__(self, num_state_qubits: int, min_state_value: float, max_state_value: float, breakpoints: Union[(List[float], np.ndarray)], slopes: Union[(List[float], np.ndarray)], offsets: Union[(List[float], np.ndarray)], f_min: float, f_max: float, c_approx...
def test_query_grant(graphql_client, user, conference, grant_factory): graphql_client.force_login(user) grant = grant_factory(user_id=user.id, conference=conference) response = graphql_client.query('query($conference: String!) {\n me {\n grant(conference: $conference) {\n ...
class Deterministic_Wallet(Abstract_Wallet): def __init__(self, db, storage, *, config): self._ephemeral_addr_to_addr_index = {} Abstract_Wallet.__init__(self, db, storage, config=config) self.gap_limit = db.get('gap_limit', 20) self.synchronize() if self.can_have_lightning()...
class Migration(migrations.Migration): dependencies = [('questions', '0085_section_pages')] operations = [migrations.CreateModel(name='PageQuestionSet', fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('order', models.IntegerField(default=0)), ('page', ...
class TerminusPasteFromHistoryCommand(sublime_plugin.TextCommand): def run(self, edit): paste_list = g_clipboard_history.get() keys = [x[0] for x in paste_list] self.view.show_popup_menu(keys, (lambda choice_index: self.paste_choice(choice_index))) def is_enabled(self): return (n...
def test_loop_variable_initialized_in_loop() -> None: with AccumulationTable(['i']) as table: for number in [10, 20, 30, 40, 50, 60]: i = number assert (table.loop_variables == {'number': ['N/A', 10, 20, 30, 40, 50, 60]}) assert (table.loop_accumulators == {'i': ['N/A', 10, 20, 30, 40, 5...
def minimize(fun: Callable[(..., float)], x0: np.ndarray, args: Tuple=(), method: Optional[str]=None, **kwargs) -> scipy.optimize.OptimizeResult: if (method.lower() in OPTIMIZERS): optimizer = OPTIMIZERS[method.lower()] return optimizer(fun, x0, args=args, **kwargs) return scipy.optimize.minimiz...
class ThreadState(): def __init__(self, name, trace): self.root = CallNode({}, OrderedDict(), None) self.calltree = self.root self.curr = self.calltree self.context_switch = 0 self.name = name if trace: self.depth = (len(trace) - 1) for call in...
def test_voting_open_and_user_can_vote(graphql_client, submission_factory, user, other_user, mocker): submission = _submission(submission_factory, user) graphql_client.force_login(other_user) can_vote_mock = mocker.patch('api.submissions.permissions.check_if_user_can_vote', return_value=True) data = _qu...
def initialize_decoder(module): for m in module.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_uniform_(m.weight, mode='fan_in', nonlinearity='relu') if (m.bias is not None): nn.init.constant_(m.bias, 0) elif isinstance(m, nn.BatchNorm2d): ...
('/suite', methods=['GET', 'POST']) def suite(): if (not session.get('logged_in')): return redirect(url_for('login')) if (request.method == 'GET'): project = [elem[0] for elem in g.db.execute('select name from project;').fetchall()] return render_template('suite.html', projects=project) ...
def findContours(*args, **kwargs): if cv2.__version__.startswith('4'): (contours, hierarchy) = cv2.findContours(*args, **kwargs) elif cv2.__version__.startswith('3'): (_, contours, hierarchy) = cv2.findContours(*args, **kwargs) else: raise AssertionError('cv2 must be either version 3...
def test(strng): print(strng) try: iniFile = open(strng) iniData = ''.join(iniFile.readlines()) bnf = inifile_BNF() tokens = bnf.parseString(iniData) pp.pprint(tokens.asList()) except ParseException as err: print(err.line) print(((' ' * (err.column - 1...
def _get_example(language: str) -> str: if (language.lower() in _parsing.PY_LANG_CODES): log.trace(f'Code block has a Python language specifier `{language}`.') content = _EXAMPLE_PY.format(lang=language) elif language: log.trace(f'Code block has a foreign language specifier `{language}`....
def _generate_mock_adapters(): mock_lo0 = Mock(spec=ifaddr.Adapter) mock_lo0.nice_name = 'lo0' mock_lo0.ips = [ifaddr.IP('127.0.0.1', 8, 'lo0')] mock_lo0.index = 0 mock_eth0 = Mock(spec=ifaddr.Adapter) mock_eth0.nice_name = 'eth0' mock_eth0.ips = [ifaddr.IP(('2001:db8::', 1, 1), 8, 'eth0')] ...
def temporary_failure(count=1): return f''' import py path = py.path.local(__file__).dirpath().ensure('test.res') count = path.read() or 1 if int(count) <= {count}: path.write(int(count) + 1) raise Exception('Failure: {{0}}'.format(coun...
class Money(): def __init__(self, money=None, chntext=None): self.money = money self.chntext = chntext def money2chntext(self): money = self.money pattern = re.compile('(\\d+(\\.\\d+)?)') matchers = pattern.findall(money) if matchers: for matcher in ma...
class Time2CapAmountGetter(SmoothPointGetter): def getRange(self, xRange, miscParams, src, tgt): if (not miscParams['useCapsim']): return super().getRange(xRange=xRange, miscParams=miscParams, src=src, tgt=tgt) capAmountT0 = (miscParams['capAmountT0'] or 0) capSimDataRaw = src.it...
def test_prevent_redundant_quantity(blank_game_description): db = blank_game_description.resource_database (res_a, id_req_a) = make_req_a(db) (res_b, id_req_b) = make_req_b(db) the_set = RequirementSet([RequirementList([id_req_a]), RequirementList([id_req_a, id_req_b]), RequirementList([ResourceRequirem...
class MultiResolutionDataset(Dataset): def __init__(self, path, transform, resolution=8): self.env = lmdb.open(path, max_readers=32, readonly=True, lock=False, readahead=False, meminit=False) if (not self.env): raise IOError('Cannot open lmdb dataset', path) with self.env.begin(w...