code
stringlengths
281
23.7M
.django_db def test_is_registered_any_way_with_is_attendee_true_should_return_true(mocker, user1, event1): mock_is_attendee = mocker.patch('manager.templatetags.filters.is_attendee') mock_is_registered = mocker.patch('manager.templatetags.filters.is_registered') mock_is_attendee.return_value = True mock...
def make_the_menu(): machine_learning.groups.append(top) machine_learning.groups.append(classic) incremental_learning.groups.append(classification) incremental_learning.groups.append(clustering) incremental_learning.groups.append(regression) the_menu.groups.append(data_sources) the_menu.grou...
def test_count_values_in_summary(backend_db, stats_update_db): (fw, parent_fo, child_fo) = create_fw_with_parent_and_child() fw.processed_analysis = {'foo': generate_analysis_entry(summary=['s1', 's2'])} parent_fo.processed_analysis = {'foo': generate_analysis_entry(summary=['s3', 's4'])} child_fo.proce...
class PhoneNumber(str): def __get_validators__(cls) -> Generator: (yield cls.validate) def validate(cls, value: str) -> str: if (value == ''): return '' max_length = 16 min_length = 9 pattern = regex('^\\+[1-9]\\d{1,14}$') if ((len(value) > max_length)...
def atomic_write(path, mode='wt', permissions=None, file_factory=None, **kwargs): if (permissions is None): permissions = apply_umask() if (path == '-'): (yield sys.stdout) else: base_dir = os.path.dirname(path) kwargs['suffix'] = os.path.basename(path) tf = tempfile....
def generateCLM1(iterationsMap, iteration, t): msg = generateGenericMessage('EiffelConfidenceLevelModifiedEvent', t, '1.0.0', 'CLM1', iteration) link(msg, iterationsMap[iteration]['ArtC1'], 'SUBJECT') link(msg, iterationsMap[iteration]['TCF1'], 'CAUSE') link(msg, iterationsMap[iteration]['TCF2'], 'CAUSE...
def test_delayed(tmp_path: Path) -> None: delayed = utils.DelayedSubmission(_three_time, 4) assert (not delayed.done()) assert (delayed.result() == 12) assert delayed.done() delayed_pkl = (tmp_path / 'test_delayed.pkl') delayed.dump(delayed_pkl) delayed2 = utils.DelayedSubmission.load(delaye...
class OptionSeriesScatter3dSonificationPointgrouping(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: bool): self._co...
def replace_file(path: PathIn, src: PathIn, *, autodelete: bool=False) -> None: path = _get_path(path) src = _get_path(src) assert_not_dir(path) assert_file(src) if (path == src): return make_dirs_for_file(path) (dirpath, filename) = split_filepath(path) (_, extension) = split_fi...
class ListUserSchema(PaginatedSchema, SearchableSchema): name = colander.SchemaNode(colander.String(), location='querystring', missing=None) groups = Groups(colander.Sequence(accept_scalar=True), location='querystring', missing=None, preparer=[util.splitter]) updates = Updates(colander.Sequence(accept_scala...
class TestYaffsUnpacker(TestUnpackerBase): def test_unpacker_selection_generic(self): self.check_unpacker_selection('filesystem/yaffs', 'YAFFS') def test_extraction_big_endian(self): self.check_unpacking_of_standard_unpack_set(os.path.join(TEST_DATA_DIR, 'yaffs2_be.img'), additional_prefix_folde...
def extractCalicoxTabby(item): (chp, vol, frag) = extractChapterVolFragment(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None if ('Meow Meow Meow' in item['tags']): return buildReleaseMessageWithType(item, 'Meow Meow Meow', vol, chp, frag=frag) r...
class OptionSeriesWaterfallSonificationDefaultinstrumentoptionsMappingHighpass(Options): def frequency(self) -> 'OptionSeriesWaterfallSonificationDefaultinstrumentoptionsMappingHighpassFrequency': return self._config_sub_data('frequency', OptionSeriesWaterfallSonificationDefaultinstrumentoptionsMappingHighp...
class OptionPlotoptionsLollipopSonificationDefaultinstrumentoptionsMappingHighpass(Options): def frequency(self) -> 'OptionPlotoptionsLollipopSonificationDefaultinstrumentoptionsMappingHighpassFrequency': return self._config_sub_data('frequency', OptionPlotoptionsLollipopSonificationDefaultinstrumentoptions...
class Migration(migrations.Migration): dependencies = [('search', '0035_add_county_fips_code_to_awardsearch_transactionsearch')] operations = [migrations.AddField(model_name='subawardsearch', name='legal_entity_county_fips', field=models.TextField(blank=True, null=True)), migrations.AddField(model_name='subawar...
class PerfettoConfig(): ADAPTIVE_SAMPLING_SHMEM_THRESHOLD_DEFAULT = 32746 BUFFER_SIZE_KB_DEFAULT = (256 * 1024) BUFFER_SIZE2_KB_DEFAULT = (2 * 1024) SHMEM_SIZE_BYTES_DEFAULT = (16384 * 4096) SAMPLING_INTERVAL_BYTES_DEFAULT = 4096 DUMP_INTERVAL_MS_DEFAULT = 1000 BATTERY_POLL_MS_DEFAULT = 1000...
class NodeClient(): ACN_ACK_TIMEOUT = 5 def __init__(self, pipe: IPCChannel, agent_record: AgentRecord) -> None: self.pipe = pipe self.agent_record = agent_record self._wait_status: Optional[asyncio.Future] = None async def connect(self) -> bool: return (await self.pipe.conne...
def correlation(trace, pattern): (trace, pattern) = _check_and_cast_args(trace, pattern) n = len(pattern) ex = moving_mean(trace, n) ey = _np.mean(pattern) x2 = moving_sum((trace ** 2), n) y2 = _np.sum((pattern ** 2)) xy = _signal.correlate(trace, pattern, 'valid') numerator = (xy - ((n ...
class OptionSonificationGlobaltracksMappingRate(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._config(tex...
class Lock(Semaphore): def release(self, blocking=True): if (self.counter > 0): raise RuntimeError('release unlocked lock') self.counter += 1 if self._waiters: hubs.get_hub().schedule_call_global(0, self._do_acquire) return True def _at_fork_reinit(self): ...
def test(): sample_path = os.path.join('examples', 'data', 'sample.wav') alt_path = os.path.join('..', 'data', 'sample.wav') fname = find_resource('Chaco', sample_path, alt_path=alt_path, return_path=True) (index, data) = wav_to_numeric(fname) print(data[:100]) return (index, data)
def extractNovelSanctuary(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, chp, frag=frag, postf...
def update_binwise_positions(cnarr, segments=None, variants=None): cnarr = cnarr.copy() if segments: segments = segments.copy() seg_chroms = set(segments.chromosome.unique()) if variants: variants = variants.copy() var_chroms = set(variants.chromosome.unique()) for chrom ...
class TestFilmAdvanceMechanismShutterInterlock(object): def test_film_advance_cocks_shutter(self): c = Camera() c.film_advance_mechanism.advance() assert (c.exposure_control_system.shutter.cocked == True) with pytest.raises(FilmAdvanceMechanism.AlreadyAdvanced): c.film_ad...
class TestKQLtoDSL(unittest.TestCase): def validate(self, kql_source, dsl, **kwargs): actual_dsl = kql.to_dsl(kql_source, **kwargs) self.assertListEqual(list(actual_dsl), ['bool']) self.assertDictEqual(actual_dsl['bool'], dsl) def test_field_match(self): def match(**kv): ...
def test_host_with_auth_and_port_in_url(): url = ' client = response = client.get(url) assert (response.status_code == 200) assert (response.json() == {'headers': {'accept': '*/*', 'accept-encoding': 'gzip, deflate, br', 'connection': 'keep-alive', 'host': 'example.org', 'user-agent': f'python- 'au...
class WeeklyLogFile(logfile.DailyLogFile): def __init__(self, name, directory, defaultMode=None, day_rotation=7, max_size=1000000): self.day_rotation = day_rotation self.max_size = max_size self.size = 0 logfile.DailyLogFile.__init__(self, name, directory, defaultMode=defaultMode) ...
_stats_reply_type(ofproto.OFPST_DESC, body_single_struct=True) class OFPDescStats(ofproto_parser.namedtuple('OFPDescStats', ('mfr_desc', 'hw_desc', 'sw_desc', 'serial_num', 'dp_desc'))): _TYPE = {'ascii': ['mfr_desc', 'hw_desc', 'sw_desc', 'serial_num', 'dp_desc']} def parser(cls, buf, offset): desc = s...
_checkpoint(dump_params=True, include=['adpixels_ids'], component=LOG_COMPONENT) def _verify_adspixels_if_exist(adspixels_ids: List[str], client: BoltGraphAPIClient[BoltPLGraphAPICreateInstanceArgs]) -> None: if adspixels_ids: try: for pixel_id in adspixels_ids: client.get_adspix...
def fail_processing(submission_id: int, processor_id: str, exception: BaseException) -> int: exception_message = ''.join(format_exception(type(exception), exception, exception.__traceback__)) return DABSLoaderQueue.objects.filter(submission_id=submission_id, processor_id=processor_id, state=DABSLoaderQueue.IN_P...
class Text_Visitor(AST_Visitor): def __init__(self, fd): super().__init__() self.indent = 0 self.fd = fd def write(self, string): assert isinstance(string, str) txt = ((' ' * (self.indent * 2)) + string) if self.fd: self.fd.write((txt + '\n')) ...
def extractIsekaintrWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('Saint Doll', 'Seikishin -Saint Doll-', 'translated'), ('When I was summoned to different world ...
def extractLotustranslationsWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None if (item['tags'] == ['Announcements']): return None tagmap = [('Xianggong, Please Divor...
_deserializable class CacheConfig(BaseConfig): def __init__(self, similarity_eval_config: Optional[CacheSimilarityEvalConfig]=CacheSimilarityEvalConfig(), init_config: Optional[CacheInitConfig]=CacheInitConfig()): self.similarity_eval_config = similarity_eval_config self.init_config = init_config ...
def create_ssl_context(options: argparse.Namespace, bool=False) -> ssl.SSLContext: ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) ctx.load_cert_chain(options.certfile, keyfile=options.keyfile) if ctx.set_alpn_protocols(['h2']) ctx.options |= ((ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1) | ...
def read_asn1_key(binary: bytes, offset: int): if (binary[offset] not in TLV_KNOWN_STARTS): return None (start, size) = _get_start_and_size_of_der_field(binary=binary, offset=offset) try: key = OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_ASN1, binary[offset:(start + size)]) ...
class DNSLookupTool(LocalComponent, metaclass=ABCMeta): DEFAULT_HOSTNAME = 'google.com' DEFAULT_TIMEOUT = 5 def __init__(self, device, config): super().__init__(device, config) self._dig = Dig(self._device) def _check_current_dns_server_is_known(self, servers): server = ipaddress...
class SparkWasserstein(SparkStatTestImpl): base_stat_test = wasserstein_stat_test def __call__(self, data: SpartStatTestData, feature_type: ColumnType, threshold: float) -> StatTestFuncReturns: cur = data.current_data ref = data.reference_data column_name = data.column_name from ...
def create(reg_code: RegCodeModel, password: str) -> RegCodeModel: reg_code.password = _hash(password) with session() as s: existing = s.query(RegCodeOrmModel).filter_by(password=reg_code.password).one_or_none() if existing: raise ArgumentError(MESSAGE_DUPLICATE_REG_CODE) orm...
def admit_patient(inpatient_record, service_unit, check_in, expected_discharge=None): validate_nursing_tasks(inpatient_record) inpatient_record.admitted_datetime = check_in inpatient_record.status = 'Admitted' inpatient_record.expected_discharge = expected_discharge inpatient_record.set('inpatient_o...
class TaskHandler(object): def __init__(self): self.tasks = {} self.to_save = {} self.clock = reactor self.stale_timeout = 60 self._now = False def load(self): to_save = False value = ServerConfig.objects.conf('delayed_tasks', default={}) if isinst...
def read_simulation_from_hdf5(file_name: str) -> str: with h5py.File(file_name, 'r') as f_handle: num_string_parts = len([key for key in f_handle.keys() if (JSON_TAG in key)]) json_string = b'' for ind in range(num_string_parts): json_string += f_handle[_json_string_key(ind)][()]...
def hash_domain(domain_data: Dict[(str, Any)]) -> bytes: eip712_domain_map = {'name': {'name': 'name', 'type': 'string'}, 'version': {'name': 'version', 'type': 'string'}, 'chainId': {'name': 'chainId', 'type': 'uint256'}, 'verifyingContract': {'name': 'verifyingContract', 'type': 'address'}, 'salt': {'name': 'salt...
def test_strhex2int(): assert (strhex2int('0x00') == 0) assert (strhex2int('0x0A') == 10) assert (strhex2int('0x7F') == 127) assert (strhex2int('0xFF') == (- 1)) assert (strhex2int('0x0F') == 15) assert (strhex2int('0x80') == (- 128)) assert (strhex2int('0x80', signed=False) == 128) asse...
class OptionSeriesArearangeSonificationDefaultinstrumentoptionsMappingPlaydelay(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...
class BaseInstanceTest(object): def test_tag_unique(self, instance, i_data, cls, mod): tag = instance.tag err = ("tag '%s' is not unique (%s.%s)" % (tag, mod, cls)) assert (tags.count(tag) == 1), err def test_fields(self, instance, i_data, cls, mod): assert ('tag' in i_data) ...
class OptionPlotoptionsVariablepieSonificationContexttracksMappingTime(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): ...
_cli_group.command() ('--trace_id', required=False, type=str, default=None, show_default=True, help='Specify the trace ID to list') ('--span_id', required=False, type=str, default=None, show_default=True, help='Specify the Span ID to list.') ('--span_type', required=False, type=str, default=None, show_default=True, hel...
def _responderChain(startResponder): responderAddress = fb.evaluateExpression(startResponder) while int(responderAddress, 16): (yield fb.evaluateExpressionValue(responderAddress).GetObjectDescription()) responderAddress = fb.evaluateExpression((('(id)[(id)' + responderAddress) + ' nextResponder]...
class TestScriptGeneratorCli(): .parametrize('args', [['my-script.sh'], ['--use-nix', 'my-script.sh']]) def test_should_generate_script_using_given_arguments(self, cli_runner, args): with cli_runner.isolated_filesystem() as tmp: result = cli_runner.invoke(ScriptGenerator, args) a...
class Migration(migrations.Migration): dependencies = [migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('django_etebase', '0002_userinfo')] operations = [migrations.CreateModel(name='CollectionInvitation', fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_n...
class MigrationMongoInterface(MongoInterface): def _setup_database_mapping(self): main_database = self.config['data-storage']['main-database'] self.main = self.client[main_database] self.firmwares = self.main.firmwares self.file_objects = self.main.file_objects self.compare_r...
def run_baker_ts_opts(geoms, meta, coord_type='cart', thresh='baker', runid=0): start = time.time() converged = 0 failed = 0 cycles = 0 opt_kwargs = {'thresh': thresh, 'max_cycles': 100, 'dump': True, 'trust_radius': 0.3, 'trust_max': 0.3} results = dict() for (i, (name, geom)) in enumerate(...
class OptionSeriesParetoMarkerStatesHover(Options): def animation(self) -> 'OptionSeriesParetoMarkerStatesHoverAnimation': return self._config_sub_data('animation', OptionSeriesParetoMarkerStatesHoverAnimation) def enabled(self): return self._config_get(True) def enabled(self, flag: bool): ...
class OptionPlotoptionsAreasplinerangeLowmarkerStatesSelect(Options): def enabled(self): return self._config_get(True) def enabled(self, flag: bool): self._config(flag, js_type=False) def fillColor(self): return self._config_get('#cccccc') def fillColor(self, text: str): ...
class OptionSeriesBubbleSonificationTracksMappingPlaydelay(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....
class KobatoChanDaiSukiPageProcessor(BaseFontRemapProcessor): wanted_mimetypes = ['text/html'] want_priority = 80 loggerPath = 'Main.Text.KobatoChanDaiSuki' def wantsUrl(url): if re.search('^ url): print(("KobatoChanDaiSukiProcessor Wants url: '%s'" % url)) return True ...
class CurrentPrivacyPreference(LastSavedMixin, Base): preference = Column(EnumColumn(UserConsentPreference), nullable=False, index=True) privacy_preference_history_id = Column(String, ForeignKey(PrivacyPreferenceHistory.id), nullable=False, index=True) __table_args__ = (UniqueConstraint('provided_identity_i...
def getTemporaryPath(cmdenv): tmpPath = pathlib.Path('prices.tmp') if tmpPath.exists(): if (not cmdenv.force): raise TemporaryFileExistsError("Temporary file already exists: {}\n(Check you aren't already editing in another window".format(tmpPath)) tmpPath.unlink() return tmpPath
class SwapQuotes(bh_plugin.BracketPluginCommand): def escaped(self, idx): view = self.view escaped = False while ((idx >= 0) and (view.substr(idx) == '\\')): escaped = (~ escaped) idx -= 1 return escaped def run(self, edit, name): view = self.view ...
class OptionSeriesOrganizationSonificationDefaultinstrumentoptionsMappingTime(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: ...
class Solution(): def wordsAbbreviation(self, dict: List[str]) -> List[str]: def shorten(word, idx): return (word if (idx > (len(word) - 3)) else ((word[:idx] + str(((len(word) - 1) - idx))) + word[(- 1)])) res = [shorten(word, 1) for word in dict] pre = {word: 1 for word in dict...
def get_bridge_by_datapath_id(manager, system_id, datapath_id, fn=None): def _match_fn(row): row_dpid = dpidlib.str_to_dpid(str(row.datapath_id[0])) return (row_dpid == datapath_id) bridge = match_row(manager, system_id, 'Bridge', _match_fn) if (fn is not None): return fn(bridge) ...
class RaisingContainer(collections.abc.Sequence): def __len__(self): return 15 def __getitem__(self, index): if (not (0 <= index < 15)): raise IndexError('Index out of range') return 1729 def __contains__(self, value): if (value != 1729): raise TypeErr...
def add_filter(fledge_url, filter_plugin, filter_name, filter_config, plugin_to_filter): data = {'name': '{}'.format(filter_name), 'plugin': '{}'.format(filter_plugin), 'filter_config': filter_config} conn = conn.request('POST', '/fledge/filter', json.dumps(data)) r = conn.getresponse() assert (200...
.parametrize('transaction_args,method_args,method_kwargs,expected,skip_testrpc', (({}, (5,), {}, {'data': '0x6abbb3b', 'value': 0, 'maxFeePerGas': , 'maxPriorityFeePerGas': , 'chainId': }, False), ({'gas': 800000}, (5,), {}, {'data': '0x6abbb3b', 'value': 0, 'maxFeePerGas': , 'maxPriorityFeePerGas': , 'chainId': }, Fal...
def test_full_initialized_data_dir_with_custom_nodekey(): trinity_config = TrinityConfig(network_id=1, nodekey=NODEKEY) os.makedirs(trinity_config.data_dir, exist_ok=True) os.makedirs(trinity_config.logfile_path, exist_ok=True) os.makedirs(trinity_config.ipc_dir, exist_ok=True) os.makedirs(trinity_c...
def test_create_categorical_plot(): values = [int(i) for i in np.random.randint(low=0, high=10, size=100)] fig = create_categorical_plot(values) plt.close(fig) values = [(v, 10) for v in np.random.randint(low=0, high=10, size=100)] fig = create_categorical_plot(values) plt.close(fig) with ra...
def test_predict_num_roles(): with tempfile.TemporaryDirectory() as tmpdir: testdata = os.path.join(tmpdir, 'test_data') shutil.copytree('./tests/test_data', testdata) for file in ['combined_three_roles.csv', 'combined_two_roles.csv']: input_file = os.path.join(testdata, file) ...
class DahoasRMStaticDataset(Dataset): def __init__(self, block_size, split='train', max_examples=None, tokenizer_name='tiktoken/gpt2') -> None: super().__init__() dataset = load_dataset('Dahoas/rm-static', split=split) self.pairs = [] self.masks = [] if (tokenizer_name == 'hu...
def load_result_format(lab_test, template, prescription, invoice): if (template.lab_test_template_type == 'Single'): create_normals(template, lab_test) elif (template.lab_test_template_type == 'Compound'): create_compounds(template, lab_test, False) elif (template.lab_test_template_type == '...
def fortios_gtp(data, fos, check_mode): fos.do_member_operation('gtp', 'tunnel-limit') if data['gtp_tunnel_limit']: resp = gtp_tunnel_limit(data, fos, check_mode) else: fos._module.fail_json(msg=('missing task body: %s' % 'gtp_tunnel_limit')) if check_mode: return resp return...
def parseruleline(linestr, rulenum=(- 1)): global GlobalRules, EventValues, SysVars cline = linestr.strip() state = 'CMD' if ('[' in linestr): m = re.findall('\\[([A-Za-z0-9_#\\-]+)\\]', linestr) if (len(m) > 0): for r in range(len(m)): tval = str(gettaskvalue...
class HNSW(MutableMapping): def __init__(self, distance_func: Callable[([np.ndarray, np.ndarray], float)], m: int=16, ef_construction: int=200, m0: Optional[int]=None, seed: Optional[int]=None, reversed_edges: bool=False) -> None: self._nodes: OrderedDict[(Hashable, _Node)] = OrderedDict() self._dis...
class OptionSeriesWaterfallSonificationTracksMappingTremoloSpeed(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 OptionSeriesBulletDataTargetoptions(Options): def borderColor(self): return self._config_get(None) def borderColor(self, text: str): self._config(text, js_type=False) def borderRadius(self): return self._config_get(0) def borderRadius(self, num: float): self._config...
class OptionsSparkLineDiscrete(OptionsSpark): def lineHeight(self): return self._config_get(None) def lineHeight(self, value): self._config(value) def thresholdValue(self): return self._config_get(None) def thresholdValue(self, value): self._config(value) def threshol...
class OptionPlotoptionsPyramid3dSonificationDefaultinstrumentoptionsMappingPlaydelay(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 test_attrdict_middleware_is_recursive(w3): w3.middleware_onion.inject(construct_result_generator_middleware({RPCEndpoint('fake_endpoint'): (lambda *_: GENERATED_NESTED_DICT_RESULT)}), 'result_gen', layer=0) response = w3.manager.request_blocking('fake_endpoint', []) result = response['result'] asser...
def get_EC_and_optimization_config(enable_optimization): (time_alignment_config, hand_eye_config) = get_exhaustive_search_pose_inliers_config() optimiztion_config = OptimizationConfig() optimiztion_config.enable_optimization = enable_optimization optimiztion_config.optimization_only = False algorith...
def test_data_integrity_test_constant_columns() -> None: test_dataset = pd.DataFrame({'category_feature': [None, 'd', 'p', 'n'], 'numerical_feature': [0, 0, 0, 0], 'target': [0, 0, 0, 1]}) suite = TestSuite(tests=[TestNumberOfConstantColumns()]) suite.run(current_data=test_dataset, reference_data=test_datas...
_in_both(MyObject) def test_property_dict_mutate(): m = MyObject() print(m.dictprop) loop._processing_action = True m._mutate_dictprop(dict(foo=3), 'insert') m._mutate_dictprop(dict(bar=4), 'replace') print((('{' + ', '.join([('%s: %i' % (key, val)) for (key, val) in sorted(m.dictprop.items())])...
class FakeTableDataCreater(object): def __init__(self, id, dataset): self._id = id self._parent = dataset self._create_time = DEFAULT_TABLE_CREATE_TIME self._expiration_time = None def SetExpirationTime(self, et): self._expiration_time = et def get_resource(self): ...
class JSONDiffTestCase(CfgDiffTestCase): def test_json_same(self): self._test_same(cfgdiff.JSONDiff, './tests/test_same_1-a.json', './tests/test_same_1-b.json') def test_json_different(self): self._test_different(cfgdiff.JSONDiff, './tests/test_different_1-a.json', './tests/test_different_1-b.js...
class WalletStorage(): _store: AbstractStore _is_closed: bool = False _backup_filepaths: Optional[Tuple[(str, str)]] = None def __init__(self, path: str, manual_upgrades: bool=False, storage_kind: StorageKind=StorageKind.UNKNOWN) -> None: logger.debug("wallet path '%s'", path) dirname = ...
(malformed_type_strs) def test_predicates_have_expected_behavior_for_malformed_types(malformed_type_str): is_int = BaseEquals('int') is_int_with_sub = BaseEquals('int', with_sub=True) is_int_with_no_sub = BaseEquals('int', with_sub=False) assert (not is_int(malformed_type_str)) assert (not is_int_wi...
def pkginfo_to_metadata(egg_info_path, pkginfo_path): pkg_info = read_pkg_info(pkginfo_path) pkg_info.replace_header('Metadata-Version', '2.1') requires_path = os.path.join(egg_info_path, 'requires.txt') if os.path.exists(requires_path): with open(requires_path) as requires_file: req...
class IntervalSeries(MetricResult): class Config(): underscore_attrs_are_private = True bins: List[float] values: List[float] _data: pd.Series def data(self): if (not hasattr(self, '_data')): self._data = pd.Series(self.values, index=[Interval(a, b, closed='right') for (a...
class ClusterClient(NamespacedClient): _rewrite_parameters(body_fields=('current_node', 'index', 'primary', 'shard')) async def allocation_explain(self, *, current_node: t.Optional[str]=None, error_trace: t.Optional[bool]=None, filter_path: t.Optional[t.Union[(str, t.Sequence[str])]]=None, human: t.Optional[boo...
class TestSpotifyShow(): .xfail(reason='API inconsistencies') def test_show_not_found_without_market(self, app_client): with pytest.raises(HTTPError): app_client.show(show_id) def test_show_found_with_market(self, app_client): show = app_client.show(show_id, market='FI') ...
def test_marked_log_matches() -> None: marked_bytes = importlib.resources.read_binary(package=plotman._tests.resources, resource='chianetwork.marked') log_bytes = importlib.resources.read_binary(package=plotman._tests.resources, resource='chianetwork.plot.log') for (marked_line, log_line) in zip(marked_byte...
class Status(Html.Html): name = 'status' tag = 'div' _option_cls = OptText.OptionsStatus def __init__(self, page: primitives.PageModel, status, width, height, html_code, profile, options): super(Status, self).__init__(page, status, html_code=html_code, profile=profile, options=options, css_attrs...
def arc(pRA, pDecl, sRA, sDecl, mcRA, lat): (pDArc, pNArc) = utils.dnarcs(pDecl, lat) (sDArc, sNArc) = utils.dnarcs(sDecl, lat) mdRA = mcRA sArc = sDArc pArc = pDArc if (not utils.isAboveHorizon(sRA, sDecl, mcRA, lat)): mdRA = angle.norm((mcRA + 180)) sArc = sNArc pArc = ...
class TaskContext(ABC, Generic[T]): def task_id(self) -> str: def task_input(self) -> 'InputContext': def set_task_input(self, input_ctx: 'InputContext') -> None: def task_output(self) -> TaskOutput[T]: def set_task_output(self, task_output: TaskOutput[T]) -> None: def current_state(self) -> Tas...
def uuid(ctokens=_UNPACKED_CTOKENS): rand_longs = (random.getrandbits(64), random.getrandbits(64)) if _HAVE_URANDOM: urand_longs = struct.unpack('=QQ', fast_urandom16()) byte_s = struct.pack('=QQ', ((rand_longs[0] ^ urand_longs[0]) ^ ctokens[0]), ((rand_longs[1] ^ urand_longs[1]) ^ ctokens[1])) ...
class TestUtils(unittest.TestCase): def setUp(self) -> None: self.utils = Utils() def test_create_file(self) -> None: fake_file_path = 'fake/file/path' content_list = ['This is test string'] with patch('fbpcs.infra.logging_service.download_logs.utils.utils.open', mock_open()) as ...
class TestSetEventFactory(unittest.TestCase): def test_trait_set_notification_compat(self): events = [] def notifier(*args, **kwargs): event = set_event_factory(*args, **kwargs) events.append(event) trait_set = TraitSet([1, 2, 3], notifiers=[notifier]) trait_s...
def expand_faces(faces: Set[bmesh.types.BMFace], dist: int) -> Set[bmesh.types.BMFace]: if (dist <= 0): visited = set(faces) else: visited = set() traversal_queue = collections.deque(((f, 0) for f in faces)) while (len(traversal_queue) > 0): (f_curr, dist_curr) = trav...
.integration class TestHealthchecks(): .parametrize('database_health, expected_status_code', [('healthy', 200), ('unhealthy', 503), ('needs migration', 503)]) def test_database_healthcheck(self, test_config: FidesConfig, database_health: str, expected_status_code: int, monkeypatch: MonkeyPatch, test_client: Tes...
def get_workout_types(df_summary, run_status, ride_status, all_status): df_summary['type'] = df_summary['type'].fillna('REMOVE') df_summary = df_summary[(df_summary['type'] != 'REMOVE')] other_workout_types = [x for x in df_summary['type'].unique() if (('ride' not in x.lower()) and ('run' not in x.lower()))...