code
stringlengths
281
23.7M
def extractBlacktuliptranslationsWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('WPH', 'Warhead Pet Hamster', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiter...
def carryforward_convert(color: 'Color', space: str, hue_index: int, powerless: bool) -> None: carry = [] needs_conversion = (space != color.space()) if (needs_conversion and any((math.isnan(c) for c in color))): cs1 = color._space cs2 = color.CS_MAP[space] channels = {'R': False, 'G...
def draw(results: Dict[(int, Dict[(bool, int)])]): try: from matplotlib import pyplot as plt except ImportError: return plt.figure() plt.subplot(2, 1, 1) plt.title('Threading performance') plt.ylabel('Operations Count') plt.xlabel('CPU Workers count') plt.plot(results.key...
def add_header_to_file(filepath: str) -> None: with open(filepath, mode='r') as f: lines = list(f) i = 0 for (i, line) in enumerate(lines): if (line not in lines_to_keep): break new_lines = (lines[:i] + license_header_lines) if (lines and (lines[i] != '\n')): line...
def _handle_optional_typing(typed): optional = False if (hasattr(typed, '__args__') and (not isinstance(typed, _SpockVariadicGenericAlias))): type_args = typed.__args__ if ((len(type_args) == 2) and (typed == Union[(type_args[0], None)])): typed = type_args[0] optional = ...
def extractChrysanthemumconquerortranslationsHomeBlog(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 (ta...
class Compass(): compass = [NORTH, EAST, SOUTH, WEST] def __init__(self, direction=NORTH): self.direction = direction def left(self): self.direction = self.compass[(self.direction - 1)] def right(self): self.direction = self.compass[((self.direction + 1) % 4)]
class DataConfig(): def __init__(self): self.keys = {} self.docs = {} def __getitem__(self, key: str): from epyk.core.js.primitives import JsObjects self.keys[key] = '' return JsObjects.JsObjects.get(("window['page_config']['%s']" % key)) def get(self, key: str, dfl: ...
class Test(testbase.ClassSetup): def setUpClass(cls): super().setUpClass() cls.g_comp.load_formula_file('gf4d.frm') cls.g_comp.load_formula_file('gf4d.cfrm') cls.g_comp.load_formula_file('test.frm') def setUp(self): self.anim = animation.T(Test.g_comp, Test.userConfig) ...
def get_documents(mur_id): documents = [] with db.engine.connect() as conn: rs = conn.execute(MUR_DOCUMENTS, mur_id) for row in rs: documents.append({'document_id': int((row['document_id'] or 1)), 'length': int((row['length'] or 0)), 'text': row['pdf_text'], 'url': (row['url'] or '/f...
(HISTORICAL_PRIVACY_PREFERENCES_REPORT, status_code=HTTP_200_OK, dependencies=[Security(verify_oauth_client, scopes=[PRIVACY_PREFERENCE_HISTORY_READ])], response_model=Page[ConsentReportingSchema]) def get_historical_consent_report(*, params: Params=Depends(), db: Session=Depends(get_db), request_timestamp_gt: Optional...
.parametrize('warm_up_period, error', [((- 1), VALIDATION_ERROR), (0, None), (10, None), (256, None), (50000, None)]) def test_init_warm_up_period(warm_up_period, error, casper_args, deploy_casper_contract, assert_tx_failed): casper = deploy_casper_contract(casper_args, initialize_contract=False) if error: ...
def test_parent_id_included(caplog): test_id = '1.1.1' test_level = 1 custom_config = SimpleNamespace(includes=['1.1'], excludes=None, level=0, log_level='DEBUG') test = CISAudit(config=custom_config) result = test._is_test_included(test_id=test_id, test_level=test_level) assert (caplog.records[...
class UserPermission(UUIDModel, CreatedUpdatedAt, WorkspaceBase): __tablename__ = 'user_permissions' __table_args__ = (UniqueConstraint('user_id', 'permission_id', 'from_role_id'),) user_id: Mapped[UUID4] = mapped_column(GUID, ForeignKey(User.id, ondelete='CASCADE'), nullable=False) permission_id: Mappe...
class CatalogBasedTargeting(AbstractObject): def __init__(self, api=None): super(CatalogBasedTargeting, self).__init__() self._isCatalogBasedTargeting = True self._api = api class Field(AbstractObject.Field): geo_targeting_type = 'geo_targeting_type' _field_types = {'geo_targ...
def test_single_window_when_using_periods(df_time): expected_results = {'ambient_temp': [31.31, 31.51, 32.15, 32.39, 32.62, 32.5, 32.52, 32.68, 33.76], 'module_temp': [49.18, 49.84, 52.35, 50.63, 49.61, 47.01, 46.67, 47.52, 49.8], 'irradiation': [0.51, 0.79, 0.65, 0.76, 0.42, 0.49, 0.57, 0.56, 0.74], 'color': ['blu...
class OptionPlotoptionsPackedbubbleSonificationContexttracksMappingPitch(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): ...
def extractAm4LynneWordpressCom(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) ...
(scope='function') def integration_dynamodb_config(db) -> ConnectionConfig: connection_config = ConnectionConfig(key='dynamodb_example', connection_type=ConnectionType.dynamodb, access=AccessLevel.write, secrets=integration_secrets['dynamodb_example'], name='dynamodb_example') connection_config.save(db) (yi...
.parametrize('log_level', [None, 0, 5, 10, 20, 30, 40, 50]) .parametrize('uvicorn_logger_level', [0, 5, 10, 20, 30, 40, 50]) def test_config_log_effective_level(log_level: Optional[int], uvicorn_logger_level: Optional[int]) -> None: default_level = 30 log_config = {'version': 1, 'disable_existing_loggers': Fals...
class SplitTableBatchedEmbeddingBagsCodegenInputIterator(ConfigIterator): def __init__(self, configs: Dict[(str, Any)], key: str, device: str): super(SplitTableBatchedEmbeddingBagsCodegenInputIterator, self).__init__(configs, key, device) logger.debug(f'build_input_config: {configs}') build_...
def test_that_load_responses_throws_exception(tmp_path): with open_storage(tmp_path, mode='w') as storage: experiment = storage.create_experiment() ensemble = storage.create_ensemble(experiment, name='foo', ensemble_size=1) with pytest.raises(expected_exception=ValueError, match='I_DONT_EXIS...
class OptionSeriesAreaDragdropGuideboxDefault(Options): def className(self): return self._config_get('highcharts-drag-box-default') def className(self, text: str): self._config(text, js_type=False) def color(self): return self._config_get('rgba(0, 0, 0, 0.1)') def color(self, tex...
def mock_config_openai_plugin(): class MockConfig(): current_dir = os.getcwd() plugins_dir = f'{current_dir}/{PLUGINS_TEST_DIR_TEMP}/' plugins_openai = [PLUGIN_TEST_OPENAI] plugins_denylist = ['AutoGPTPVicuna'] plugins_allowlist = [PLUGIN_TEST_OPENAI] return MockConfig()
.gpu .skipif((not has_torch_cuda_gpu), reason='needs GPU & CUDA') def test_init(): nlp = spacy.blank('en') nlp.add_pipe('llm', config=_PIPE_CFG) doc = nlp('This is a test.') torch.cuda.empty_cache() assert (not doc.user_data['llm_io']['llm']['response'].startswith(doc.user_data['llm_io']['llm']['pro...
class BigqueryAccessControls(object): def __init__(self, project_id, dataset_id, full_name, special_group, user_email, domain, group_email, role, view, raw_json): self.project_id = project_id self.dataset_id = dataset_id self.full_name = full_name self.special_group = special_group ...
def test_hmac_sha_256(): configuration = HmacMaskingConfiguration(algorithm='SHA-256') masker = HmacMaskingStrategy(configuration) expected = 'df1e66dc2262ae3336ff795be0a1add7974eacea8a52970' secret_key = MaskingSecretCache[str](secret='test_key', masking_strategy=HmacMaskingStrategy.name, secret_type=S...
class OptionPlotoptionsBarStatesInactive(Options): def animation(self) -> 'OptionPlotoptionsBarStatesInactiveAnimation': return self._config_sub_data('animation', OptionPlotoptionsBarStatesInactiveAnimation) def enabled(self): return self._config_get(True) def enabled(self, flag: bool): ...
def _check_for_incoming_envelope(inbox: InBox, message_class: Type[Message]) -> None: if (not inbox.empty()): envelope = inbox.get_nowait() if (envelope is None): raise ValueError('Could not recover envelope from inbox.') click.echo(_construct_message('received', envelope, messag...
def test_that_report_step_mismatch_warns(tmpdir): with tmpdir.as_cwd(): config = dedent('\n JOBNAME my_name%d\n NUM_REALIZATIONS 10\n OBS_CONFIG observations\n GEN_DATA RES INPUT_FORMAT:ASCII REPORT_STEPS:1 RESULT_FILE:file%d\n ') with open('config.ert', 'w', encod...
class AdsPixelStatsResult(AbstractObject): def __init__(self, api=None): super(AdsPixelStatsResult, self).__init__() self._isAdsPixelStatsResult = True self._api = api class Field(AbstractObject.Field): aggregation = 'aggregation' data = 'data' start_time = 'start...
def get_savings_for_orgs(generic_code, date, org_type, org_ids, min_saving=1): try: substitution_set = get_substitution_sets()[generic_code] except KeyError: return [] (quantities, net_costs) = get_quantities_and_net_costs_at_date(get_db(), substitution_set, date) group_by_org = get_row_...
def test_check_availability_on_ftp(ftpserver): with data_over_ftp(ftpserver, 'tiny-data.txt') as url: pup = Pooch(path=DATA_DIR, base_url=url.replace('tiny-data.txt', ''), registry={'tiny-data.txt': 'baee0894dba14b12085eacb204284b97e362f4f3e5a5807693cc90ef415c1b2d', 'doesnot_exist.zip': 'jdjdjdjdflld'}) ...
def test_describe_notebooks_scripts_report(): runner = CliRunner() pipeline_file_path = (((Path(__file__).parent / 'resources') / 'pipelines') / 'pipeline_with_scripts.pipeline') result = runner.invoke(pipeline, ['describe', str(pipeline_file_path)]) assert (result.exit_code == 0) assert ('Notebook ...
.parametrize('response, case_sensitive, gold_ents', [("1. Jean | True | PER | is a person's name", False, [('jean', 'PER')]), ("1. Jean | True | PER | is a person's name", True, [('Jean', 'PER')]), ("1. jean | True | PER | is a person's name\n2. Jean | True | PER | is a person's name\n3. Jean Foundation | True | ORG | ...
def test_data_drift_test_feature_value_drift() -> None: test_current_dataset = pd.DataFrame({'feature_1': [0, 0, 0, 1], 'target': [0, 0, 0, 1], 'prediction': [0, 0, 0, 1]}) test_reference_dataset = pd.DataFrame({'feature_1': [0, 1, 2, 0], 'target': [0, 0, 0, 1], 'prediction': [0, 0, 0, 1]}) suite = TestSuit...
class RMTTestReqClass(object): def rmttest_positive_01(self): (config, req) = create_parameters() rt = ReqClass(config) (name, value) = rt.rewrite('Class-test', req) assert ('Class' == name) assert isinstance(value, ClassTypeDetailable) def rmttest_positive_02(self): ...
class SocketIO(): def __init__(self, htmlCode: str=None, page: primitives.PageModel=None): if (page is not None): page.jsImports.add('socket.io') self.page = page self._selector = (htmlCode or ('socket_%s' % id(self))) def message(self): return JsObjects.JsObject.JsOb...
class GrowingChainOfStates(ChainOfStates): def __init__(self, images, calc_getter, max_nodes=10, **kwargs): super().__init__(images, **kwargs) self.max_nodes = max_nodes self.calc_getter = calc_getter self.zero_step = np.zeros_like(self.images[0].coords) def get_new_image_from_co...
.compilertest def test_simple_targets(tmp_path): builder = Builder(logger, tmp_path, 'cache_test_1.yaml') builder.build() builder.build() builder.check_last('immediate rebuild') builder.invalidate('Mapping-v2-foo-4-default') builder.build() builder.check_last('after delete foo-4')
def main(): global_config = config['Global'] post_process_class = build_post_process(config['PostProcess'], global_config) if hasattr(post_process_class, 'character'): char_num = len(getattr(post_process_class, 'character')) if (config['Architecture']['algorithm'] in ['Distillation']): ...
.usefixtures('request_context') def test_start_thread_last_requested(endpoint, config): config.app.url_map.add(Rule('/', endpoint=endpoint.name)) init_cache() num_threads = threading.active_count() start_thread_last_requested(endpoint) wait_until_threads_finished(num_threads) assert memory_cache...
def processPrices(tdenv, priceFile, db, defaultZero): (DEBUG0, DEBUG1) = (tdenv.DEBUG0, tdenv.DEBUG1) DEBUG0('Processing prices file: {}', priceFile) cur = db.cursor() ignoreUnknown = tdenv.ignoreUnknown quiet = tdenv.quiet merging = tdenv.mergeImport systemByName = getSystemByNameIndex(cur)...
def delete_user_button(): with st.form('Delete all user data.'): st.write('Delete all user data') st.warning('This will permanently delete all of your data with no chance for recovery.') confirmation = st.text_input('Type "delete me"') submit_button = st.form_submit_butto...
_as_parloop_arg.register(kernel_args.OutputKernelArg) def _as_parloop_arg_output(_, self): rank = len(self._form.arguments()) tensor = self._indexed_tensor Vs = self._indexed_function_spaces if (rank == 0): return op2.GlobalParloopArg(tensor) elif ((rank == 1) or ((rank == 2) and self._diago...
class OptionPlotoptionsPictorialSonificationDefaultinstrumentoptionsMappingFrequency(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,...
def extractSecondtranslationWordpressCom(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, ...
def test_get_by_id(client): repository_mock = mock.Mock(spec=UserRepository) repository_mock.get_by_id.return_value = User(id=1, email='', hashed_password='pwd', is_active=True) with app.container.user_repository.override(repository_mock): response = client.get('/users/1') assert (response.statu...
def test_incorrect_type_resources(): with pytest.raises(AssertionError): Resources(cpu=1) with pytest.raises(AssertionError): Resources(mem=1) with pytest.raises(AssertionError): Resources(gpu=1) with pytest.raises(AssertionError): Resources(storage=1) with pytest.rai...
class OptionPlotoptionsPictorialSonificationContexttracksMapping(Options): def frequency(self) -> 'OptionPlotoptionsPictorialSonificationContexttracksMappingFrequency': return self._config_sub_data('frequency', OptionPlotoptionsPictorialSonificationContexttracksMappingFrequency) def gapBetweenNotes(self...
class RMTTestTemplateproject(BBHelper): in_test_dir = '../contrib/template_project' out_test_dir = 'tests/RMTTest-Blackbox/RMTTest-TemplateProject' def rmttest_pos_001(self): self.artifacts_dir = 'artifacts' cfg_file = 'tests/RMTTest-Blackbox/RMTTest-TemplateProject/input/Config.yaml' ...
def foundry_schema_to_dataset_format(foundry_schema: dict) -> str: if ('ParquetDataFrameReader' in foundry_schema['dataFrameReaderClass']): return 'parquet' if ('TextDataFrameReader' in foundry_schema['dataFrameReaderClass']): return 'csv' if ('AvroDataFrameReader' in foundry_schema['dataFra...
def test_details_view(): (app, db, admin) = setup() (Model1, Model2) = create_models(db) view_no_details = CustomModelView(Model1) admin.add_view(view_no_details) view_w_details = CustomModelView(Model2, can_view_details=True) admin.add_view(view_w_details) char_field_view = CustomModelView(...
def get_fraction_per_zone(self, dlogname, dvalues, zonelist=None, incl_limit=80, count_limit=3, zonelogname=None): logger.debug('The zonelist is %s', zonelist) logger.debug('The dlogname is %s', dlogname) logger.debug('The dvalues are %s', dvalues) if (zonelogname is not None): usezonelogname = ...
class OptionPlotoptionsVennSonificationDefaultinstrumentoptionsMappingTremoloSpeed(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, t...
class PackModeDecision(ErsiliaBase): def __init__(self, model_id, config_json): ErsiliaBase.__init__(self, config_json=config_json, credentials_json=None) self.model_id = model_id self.versioner = Versioner(config_json=config_json) def _correct_protobuf(self, version, dockerfile, protobu...
class MergeableCommand(SimpleCommand): name = 'Increment' amount = Int(1) def do(self): self.redo() def redo(self): self.data += self.amount def undo(self): self.data -= self.amount def merge(self, other): if (not isinstance(other, MergeableCommand)): ...
class StructuredTransforms1DInterfacesLeft(TestCase, Common): def setUp(self): super().setUp() self.seq = nutils.transformseq.StructuredTransforms(x1, (nutils.transformseq.IntAxis(1, 4, 9, 0, False),), 0) self.check = ((x1, i11, e1), (x1, i12, e1), (x1, i13, e1)) self.checkmissing = ...
class TestValidateBoolTests(): def test_bool(self): assert (not config._validate_bool(False)) assert config._validate_bool(True) def test_other(self): with pytest.raises(ValueError) as exc: config._validate_bool({'not a': 'bool'}) assert (str(exc.value) == '"{\'not a\...
def on_window_move(layouts: Layouts, state: State): def _on_window_move(i3l: Connection, e: WindowEvent): logger.debug(f'[ipc] window move event - container:{e.container.id}') context = state.sync_context(i3l) if (context.contains_container(e.container.id) or (e.container.type != 'con')): ...
class LabelDecrementSizeCommand(AbstractCommand): data = Instance(Label) name = Str('&Decrement size') _decremented_by = Int() def do(self): self.data.decrement_size(1) self._decremented_by = 1 def merge(self, other): if isinstance(other, type(self)): self._decrem...
def test_gauss_cube3(): print('3rd Order Polynomial') print('Cube') gaussCube.setOrder(1) int0_f3 = dot(f3(gaussCube.points), gaussCube.weights) print(int0_f3) gaussCube.setOrder(2) int1_f3 = dot(f3(gaussCube.points), gaussCube.weights) print(int1_f3) gaussCube.setOrder(3) int2_f...
_meta(characters.sp_flandre.DestructionImpulseHandler) class DestructionImpulseHandler(): def choose_card_text(self, act, cards): if cards: return (False, '!') return (True, '') def target(self, pl): if (not pl): return (False, '1,') return (True, '')
def render_copr_detail(copr): repo_dl_stat = CounterStatLogic.get_copr_repo_dl_stat(copr) form = forms.CoprLegalFlagForm() repos_info = ReposLogic.repos_for_copr(copr, repo_dl_stat) repos_info_list = sorted(repos_info.values(), key=(lambda rec: rec['name_release'])) builds = builds_logic.BuildsLogic...
class InfraredSensor(Sensor, ButtonBase): SYSTEM_CLASS_NAME = Sensor.SYSTEM_CLASS_NAME SYSTEM_DEVICE_NAME_CONVENTION = Sensor.SYSTEM_DEVICE_NAME_CONVENTION MODE_IR_PROX = 'IR-PROX' MODE_IR_SEEK = 'IR-SEEK' MODE_IR_REMOTE = 'IR-REMOTE' MODE_IR_REM_A = 'IR-REM-A' MODE_IR_CAL = 'IR-CAL' MOD...
class InputContactMessageContent(Dictionaryable): def __init__(self, phone_number, first_name, last_name=None, vcard=None): self.phone_number: str = phone_number self.first_name: str = first_name self.last_name: str = last_name self.vcard: str = vcard def to_dict(self): j...
class OptionPlotoptionsDependencywheelSonificationDefaultspeechoptionsMappingRate(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...
class HistoricalUsageService(ModelNormal): allowed_values = {} validations = {} _property def additional_properties_type(): lazy_import() return (HistoricalUsageData,) _nullable = False _property def openapi_types(): lazy_import() return {'name': (str,)} _...
class ESP32C5BETA3StubLoader(ESP32C5BETA3ROM): FLASH_WRITE_SIZE = 16384 STATUS_BYTES_LENGTH = 2 IS_STUB = True def __init__(self, rom_loader): self.secure_download_mode = rom_loader.secure_download_mode self._port = rom_loader._port self._trace_enabled = rom_loader._trace_enabled...
def get_default_storage_config_by_type(db: Session, storage_type: StorageType) -> Optional[StorageConfig]: if (not isinstance(storage_type, StorageType)): try: storage_type = StorageType[storage_type] except KeyError: raise ValueError('storage_type argument must be a valid St...
def create_app(): logger.debug('loading config') setup_configs(app) logger.debug('registering blueprints') register_blueprints(app) db_models = {'models': [models]} if (not get_settings().DISABLE_PLUGIN_LOADER): logger.debug('loading plugins') plugin_models = load_plugins(app) ...
def test_metrics_labels(elasticapm_client): metricset = MetricSet(MetricsRegistry(elasticapm_client)) metricset.counter('x', mylabel='a').inc() metricset.counter('y', mylabel='a').inc() metricset.counter('x', mylabel='b').inc().inc() metricset.counter('x', mylabel='b', myotherlabel='c').inc() me...
class MatrixFourierTransform(FourierTransform): def __init__(self, input_grid, output_grid, precompute_matrices=None, allocate_intermediate=None): if ((not input_grid.is_separated) or (not input_grid.is_('cartesian'))): raise ValueError('The input_grid must be separable in cartesian coordinates....
def rollout_from_init_states(init_states, env, policy, eval_mode=False, horizon=1000000.0, debug=False) -> list: assert isinstance(env, GymEnv) assert isinstance(init_states, list) num_traj = len(init_states) horizon = min(horizon, env.horizon) paths = [] for ep in toggle_tqdm(range(num_traj), d...
def create_user_link_pattern(provider, host, www=True): template = USER_LINK_TEMPLATES[provider] host_pat = re.escape(host.lower().rstrip('/')) if www: m = RE_WWW.match(host_pat) if m: host_pat = ((m.group(1) + '(?:w{3}\\.)?') + m.group(2)) return template[0].format(host_pat,...
class BaseReplayBuffer(): def add_rollout(self, rollout: Union[(SpacesTrajectoryRecord, List[StructuredSpacesRecord])]) -> None: def sample_batch(self, n_samples: int, learner_device: str) -> List[Union[(StructuredSpacesRecord, SpacesTrajectoryRecord)]]: def add_transition(self, transition: Union[(Structure...
def protfunc_callable_protkey(*args, **kwargs): if (not args): return '' prototype = kwargs.get('prototype', {}) fieldname = args[0] prot_value = None if (fieldname in prototype): prot_value = prototype[fieldname] else: for attrtuple in prototype.get('attrs', []): ...
def large_poisson(lam, thresh=1000000.0): large = (lam > thresh) small = (~ large) n = np.zeros(lam.shape) n[large] = np.round((lam[large] + (np.random.normal(size=np.sum(large)) * np.sqrt(lam[large])))) n[small] = np.random.poisson(lam[small], size=np.sum(small)) if hasattr(lam, 'grid'): ...
class RegexTests(unittest.TestCase): def testInit(self): self.assertRaises(RegexException, Regex, '') self.assertRaises(RegexException, Regex, ' ') self.assertRaises(RegexException, Regex, '\t') def testStr(self): self.assertEqual(str(Regex('a')).replace('"', "'"), "Regex('a')") ...
class LBRN2Surface(Surface): invert_y = False dbg = False fonts = {'serif': 'Times New Roman', 'sans-serif': 'Arial', 'monospaced': 'Courier New'} lbrn2_colors = [0, 1, 3, 6, 30, 7, 4, 8] def finish(self, inner_corners='loop'): if self.dbg: print('LBRN2 save') extents = s...
class G2Basic(BaseG2Ciphersuite): DST = b'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_' def AggregateVerify(cls, PKs: Sequence[BLSPubkey], messages: Sequence[bytes], signature: BLSSignature) -> bool: if (len(messages) != len(set(messages))): return False return cls._CoreAggregateVerif...
def pytest_sessionstart(session): mock_env = {'HOOK_URL': 'x', 'RULES_SEPARATOR': 'x', 'RULES': 'x', 'IGNORE_RULES': 'x', 'USE_DEFAULT_RULES': 'x', 'EVENTS_TO_TRACK': 'x', 'CONFIGURATION': '[{}]', 'LOG_LEVEL': 'DEBUG', 'RULE_EVALUATION_ERRORS_TO_SLACK': 'x'} os.environ |= mock_env boto3.setup_default_sessio...
def random_env_steps(env: ObservationNormalizationWrapper, steps: int) -> np.ndarray: observations = [] obs = env.reset() observations.append(obs['observation']) for _ in range(steps): action = env.sampling_policy.compute_action(obs, maze_state=None, env=env, actor_id=ActorID(0, 0), deterministi...
class Axis(types.Singleton): def __init__(self, i: Integral, j: Integral, mod: Integral): assert isinstance(i, Integral), f'i={i!r}' assert isinstance(j, Integral), f'j={j!r}' assert isinstance(mod, Integral), f'mod={mod!r}' assert (i <= j) self.i = i self.j = j ...
class BenchmarkIO(): LOGDIR = 'iologs' def __init__(self, filename, seek, chunksize, SIZE): self.tic = Timer() self.filename = filename self.seek = seek self.chunksize = chunksize self.SIZE = SIZE def chunksize_str_hook(self): return '' def go(self): ...
class TestToolkit(BaseTestMixin, unittest.TestCase): def setUp(self): BaseTestMixin.setUp(self) def tearDown(self): BaseTestMixin.tearDown(self) def test_default_toolkit(self): with clear_toolkit(): tk = traitsui.toolkit.toolkit() self.assertNotEqual(ETSConfig...
def has_permission(permission): def wrapper(fn): (fn) async def wrapped(*args, **kwargs): request = args[(- 1)] if (not isinstance(request, web.BaseRequest)): msg = 'Incorrect decorator usage. Expecting `def handler(request)` or `def handler(self, request)`.' ...
class TestGetManualWebhookAccessInputs(): (scope='function') def url(self, db, privacy_request_requires_input, access_manual_webhook, integration_manual_webhook_config): return (V1_URL_PREFIX + PRIVACY_REQUEST_MANUAL_WEBHOOK_ACCESS_INPUT.format(privacy_request_id=privacy_request_requires_input.id, conne...
def print_md5sums(library): try: print(('%s %s' % (md5sum(library.csfasta), strip_prefix(library.csfasta, os.getcwd())))) except Exception as ex: logging.error(('FAILED for F3 csfasta: %s' % ex)) try: print(('%s %s' % (md5sum(library.qual), strip_prefix(library.qual, os.getcwd())))...
class NoopEth1PeerTracker(BaseEth1PeerTracker): def track_peer_connection(self, remote: NodeAPI, is_outbound: bool, last_connected_at: Optional[datetime.datetime], genesis_hash: Hash32, protocol: str, protocol_version: int, network_id: int) -> None: pass async def get_peer_candidates(self, max_candidate...
def load_fonts(): fonts = [] fontdir = os.path.join(os.path.dirname(__file__), 'fonts') for font_name in tqdm.tqdm(os.listdir(fontdir)): if font_name.endswith('.woff'): with open(os.path.join(fontdir, font_name), 'rb') as fp: font = TTFont(fp) fonts.append...
class TraitSheetApp(wx.App): def __init__(self): wx.InitAllImageHandlers() wx.App.__init__(self, 1, 'debug.log') self.MainLoop() def OnInit(self): Person().edit_traits() ExtraPerson().edit_traits() LocatedPerson().edit_traits() EmployedPerson().edit_traits...
class TestDevice(object): def mouse(self): settings = mouse_settings.FakeMouseSettings(4152, 47789, rival110.profile) return mouse.Mouse(usbhid.FakeDevice(), rival110.profile, settings) .parametrize('value,expected_hid_report', [(200, b'\x02\x00\x03\x01\x04'), (210, b'\x02\x00\x03\x01\x04'), (29...
() ('--username', help='This can be set via env var GREETER_GREET_USERNAME', show_envvar=True) ('--nickname', envvar='NICKNAME', show_envvar=True, show_default=True, help='This can be set via env var NICKNAME') ('--email', envvar=['EMAIL', 'EMAIL_ADDRESS'], show_envvar=True, default='', show_default=True, help='This ca...
def read_traceheaders_forall(f, mmap): if mmap: f.mmap() (start, stop, step) = (20, (- 1), (- 5)) indices = range(start, stop, step) attrs = numpy.empty(len(indices), dtype=numpy.intc) field = segyio.TraceField.INLINE_3D with pytest.raises(ValueError): f.field_forall(attrs, start...
class BaseServerTestCase(object): server_class = None server_settings = None def setup_pysoa(self): if (self.server_class is None): raise TypeError('You must specify `server_class` in `ServerTestCase` subclasses') if (not issubclass(self.server_class, Server)): raise ...
.django_db def test_double_eclipsing_filters2(client, monkeypatch, elasticsearch_award_index, subaward_with_tas): _setup_es(client, monkeypatch, elasticsearch_award_index) resp = query_by_tas_subaward(client, {'require': [_fa_path(BASIC_TAS)], 'exclude': [_agency_path(BASIC_TAS), _tas_path(BASIC_TAS)]}) ass...
class SystemStatsView(APIView): _cache_key = 'system_stats' dc_bound = False def get_stats(cls, cache_timeout=30): res = cache.get(cls._cache_key) if res: return res created = now() dcs = {force_text(label).lower(): Dc.objects.filter(access=access).count() for (ac...
def _backup_list_context(request, node, context, vm_hostname=None): context['filters'] = filter_form = BackupFilterForm(request, node, request.GET) bkps = node.backup_set.select_related('vm', 'dc') qs = QueryDict('', mutable=True) if (filter_form.is_valid() and filter_form.has_changed()): q = fi...
class OptionPlotoptionsSunburstSonificationContexttracksMappingTremolo(Options): def depth(self) -> 'OptionPlotoptionsSunburstSonificationContexttracksMappingTremoloDepth': return self._config_sub_data('depth', OptionPlotoptionsSunburstSonificationContexttracksMappingTremoloDepth) def speed(self) -> 'Op...