code
stringlengths
281
23.7M
.parametrize('distance_matrix, expected_distance', [(distance_matrix1, optimal_distance1), (distance_matrix2, optimal_distance2), (distance_matrix3, optimal_distance3)]) def test_solution_is_optimal(distance_matrix, expected_distance): (_, distance) = solve_tsp_branch_and_bound(distance_matrix) assert (distance...
class CO2eqParametersLifecycle(BaseClasses.CO2eqParametersDirectAndLifecycleBase): parameters = CO2EQ_PARAMETERS_LIFECYCLE ranges_by_mode: dict[(str, tuple[((int | float), (int | float))])] = {'oil': (600, 1600), 'coal': (500, 1600), 'gas': (400, 900), 'geothermal': (30, 199), 'hydro': (10, 25), 'nuclear': (4, ...
.parametrize('method,expected', (('test_endpoint', 'value-a'), ('not_implemented', NotImplementedError))) def test_fixture_middleware(w3, method, expected): w3.middleware_onion.add(construct_fixture_middleware({'test_endpoint': 'value-a'})) if (isinstance(expected, type) and issubclass(expected, Exception)): ...
class PageAboutStory(AbstractCrudObject): def __init__(self, fbid=None, parent_id=None, api=None): self._isPageAboutStory = True super(PageAboutStory, self).__init__(fbid, parent_id, api) class Field(AbstractObject.Field): composed_text = 'composed_text' cover_photo = 'cover_phot...
.parametrize(('input_data', 'expected'), [({}, {}), ({2016: {1: 1, 4: 4}}, {2016: {1: 1, 2: 0, 3: 0, 4: 4}}), ({2000: {12: 1}, 2001: {2: 1}}, {2000: {12: 1}, 2001: {1: 0, 2: 1}}), ({2000: {11: 1}, 2001: {1: 1}}, {2000: {11: 1, 12: 0}, 2001: {1: 1}})]) def test_fill_in_time_gaps(input_data, expected): _fill_in_time_...
def merge_neighbors_loose_p_value(pLoosePValue, pData, pViewpointObj, pResolution, pTruncateZeroPvalues): accepted = {} accepted_line = {} if isinstance(pLoosePValue, float): for key in pData[0]: if pTruncateZeroPvalues: if ((pData[0][key][1] == 0) or (pData[0][key][1] > ...
def _check_updates_dom0(): try: subprocess.check_call(['sudo', 'qubes-dom0-update', '--check-only']) except subprocess.CalledProcessError as e: sdlog.error('dom0 updates required, or cannot check for updates') sdlog.error(str(e)) return UpdateStatus.UPDATES_REQUIRED sdlog.inf...
class WidgetEventFilter(QtCore.QObject): def __init__(self, widget): QtCore.QObject.__init__(self) self._widget = widget def eventFilter(self, obj, event): widget = self._widget if (obj is not widget.control): return False event_type = event.type() if ...
def test_remote_set_signal(remote): mock_client = MagicMock() def checker(request): assert (request.id.signal_id == 'sigid') assert (request.value.scalar.primitive.integer == 3) mock_client.set_signal.side_effect = checker remote._client = mock_client remote.set_signal('sigid', 'exec...
def render_template(input_files, template_file, output_file): if (isinstance(input_files, str) and input_files): input_files = (input_files,) all_input_files = () gen_kw_export_path = (DEFAULT_GEN_KW_EXPORT_NAME + '.json') if os.path.isfile(gen_kw_export_path): all_input_files += (gen_kw...
class aifunc(): model = None embedding_provider = None def __init__(self, tools: List=[]): self.tools = tools def __call__(self, func): (func) def inner(*args, model=None, embedding_provider=None, **kwargs): sig = inspect.signature(func) agent_kwargs = {'m...
class TestMMLEAPMethods(unittest.TestCase): def test_2pl_mml_eap_method(self): rng = np.random.default_rng() n_items = 5 n_people = 150 difficulty = rng.standard_normal(n_items) discrimination = (rng.rayleigh(scale=0.8, size=n_items) + 0.25) thetas = rng.standard_norm...
.django_db def test_match_from_component_both_filters(client, monkeypatch, elasticsearch_award_index, subaward_with_tas): _setup_es(client, monkeypatch, elasticsearch_award_index) resp = query_by_treasury_account_components_subaward(client, {'require': [_agency_path(BASIC_TAS)]}, [component_dictionary(BASIC_TAS...
def displayCode(dom, element): source = dom.executeString(f"getOrGenerateId(getElement('{element}').firstElementChild.nextElementSibling);") code = clean(dom.getValue(source)) target = dom.executeString(f"getOrGenerateId(getElement('{source}').nextElementSibling.nextElementSibling.firstElementChild.nextElem...
class HCI_LEM_Ext_Adv_Report(Packet): def __init__(self): self.name = 'Ext Adv Report' self.payload = [BitFieldByte('ev type', 0, ['Connectable', 'Scannable', 'Directed', 'Scan Response', 'Legacy', 'Incomplete/more', 'Incomplete/truncated', 'RFU']), UIntByte('unused'), EnumByte('addr type', 0, {0: '...
class GymChannel(): THREAD_POOL_SIZE = 3 def __init__(self, address: Address, gym_env: gym.Env): self.address = address self.gym_env = gym_env self._loop: Optional[AbstractEventLoop] = None self._queue: Optional[asyncio.Queue] = None self._threaded_pool: ThreadPoolExecuto...
def test_numpy_ufunc(): vx = [(- 1.0), 0.0, 1.0] vy = [1.0, 2.0, 4.0] vc = [(1j * 0.5), (1.5 + (1j * 2.0)), ((- 0.5) + (1j * 0))] nx = np.asarray(vx) ny = np.asarray(vy) nc = np.asarray(vc) fx = Fxp(vx, True, (16 * 8), (8 * 8)) fy = Fxp(vy, True, (12 * 8), (4 * 8)) fc = Fxp(vc, True,...
class Position(DocType): securityId = Keyword() longAmount = Long() availableLong = Long() averageLongPrice = Long() shortAmount = Long() availableShort = Long() averageShortPrice = Long() value = Float() tradingT = Short() def __init__(self, meta=None, security_id=None, trading_...
('flytekit.remote.remote_callable.create_and_link_node_from_remote') def test_lazy_loading_compile(create_and_link_node_from_remote_mock): once = True def _getter(): nonlocal once if (not once): raise ValueError('Should be called once only') once = False return dummy_...
class OfflineMessageTableStrategy(GasStrategy): DEFAULT_FALLBACK_GAS_LIMIT = 400000 DEFAULT_BLOCK_LIMIT = 2000000 def default_table() -> 'OfflineMessageTableStrategy': strategy = OfflineMessageTableStrategy() strategy.update_entry('cosmos.bank.v1beta1.MsgSend', 100000) strategy.updat...
def test_main(): outfile = NamedTemporaryFile(suffix='.txt', delete=True) args = '--range {} {} -tv {} -o {}'.format(200000, 200000, 0.5, outfile.name).split() hicCreateThresholdFile.main(args) assert are_files_equal((ROOT + 'hicCreateThresholdFile/thresholdFile_loose_pValue.txt'), outfile.name, delta=1...
_router.get('/item/', response_model=CollectionItemListResponse, dependencies=PERMISSIONS_READ) def item_list(queryset: CollectionItemQuerySet=Depends(get_item_queryset), stoken: t.Optional[str]=None, limit: int=50, prefetch: Prefetch=PrefetchQuery, withCollection: bool=False, user: UserType=Depends(get_authenticated_u...
.django_db def test_remove_empty_federal_accounts(): baker.make(FederalAccount, pk=1, agency_identifier='ab1', main_account_code='0987') baker.make(FederalAccount, pk=2, agency_identifier='ab2', main_account_code='0987') baker.make(FederalAccount, pk=4, agency_identifier='ab4', main_account_code='0987') ...
class TestTupleIndexManager(IndexManagerMixin, TestCase): def setUp(self): super().setUp() self.index_manager = TupleIndexManager() def tearDown(self): self.index_manager.reset() def test_complex_sequence_round_trip(self): sequence = (5, 6, 7, 8, 9, 10) index = self.i...
class InlineImage(object): tpl = None image_descriptor = None width = None height = None def __init__(self, tpl, image_descriptor, width=None, height=None): (self.tpl, self.image_descriptor) = (tpl, image_descriptor) (self.width, self.height) = (width, height) def _insert_image(s...
def extractMobileSuitZetaGundamNovelsTranslation(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None if ('WATTT' in item['tags']): return buildReleaseMessageWithType(item, 'WATTT', vol...
def extractYellowpufffWordpressCom(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_typ...
class IAsyncTrainingStartTimeDistr(abc.ABC): def __init__(self, **kwargs) -> None: init_self_cfg(self, component_class=__class__, config_class=AsyncTrainingStartTimeDistrConfig, **kwargs) assert (self.cfg.training_rate > 0), f'Event rate must be positive, got {self.cfg.training_rate}' def _set_d...
.skip def test_en_ner_simple_types(NLP): doc = NLP('Mr. Best flew to New York on Saturday morning.') assert (doc.ents[0].start == 1) assert (doc.ents[0].end == 2) assert (doc.ents[0].label_ == 'PERSON') assert (doc.ents[1].start == 4) assert (doc.ents[1].end == 6) assert (doc.ents[1].label_ ...
class TwoPartSimpleModel(nn.Module): def __init__(self): super().__init__() self.part1 = SimpleModel() self.part2 = SimpleModel() def forward(self, x): x = self.part1(x) x = TwoPartSimpleModel.non_traceable_func(x) x = self.part2(x) return x def prepar...
def test_io_dispersive(tmp_path): Mx_custom = 1.0 My_custom = 2.1 Nx = 10 Ny = 11 x_custom = np.linspace(((- Mx_custom) / 2), (Mx_custom / 2), Nx) y_custom = np.linspace(((- My_custom) / 2), (My_custom / 2), Ny) z_custom = [0] delep_data = np.ones([len(x_custom), len(y_custom), len(z_cus...
class Dispatcher(): def __init__(self): self._registry: Dict[(Type[Operation], Callable[([Operation], str)])] = {} def dispatch_for(self, target: Type[Operation]) -> Callable[([Callable[([Operation], str)]], Callable[([Operation], str)])]: def wrap(fn: Callable[([Operation], str)]) -> Callable[(...
class JsCookies(): def __init__(self, page: Optional[primitives.PageModel]): self.page = page def set(self, key: str, data, data_key: str=None, python_data=True, js_funcs: Optional[Union[(list, str)]]=None): data = JsUtils.jsConvert(data, data_key, python_data, js_funcs) if (self.page._c...
class OptionSeriesPictorialSonificationDefaultspeechoptionsMapping(Options): def pitch(self) -> 'OptionSeriesPictorialSonificationDefaultspeechoptionsMappingPitch': return self._config_sub_data('pitch', OptionSeriesPictorialSonificationDefaultspeechoptionsMappingPitch) def playDelay(self) -> 'OptionSeri...
def load_config_files(config_paths: []) -> dict: config = {} for config_path in config_paths: try: loaded_config = hjson.load(open(config_path, encoding='utf-8')) config = {**config, **loaded_config} except Exception as e: raise Exception('failed to load confi...
def test_script(flatpak_builder: FlatpakBuilder) -> None: COMMANDS = ['echo 123'] with ManifestGenerator() as gen: gen.add_script_source(COMMANDS, Path('script')) flatpak_builder.build(sources=gen.ordered_sources()) with (flatpak_builder.module_dir / 'script').open() as fp: assert fp.rea...
class SplitterGroupEditor(GroupEditor): splitter = Instance(_GroupSplitter) def restore_prefs(self, prefs): if isinstance(prefs, dict): structure = prefs.get('structure') else: structure = prefs self.splitter._initialized = True self.splitter.restoreState(...
class ReconnectLogic(zeroconf.RecordUpdateListener): def __init__(self, *, client: APIClient, on_connect: Callable[([], Awaitable[None])], on_disconnect: Callable[([bool], Awaitable[None])], zeroconf_instance: (ZeroconfInstanceType | None)=None, name: (str | None)=None, on_connect_error: (Callable[([Exception], Awa...
class NoScrollZoom(MacroElement): _name = 'NoScrollZoom' _template = Template('\n {% macro header(this,kwargs) %}\n {% endmacro %}\n {% macro html(this,kwargs) %}\n {% endmacro %}\n {% macro script(this,kwargs) %}\n {{ this._parent.get_name() }}.scrollWheelZoom.disable(...
class VerilatorLPDDR4Tests(unittest.TestCase): ALLOWED = [('WARN', 'tINIT1 violated: RESET deasserted too fast'), ('WARN', 'tINIT3 violated: CKE set HIGH too fast after RESET being released')] def check_logs(self, logs): for match in SimLogger.LOG_PATTERN.finditer(logs): if (match.group('lev...
class OptionSeriesBarSonificationDefaultinstrumentoptionsMappingHighpassFrequency(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, te...
def test_output_reference_with_attr_path(): obj = _types.OutputReference(node_id='node1', var='var1', attr_path=['a', 0]) assert (obj.node_id == 'node1') assert (obj.var == 'var1') assert (obj.attr_path[0] == 'a') assert (obj.attr_path[1] == 0) obj2 = _types.OutputReference.from_flyte_idl(obj.to...
class OptionPlotoptionsColumnSonificationContexttracksMappingTremoloSpeed(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 queue_stats_request(stats_request): version = 6 type = 18 stats_type = 5 def __init__(self, xid=None, flags=None, port_no=None, queue_id=None): if (xid != None): self.xid = xid else: self.xid = None if (flags != None): self.flags = flags ...
class TestSpotifyPlaylistModify(): def test_playlist_modifications(self, user_client, current_user_id): playlist = user_client.playlist_create(current_user_id, 'tekore-test', public=False, description='Temporary test playlist for Tekore') assert (playlist is not None) track_uris = [to_uri('t...
def hostloc_checkin_retry(account, retry=3, strage='local', show_secret=False): while True: try: hostloc_checkin(account, strage='local', show_secret=show_secret) break except RemoteDisconnected: logger.debug('') break except Exception as e: ...
class OptionSeriesBulletSonificationTracksMappingPitch(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('y') def mapTo(self, text: str): self._conf...
_ordering class ForkCriteria(ABC): BLOCK_NUMBER: Final[int] = 0 TIMESTAMP: Final[int] = 1 UNSCHEDULED: Final[int] = 2 _internal: Tuple[(int, int)] def __eq__(self, other: object) -> bool: if isinstance(other, ForkCriteria): return (self._internal == other._internal) retur...
class _ComposedProperty(object): def __init__(self, name): self.name = name def __get__(self, instance, owner): return getattr(instance.real, self.name) def __set__(self, instance, value): return setattr(instance.real, self.name, value) def __delete__(self, instance): ret...
def test_get_font_metrics(fx_asset): with Image(width=144, height=192, background=Color('#fff')) as img: with Drawing() as draw: draw.font = str(fx_asset.joinpath('League_Gothic.otf')) draw.font_size = 13 nm1 = draw.get_font_metrics(img, 'asdf1234') nm2 = draw...
class DeleteSubExtension(Extension): def __init__(self, *args, **kwargs): self.config = {'smart_delete': [True, 'Treat ~~connected~~words~~ intelligently - Default: True'], 'delete': [True, 'Enable delete - Default: True'], 'subscript': [True, 'Enable subscript - Default: True']} super().__init__(*a...
def assert_default_errors(errors, include_ingress_errors=True): default_errors = [['', 'Ambassador could not find core CRD definitions. Please visit for more information. You can continue using Ambassador via Kubernetes annotations, any configuration via CRDs will be ignored...'], ['', 'Ambassador could not find R...
def jagged_to_dense(jagged: torch.Tensor, offsets_list: List[torch.Tensor], dense_shape: List[int], padding_value: float=0.0) -> torch.Tensor: assert all(((t.dim() == 1) for t in offsets_list)) offsets_list = [list(t.cpu().numpy()) for t in offsets_list] _check_offsets(offsets_list) assert ((len(dense_s...
def generate_predictable_pipeline_id(application_name, pipeline_name): seed = (application_name + pipeline_name) pipeline_uuid = uuid.uuid5(_foremast_uuid_namespace, seed) LOG.debug("Generating pipeline id '%s' using namespace '%s' and seed '%s'", pipeline_name, _foremast_uuid_namespace, seed) return pi...
def _apply_dict_type(value, key_type=None, value_type=None): if ((not key_type) and (not value_type)): return dict(value) key_type = (key_type or _identity_function) value_type = (value_type or _identity_function) return {key_type(key): value_type(value) for (key, value) in value.items()}
def firewall_ssh_setting(data, fos): vdom = data['vdom'] firewall_ssh_setting_data = data['firewall_ssh_setting'] filtered_data = underscore_to_hyphen(filter_firewall_ssh_setting_data(firewall_ssh_setting_data)) return fos.set('firewall.ssh', 'setting', data=filtered_data, vdom=vdom)
() _option _option _option _option _option _option def install(edm, runtime, toolkit, environment, editable, source): parameters = get_parameters(edm, runtime, toolkit, environment) packages = ' '.join(((dependencies | toolkit_dependencies.get(toolkit, set())) | runtime_dependencies.get(runtime, set()))) co...
class Color(): def __call__(self, color_str: str=None) -> str: if (not CONFIG.settings['console']['show_colors']): return '' if (not color_str): return (BASE + 'm') try: if (' ' not in color_str): return f'{BASE}{COLORS[color_str]}m' ...
class TestMultipleListenersCleanup(tests.LimitedTestCase): def setUp(self): super().setUp() debug.hub_prevent_multiple_readers(False) debug.hub_exceptions(False) def tearDown(self): super().tearDown() debug.hub_prevent_multiple_readers(True) debug.hub_exceptions(T...
def get_next_event(shot: System, *, transition_cache: Optional[TransitionCache]=None, quartic_solver: QuarticSolver=QuarticSolver.HYBRID) -> Event: event = null_event(time=np.inf) if (transition_cache is None): transition_cache = TransitionCache.create(shot) transition_event = transition_cache.get_n...
def parse_atom_name(name): org_name = name assert (len(name) == 4) name = name.lower() use_full_name = (name in FULL_NAME) if (not use_full_name): name = name[:2] stripped = STRIP_RE.sub('', name).lower() if use_full_name: stripped = stripped[:2] try: mapped = NAM...
class TreeNodePerformanceTestCase(TransactionTestCase): def setUp(self): pass def tearDown(self): pass def test_performance(self): settings.DEBUG = True message_prefix = f'[treenode] create {Category.__module__}.{Category.__name__} tree: ' with debug_performance(messa...
def extractWatashiwasugoidesuCom(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_type)...
(suppress_health_check=[HealthCheck.function_scoped_fixture]) .usefixtures('use_tmpdir') (job_queue_nodes) def test_that_exclude_host_is_in_the_bsub_resource_request(tmp_path, job_queue_node): reset_command_queue(tmp_path) next_command_output('submit', submit_success_output('LSF', 1)) queue_config = QueueCo...
def latest_widevine_version(eula=False): if (eula or cdm_from_repo()): url = config.WIDEVINE_VERSIONS_URL versions = return versions.split()[(- 1)] from .arm import chromeos_config, select_best_chromeos_image devices = chromeos_config() arm_device = select_best_chromeos_image(de...
class TestCommandChooser(unittest.TestCase): def test_helper_methods_correct(self): def main_generator(dut): possible_cmds = '_rwap' expected_read = '01000' expected_write = '00100' expected_activate = '00010' helper_methods = {'write': expected_wr...
class Task(WithLogger): def __init__(self, **kwargs: Any) -> None: super().__init__(**kwargs) self._is_executed = False self._result = None self.config = kwargs def __call__(self, *args: Any, **kwargs: Any) -> Any: if self._is_executed: raise ValueError('Task ...
def test_prolong_low_order_to_restricted(tp_mesh, tp_family, variant): from firedrake.preconditioners.pmg import prolongation_matrix_matfree degree = 5 cell = tp_mesh.ufl_cell() element = FiniteElement(tp_family, cell=cell, degree=degree, variant=variant) Vi = FunctionSpace(tp_mesh, RestrictedElemen...
def test_migrate_gen_kw(setup_case, set_ert_config): setup_case('block_storage/version-1/poly_example', 'poly.ert') with open_storage('storage', 'w') as storage: assert (len(list(storage.experiments)) == 1) experiment = list(storage.experiments)[0] param_info = json.loads((experiment._pa...
class SizePrefsTestCase(unittest.TestCase): def assert_tuple(self, t1, t2): self.assertEqual(t1[0], t2[0]) self.assertEqual(t1[1], t2[1]) def test_sequential_non_resizable(self): prefs = SizePrefs(4, 'h') components = [StaticPlotComponent([100, 100]) for i in range(4)] fo...
class OptionPlotoptionsBellcurveSonificationDefaultinstrumentoptionsMappingNoteduration(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(se...
class SnmprecRecordMixIn(object): def evaluate_value(self, oid, tag, value, **context): if (':' in tag): (mod_name, tag) = (tag[(tag.index(':') + 1):], tag[:tag.index(':')]) else: mod_name = None if mod_name: if (('variationModules' in context) and (mod_na...
def unregisterStatsCallback(callback): with _stats_lock: try: _stats_callbacks.remove(callback) except ValueError: _logger.error('Callback {!r} is not registered'.format(callback)) return False else: _logger.debug('Unregistered stats-callback {...
class OptionPlotoptionsVariablepieSonificationContexttracksPointgrouping(Options): def algorithm(self): return self._config_get('minmax') def algorithm(self, text: str): self._config(text, js_type=False) def enabled(self): return self._config_get(True) def enabled(self, flag: boo...
def create_objects(): logger.log_info('Initial setup: Creating objects (Account #1 and Limbo room) ...') superuser = _get_superuser_account() from evennia.objects.models import ObjectDB account_typeclass = settings.BASE_ACCOUNT_TYPECLASS superuser.swap_typeclass(account_typeclass, clean_attributes=T...
class GreenConnection(greenio.GreenSocket): def __init__(self, ctx, sock=None): if (sock is not None): fd = orig_SSL.Connection(ctx, sock) else: fd = ctx super(ConnectionType, self).__init__(fd) def do_handshake(self): if self.act_non_blocking: ...
def get_puts_call_addr(): addr = stop_addr while True: addr += 1 payload = ('A' * buf_size) payload += p64((gadgets_addr + 9)) payload += p64(4194304) payload += p64(addr) payload += p64(stop_addr) try: io = get_io() io.sendline(pay...
(scope='module') def module1_unique(): class Module1(): a = 'a' def __init__(self, w3): self._b = 'b' self.w3 = w3 def b(self): return self._b def return_eth_chain_id(self): return self.w3.eth.chain_id return Module1
def get_balance_sheet_items(security_item, start_date=None, report_period=None, report_event_date=None, return_type='json'): security_item = to_security_item(security_item) path = get_balance_sheet_path(security_item) _download_finance_data_if_need(path, security_item['code']) encoding = 'GB2312' wi...
def dtest(): herder = VpsHerder(debug=True) clientname = 'test-2' (provider, kwargs) = herder.generate_do_conf() herder.log.info('Creating instance...') herder.log.info("\tClient name: '%s'", clientname) herder.log.info("\tusing provider: '%s'", provider) herder.log.info("\tkwargs: '%s'", kw...
def go(): flags.IS_FLASK = True settings.MAX_DB_SESSIONS = 10 import sys if (not ('debug' in sys.argv)): print('Starting background thread') if ('debug' in sys.argv): print('Running in debug mode.') app.run(host='0.0.0.0', port=5001, debug=True) else: print('Runni...
def test_distinguisher_mixin_handles_processed_traces_count(): d = DumbDistinguisher() assert (d.processed_traces == 0) data = np.random.randint(0, 255, (500, 16), dtype='uint8') traces = np.random.randint(0, 255, (500, 16), dtype='uint8') d.update(data=data, traces=traces) assert (d.processed_t...
class Invocation(BaseObject): def __init__(self, api=None, id=None, latest_completed_at=None, status=None, status_code=None, **kwargs): self.api = api self.id = id self.latest_completed_at = latest_completed_at self.status = status self.status_code = status_code for (...
class ObstacleManager(object): def __init__(self, pb_client, dt, v_up_env, visualization=False): self.pb_client = pb_client self.obstacles = [] self.dt = dt self.v_up_env = v_up_env if visualization: global gl_render, bullet_render, gl from basecode.re...
class NodeSupportTest(unittest.TestCase): def assertEqual(self, x: Any, y: Any) -> None: if (isinstance(x, Tensor) and isinstance(y, Tensor)): self.assertTrue(tensor_equality(x, y)) else: super().assertEqual(x, y) def test_node_supports(self) -> None: self.maxDiff...
class ModuleBuild(Build): __mapper_args__ = {'polymorphic_identity': ContentType.module} def nvr_name(self): return self._get_kojiinfo()['name'] def nvr_version(self): return self._get_kojiinfo()['version'] def nvr_release(self): return self._get_kojiinfo()['release']
class _A100(_A100_Base): partition_1g_5gb = _A100_Base.partitioned('1g.5gb') partition_2g_10gb = _A100_Base.partitioned('2g.10gb') partition_3g_20gb = _A100_Base.partitioned('3g.20gb') partition_4g_20gb = _A100_Base.partitioned('4g.20gb') partition_7g_40gb = _A100_Base.partitioned('7g.40gb')
def generate_readiness_modal_summary(days=7): date = (datetime.now().date() - timedelta(days=days)) df = pd.read_sql(sql=app.session.query(ouraReadinessSummary).filter((ouraReadinessSummary.report_date > date)).statement, con=engine, index_col='report_date') hrv_df = pd.read_sql(sql=app.session.query(ouraSl...
def hash_node(node): if isinstance(node, LeafNode): return hash(node.serialize()) elif isinstance(node, BranchNode): serialized = node.serialize() return (None if (serialized is None) else hash(serialized)) elif (node is None): return None else: raise Exception('B...
class Logger(): ALL = (- 5) NOTHING = (- 4) FATAL = (- 3) TRACEBACK = (- 2) ERROR = (- 1) WARNING = 0 stdout = _StdoutLog() stderr = _StderrLog() syslog = _SyslogLog() def __init__(self, info_max=5, debug_max=10): self._level = {} self._debug_level = {} se...
class Messenger(): _shared_data = _saved def __init__(self): self.__dict__ = self._shared_data if (not hasattr(self, '_signals')): self._signals = {} self._catch_all = ['AnyEvent', 'all'] def connect(self, obj, event, callback): typ = type(callback) ke...
class TestCompanion(I3LayoutScenario): def test_scenario(self): for params in self.layout_params(): self.senario(params) self._close_all() def layout(self, params: List) -> str: (odd_companion_ratio, even_companion_ratio, companion_position) = params return f'comp...
def test_run_component_modeler_mappings(monkeypatch, tmp_path): element_mappings = (((('left_bot', 0), ('right_bot', 0)), (('left_top', 0), ('right_top', 0)), (- 1j)), ((('left_bot', 0), ('right_top', 0)), (('left_top', 0), ('right_bot', 0)), (+ 1))) modeler = make_component_modeler(element_mappings=element_map...
class SessionError(Exception): def __init__(self, error=0, packet=0): Exception.__init__(self) self.error = error self.packet = packet def getErrorCode(self): return self.error def getErrorPacket(self): return self.packet def getErrorString(self): return s...
class TestTraitEventNotifierAddRemove(unittest.TestCase): def setUp(self): push_exception_handler(reraise_exceptions=True) self.addCleanup(pop_exception_handler) def tearDown(self): pass def test_add_to_observable(self): dummy = DummyObservable() dummy.notifiers = [st...
class RingControl(Module): def __init__(self, pad, mode, color, nleds, sys_clk_freq): ring = RingSerialCtrl(nleds, sys_clk_freq) self.submodules += ring ring_timer = WaitTimer(int((0.05 * sys_clk_freq))) self.submodules += ring_timer index = Signal(12, reset=1) if (mo...
class OptionSeriesVariablepie(Options): def accessibility(self) -> 'OptionSeriesVariablepieAccessibility': return self._config_sub_data('accessibility', OptionSeriesVariablepieAccessibility) def allowPointSelect(self): return self._config_get(False) def allowPointSelect(self, flag: bool): ...
def validate_ommers(ommers: Tuple[(Header, ...)], block_header: Header, chain: BlockChain) -> None: block_hash = rlp.rlp_hash(block_header) ensure((rlp.rlp_hash(ommers) == block_header.ommers_hash), InvalidBlock) if (len(ommers) == 0): return for ommer in ommers: ensure((1 <= ommer.numbe...
def extractCheldraWordpressCom(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_type) i...
class Python(Generator, Jinja2): def __init__(self, rmap=None, path='regs.py', **args): super().__init__(rmap, **args) self.path = path def generate(self): self.validate() j2_template = 'regmap_py.j2' j2_vars = {} j2_vars['corsair_ver'] = __version__ j2_va...