code
stringlengths
281
23.7M
class OptionSeriesWordcloudDataDatalabelsFilter(Options): def operator(self): return self._config_get(None) def operator(self, value: Any): self._config(value, js_type=False) def property(self): return self._config_get(None) def property(self, text: str): self._config(tex...
def delete_obsolete_rows(source: ETLObjectBase, destination: ETLWritableObjectBase) -> int: sql = '\n delete from {destination_object_representation}\n where not exists (\n select from {source_object_representation} s where {join}\n )\n ' sql = SQL(sql).format(destination_obje...
def test_requeuing_checkpointable(tmp_path: Path, fast_forward_clock) -> None: usr_sig = submitit.JobEnvironment._usr_sig() fs0 = helpers.FunctionSequence() fs0.add(test_core._three_time, 10) assert isinstance(fs0, helpers.Checkpointable) with mocked_slurm(): executor = slurm.SlurmExecutor(f...
def query_cache(cls, pk=None, pks=None): (ls, d) = _get_cached_collections() if ((not ls[cls]) or (not d[cls])): update_cache(cls) (ls, d) = _get_cached_collections() if (pk is not None): return d[cls].get(str(pk)) elif (pks is not None): return [d[cls].get(str(pk)) for p...
def test(): assert (len(pattern) == 3), 'The pattern should describe three tokens (three dictionaries).' assert (isinstance(pattern[0], dict) and isinstance(pattern[1], dict) and isinstance(pattern[2], dict)), 'Each entry in a pattern should be a dictionary.' assert ((len(pattern[0]) == 1) and (len(pattern[...
class PatchEmbed(nn.Module): def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, norm_layer=None, flatten=True): super().__init__() self.img_size = img_size self.patch_size = patch_size self.grid_size = ((img_size // patch_size), (img_size // patch_size)) ...
class _BlockStore(): _block_present: Set[BlockUid] def __init__(self, directory: str) -> None: self._directory = directory self._block_present = set() def _cache_filename(self, block_uid: BlockUid) -> str: assert ((block_uid.left is not None) and (block_uid.right is not None)) ...
def transform_award_data(worker: TaskSpec, records: List[dict]) -> List[dict]: converters = {'covid_spending_by_defc': convert_json_data_to_dict, 'iija_spending_by_defc': convert_json_data_to_dict} agg_key_creations = {'funding_subtier_agency_agg_key': (lambda x: x['funding_subtier_agency_code']), 'funding_topt...
class FifteenAPI(BikeShareSystem): sync = True meta = {'system': 'Fifteen', 'company': ['Fifteen SAS']} def __init__(self, tag, feed_url, meta): super(FifteenAPI, self).__init__(tag, meta) self.feed_url = feed_url def update(self, scraper=None): scraper = (scraper or PyBikesScrap...
class RelationshipServices(ModelNormal): 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_import()...
def test_with_initialize() -> None: with initialize(version_base=None, config_path='../hydra_app/conf'): cfg = compose(config_name='config', overrides=['app.user=test_user']) assert (cfg == {'app': {'user': 'test_user', 'num1': 10, 'num2': 20}, 'db': {'host': 'localhost', 'port': 3306}})
def test_trees_to_dot(): (X, Y) = datasets.make_classification(n_classes=2, n_samples=10, random_state=1) model = RandomForestClassifier(n_estimators=3, max_depth=5, random_state=1) model.fit(X, Y) trees = emlearn.convert(model) dot = trees.to_dot(name='ffoo') with open('tmp/trees.dot', 'w') as ...
def test_websocket(dash_duo, server): app = DashProxy(blueprint=ws_example_bp(), prevent_initial_callbacks=True) dash_duo.start_server(app) time.sleep(0.01) assert (dash_duo.find_element('#msg').text == '') name = 'x' dash_duo.find_element('#input').send_keys(name) dash_duo.wait_for_text_to_...
class stackoverflow_question__test_case(unittest.TestCase): def test_stackoverflow_question_(self): from benedict import benedict as bdict data_source = '\nRecordID,kingdom,phylum,class,order,family,genus,species\n1,Animalia,Chordata,Mammalia,Primates,Hominidae,Homo,Homo sapiens\n2,Animalia,Chordata...
('rocm.groupnorm.gen_profiler') def groupnorm_gen_profiler(func_attrs: Dict[(str, Any)], workdir: str, indent: str=' ', use_swish: bool=False) -> str: shapes = func_attrs['inputs'][0]._attrs['shape'] for dim_idx in (1, 2, 3): assert isinstance(shapes[dim_idx], IntImm), f'groupnorm requires reduction di...
class TestAllTypesFromS3MockYAMLMissingS3(): def test_missing_s3_raise(self, monkeypatch, s3): with monkeypatch.context() as m: (aws_session, s3_client) = s3 mock_s3_bucket = 'spock-test' mock_s3_object = 'fake/test/bucket/pytest.load.yaml' s3_client.create_bu...
def test_wfo_compare_butadiene_cc2(): in_path = (THIS_DIR / 'butadiene_cc2') geom = geom_from_xyz_file((in_path / 'buta.xyz')) turbo = Turbomole(in_path, track=True, wfo_basis='def2-svp') geom.set_calculator(turbo) opt_kwargs = {'max_cycles': 1, 'dump': True} opt = SteepestDescent(geom, **opt_kw...
class CustomStringField(marshmallow.fields.String): def _deserialize(self, value: object, attr: Optional[str], data: Optional[Mapping[(str, object)]], **kwargs: Dict[(str, object)]) -> str: if isinstance(value, int): value = str(value) return super()._deserialize(value, attr, data, **kwa...
def test_text_store__write_version_incompatible(tmp_path) -> None: wallet_path = os.path.join(tmp_path, 'database') store = TextStore(wallet_path) try: store.put('seed_version', (TextStore.FINAL_SEED_VERSION + 1)) with pytest.raises(IncompatibleWalletError): store.write() fin...
def debug_flag(): logging.basicConfig(format=consts.LOGGING_FORMAT) parser = argparse.ArgumentParser(description=debug_flag.__doc__) add_debug(parser) (args, _extra_args) = parser.parse_known_args() (package, *_) = __package__.split('.') logging.getLogger(package).setLevel(args.debug)
def test_stdout_report(monkeypatch): monkeypatch.setenv('MYTHX_API_KEY', 'foo') submission = SubmissionPipeline({'test': {'sourcePath': 'contracts/SafeMath.sol', 'contractName': 'SafeMath'}}) submission.reports = {'contracts/SafeMath.sol': DetectedIssuesResponse.from_dict(TEST_REPORT)} submission.genera...
class OptionYaxisTitleStyle(Options): def color(self): return self._config_get('#666666') def color(self, text: str): self._config(text, js_type=False) def fontSize(self): return self._config_get('0.8em') def fontSize(self, num: float): self._config(num, js_type=False)
class BaseTenantForm(CSRFBaseForm): name = StringField('Name', validators=[validators.InputRequired()]) registration_allowed = BooleanField('Registration allowed', default=True) logo_url = URLField('Logo URL', validators=[validators.Optional(), validators.URL(require_tld=False)], filters=[empty_string_to_no...
def matmul_tile(gemmini): gemmini = divide_loop(gemmini, 'j', 4, ['jo', 'ji'], perfect=True) gemmini = divide_loop(gemmini, 'i', 8, ['io', 'i'], perfect=True) gemmini = divide_loop(gemmini, 'io', 2, ['ioo', 'io'], perfect=True) gemmini = old_reorder(gemmini, 'i jo') gemmini = old_reorder(gemmini, 'i...
def decode_i2c(frames): results = [] x_scale = frames[0].sx x_trans = frames[0].tx scl = frames[0].to_ttl() sda = frames[1].to_ttl() scl_diff = (scl[1:] - scl[:(- 1)]) sda_diff = (sda[1:] - sda[:(- 1)]) edges = [i for i in range(len(sda_diff)) if (sda_diff[i] and scl[i] and (not scl_diff...
class TargetingGeoLocationElectoralDistrict(AbstractObject): def __init__(self, api=None): super(TargetingGeoLocationElectoralDistrict, self).__init__() self._isTargetingGeoLocationElectoralDistrict = True self._api = api class Field(AbstractObject.Field): country = 'country' ...
def extractEarthviewloungeWordpressCom(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...
def test_get_complete_object(backend_db, common_db): (fw, parent_fo, child_fo) = create_fw_with_parent_and_child() fw.processed_analysis['test_plugin'] = generate_analysis_entry(summary=['entry0']) parent_fo.processed_analysis['test_plugin'] = generate_analysis_entry(summary=['entry1', 'entry2']) child_...
class InlineQueryResultArticle(InlineQueryResultBase): def __init__(self, id, title, input_message_content, reply_markup=None, url=None, hide_url=None, description=None, thumbnail_url=None, thumbnail_width=None, thumbnail_height=None): super().__init__('article', id, title=title, input_message_content=input...
class RCareWorld(RCareWorldBaseEnv): def __init__(self, executable_file: str=None, scene_file: str=None, custom_channels: list=[], assets: list=[], **kwargs): super().__init__(executable_file=executable_file, scene_file=scene_file, custom_channels=custom_channels, assets=assets, **kwargs) self.robot...
class ProgressReporting(): def __init__(self, process_name: str) -> None: self._process_name = process_name self._old_proctitle = '' self.reset() def _setproctitle(self, proctitle: str='') -> None: if proctitle: new_proctitle = '{} [{}]'.format(self._process_name, pro...
(x_input=INTEGER_ST) (deadline=DEADLINE, max_examples=5) def test_eager_workflow_with_dynamic_exception(x_input: int): async def eager_wf(x: int) -> typing.List[int]: return (await dynamic_wf(x=x)) with pytest.raises(EagerException, match='Eager workflows currently do not work with dynamic workflows'): ...
def test_order_availability_normalize_int(): decorators = [availability(C2), normalize('step', type=int, multiple=True), normalize('param', type=str, multiple=True), normalize('level', type=int, multiple=False)] g = level_param_step_no_default for order in itertools.permutations(decorators): print(o...
def maskView(viewOrLayer, color, alpha): unmaskView(viewOrLayer) window = fb.evaluateExpression('(UIWindow *)[[UIApplication sharedApplication] keyWindow]') origin = convertPoint(0, 0, viewOrLayer, window) size = fb.evaluateExpressionValue(('(CGSize)((CGRect)[(id)%s frame]).size' % viewOrLayer)) rec...
('/<int:key>/', methods=['GET', 'PUT', 'DELETE']) def notes_detail(key): if (request.method == 'PUT'): note = str(request.data.get('text', '')) notes[key] = note return note_repr(key) elif (request.method == 'DELETE'): notes.pop(key, None) return ('', status.HTTP_204_NO_C...
_cache(maxsize=1024) def parse_packet_in_pkt(data, max_len, eth_pkt=None, vlan_pkt=None): pkt = None eth_type = None vlan_vid = None if max_len: data = data[:max_len] try: if (vlan_pkt is None): if (eth_pkt is None): pkt = packet.Packet(data[:ETH_HEADER_SI...
def test_import_objects_expectedValuesFromStandardDataSet(testdata_ldapsearchbof_beacon_257_objects): adds = ADDS() adds.import_objects(testdata_ldapsearchbof_beacon_257_objects) assert (len(adds.SID_MAP) == 68) assert (len(adds.DN_MAP) == 68) assert (len(adds.DOMAIN_MAP) == 1) assert (len(adds....
def extract_instances(data: List[List[Tuple[(str, str)]]], label_map, feature_map, training=False): instances = [] for sentence in data: for i in range(len(sentence)): c = sentence[i] p = (sentence[(i - 1)] if ((i - 1) >= 0) else None) n = (sentence[(i + 1)] if ((i + ...
class MockStrategyDestroyNotSupported(Strategy, Generic[models.UP]): async def read_token(self, token: Optional[str], user_manager: BaseUserManager[(models.UP, models.ID)]) -> Optional[models.UP]: return None async def write_token(self, user: models.UP) -> str: return 'TOKEN' async def destr...
.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_region_start_end_pca1_colormap_bigwig(): outfile = NamedTemporaryFile(suffix='.png', prefix='hicexplorer_test', d...
def html_meta_to_nodes(data: dict[(str, Any)], document: nodes.document, line: int, reporter: Reporter) -> list[(nodes.pending | nodes.system_message)]: if (not data): return [] try: meta_cls = nodes.meta except AttributeError: from docutils.parsers.rst.directives.html import MetaBod...
class JMSCheckin(AnswerBotCheckin): ocr = '' idioms = None lock = asyncio.Lock() name = '' bot_username = 'jmsembybot' max_retries = 2 async def start(self): async with self.lock: if (self.idioms is None): file = (await get_data(self.basedir, '.txt', proxy...
class InvocationsFetcher(FetcherClient): def get_test_last_invocation(self, macro_args: Optional[dict]=None) -> DbtInvocationSchema: invocation_response = self.dbt_runner.run_operation(macro_name='elementary_cli.get_test_last_invocation', macro_args=macro_args) invocation = (json.loads(invocation_re...
class TestPCAttestationService(unittest.TestCase): ('onedocker.gateway.repository_service.RepositoryServiceGateway') def setUp(self, MockRepositoryServiceGateway) -> None: self.pc_attestation_svc = PCAttestationService() ('onedocker.gateway.repository_service.RepositoryServiceGateway.get_measurement...
def get_all_board_names() -> List[str]: local_cached = local_cache.get('all_board_names') if local_cached: return local_cached all_board_names_cached = cache.get(cache_key('all_board_names')) if (all_board_names_cached is not None): res = all_board_names_cached else: with ses...
class Hotel(AbstractCrudObject): def __init__(self, fbid=None, parent_id=None, api=None): self._isHotel = True super(Hotel, self).__init__(fbid, parent_id, api) class Field(AbstractObject.Field): address = 'address' applinks = 'applinks' brand = 'brand' category =...
class Select(Options): def activate(self): self.info = False self.items = 'row' return self def info(self): return self._config_get() def info(self, val): self._config(val) def blurable(self): return self._config_get() def blurable(self, val): ...
def get_formatted_value_for_table_field(items, df): child_meta = frappe.get_meta(df.options) table_head = '' table_row = '' html = '' create_head = True for item in items: table_row += '<tr>' for cdf in child_meta.fields: if cdf.in_list_view: if create...
def test_build_post_request(server): url = server.url.copy_with(path='/echo_headers') headers = {'Custom-header': 'value'} with as client: request = client.build_request('POST', url) request.headers.update(headers) response = client.send(request) assert (response.status_code == ...
def test_mixed_vector_copy(): mesh = UnitIntervalMesh(2) V = FunctionSpace(mesh, 'CG', 1) W = (V * V) f = Function(W) f.assign(1) v = f.vector() assert np.allclose(v.array(), 1.0) copy = v.copy() assert isinstance(copy, Vector) assert np.allclose(copy.array(), 1.0) local = co...
class TypeInvitation(ModelSimple): allowed_values = {('value',): {'INVITATION': 'invitation'}} validations = {} additional_properties_type = None _nullable = False _property def openapi_types(): return {'value': (str,)} _property def discriminator(): return None attri...
.django_db def test_spending_by_award_recipient_zip_filter(client, monkeypatch, elasticsearch_award_index, test_data): setup_elasticsearch_test(monkeypatch, elasticsearch_award_index) resp = client.post('/api/v2/search/spending_by_award/', content_type='application/json', data=json.dumps({'fields': ['Place of P...
def construct_latest_index(session: Session) -> dict[(date, str)]: index = {} latest_index_page = session.get(LATEST_URL) soup = BeautifulSoup(latest_index_page.text, 'html.parser') for a in soup.find_all('a', href=True): if a['href'].startswith(DATA_DOC_PREFIX): dt = pd.to_datetime(...
def migrate_case(storage: StorageAccessor, path: Path) -> None: logger.info(f"Migrating case '{path.name}'") time_map = _load_timestamps((path / 'files/time-map')) state_map = _load_states((path / 'files/state-map')) parameter_files = [DataFile(x) for x in path.glob('Ensemble/mod_*/PARAMETER.data_0')] ...
class TestUpdateUserPassword(): (scope='function') def url_no_id(self) -> str: return (V1_URL_PREFIX + USERS) def test_update_different_user_password(self, api_client, db, url_no_id, user, application_user) -> None: OLD_PASSWORD = 'oldpassword' NEW_PASSWORD = 'newpassword' ap...
class PrimeField(): def __init__(self, modulus): assert (pow(2, modulus, modulus) == 2) self.modulus = modulus def add(self, x, y): return ((x + y) % self.modulus) def sub(self, x, y): return ((x - y) % self.modulus) def mul(self, x, y): return ((x * y) % self.mod...
def run(): sites = list(gen_sites()) print('\n`define N_DI {}\n\nmodule top(input wire [`N_DI-1:0] di);\n wire [`N_DI-1:0] di_buf;\n '.format(len(sites))) params = {} print('\n (* KEEP, DONT_TOUCH *)\n LUT6 dummy_lut();') for (idx, ((tile_name, site_name), isone)) in enumerate(zi...
class Max(DCCBase): name = ('3dsMax%s' % get_max_version()) extensions = ['.max'] def get_current_version(self): version = None full_path = MaxPlus.FileManager.GetFileNameAndPath() if (full_path != ''): version = self.get_version_from_full_path(full_path) return v...
class OptionPlotoptionsDependencywheelSonificationDefaultinstrumentoptionsMappingPan(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,...
class FileLoaderTest(ForsetiTestCase): def test_get_filetype_parser_works(self): self.assertIsNotNone(file_loader._get_filetype_parser('file.yaml', 'string')) self.assertIsNotNone(file_loader._get_filetype_parser('file.yaml', 'file')) self.assertIsNotNone(file_loader._get_filetype_parser('fi...
def basic_types(): global _basic_types if (_basic_types is None): _basic_types = [(type(None), NoneNode), (str, StringNode), (str, StringNode), (bool, BoolNode), (int, IntNode), (float, FloatNode), (complex, ComplexNode), (tuple, TupleNode), (list, ListNode), (set, SetNode), (dict, DictNode), (FunctionT...
def extractDarkness7913WordpressCom(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_ty...
def test_not_transonified(): path_for_test = (Path(__file__).parent.parent / '_transonic_testing/for_test_init.py') path_output = (path_for_test.parent / f'__{backend_default}__') if (path_output.exists() and (mpi.rank == 0)): rmtree(path_output) mpi.barrier() from _transonic_testing import ...
class MDRenderer(): __output__ = 'md' def __init__(self, parser: Any=None): def render(self, tokens: Sequence[Token], options: Mapping[(str, Any)], env: MutableMapping, *, finalize: bool=True) -> str: tree = RenderTreeNode(tokens) return self.render_tree(tree, options, env, finalize=finalize...
def extractBooksnailTumblrCom(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...
def upload_presentations(): table = Client('hscic').get_table('presentation') presentations = [('0703021Q0AAAAAA', 'Desogestrel_Tab 75mcg'), ('0703021Q0BBAAAA', 'Cerazette_Tab 75mcg'), ('AAAAAA', 'Etynodiol Diacet_Tab 500mcg'), ('0407010Q0AAAAAA', 'Co-Proxamol_Tab 32.5mg/325mg'), ('0904010AUBBAAAA', "Mrs Crimbl...
class SendMixin(object): def send(self, qb=None, send_to=None): if (not qb): qb = QuickBooks() end_point = '{0}/{1}/send'.format(self.qbo_object_name.lower(), self.Id) if send_to: send_to = quote(send_to, safe='') end_point = '{0}?sendTo={1}'.format(end_po...
def interpret_path(path, pwd='.'): result = path.strip().replace('$(dirname)', pwd) pkg_pattern = re.compile('\\$\\(find (.*?)\\)/|pkg:\\/\\/(.*?)/|package:\\/\\/(.*?)/') for groups in pkg_pattern.finditer(path): for index in range(groups.lastindex): pkg_name = groups.groups()[index] ...
class UNet(torch.nn.Module): def __init__(self): super().__init__() self.layer1 = ConvBlock(1, 64) self.layer2 = ConvBlock(64, 128) self.layer3 = ConvBlock(128, 256) self.layer4 = ConvBlock(256, 512) self.layer5 = ConvBlock((256 + 512), 256) self.layer6 = Conv...
_event class PlanResponded(ThreadEvent): plan = attr.ib(type='_models.PlanData') take_part = attr.ib(type=bool) at = attr.ib(type=datetime.datetime) def _parse(cls, session, data): (author, thread, at) = cls._parse_metadata(session, data) plan = _models.PlanData._from_pull(session, data[...
_latency_scorer('LAAL') class LAALScorer(ALScorer): def compute(self, ins: Instance): (delays, source_length, target_length) = self.get_delays_lengths(ins) if (delays[0] > source_length): return delays[0] LAAL = 0 gamma = (max(len(delays), target_length) / source_length) ...
def get_addr_for_intercepts(intercepts, firmware): funct_2_addr = get_functions_and_addresses(firmware) mapped_intercepts = [] for inter in intercepts: funct = inter['function'] if (funct in funct_2_addr): inter['addr'] = funct_2_addr[funct] mapped_intercepts.append(i...
class NetCDFField(Field): def __init__(self, owner, ds, variable, slices, non_dim_coords): data_array = ds[variable] (self.north, self.west, self.south, self.east) = ds.bbox(variable) self.owner = owner self.variable = variable self.slices = slices self.non_dim_coords...
class TestWait(object): ('copr.v3.proxies.build.BuildProxy.get') def test_wait(self, mock_get): build = MunchMock(id=1, state='importing') mock_get.return_value = MunchMock(id=1, state='succeeded') assert wait(build) mock_get.return_value = MunchMock(id=1, state='unknown') ...
class BatchItemResponseTests(unittest.TestCase): def test_set_object(self): obj = FaultError() batch_item = BatchItemResponse() batch_item.set_object(obj) self.assertEqual(batch_item._original_object, obj) self.assertEqual(batch_item.Error, obj) def test_get_object(self):...
.django_db def test_agency_failure(client): resp = client.post('/api/v2/search/spending_over_time/', content_type='application/json', data=json.dumps({})) assert (resp.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY) resp = client.post('/api/v2/spending/', content_type='application/json', data=json.dump...
class OptionSeriesSunburstSonificationDefaultspeechoptionsMappingVolume(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 Console2(Boxes): ui_group = 'Box' description = "\nThis box is designed as a housing for electronic projects. It has hatches that can be re-opened with simple tools. It intentionally cannot be opened with bare hands - if build with thin enough material.\n\n#### Caution\nThere is a chance that the latches ...
def sft_set(): with open('dataset_hhrlhf_train.json', 'w') as fp: AnthropicHHRLHFDataset.save('train', fp) with open('dataset_hhrlhf_test.json', 'w') as fp: AnthropicHHRLHFDataset.save('test', fp) with open('dataset_rmstatic_train.json', 'w') as fp: DahoasRMStaticDataset.save('train'...
def test_dev_deployment_map_clear_on_remove(testproject, BrownieTester, config, accounts): config.settings['dev_deployment_artifacts'] = True BrownieTester.deploy(True, {'from': accounts[0]}) BrownieTester.remove(BrownieTester[(- 1)]) assert (len(get_dev_artifacts(testproject)) == 0) content = get_m...
class TradingMethod(): def __init__(self, symbols, freq, lookback, strategy, variables, weight_btc=None, weight=None, weight_unit=None, filters=None, name='', execution_price='close'): self.symbols = symbols self.freq = freq self.lookback = lookback self.strategy = strategy s...
def test_migrating_simple_asset_1(migration_test_data): data = migration_test_data migration_recipe = {data['asset2'].id: {'new_name': 'Asset 2A', 'new_code': 'asset2a', 'new_parent_id': data['assets_task2'].id}, data['asset2_model'].id: {'new_parent_id': data['asset2'].id, 'takes': {'Main': {'new_name': 'Main'...
class PHYSink(Module): def __init__(self): self.sink = stream.Endpoint(phy_description(32)) self.dword = PHYDword() def receive(self): self.dword.done = 0 while (self.dword.done == 0): (yield) def generator(self): while True: self.dword.done = ...
class StartUpChecker(): def __init__(self, app): A = QObject() serverName = 'jamtoolsserver' self.ssocket = QLocalSocket(A) self.ssocket.connectToServer(serverName) if self.ssocket.waitForConnected(500): print('connected server') self.ssocket.write(str...
def test_custom_virtual_machines(): if (not is_supported_pyevm_version_available()): pytest.skip('PyEVM is not available') backend = PyEVMBackend(vm_configuration=((0, FrontierVM), (3, ParisVM))) VM_at_2 = backend.chain.get_vm_class_for_block_number(2) VM_at_3 = backend.chain.get_vm_class_for_bl...
def test_proj_monitors(): dipole_center = [0, 0, 0] domain_size = (5 * WAVELENGTH) buffer_mon = (1 * WAVELENGTH) grid_spec = td.GridSpec.auto(min_steps_per_wvl=20) boundary_spec = td.BoundarySpec.all_sides(boundary=td.PML()) sim_size = (domain_size, domain_size, domain_size) fwidth = (F0 / 1...
def get_detected_external_identifier_type_and_value_for_text(text: str) -> Tuple[(Optional[str], str)]: value = re.sub('\\s', '', text) m = re.search(DOI_PATTERN, value) if m: value = m.group(1) return (SemanticExternalIdentifierTypes.DOI, value) m = re.search(PMCID_PATTERN, value) i...
class _InteractiveConsole(code.InteractiveInterpreter): def __init__(self, globals, locals): code.InteractiveInterpreter.__init__(self, locals) self.globals = dict(globals) self.globals['dump'] = dump self.globals['help'] = helper self.globals['__loader__'] = self.loader = _C...
class MiningHeader(rlp.Serializable, MiningHeaderAPI): fields = [('parent_hash', hash32), ('uncles_hash', hash32), ('coinbase', address), ('state_root', trie_root), ('transaction_root', trie_root), ('receipt_root', trie_root), ('bloom', uint256), ('difficulty', big_endian_int), ('block_number', big_endian_int), ('g...
def _parse_commandline(): parser = argparse.ArgumentParser() parser.add_argument('wallet_address', help='main wallet address') parser.add_argument('task_wallet_address', help='wallet address that will perform transactions') parser.add_argument('top_up_amount', type=int, nargs='?', default=, help='top-up...
class Date(fields.Str): def _validate(self, value): value = value.strip() super()._validate(value) try: datetime.datetime.strptime(value, '%Y-%m-%d') except (TypeError, ValueError): try: datetime.datetime.strptime(value, '%m/%d/%Y') ...
.parametrize('input_features', [None, variables_arr, np.array(variables_arr), variables_str, np.array(variables_str), variables_user]) def test_with_pipeline_and_array(df_vartypes, input_features): pipe = Pipeline([('transformer', MockTransformer())]) pipe.fit(df_vartypes.to_numpy()) if (input_features is N...
class ContainerRunningChecker(BaseHealthChecker): def check(self, model_instance: dm.ModelInstance) -> Status: reasoning_output = self.cloud_client.is_instance_running(model_instance) status = Status(model_instance, reasoning_output.output, reason=reasoning_output.reason) return status
class ZipkinDataBuilder(): def build_span(name, trace_id, span_id, parent_id, annotations, bannotations): return ttypes.Span(name=name, trace_id=trace_id, id=span_id, parent_id=parent_id, annotations=annotations, binary_annotations=bannotations) def build_annotation(value, endpoint=None): if isi...
class table_features_failed_error_msg(error_msg): version = 5 type = 1 err_type = 13 def __init__(self, xid=None, code=None, data=None): if (xid != None): self.xid = xid else: self.xid = None if (code != None): self.code = code else: ...
def main(): N = 10 L = 30 heads = 8 H = 64 q = torch.rand(size=(N, L, H)) k = torch.rand(size=(N, L, H)) v = torch.rand(size=(N, L, H)) q = q.view(N, L, heads, (H // heads)) k = k.view(N, L, heads, (H // heads)) v = v.view(N, L, heads, (H // heads)) q = q.transpose(1, 2) ...
_component_ids.register(AgentConfig) def _(arg: AgentConfig, replacements: Dict[(ComponentType, Dict[(PublicId, PublicId)])]) -> None: _replace_component_id(arg, {ComponentType.PROTOCOL, ComponentType.CONNECTION, ComponentType.CONTRACT, ComponentType.SKILL}, replacements) protocol_replacements = replacements.ge...
def upgrade(): op.execute('alter type connectiontype rename to connectiontype_old') op.execute("create type connectiontype as enum('postgres', 'mongodb', 'mysql', ' 'snowflake', 'redshift', 'mssql', 'mariadb', 'bigquery', 'saas', 'manual', 'email', 'manual_webhook', 'timescale', 'fides', 'sovrn')") op.execu...
class Houdini(DCCBase): name = 'Houdini' extensions = {0: '.hiplc', hou.licenseCategoryType.Commercial: '.hip', hou.licenseCategoryType.Apprentice: '.hipnc', hou.licenseCategoryType.Indie: '.hiplc'} def __init__(self, name='', version=None): super(Houdini, self).__init__(name, version) self....
class OptionPlotoptionsHistogramSonificationTracksMappingTremolo(Options): def depth(self) -> 'OptionPlotoptionsHistogramSonificationTracksMappingTremoloDepth': return self._config_sub_data('depth', OptionPlotoptionsHistogramSonificationTracksMappingTremoloDepth) def speed(self) -> 'OptionPlotoptionsHis...