code
stringlengths
281
23.7M
('StrictMock') def strict_mock(context): def assertRaisesWithMessage(self, exception, msg): with self.assertRaises(exception) as cm: (yield) ex_msg = str(cm.exception) self.assertEqual(ex_msg, msg, 'Expected exception {}.{} message to be\n{}\nbut got\n{}.'.format(exception.__modu...
def validate_not_monthly_to_quarterly(source_fiscal_period, destination_fiscal_period): if ((not is_quarter_final_period(source_fiscal_period)) and is_quarter_final_period(destination_fiscal_period)): raise RuntimeError('Unfortunately, copying from a monthly period to a quarterly period is not supported. T...
('config_name,overrides,expected', [param('legacy_override_hydra', [], raises(ConfigCompositionException, match=re.escape(dedent(" Multiple values for hydra/help. To override a value use 'override hydra/help: custom1'"))), id='legacy_override_hydra-error'), param('legacy_override_hydra2', [], rai...
class ChartJs(JsCanvas.Canvas): display_value = 'inline-block' def __init__(self, component: primitives.HtmlModel, js_code: str=None, set_var: bool=True, is_py_data: bool=True, page: primitives.PageModel=None): self.htmlCode = (js_code if (js_code is not None) else component.html_code) (self.var...
def execute(function, filenames, verbose): if PY3: name = function.__name__ elif hasattr(function, 'unittest_name'): name = function.unittest_name else: name = function.func_name if verbose: sys.stdout.write((('=' * 75) + '\n')) sys.stdout.write(('%s(%s)...\n' % (...
class role_request(message): version = 3 type = 24 def __init__(self, xid=None, role=None, generation_id=None): if (xid != None): self.xid = xid else: self.xid = None if (role != None): self.role = role else: self.role = 0 ...
.django_db def test_agency_count_invalid_defc(client, monkeypatch, disaster_account_data, helpers, elasticsearch_award_index): setup_elasticsearch_test(monkeypatch, elasticsearch_award_index) helpers.patch_datetime_now(monkeypatch, 2022, 12, 31) resp = helpers.post_for_count_endpoint(client, url, ['ZZ']) ...
def test_chained_cause_exception(elasticapm_client): try: try: (1 / 0) except ZeroDivisionError as zde: raise ValueError('bla') from zde except ValueError: elasticapm_client.capture_exception() error = elasticapm_client.events[ERROR][0] assert (error['exce...
class OptionPlotoptionsColumnSonificationDefaultinstrumentoptions(Options): def activeWhen(self) -> 'OptionPlotoptionsColumnSonificationDefaultinstrumentoptionsActivewhen': return self._config_sub_data('activeWhen', OptionPlotoptionsColumnSonificationDefaultinstrumentoptionsActivewhen) def instrument(se...
def transfer(frm, to, value, height, hash): if ((len(deps) <= height) or (deps[height] != hash)): return False if (not (is_account_state_active(state[to]) and (height >= state[to].yes_dep.height))): return False if ((frm is not None) and (not (is_account_state_active(state[frm]) and (height ...
def _retrieveInfo(info, data): if ('treatment' in info): if ('meta' not in data): data['meta'] = {} data['meta']['treatment_diff'] = info['treatment'].get('diff', '') data['meta']['treatment_version'] = info['treatment'].get('version', '') data['meta']['treatment_commit']...
def update_item_config(item_type: str, package_path: Path, **kwargs: Any) -> None: item_config = load_item_config(item_type, package_path) for (key, value) in kwargs.items(): setattr(item_config, key, value) config_filepath = os.path.join(package_path, item_config.default_configuration_filename) ...
class bsn_flow_idle_enable_get_request(bsn_header): version = 6 type = 4 experimenter = 6035143 subtype = 38 def __init__(self, xid=None): if (xid != None): self.xid = xid else: self.xid = None return def pack(self): packed = [] pac...
def extract_from_pdf(response): pdf_content = response.content pdf_reader = PyPDF2.PdfFileReader(io.BytesIO(pdf_content)) pdf_text = '' for page_num in range(pdf_reader.getNumPages()): pdf_text += pdf_reader.getPage(page_num).extractText() pdf_text = re.sub('\\r\\n|\\r|\\n', ' ', pdf_text) ...
class ClusterResourceAttributes(_common.FlyteIdlEntity): def __init__(self, attributes): self._attributes = attributes def attributes(self): return self._attributes def to_flyte_idl(self): return _matchable_resource.ClusterResourceAttributes(attributes=self.attributes) def from_f...
def populate_quantsarray(fname, feats_dir): arr = {} arr['fname'] = fname quant = np.load(fname) quant = (quant.astype(np.int64) + (2 ** 15)) assert (len(quant) > 1) coarse = (quant // 256) coarse_float = ((coarse.astype(np.float) / 127.5) - 1.0) fine = (quant % 256) fine_float = ((f...
class TestTwoColumns(I3LayoutScenario): def test_scenario(self): for params in self.layout_params(): self.senario(params) self._close_all() def layout(self, params: List) -> str: position = params[0] return f'2columns {position}' def layout_params(self) -> Lis...
class IamPolicyTest(ForsetiTestCase): def setUp(self): self.members = ['user:test-', 'group:test-', 'serviceAccount:test-.com', 'allUsers', 'allAuthenticatedUsers', 'user:*', 'serviceAccount:**.gserviceaccount.com', 'user:*'] self.test_members = ['user:test-', 'serviceAccount:.com', 'user:', 'allUse...
def prepare_middleware_ws(middleware: Iterable) -> Tuple[(list, list)]: request_mw = [] resource_mw = [] for component in middleware: process_request_ws = util.get_bound_method(component, 'process_request_ws') process_resource_ws = util.get_bound_method(component, 'process_resource_ws') ...
class _MultiMethod(): def __init__(self, name): self.name = name self.typemap = {} def __call__(self, *args): types = tuple((arg.__class__ for arg in args)) try: return self.typemap[types](*args) except KeyError: raise TypeError(('no match %s for t...
class TestGlyph(TestCase): def make_data(self): s = numpy.arange(0.0, 10.0, 0.01) s = numpy.reshape(s, (10, 10, 10)) s = numpy.transpose(s) v = numpy.zeros(3000, 'd') v[1::3] = 1.0 v = numpy.reshape(v, (10, 10, 10, 3)) return (s, v) def set_view(self, s): ...
.parametrize('data', ({}, {'seed_version': (MIGRATION_FIRST - 1)}, {'seed_version': (MIGRATION_FIRST + 1)})) def test_database_store_from_text_store_initial_version(tmp_path, data) -> None: wallet_path = os.path.join(tmp_path, 'database') text_store = TextStore(wallet_path, data=data) try: with pyte...
class TaskStatusWorkflowTestCase(unittest.TestCase): def setUp(self): super(self.__class__, self).setUp() from stalker import User self.test_user1 = User(name='Test User 1', login='tuser1', email='', password='secret') self.test_user2 = User(name='Test User 2', login='tuser2', email=...
class AppModuleGroup(): def __init__(self, *modules: AppModule): self.modules = modules def module(self, import_name: str, name: str, template_folder: Optional[str]=None, template_path: Optional[str]=None, static_folder: Optional[str]=None, static_path: Optional[str]=None, url_prefix: Optional[str]=None...
def mk_segtiles(tiles): segtiles = {} baseaddrs = {} for (tile_name, tile) in tiles.items(): for (block_name, block) in tile['bits'].items(): baseaddrs.setdefault(block['baseaddr'], []).append((block['offset'], tile_name, block, block_name)) for (baseaddr, values) in baseaddrs.items(...
def render_plugin(values) -> jinja2.Template: env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')), auto_reload=False, keep_trailing_newline=True, autoescape=True) template = env.get_template('new_plugin.py.tmpl') return template.render(**values)
class DefinitionsTransform(SphinxTransform): default_priority = 500 def apply(self): for kind in KINDS: storage = get_storage(self.env, kind) for node in self.document.findall(DefIdNode): if (node['def_kind'] != kind.NAME): continue ...
def train_model(train_file, eval_file, scale, output_dir): train_dataset = TrainAugmentDataset(train_file, scale=scale) val_dataset = EvalDataset(eval_file) training_args = TrainingArguments(output_dir=output_dir, num_train_epochs=1000) config = A2nConfig(scale=scale) model = A2nModel(config) tr...
class TestGeneratorInsertRouterPath(): def test_should_insert_router_import(self, monkeypatch, fake_project, fake_router): monkeypatch.chdir(fake_project['root']) insert_router_import('fake_project', 'fake_router') insert_router_import('fake_project', 'fake_router') assert (fake_rout...
class BaseTest(unittest.TestCase): def __str__(self): return self.id().replace('.runTest', '') def setUp(self): oftest.open_logfile(str(self)) logging.info(('** START TEST CASE ' + str(self))) def tearDown(self): logging.info(('** END TEST CASE ' + str(self)))
class OnlyExecutableFilter(): def __init__(self, parent): self.parent = parent def update(self): pass def filter(self, tasks): filtered_tasks = [] execution_flags = [64, 16, 32, 128] for task in tasks: for segment in task.segments: if (segm...
def _get_access_mask_string(access_mask, mappings, access_strings): if (access_mask & ): access_mask |= mappings[0] if (access_mask & ): access_mask |= mappings[1] if (access_mask & ): access_mask |= mappings[2] if (access_mask & ): access_mask |= mappings[3] string =...
class OpenAIAutomataAgent(Agent): ASSISTANT_INTRO: Final = "Hello, I am Automata, OpenAI's most skilled coding system. How may I assist you today?" ASSISTANT_INITIALIZE_MESSAGE: Final = 'Thoughts:\\nFirst, I will initialize myself. Then I will continue on to carefully consider the user task and carry out the ne...
def main(args=None): args = parse_arguments().parse_args(args) viewpointObj = Viewpoint() (referencePoints, gene_list) = viewpointObj.readReferencePointFile(args.referencePoints) referencePointsPerThread = (len(referencePoints) // args.threads) queue = ([None] * args.threads) process = ([None] *...
class CoreAxSweeper(Sweeper): def __init__(self, ax_config: AxConfig, max_batch_size: Optional[int]): self.config: Optional[DictConfig] = None self.launcher: Optional[Launcher] = None self.hydra_context: Optional[HydraContext] = None self.job_results = None self.experiment: E...
def test_rename_var(): string = write_rpc_request(1, 'initialize', {'rootPath': str(test_dir)}) file_path = (test_dir / 'test_prog.f08') string += rename_request('str_rename', file_path, 5, 25) (errcode, results) = run_request(string) assert (errcode == 0) ref = {} ref[path_to_uri(str(file_p...
.parametrize('test_input, expected', [('fullpath', False), ('paged', False)]) def test_searchsploit_results_parser_defaults(test_input, expected): parsed = searchsploit_results_parser.parse_known_args(['FullScan', '--target-file', 'required'])[0] assert (getattr(parsed, test_input) == expected)
class MWizard(HasTraits): def next(self): page = self.controller.get_next_page(self.controller.current_page) self._show_page(page) def previous(self): page = self.controller.get_previous_page(self.controller.current_page) self._show_page(page) return def _create_conte...
class StreamOutput(Text): def __init__(self, master): super().__init__(master) self.buffer = [] self.tag_configure('err', foreground='red') def install(self): self.__enter__() return def unistall(self): self.__exit__() return def __enter__(self): ...
class SecretsManagerService(abc.ABC): def create_secret(self, secret_name: str, secret_value: str, tags: Optional[Dict[(str, str)]]=None) -> str: pass def get_secret(self, secret_id: str) -> StringSecret: pass async def create_secret_async(self, secret_name: str, secret_value: str, tags: Opt...
def _parse_meta_data(meta_data_string: str) -> dict[(str, ((str | bool) | int))]: try: meta_data_string = meta_data_string.replace("\\'", "'") meta_data = yaml.safe_load(f"{{{meta_data_string.replace('=', ': ')}}}") assert isinstance(meta_data, dict) return meta_data except (Pars...
def K_to_K_tilda_str(K): emsg1 = 'K_to_K_tilda K len is {}. it should be {}'.format(len(K), Ar_KEY_LEN) assert (len(K) == Ar_KEY_LEN), emsg1 emsg2 = 'K_to_K_tilda K type is {}. it should be {}'.format(type(K), str) assert (type(K) == str), emsg2 K_tilda = '' K_tilda += chr(((ord(K[0]) + 233) % 2...
_figures_equal(extensions=['png']) def test_plot_hist(fig_test, fig_ref): test_data = TestData() pd_flights = test_data.pd_flights()[['DistanceKilometers', 'DistanceMiles', 'FlightDelayMin', 'FlightTimeHour']] ed_flights = test_data.ed_flights()[['DistanceKilometers', 'DistanceMiles', 'FlightDelayMin', 'Fli...
def expire_invitations(): from frappe.utils import add_days, now days = 3 invitations_to_expire = frappe.db.get_all('GP Invitation', filters={'status': 'Pending', 'creation': ['<', add_days(now(), (- days))]}) for invitation in invitations_to_expire: invitation = frappe.get_doc('GP Invitation', ...
def validate_model(model, val_loader): print('Validating the model') model.eval() y_true = [] y_pred = [] fnames = [] running_loss = 0.0 criterion = nn.CrossEntropyLoss() with torch.no_grad(): for (step, (mfcc, lid, lengths, fname)) in enumerate(val_loader): (sorted_l...
.parametrize('toc_file', ('_toc_numbered.yml', '_toc_numbered_depth.yml', '_toc_numbered_parts.yml', '_toc_numbered_parts_subset.yml', '_toc_numbered_depth_parts_subset.yml')) def test_toc_numbered_multitoc_numbering_false(toc_file, cli, build_resources, file_regression): (books, tocs) = build_resources config ...
.django_db def test_ignore_funding_for_unselected_defc(client, monkeypatch, helpers, defc_codes, basic_ref_data, year_2_gtas_covid, year_2_gtas_covid_2): helpers.patch_datetime_now(monkeypatch, LATE_YEAR, EARLY_MONTH, 25) helpers.reset_dabs_cache() resp = client.get((OVERVIEW_URL + '?def_codes=M,A')) as...
class OptionPlotoptionsColumnSonificationDefaultinstrumentoptionsMappingHighpassFrequency(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(...
def plot_partial_pooling_model(samples: MonteCarloSamples, df: pd.DataFrame) -> Figure: diagnostics_data = _sample_data_prep(samples, df) hdi_df = az.hdi(diagnostics_data, hdi_prob=0.89).to_dataframe() hdi_df = hdi_df.T.rename(columns={'lower': 'hdi_11%', 'higher': 'hdi_89%'}) summary_df = az.summary(di...
def test_documentLib(tmpdir): tmpdir = str(tmpdir) testDocPath1 = os.path.join(tmpdir, 'testDocumentLibTest.designspace') doc = DesignSpaceDocument() a1 = AxisDescriptor() a1.tag = 'TAGA' a1.name = 'axisName_a' a1.minimum = 0 a1.maximum = 1000 a1.default = 0 doc.addAxis(a1) d...
def run(args): import re from .. import PhyloTree, NCBITaxa if ((not args.tree) and (not args.info) and (not args.descendants)): args.tree = True ncbi = NCBITaxa(args.dbfile, args.taxdumpfile) if args.create: sys.exit(0) all_taxids = {} all_names = set() queries = [] ...
class AirflowTaskResolver(TrackedInstance, TaskResolverMixin): def name(self) -> str: return 'AirflowTaskResolver' ('Load airflow task') def load_task(self, loader_args: typing.List[str]) -> typing.Union[(airflow_models.BaseOperator, airflow_sensors.BaseSensorOperator, airflow_triggers.BaseTrigger)]...
def test_id_included(caplog): test_id = '1.1' test_level = 1 custom_config = SimpleNamespace(includes=['1.1'], excludes=None, level=0, log_level='DEBUG') test = CISAudit(config=custom_config) result = test._is_test_included(test_id, test_level) assert (caplog.records[0].msg == f'Checking whether...
class OptionPlotoptionsWindbarbSonificationDefaultinstrumentoptionsMappingVolume(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...
class Test_SetWindowSet(): () def wrapper(self): return Mock(name='wrapper') () def wset(self, *, key, table, wrapper): return SetWindowSet(key, table, wrapper) def test_add(self, *, wset): event = Mock(name='event') wset._apply_set_operation = Mock() wset.add...
class FillMissingWithMean(elmdptt.TaskOneToOne): col_names = luigi.Parameter() def actual_task_code(self, df: pd.DataFrame): if (self.col_names == 'all'): df.fillna(df.mean(), inplace=True) else: for col_name in str(self.col_names).split(','): df[col_name]...
.WebInterfaceUnitTestConfig(database_mock_class=DbMock) class TestShowStatistic(): def test_no_stats_available(self, test_client): DbMock.result = None rv = test_client.get('/statistic') assert (b'General' not in rv.data) assert (b'<strong>No statistics available!</strong>' in rv.dat...
def main(): config.load() postgres = BackendDbInterface() mongo_config = ConfigParser() mongo_config.read(((Path(__file__).parent / 'config') / 'migration.cfg')) try: with ConnectTo(MigrationMongoInterface, mongo_config) as db: with Progress(DESCRIPTION, BarColumn(), PERCENTAGE, ...
def test_get_invalid_business_category_display_names(): business_category_field_names_list = _get_all_business_category_field_names() business_category_field_names_list.insert(0, 'invalid_name_1') business_category_field_names_list.append('invalid_name_2') business_category_display_names_list = _get_all...
def test_resize(): assert (Integer.int32_t().resize(64) == Integer.int64_t()) assert (Float.float().resize(64) == Float.double()) assert ((Integer.uint8_t() + Integer.int16_t()) == Integer(24, signed=False)) assert ((CustomType.void() + CustomType.void()) == CustomType.void()) assert ((CustomType.bo...
def test_simple_plot(tmpdir, show_plot, generate_plot): mywell = xtgeo.well_from_file(USEFILE4) mysurfaces = [] mysurf = xtgeo.surface_from_file(USEFILE2) for i in range(10): xsurf = mysurf.copy() xsurf.values = (xsurf.values + (i * 20)) xsurf.name = f'Surface_{i}' mysurf...
def flatten_coords(in_coords): if isinstance(in_coords, g_l_y_f.GlyphComponent): return in_coords.getComponentInfo() elif hasattr(in_coords, 'coordinates'): ret = list(in_coords.coordinates) ret.sort() return tuple(ret) elif hasattr(in_coords, 'components'): ret = [fl...
class SkeletonSyncer(Service, Generic[TChainPeer]): _skip_length = (MAX_HEADERS_FETCH + 1) max_reorg_depth = MAX_SKELETON_REORG_DEPTH _fetched_headers: 'asyncio.Queue[Tuple[BlockHeaderAPI, ...]]' def __init__(self, chain: AsyncChainAPI, db: BaseAsyncHeaderDB, peer: TChainPeer, launch_strategy: SyncLaunc...
def manage_prescriptions(invoiced, ref_dt, ref_dn, dt, created_check_field): created = frappe.db.get_value(ref_dt, ref_dn, created_check_field) if created: doc_created = frappe.db.get_value(dt, {'prescription': ref_dn}) frappe.db.set_value(dt, doc_created, 'invoiced', invoiced)
class SynthesizeRule(SemanticRule): def __init__(self, func, arguments, dependencies, name, source_location=None, annotations=None, target=None): super().__init__(func, arguments, dependencies, name, source_location, annotations) self.target = ('self', (target or name)) def __repr__(self): ...
def test_empty_endless_loop(task): task.graph.add_node((block := BasicBlock(0, instructions=[]))) task.graph.add_edge(UnconditionalEdge(block, block)) PatternIndependentRestructuring().run(task) context = LogicCondition.generate_new_context() while_loop = WhileLoopNode(LogicCondition.initialize_true...
class ASTComparator(): def __init__(self): self._color_of_node: Dict[(AbstractSyntaxTreeNode, Color)] = dict() def compare(cls, ast_forest_1: AbstractSyntaxInterface, ast_forest_2: AbstractSyntaxInterface) -> bool: if (id(ast_forest_1) == id(ast_forest_2)): return True ast_fo...
def exploit(start): global p def go(aslr=False): global p p = process('./asciishop', aslr=True, env={}) if (not aslr): gdb.attach(p, gdbscript='\n c\n ') else: gdb.attach(p, gdbscript='\n #break *0xd0f\n #break *0xb8f\n ...
class OFPMatch(StringifyMixin): def __init__(self, type_=None, length=None, _ordered_fields=None, **kwargs): super(OFPMatch, self).__init__() self._wc = FlowWildcards() self._flow = Flow() self.fields = [] self.type = ofproto.OFPMT_OXM self.length = length if ...
class StalkerSceneAddAllShotOutputsOperator(bpy.types.Operator): bl_label = 'Add All Shot Outputs' bl_idname = 'stalker.scene_add_all_shot_outputs_op' stalker_entity_id = bpy.props.IntProperty(name='stalker_entity_id') stalker_entity_name = bpy.props.StringProperty(name='stalker_entity_name') def ex...
class FilterBase(Filter): __version__ = 0 filter = Instance(tvtk.Object, allow_none=False, record=True) view = View(Group(Item(name='filter', style='custom', resizable=True, show_label=False), springy=True), scrollable=True, resizable=True) def setup_pipeline(self): f = self.filter if (f...
_from_version('1.8') def update_1_8(sim_dict: dict) -> dict: def fix_missing_scalar_field(mnt_dict: dict) -> dict: for (key, val) in mnt_dict['field_dataset'].items(): if (isinstance(val, str) and (val == 'XR.DATAARRAY')): mnt_dict['field_dataset'][key] = 'ScalarFieldDataArray' ...
class Animation(object): def equalize_node_speed(cls): start_frame = int(pm.playbackOptions(q=1, min=1)) end_frame = int(pm.playbackOptions(q=1, max=1)) selected_node = pm.selected()[0] node = pm.duplicate(selected_node, un=1, rr=1)[0] node.rename(('%s_Equalized#' % selected_...
class TestButtonEditorSimpleDemo(unittest.TestCase): def test_button_editor_simple_demo(self): demo = runpy.run_path(DEMO_PATH)['demo'] tester = UITester() with tester.create_ui(demo) as ui: button = tester.find_by_name(ui, 'my_button_trait') for index in range(5): ...
def run_adb_command(command: str) -> bool: command = f'adb {command}' if (not is_adb_installed()): raise ADBException(ADBExceptionTypes.ADB_NOT_INSTALLED) try: adb_root() subprocess.run(command, shell=True, check=True, text=True, capture_output=True) except subprocess.CalledProce...
def extractThenthvoidWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')] for (tagname, name, tl_type...
class setOption_result(): 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) a...
def manifest_paths(app_dir, flavours): possible_manifests = [(Path(app_dir) / 'AndroidManifest.xml'), (Path(app_dir) / 'src/main/AndroidManifest.xml'), (Path(app_dir) / 'src/AndroidManifest.xml'), (Path(app_dir) / 'build.gradle'), (Path(app_dir) / 'build-extras.gradle'), (Path(app_dir) / 'build.gradle.kts')] fo...
class FaucetUntaggedRestBcastIPv6RouteTest(FaucetUntaggedIPv6RouteTest): CONFIG = '\n nd_neighbor_timeout: 2\n max_resolve_backoff_time: 1\n interfaces:\n %(port_1)d:\n native_vlan: 100\n restricted_bcast_arpnd: true\n %(port_2)d:\n ...
def initialize(): global all_relocs all_relocs = {} for path in options.opts.reloc_addrs_paths: if (not path.exists()): continue with path.open() as f: sym_addrs_lines = f.readlines() prog_bar = progress_bar.get_progress_bar(sym_addrs_lines) prog_bar.s...
class OptionSeriesPolygonSonificationTracksMappingLowpassFrequency(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 TlsActivationResponse(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(...
class Vhdl(Generator, Jinja2): def __init__(self, rmap=None, path='regs.vhd', read_filler=0, interface='axil', **args): super().__init__(rmap, **args) self.path = path self.read_filler = read_filler self.interface = interface def validate(self): super().validate() ...
def test_anomalous_all_columns_anomalies(test_id: str, dbt_project: DbtProject): utc_today = datetime.utcnow().date() (test_date, *training_dates) = generate_dates(base_date=(utc_today - timedelta(1))) data: List[Dict[(str, Any)]] = [{TIMESTAMP_COLUMN: test_date.strftime(DATE_FORMAT), 'superhero': None} for...
class wallBreakerForm(QDialog, Ui_Wallbreaker): def __init__(self, parent=None): super(wallBreakerForm, self).__init__(parent) self.setupUi(self) self.setWindowOpacity(0.93) self.btnClassSearch.clicked.connect(self.classSearch) self.btnClassDump.clicked.connect(self.classDump...
def setup_to_pass(): shutil.copy('/etc/default/useradd', '/etc/default/useradd.bak') shutil.copy('/etc/shadow', '/etc/shadow.bak') shellexec("sed -i '/INACTIVE/ s/=.*/=30/' /etc/default/useradd") shellexec("sed -i -E '/(root|vagrant):/ s/0:99999:7::/0:99999:7:30:/' /etc/shadow") (yield None) shu...
def downgrade(): op.create_table('stacks', sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False), sa.Column('name', sa.TEXT(), autoincrement=False, nullable=False), sa.Column('description', sa.TEXT(), autoincrement=False, nullable=True), sa.Column('requirements', sa.TEXT(), autoincrement=False, nullable...
class DrQV2Builder(builders.ActorLearnerBuilder): def __init__(self, config: drq_v2_config.DrQV2Config): self._config = config def make_replay_tables(self, environment_spec: specs.EnvironmentSpec, policy: drq_v2_networks.DrQV2PolicyNetwork) -> List[reverb.Table]: del policy samples_per_i...
def load_tests(): if (fold_tests or verifier_failures): return for name in ['test_string_functions.toml', 'test_folding.toml', 'test_optimizer.toml']: data = eql.load_dump(eql.etc.get_etc_path(name)) for (test_name, contents) in sorted(data.items()): test_name = '{file}:{test...
.slow_integration_test def test_clone_subgroup_exclude_archived(): os.environ['GITLAB_URL'] = ' output = io_util.execute(['-p', '--print-format', 'json', '-a', 'exclude'], 60) obj = json.loads(output) assert (obj['children'][0]['name'] == 'Group Test') assert (obj['children'][0]['children'][0]['name...
def iter_slices(table, other, mode: str, keep_empty: bool): for (_c, bin_rows, src_rows) in by_shared_chroms(other, table, keep_empty): if (src_rows is None): for _ in range(len(bin_rows)): (yield pd.Index([], dtype='int64')) else: for (slc, _s, _e) in idx_ran...
class ACLMixin(object): _attr def permissions(cls): secondary_table = create_secondary_table(cls.__name__, 'Permission', cls.__tablename__, 'Permissions') return relationship('Permission', secondary=secondary_table) ('permissions') def _validate_permissions(self, key, permission): ...
class CmdReset(COMMAND_DEFAULT_CLASS): key = '' aliases = [''] locks = 'cmd:perm(reload) or perm(Developer)' help_category = 'System' def func(self): evennia.SESSION_HANDLER.announce_all(' Server resetting/restarting ...') evennia.SESSION_HANDLER.portal_reset_server()
class ThermoEntity(): def __init__(self, busnum=0, devnum=0, dtype=6675): self.busy = False self.initialized = False self.busnum = int(busnum) self.devnum = int(devnum) self.values = 0 try: self.spi = spidev.SpiDev() self.spi.open(self.busnum, ...
def test(): assert ((len(doc1.ents) == 2) and (len(doc2.ents) == 2) and (len(doc3.ents) == 2)), 'Attendu deux entites pour tous les exemples' assert any((((e.label_ == 'PER') and (e.text == 'PewDiePie')) for e in doc2.ents)), 'As-tu utilise le label pour PER correctement ?' assert any((((e.label_ == 'PER') ...
class TestAllowEventWithoutTransition(): def test_send_unknown_event(self, classic_traffic_light_machine): sm = classic_traffic_light_machine(allow_event_without_transition=True) assert sm.green.is_active sm.send('unknow_event') assert sm.green.is_active def test_send_not_valid_f...
class OptionPlotoptionsWaterfallSonificationDefaultinstrumentoptionsMappingHighpassFrequency(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 map...
class OptionSeriesAreasplinerangeSonificationDefaultinstrumentoptionsMappingFrequency(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...
def GetNormal(kwargs: dict) -> OutgoingMessage: compulsory_params = ['id'] optional_params = ['width', 'height', 'fov', 'intrinsic_matrix'] utility.CheckKwargs(kwargs, compulsory_params) msg = OutgoingMessage() msg.write_int32(kwargs['id']) msg.write_string('GetNormal') if ('intrinsic_matrix...
(name='api.vm.snapshot.tasks.vm_snapshot_cb', base=MgmtCallbackTask, bind=True) (error_fun=_vm_snapshot_cb_alert) def vm_snapshot_cb(result, task_id, vm_uuid=None, snap_id=None): snap = Snapshot.objects.select_related('vm').get(id=snap_id) vm = Vm.objects.get(uuid=vm_uuid) action = result['meta']['apiview']...