code
stringlengths
281
23.7M
def test_cli_with_poetry(poetry_venv_factory: PoetryVenvFactory) -> None: with poetry_venv_factory('project_with_poetry') as virtual_env: issue_report = f'{uuid.uuid4()}.json' result = virtual_env.run(f'deptry . -o {issue_report}') assert (result.returncode == 1) assert (get_issues_r...
class SurfaceIntegrationMonitor(Monitor, ABC): normal_dir: Direction = pydantic.Field(None, title='Normal Vector Orientation', description="Direction of the surface monitor's normal vector w.r.t. the positive x, y or z unit vectors. Must be one of ``'+'`` or ``'-'``. Applies to surface monitors only, and defaults t...
def _get_normal_forms(form): terms = [(~ logic_x[1].copy()), (((~ logic_x[1].copy()) | logic_x[2].copy()) & (logic_x[3].copy() | (~ logic_x[1].copy()))), ((((~ logic_x[1].copy()) | logic_x[2].copy()) & (logic_x[3].copy() | (~ logic_x[1].copy()))) & (logic_x[4].copy() | (logic_x[2].copy() & logic_x[3].copy()))), ((l...
class PredictionTable(Base): __tablename__ = 'prediction' id = Column(Integer, primary_key=True) lpep_pickup_datetime = Column(Float) PULocationID = Column(Integer) DOLocationID = Column(Integer) passenger_count = Column(Integer) trip_distance = Column(Float) fare_amount = Column(Float) ...
def test_functional_block_single_arg_lambda_unsqueeze(): in_dict = build_input_dict(dims=[100, 64]) net: FunctionalBlock = FunctionalBlock(in_keys='in_key', out_keys='out_key', in_shapes=(100, 64), func=(lambda value: torch.unsqueeze(value, dim=(- 1)))) str(net) out_dict = net(in_dict) assert isinst...
class EventHandler(object): def __init__(self): self.tab = None self.token = None self.is_first_request = False self.post_data = {} def set_tab(self, t): self.tab = t def set_token(self, t): self.token = t def set_post_data(self, pd): self.post_dat...
class Plotly2D(): def __init__(self, ui): self.page = ui.page self.chartFamily = 'Plotly' def line(self, record=None, y_columns=None, x_axis=None, profile=None, options=None, width=(100, '%'), height=(330, 'px'), html_code=None): options = (options or {}) options.update({'y_colum...
class Git(LocalComponent): def _git_branch(): return check_subprocess(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])[0].strip() def setup(self): if (not self._config.get('checkout', False)): return branch = Git._git_branch() L.info('Updating git repo to branch {} on de...
class TacDialogues(Model, BaseTacDialogues): def __init__(self, **kwargs: Any) -> None: Model.__init__(self, **kwargs) def role_from_first_message(message: Message, receiver_address: Address) -> BaseDialogue.Role: return BaseTacDialogue.Role.PARTICIPANT BaseTacDialogues.__init__(...
class op(bpy.types.Operator): bl_idname = 'uv.textools_island_straighten_edge_loops' bl_label = 'Straight edges chain' bl_description = 'Straighten selected edge-chain and relax the rest of the UV Island' bl_options = {'REGISTER', 'UNDO'} def poll(cls, context): if (bpy.context.area.ui_type ...
.parametrize('options_prefix', [None, '', 'foo']) def test_matrix_prefix_solver(options_prefix): parameters = {'ksp_type': 'preonly', 'pc_type': 'lu', 'pc_factor_mat_solver_type': 'mumps', 'mat_mumps_icntl_14': 200, 'mat_mumps_icntl_24': 1} mesh = UnitSquareMesh(1, 1) V = FunctionSpace(mesh, 'P', 1) u =...
class Shadow(Cover): SIZE = 120.0 WIDTH = 11 def __init__(self, size, image): super(Shadow, self).__init__(size, image) self._calculate_sizes(size) def resize(self, size): super(Shadow, self).resize(size) self._calculate_sizes(size) def _calculate_sizes(self, size): ...
class TestEllipticRedistancing(object): def setup_class(cls): pass def teardown_class(cls): pass def setup_method(self, method): self._scriptdir = os.path.dirname(__file__) def teardown_method(self, method): pass def test_ELLIPTIC_REDISTANCING_0(self): vortex2...
class _FlowSpecPrefixBase(_FlowSpecIPv4Component, IPAddrPrefix): def __init__(self, length, addr, type_=None): super(_FlowSpecPrefixBase, self).__init__(type_) self.length = length prefix = ('%s/%s' % (addr, length)) self.addr = str(netaddr.ip.IPNetwork(prefix).network) def parse...
class ClientC2Data(C2Data): def iter_encrypted_packets(self) -> Iterator[EncryptedPacket]: data = self.output while data: fobj = io.BytesIO(data) size = c2struct.uint32(fobj) ciphertext = fobj.read((size - 16)) signature = fobj.read(16) dat...
class AsyncNode(): def __init__(self, async_entity, entity_name, execution=None, url=None): self.entity_name = entity_name self.async_entity = async_entity self.execution = execution self._url = url def url(self) -> str: endpoint_root = FLYTE_SANDBOX_INTERNAL_ENDPOINT.rep...
def pwdlyze(passwords): prefixes = {} postfixes = {} lengths = {} symbols = {} numbers = {} for password in passwords: if (not password): continue prefix = password[0] postfix = password[(- 1)] length = len(password) if (prefix not in prefixes)...
def get_shuffling(seed: Bytes32, validators: List[Validator], epoch: Epoch) -> List[List[ValidatorIndex]]: param_hash = (seed, hash_tree_root(validators, [Validator]), epoch) if (param_hash in shuffling_cache): return shuffling_cache[param_hash] else: ret = _get_shuffling(seed, validators, e...
class OptionPlotoptionsAreaSonificationContexttracksMappingLowpassFrequency(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: st...
def _get_pe_size(pe_file_path: str) -> Optional[int]: binary = lief.PE.parse(pe_file_path) if (binary is None): LOG.error("Failed to parse PE '%s'", pe_file_path) return None number_of_sections = len(binary.sections) if (number_of_sections == 0): return None highest_section =...
_required _required _required _required('DNS_ENABLED') def dc_domain_list(request): user = request.user domains = Domain.objects.order_by('name') dc_domain_ids = list(request.dc.domaindc_set.values_list('domain_id', flat=True)) context = collect_view_data(request, 'dc_domain_list') context['is_staff...
def flag_dict(name): def _init_flag_dict(source): def subscribe(observer, scheduler=None): def on_next(value): flag_dict = {name: value} observer.on_next(flag_dict) return source.subscribe(on_next, observer.on_error, observer.on_completed, scheduler) ...
class UpdateConfiguration(BaseModel): update_steps: ConstrainedUpdateStepList def __iter__(self) -> Iterator[UpdateStep]: (yield from self.update_steps) def __getitem__(self, item: int) -> UpdateStep: return self.update_steps[item] def __len__(self) -> int: return len(self.update...
class ConfirmationAW3TestCase(BaseSkillTestCase): path_to_skill = Path(ROOT_DIR, 'packages', 'fetchai', 'skills', 'confirmation_aw3') def setup(cls): cls.aw1_aea = 'some_aw1_aea' cls.leaderboard_url = 'some_leaderboard_url' cls.leaderboard_token = 'some_leaderboard_token' config_...
class MyNode(Node): config: MyConfig state: MyState A = Topic(MyMessage) B = Topic(MyMessage) def setup(self) -> None: self.other_state: int = 5 (A) async def my_publisher(self) -> AsyncPublisher: for i in range(NUM_MESSAGES): (yield (self.A, MyMessage(my_field=i)...
class GlobalStyle(): def __init__(self, page: primitives.PageModel): self.page = page self._font = None self._icon = None self._table = None self._line_height = max(defaultHtml.LINE_HEIGHT, self.font.size) def line_height(self): return self._line_height _heigh...
def test_dict_wf_with_conversion(): def t1(a: int) -> typing.Dict[(str, str)]: return {'a': str(a)} def t2(a: dict) -> str: print(f'HAHAH {a}') return ' '.join([v for (k, v) in a.items()]) def my_wf(a: int) -> str: return t2(a=t1(a=a)) with pytest.raises(TypeError): ...
class override_maintenance_mode(ContextDecorator): def __init__(self, value): self.value = value self.old_value = None def __enter__(self): self.old_value = get_maintenance_mode() set_maintenance_mode(self.value) def __exit__(self, exc_type, exc_value, traceback): set...
def downgrade(): op.add_column(u'Projects', sa.Column('lead_id', sa.INTEGER(), nullable=True)) op.add_column(u'Departments', sa.Column('lead_id', sa.INTEGER(), nullable=True)) op.drop_column(u'Project_Users', 'rid') op.drop_column(u'Department_Users', 'rid') op.rename_table('Department_Users', 'User...
class table_feature_prop_experimenter(table_feature_prop): subtypes = {} type = 65534 def __init__(self, experimenter=None, subtype=None): if (experimenter != None): self.experimenter = experimenter else: self.experimenter = 0 if (subtype != None): ...
class NpmProviderFactory(ProviderFactory): class Options(NamedTuple): lockfile: NpmLockfileProvider.Options module: NpmModuleProvider.Options def __init__(self, lockfile_root: Path, options: Options) -> None: self.lockfile_root = lockfile_root self.options = options def creat...
class TestRegisterMessage(): def setup_class(cls): cls.info = {'a': 'b', 'c': 'd'} def test_register(self): tx_msg = RegisterMessage(performative=RegisterMessage.Performative.REGISTER, info=self.info) assert tx_msg._is_consistent() encoded_tx_msg = tx_msg.encode() decoded...
def get_kerning_by_blocks(blocks: List[Tuple[(int, int)]]) -> Tuple[(List[str], str)]: value = 0 glyphs: List[str] = [] rules = [] for (script, (width, height)) in enumerate(blocks): glyphs.extend((f'g_{script}_{i}' for i in range(max(width, height)))) for l in range(height): ...
def extractPrinceOfStrideNovelTranslation(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None if ('WATTT' in item['tags']): return buildReleaseMessageWithType(item, 'WATTT', vol, chp, ...
def compute_specifier_from_version(version: Version) -> str: new_major_low = version.major new_major_high = (version.major + 1) new_minor_low = version.minor new_minor_high = (new_minor_low + 1) if (new_major_low == 0): lower_bound = Version(f'{new_major_low}.{new_minor_low}.0') lowe...
def test_adding_a_label_on_non_headless_service(): config = '' r = helm_template(config) assert ('label1' not in r['service'][uname]['metadata']['labels']) config = '\n service:\n labels:\n label1: value1\n ' r = helm_template(config) assert (r['service'][uname]['metadata']['la...
def test_adding_an_extra_volume_with_volume_mount(): config = '\nextraVolumes:\n - name: extras\n emptyDir: {}\nextraVolumeMounts:\n - name: extras\n mountPath: /usr/share/extras\n readOnly: true\n' r = helm_template(config) extraVolume = r['deployment'][name]['spec']['template']['spec']['volumes...
class TornadoServer(AbstractServer): def __init__(self, *args, **kwargs): self._app = None self._server = None super().__init__(*args, **kwargs) def _open(self, host, port, **kwargs): self._io_loop = AsyncIOMainLoop() if hasattr(IOLoop, '_current'): IOLoop._cu...
class ValveSwitchStackManagerReflection(ValveSwitchStackManagerBase): _USES_REFLECTION = True def _learn_cache_check(self, entry, vlan, now, eth_src, port, ofmsgs, cache_port, cache_age, delete_existing, refresh_rules): learn_exit = False update_cache = True if (cache_port is not None): ...
class ServiceRecord(): SERVICE_RECORD_HANDLE = 0 SERVICE_CLASS_ID_LIST = 1 SERVICE_RECORD_STATE = 2 SERVICE_ID = 3 PROTOCOL_DESCRIPTOR_LIST = 4 BROWSE_GROUP_LIST = 5 LANGUAGE_BASE_ATTRIBUTE_ID_LIST = 6 SERVICE_INFO_TIME_TO_LIVE = 7 SERVICE_AVAILABILITY = 8 BLUETOOTH_PROFILE_DESCR...
class OptionSeriesSankeySonificationContexttracksMappingPan(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: str): self...
def test_regression(): (X, y) = df_regression() sel = SelectByTargetMeanPerformance(variables=None, bins=2, scoring='r2', regression=True, cv=2, strategy='equal_width', threshold=None) sel.fit(X, y) Xtransformed = X[['cat_var_A', 'cat_var_B', 'num_var_A']] performance_dict = {'cat_var_A': 1.0, 'cat_...
_log_on_failure_all class TestSlowQueue(): _log_on_failure def setup_class(cls): cls.cwd = os.getcwd() cls.t = tempfile.mkdtemp() os.chdir(cls.t) cls.log_files = [] cls.multiplexers = [] try: port_genesis = (DEFAULT_PORT + 10) temp_dir_gen ...
class ProductCatalogImageSettingsOperation(AbstractObject): def __init__(self, api=None): super(ProductCatalogImageSettingsOperation, self).__init__() self._isProductCatalogImageSettingsOperation = True self._api = api class Field(AbstractObject.Field): transformation_type = 'tra...
def test_dstdirs_to_furthest_phase() -> None: all_jobs = [job_w_dstdir_phase('/plots1', job.Phase(1, 5)), job_w_dstdir_phase('/plots2', job.Phase(1, 1)), job_w_dstdir_phase('/plots2', job.Phase(3, 1)), job_w_dstdir_phase('/plots2', job.Phase(2, 1)), job_w_dstdir_phase('/plots3', job.Phase(4, 1))] assert (manage...
def test_with_gen_kw(copy_case, storage): copy_case('snake_oil') ert_config = ErtConfig.from_file('snake_oil.ert') experiment_id = storage.create_experiment(parameters=ert_config.ensemble_config.parameter_configuration) prior_ensemble = storage.create_ensemble(experiment_id, name='prior', ensemble_size=...
class InMemoryAttribute(IAttribute): def __init__(self, pk, **kwargs): self.id = pk self.pk = pk for (key, value) in kwargs.items(): if (key == 'value'): self.value = value elif (key == 'lock_storage'): self.lock_storage = value ...
class TestUpdateModel(): def setup_class(cls): cred = testutils.MockCredential() firebase_admin.initialize_app(cred, {'projectId': PROJECT_ID}) ml._MLService.POLL_BASE_WAIT_TIME_SECONDS = 0.1 def teardown_class(cls): testutils.cleanup_apps() def _url(project_id, model_id): ...
class OptionSeriesHistogramSonificationTracksMappingHighpassResonance(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 workflow_expect_event_tuples(workflow: Workflow) -> Set[EventKeyTuple]: result_keys = set() for (task_name, rules) in workflow.rules.items(): for rule in rules: keys = expect_keys_to_tuple_set(workflow.namespace, rule.condition.expect_event_keys) result_keys = (result_keys | ...
class OptionSeriesPictorialSonificationContexttracksMappingHighpass(Options): def frequency(self) -> 'OptionSeriesPictorialSonificationContexttracksMappingHighpassFrequency': return self._config_sub_data('frequency', OptionSeriesPictorialSonificationContexttracksMappingHighpassFrequency) def resonance(s...
.skip def test_molcas_s1_opt(): path = Path(os.path.dirname(os.path.abspath(__file__))) xyz_fn = (path / 'trans_butadien.xyz') inporb_fn = (path / 'butadien_vdzp.RasOrb') geom = geom_from_xyz_file(xyz_fn) kwargs = {'basis': 'ano-rcc-vdzp', 'inporb': inporb_fn, 'charge': 0, 'mult': 1, 'roots': 5, 'md...
def setup_logger(name, log_file, level=logging.INFO, formatter=None): if (not formatter): formatter = logging.Formatter('%(asctime)s\t%(levelname)s\t%(message)s') handler = RotatingFileHandler(log_file, maxBytes=, backupCount=50) handler.setFormatter(formatter) logger = logging.getLogger(name) ...
class TaxAgencyTests(unittest.TestCase): def test_unicode(self): transfer = Transfer() transfer.Amount = 100 self.assertEqual(str(transfer), '100') def test_valid_object_name(self): obj = Transfer() client = QuickBooks() result = client.isvalid_object_name(obj.qbo...
.parametrize('max_age', [0, 300]) def test_yaml_loader_without_cache(tmpdir, mocker, yaml_string, expected_from_loader, max_age): mock_resp = mocker.Mock() mock_resp.status_code = 200 mock_resp.text = yaml_string mock_get = mocker.patch('requests.Session.get', return_value=mock_resp) mock_mal = mock...
class CreateRevisionFollowTest(TestBase): def testCreateRevisionFollow(self): reversion.register(TestModel, follow=('related',)) reversion.register(TestModelRelated) obj_related = TestModelRelated.objects.create() with reversion.create_revision(): obj = TestModel.objects....
def extractHiohbyeTranslations(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol or frag)) or ('preview' in item['title'].lower())): return None if ('The Corpse King Confuses the World, All Seven Husbands Are Devils' in item['tags']): ret...
def test(): assert (('token1.similarity(token2)' in __solution__) or ('token2.similarity(token1)' in __solution__)), 'Voce esta comparando a similaridade entre os dois tokens?' assert (0 <= float(similarity) <= 1), 'O valor da similaridade deve ser um numero de ponto flutuante. Voce fez este calculo corretament...
class LayoutEukOgs(TreeLayout): def __init__(self, name='OGs euk', text_color='grey'): super().__init__(name, aligned_faces=True) self.text_color = text_color def set_node_style(self, node): if node.is_leaf: if node.props.get('OG_euk'): OG = node.props.get('OG...
def test_machine_should_not_allow_transitions_from_final_state(): with pytest.raises(exceptions.InvalidDefinition): class CampaignMachine(StateMachine): draft = State(initial=True) producing = State() closed = State(final=True) add_job = ((draft.to(draft) | pr...
class TestESP32FlashHeader(BaseTestCase): def test_16mb(self): ELF = 'esp32-app-template.elf' BIN = 'esp32-app-template.bin' try: self.run_elf2image('esp32', ELF, extra_args=['--flash_size', '16MB', '--flash_mode', 'dio', '--min-rev', '1']) with open(BIN, 'rb') as f: ...
class OptionSeriesTreegraphAccessibilityPoint(Options): def dateFormat(self): return self._config_get(None) def dateFormat(self, text: str): self._config(text, js_type=False) def dateFormatter(self): return self._config_get(None) def dateFormatter(self, value: Any): self....
class ClickType(Enum): SINGLE = auto() DOUBLE = auto() def from_click_times(cls, last_click_time, previous_click_time) -> 'ClickType': if (previous_click_time is None): return cls.SINGLE if ((last_click_time - previous_click_time) < _DOUBLE_CLICK_THRESHOLD_SECONDS): r...
class LiteEthPHYRGMIIRX(LiteXModule): def __init__(self, pads, rx_delay=2e-09, usp=False): self.source = source = stream.Endpoint(eth_phy_description(8)) rx_ctl_ibuf = Signal() rx_ctl_idelay = Signal() rx_ctl = Signal() rx_data_ibuf = Signal(4) rx_data_idelay = Signal...
def get_log_rhos(target_action_log_probs: List[TorchActionType], behaviour_action_log_probs: List[TorchActionType]) -> List[torch.Tensor]: log_rhos = list() with torch.no_grad(): for (step_target_action_log_probs, step_behaviour_action_log_probs) in zip(target_action_log_probs, behaviour_action_log_prob...
.xfail(reason='Test case should fail because of wrong input.') def test_significant_one_gene_bigwig_fail(): outfile = NamedTemporaryFile(suffix='.tar.gz', delete=False) outfile.close() args = '-f {} -o {} -om {} -omn {} -oft {}'.format((ROOT + 'chicSignificantInteractions/significantInteractions_dual.hdf5')...
def test_make_hash(): assert (make_hash({'a': 1}) == make_hash({'a': 1})) assert (make_hash({'a': 1}) != make_hash({'a': 2})) assert (make_hash({'a': 1, 'b': 2}) == make_hash({'a': 1, 'b': 2})) assert (make_hash({'a': 1, 'b': 2}) != make_hash({'a': 2, 'b': 1})) def make_complex_object(): ret...
class Migration(migrations.Migration): dependencies = [('awards', '0095_auto__1620'), ('references', '0058_bureautitlelookup'), ('search', '0009_awardsearch_view_drop')] operations = [CreateExtension('intarray'), CreateExtension('pg_trgm'), migrations.CreateModel(name='SubawardSearch', fields=[('broker_created_...
def extractAshtranslationsWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('Someone Explain This Situation!', 'Someone Explain This Situation!', 'translated'), ('Som...
class SaplingApi(ProviderInterface, TextInterface): provider_name = 'sapling' def __init__(self, api_keys: Optional[Dict]=None) -> None: self.api_settings = load_provider(ProviderDataEnum.KEY, self.provider_name, api_keys=(api_keys or {})) self.api_key = self.api_settings['key'] self.url...
class MutualAuthenticationResponseAttributes(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(): ...
def test_transform_interface_to_typed_interface_with_docstring(): def z(a: int, b: str) -> typing.Tuple[(int, str)]: ... our_interface = transform_function_to_interface(z, Docstring(callable_=z)) typed_interface = transform_interface_to_typed_interface(our_interface) assert (typed_interface.inpu...
def main(): N = 5 max_length = 10 hidden_size = 2 encodings = pos_encodings(max_length, hidden_size) print(np.linalg.norm((encodings[2] - encodings[0]))) print(np.linalg.norm((encodings[3] - encodings[1]))) print(np.linalg.norm((encodings[4] - encodings[2]))) print(np.linalg.norm((encodi...
def quadrupole3d_44(ax, da, A, bx, db, B, R): result = numpy.zeros((6, 15, 15), dtype=float) x0 = (0.5 / (ax + bx)) x1 = ((ax + bx) ** (- 1.0)) x2 = ((- x1) * ((ax * A[0]) + (bx * B[0]))) x3 = ((- x2) - A[0]) x4 = ((- x2) - B[0]) x5 = ((ax * bx) * x1) x6 = numpy.exp(((- x5) * ((A[0] - B[...
def test_get_exceptions_with_intersections(tmp_path: Path): exceptions = {'tests/': {'pyflakes': ['+*']}, '**/test.py': {'pycodestyle': ['+*']}} tests_dir = (tmp_path / 'tests') tests_dir.mkdir() test_file_path = (tests_dir / 'test.py') test_file_path.touch() result = get_exceptions(path=test_fi...
class BudgetTestBase(unittest.TestCase): def setUp(self): super(BudgetTestBase, self).setUp() from stalker import Status self.status_wfd = Status(name='Waiting For Dependency', code='WFD') self.status_rts = Status(name='Ready To Start', code='RTS') self.status_wip = Status(na...
def speedMenu(): while True: try: clear() print('\n At what speed would you like the AI to play?') print('\n 1. Slow enough to watch the game') print(' 2. Full speed ahead') n = input('\n Option: ') choices(n) except ValueError:...
class table_desc_stats_reply(stats_reply): version = 6 type = 19 stats_type = 14 def __init__(self, xid=None, flags=None, entries=None): if (xid != None): self.xid = xid else: self.xid = None if (flags != None): self.flags = flags else:...
def blockedwell_from_roxar(project, gname, bwname, wname, lognames=None, ijk=True, realisation=0): obj = BlockedWell(*([0.0] * 3), '', pd.DataFrame({_AttrName.XNAME.value: [], _AttrName.YNAME.value: [], _AttrName.ZNAME.value: []})) _blockedwell_roxapi.import_bwell_roxapi(obj, project, gname, bwname, wname, logn...
('func_name, func, value, expected', [param('foo_1', F.foo1, 'foo_1(10)', 'int:10', id='foo_1(10)'), param('foo_1', F.foo1, 'foo_1(value=10)', 'int:10', id='foo_1(value=10)'), param('foo_2', F.foo2, "foo_2('10',10)", 'str:10,int:10', id="foo_2('10',10)"), param('empty', F.empty, 'empty()', 10, id='empty()'), param('sum...
class InsertConsts2(SqlStatement): table: Id cols: List[str] tuples: list def _compile(self, qb): assert self.tuples, self if (get_db().target == oracle): values_q = join_sep([((['SELECT '] + join_comma(([t] for t in tpl))) + [' FROM dual']) for tpl in self.tuples], ' UNION A...
class HelpForParameters(object): header = attr.ib() footer = attr.ib() sections = attr.ib() after = attr.ib() def blank_from_signature(cls, signature): s = util.OrderedDict(((LABEL_POS, util.OrderedDict()), (LABEL_OPT, util.OrderedDict()), (LABEL_ALT, util.OrderedDict()))) for p in _...
def test_perm_logarithmic_map(tmpdir, generate_plot): mysurf = xtgeo.surface_from_file(SFILE2) myplot = Map() myplot.canvas(title='PERMX normal scale') myplot.colormap = 'rainbow' myplot.plot_surface(mysurf, minvalue=0, maxvalue=6000, xlabelrotation=45, logarithmic=True) if generate_plot: ...
class OldFalconDecoderLayer(Module): def __init__(self, layer_config: TransformerLayerConfig, *, device: Optional[torch.device]=None): super().__init__() attention_config = layer_config.attention if (attention_config.rotary_embeddings is None): raise ValueError('Falcon attention ...
class RichMediaElement(AbstractObject): def __init__(self, api=None): super(RichMediaElement, self).__init__() self._isRichMediaElement = True self._api = api class Field(AbstractObject.Field): element = 'element' element_type = 'element_type' name = 'name' _f...
def _function_over_one_var(repr_func, raw_func, x, out=None, out_like=None, sizing='optimal', method='raw', optimal_size=None, **kwargs): if (not isinstance(x, Fxp)): x = Fxp(x) (signed, _, n_int, n_frac) = _get_sizing([x], sizing=sizing, method=method, optimal_size=optimal_size) if (out is not None...
.asyncio .workspace_host class TestGetPermission(): async def test_unauthorized(self, unauthorized_api_assertions: HTTPXResponseAssertion, test_client_api: test_data: TestData): permission = test_data['permissions']['castles:create'] response = (await test_client_api.get(f'/permissions/{permission....
.parametrize('rule, source, expected', [pytest.param(UseFunctionLevelImports, '\n from functools import reduce\n from operator import add\n import dataclass\n\n def something():\n a = reduce(x, y)\n b = add(a, a)\n return b\n\n ...
_after def scaffold_item(ctx: Context, item_type: str, item_name: str) -> None: validate_package_name(item_name) author_name = ctx.agent_config.author loader = getattr(ctx, f'{item_type}_loader') default_config_filename = globals()[f'DEFAULT_{item_type.upper()}_CONFIG_FILE'] item_type_plural = (item...
class StructuredDataset(DataClassJSONMixin): uri: typing.Optional[str] = field(default=None, metadata=config(mm_field=fields.String())) file_format: typing.Optional[str] = field(default=GENERIC_FORMAT, metadata=config(mm_field=fields.String())) def columns(cls) -> typing.Dict[(str, typing.Type)]: re...
def THD(signal, fs): signal = (np.asarray(signal) + 0.0) signal -= mean(signal) window = general_cosine(len(signal), flattops['HFT248D']) windowed = (signal * window) del signal f = rfft(windowed) i = argmax(abs(f)) true_i = parabolic(log(abs(f)), i)[0] print(('Frequency: %f Hz' % (f...
('cuda.index_select.func_decl') def gen_function_decl(func_attrs) -> str: backend_spec = CUDASpec() x = func_attrs['inputs'][0] input_type = backend_spec.dtype_to_backend_type(x._attrs['dtype']) return FUNC_DECL_TEMPLATE.render(func_name=func_attrs['name'], input_type=input_type, index_type=backend_spec...
def send_status(status: 'Status'): global middlewares, master if (status is None): return s: 'Optional[Status]' = status for i in middlewares: s = i.process_status(cast('Status', s)) if (s is None): return status = cast('Status', s) status.verify() status....
_validator def validate_build_nvrs(request, **kwargs): for build in (request.validated.get('builds') or []): try: cache_nvrs(request, build) if request.validated.get('from_tag'): (n, v, r) = request.buildinfo[build]['nvr'] release = request.db.query(Re...
(urls.RULE_TARGET_DETAIL, status_code=HTTP_200_OK, response_model=schemas.RuleTarget, dependencies=[Security(verify_oauth_client, scopes=[scope_registry.RULE_READ])]) def get_rule_target(*, policy_key: FidesKey, rule_key: FidesKey, rule_target_key: FidesKey, db: Session=Depends(deps.get_db)) -> RuleTarget: return g...
def load_ecdsa_signing_key(keyfile): try: sk = ecdsa.SigningKey.from_pem(keyfile.read()) except ValueError: raise esptool.FatalError('Incorrect ECDSA private key specified. Please check algorithm and/or format.') if (sk.curve not in [ecdsa.NIST192p, ecdsa.NIST256p]): raise esptool.Fa...
class OptionSeriesHistogramSonificationDefaultinstrumentoptionsMappingFrequency(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text...
class TestExpr(): def __init__(self): pass def run(self): for method in dir(self): if method.startswith('test_'): print(method, '...', end=' ') getattr(self, method)() print('OK!') def test_free_variables(self): assert (((x ...
class WcRegexp(util.Immutable, Generic[AnyStr]): _include: tuple[(Pattern[AnyStr], ...)] _exclude: (tuple[(Pattern[AnyStr], ...)] | None) _real: bool _path: bool _follow: bool _hash: int __slots__ = ('_include', '_exclude', '_real', '_path', '_follow', '_hash') def __init__(self, include...
.skipif(('pandas' not in sys.modules), reason='Pandas is not installed.') def test_wf1_with_sql(): import pandas as pd sql = SQLTask('my-query', query_template="SELECT * FROM hive.city.fact_airport_sessions WHERE ds = '{{ .Inputs.ds }}' LIMIT 10", inputs=kwtypes(ds=datetime.datetime), outputs=kwtypes(results=Fl...