code
stringlengths
281
23.7M
def get_register_erc1155() -> Contract: directory = Path(ROOT_DIR, 'packages', 'fetchai', 'contracts', 'erc1155') configuration = load_component_configuration(ComponentType.CONTRACT, directory) configuration._directory = directory configuration = cast(ContractConfig, configuration) if (str(configura...
class AdAssetFeedSpecLinkURL(AbstractObject): def __init__(self, api=None): super(AdAssetFeedSpecLinkURL, self).__init__() self._isAdAssetFeedSpecLinkURL = True self._api = api class Field(AbstractObject.Field): adlabels = 'adlabels' carousel_see_more_url = 'carousel_see_...
def init_async_web3(provider: 'AsyncBaseProvider'=cast('AsyncBaseProvider', default), middlewares: Optional[Sequence[Tuple[('AsyncMiddleware', str)]]]=()) -> 'AsyncWeb3': from web3 import AsyncWeb3 as AsyncWeb3Main from web3.eth import AsyncEth as AsyncEthMain middlewares = list(middlewares) for (i, (mi...
def test_ignore_on_order_event_update(client, db, user, jwt): order_id = create_order(db, user) order = Order.query.get(order_id) order_event = order.event event = EventFactoryBasic() db.session.commit() data = json.dumps({'data': {'type': 'order', 'id': order_id, 'relationships': {'event': {'da...
class u5Ex(object): def __init__(self): pass def uOfX(self, x): return ((x[0] ** 2) + (x[1] ** 2)) def uOfXT(self, X, T): return self.uOfX(X) def duOfX(self, X): du = (2.0 * numpy.reshape(X[0:2], (2,))) return du def duOfXT(self, X, T): return self.duO...
def test_ge_runtimebatchrequest_sqlite_config(): task_object = GreatExpectationsTask(name='test4', datasource_name='sqlite_data', inputs=kwtypes(dataset=str), expectation_suite_name='sqlite.movies', data_connector_name='sqlite_data_connector', data_asset_name='sqlite_data', task_config=BatchRequestConfig(batch_iden...
def extractChenguangsorchardBlogspotCom(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, t...
class Solution(): def findDuplicate(self, nums: List[int]) -> int: if (len(nums) < 2): return (- 1) slow = nums[0] fast = nums[nums[0]] while (slow != fast): slow = nums[slow] fast = nums[nums[fast]] fast = 0 while (fast != slow): ...
def filter_firewall_internet_service_ipbl_reason_data(json): option_list = ['id', 'name'] json = remove_invalid_fields(json) dictionary = {} for attribute in option_list: if ((attribute in json) and (json[attribute] is not None)): dictionary[attribute] = json[attribute] return di...
class InlineResponse2002(ModelNormal): allowed_values = {} validations = {} _property def additional_properties_type(): return (bool, date, datetime, dict, float, int, list, str, none_type) _nullable = False _property def openapi_types(): return {'expires_at': (str,)} _pr...
def test_imperative_tuples(): def t1() -> (int, str): return (3, 'three') def t3(a: int, b: str) -> typing.Tuple[(int, str)]: return ((a + 2), ('world' + b)) wb = ImperativeWorkflow(name='my.workflow.a') t1_node = wb.add_entity(t1) t3_node = wb.add_entity(t3, a=t1_node.outputs['o0'],...
class ProgramSelect(InteractiveEntityBase, SelectEntity): def unique_id(self) -> str: return f'{self.haId}_programs' def translation_key(self) -> str: return 'programs' def name_ext(self) -> str: return 'Programs' def icon(self) -> str: if (self._appliance.type in DEVICE_...
def downgrade(): bind: Connection = op.get_bind() logger.info('Downgrading data use on privacy declaration') update_privacy_declaration_data_uses(bind, data_use_downgrades) logger.info('Downgrading ctl policy rule data uses') update_ctl_policy_data_uses(bind, data_use_downgrades)
def main(): async def run(): result = (await asyncio.gather(*[pool.run_async(g, i) for i in range(REPS)])) print(result) async def map_async(): async for result in pool.map_async(g, range(REPS), chunksize=1, timeout=None): pass print(result) pool = Pool() if 1...
def make_python_patch(): pywin32_filename = ('pywin32-%s.win-amd64-py%s.exe' % (pywin32_version, major_minor_version)) filename = ('python-%s-amd64.zip' % version) out_filename = ('python-%s-%s-amd64+pywin32.zip' % (version, revision)) if (not os.path.exists(pywin32_filename)): url = (pywin32_ba...
class SolidRunDefinition(): def __init__(self, run_definition_file): self.file = run_definition_file self.version = None self.userId = None self.runType = None self.isMultiplexing = None self.runName = None self.runDesc = None self.mask = None ...
class OptionPlotoptionsScatter3dTooltip(Options): def clusterFormat(self): return self._config_get('Clustered points: {point.clusterPointsAmount}') def clusterFormat(self, text: str): self._config(text, js_type=False) def dateTimeLabelFormats(self) -> 'OptionPlotoptionsScatter3dTooltipDateti...
class PcapWriter(): def __init__(self, filename, port_cp=4729, port_up=47290): self.port_cp = port_cp self.port_up = port_up self.ip_id = 0 self.base_address = self.pcap_file = open(filename, 'wb') self.eth_hdr = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x08...
class TestAutoValue(TestCase): def test_bare(self): class BareEnum(Enum): _order_ = 'ONE TWO THREE' ONE = auto() TWO = auto() THREE = auto() self.assertEqual(BareEnum.THREE.value, 3) class BareIntEnum(IntEnum): _order_ = 'ONE TWO TH...
class CookieTokenAuthTests(mixins.CookieTokenAuthMixin, CookieTestCase): query = '\n mutation TokenAuth($username: String!, $password: String!) {\n tokenAuth(username: $username, password: $password) {\n token\n payload\n refreshToken\n refreshExpiresIn\n }\n }' refre...
class TestReportingDates(ApiBaseTest): def test_reporting_dates_filters(self): factories.ReportTypeFactory(report_type='YE', report_type_full='Year End') factories.ReportDateFactory(due_date=datetime.datetime(2014, 1, 2)) factories.ReportDateFactory(report_year=2015) factories.Report...
_oriented class ParticleSystem(): def __init__(self, config: SimConfig, GGUI=False): self.cfg = config self.GGUI = GGUI self.domain_start = np.array([0.0, 0.0, 0.0]) self.domain_start = np.array(self.cfg.get_cfg('domainStart')) self.domain_end = np.array([1.0, 1.0, 1.0]) ...
def _secho_task_execution_status(status, nl=True): red_phases = {_core_execution_models.TaskExecutionPhase.ABORTED, _core_execution_models.TaskExecutionPhase.FAILED} yellow_phases = {_core_execution_models.TaskExecutionPhase.QUEUED, _core_execution_models.TaskExecutionPhase.UNDEFINED, _core_execution_models.Tas...
_cache def display_pickle_warning(python_type: str): logger.warning(f'Unsupported Type {python_type} found, Flyte will default to use PickleFile as the transport. Pickle can only be used to send objects between the exact same version of Python, and we strongly recommend to use python type that flyte support.')
class CustomAudienceTestCase(unittest.TestCase): def test_format_params(self): payload = customaudience.CustomAudience.format_params(customaudience.CustomAudience.Schema.email_hash, [' test ', 'test', '..test..']) test_hash = '9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08' ...
def _re_wrap_length(cmp, l): if (cmp == '=='): return '(?:[^ ]{{{}}}+)'.format(l) elif (cmp == '!='): return '(?:[^ ]{{1,{}}}+|[^ ]{{{},}}+)'.format((l - 1), (l + 1)) elif (cmp == '>='): return '(?:[^ ]{{{},}}+)'.format(l) elif (cmp == '<='): return '(?:[^ ]{{1,{}}}+)'.fo...
class DataTypeProxyModel(QSortFilterProxyModel): def __init__(self, parent, model): QSortFilterProxyModel.__init__(self, parent) self.__show_summary_keys = True self.__show_block_keys = True self.__show_gen_kw_keys = True self.__show_gen_data_keys = True self.__show_c...
class OptionPlotoptionsParetoAccessibility(Options): def description(self): return self._config_get(None) def description(self, text: str): self._config(text, js_type=False) def descriptionFormat(self): return self._config_get(None) def descriptionFormat(self, text: str): ...
class op(bpy.types.Operator): bl_idname = 'uv.textools_island_align_world' bl_label = 'Align World' bl_description = 'Align selected UV islands or faces to world / gravity directions' bl_options = {'REGISTER', 'UNDO'} bool_face: bpy.props.BoolProperty(name='Per Face', default=False, description='Pro...
class OptionPlotoptionsFunnel3dSonificationDefaultinstrumentoptionsMappingHighpassFrequency(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 mapT...
class TCFVendorLegitimateInterestsRecord(UserSpecificConsentDetails, CommonVendorFields): purpose_legitimate_interests: List[EmbeddedPurpose] = [] _validator def add_default_preference(cls, values: Dict[(str, Any)]) -> Dict[(str, Any)]: values['default_preference'] = UserConsentPreference.opt_in ...
class GraphDiffSummary(FidesSchema): prev_collection_count: int = 0 curr_collection_count: int = 0 added_collection_count: int = 0 removed_collection_count: int = 0 added_edge_count: int = 0 removed_edge_count: int = 0 already_processed_access_collection_count: int = 0 already_processed_...
class TransformOddAlignmentCase(unittest.TestCase): def setUpClass(cls): torch.manual_seed(0) def _create_permute_bmm_graph(self, A_shape, B_shape, bmm_type, const_A=None, const_B=None): OP = getattr(ops, bmm_type, None) assert (OP is not None) A = (const_A if const_A else Tensor...
.parametrize('condition_args,expected', [({}, ''), ({'gte': 10}, 'gte=10'), ({'gte': 10.5}, 'gte=10.5'), ({'gt': 10}, 'gt=10'), ({'gt': 10, 'lt': 40}, 'gt=10 and lt=40'), ({'eq': 8}, 'eq=8'), ({'not_eq': 10}, 'not_eq=10'), ({'lte': 10}, 'lte=10'), ({'lt': 10}, 'lt=10'), ({'is_in': [10, 20, 30]}, 'is_in=[10, 20, 30]'), ...
def cidr_validator(value, return_ip_interface=False): try: if ('/' in value): (ipaddr, netmask) = value.split('/') netmask = int(netmask) else: (ipaddr, netmask) = (value, 32) if ((not validators.ipv4_re.match(ipaddr)) or (not (1 <= netmask <= 32))): ...
def show_results(model_name: str, dir_name_output: str, file_sources: List): sources = get_sources(((out_path / Path(model_name)) / dir_name_output), file_sources) tab_sources = st.tabs([f'**{label_sources.get(k)}**' for k in sources.keys()]) for (i, (file, pathname)) in enumerate(sources.items()): ...
class DBApi(): def __init__(self, database='') -> None: if (not database): database = current_app.config['DATABASE'] port = int(current_app.config['PORT']) self.db = pymysql.connect(host=current_app.config['HOST'], user=current_app.config['USERNAME'], password=current_app.config[...
def handle_done_response_ocr_async(result, client, job_id) -> AsyncResponseType[OcrAsyncDataClass]: gcs_destination_uri = result['response']['responses'][0]['outputConfig']['gcsDestination']['uri'] match = re.match('gs://([^/]+)/(.+)', gcs_destination_uri) bucket_name = match.group(1) prefix = match.gro...
(scope='function') def unlinked_dataset(db: Session): ds = Dataset(fides_key='unlinked_dataset', organization_fides_key='default_organization', name='Unlinked Dataset', description='Example dataset created in test fixtures', collections=[{'name': 'subscriptions', 'fields': [{'name': 'id', 'data_categories': ['syste...
def visualize2(facts): graph = Digraph() graph.attr('graph', fontname='mono') graph.attr('node', fontname='mono') stmt_block_map = {f.id_stmt: f.id_block for f in facts if isinstance(f, BlockStmtFact)} block_graph_map = {f.id_block: Digraph() for f in facts if isinstance(f, BlockFact)} for fact ...
def reduce_max(X, lengths, *, threads_per_block=128, num_blocks=128): _is_float_array(X) B = len(lengths) T = X.shape[0] O = X.shape[1] _check_lengths(lengths, T, min_length=1) out_shape = (B, O) maxes = _alloc(out_shape, dtype=X.dtype, zeros=False) which = _alloc(out_shape, dtype='i', z...
def _plotCrossCaseStatistics(axes: 'Axes', plot_config: 'PlotConfig', data: CcsData, index: int): axes.set_xlabel(plot_config.xLabel()) axes.set_ylabel(plot_config.yLabel()) style = plot_config.getStatisticsStyle('mean') if style.isVisible(): axes.plot([index], data['mean'][index], alpha=style.a...
class BackendResult(): def __init__(self, bres): self.name = 'raw' self.request = None self.response = bres if isinstance(bres, dict): self.name = cast(str, bres.get('backend')) self.request = (BackendRequest(bres['request']) if ('request' in bres) else None) ...
class OptionPlotoptionsTimelineDragdropGuideboxDefault(Options): def className(self): return self._config_get('highcharts-drag-box-default') def className(self, text: str): self._config(text, js_type=False) def color(self): return self._config_get('rgba(0, 0, 0, 0.1)') def color(...
def main(page: ft.Page): data_1 = [ft.LineChartData(data_points=[ft.LineChartDataPoint(1, 1), ft.LineChartDataPoint(3, 1.5), ft.LineChartDataPoint(5, 1.4), ft.LineChartDataPoint(7, 3.4), ft.LineChartDataPoint(10, 2), ft.LineChartDataPoint(12, 2.2), ft.LineChartDataPoint(13, 1.8)], stroke_width=8, color=ft.colors.LI...
class OptionSeriesItemSonificationPointgrouping(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._config(...
def read(self, genre, method=None, command=None, _class=None): datas = b'' data_len = (- 1) k = 0 pre = 0 t = time.time() wait_time = 0.1 if (genre == ProtocolCode.GO_ZERO): wait_time = 120 if (method is not None): if (genre == 177): while True: ...
def normalize_severity_args(args): translate = dict(C='CRITICAL', H='HIGH', M='MEDIUM', L='LOW', O='OPTIMIZATION', I='INFO') if (args == 'all'): return translate.values() if (args == 'none'): return [] severities = args.split(',') severities = [s.strip().upper() for s in severities] ...
def batch_pictures(): cur_path = pathlib.Path(__file__) config_path = (cur_path.parent.parent / 'config.yaml') config = dm.Config.parse_file(config_path, content_type='yaml') ctx = zmq.Context() sock_sender = ctx.socket(zmq.PUSH) sock_sender.connect(config.zmq_input_address) sock_receiver = ...
class BenchSoC(SoCCore): def __init__(self, uart='crossover', sys_clk_freq=int(.0), with_bist=False, with_analyzer=False): platform = xilinx_kcu105.Platform() SoCCore.__init__(self, platform, clk_freq=sys_clk_freq, ident='LiteDRAM bench on KCU105', integrated_rom_size=65536, integrated_rom_mode='rw'...
class OptionSeriesWaterfallSonificationDefaultinstrumentoptionsMappingFrequency(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...
.parametrize('tuple_type,python_value,solidity_abi_encoded,_', CORRECT_TUPLE_ENCODINGS) def test_abi_encode_for_multiple_types_as_list(tuple_type, python_value, solidity_abi_encoded, _): abi_type = parse(tuple_type) if (abi_type.arrlist is not None): pytest.skip('ABI coding functions do not support arra...
def dumpdexInit(packageName): path = (((('/data/data/' + packageName) + '/files/') + '/dump_dex_') + packageName) res = '' res += (adbshellCmd(('mkdir -p ' + path)) + '\n') res += (adbshellCmd(((('chmod 0777 ' + '/data/data/') + packageName) + '/files/')) + '\n') res += (adbshellCmd(('chmod 0777 ' +...
def test_chroma_db_collection_reset(): db1 = ChromaDB(config=ChromaDbConfig(allow_reset=True, dir='test-db')) app1 = App(config=AppConfig(collect_metrics=False), db=db1) app1.set_collection_name('one_collection') db2 = ChromaDB(config=ChromaDbConfig(allow_reset=True, dir='test-db')) app2 = App(confi...
def extractThebrilliantjadeinaiWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [("Marielle Clarac's Engagement", "Marielle Clarac's Engagement", 'translated'), ('The ...
class Window(lg.Node): PLOT: LinePlot PLOT_2: LinePlot def run_plot(self) -> None: win = pg.GraphicsWindow() win.addItem(self.PLOT.build()) win.nextRow() win.addItem(self.PLOT_2.build()) QtGui.QApplication.instance().exec_() def cleanup(self) -> None: self...
class DistributedDrQV2Test(absltest.TestCase): def test_distributed_drq_v2_run(self): def environment_factory(seed, testing): del seed, testing environment = fakes.Environment(spec=specs.EnvironmentSpec(observations=specs.Array((84, 84, 3), dtype=np.uint8), actions=specs.BoundedArray...
class ImportJobList(ResourceList): def query(self, kwargs): query_ = self.session.query(ImportJob) query_ = query_.filter_by(user_id=current_user.id) return query_ decorators = (jwt_required,) schema = ImportJobSchema data_layer = {'session': db.session, 'model': ImportJob, 'meth...
def get_cuda_version_from_nvidia_smi(): try: output = subprocess.check_output(['nvidia-smi']).decode('utf-8') match = re.search('CUDA Version:\\s+(\\d+\\.\\d+)', output) if match: return match.group(1) else: return None except: return None
def sort_frame_processors(frame_processors: List[str]) -> list[str]: available_frame_processors = list_module_names('facefusion/processors/frame/modules') return sorted(available_frame_processors, key=(lambda frame_processor: (frame_processors.index(frame_processor) if (frame_processor in frame_processors) else...
class ConditionEncoder(Chain): def __init__(self, device: ((Device | str) | None)=None, dtype: (DType | None)=None) -> None: self.out_channels = (16, 32, 96, 256) super().__init__(Chain(Conv2d(in_channels=3, out_channels=self.out_channels[0], kernel_size=3, stride=1, padding=1, device=device, dtype=...
def int2c2e3d_33(ax, da, A, bx, db, B): result = numpy.zeros((10, 10), dtype=float) x0 = (ax + bx) x1 = (x0 ** (- 1.0)) x2 = ((- x1) * ((ax * A[0]) + (bx * B[0]))) x3 = (x2 + B[0]) x4 = (bx ** (- 1.0)) x5 = (((ax * bx) * x1) * ((((A[0] - B[0]) ** 2) + ((A[1] - B[1]) ** 2)) + ((A[2] - B[2]) *...
class ModelTester(ErsiliaBase): def __init__(self, model_id, config_json=None): ErsiliaBase.__init__(self, config_json=config_json, credentials_json=None) self.model_id = model_id self.model_size = 0 self.tmp_folder = tempfile.mkdtemp(prefix='ersilia-') self._info = self._rea...
.django_db(transaction=True) def test_threaded_data_loader(): field_map = {'treasury_account_identifier': 'ACCT_NUM', 'account_title': 'GWA_TAS_NAME'} loader = ThreadedDataLoader(model_class=TreasuryAppropriationAccount, field_map=field_map, collision_field='treasury_account_identifier', collision_behavior='upd...
class OptionSeriesAreasplineTooltip(Options): def clusterFormat(self): return self._config_get('Clustered points: {point.clusterPointsAmount}') def clusterFormat(self, text: str): self._config(text, js_type=False) def dateTimeLabelFormats(self) -> 'OptionSeriesAreasplineTooltipDatetimelabelf...
class Utils(BotPlugin): def echo(self, _, args): return args def whoami(self, msg, args): if args: frm = self.build_identifier(str(args).strip('"')) else: frm = msg.frm resp = '' if self.bot_config.GROUPCHAT_NICK_PREFIXED: resp += '\n\n...
class TestOFPVendorStatsReply(unittest.TestCase): class Datapath(object): ofproto = ofproto ofproto_parser = ofproto_v1_0_parser c = OFPVendorStatsReply(Datapath) def setUp(self): pass def tearDown(self): pass def test_init(self): pass def test_parser(self...
class AppEngineClient(object): def __init__(self, global_configs, **kwargs): (max_calls, quota_period) = api_helpers.get_ratelimiter_config(global_configs, API_NAME) cache_discovery = (global_configs['cache_discovery'] if ('cache_discovery' in global_configs) else False) self.repository = Ap...
def test_jenkins_dir(host): assert host.file('/jenkins').is_directory assert (host.file('/jenkins').mode == 493) assert (host.file('/jenkins').user == 'jenkins') assert (host.file('/jenkins').group == 'jenkins') assert host.file('/jenkins/config.xml').is_file assert (host.file('/jenkins/config.x...
def test_default_notation_1(): true_value = LogicCondition.initialize_true(LogicCondition.generate_new_context()) ast = AbstractSyntaxTree(CodeNode(Assignment((var := Variable('var_0', I32)), Constant(0)), true_value), {}) _run_vng(ast, _generate_options(notation='default')) assert (var.name == 'var_0')
.skipif(('pandas' not in sys.modules), reason='Pandas is not installed.') def test_structured_dataset_in_dataclass(): import pandas as pd from pandas._testing import assert_frame_equal df = pd.DataFrame({'Name': ['Tom', 'Joseph'], 'Age': [20, 22]}) People = Annotated[(StructuredDataset, 'parquet', kwtyp...
class KMSGateway(AWSGateway): def __init__(self, region: str, access_key_id: Optional[str]=None, access_key_data: Optional[str]=None, config: Optional[Dict[(str, Any)]]=None) -> None: super().__init__(region, access_key_id, access_key_data, config) self.client: BaseClient = boto3.client('kms', regio...
def named_color_function(obj: 'Color', func: str, alpha: Optional[bool], precision: int, fit: Union[(str, bool)], none: bool, percent: bool, legacy: bool, scale: float) -> str: a = get_alpha(obj, alpha, none, legacy) string = ['{}{}('.format(func, ('a' if (legacy and (a is not None)) else EMPTY))] coords = ...
def unwrap_workflow_schedule_response(response): if (response.return_code == str(SUCCESS)): return ProtoToMeta.proto_to_workflow_schedule_meta(Parse(response.data, WorkflowScheduleProto())) elif (response.return_code == str(RESOURCE_DOES_NOT_EXIST)): return None else: raise AIFlowExc...
class TestRallyRepository(): ('esrally.utils.io.exists', autospec=True) ('esrally.utils.git.is_working_copy', autospec=True) def test_fails_in_offline_mode_if_not_a_git_repo(self, is_working_copy, exists): is_working_copy.return_value = False exists.return_value = True with pytest.ra...
def _deployment_test(): import torch set_log_level('INFO') logger.info('') logger.info(' TESTING DEPLOYMENT ') logger.info('') logger.info('') logger.info('Testing CUDA init... ') enable_cuda() set_precision('double') logger.info('Done.') logger.info('') logger.info('') ...
class GraphClient(NamespacedClient): _rewrite_parameters(body_fields=('connections', 'controls', 'query', 'vertices')) def explore(self, *, index: t.Union[(str, t.Sequence[str])], connections: t.Optional[t.Mapping[(str, t.Any)]]=None, controls: t.Optional[t.Mapping[(str, t.Any)]]=None, error_trace: t.Optional[b...
def test_just_three_padded_mol(): f = open(just_three_residues, 'r') pdb_string = f.read() termini = {':MET:15': 'N'} chorizo = LinkedRDKitChorizo(pdb_string, termini=termini) assert (len(chorizo.residues) == 3) assert (len(chorizo.getIgnoredResidues()) == 0) expected_suggested_mutations = {...
def _nuke_set_zero_margins(widget_object): parentApp = QtWidgets.QApplication.allWidgets() parentWidgetList = [] for parent in parentApp: for child in parent.children(): if (widget_object.__class__.__name__ == child.__class__.__name__): parentWidgetList.append(parent.pare...
class _AsyncWrapperForSyncCallbackManagerForRun(AsyncCallbackManagerForLLMRun): def __init__(self, callback_manager: 'CallbackManagerForLLMRun'): super().__init__(run_id=callback_manager.run_id, handlers=callback_manager.handlers, inheritable_handlers=callback_manager.inheritable_handlers, parent_run_id=cal...
def gen_function_single_thread(fused_func_metadata, input_names, output_names, type_converter) -> str: tensor_to_expr: Dict[(Tensor, str)] = {} float32_t = fused_func_metadata.float32_t body = '' for (tensor, name) in zip(fused_func_metadata.original_inputs, input_names): if (fused_func_metadata...
def test_json_interface(newproject): with newproject._path.joinpath('contracts/Foo.vy').open('w') as fp: fp.write(CONTRACT) with newproject._path.joinpath('interfaces/Bar.json').open('w') as fp: json.dump(ABI, fp) newproject.load() assert newproject._path.joinpath('build/contracts/Foo.js...
class AddMetaTest(TestModelMixin, TestBase): databases = {'default', 'mysql', 'postgres'} def testAddMeta(self): with reversion.create_revision(): reversion.add_meta(TestMeta, name='meta v1') obj = TestModel.objects.create() self.assertSingleRevision((obj,), meta_names=('...
def test_should_burn_gas_with_revert(computation): assert (computation.get_gas_remaining() == 100) with computation: raise Revert('Triggered VMError for tests') assert (not computation.should_burn_gas) assert (computation.get_gas_used() == 0) assert (computation.get_gas_remaining() == 100)
class OptionSeriesOrganizationSonificationContexttracksMappingHighpassResonance(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...
_models('spacy.Dolly.v1') def dolly_hf(name: Dolly.MODEL_NAMES, config_init: Optional[Dict[(str, Any)]]=SimpleFrozenDict(), config_run: Optional[Dict[(str, Any)]]=SimpleFrozenDict()) -> Callable[([Iterable[str]], Iterable[str])]: return Dolly(name=name, config_init=config_init, config_run=config_run)
class App(): def __init__(self, server): (self.imports, self.comps) = ({}, {}) (self.vars, self.__map_var_names, self.server, self.__components) = ({}, {}, server, None) def route(self, component: str, alias: str): index_router = Path(self.server.app_path, 'index.js') if (not ind...
class StateContext(): def __init__(self, obj, chat_id, user_id): self.obj = obj self.data = None self.chat_id = chat_id self.user_id = user_id async def __aenter__(self): self.data = copy.deepcopy((await self.obj.get_data(self.chat_id, self.user_id))) return self....
def test_config_entry_precedence(): c = ConfigEntry(LegacyConfigEntry('platform', 'url', str)) assert (c.read() is None) old_environ = dict(os.environ) os.environ['FLYTE_PLATFORM_URL'] = 'xyz' cfg = get_config_file(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'configs/good.config')) ...
def interactive_map(obj, **kwargs): h = (100 * 3) tmp = temp_file('.svg') p = new_plot(projection='web-mercator', width=(6 * 1024), width_cm=h, height_cm=h, frame=False, foreground=False, background=False) p.plot_map(obj) bbox = p.save(tmp.path) return make_map(tmp.path, bbox)
class OptionPlotoptionsColumnrangeStatesHover(Options): def animation(self) -> 'OptionPlotoptionsColumnrangeStatesHoverAnimation': return self._config_sub_data('animation', OptionPlotoptionsColumnrangeStatesHoverAnimation) def borderColor(self): return self._config_get(None) def borderColor(...
def test_receive_before_accept(test_client_factory): async def app(scope: Scope, receive: Receive, send: Send) -> None: websocket = WebSocket(scope, receive=receive, send=send) (await websocket.accept()) websocket.client_state = WebSocketState.CONNECTING (await websocket.receive()) ...
class OptionSeriesSunburstSonificationTracksMappingTremoloSpeed(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 extractMehtranslationsCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('paw in paw', 'Paw in Paw, Lets Satisfy Our Desire for Dogs', 'translated'), ('the favoured genius'...
class BranchesAlreadyExistError(FoundryAPIError): def __init__(self, dataset_rid: str, branch_rid: str, response: (requests.Response | None)=None): super().__init__((f'''Branch {branch_rid} already exists in {dataset_rid}. ''' + (response.text if (response is not None) else ''))) self.dataset_rid = ...
class OptionPlotoptionsFunnel3dSonificationDefaultinstrumentoptionsMappingVolume(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...
('aea.cli.utils.config.get_or_create_cli_config') ('aea.cli.utils.generic.yaml.dump') ('aea.cli.utils.click_utils.open_file', mock.mock_open()) class UpdateCLIConfigTestCase(TestCase): def testupdate_cli_config_positive(self, dump_mock, icf_mock): update_cli_config({'some': 'config'}) icf_mock.asser...
class StartResponseMockLite(): def __init__(self): self._called = 0 self.status = None self.headers = None self.exc_info = None def __call__(self, status, headers, exc_info=None): self._called += 1 self.status = status self.headers = headers self.e...
def _add_tests(): _ofp_vers = {'of10': ofproto_v1_0.OFP_VERSION, 'of12': ofproto_v1_2.OFP_VERSION, 'of13': ofproto_v1_3.OFP_VERSION, 'of14': ofproto_v1_4.OFP_VERSION, 'of15': ofproto_v1_5.OFP_VERSION} this_dir = os.path.dirname(sys.modules[__name__].__file__) ofctl_rest_json_dir = os.path.join(this_dir, 'of...
class StringifyObject(PropertyPreprocessor): type = 'stringify_object' def imports(self): return {'modules': ['json']} def process_arg(self, arg, node, raw_args): scrubbed = {} for (k, v) in arg.items(): if (v == ''): scrubbed[k] = 'null' elif ...