code
stringlengths
281
23.7M
def fft(field, domain, poly): if (len(domain) <= 8): return _simple_ft(field, domain, poly) offset = domain[1] (evens, odds) = cast(field, poly, offset) casted_domain = [field.mul(x, (offset ^ x)) for x in domain[::2]] even_points = fft(field, casted_domain, evens) odd_points = fft(field...
def infer_device_type(df: pd.DataFrame) -> DeviceType: if (('stream' in df.columns) and (('pid' not in df.columns) or ('tid' not in df.columns))): if (df.stream.unique() > 0).all(): return DeviceType.GPU elif (df.stream.unique() == (- 1)).all(): return DeviceType.CPU elif...
class SliceTemplate(models.Model): templateId = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) description = models.TextField(null=True, blank=True) nfvoType = models.ManyToManyField(ServiceMappingPluginModel) genericTemplates = models.ManyToManyField(GenericTemplate, related_nam...
class TestDevice(object): def mouse(self): settings = mouse_settings.FakeMouseSettings(4152, 47789, aerox9_wireless_wireless.profile) return mouse.Mouse(usbhid.FakeDevice(), aerox9_wireless_wireless.profile, settings) .parametrize('value,expected_hid_report', [(100, b'\x02\x00m\x01\x00\x00'), (2...
def main(numpy: bool=False, pytorch: bool=False, generic: bool=False, gpu_id: int=(- 1)): global CONFIG fix_random_seed(0) if (gpu_id >= 0): require_gpu(gpu_id) print('Set GPU', gpu_id) backends = {'pytorch': pytorch, 'numpy': numpy, 'generic': generic} for (name, use_backend) in bac...
def extractCakesnorterBlogspotCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('back to before i married the tyrant', 'Back to Before I Married the Tyrant [Rebirth]', 'transl...
def read_relation_as_df(adapter: RedshiftAdapter, relation: BaseRelation) -> pd.DataFrame: sql = f'SELECT * FROM {relation}' assert (adapter.type() == 'redshift') with new_connection(adapter, 'fal-redshift:read_relation_as_df') as conn: df = wr.redshift.read_sql_query(sql, con=conn.handle) r...
class FBPrintInternals(fb.FBCommand): def name(self): return 'pinternals' def description(self): return 'Show the internals of an object by dereferencing it as a pointer.' def args(self): return [fb.FBCommandArgument(arg='object', type='id', help='Object expression to be evaluated.')...
def test_split_full_desktop_to_screens(monkeypatch): class MockedPrimaryScreen(): def virtualGeometry(self) -> QtCore.QRect: return QtCore.QRect(0, 0, 300, 120) class MockedScreen(): def __init__(self, left, top, width, height): self._geometry = QtCore.QRect(left, top, wi...
class Queen(Piece): def __init__(self, x, y, c): super().__init__(x, y, c) self.set_letter('') def drag(self, new_p, pieces): if self.grabbed: (path, dist) = self.select_path((self.start_x, self.start_y), [[1, 1], [(- 1), 1], [1, 0], [0, 1]], new_p) path_len = mat...
def _delete_symlinks(bench_path): bench_dir = os.path.abspath(bench_path) etc_systemd_system = os.path.join('/', 'etc', 'systemd', 'system') unit_files = get_unit_files(bench_dir) for unit_file in unit_files: exec_cmd(f"sudo rm {etc_systemd_system}/{''.join(unit_file)}") exec_cmd('sudo syste...
.xfail(raises=ImageComparisonFailure, reason='Matplotlib plots for reasons a different image size.') .skipif((LOW_MEMORY > memory), reason='Travis has too less memory to run it.') def test_hicPlotMatrix_h5_region1(): outfile = NamedTemporaryFile(suffix='.png', prefix='hicexplorer_test_cool', delete=False) args ...
def test_module_attribute_wiring_with_invalid_marker(container: Container): from samples.wiring import module_invalid_attr_injection with raises(Exception, match='Unknown type of marker {0}'.format(module_invalid_attr_injection.service)): container.wire(modules=[module_invalid_attr_injection])
class Actuarial(): def __init__(self, lx=[], qx=[], nt=None, i=None, perc=100): self.lx = lx self.qx = qx self.dx = [] self.ex = [] self.w = 0 self.i = i self.q = 0 self.perc = perc self.nt = nt self.Dx = [] self.Nx = [] ...
class DeviceCodeAuthenticator(Authenticator): def __init__(self, endpoint: str, cfg_store: ClientConfigStore, header_key: typing.Optional[str]=None, audience: typing.Optional[str]=None, scopes: typing.Optional[typing.List[str]]=None, typing.Optional[str]=None, verify: typing.Optional[typing.Union[(bool, str)]]=Non...
class AlertsFetcher(FetcherClient): def __init__(self, dbt_runner: BaseDbtRunner, config: Config, elementary_database_and_schema: str): super().__init__(dbt_runner) self.config = config self.elementary_database_and_schema = elementary_database_and_schema def skip_alerts(self, alerts_to_s...
class OptionSeriesOrganizationSonificationTracksMappingLowpassFrequency(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 CssUIMenuActive(CssStyle.Style): classname = 'ui-state-active' def customize(self): self.css({'border': BORDER_1PX_EXPR.format(self.page.theme.notch()), 'background-color': self.page.theme.notch()}, important=True) self.hover.css({'border': BORDER_1PX_EXPR.format(self.page.theme.notch()), ...
class FunctionImageData(ImageData): func = Callable data_range = Instance(DataRange2D) def __init__(self, **kw): super().__init__(**kw) self.recalculate() ('data_range.updated') def recalculate(self, event=None): if ((self.func is not None) and (self.data_range is not None)):...
def extractPickupnovelsCom(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) in ta...
class SyncMimeLiteServer(SyncServer): def __init__(self, *, global_model: IFLModel, channel: Optional[IFLChannel]=None, **kwargs) -> None: init_self_cfg(self, component_class=__class__, config_class=SyncMimeLiteServerConfig, **kwargs) self._global_model = global_model self._aggregator = Aggr...
def close_all(map=None, ignore_all=False): if (map is None): map = socket_map for x in list(map.values()): try: x.close() except OSError as x: if (x.errno == EBADF): pass elif (not ignore_all): raise except _rera...
class EmulateEfuseController(EmulateEfuseControllerBase): CHIP_NAME = 'ESP32-P4' mem = None debug = False def __init__(self, efuse_file=None, debug=False): self.Blocks = EfuseDefineBlocks self.Fields = EfuseDefineFields() self.REGS = EfuseDefineRegisters super(EmulateEfus...
_config(context=HTTPForbidden, accept='text/html') _config(context=HTTPUnauthorized, accept='text/html') _config(context=Exception, accept='text/html') def exception_html_view(exc, request): errors = getattr(request, 'errors', []) status = getattr(exc, 'status_code', 500) if (status not in (404, 403, 401)):...
class TestRiskScoreMismatch(BaseRuleTest): def test_rule_risk_score_severity_mismatch(self): invalid_list = [] risk_severity = {'critical': (74, 100), 'high': (48, 73), 'medium': (22, 47), 'low': (0, 21)} for rule in self.all_rules: severity = rule.contents.data.severity ...
class FileUploadInput(object): empty_template = '<input %(file)s>' input_type = 'file' data_template = '<div> <input %(text)s> <input type="checkbox" name="%(marker)s">Delete</input></div><input %(file)s>' def __call__(self, field, **kwargs): kwargs.setdefault('id', field.id) kwargs.setd...
def test_arrow(): encoder = basic_dfs.ArrowToParquetEncodingHandler() decoder = basic_dfs.ParquetToArrowDecodingHandler() assert (encoder.protocol is None) assert (decoder.protocol is None) assert (encoder.python_type is decoder.python_type) d = StructuredDatasetTransformerEngine.DECODERS[encode...
class Common(): def test_todims(self): self.assertEqual(self.seq.todims, self.checktodims) for trans in self.seq: self.assertEqual(trans[0].todims, self.checktodims) def test_fromdims(self): self.assertEqual(self.seq.fromdims, self.checkfromdims) for trans in self.seq...
class OptionPlotoptionsTreemapSonificationDefaultinstrumentoptionsMappingTime(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 downgrade(): op.create_table('format', sa.Column('id', sa.INTEGER(), nullable=False), sa.Column('name', sa.VARCHAR(), autoincrement=False, nullable=True), sa.Column('label_en', sa.VARCHAR(), autoincrement=False, nullable=False), sa.Column('event_id', sa.INTEGER(), autoincrement=False, nullable=False), sa.Primar...
class OptionSonificationGlobaltracksMappingGapbetweennotes(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): self....
def create_server_datasets(test_config: FidesConfig, datasets: List[Dataset]) -> None: for dataset in datasets: api.delete(url=test_config.cli.server_url, resource_type='dataset', resource_id=dataset.fides_key, headers=test_config.user.auth_header) api.create(url=test_config.cli.server_url, resource...
class TestBootloaderHeaderRewriteCases(EsptoolTestCase): .skipif((arg_chip not in ['esp8266', 'esp32', 'esp32c3']), reason="Don't run on every chip, so other bootloader images are not needed") .quick_test def test_flash_header_rewrite(self): bl_offset = (4096 if (arg_chip in ('esp32', 'esp32s2')) el...
('cuda.bmm_rrr_permute.gen_function') def gen_function(func_attrs, exec_cond_template, dim_info_dict): default_mm_info = bmm_common.get_default_problem_info(PROBLEM_ARGS, alpha_value=func_attrs.get('alpha', 1)) (problem_args, _, input_addr_calculator, output_addr_calculator) = bmm_common.make_function_strided_a...
.parametrize('test_dataset, conditions, result', ((pd.DataFrame({'target': [0, 0, 0, 1]}), {'eq': 0}, True), (pd.DataFrame({'target': [0, 0, None, 1], 'numeric': [None, None, None, 1]}), {'lt': 3}, False))) def test_data_integrity_test_number_of_missing_values_no_errors(test_dataset: pd.DataFrame, conditions: dict, res...
class ResolveAnchorIds(Transform): default_priority = 879 def apply(self, **kwargs: t.Any) -> None: slugs: dict[(str, tuple[(int, str, str)])] = getattr(self.document, 'myst_slugs', {}) explicit: dict[(str, tuple[(str, (None | str))])] = {} for (name, is_explicit) in self.document.namety...
def test_process(): from threading import Thread class MockMonitor(Monitor): def __init__(self): self.sdnc = get_sdn_connect(logger) self.logger = self.sdnc.logger self.config = self.sdnc.config self.sdnc.config['TYPE'] = 'None' self.sdnc.get_s...
_log_on_failure_all class BaseTestLibp2pClientSamePeer(): _log_on_failure def setup_class(cls): cls.cwd = os.getcwd() cls.t = tempfile.mkdtemp() os.chdir(cls.t) MockDefaultMessageProtocol = Mock() MockDefaultMessageProtocol.protocol_id = DefaultMessage.protocol_id ...
.skipif((pytz is None), reason='As Django 4.0 has deprecated pytz, this test should eventually be able to get removed.') class TestPytzNaiveDayLightSavingTimeTimeZoneDateTimeField(FieldValues): valid_inputs = {} invalid_inputs = {'2017-03-12T02:30:00': ['Invalid datetime for the timezone "America/New_York".'], ...
class Weight(object): def __init__(self, weight_function, support=None, pdf=False, mean=None, variance=None): self.weight_function = weight_function self.flag = 'function' tmp = (lambda : 0) if (not isinstance(self.weight_function, type(tmp))): self.weight_function = stat...
class OptionPlotoptionsHeatmapMarkerStates(Options): def hover(self) -> 'OptionPlotoptionsHeatmapMarkerStatesHover': return self._config_sub_data('hover', OptionPlotoptionsHeatmapMarkerStatesHover) def normal(self) -> 'OptionPlotoptionsHeatmapMarkerStatesNormal': return self._config_sub_data('no...
('Build libcares - {arch}') def build_libcares(version: str, arch: str='linux-x86_64'): libcares = ProjectPaths('c-ares', arch) pkgconfig.add(libcares) if libcares.is_installed(): return (libcares.repo.exists() or git.clone(' libcares.repo)) libcares.clean() with chdir(libcares.repo): ...
class FindItemLocallyTestCase(TestCase): ('aea.cli.utils.package_utils.Path.exists', return_value=True) ('aea.cli.utils.package_utils.ConfigLoader.from_configuration_type', _raise_validation_error) def test_find_item_locally_bad_config(self, *mocks): public_id = PublicIdMock.from_str('fetchai/echo:0...
class ResetPointInfo(betterproto.Message): binary_checksum: str = betterproto.string_field(1) run_id: str = betterproto.string_field(2) first_workflow_task_completed_id: int = betterproto.int64_field(3) create_time: datetime = betterproto.message_field(4) expire_time: datetime = betterproto.message_...
class MahjongDrugHandler(THBEventHandler): interested = ['action_after'] def handle(self, evt_type, act): if ((evt_type == 'action_after') and isinstance(act, Heal)): tgt = act.target if (not tgt.has_skill(MahjongDrug)): return act card = getattr(act, ...
class NetasciiReader(): def __init__(self, reader): self._reader = reader self._buffer = bytearray() self._slurp = None self._size = None def read(self, size): if (self._slurp is not None): return self._slurp.read(size) (data, buffer_size) = (bytearray...
def test_text_store__raise_unsupported_version(tmp_path) -> None: wallet_path = os.path.join(tmp_path, 'database') store = TextStore(wallet_path) try: with pytest.raises(Exception) as e: store._raise_unsupported_version(5) assert ('To open this wallet' in e.value.args[0]) ...
() def setup_to_pass(): shellexec('echo -e "*\thard\tcore\t0" > /etc/security/limits.d/pytest.conf') shellexec('echo 0 > /proc/sys/fs/suid_dumpable') shellexec('echo -e "fs.suid_dumpable = 0" > /etc/sysctl.d/pytest.conf') (yield None) os.remove('/etc/security/limits.d/pytest.conf') os.remove('/e...
.skipcomplex def test_step_function_loop(mesh, iterations=100): v = space(mesh) m = VectorFunctionSpace(mesh, 'CG', 1) if (m.shape == (1,)): u0 = as_vector([1]) else: u0 = as_vector([1, 0]) u = Function(m).interpolate(u0) dt = (1.0 / iterations) phi = TestFunction(v) D = ...
('/charge_control') def get_charge_control(): logger.info(request) vin = request.args['vin'] charge_control = APP.chc.get(vin) if (charge_control is None): return jsonify('error: VIN not in list') if (('hour' in request.args) and ('minute' in request.args)): charge_control.set_stop_h...
class TestFINDPEAKS(unittest.TestCase): def test_fit(self): import numpy as np import matplotlib.pyplot as plt from findpeaks import findpeaks fp = findpeaks(method='topology', whitelist=['peak']) X = fp.import_example('2dpeaks') results = fp.fit(X) assert (fp...
class BasePayload(BaseHandler): def __init__(self, s3_config: Optional[_T]=None): super(BasePayload, self).__init__(s3_config=s3_config) def _update_payload(base_payload, input_classes, ignore_classes, payload): def payload(self, input_classes, ignore_classes, path, cmd_args, deps): payload ...
class AddrFilenamePairAction(argparse.Action): def __init__(self, option_strings, dest, nargs='+', **kwargs): super(AddrFilenamePairAction, self).__init__(option_strings, dest, nargs, **kwargs) def __call__(self, parser, namespace, values, option_string=None): pairs = [] for i in range(0...
def test_seqcap_align_mafft_untrim(o_dir, e_dir, request): program = 'bin/align/phyluce_align_seqcap_align' output = os.path.join(o_dir, 'mafft') cmd = [os.path.join(request.config.rootdir, program), '--input', os.path.join(e_dir, 'taxon-set.incomplete.fasta'), '--output', output, '--taxa', '4', '--aligner'...
def test_that_sort_orders_by_line_number_after_filename(): assert (sorted([ErrorInfo('', filename='a', line=1), ErrorInfo('', filename='b', line=1), ErrorInfo('', filename='a', line=2), ErrorInfo('', filename='b', line=2)]) == [ErrorInfo('', filename='a', line=1), ErrorInfo('', filename='a', line=2), ErrorInfo('', ...
def get_file_locations(): data_path = (os.getcwd() + '/graph_data/') envs = [env for env in os.listdir(data_path) if os.path.isdir(os.path.join(data_path, env))] paths = {} for env in envs: env_data = {} for (directory, _, filenames) in os.walk((data_path + env)): if ('seeds....
class DictionaryItemResponse(ModelComposed): allowed_values = {} validations = {} _property def additional_properties_type(): lazy_import() return (bool, date, datetime, dict, float, int, list, str, none_type) _nullable = False _property def openapi_types(): lazy_impo...
class Keyboard_locks(IntervalModule): interval = 1 settings = (('format', 'Format string'), ('caps_on', 'String to show in {caps} when CAPS LOCK is on'), ('caps_off', 'String to show in {caps} when CAPS LOCK is off'), ('num_on', 'String to show in {num} when NUM LOCK is on'), ('num_off', 'String to show in {num...
def _check_type(arg_name: str, arg_values: Any, expected_type: Union[(Type[Any], Tuple[(Type[Any], ...)])], element_type: Optional[Union[(Type[Any], Tuple[(Type[Any], ...)])]]=None) -> None: if isinstance(expected_type, tuple): class_names = [cls.__name__ for cls in expected_type] expected_type_stri...
class OptionPlotoptionsColumnpyramidSonificationContexttracksActivewhen(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, nu...
def test_custom_token(sample_tenant, api_key): client = tenant_mgt.auth_for_tenant(sample_tenant.tenant_id) custom_token = client.create_custom_token('user1') id_token = _sign_in(custom_token, sample_tenant.tenant_id, api_key) claims = client.verify_id_token(id_token) assert (claims['uid'] == 'user1...
def _get_name_and_record_counts_from_union(schema: List[Schema]) -> Tuple[(int, int)]: record_type_count = 0 named_type_count = 0 for s in schema: extracted_type = extract_record_type(s) if (extracted_type == 'record'): record_type_count += 1 named_type_count += 1 ...
def invalidate_aws_cloudfront_data(opts, owner, project, chroot): distro_id = opts.aws_cloudfront_distribution if (not distro_id): return base = urlparse(opts.results_baseurl).path path_pattern = ('/'.join([base, owner, project, chroot]) + '/*') log.info('Invalidating CDN cache %s', path_pat...
def _setup_simple_unet_3d() -> Tuple[(SimpleUnet3D, torch.Tensor, torch.Tensor)]: simple_unet_3d = SimpleUnet3D().to(device) test_batch_size = 1 resol = (32, 32, 32) dummy_x = torch.randn(test_batch_size, simple_unet_3d.in_channels, *resol, dtype=torch.float32, device=device) dummy_timesteps = torch...
() ('--strategy_interval', default=20, help='Update the current strategy whenever the iteration % strategy_interval == 0.') ('--n_iterations', default=1500, help='The total number of iterations we should train the model for.') ('--lcfr_threshold', default=400, help="A threshold for linear CFR which means don't apply di...
('/experiments/{experiment_id}/observations', response_model=List[js.ObservationOut]) def get_observations(*, res: LibresFacade=DEFAULT_LIBRESFACADE, experiment_id: UUID) -> List[js.ObservationOut]: return [js.ObservationOut(id=UUID(int=0), userData=[], errors=obs['errors'], values=obs['values'], x_axis=obs['x_axis...
_command def add_data(dm: DataManager, key: str, video: str=None, masks: str=None, mask_name: str=None, v2i_step: int=1, v2i_limit: int=200, v2i_skip: str=None, run_extra: bool=True): (key, ds_cat, ds_name) = validate_key(key) if (key not in dm.datasets): dm.datasets[key] = Dataset(ds_cat, ds_name) ...
def convert(config_path, input_path, output_path): config = Config.fromfile(config_path) model = DiffSingerLightning(config) logger.info('Loading Diff-SVC checkpoint...') diff_svc_state_dict = torch.load(input_path, map_location='cpu')['state_dict'] residual_channels = diff_svc_state_dict['model.den...
class TestMarkdown(): def test_md(self, tmpdir): md_path = str(tmpdir.join('regs.md')) print('md_path:', md_path) rmap = utils.create_template() generators.Markdown(rmap, md_path).generate() with open(md_path, 'r') as f: raw_str = ''.join(f.readlines()) as...
_2_unicode_compatible class MediaType(object): def __init__(self, media_type_str): if (media_type_str is None): media_type_str = '' self.orig = media_type_str (self.full_type, self.params) = parse_header(media_type_str.encode(HTTP_HEADER_ENCODING)) (self.main_type, sep, s...
def infer_fids_by_tr_outputs(output_filename=None): if (output_filename is None): output_filename = 'fid.xlsx' infos = KiwoomOpenApiPlusTrInfo.infos_from_data_dir() fields = [] for info in infos: for field in info.single_outputs: fields.append(field) for field in info...
def run_tests(package, mask, verbosity, search_leaks): (skipped, testcases) = get_tests(package, mask, verbosity) runner = TestRunner(verbosity=verbosity) suites = [unittest.makeSuite(o) for o in testcases] suite = unittest.TestSuite(suites) result = runner.run(suite, skipped) if search_leaks: ...
def _get_results_for_tar_file(file_info: tarfile.TarInfo) -> FileMetadata: file_path = file_info.name if (file_path[:2] == './'): file_path = file_path[2:] file_mode = _get_tar_file_mode_str(file_info) return FileMetadata(mode=file_mode, name=Path(file_path).name, path=file_path, user=file_info....
class OptionPlotoptionsVennSonificationContexttracksMappingTime(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 Block(): def __init__(self, parent, txstate): self.parent = parent self.score = (1 if (parent is None) else (parent.score + 1)) if ((parent is None) or (parent.txstate is None)): self.txstate = txstate else: self.txstate = parent.txstate
class FaucetTaggedMirrorTest(FaucetTaggedTest): CONFIG_GLOBAL = '\nvlans:\n 100:\n description: "tagged"\n' CONFIG = '\n interfaces:\n %(port_1)d:\n tagged_vlans: [100]\n %(port_2)d:\n tagged_vlans: [100]\n %(port_3)d:\n ...
class OptionSeriesStreamgraphSonificationDefaultinstrumentoptionsMappingFrequency(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 ScheduleAByStateRecipientTotals(BaseModel): __tablename__ = 'ofec_sched_a_aggregate_state_recipient_totals_mv' total = db.Column(db.Numeric(30, 2), index=True, doc='The calculated total.') count = db.Column(db.Integer, index=True, doc='Number of records making up the total.') cycle = db.Column(db....
class Piece(): def __init__(self, x_pos, y_pos, color): diameter = 0.7 self.x = x_pos self.y = y_pos self.radius = (diameter / 2) self.grabbed = False self.targeted = False self.color = color self.start_x = self.x self.start_y = self.y ...
class OptionSeriesBellcurveSonificationTracksMappingLowpassResonance(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 BaseEventStorage(ABC): def add_event(self, event: Event, uuid: str): pass def list_events(self, key: str=None, namespace: str=None, sender: str=None, begin_offset: int=None, end_offset: int=None): pass def count_events(self, key: str=None, namespace: str=None, sender: str=None, begin_o...
class TestFetchProduction(unittest.TestCase): def setUp(self): self.adapter = requests_mock.Adapter() self.session = requests.Session() self.session.mount(' self.adapter) _time('2021-12-30 09:58:40', tz_offset=(- 5)) def test_nominal_response_uses_timestamp_from_page(self): s...
def test_job_override_dirname(tmpdir: Path) -> None: cmd = ['examples/configure_hydra/job_override_dirname/my_app.py', ('hydra.sweep.dir=' + str(tmpdir)), 'hydra.job.chdir=True', 'learning_rate=0.1,0.01', 'batch_size=32', 'seed=999', '-m'] run_python_script(cmd) assert Path((tmpdir / 'batch_size=32,learning...
class Uncle(TypedDict): author: ChecksumAddress difficulty: HexStr extraData: HexStr gasLimit: HexStr gasUsed: HexStr hash: HexBytes logsBloom: HexStr miner: HexBytes mixHash: HexBytes nonce: HexStr number: HexStr parentHash: HexBytes receiptsRoot: HexBytes sealFi...
def get_macrocycle_atom_types(pdbqt_string): macrocycle_carbon = ['CG0', 'CG1', 'CG2', 'CG3', 'CG4', 'CG5', 'CG6', 'CG7', 'CG8', 'CG9'] macrocycle_pseudo = ['G0', 'G1', 'G2', 'G3', 'G4', 'G5', 'G6', 'G7', 'G8', 'G9'] cg_atoms = [] g_atoms = [] lines = pdbqt_string.split('\n') for line in lines: ...
class TestRequestOptions(): def test_option_defaults(self): options = RequestOptions() assert options.keep_blank_qs_values assert (not options.auto_parse_form_urlencoded) assert (not options.auto_parse_qs_csv) assert (not options.strip_url_path_trailing_slash) .parametriz...
class Backtest(): def __init__(self, task, session): self.session = session self.task = task self.gApis = {} self.tpls = task['Code'] del task['Code'] self.ctx = VCtx(task=self.task, gApis=self.gApis, progressCallback=self.progressCallback) def progressCallback(se...
class TaskDataOutputMetaData(TaskOutputMetaData): def __init__(self, sample_df, o_sequence, o_label, dtypes, number_of_records, df_description, df_info, explanation=''): super(TaskDataOutputMetaData, self).__init__(o_sequence, o_label, elmdpenum.TaskOutputMetaDataTypes.DATA_OUTPUT.value) self.sample...
def validate_pce(region: str, key_id: str, key_data: str, pce_id: str, role: MPCRoles, skip_steps: List[ValidationStepNames], run_steps: List[ValidationStepNames]) -> ValidatorResult: duplicate_resource_checker = DuplicatePCEResourcesChecker(region, key_id, key_data, None) duplicate_resources = duplicate_resour...
class OptionAnnotationsShapes(Options): def dashStyle(self): return self._config_get(None) def dashStyle(self, text: str): self._config(text, js_type=False) def fill(self): return self._config_get('rgba(0, 0, 0, 0.75)') def fill(self, text: str): self._config(text, js_typ...
class OperatorNode(RegistryNode): type = NodeTypes.OPERATOR def operator_class(self): return self.config['operator_class'] def operator_class_module(self): return self.config['operator_class_module'] def __init__(self, config, item): super(OperatorNode, self).__init__(config=conf...
class SPIFlash(): def __init__(self, regs): self.regs = regs def spi_xfer(self, length, mosi): self.regs.spiflash_spi_mosi.write(mosi) self.regs.spiflash_spi_control.write(((length * CTRL_LENGTH) | CTRL_START)) while (not (self.regs.spiflash_spi_status.read() & STATUS_DONE)): ...
class EncodeTextLoader(BaseLoader): def __init__(self, file_path: str, encoding: Optional[str]=None): self.file_path = file_path self.encoding = encoding def load(self) -> List[Document]: with open(self.file_path, 'rb') as f: raw_text = f.read() result = chardet.d...
def test_build_matrix_cooler_multiple(): outfile = NamedTemporaryFile(suffix='.mcool', delete=False) outfile.close() outfile_bam = NamedTemporaryFile(suffix='.bam', delete=False) outfile.close() qc_folder = mkdtemp(prefix='testQC_') args = '-s {} {} --outFileName {} -bs 5000 10000 20000 -b {} --...
class VersionTester(unittest.TestCase): def setUp(self): super(self.__class__, self).setUp() self.patcher = PlatformPatcher() from stalker import Status, StatusList self.test_status1 = Status(name='Status1', code='STS1') self.test_status2 = Status(name='Status2', code='STS2')...
class OptionSeriesCylinderSonificationTracksMappingTremoloSpeed(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): ...
def gemini_generate_stream(model: ProxyModel, tokenizer, params, device, context_len=2048): 'Zhipu ai, see: model_params = model.get_params() print(f'Model: {model}, model_params: {model_params}') global history proxy_api_key = model_params.proxy_api_key proxyllm_backend = (GEMINI_DEFAULT_MODEL...
class Pawn(Piece): def __init__(self, x, y, d): super().__init__(x, y, d) self.set_letter('') def draw_moves(self, pieces): fake_piece = Pawn(self.start_x, self.start_y, self.color) end_positions = [] forward_dist = 1 if (self.turn == 0): forward_dist ...
class RowLimitedIDVDownloadViewSet(BaseDownloadViewSet): endpoint_doc = 'usaspending_api/api_contracts/contracts/v2/download/idv.md' def post(self, request): request.data['constraint_type'] = 'row_count' return BaseDownloadViewSet.post(self, request, validator_type=IdvDownloadValidator)
class Dialogues(): _keep_terminal_state_dialogues = False def __init__(self, self_address: Address, end_states: FrozenSet[Dialogue.EndState], message_class: Type[Message], dialogue_class: Type[Dialogue], role_from_first_message: Callable[([Message, Address], Dialogue.Role)], keep_terminal_state_dialogues: Optio...