code
stringlengths
281
23.7M
class Command(BaseCommand): help = '\n This command creates an empty Delta Table based on the provided --destination-table argument.\n ' def add_arguments(self, parser): parser.add_argument('--destination-table', type=str, required=True, help='The destination Delta Table to write the data', choice...
def youtube_channel_details(key, channel_ids): base_url = ' channel_ids = _split_by_comma(channel_ids, length=50) final_df = pd.DataFrame() for channel_id in channel_ids: params = {'id': channel_id, 'key': key} logging.info(msg=('Requesting: ' + 'channel details')) channel_resp =...
class DatatableColumn(): def __init__(self, title: str, slug: str, renderer_macro: str, *, ordering: (str | None)=None, renderer_macro_kwargs: (dict[(str, Any)] | None)=None) -> None: self.title = title self.slug = slug self.ordering = ordering self.renderer_macro = renderer_macro ...
class ProductItemCommerceInsights(AbstractObject): def __init__(self, api=None): super(ProductItemCommerceInsights, self).__init__() self._isProductItemCommerceInsights = True self._api = api class Field(AbstractObject.Field): message_sends = 'message_sends' organic_impre...
.skipif((MID_MEMORY > memory), reason='Travis has too less memory to run it.') .parametrize('matrix', [matrix]) .parametrize('outFileName', [outfile_aggregate_plots]) .parametrize('BED', [BED]) .parametrize('mode', ['intra-chr']) .parametrize('ran', ['50000:900000']) .parametrize('BED2', [BED2]) .parametrize('numberOfB...
class backtracking(dummy): def __init__(self, eta=0.5, **kwargs): if ((eta > 1) or (eta <= 0)): raise ValueError('eta must be between 0 and 1.') self.eta = eta super(backtracking, self).__init__(**kwargs) def _update_step(self, solver, objective, niter): properties = ...
def go(): print('AutoTreiver Launching!') settings = loadSettings() threads = 1 if (('threads' in settings) and settings['threads']): threads = settings['threads'] print('Have multithreading configuration directive!', threads) else: print('Running in single thread mode.') ...
class PretrainedConfig(): model_type: str = '' def __init__(self, **kwargs): self._name_or_path = str(kwargs.pop('name_or_path', '')) self.scale = None def name_or_path(self) -> str: return self._name_or_path _or_path.setter def name_or_path(self, value): self._name_o...
class NodeLookup(object): def __init__(self, database): self.conn = sqlite3.connect(database) def build_database(self, nodes, tiles): create_tables(self.conn) c = self.conn.cursor() tile_names = [] for tile_type in tiles: for tile in tiles[tile_type]: ...
def exposed_update_from_dead_netlocs(): with open('bad_urls.json', 'r') as fp: cont = fp.read() items = json.loads(cont) moved = [] for (key, value) in items.items(): if (('code' in value) and (value['code'] == 410)): comment_line = comment_netloc(key) moved.a...
def test_run_bench(tmp_path, monkeypatch): def dummy(*args, **kwargs): return monkeypatch.setitem(__main__.COMMANDS, 'attach', dummy) __main__._parse_and_main([*helpers.setup_temp_env(tmp_path), 'run-bench', '--worker', 'mac', '--benchmarks', 'deepcopy', 'caf63ec5'], __file__) queue = json.loads...
.feature('unit') .story('services', 'core', 'scheduler') class TestSchedulerEntities(): def test_scheduled_process(self): scheduled_process = ScheduledProcess() assert (scheduled_process.name is None) assert (scheduled_process.script is None) def test_schedule(self): assert isins...
def make_blocks(num_records=2000, codec='null'): records = make_records(num_records) new_file = BytesIO() fastavro.writer(new_file, schema, records, codec=codec) new_file.seek(0) block_reader = fastavro.block_reader(new_file, schema) blocks = list(block_reader) new_file.close() return (b...
class ModifyL4Src(base_tests.SimpleDataPlane): def runTest(self): logging.info('Running Modify_L4_Src test') of_ports = config['port_map'].keys() of_ports.sort() self.assertTrue((len(of_ports) > 1), 'Not enough ports for test') delete_all_flows(self.controller) loggin...
(scope='function') def privacy_preference_history_for_tcf_feature(db, provided_identity_and_consent_request, privacy_experience_france_overlay, fides_user_provided_identity, served_notice_history_for_tcf_feature): preference_history_record = PrivacyPreferenceHistory.create(db=db, data={'anonymized_ip_address': '92....
class OriginInspectorDimensions(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 {'region': (str,), 'dat...
def forward(model: Model[(InT, OutT)], Xr: InT, is_train: bool) -> Tuple[(OutT, Callable)]: Q = model.get_param('Q') key_transform = model.get_ref(KEY_TRANSFORM_REF) (attention, bp_attention) = _get_attention(model.ops, Q, key_transform, Xr.dataXd, Xr.lengths, is_train) (output, bp_output) = _apply_atte...
def display_tag_info(editor, stamp, tag, index): synonyms = index.synonyms if (' ' in tag): tagsContained = tag.split(' ') else: tagsContained = [tag] for synset in synonyms: synsetNorm = [s.lower() for s in synset] for tag in tagsContained: if (tag.lower() in...
class HamiltonJacobiDiffusionReaction_ASGS(SGE_base): def __init__(self, coefficients, nd, stabFlag='1', lag=False): SGE_base.__init__(self, coefficients, nd, lag) self.stabilizationFlag = stabFlag def initializeElementQuadrature(self, mesh, t, cq): import copy self.mesh = mesh ...
class JsDomEffects(): def __init__(self, page: primitives.PageModel, component: primitives.HtmlModel): self._effects = Effects.Effects(page) self.component = component def glow(self, color, radius=50, duration=1, timing_fnc='ease-in-out', delay=0, iteration_count='infinite', direction='alternate...
(('config_name', 'overrides', 'expected'), [param('defaults_with_override_only', [], DefaultsTreeNode(node=VirtualRoot(), children=[DefaultsTreeNode(node=ConfigDefault(path='hydra/config'), children=[GroupDefault(group='help', value='custom1'), GroupDefault(group='output', value='default'), ConfigDefault(path='_self_')...
.skipif((sys.version_info < (3, 5)), reason='requires python3.5 or higher due to incompatible pickle file in tests.') def test_read_results_dicts(): (inputs, results) = ds.get_sim_results(path=SIM_DIR, return_xarray=False, return_status=False) assert isinstance(inputs, dict) assert isinstance(results, dict)
class shutdown_args(): thrift_spec = None thrift_field_annotations = None thrift_struct_annotations = None def isUnion(): return False def read(self, iprot): if ((isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocol) and ...
class OnlyFieldsSerializerMixinTests(SerializerMixinTestCase): def serialize(self, **context): return CarModelTestSerializer(self.carmodel_model_s, context=context).data def test_all_fields_implicit(self): self.assertDictEqual(self.serialize(), self.expected_complete_data) def test_all_field...
def update_ear_flag(vertices: List[Vertex], i: int) -> None: h = ((i - 1) % len(vertices)) j = ((i + 1) % len(vertices)) triangle = (vertices[h].coordinate, vertices[i].coordinate, vertices[j].coordinate) vertices[i].is_ear = (vertices[i].is_convex and (not any((is_inside(v.coordinate, triangle) for (k,...
class RemoteEvaluator(): def __init__(self, evaluator: SentenceLevelEvaluator) -> None: self.evaluator = evaluator self.address = evaluator.args.remote_address self.port = evaluator.args.remote_port self.source_segment_size = evaluator.args.source_segment_size self.base_url =...
class _Background(): def __init__(self, color=None): self.color = color def apply(self, item): if self.color: r = item.boundingRect() bg = QGraphicsRectItem(r) bg.setParentItem(item) pen = QPen(QColor(self.color)) brush = QBrush(QColor(...
class OptionPlotoptionsXrangeSonificationContexttracksMappingPitch(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('y') def mapTo(self, text: str): ...
class WafExclusionResponseData(ModelComposed): allowed_values = {} validations = {} _property def additional_properties_type(): lazy_import() return (bool, date, datetime, dict, float, int, list, str, none_type) _nullable = False _property def openapi_types(): lazy_im...
class ModelDataGenerator(ABC): def iter_data_lines_for_xml_root(self, root: etree.ElementBase) -> Iterable[str]: return self.iter_data_lines_for_layout_document(parse_alto_root(root)) def iter_model_data_for_layout_document(self, layout_document: LayoutDocument) -> Iterable[LayoutModelData]: pas...
class FetchedModelsManager(ErsiliaBase): def __init__(self, config_json=None): ErsiliaBase.__init__(self, config_json=config_json, credentials_json=None) self.file_name = os.path.abspath(os.path.join(EOS, FETCHED_MODELS_FILENAME)) def add(self, model_id): pass def delete(self, model_...
class RiversideHandler(THBEventHandler): interested = ['calcdistance', 'action_after'] def handle(self, evt_type, arg): if (evt_type == 'calcdistance'): (src, card, dist) = arg if (not src.has_skill(Riverside)): return arg for p in dist: ...
def make_class_defs(ole_item): class_defs = [] class_name = ole_item.python_name is_sink = ole_item.bIsSink class_body = [] class_body_assigns = [] clsid = ole_item.clsid clsid_assign = ast.Assign([ast.Name('CLSID', ast.Store())], ast.Call(ast.Name('IID', ast.Load()), [ast.Constant(str(clsid...
class Arcfour(): def __init__(self, key): s = list(range(256)) j = 0 klen = len(key) for i in range(256): j = (((j + s[i]) + key[(i % klen)]) % 256) (s[i], s[j]) = (s[j], s[i]) self.s = s (self.i, self.j) = (0, 0) return def process...
def extractNyankonyantranslationBlogspotCom(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, nam...
('input_list, reference, expected_idx', [([], ('', ''), (- 1)), ([('a', '10')], ('a', None), 0), ([('a', '10'), ('b', '20'), ('a', '30')], ('a', None), 2), ([('a', '10'), ('b', '20'), ('a', '30')], ('b', None), 1), ([('a', '10'), ('b', '20'), ('a', '30')], ('a', '10'), 0)]) def test_find_last_match(input_list: List[Tup...
.parametrize('idx, i, slice_at', [(0, 0, 0), (10, 3, 2), (33, 7, 4), (4, 1, 0), (13, 3, 2), pytest.param((- 1), 0, 0, marks=pytest.mark.xfail), pytest.param(40, 0, 0, marks=pytest.mark.xfail)]) def test_idx2i(nlp, idx, i, slice_at): doc = nlp(_TEXT_SAMPLE) doc_idx = idx2i(doc, idx) assert (doc_idx == i) ...
class HistoricalDomainsMetaFilters(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 {'region': (str,), '...
class OptimizerScheduler(abc.ABC): def __init__(self, *, optimizer: Optimizer, **kwargs): init_self_cfg(self, component_class=__class__, config_class=OptimizerSchedulerConfig, **kwargs) self.optimizer = optimizer def _set_defaults_in_cfg(cls, cfg): pass def step(self, batch_metric: O...
class Port(Base): __tablename__ = 'port' __table_args__ = (UniqueConstraint('protocol', 'port_number'),) id = Column(Integer, primary_key=True) protocol = Column('protocol', String) port_number = Column('port_number', Integer) target_id = Column(Integer, ForeignKey('target.id')) targets = re...
class Ohno2013(CCT): NAME = 'ohno-2013' CHROMATICITY = 'uv-1960' def __init__(self, cmfs: dict[(int, tuple[(float, float, float)])]=cmfs.CIE_1931_2DEG, white: VectorLike=cat.WHITES['2deg']['D65'], planck_step: int=5): self.white = white self.blackbody = BlackBodyCurve(cmfs, white, planck_ste...
class GenrePopupController(OptionsController): new_genre_icon = GObject.property(type=bool, default=False) def __init__(self, plugin, album_model): super(GenrePopupController, self).__init__() cl = CoverLocale() cl.switch_locale(cl.Locale.LOCALE_DOMAIN) self._album_model = album_...
def expand_derivatives_form(form, fc_params): if isinstance(form, ufl.form.Form): from firedrake.parameters import parameters as default_parameters from tsfc.parameters import is_complex if (fc_params is None): fc_params = default_parameters['form_compiler'].copy() else: ...
class Panda(CommandBase): def __init__(self): super().__init__() self.name = 'panda' self.description = ' panda interfacing tools' self.commands = {'flash': Command(description=' flashes panda with make recover (usually works with the C2)'), 'flash2': Command(description=' flashes pa...
class TestAVSUCDReader(DataReaderTestBase): def setup_reader(self): r = UnstructuredGridReader() r.initialize(get_example_data('cellsnd.ascii.inp')) self.e.add_source(r) self.bounds = ((- 2.0), 2.0, (- 2.0), 2.0, 0.0, 0.0) def test_avsucd_data_reader(self): self.check(sel...
def test_mask_sha256(): configuration = HashMaskingConfiguration(algorithm='SHA-256') masker = HashMaskingStrategy(configuration) expected = '1c015e801323afa54bde5e4d510809e6b5f14ad9b9961c48cbd7143106b6e596' secret = MaskingSecretCache[str](secret='adobo', masking_strategy=HashMaskingStrategy.name, secr...
def fix_content(content, tmpdir): if nodeenv.is_WIN: bin_name = 'Scripts' node_name = 'node.exe' else: bin_name = 'bin' node_name = 'node' tmpdir.join('Scripts').join('node.exe') content = content.replace('__NODE_VIRTUAL_PROMPT__', '({})'.format(tmpdir.basename)) ...
def get_all_package_ids() -> Set[PackageId]: result: Set[PackageId] = set() now = get_hashes_from_current_release() now_by_type = split_hashes_by_type(now) for (type_, name_to_hashes) in now_by_type.items(): for (name, _) in name_to_hashes.items(): if (name in TEST_PROTOCOLS): ...
class FSWriter(BaseWriter): def __init__(self, params): super().__init__(params) self.type = 'filesystem' self.out_dir = params.get('directory') def write_data(self, data, file_name=None): if (not file_name): file_name = str(uuid.uuid4()) dir_path = os.path.jo...
def test_multiple_tasks(test_client_factory: Callable[(..., TestClient)]): TASK_COUNTER = 0 def increment(amount): nonlocal TASK_COUNTER TASK_COUNTER += amount async def app(scope, receive, send): tasks = BackgroundTasks() tasks.add_task(increment, amount=1) tasks.add...
class FidesModel(BaseModel): fides_key: FidesKey = Field(description='A unique key used to identify this resource.') organization_fides_key: FidesKey = Field(default='default_organization', description='Defines the Organization that this resource belongs to.') tags: Optional[List[str]] = None name: Opti...
def streaming_post_to_es(client: Elasticsearch, chunk: list, index_name: str, job_name: str=None, delete_before_index: bool=True, delete_key: str='_id') -> Tuple[(int, int)]: (success, failed) = (0, 0) try: if delete_before_index: value_list = [doc[delete_key] for doc in chunk] d...
class TimeStamped(object): swagger_types = {'created_at': 'datetime'} attribute_map = {'created_at': 'createdAt'} def __init__(self, created_at=None): self._created_at = None self.discriminator = None if (created_at is not None): self.created_at = created_at def creat...
(version=(1, 1, 6)) () ('-k', '--size', help='Plot size', type=int, default=32, show_default=True) ('--override-k', help='Force size smaller than 32', default=False, show_default=True, is_flag=True) ('-n', '--num', help='Number of plots or challenges', type=int, default=1, show_default=True) ('-b', '--buffer', help='Me...
def test_select_range_mult(monkeypatch: MonkeyPatch): inputs = ['1-5 7-10'] monkeypatch.setattr('builtins.input', (lambda : inputs.pop(0))) save_stats = {'cats': [1, 1, 1, 0, 1]} ids = cat_id_selector.select_cats_range(save_stats) actual_ids = [1, 2, 3, 4, 5, 7, 8, 9, 10] assert (ids == actual_i...
def test_success_message_succeeds(): (message, code) = success_message({'my': 'response'}, '/any/url') assert (message['my'] == 'response') assert (message['status'] == 0) assert (code == 200) (_, code) = success_message({'my': 'response'}, '/any/url', return_code=202) assert (code == 202)
def test_paginate_query(sqlalchemy_storage): for i in range(10): item = MockStorageItem(MockResourceIdentifier(str(i)), f'test_data_{i}') sqlalchemy_storage.save(item) page_size = 3 page_number = 2 query_spec = QuerySpec(conditions={}) page_result = sqlalchemy_storage.paginate_query(...
class TestTachoMotorSpeedDValue(ptc.ParameterizedTestCase): def test_speed_d_negative(self): with self.assertRaises(IOError): self._param['motor'].speed_d = (- 1) def test_speed_d_zero(self): self._param['motor'].speed_d = 0 self.assertEqual(self._param['motor'].speed_d, 0) ...
def write_mcj_data(outFile): b_data = {} dat = {'Created': 'MifareClassicTool', 'FileType': 'mfcard', 'blocks': b_data} i = 0 for b in blk_data: b_data[str(i)] = ''.join(b).upper() i += 1 with open((outFile + '_mct.json'), 'w', encoding='utf-8') as fd: json.dump(dat, fd, inde...
_group.command('kibana-diff') ('--rule-id', '-r', multiple=True, help='Optionally specify rule ID') ('--repo', default='elastic/kibana', help='Repository where branch is located') ('--branch', '-b', default='main', help='Specify the kibana branch to diff against') ('--threads', '-t', type=click.IntRange(1), default=50,...
def extractWinkcherryfoxBlogspotCom(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...
class OptionSeriesTreemapStatesHover(Options): def animation(self) -> 'OptionSeriesTreemapStatesHoverAnimation': return self._config_sub_data('animation', OptionSeriesTreemapStatesHoverAnimation) def brightness(self): return self._config_get('undefined') def brightness(self, num: float): ...
class PythonConnectionManager(metaclass=abc.ABCMeta): TYPE: str = NotImplemented def __init__(self, profile: AdapterRequiredConfig): self.profile = profile if (profile.credentials.type == self.TYPE): self.credentials = profile.credentials else: self.credentials = ...
class OptionPlotoptionsBulletSonificationDefaultinstrumentoptionsMappingPlaydelay(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, te...
class IntricateApp(): def unorthodox_call(self, scope, receive, send): return self._call_factory(scope, receive, send) async def _call_factory(self, scope, receive, send): (await send('Hello!')) (await send('Bye.')) __call__ = _asgi_helpers._wrap_asgi_coroutine_func(unorthodox_call)
class QuadratureRule(object): def __init__(self, cell, degree, points, weights): self.cell = cell self.points = np.array(points, dtype=np.double) self.weights = np.array(weights, dtype=np.double) self.degree = degree if (self.cell.dim != self.points.shape[1]): rai...
def get_jobdetails(job_details): deets_dict = {} if ('Benchmark' in job_details): deet_match_list = ['name', 'benchmark', 'benchmark_all'] else: deet_match_list = ['hash_mode', 'attack_mode', 'mask', 'wordlist', 'wordlist2', 'rules', 'name', 'username', 'increment', 'increment_min', 'increme...
class icmp(packet_base.PacketBase): _PACK_STR = '!BBH' _MIN_LEN = struct.calcsize(_PACK_STR) _ICMP_TYPES = {} def register_icmp_type(*args): def _register_icmp_type(cls): for type_ in args: icmp._ICMP_TYPES[type_] = cls return cls return _register_...
class QueryStub(object): def __init__(self, channel): self.Evidence = channel.unary_unary('/cosmos.evidence.v1beta1.Query/Evidence', request_serializer=cosmos_dot_evidence_dot_v1beta1_dot_query__pb2.QueryEvidenceRequest.SerializeToString, response_deserializer=cosmos_dot_evidence_dot_v1beta1_dot_query__pb2....
def create_dyn_dep_munger(buildopts, install_dirs, strip: bool=False) -> Optional[DepBase]: if buildopts.is_linux(): return ElfDeps(buildopts, install_dirs, strip) if buildopts.is_darwin(): return MachDeps(buildopts, install_dirs, strip) if buildopts.is_windows(): return WinDeps(buil...
(cls=PluggableGroup, entry_point_group='jb.cmdline', use_internal={'build', 'clean', 'config', 'create', 'myst'}, context_settings={'help_option_names': ['-h', '--help']}) ('--version', is_flag=True, expose_value=False, is_eager=True, help='Show the version and exit.', callback=version_callback) def main(): pass
class TraditionalPokerScoreDetectorTests(unittest.TestCase): def _test_detect(self, cards, expected_category, expected_cards): score = TraditionalPokerScoreDetector(lowest_rank=7).get_score(cards) self.assertIsInstance(score, TraditionalPokerScore) self.assertEqual(score.category, expected_c...
def test_mars_api_key(): answers = [' 'b295aad8af30332fad2fa8c963ab7900', 'joe.'] with patch('climetlab.sources.prompt.Text.ask', side_effect=answers): with patch('sys.stdout', new_callable=StringIO) as stdout: prompt = MARSAPIKeyPrompt().ask_user() assert (prompt == {'url': ' 'key': 'b2...
def run(): snmpDispatcher = SnmpDispatcher() iterator = sendNotification(snmpDispatcher, CommunityData('public', mpModel=0), UdpTransportTarget(('demo.snmplabs.com', 162)), 'trap', NotificationType(ObjectIdentity('1.3.6.1.6.3.1.1.5.2')).loadMibs('SNMPv2-MIB').addVarBinds(('1.3.6.1.6.3.1.1.4.3.0', '1.3.6.1.4.1.2...
class TestOrderedDictionary(unittest.TestCase): def test_get_and_set(self): d = OrderedDictionary() self.assertEqual(len(d), 0) d['hello'] = 'goodbye' self.assertEqual(d['hello'], 'goodbye') def test_insert(self): d = OrderedDictionary() d['hello'] = 'goodbye' ...
class OptionChartOptions3dFrameLeft(Options): def color(self): return self._config_get('transparent') def color(self, text: str): self._config(text, js_type=False) def size(self): return self._config_get(1) def size(self, num: float): self._config(num, js_type=False) ...
_cli.command('set', short_help='Overrides database revision with selected migration.') ('--revision', '-r', default='head', help='The migration to set.') ('--auto-confirm', default=False, is_flag=True, help='Skip asking confirmation.') _script_info def migrations_set(info, revision, auto_confirm): from .orm.migrati...
class GraphLegend(sweetviz.graph.Graph): def __init__(self, dataframe_report): styles = ['graph_base.mplstyle'] self.set_style(styles) fig = plt.figure(figsize=(config['Graphs'].getfloat('legend_width'), config['Graphs'].getfloat('legend_height'))) axs = fig.add_axes([0, 0, 1, 1]) ...
def clean_tag(in_txt): assert isinstance(in_txt, str), ("Passed item is not a string! Type: '%s' -> '%s'" % (type(in_txt), in_txt)) assert (not (',' in in_txt)), ("It looks like a tag list got submitted as a tag! String: '%s'" % (in_txt,)) in_txt = in_txt.strip().lower().replace(' ', '-') return in_txt
class TestTask(BasePyTestCase): ('bodhi.server.tasks.bugs') ('bodhi.server.tasks.buildsys') ('bodhi.server.tasks.initialize_db') ('bodhi.server.tasks.config') ('bodhi.server.tasks.check_policies.main') def test_task(self, main_function, config_mock, init_db_mock, buildsys, bugs): check_p...
class OptionSeriesAreasplinerangeSonificationTracksMappingPan(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): se...
.timeout(8) def test_account_transactions(db_context: DatabaseContext) -> None: ACCOUNT_ID_1 = 10 ACCOUNT_ID_2 = 11 MASTERKEY_ID_1 = 20 MASTERKEY_ID_2 = 21 masterkey1 = MasterKeyRow(MASTERKEY_ID_1, None, DerivationType.BIP32, b'111') masterkey2 = MasterKeyRow(MASTERKEY_ID_2, None, DerivationType...
class WallPinRow(_WallMountedBox): def __init__(self) -> None: super().__init__() self.argparser.add_argument('--pins', action='store', type=int, default=8, help='number of pins') self.argparser.add_argument('--pinlength', action='store', type=float, default=35, help='length of pins (in mm)'...
class OptionSeriesVariwideSonificationDefaultinstrumentoptionsMappingLowpassResonance(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 OptionSeriesPictorialSonificationContexttracksMappingTremoloDepth(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 NoiseGenerator(lg.Node): OUTPUT = lg.Topic(RandomMessage) config: NoiseGeneratorConfig (OUTPUT) async def generate_noise(self) -> lg.AsyncPublisher: while True: (yield (self.OUTPUT, RandomMessage(timestamp=time.time(), data=np.random.rand(self.config.num_features)))) ...
.parametrize('uri_template', ['/{field}{field}', '/{field}...{field}', '/{field}/{another}/{field}', '/{field}/something/something/{field}/something']) def test_duplicate_field_names(uri_template): router = DefaultRouter() with pytest.raises(ValueError): router.add_route(uri_template, ResourceWithId(1))
class PowerFunctionExample(HasStrictTraits): plot = Instance(Plot) power = Range(0, 5, value=2) x = Array(shape=(None,), dtype='float') def _plot_default(self): y = (self.x ** self.power) plot_data = ArrayPlotData(x=self.x, y=y) plot = Plot(plot_data) plot.plot(('x', 'y')...
def delays_to_cells(ws, row, delays, cells): cells['FAST_MAX'] = 'E{}'.format(row) cells['FAST_MIN'] = 'F{}'.format(row) cells['SLOW_MAX'] = 'G{}'.format(row) cells['SLOW_MIN'] = 'H{}'.format(row) if (delays is not None): ws[cells['FAST_MAX']] = delays[FAST].max ws[cells['FAST_MIN']]...
() def docs_serve(session: nox.Session) -> None: generate_docs(session) session.notify('teardown') session.run('docker', 'compose', 'build', 'docs', external=True) run_shell = ('docker', 'compose', 'run', '--rm', '--service-ports', CI_ARGS, 'docs', '/bin/bash', '-c', 'mkdocs serve --dev-addr=0.0.0.0:800...
.xfail def test_when_exception_can_not_be_deserialized(isolated_client): _client('virtualenv', requirements=['']) def unpicklable_input_function_client(): class T(Exception): frame = __import__('sys')._getframe(0) raise T() with pytest.raises(FalServerlessError, match='...'): ...
class OptionPlotoptionsArearangeSonificationDefaultinstrumentoptionsMappingTremoloDepth(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(se...
def fetch_production(zone_key: str, session: (Session | None)=None, target_datetime: (datetime | None)=None, logger: Logger=getLogger(__name__)) -> dict: session = (session or Session()) if target_datetime: raise NotImplementedError('This parser is not yet able to parse past dates') value_map = fetc...
def test_search_query_cache(frontend_db, frontend_editing_db): assert (frontend_db.search_query_cache(offset=0, limit=10) == []) id1 = frontend_editing_db.add_to_search_query_cache('foo', 'rule bar{}') id2 = frontend_editing_db.add_to_search_query_cache('bar', 'rule foo{}') assert (sorted(frontend_db.se...
def test_behaviour_parse_module_missing_class(): skill_context = SkillContext(skill=MagicMock(skill_id=PublicId.from_str('author/name:0.1.0'))) dummy_behaviours_path = Path(ROOT_DIR, 'tests', 'data', 'dummy_skill', 'behaviours.py') with unittest.mock.patch.object(aea.skills.base._default_logger, 'warning') ...
class InstallationAdmin(ExportMixin, EventoLAdmin): resource_class = InstallationResource list_display = ('hardware', 'software', 'get_event', 'get_installer', 'attendee') list_filter = (EventFromInstallerFilter, HardwareFilter, SoftwareFilter, InstallerFilter) search_fields = ('notes',) def get_eve...
class TlsPrivateKeyResponseAttributesAllOf(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 {'name': (st...
class TraditionalPokerGameEventDispatcher(GameEventDispatcher): def new_game_event(self, game_id: str, players: List[Player], dealer_id: str, blind_bets): self.raise_event('new-game', {'game_id': game_id, 'game_type': 'traditional', 'players': [player.dto() for player in players], 'dealer_id': dealer_id, 'b...
('ui', 'trackproperties_dialog_cover_row.ui') class TagImageField(Gtk.Box): __gtype_name__ = 'TagImageField' (button, image, type_model, description_entry, type_selection, info_label) = GtkTemplate.Child.widgets(6) def __init__(self, all_button=True): Gtk.Box.__init__(self) self.init_templat...
def add_file_to_realization_runpaths(runpath_file): with open(runpath_file, 'r', encoding='utf-8') as fh: runpath_file_lines = fh.readlines() for line in runpath_file_lines: realization_path = line.split()[1] realization_nr = re.findall(REGEX, realization_path) (Path(realization_...