code
stringlengths
281
23.7M
def test_EquationBC_mixedpoisson_matrix_fieldsplit(): mat_type = 'aij' eq_type = 'linear' porder = 2 solver_parameters = {'mat_type': mat_type, 'ksp_type': 'fgmres', 'ksp_rtol': 1e-08, 'ksp_max_it': 200, 'pc_type': 'fieldsplit', 'pc_fieldsplit_type': 'schur', 'pc_fieldsplit_schur_fact_type': 'full', 'fi...
def test_analytic_mass(u_v): (u, v) = u_v a = (inner(u, v) * dx) vals = assemble(a).M.values analytic = np.asarray([[(1 / 36), (1 / 72), (1 / 72), (1 / 144), (1 / 72), (1 / 144)], [(1 / 72), (1 / 36), (1 / 144), (1 / 72), (1 / 144), (1 / 72)], [(1 / 72), (1 / 144), (1 / 36), (1 / 72), (1 / 72), (1 / 144...
class SchemaCheck(object): def __init__(self, config, schema, test_what, location): self.loggit = logging.getLogger('curator.validators.SchemaCheck') self.loggit.debug('Schema: %s', schema) self.loggit.debug('"%s" config: %s', test_what, config) self.config = config self.sche...
def assemble_word_html_content(user_email, subscription, todays_words): print('assembling word content...') print('list subscription: ', subscription) url = os.environ['URL'] word = todays_words[subscription.list_id][0]['word'] print('selected word, ', word) if (word is None): return '' ...
def ray_tmp_dir(config: Dict[(Any, Any)], run_env: str) -> Generator[(Any, None, None)]: out = sdk.run_on_cluster(config, run_env=run_env, cmd='echo $(mktemp -d)', with_output=True).decode() tmppath = [x for x in out.strip().split() if (x.startswith('/tmp/') and ('ray-config' not in x))] assert (len(tmppath...
def test_encode_1_variable_with_counts(df_enc): encoder = CountFrequencyEncoder(encoding_method='count', variables=['var_A']) X = encoder.fit_transform(df_enc) transf_df = df_enc.copy() transf_df['var_A'] = [6, 6, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 4, 4, 4, 4] assert (encoder.encodi...
def test_default_values(): schema = {'type': 'record', 'name': 'test_default_values', 'fields': [{'name': 'default_field', 'type': 'string', 'default': 'default_value'}]} records = [{}] new_records = roundtrip(schema, records) assert (new_records == [{'default_field': 'default_value'}])
def _message_handler(func: _C1, raw: _ce.CloudEvent) -> None: event_attributes = raw._get_attributes() data: _typing.Any = raw.get_data() message: StorageObjectData = StorageObjectData(bucket=data['bucket'], generation=data['generation'], id=data['id'], metageneration=data['metageneration'], name=data['name...
class TestInterpolateConverter(AITTestCase): ([param(scale_factor=1, mode='nearest'), param(scale_factor=2, mode='nearest'), param(scale_factor=2, mode='bilinear')]) def test_interpolate(self, scale_factor, mode): class TestModule(torch.nn.Module): def forward(self, y: torch.Tensor) -> torch...
def test_not_really_json_parsing(): father = '{\n "id" : 1,\n "married" : true,\n "name" : "Larry Lopez",\n "sons" : null,\n "daughters" : [\n {\n "age" : 26,\n "name" : "Sandra"\n },\n {\n "age" : 25,\n "nam...
def test(): model.eval() test_loss = 0 correct = 0 for (data, target) in test_loader: if args.cuda: (data, target) = (data.cuda(), target.cuda()) (data, target) = (Variable(data, volatile=True), Variable(target)) data = data.view((- 1), (28 * 28)) output = mod...
class PriorityTab(QWidget): def __init__(self, priority_list, parent): QWidget.__init__(self) self.parent = parent self.t_view = QTableView() html_delegate = HTMLDelegate() model = self.get_model(priority_list) self.t_view.setItemDelegateForColumn(0, html_delegate) ...
def json_path_to_examples(data_path, NLP): data = srsly.read_json(data_path) docs = json_to_docs(data) docbin = DocBin() for doc in docs: docbin.add(doc) docs = docbin.get_docs(NLP.vocab) examples = [Example(NLP.make_doc(doc.text), doc) for doc in docs] return examples
class TestRestartFromFailure(): (scope='function') def url(self, db, privacy_request): return (V1_URL_PREFIX + PRIVACY_REQUEST_RETRY.format(privacy_request_id=privacy_request.id)) def test_restart_from_failure_not_authenticated(self, api_client, url): response = api_client.post(url, headers=...
def on_message(client, userdata, msg): if (not msg.topic.startswith('$SYS')): try: key = msg.topic.replace('/', '.').lower() if len(prefix): key = ('%s.%s' % (prefix, key)) val = EEGsynth.rescale(float(msg.payload), slope=output_scale, offset=output_offset...
class Paginator(object): LIMIT = None OFFSET = 0 ORDER = 'id' def __init__(self, query, model, limit=None, offset=None, order=None, order_type=None, **kwargs): self.query = query self.model = model self.limit = (limit or self.LIMIT) self.offset = (offset or self.OFFSET) ...
(scope='function') def privacy_request_status_canceled(db: Session, policy: Policy) -> PrivacyRequest: privacy_request = _create_privacy_request_for_policy(db, policy, PrivacyRequestStatus.canceled) privacy_request.started_processing_at = None privacy_request.save(db) (yield privacy_request) privacy...
def mock_module_disabled(self, cmd): if ('modprobe' in cmd): output = ['install /bin/true '] error = [''] returncode = 0 elif ('lsmod' in cmd): output = [''] error = [''] returncode = 1 return SimpleNamespace(stdout=output, stderr=error, returncode=returncode)
def _discover_minimum_mtu_to_target(address, port): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect((address, port)) s.setsockopt(socket.IPPROTO_IP, IP_MTU_DISCOVER, IP_MTU_DISCOVER_DO) for attempt in MTU_ATTEMPTS: try: s.send((b'#' * (attempt - DATAGRAM_HEADER_LENGTH_...
.django_db def test_missing_spending_type(client, monkeypatch, generic_account_data, helpers): helpers.patch_datetime_now(monkeypatch, 2022, 12, 31) resp = helpers.post_for_spending_endpoint(client, url, def_codes=['A']) assert (resp.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY) assert (resp.data...
def mock_audit_events_for_successful_file_system_mounts_are_collected_pass(self, cmd): if ('auditctl' in cmd): stdout = ['-a always,exit -F arch=b64 -S mount -F auid>=1000 -F auid!=-1 -F key=mounts', '-a always,exit -F arch=b32 -S mount -F auid>=1000 -F auid!=-1 -F key=mounts'] else: stdout = ['...
.django_db def test_budget_function_list_sort_by_obligated_amount(client, monkeypatch, agency_account_data, helpers): helpers.mock_current_fiscal_year(monkeypatch) query_params = f'?fiscal_year={helpers.get_mocked_current_fiscal_year()}&order=asc&sort=obligated_amount' resp = client.get(url.format(code='007...
class TestTask(GymTestCase): def test__init__(self): assert (self.task.nb_steps == self.nb_steps) assert (self.task.is_rl_agent_training is False) def test_properties(self): assert (self.task.proxy_env == self.task._proxy_env) assert (self.task.proxy_env_queue == self.task._proxy...
class Migration(migrations.Migration): dependencies = [('admin_interface', '0020_module_selected_colors')] operations = [migrations.AlterField(model_name='theme', name='favicon', field=models.FileField(blank=True, help_text='(.ico|.png|.gif - 16x16|32x32 px)', upload_to='admin-interface/favicon/', validators=[F...
def extractBallKickingGangBoss(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol or frag)) or ('preview' in item['title'].lower())): return None if ('jinsei' in item['tags']): return buildReleaseMessageWithType(item, "I'll Live My Second ...
def setUpModule(): Practice.objects.create(code='N84014', name='AINSDALE VILLAGE SURGERY', address1='THE SURGERY', address2='2 LEAMINGTON RD AINSDALE', address3='SOUTHPORT', address4='MERSEYSIDE', postcode='PR8 3LB') Practice.objects.create(code='G82650', name='MOCKETTS WOOD SURGERY', address1="THE MOCKETT'S WO...
class Serializer(BaseSerializer, _Serializer, DRFSerializer): _property async def adata(self): ret = (await super().adata) return ReturnDict(ret, serializer=self) async def ato_representation(self, instance): ret = OrderedDict() fields = self._readable_fields for fiel...
class SpecialConv2dBiasAct(Module): def __init__(self, op_name, in_channels, out_channels, kernel_size, stride, padding=0, dilation=1, auto_padding=True, dtype='float16'): super().__init__() if (auto_padding and (in_channels < 4)): in_channels = 4 elif (auto_padding and (in_chann...
def test_call_with_init_positional_args(): provider = providers.Factory(Example, 'i1', 'i2') instance1 = provider() instance2 = provider() assert (instance1.init_arg1 == 'i1') assert (instance1.init_arg2 == 'i2') assert (instance2.init_arg1 == 'i1') assert (instance2.init_arg2 == 'i2') a...
(STORAGE_DEFAULT, dependencies=[Security(verify_oauth_client, scopes=[STORAGE_READ])], response_model=Page[StorageDestinationResponse]) def get_default_configs(*, db: Session=Depends(deps.get_db), params: Params=Depends()) -> AbstractPage[StorageConfig]: logger.info('Finding default storage configurations with pagi...
class LedgerApiHandler(Handler): SUPPORTED_PROTOCOL = LedgerApiMessage.protocol_id def setup(self) -> None: def handle(self, message: Message) -> None: self.context.logger.info('Handling ledger api msg') ledger_api_msg = cast(LedgerApiMessage, message) ledger_api_dialogues = cast(Led...
class OptionTooltipDatetimelabelformats(Options): def day(self): return self._config_get('%A, %e %b %Y') def day(self, text: str): self._config(text, js_type=False) def hour(self): return self._config_get('%A, %e %b, %H:%M') def hour(self, text: str): self._config(text, j...
def test_inverse_transform_when_ignore_unseen(): df1 = pd.DataFrame({'words': ['dog', 'dog', 'cat', 'cat', 'cat', 'bird']}) df2 = pd.DataFrame({'words': ['dog', 'dog', 'cat', 'cat', 'cat', 'frog']}) df3 = pd.DataFrame({'words': ['dog', 'dog', 'cat', 'cat', 'cat', nan]}) y = [1, 0, 1, 0, 1, 0] enc = ...
('dalton') def test_h2o_opt(): geom = geom_loader('lib:h2o.xyz', coord_type='redund') calc = Dalton(basis='3-21G') geom.set_calculator(calc) opt = RFOptimizer(geom, thresh='gau_tight') opt.run() assert opt.is_converged assert (opt.cur_cycle == 4) assert (geom.energy == pytest.approx((- 7...
def server_functional(host, port, dbtype=DB_TYPE_HMM, qtype=QUERY_TYPE_SEQ): if server_up(host, port): try: if (qtype == QUERY_TYPE_SEQ): get_hits('test', 'TESTSEQ', host, port, dbtype, qtype=qtype) elif (qtype == QUERY_TYPE_HMM): get_hits('test', test...
def extractLovexsweetWordpressCom(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...
class Product(TestCase, Common): def setUp(self): self.seq = nutils.elementseq._Product(nutils.elementseq.References.from_iter([square, triangle], 2), nutils.elementseq.References.uniform(line, 3)) self.check = (([(square * line)] * 3) + ([(triangle * line)] * 3)) self.checkndims = 3 ...
class Reject(InstantSpellCardAction): def __init__(self, source, target_act): self.source = source self.target_act = target_act self.target = target_act.target def apply_action(self): if (not isinstance(self.target_act, SpellCardAction)): return False self.tar...
class TestSparseMaskChannel(): def test_sparse_model_size(self) -> None: model = FCModel() params_to_prune = [(model.fc1, 'weight'), (model.fc1, 'bias'), (model.fc2, 'weight'), (model.fc2, 'bias'), (model.fc3, 'weight'), (model.fc3, 'bias')] prune.global_unstructured(params_to_prune, pruning...
def get_pubkey(username, projectname, log, sign_domain, outfile=None): usermail = create_gpg_email(username, projectname, sign_domain) cmd = [SIGN_BINARY, '-u', usermail, '-p'] (returncode, stdout, stderr) = call_sign_bin(cmd, log) if (returncode != 0): if ('unknown key:' in stderr): ...
def unsign(wheelfile): warn_signatures() vzf = VerifyingZipFile(wheelfile, 'a') info = vzf.infolist() if (not (len(info) and info[(- 1)].filename.endswith('/RECORD.jws'))): raise WheelError('The wheel is not signed (RECORD.jws not found at end of the archive).') vzf.pop() vzf.close()
class OptionSeriesLollipopSonificationTracksPointgrouping(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): sel...
def test_main(modules, serial_override=None): print(('testing module %s' % modules)) (requested_test_classes, regex_test_classes, clean, dumpfail, debug, keep_logs, nocheck, serial, repeat, excluded_test_classes, report_json_filename, port_order, start_port, loglevel, profile) = parse_args() if (serial_over...
class UntypedActivityStub(): _decision_context: object = None _retry_parameters: RetryParameters = None _activity_options: ActivityOptions = None async def execute(self, activity_name: str, *args): f = (await self.execute_async(activity_name, *args)) return (await f.wait_for_result()) ...
class PurgatoryMode(BaseMode): name = Mode.purgatory keymap = {Action.regain_control: False} def __init__(self): super().__init__() self.is_window_active = None self.dim_overlay = GenericMenu(title='Click to continue...', frame_color=(0, 0, 0, 0.4), title_pos=(0, 0, (- 0.2))) ...
class InetZoneIndex(TextualConvention, Unsigned32): status = 'current' displayHint = 'd' if mibBuilder.loadTexts: description = 'A zone index identifies an instance of a zone of a specific scope. The zone\nindex MUST disambiguate identical address values. For link-local addresses, the\nzone index wi...
def configure_fn(apikey: str) -> None: def auth(req): req.headers[HEADER_APIKEY] = apikey return req if os.path.exists(CREDENTIAL_FILE): with open(CREDENTIAL_FILE, encoding='utf-8') as fp: auth_json = json.load(fp) email = auth_json['email'] password = auth_js...
_member_required def remove_document_metadata(request, uuid, metadata_uuid=None): uuid = UUID(uuid) doc = get_object_or_404(Document, uuid=uuid) if (metadata_uuid is not None): try: has = DocumentHasBinaryMetadata.objects.all().get(document=doc, metadata=metadata_uuid) except Doc...
def test_partitioned_analyses_raises_exception_at_init_if_partitions_is_none_and_value_gt_than_255(): d = DumbPartDistinguisher() with pytest.raises(ValueError, match='max value for intermediate data is greater than 255'): d.update(traces=np.random.randint(0, 255, (500, 200), dtype='int16'), data=np.ran...
class SearchFilterFkTests(TestCase): def test_must_call_distinct(self): filter_ = filters.SearchFilter() prefixes = ([''] + list(filter_.lookup_prefixes)) for prefix in prefixes: assert (not filter_.must_call_distinct(SearchFilterModelFk._meta, [('%stitle' % prefix)])) ...
def test_receipts_request_with_extra_unrequested_receipts(): headers_bundle = mk_headers(1, 3, 2, 5, 4) (headers, receipts, trie_roots_and_data) = zip(*headers_bundle) receipts_bundle = tuple(zip(receipts, trie_roots_and_data)) wrong_headers = mk_headers(4, 3, 8) (_, wrong_receipts, wrong_trie_roots...
class OptionSeriesBarDragdropDraghandle(Options): def className(self): return self._config_get('highcharts-drag-handle') def className(self, text: str): self._config(text, js_type=False) def color(self): return self._config_get('#fff') def color(self, text: str): self._co...
class HomeConnectStatusSensor(SensorEntity): should_poll = True _attr_has_entity_name = True def __init__(self, homeconnect: HomeConnect) -> None: self._homeconnect = homeconnect self.entity_id = f'home_connect.{self.unique_id}' def device_info(self): return HOME_CONNECT_DEVICE ...
def lazy_import(): from fastly.model.read_only_customer_id import ReadOnlyCustomerId from fastly.model.read_only_id import ReadOnlyId from fastly.model.read_only_user_id import ReadOnlyUserId globals()['ReadOnlyCustomerId'] = ReadOnlyCustomerId globals()['ReadOnlyId'] = ReadOnlyId globals()['Rea...
class MH_Trace(command_line.MISS_HIT_Back_End): def __init__(self, options): super().__init__('MH Trace') self.imp_items = [] self.act_items = [] self.options = options def process_wp(cls, wp): lexer = MATLAB_Lexer(wp.cfg.language, wp.mh, wp.get_content(), wp.filename, wp...
class DjangoStreamTest(IsolatedAsyncioTestCase): def setUpClass(cls): super().setUpClass() cls.storage = DjangoModelStorage() pass ('django_eventstream.eventstream.get_storage') async def test_stream_with_last_event_id_does_not_loop_forever(self, mock_get_storage): (events_co...
class AsyncSearchClient(NamespacedClient): _rewrite_parameters() async def delete(self, *, id: str, error_trace: t.Optional[bool]=None, filter_path: t.Optional[t.Union[(str, t.Sequence[str])]]=None, human: t.Optional[bool]=None, pretty: t.Optional[bool]=None) -> ObjectApiResponse[t.Any]: if (id in SKIP_...
('/select-language', strict_slashes=False) ('/allure-docker-service/select-language', strict_slashes=False) _required def select_language_endpoint(): try: code = request.args.get('code') if (code is None): raise Exception("'code' query parameter is required") code = code.lower() ...
class ExponentialSechSqDiskModel(FunctionModel2DScalarAuto): _fcoordsys = 'cartesian' def f(self, inarr, A=1, l=2, h=1, pa=0): (s, z) = inarr if (pa == 0): (sr, zr) = (s, z) else: (sinpa, cospa) = (np.sin(pa), np.cos(pa)) sr = ((cospa * s) + (sinpa * z...
class bsn_gentable_stats_request(bsn_stats_request): version = 6 type = 18 stats_type = 65535 experimenter = 6035143 subtype = 7 def __init__(self, xid=None, flags=None): if (xid != None): self.xid = xid else: self.xid = None if (flags != None): ...
class TestDictItemObserverNotifications(unittest.TestCase): def test_notify_dict_change(self): instance = ClassWithDict(values=dict()) graph = create_graph(create_observer(notify=True)) handler = mock.Mock() call_add_or_remove_notifiers(object=instance.values, graph=graph, handler=ha...
def test_cicd_contains_pypi_secrets(cookies, tmp_path): with run_within_dir(tmp_path): result = cookies.bake(extra_context={'publish_to': 'pypi'}) assert (result.exit_code == 0) assert file_contains_text(f'{result.project_path}/.github/workflows/on-release-main.yml', 'PYPI_TOKEN') as...
class Configuration(): log_level = str mqtt_host = str mqtt_password = str mqtt_port = int mqtt_ssl = bool mqtt_user = str tydom_alarm_home_zone = int tydom_alarm_night_zone = int tydom_alarm_pin = str tydom_ip = str tydom_mac = str tydom_password = str thermostat_cus...
class DisasterRecipientDownloadValidator(DownloadValidatorBase): name = 'disaster_recipient' def __init__(self, request_data: dict): super().__init__(request_data) self.tinyshield_models.extend([{'key': 'filters|def_codes', 'name': 'def_codes', 'type': 'array', 'array_type': 'enum', 'enum_values...
class TestActionShrink_route_index(TestCase): def builder(self): self.client = Mock() self.client.info.return_value = {'version': {'number': '8.0.0'}} self.client.cat.indices.return_value = testvars.state_one self.client.indices.get_settings.return_value = testvars.settings_one ...
class GasNowStrategy(SimpleGasStrategy): def __init__(self, speed: str='fast'): if (speed not in ('rapid', 'fast', 'standard', 'slow')): raise ValueError('`speed` must be one of: rapid, fast, standard, slow') self.speed = speed def get_gas_price(self) -> int: return _fetch_ga...
def generate_activity_modal_summary(days=7): date = (datetime.now().date() - timedelta(days=days)) df = pd.read_sql(sql=app.session.query(ouraActivitySummary.summary_date, ouraActivitySummary.score, ouraActivitySummary.cal_active, ouraActivitySummary.target_calories, ouraActivitySummary.inactive).filter((ouraAc...
class ClientTestCase(unittest.TestCase): def setUp(self): env_dist = os.environ email = env_dist.get('FOFA_EMAIL') key = env_dist.get('FOFA_KEY') if ((not email) and (not key)): config = open('../CONFIG').read() (email, key) = config.split('\n') self.c...
(scope='module', params=[('mu_s*inner(grad(u), outer(conj(v), n)) * ds', 'mu_s*inner(grad(u), outer(conj(v), n)) * ds'), ('mu_s*(-inner(grad(u), outer(conj(v), n), ) - inner(outer(conj(u), n), grad(v))) * ds', '-2*mu_s*(inner(grad(u), outer(conj(v), n))) * ds'), ('-mu_s*(inner(grad(u), outer(conj(v), n)) + inner(outer(...
def usort_stdin() -> bool: if sys.stdin.isatty(): print('Warning: stdin is a tty', file=sys.stderr) try: config = Config.find() data = sys.stdin.read() result = usort_string(data, config, Path('<stdin>')) sys.stdout.write(result) return True except Exception a...
class TestVerifyRunAgainstBcl2fastq2MultiLaneSampleSheetNoLaneSplitting(unittest.TestCase): def setUp(self): self.top_dir = tempfile.mkdtemp() self.mock_illumina_data = MockIlluminaData('test.MockIlluminaData', 'bcl2fastq2', no_lane_splitting=True, paired_end=True, top_dir=self.top_dir) self...
class StatMixClass(SimpleEntity, StatusMixin): __tablename__ = 'StatMixClasses' __mapper_args__ = {'polymorphic_identity': 'StatMixClass'} StatMixClass_id = Column('id', Integer, ForeignKey('SimpleEntities.id'), primary_key=True) def __init__(self, **kwargs): super(StatMixClass, self).__init__(*...
class YamlParser(FileParser): def parse(self, content: str) -> List[str]: try: data = yaml.safe_load(content) if (isinstance(data, dict) and ('dependencies' in data)): dependencies = [] for package in data['dependencies']: if isinst...
.parametrize('filter_params,is_valid', ((_make_filter_params(), True), (_make_filter_params(from_block=0), True), (_make_filter_params(to_block=0), True), (_make_filter_params(from_block=(- 1)), False), (_make_filter_params(to_block=(- 1)), False), (_make_filter_params(from_block=True), False), (_make_filter_params(to_...
def file_object_from_entry(fo_entry: FileObjectEntry, analysis_filter: (list[str] | None)=None, included_files: (set[str] | None)=None, parents: (set[str] | None)=None, virtual_file_paths: (dict[(str, list[str])] | None)=None, parent_fw: (set[str] | None)=None) -> FileObject: file_object = FileObject() _populat...
def get_config(): config = config_dict.ConfigDict() config.task = 'quadruped-run' config.action_repeat = 4 action_repeat = config.get_oneway_ref('action_repeat') config.discount = 0.99 config.episode_length = (1000 // action_repeat) config.train_steps = (500000 // action_repeat) config.i...
def test_call(): app = Flask(__name__) admin = base.Admin(app) view = MockView() admin.add_view(view) client = app.test_client() rv = client.get('/admin/') assert (rv.status_code == 200) rv = client.get('/admin/mockview/') assert (rv.data == b'Success!') rv = client.get('/admin/m...
def fill_numeric(df: pd.DataFrame, col: str, fill_type: str='median') -> pd.DataFrame: if (fill_type == 'median'): fill_value = df[col].median() elif (fill_type == 'mean'): fill_value = df[col].mean() elif (fill_type == '-1'): fill_value = (- 1) else: raise NotImplemented...
.anyio class TestMaxPerSecond(): class Spy(): def __init__(self, num_tasks: int) -> None: self.tasks = [self.task for _ in range(num_tasks)] self.args = [None for _ in range(num_tasks)] self.start_times: List[float] = [] async def task(self, *args: Any) -> None: ...
def test_multiple_values_returned_with_multiple_targets(): class ApprovalMachine(StateMachine): requested = State(initial=True) accepted = State(final=True) denied = State(final=True) (accepted, denied) def validate(self): return (1, 2) machine = ApprovalMachi...
class Camera_Clip(object): def __init__(self, filename, timestamp, duration=0, include=False): self._filename = filename self._duration = duration self._timestamp = timestamp self._include = include def filename(self): return self._filename def filename(self, value): ...
class MultiPartParser(BaseParser): media_type = 'multipart/form-data' handles_file_uploads = True handles_form_data = True def parse(self, stream, media_type, **options): boundary = media_type.params.get('boundary') if (boundary is None): msg = 'Multipart message missing boun...
class TestStoragePromptTemplate(): def test_constructor_and_properties(self): storage_item = StoragePromptTemplate(prompt_name='test', content='Hello {name}', prompt_language='en', prompt_format='f-string', input_variables='name', model='model1', chat_scene='chat', sub_chat_scene='sub_chat', prompt_type='ty...
def test_topic_tracker_needs_update(database, user, topic): forumsread = ForumsRead.query.filter((ForumsRead.user_id == user.id), (ForumsRead.forum_id == topic.forum_id)).first() topicsread = TopicsRead.query.filter((TopicsRead.user_id == user.id), (TopicsRead.topic_id == topic.id)).first() with current_app...
('cmd_args', [['polynomial.y=choice(-1, 0, 1)', 'polynomial.x=range(2,4)'], ['polynomial.y=1', 'polynomial.x=range(2,4)']]) def test_search_space_exhausted_exception(tmpdir: Path, cmd_args: List[str]) -> None: cmd = (['tests/apps/polynomial.py', '-m', ('hydra.run.dir=' + str(tmpdir)), 'hydra.job.chdir=True', 'hydra...
def test_tokenization_mismatch(nlp, train_data): train_examples = [] for (text, annot) in train_data[0:1]: eg = Example.from_dict(nlp.make_doc(text), annot) ref = eg.reference char_spans = {} for (key, cluster) in ref.spans.items(): char_spans[key] = [] fo...
class FacebookEvent(BaseObject): def __init__(self, api=None, body=None, communication=None, id=None, page=None, ticket_via=None, type=None, **kwargs): self.api = api self.body = body self.communication = communication self.id = id self.page = page self.ticket_via = t...
def get_local_rev(proj_dir, local_branch): try: output = subprocess.check_output('git rev-parse {}'.format(local_branch), cwd=proj_dir, shell=True).decode('utf-8') return output.rstrip() except subprocess.CalledProcessError: log.error("failed to call 'git rev-parse'") return None
class PlotExample(HasTraits): plot = Instance(Component) traits_view = View(UItem('plot', editor=ComponentEditor()), width=700, height=600, resizable=True, title='Dataview + renderer example') def _plot_default(self): x = linspace((- 5), 10, 500) y = sin(x) y2 = (0.5 * cos((2 * x))) ...
class MPOConfig(): min_replay_size: int = 1000 max_replay_size: int = 1000000 replay_table_name: str = adders_reverb.DEFAULT_PRIORITY_TABLE prefetch_size: Optional[int] = None samples_per_insert: float = 256.0 samples_per_insert_tolerance_rate: float = 0.1 discount: float = 0.99 batch_si...
.django_db def test_admin_readonly_fields(rf: RequestFactory) -> None: request = build_admin_request(rf) admin = APIKeyModelAdmin(APIKey, site) assert (admin.get_readonly_fields(request) == ('prefix',)) api_key = APIKey(name='test') assert (admin.get_readonly_fields(request, obj=api_key) == ('prefix...
((sys.version_info[0:2] < (3, 8)), reason='zip.Path available in python 3.8+') def test_importlib_resource_load_zip_path() -> None: config_source = ImportlibResourcesConfigSource(provider='foo', path='pkg://bar') conf = config_source._read_config(zipfile.Path('hydra/test_utils/configs/conf.zip', 'config.yaml'))...
('pyscf') def test_layer_calc(pyscf_acetaldehyd_getter): geom = pyscf_acetaldehyd_getter() calc = geom.calculator real_calc = PySCF(basis='sto3g') args = (geom.atoms, geom.cart_coords) real_low_en = real_calc.get_energy(*args)['energy'] oniom_en = geom.energy ref_energies = (real_low_en, oni...
class OptionPlotoptionsSunburstSonificationDefaultinstrumentoptionsMappingVolume(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, tex...
('config_name,overrides,expected', [param(None, [], [], id='none'), param(None, ['+group1=file1'], [ResultDefault(config_path='group1/file1', package='group1', parent='_dummy_empty_config_')], id='none+group1=file1')]) def test_with_none_primary(config_name: str, overrides: List[str], expected: List[ResultDefault]) -> ...
class HTMLInline(ContentEditorInline): formfield_overrides = {models.TextField: {'widget': forms.Textarea(attrs={'rows': 3, 'cols': 40, 'class': 'vLargeTextField'})}} button = '<span class="material-icons">code</span>' def get_fieldsets(self, request, obj=None): fieldsets = super().get_fieldsets(req...
def tokenizer_senter_score(examples, **kwargs): def has_sents(doc): return doc.has_annotation('SENT_START') results = Scorer.score_tokenization(examples) results.update(Scorer.score_spans(examples, 'sents', has_annotation=has_sents, **kwargs)) del results['sents_per_type'] return results
class Territory(): def __init__(self, grid, main, id_num, color): self.grid = grid self.id = id_num self.color = color self.main = main main.territory = self self.last_added = [main] self.members = [main] self.groups = [] self.db_instance = Non...
class OptionSeriesErrorbarSonificationContexttracksMappingLowpass(Options): def frequency(self) -> 'OptionSeriesErrorbarSonificationContexttracksMappingLowpassFrequency': return self._config_sub_data('frequency', OptionSeriesErrorbarSonificationContexttracksMappingLowpassFrequency) def resonance(self) -...
def test_write_messages(): output = BytesIO() ros_writer = Ros2Writer(output=output) schema = ros_writer.register_msgdef('test_msgs/TestData', 'string a\nint32 b') for i in range(0, 10): ros_writer.write_message(topic='/test', schema=schema, message={'a': f'string message {i}', 'b': i}, log_time...