code
stringlengths
281
23.7M
.usefixtures('use_tmpdir') def test_that_giving_too_many_arguments_gives_config_validation_error(): test_config_file_name = 'test.ert' test_config_contents = dedent('\n NUM_REALIZATIONS 1\n ENKF_ALPHA 1.0 2.0 3.0\n ') with open(test_config_file_name, 'w', encoding='utf-8') as fh: ...
_blueprint.route('/users', methods=['GET']) _required def browse_users(): if (not is_admin()): flask.abort(401) user_id = flask.request.args.get('user_id', None) username = flask.request.args.get('username', None) email = flask.request.args.get('email', None) admin = flask.request.args.get('...
def upgrade(): connection = op.get_bind() connection.execute('pragma foreign_keys=OFF') with op.batch_alter_table('kronos_device', schema=None) as batch_op: batch_op.add_column(sa.Column('frontButton', sa.Boolean(), nullable=True)) batch_op.add_column(sa.Column('timezone', sa.Text(), nullabl...
def makeParametrizedVF(glyphOrder, features, values, increments): assert (values and (len(values) == len(increments))) assert all(((len(i) == 2) for i in increments)) masterLocations = [{'wght': 100, 'wdth': 50}, {'wght': 100, 'wdth': 100}, {'wght': 100, 'wdth': 150}, {'wght': 400, 'wdth': 50}, {'wght': 400...
.parametrize(('words', 'transformed_expected'), [((), ''), (('oneword',), 'oneword'), (('two', 'words'), 'two words'), ((' ', 'words', 'with', 'whitespace', '\n'), 'words with whitespace')]) def test_single_line_magic_transform(ocr_result, words, transformed_expected): ocr_result.words = [{'text': w} for w in words...
def extractGrowWithMe(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None if ('zui wu dao' in item['tags']): (vol, chp, frag) = (frag, chp, 0) return buildReleaseMessageWithTyp...
def test_matcher_operator_shadow(en_vocab): matcher = Matcher(en_vocab) doc = Doc(en_vocab, words=['a', 'b', 'c']) pattern = [{'ORTH': 'a'}, {'IS_ALPHA': True, 'OP': '+'}, {'ORTH': 'c'}] matcher.add('A.C', [pattern]) matches = matcher(doc) assert (len(matches) == 1) assert (matches[0][1:] ==...
def test_query_more_multibatch(): testutil.add_response('login_response_200') testutil.add_response('query_more_multibatch_0_200') testutil.add_response('query_more_multibatch_1_200') testutil.add_response('query_more_multibatch_2_200') testutil.add_response('api_version_response_200') client = ...
class OptionPlotoptionsPyramidEvents(Options): def afterAnimate(self): return self._config_get(None) def afterAnimate(self, value: Any): self._config(value, js_type=False) def checkboxClick(self): return self._config_get(None) def checkboxClick(self, value: Any): self._co...
class SecurityCenterClient(object): def __init__(self, global_configs): (max_calls, quota_period) = api_helpers.get_ratelimiter_config(global_configs, API_NAME) cache_discovery = (global_configs['cache_discovery'] if ('cache_discovery' in global_configs) else False) self.repository = Securit...
class OptionPlotoptionsWaterfallTooltipDatetimelabelformats(Options): def day(self): return self._config_get('%A, %e %b %Y') def day(self, text: str): self._config(text, js_type=False) def hour(self): return self._config_get('%A, %e %b, %H:%M') def hour(self, text: str): ...
.asyncio .workspace_host class TestCreateEncryptionKey(): async def test_unauthorized(self, unauthorized_api_assertions: HTTPXResponseAssertion, test_client_api: test_data: TestData): client = test_data['clients']['default_tenant'] response = (await test_client_api.post(f'/clients/{client.id}/encry...
class Red(Theme.Theme): _charts = ['#009999', '#336699', '#ffdcb9', '#cc99ff', '#b3d9ff', '#ffff99', '#000066', '#b2dfdb', '#80cbc4', '#e0f2f1', '#b2dfdb', '#80cbc4', '#ffebee', '#ffcdd2', '#ef9a9a', '#f3e5f5', '#e1bee7', '#ce93d8', '#ede7f6', '#d1c4e9', '#b39ddb', '#e8eaf6', '#c5cae9', '#9fa8da', '#fffde7', '#fff9...
class OptionPlotoptionsWaterfallSonificationContexttracksMappingTime(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: str): ...
class HasManyViaSet(ViaSet): _via_error = "Can't %s elements in has_many relations without a join table" def _cache_resultset(self): return self.select(self._viadata.rfield) def __call__(self, *args, **kwargs): refresh = self._filter_reload(kwargs) if (not args): if (not ...
class Eth(BaseEth): w3: 'Web3' _default_contract_factory: Type[Union[(Contract, ContractCaller)]] = Contract _accounts: Method[Callable[([], Tuple[ChecksumAddress])]] = Method(RPC.eth_accounts, is_property=True) def accounts(self) -> Tuple[ChecksumAddress]: return self._accounts() _hashrate:...
class JSONOpenAPIRenderer(BaseRenderer): media_type = 'application/vnd.oai.openapi+json' charset = None encoder_class = encoders.JSONEncoder format = 'openapi-json' ensure_ascii = (not api_settings.UNICODE_JSON) def render(self, data, media_type=None, renderer_context=None): return json....
def _consolidate_batches(batches: Sequence[TransitionBatch]) -> TransitionBatch: len_batches = len(batches) b0 = batches[0] obs = np.empty(((len_batches,) + b0.obs.shape), dtype=b0.obs.dtype) act = np.empty(((len_batches,) + b0.act.shape), dtype=b0.act.dtype) next_obs = np.empty(((len_batches,) + b0...
def generate_c(model, name='myclassifier'): (n_classes, n_features, n_attributes) = model.shape assert (n_attributes == 3) cgen.assert_valid_identifier(name) summaries_data = [] for (class_n, class_summaries) in enumerate(model): for (feature_n, summary) in enumerate(class_summaries): ...
def get_pr_rec_plot_data(current_pr_curve: PRCurve, reference_pr_curve: Optional[PRCurve], color_options: ColorOptions) -> List[Tuple[(str, BaseWidgetInfo)]]: additional_plots = [] cols = 1 subplot_titles = [''] if (reference_pr_curve is not None): cols = 2 subplot_titles = ['current', '...
def read_small(mmap=False): f = _segyio.segyiofd(str((testdata / 'small.sgy')), 'r', 0).segyopen() if mmap: f.mmap() ilb = 189 xlb = 193 metrics = f.metrics() metrics.update(f.cube_metrics(ilb, xlb)) sorting = metrics['sorting'] trace_count = metrics['tracecount'] inline_coun...
def lambda_handler(event, context): print('event: ', event) idempotency_key = event['detail']['idempotency-key'] time = event['time'] consumer = 'SendEmail' try: idempotency_response = check_idempotency_key(idempotency_key, consumer) except Exception as e: print(f'Error: Failed t...
(no_gui_test_assistant, 'No GuiTestAssistant') (no_modal_dialog_tester, 'ModalDialogTester unavailable') class TestMessageDialogHelpers(unittest.TestCase, GuiTestAssistant): def test_information(self): self._check_dialog(information) def test_warning(self): self._check_dialog(warning) def te...
class DocumentMeta(BaseModel): identifier: str filename: str = Field(..., alias='fileName') is_archived: bool = Field(..., alias='isArchived') is_confirmed: bool = Field(..., alias='isConfirmed') is_ocrd: bool = Field(..., alias='isOcrd') is_rejected: bool = Field(..., alias='isRejected') is...
class Animator(Gtk.DrawingArea): def __init__(self, **properties): super().__init__(**properties) self.set_size_request(200, 80) self.connect('draw', self.do_drawing) GLib.timeout_add(50, self.tick) def tick(self): self.queue_draw() return True def do_drawing(...
def test_single_branch_multiple_empty_blocks_between_stack_fail(): cfg = ControlFlowGraph() cfg.add_nodes_from([(n0 := BasicBlock(0, instructions=[])), (n1 := BasicBlock(1, instructions=[Branch(Condition(OperationType.equal, [Variable('canary'), Constant(0)]))])), (n2 := BasicBlock(2, instructions=[Return([Cons...
def test_fdata_suppressed(tmpdir, merge_lis_prs): fpath = os.path.join(str(tmpdir), 'suppressed.lis') content = ((headers + ['data/lis/records/curves/dfsr-suppressed.lis.part', 'data/lis/records/curves/fdata-suppressed.lis.part']) + trailers) merge_lis_prs(fpath, content) with lis.load(fpath) as (f,): ...
def extractWwwRaisminetranslationsCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')] for (tagname, name, tl_...
class SiteType(object): def __init__(self, site_type): self.type = site_type['type'] self.site_pins = {} for (site_pin, site_pin_info) in site_type['site_pins'].items(): self.site_pins[site_pin] = SiteTypePin(name=site_pin, direction=SitePinDirection(site_pin_info['direction'])) ...
def humanbytes(B: float): B = float(B) KB = float(1024) MB = float((KB ** 2)) GB = float((KB ** 3)) TB = float((KB ** 4)) if (B < KB): return '{0} {1}'.format(B, ('Bytes' if (0 == B > 1) else 'Byte')) elif (KB <= B < MB): return '{0:.2f} KB'.format((B / KB)) elif (MB <= B...
def validate_google_id_token(request): csrf_token_cookie = request.COOKIES.get('g_csrf_token', None) if (not csrf_token_cookie): raise Exception('No CSRF token in Cookie.') csrf_token_body = request.POST.get('g_csrf_token', None) if (not csrf_token_body): raise Exception('No CSRF token i...
class StickerSet(JsonDeserializable): def de_json(cls, json_string): if (json_string is None): return None obj = cls.check_json(json_string) stickers = [] for s in obj['stickers']: stickers.append(Sticker.de_json(s)) obj['stickers'] = stickers ...
class SpeciesTrait(Base): __tablename__ = 'species_trait' trait_id = Column(Integer, primary_key=True) description_id = Column(ForeignKey(SharedDescription.description_id)) species_id = Column(ForeignKey(Species.species_id), index=True) species = relationship(Species, back_populates='db_traits') ...
class Lane(object): def __init__(self, ctx, idx, midich, parent=None): self.idx = idx self.midi = ctx.midi self.ctx = ctx self.schedule = self.ctx.schedule def master(self): return (self.parent if self.parent else self) def reset(self): self.notes = ([0] * RAN...
class BatchFirewallEnforcerTest(constants.EnforcerTestCase): def setUp(self): super(BatchFirewallEnforcerTest, self).setUp() self.batch_enforcer = batch_enforcer.BatchFirewallEnforcer(dry_run=True) self.batch_enforcer._local = mock.Mock(compute_client=self.gce_api_client) self.expect...
def card_cmd(): _cli.command(short_help='Get model info card', help='Get model info card from Ersilia Model Hub.') ('model', type=click.STRING) ('-s', '--schema', is_flag=True, default=False, help='Show schema of the model') ('-l', '--lake', is_flag=True, default=False, help='Show the properties of the ...
def paws_x_zh(): datasets_name = sys._getframe().f_code.co_name writer = open('./collect_datasets/{}.txt'.format(datasets_name), 'w') base_dir = './STS/{}/'.format(datasets_name) file_list = os.listdir(base_dir) qus_base = ['?{} \\t {}', '?{} \\n {}', '?{} {}', '{} \\t {}?'] ans_true = ['', ''...
class NotebookReader(FileReader): def __init__(self, filepath: str, **kwargs): super().__init__(filepath, **kwargs) with open(self._filepath) as f: self._notebook = nbformat.read(f, as_version=4) self._language = None try: self._language = self._no...
def find_path(node: object, pathfile: str): name = str() path = str() if isinstance(node, ast.ImportFrom): name = node.module if (name in packages_supported_by_pythran): return (None, None) else: parent = Path(pathfile).parent path = (parent / (str...
class TestConfigZones(unittest.TestCase): def test_bounding_boxes_basic(self): zones: dict[(ZoneKey, Any)] = {ZoneKey('AD'): {'bounding_box': [[0.906, 41.928], [2.265, 43.149]]}, ZoneKey('XX'): {}} self.assertDictEqual(zone_bounding_boxes(zones), {ZoneKey('AD'): [[0.906, 41.928], [2.265, 43.149]]}) ...
class TestsAchromatic(util.ColorAsserts, unittest.TestCase): def test_achromatic(self): self.assertEqual(Color('srgb', [0.3, 0.3, 0.3]).convert('ryb').is_achromatic(), True) self.assertEqual(Color('srgb', [0.3, 0.3, 0.]).convert('ryb').is_achromatic(), True) self.assertEqual(Color('srgb', [0...
class HTMLCorpusReader(CategorizedCorpusReader, CorpusReader): def __init__(self, root, fileids=DOC_PATTERN, word_tokenizer=WordPunctTokenizer(), sent_tokenizer=nltk.data.LazyLoader('tokenizers/punkt/english.pickle'), encoding='latin-1', **kwargs): if (not any((key.startswith('cat_') for key in kwargs.keys(...
class SemanticVersionTests(unittest.TestCase): def test_identity_string(self): self.assertEqual('Semantic', semver.SemanticVersion.name) def test_prerelease_false(self): version = semver.SemanticVersion(version='1.0.0') self.assertFalse(version.prerelease()) def test_prerelease_prere...
def check_menu_item(name: str, after, display_name: str, checked_func: Callable[(..., bool)], callback) -> 'MenuItem': (accelerator, callback, display_name) = _get_accel(callback, display_name) def factory(menu, parent, context): item = Gtk.CheckMenuItem.new_with_mnemonic(display_name) active = ...
('subprocess.check_call') def test_run_command(mock_check_call): mock_check_call.side_effect = check_call_side_effect cmd_parameters = cmd_exec.CommandParameters(cwd='/tmp') cmd = 'spanish_output_stdout' output = cmd_exec.run_command(cmd, cmd_parameters) assert (output == 'No te hablas una palabra d...
def extractIsotlsCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None if (item['tags'] == []): titlemap = [('Quick Transmigration Female Lead: Male God, Never Stopping Chapter', 'Qu...
class ProtestsPretrained(Analyser): def pre_analyse(self, config): rLabels = config['labels'] self.THRESH = 0.0 t = transform() model = modified_resnet50() model.load_state_dict(torch.load(PTH_TAR, map_location=torch.device('cpu'))['state_dict']) model.eval() ...
def db_read(dbstate, tiletype, db_dir): dbstate.cfgbits[tiletype] = dict() dbstate.cfgbits_r[tiletype] = dict() dbstate.maskbits[tiletype] = set() dbstate.ppips[tiletype] = dict() dbstate.routebits[tiletype] = dict() dbstate.routezbits[tiletype] = dict() def add_pip_bits(tag, bits): ...
class Resource(object): def __init__(self, cai_resource_name, cai_resource_type, full_name, type_name, data): self.cai_resource_name = cai_resource_name self.cai_resource_type = cai_resource_type self.full_name = full_name self.type_name = type_name self.data = data
def display_snapshot_detail(repo_name=None, snapshot_name=None): es_client = create_es_client() repo_name = (repo_name or CASE_REPO) snapshot_name = (snapshot_name or '*') configure_snapshot_repository(repo_name) result = es_client.snapshot.get(repository=repo_name, snapshot=snapshot_name) logge...
.skip('These tests take a very long time to compute') def test_inv_j2(): with set_double_precision(): low = torch.randn(1, 3, 16, 16, device=dev, requires_grad=True) high = torch.randn(1, 3, 6, 8, 8, 2, device=dev, requires_grad=True) ifm = DTCWTInverse().to(dev) input = (low, high, ifm....
def gen_touch_tunes(pin=0): dirname = f'touch_tunes-{pin:03d}' if (not os.path.isdir(dirname)): os.mkdir(dirname) for (cmdname, cmd) in TOUCH_TUNES_COMMANDS.items(): with open((((dirname + '/') + cmdname) + '.sub'), 'w') as f: print(gen_sub(, 566, 566, 1, 0, encode_touchtunes(cmd...
def get_last_dagrun_info() -> List[DagStatusInfo]: assert (Session is not None) last_dagrun_query = Session.query(DagRun.dag_id, DagRun.state, func.row_number().over(partition_by=DagRun.dag_id, order_by=DagRun.execution_date.desc()).label('row_number')).subquery() sql_res = Session.query(last_dagrun_query.c...
def main(): parser = argparse.ArgumentParser(description='Generic LiteX SoC Simulation') builder_args(parser) soc_core_args(parser) parser.add_argument('--threads', default=1, help='Set number of threads (default=1)') parser.add_argument('--rom-init', default=None, help='rom_init file') parser.a...
class OptionSeriesGaugeSonificationDefaultinstrumentoptionsMappingNoteduration(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text:...
def batchlist_attribute_hook(ctx: AttributeContext) -> Type: if isinstance(ctx.type, UnionType): for i in ctx.type.items: if (isinstance(i, Instance) and (i.type.fullname == 'utils.misc.BatchList')): instance = i break elif isinstance(ctx.type, Instance): ...
class InvalidVersion(AnityaException): def __init__(self, version, exception=None): self.version = version self.exception = exception def __str__(self): if self.exception: return f'Invalid version "{self.version}": {str(self.exception)}' else: return f'Inv...
def test_suite_loading(data): (ref, curr) = data ts = TestSuite([BinaryClassificationTestPreset()]) ts.run(reference_data=ref, current_data=curr) ts._inner_suite.raise_for_error() ts.save('profile.json') ts2 = TestSuite.load('profile.json') assert (ts2.as_dict() == ts.as_dict())
class Rook(Piece): def __init__(self, x, y, d): super().__init__(x, y, d) self.set_letter('R') def drag(self, new_p, pieces): if self.grabbed: (path, dist) = self.select_path((self.start_x, self.start_y), [[1, 0], [0, 1]], new_p) path_len = math.sqrt(((path[0] ** ...
class MockReloader(AbstractReloader): def __init__(self, *args, **kwargs): super(MockReloader, self).__init__(*args, **kwargs) self.code_changed_called = False self.code_changed_return_value = False self.code_changed_set_watching_to = False def code_changed(self): self.co...
def cells(): import time def query_db(): time.sleep(5) return [1, 2, 3, 4, 5] def clean(data): time.sleep(2) return [x for x in data if ((x % 2) == 0)] def myfilter(data): time.sleep(2) return [x for x in data if (x >= 3)] '\n ' rows = query_db(...
class FullTreeGenerator(SimpleTreeGenerator): def __init__(self, **traits): super(FullTreeGenerator, self).__init__(**traits) self.last_transform = 0 def get_children(self, obj): vtk_obj = tvtk.to_vtk(obj) methods = self._get_methods(vtk_obj) kids = {} def _add_ki...
class TraitMap(TraitHandler): is_mapped = True def __init__(self, map): self.map = map self.fast_validate = (ValidateTrait.map, map) def validate(self, object, name, value): try: if (value in self.map): return value except: pass ...
class CraftingRecipe(CraftingRecipeBase): name = 'crafting recipe' consumable_tag_category = 'crafting_material' tool_tag_category = 'crafting_tool' tool_tags = [] tool_names = [] exact_tools = True exact_tool_order = False error_tool_missing_message = 'Could not craft {outputs} without ...
class FeatureEmbeddingWrapper(torch.nn.Module): def __init__(self, model: DiffSinger): super().__init__() self.model = model def forward(self, hubert, mel2ph, spk_embed, f0): decoder_inp = F.pad(hubert, [0, 0, 1, 0]) mel2ph_ = mel2ph.unsqueeze(2).repeat([1, 1, hubert.shape[(- 1)]...
def eos_account_to_es(): account = db.accounts count = account.count() logger.info('current account size:{}'.format(count)) actions = [] start = 0 size = 1000 while True: for item in account.find().skip(start).limit(size): liquidEos = item.get('liquid_eos', 0) ...
def test_mention_from_range(): data = {'length': 17, 'offset': 0, 'entity': {'__typename': 'User', 'id': '1234'}} assert (Mention(thread_id='1234', offset=0, length=17) == Mention._from_range(data)) data = {'length': 2, 'offset': 10, 'entity': {'__typename': 'MessengerViewer1To1Thread'}} assert (Mention...
def extractHomescribbleMybluemixNet(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('Great Tang Idyll Translations', 'Great Tang Idyll', 'translated'), ('Great Tang Idyll Chapte...
.parametrize('compiled', [True, False]) def test_expressions(compiled): c = cstruct.cstruct() c.load('\n #define const 1\n struct test {\n uint8 flag;\n uint8 data_1[flag & 1 * 4];\n uint8 data_2[flag & (1 << 2)];\n uint8 data_3[const];\n };\n ', compiled=compiled...
class TraceBack(object): def __init__(self, compress=False): self.__prev = '' self.__compress = compress def __call__(self): ftb = traceback.extract_stack(limit=100)[:(- 2)] entries = [[mbasename(x[0]), os.path.dirname(x[0]), str(x[1])] for x in ftb] entries = [[e[0], e[2...
class ValvePortDescTestCase(ValveTestBases.ValveTestNetwork): CONFIG = ('\ndps:\n s1:\n%s\n interfaces:\n p1:\n number: 1\n native_vlan: v100\n p2:\n number: 2\n native_vlan: v100\nvlans:\n v100:\n vid: 0x100\n ...
def test_optimizer_schedules_valid(schedule_valid): (lr, lr_next1, lr_next2, lr_next3) = schedule_valid optimizer = Optimizer(learn_rate=lr) assert (optimizer.learn_rate == lr_next1) optimizer.step_schedules() assert (optimizer.learn_rate == lr_next2) optimizer.step_schedules() assert (optim...
def process_stack(threadName, q): while (not exitFlag_stacking): queueLock.acquire() if (not workQueue_stacking.empty()): data = q.get() queueLock.release() stack_name = data.split(' ')[1] stack_name = Path(stack_name).name[:(- 15)] temp_ou...
.skipif(utils.complex_mode, reason='Differentiation of energy not defined in Complex.') def test_auxiliary_dm(): problem = BiharmonicProblem(5, 1) mesh = problem.mesh() Ue = FiniteElement('DG', mesh.ufl_cell(), 1) Ve = FiniteElement('RT', mesh.ufl_cell(), 2) Se = FiniteElement('RT', mesh.ufl_cell(),...
def downgrade(): op.execute("UPDATE custom_forms SET name='Accept Video Recording' WHERE form='attendee' and (field_identifier='acceptVideoRecording');") op.execute("UPDATE custom_forms SET name='Accept Share Details' WHERE form='attendee' and(field_identifier='acceptShareDetails');") op.execute("UPDATE cus...
class GreenFileIO(_OriginalIOBase): def __init__(self, name, mode='r', closefd=True, opener=None): if isinstance(name, int): fileno = name self._name = ('<fd:%d>' % fileno) else: assert isinstance(name, str) with open(name, mode) as fd: ...
class Name_Value_Pair(Node): def __init__(self, n_name): super().__init__() assert isinstance(n_name, Identifier) self.n_name = n_name self.n_name.set_parent(self) self.t_eq = None self.n_value = None def loc(self): return self.n_name.loc() def set_val...
def run_trial(serving=False): if serving: bb.run(alg='serving') else: bb.run(alg='stochastic_radial_basis_function') x0 = bb.randrange('x0', 1, 11, guess=5) x1 = bb.uniform('x1', 0, 1) x2 = bb.choice('x2', [(- 10), (- 1), 0, 1, 10]) y = (x0 + (x1 * x2)) bb.minimize(y) ret...
class OptionSeriesSunburstSonificationTracksActivewhen(Options): def crossingDown(self): return self._config_get(None) def crossingDown(self, num: float): self._config(num, js_type=False) def crossingUp(self): return self._config_get(None) def crossingUp(self, num: float): ...
class CoordinateLineOverlay(AbstractOverlay): index_data = Array value_data = Array line_width = Float(1.0) color = black_color_trait line_style = LineStyle component = Instance(Component) def overlay(self, component, gc, view_bounds, mode='normal'): comp = self.component x_p...
class ChunkedFileStream(): def __init__(self, path): self.path = path with open(path, 'r', encoding='utf-8') as f: data = f.read() self.chunk_size = 2000 self.chunks = self.chunk(data) self.chunk_index = 0 def read_chunk(self): if (self.chunk_index >= ...
_checkable class Lockable(Protocol): def acquire(self, blocking: bool=True, timeout: float=(- 1)) -> bool: raise AssertionError('Should be overriden') def release(self) -> None: raise AssertionError('Should be overriden') def locked(self) -> bool: raise AssertionError('Should be over...
class TestLabgraphYamlAPI(unittest.TestCase): def setUp(self) -> None: tests_code_dir: str = 'tests_code' tests_dir: str = pathlib.Path(__file__).parent.absolute() self.tests_dir: str = os.path.join(tests_dir, tests_code_dir) def test_loader_load_from_file_success(self) -> None: ...
def _hellinger_distance(reference_data: pd.Series, current_data: pd.Series, feature_type: ColumnType, threshold: float) -> Tuple[(float, bool)]: reference_data.dropna(inplace=True) current_data.dropna(inplace=True) keys = list((set(reference_data.unique()) | set(current_data.unique()))) if (feature_type...
def test_cli_get_int(): assert (cli_options.getint('opt.int') == 42) assert (cli_options.getint('opt.int', fallback=43) == 42) assert (cli_options.getint('opt.missing', fallback=43) == 43) with pytest.raises(KeyError): cli_options.getint('opt.missing') with pytest.raises(KeyError): c...
.skipif((not has_tensorflow), reason='needs TensorFlow') def test_tensorflow_wrapper_keras_subclass_decorator(): import tensorflow as tf class UndecoratedModel(tf.keras.Model): def call(self, inputs): return inputs with pytest.raises(ValueError): TensorFlowWrapper(UndecoratedMode...
def test_template_raises_exception_if_incorrect_container_build_provided(template_klass, sf): with pytest.raises(TypeError): template_klass(container_building='foo', selection_function=sf, reverse_selection_function=sf, model=scared.HammingWeight()) with pytest.raises(TypeError): template_klass(...
def create_normals(template, lab_test): lab_test.normal_toggle = 1 normal = lab_test.append('normal_test_items') normal.lab_test_name = template.lab_test_name normal.lab_test_uom = template.lab_test_uom normal.secondary_uom = template.secondary_uom normal.conversion_factor = template.conversion_...
class TestCertificateRequest(unittest.TestCase): TEST_KEY_ALGORITHM = KeyAlgorithm.RSA TEST_KEY_SIZE = 4096 TEST_PASSPHRASE = 'test' TEST_ORGANIZATION_NAME = 'Test Company' TEST_COUNTRY_NAME = 'US' def test_create_instance(self): expected = CertificateRequest(key_algorithm=self.TEST_KEY_...
def _prepare_res_bus_table(net): if net.res_bus.shape[0]: net.res_bus['node'] = net.res_bus.index col_from_bus = ['substation', 'subnet', 'voltLvl'] net.res_bus[col_from_bus] = net.bus.loc[(net.res_bus.index, col_from_bus)] else: for col in ['node', 'substation', 'subnet', 'voltL...
def test_swag(client, specs_data): example_spec = specs_data['/apispec_1.json']['paths']['/example']['get'] assert ('400' in example_spec['responses']) assert ('401' in example_spec['responses']) assert ('200' in example_spec['responses']) assert (example_spec['responses']['400']['description'] == '...
class LunaString(TreatAs, Skill): treat_as = AttackCard skill_category = ('character', 'active') no_reveal = True use_action = LunaStringPlaceCard color = Card.NOTSET suit = Card.NOTSET number = 0 cost_detached = False def check(self): if self.cost_detached: retur...
('rocm.gemm_rcr_permute_m2n3.gen_profiler') def gemm_gen_profiler(func_attrs, workdir, dim_info_dict): return common.gen_profiler(func_attrs=func_attrs, workdir=workdir, dim_info_dict=dim_info_dict, args_parse=ARGS_PARSER_TEMPLATE.render(), gemm_flag='permute_m2n3', extra_shape_template=permute_common.EXTRA_SHAPE_T...
class TaskModelRun(sl.Task): def __init__(self, *args, **kwargs): super(sl.Task, self).__init__(*args, **kwargs) self.in_first = None self.in_second = None def actual_task_code(self, task_model_first, task_df_first): return task_df_first def out_first(self): return sl...
(scope='function') def alsa_manager(manager_nospawn, monkeypatch, request): FakeProcess.vol = 50 monkeypatch.setattr('qtile_extras.widget.alsavolumecontrol.subprocess', FakeProcess) monkeypatch.setattr('qtile_extras.widget.alsavolumecontrol.shutil.which', which_amixer) class ALSAConfig(libqtile.confread...
class TestPackages(): def test_reset_and_setup(self, reset_packages, setup_package): pass def test_ping(self, fledge_url): conn = conn.request('GET', '/fledge/ping') r = conn.getresponse() assert (200 == r.status) r = r.read().decode() jdoc = json.loads(r...
class EventList(ABC): logger: Logger events: list[Event] def __init__(self, logger: Logger): self.events = [] self.logger = logger def __len__(self): return len(self.events) def append(self, **kwargs): pass def to_list(self) -> list[dict[(str, Any)]]: retu...
(name='api.mon.alerting.action.tasks.mon_action_get', base=MgmtTask) _task(log_exception=False) def mon_action_get(task_id, dc_id, action_name, **kwargs): dc = Dc.objects.get_by_id(int(dc_id)) mon = get_monitoring(dc) try: return mon.action_detail(action_name) except RemoteObjectDoesNotExist as ...
def main() -> int: t8n_arguments(subparsers) b11r_arguments(subparsers) (options, _) = parser.parse_known_args() if (options.evm_tool == 't8n'): t8n_tool = T8N(options) return t8n_tool.run() elif (options.evm_tool == 'b11r'): b11r_tool = B11R(options) return b11r_tool...
class OptionSeriesArearangeDataDragdropDraghandle(Options): def className(self): return self._config_get('highcharts-drag-handle') def className(self, text: str): self._config(text, js_type=False) def color(self): return self._config_get('#fff') def color(self, text: str): ...