code
stringlengths
281
23.7M
class RocketGame(): def __init__(self): pygame.init() self.clock = pygame.time.Clock() self.settings = Settings() self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height)) pygame.display.set_caption('Rocket Game') self.rocket = R...
class StringField(CharField[str]): def prepare_value(self, value: Any, *, coerce: Optional[bool]=None) -> Optional[str]: if self.should_coerce(value, coerce): val = (str(value) if (not isinstance(value, str)) else value) if self.trim_whitespace: return val.strip() ...
class Migration(migrations.Migration): dependencies = [('django_etebase', '0006_auto__1040')] operations = [migrations.AlterField(model_name='collection', name='uid', field=models.CharField(db_index=True, max_length=43, validators=[django.core.validators.RegexValidator(message='Not a valid UID', regex='^[a-zA-Z...
class LongType(Type): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.name = LONG self.byte_size = (8 if (self.binary.config.MACHINE_ARCH == 'x64') else 4) def debug_info(self): bs = bytearray() bs.append(ENUM_ABBREV_CODE['BASE_TYPE_WITH_ENCODI...
def write_arbitrages(db_session, arbitrages: List[Arbitrage]) -> None: arbitrage_models = [] swap_arbitrage_ids = [] for arbitrage in arbitrages: arbitrage_id = str(uuid4()) arbitrage_models.append(ArbitrageModel(id=arbitrage_id, block_number=arbitrage.block_number, transaction_hash=arbitrag...
class AllAttendeeAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if (not self.request.user.is_authenticated()): return Attendee.objects.none() event_slug = self.forwarded.get('event_slug', None) event_user = EventUser.objects.filter(user=self.request.user,...
class SkewStabilization_1(object): def __init__(self, mesh, nc, nd): self.mesh = mesh self.nc = nc self.nd = nd def calculateSubgridError(self, q): nc = self.nc for ci in range(self.nc): vfemIntegrals.calculateSubgridErrorScalarADR_1(self.mesh.elementDiameters...
def _str_upred(p, prec=0): ptyp = type(p) if (ptyp is UEq.Eq): return f'{p.lhs} == {p.rhs}' elif ((ptyp is UEq.Conj) or (ptyp is UEq.Disj)): op = (' and ' if UEq.Conj else ' or ') s = op.join([_str_upred(pp, 1) for pp in p.preds]) if (prec > 0): s = f'({s})' ...
class SharedNoiseTable(object): def __init__(self, count: int=): seed = 123 print('Sampling {} random numbers with seed {}'.format(count, seed)) self._shared_mem = multiprocessing.Array(ctypes.c_float, count) self.noise = np.ctypeslib.as_array(self._shared_mem.get_obj()) asse...
class SimLeague(SimHelper, TeamsetMixin, StatsMixin, SimsetMixin, commands.Cog, metaclass=CompositeMetaClass): __version__ = '3.1.0' def format_help_for_context(self, ctx): pre_processed = super().format_help_for_context(ctx) return f'''{pre_processed} Cog Version: {self.__version__}''' def ...
class OptionPlotoptionsHeatmapDatalabelsTextpath(Options): def attributes(self): return self._config_get(None) def attributes(self, value: Any): self._config(value, js_type=False) def enabled(self): return self._config_get(False) def enabled(self, flag: bool): self._confi...
class TransactionNormalized(models.Model): id = models.BigAutoField(primary_key=True) award = models.ForeignKey('search.AwardSearch', on_delete=models.DO_NOTHING, help_text='The award which this transaction is contained in') usaspending_unique_transaction_id = models.TextField(blank=True, null=True, help_te...
def virtual_query_ex(process_handle, address): MBI = MEMORY_BASIC_INFORMATION64() MBI_pointer = byref(MBI) size = sizeof(MBI) lpaddress = c_void_p(address) if windll.kernel32.VirtualQueryEx(process_handle, lpaddress, MBI_pointer, size): return (MBI.BaseAddress, MBI.AllocationBase, MBI.Alloca...
class RequireIfMissing(FormValidator): required = None missing = None present = None __unpackargs__ = ('required',) def _convert_to_python(self, value_dict, state): is_empty = self.field_is_empty if (is_empty(value_dict.get(self.required)) and ((self.missing and is_empty(value_dict.g...
class TestHWBSerialize(util.ColorAssertsPyTest): COLORS = [('hwb(270 30% 50%)', {}, 'hwb(270 30% 50%)'), ('hwb(270 30% 50% / 0.5)', {}, 'hwb(270 30% 50% / 0.5)'), ('hwb(270 30% 50%)', {'alpha': True}, 'hwb(270 30% 50% / 1)'), ('hwb(270 30% 50% / 0.5)', {'alpha': False}, 'hwb(270 30% 50%)'), ('hwb(270 30% 75% / 50%)...
def generate_ics_file(event_id, temp=True, include_sessions=True): if temp: filedir = os.path.join(current_app.config.get('BASE_DIR'), f'static/uploads/temp/{event_id}/') else: filedir = os.path.join(current_app.config.get('BASE_DIR'), (('static/uploads/' + event_id) + '/')) if (not os.path....
def data_pre_classification(df: DataFrame): columns = df.columns.tolist() number_columns = [] non_numeric_colums = [] non_numeric_colums_value_map = {} numeric_colums_value_map = {} for column_name in columns: if pd.api.types.is_numeric_dtype(df[column_name].dtypes): number_c...
_register_make _set_nxm_headers([ofproto_v1_0.NXM_NX_TUN_ID, ofproto_v1_0.NXM_NX_TUN_ID_W]) _field_header([ofproto_v1_0.NXM_NX_TUN_ID, ofproto_v1_0.NXM_NX_TUN_ID_W]) class MFTunId(MFField): pack_str = MF_PACK_STRING_BE64 def __init__(self, header, value, mask=None): super(MFTunId, self).__init__(header,...
class Solution(object): def uncommonFromSentences(self, A, B): words = {} for word in A.split(' '): if (word not in words): words[word] = 0 words[word] += 1 for word in B.split(' '): if (word not in words): words[word] = 0 ...
class TestPartitionOptions(): test = CISAudit() test_id = '1.1' test_level = 1 partition = '/pytest' option = 'noexec' (CISAudit, '_shellexec', mock_option_set) def test_partition_option_is_set(self): state = self.test.audit_partition_option_is_set(partition=self.partition, option=se...
def test_shp_to_shp_record_count_is_3(create_input_file, create_output_centerline_file): EXPECTED_COUNT = 3 input_polygon_shp = create_input_file('polygons', 'shp') output_centerline_shp = create_output_centerline_file('shp') runner = CliRunner() runner.invoke(create_centerlines, [input_polygon_shp,...
class transposed_conv2d(conv2d): def __init__(self, stride, pad, dilate=1, group=1) -> None: super().__init__(stride, pad, dilate=dilate, group=group) self._attrs['op'] = 'transposed_conv2d' self._attrs['epilogue'] = 'LinearCombination' self.shape_eval_template = SHAPE_FUNC_TEMPLATE ...
def deploy_build_log_with_rsync(appid, vercode, log_content): if (not log_content): logging.warning(_('skip deploying full build logs: log content is empty')) return if (not os.path.exists('repo')): os.mkdir('repo') log_gz_path = os.path.join('repo', '{appid}_{versionCode}.log.gz'.fo...
def mocked_no_params_query(list_id, from_date, todays_date): return [{'SK': 'DATESENT#2020-10-10', 'PK': 'LIST#1ebcad3f-5dfd-6bfe-bda4-acde', 'Word': {'Word id': 'WORD#123456', 'Simplified': '', 'Pinyin': 'duo shao', 'Definition': 'number; amount; somewhat', 'HSK Level': '1', 'Traditional': '', 'Difficulty level': ...
def _test_outputs(check_tensor, check_all, test_name, dtype, capfd: pytest.CaptureFixture[str]): X1 = Tensor(shape=[IntImm(1), IntImm(3)], dtype=dtype, name='input0', is_input=True) X2_op = ops.elementwise(FuncEnum.MUL) X2 = X2_op(X1, 1.3) X2._attrs['is_output'] = True X2._attrs['name'] = 'output0' ...
class MySQLConnector(BaseConnector, ABC): def __init__(self, host='127.0.0.1', port=3306, user=None, passwd=None, db=None, charset='utf8', *args, **kwargs): super().__init__(host, port, user, passwd, db, charset, args, kwargs) self._conn = pymysql.connect(host=host, port=port, user=user, passwd=pass...
class Test_fragment(unittest.TestCase): def setUp(self): self.nxt = 44 self.offset = 50 self.more = 1 self.id_ = 123 self.fragment = ipv6.fragment(self.nxt, self.offset, self.more, self.id_) self.off_m = ((self.offset << 3) | self.more) self.form = '!BxHI' ...
def test_h5_all_multi_core_all(): outfile_pref = NamedTemporaryFile(prefix='differential_tad', delete=True) args = '--targetMatrix {} --controlMatrix {} --tadDomains {} -t {} -o {} -m {} -mr {}'.format((ROOT + 'GSM2644945_Untreated-R1.100000_chr1.h5'), (ROOT + 'GSM2644947_Auxin2days-R1.100000_chr1.h5'), (ROOT +...
def fetch_production(zone_key: str='JP-KN', session: (Session | None)=None, target_datetime: (datetime | None)=None, logger: Logger=getLogger(__name__)): session = (session or Session()) if (target_datetime is not None): raise NotImplementedError('This parser can only fetch live data') JP_data = JP_...
def emit_instance(op, for_profiler, f_instance_convertor=universal_gemm_instance, emit_kernel=False, func_attrs=None): import cutlass_lib cutlass_3x = (op.gemm_kind == cutlass_lib.library.GemmKind.Universal3x) if cutlass_3x: emitter = cutlass_lib.gemm_operation.EmitGemmUniversal3xInstance() else...
def test_query_with_page(conversation_list: List[StorageConversation], conv_storage, message_storage): query_spec = QuerySpec(conditions={'user_name': 'user1'}) page_result: PaginationResult = conv_storage.paginate_query(page=1, page_size=2, cls=StorageConversation, spec=query_spec) assert (page_result.tota...
class TestEmojiNewIndex(util.MdCase): extension = ['pymdownx.emoji'] extension_configs = {'pymdownx.emoji': {'emoji_index': _new_style_index, 'options': {'append_alias': [(':grin:', ':smile:')]}}} def test_new_index(self): self.check_markdown(':grin:', '<p><img alt="" class="twemoji" src=" title=":g...
def test_config_entry_file(): c = ConfigEntry(LegacyConfigEntry('platform', 'url', str), YamlConfigEntry('admin.endpoint'), (lambda x: x.replace('dns:///', ''))) assert (c.read() is None) cfg = get_config_file(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'configs/sample.yaml')) assert (cfg....
class TestContractions(TestCase): def test_misses(self): self.assertIsNone(IS_CONTRACTION.match("don'r")) self.assertIsNone(IS_CONTRACTION.match("'ve")) def test_matches(self): self.assertIsNotNone(IS_CONTRACTION.match("I've")) self.assertIsNotNone(IS_CONTRACTION.match("don't")) ...
class JsCountDistinct(): params = ('keys',) value = "\n var temp = {}; keys.forEach(function(k){temp[k] = {}});\n data.forEach(function(rec){keys.forEach(function(k){temp[k][rec[k]] = 1})}); \n for(var col in temp){\n var dCount = Object.keys(temp[col]).length; \n result.push({'column': col, ...
def test_dialogues(): signing_dialogues = SigningDialogues('agent_addr') (msg, dialogue) = signing_dialogues.create(counterparty='abc', performative=SigningMessage.Performative.SIGN_TRANSACTION, terms=Terms(ledger_id='ledger_id', sender_address='address1', counterparty_address='address2', amount_by_currency_id=...
def test_primitive_to_string(): primitive = Primitive(integer=1) assert (primitive_to_string(primitive) == 1) primitive = Primitive(float_value=1.0) assert (primitive_to_string(primitive) == 1.0) primitive = Primitive(boolean=True) assert (primitive_to_string(primitive) is True) primitive = ...
class OptionPlotoptionsItemDatalabelsTextpath(Options): def attributes(self): return self._config_get(None) def attributes(self, value: Any): self._config(value, js_type=False) def enabled(self): return self._config_get(False) def enabled(self, flag: bool): self._config(f...
(ACCESS_MANUAL_WEBHOOK, status_code=HTTP_201_CREATED, dependencies=[Security(verify_oauth_client, scopes=[WEBHOOK_CREATE_OR_UPDATE])], response_model=AccessManualWebhookResponse) def create_access_manual_webhook(connection_config: ConnectionConfig=Depends(_get_connection_config), *, db: Session=Depends(deps.get_db), re...
class DaemonThread(threading.Thread): def __init__(self, name): threading.Thread.__init__(self) self.name = name self.parent_thread = threading.currentThread() self.running = False self.running_lock = threading.Lock() self.job_lock = threading.Lock() self.jobs...
class TestCursorTool(unittest.TestCase, EnableTestAssistant): ((ETSConfig.toolkit == 'null'), "Skip on 'null' toolkit") def test_use_with_log_mappers(self): class TestCursor(HasTraits): plot = Instance(Plot) traits_view = View(Item('plot', editor=ComponentEditor(), show_label=Fal...
def test_nonlinear_medium(log_capture): med = td.Medium(nonlinear_spec=td.NonlinearSpec(models=[td.NonlinearSusceptibility(chi3=1.5), td.TwoPhotonAbsorption(beta=1), td.KerrNonlinearity(n2=1)], num_iters=20)) med = td.Medium(nonlinear_spec=td.NonlinearSpec(models=[td.KerrNonlinearity(n2=((- 1) + 1j), n0=1), td....
class TestLongestIncreasingSubseq(unittest.TestCase): def test_longest_increasing_subseq(self): subseq = Subsequence() self.assertRaises(TypeError, subseq.longest_inc_subseq, None) self.assertEqual(subseq.longest_inc_subseq([]), []) seq = [3, 4, (- 1), 0, 6, 2, 3] expected = ...
def test_add(devnetwork, accounts): assert (len(accounts) == 10) local = accounts.add() assert (len(accounts) == 11) assert (type(local) is LocalAccount) assert (accounts[(- 1)] == local) accounts.add(priv_key) assert (len(accounts) == 12) assert (accounts[(- 1)].address == addr) ass...
def extractRrrrhexiatranslationCom(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_typ...
def run_parallel_test_suites(root_tmpdir, resultclass, parallel_tests): results = [] if parallel_tests.countTestCases(): max_parallel_tests = min(parallel_tests.countTestCases(), max_loadavg()) print(('running maximum of %u parallel tests' % max_parallel_tests)) parallel_runner = test_ru...
def main(): p = argparse.ArgumentParser(description="Create an XLS(X) spreadsheet from the output of the MACS2 peak caller. MACS2_XLS is the output '.xls' file from MACS2; if supplied then XLS_OUT is the name to use for the output file (otherwise it will be called 'XLS_<MACS2_XLS>.xls(x)').") p.add_argument('--...
class TestConfigArgType(): def test_type_arg_builder(self, monkeypatch): with monkeypatch.context() as m: m.setattr(sys, 'argv', ['', '--config', './tests/conf/yaml/test.yaml']) with pytest.raises(TypeError): ConfigArgBuilder(['Names'], desc='Test Builder')
def run_perf(geom, calc_getter, pals=None, mems=None, pal_range=None, mem_range=None, repeat=1, kind='forces'): assert (repeat > 0) assert (pals or pal_range) assert (mems or mem_range) func_names = {'energy': 'get_energy', 'forces': 'get_forces', 'hessian': 'get_hessian'} if (pal_range is not None)...
def argparse_main(parser: argparse.ArgumentParser, *, dir: tp.Union[(str, Path)]='./outputs', exclude: tp.Sequence[str]=[], slurm: tp.Optional[SlurmConfig]=None, shared: tp.Optional[tp.Union[(str, Path)]]=None, use_underscore: bool=True, **kwargs): def _decorator(main: MainFun): dora = DoraConfig(dir=Path(d...
class OptionSeriesFunnelSonificationContexttracksMappingTremoloDepth(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 SevenSegment(): disp = None digits = [63, 6, 91, 79, 102, 109, 125, 7, 127, 111, 119, 124, 57, 94, 121, 113] def __init__(self, address=112, i2cbusnum=(- 1), debug=False): if debug: print(('Initializing a new instance of LEDBackpack at 0x%02X' % address)) self.disp = reques...
def get_custom_fields(): custom_fields = {'Patient': [dict(fieldname='abha_address', label='PHR Address', fieldtype='Data', insert_after='status', read_only=1), dict(fieldname='abha_number', label='ABHA Number', fieldtype='Data', insert_after='abha_address', read_only=1), dict(fieldname='abha_card', label='ABHA Car...
def test_monitor_workflow_execution(register): remote = FlyteRemote(Config.auto(config_file=CONFIG), PROJECT, DOMAIN) flyte_launch_plan = remote.fetch_launch_plan(name='basic.hello_world.my_wf', version=VERSION) execution = remote.execute(flyte_launch_plan, inputs={}) poll_interval = datetime.timedelta(...
class _AttrName(ExtendedEnum): XNAME = 'X_UTME' YNAME = 'Y_UTMN' ZNAME = 'Z_TVDSS' M_MD_NAME = 'M_MDEPTH' Q_MD_NAME = 'Q_MDEPTH' M_AZI_NAME = 'M_AZI' Q_AZI_NAME = 'Q_AZI' M_INCL_NAME = 'M_INCL' Q_INCL_NAME = 'Q_INCL' I_INDEX = 'I_INDEX' J_INDEX = 'J_INDEX' K_INDEX = 'K_IN...
def _test_more_sophisticated_eclipsed_psc_code_2(client): resp = client.post('/api/v2/search/spending_by_award', content_type='application/json', data=json.dumps({'filters': {'award_type_codes': ['A', 'B', 'C', 'D'], 'psc_codes': {'require': [['Service', 'P'], ['Service', 'P', 'PSC', 'PSC1']], 'exclude': [['Service...
def test_laplace_physical_ev(parallel=False): try: from slepc4py import SLEPc except ImportError: pytest.skip(msg='SLEPc unavailable, skipping eigenvalue test') mesh = UnitSquareMesh(64, 64) V = FunctionSpace(mesh, 'CG', 1) u = TrialFunction(V) v = TestFunction(V) bc = Dirich...
def get_now_time() -> str: SHA_TZ = datetime.timezone(datetime.timedelta(hours=8), name='Asia/Shanghai') fmt = '%y%m%d_%H%M%S' utc_now = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc) beijing_now = utc_now.astimezone(SHA_TZ) stamp = beijing_now.strftime(fmt) return stamp
class Scoreboard(): def __init__(self, ai_game): self.ai_game = ai_game self.screen = ai_game.screen self.screen_rect = self.screen.get_rect() self.settings = ai_game.settings self.stats = ai_game.stats self.text_color = (30, 30, 30) self.font = pygame.font.Sy...
def main(): try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError("Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?") from exc ...
class VarUint32(EosType): def pack(cls, value: int) -> bytes: mbytes = b'' val = value while True: b = (val & 127) val >>= 7 b |= ((val > 0) << 7) uint8 = Uint8.pack(b) mbytes += bytes(uint8) if (not val): ...
class OriginInspectorHistoricalMeta(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...
def test_restructure_cfg_loop_two_back_edges_condition_1(task): task.graph.add_nodes_from((vertices := [BasicBlock(0, instructions=[Assignment(variable(name='i'), Constant(0)), Assignment(variable(name='x'), Constant(42))]), BasicBlock(1, instructions=[Branch(Condition(OperationType.not_equal, [variable(name='i'), ...
def convert_ip_adapter(): run_conversion_script('convert_diffusers_ip_adapter.py', 'tests/weights/h94/IP-Adapter/models/ip-adapter_sd15.bin', 'tests/weights/ip-adapter_sd15.safetensors', expected_hash='9579b465') run_conversion_script('convert_diffusers_ip_adapter.py', 'tests/weights/h94/IP-Adapter/sdxl_models/...
def check_SPF_record(domain): global debug global domain_data global common_hostnames global check_spf global output_file global output_file_handler reverseDNS = {} if check_spf: try: print('\n\tChecking SPF record...') if (output_file != ''): ...
.django_db def test_child_recipient_preference_to_uei(recipient_lookup): recipient_parameters = {'recipient_name': 'Child Recipient Test', 'recipient_uei': '456', 'parent_recipient_uei': '123', 'recipient_unique_id': 'NOT A REAL DUNS', 'parent_recipient_unique_id': 'NOT A REAL DUNS'} expected_result = 'ede3440b...
class TestComparisonReporter(): def setup_method(self, method): config_mock = mock.Mock(config.Config) config_mock.opts.return_value = True self.reporter = reporter.ComparisonReporter(config_mock) def test_diff_percent_divide_by_zero(self): formatted = self.reporter._diff(0, 0, F...
class OptionSeriesPyramidSonificationDefaultspeechoptionsMappingTime(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 NavCollectsView(View): def post(self, request, nid): res = {'msg': '!', 'code': 412, 'isCollects': True} if (not request.user.username): res['msg'] = '' return JsonResponse(res) flag = request.user.navs.filter(nid=nid) num = 1 res['code'] = 0 ...
def human_format(num: float, precision: int, powerOfTwo: bool=False) -> str: divisor = (1024 if powerOfTwo else 1000) magnitude = 0 while (abs(num) >= divisor): magnitude += 1 num /= divisor result = ((('%.' + str(precision)) + 'f%s') % (num, ['', 'K', 'M', 'G', 'T', 'P'][magnitude])) ...
class ActionModel(nn.Module): def __init__(self, inputs_shape, num_actions): super().__init__() self.inut_shape = inputs_shape self.num_actions = num_actions self.features = nn.Sequential(nn.Conv2d(inputs_shape[1], 32, kernel_size=8, stride=4), nn.ReLU(), nn.Conv2d(32, 64, kernel_siz...
class OptionSeriesCylinderSonificationDefaultinstrumentoptionsMappingNoteduration(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 DeleteFailureError(BaseGenTableTest): def runTest(self): self.do_add(vlan_vid=1000, ipv4=, mac=(0, 1, 2, 3, 4, 5), idle_notification=True) do_barrier(self.controller) verify_no_errors(self.controller) orig_entries = self.do_entry_desc_stats() self.assertEquals(len(orig_...
class ClickSubShell(ClickShell): pending_main = False pending_exit = False prompt = staticmethod(build_prompt) def do_back(self, text): return True def do_exit(self, text): ClickSubShell.pending_exit = True return True def do_main(self, text): ClickSubShell.pendin...
def test_handle_not_replaying_callback_returns_none(decision_context): def callback(stored): return None decision_context.workflow_clock.set_replaying(False) handler = MarkerHandler(decision_context=decision_context, marker_name='the-marker-name') handler.mutable_marker_results['the-id'] = Marke...
def fifo18(tile_name, luts, lines, sites): params = {} params['tile'] = tile_name params['Y0_IN_USE'] = True params['Y1_IN_USE'] = False params['FIFO_Y0_IN_USE'] = True params['FIFO_Y1_IN_USE'] = False lines.append('\n wire fifo_rst_{site};\n (* KEEP, DONT_TOUCH *)\n LUT...
class Rpc(metaclass=_Singleton): def __init__(self) -> None: self.process: Union[(psutil.Popen, psutil.Process)] = None self.backend: Any = ganache atexit.register(self._at_exit) def _at_exit(self) -> None: if (not self.is_active()): return if (self.process.pa...
class Tidy3dStub(BaseModel, TaskStub): simulation: SimulationType = pd.Field(discriminator='type') def from_file(cls, file_path: str) -> SimulationType: extension = _get_valid_extension(file_path) if (extension == '.json'): json_str = read_simulation_from_json(file_path) elif...
def test_message_keyword_truncation(sending_elasticapm_client): too_long = ('x' * (KEYWORD_MAX_LENGTH + 1)) expected = encoding.keyword_field(too_long) sending_elasticapm_client.capture_message(param_message={'message': too_long, 'params': []}, logger_name=too_long, handled=False) sending_elasticapm_cli...
class TestPcAttributionRunner(TestCase): ('fbpcs.private_computation.pc_attribution_runner.BoltGraphAPIClient', new=MagicMock()) ('fbpcs.private_computation.pc_attribution_runner.datetime') def test_get_runnable_timestamps(self, mock_datetime: MagicMock) -> None: mock_datetime.now = MagicMock(return...
def extractShimizunovelWordpressCom(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, frag=f...
.parametrize('space', ['dg0', 'rt1']) def test_reconstruct_component(space, dg0, rt1, mesh, mesh2, dual): Z = {'dg0': dg0, 'rt1': rt1}[space] if dual: Z = Z.dual() for component in range(Z.value_size): V1 = Z.sub(component) V2 = V1.reconstruct(mesh=mesh2) assert (is_dual(V1) ...
.parametrize('bytevalue, expected', [(b'\x04', V3Flags(auth=False, priv=False, reportable=True)), (b'\x05', V3Flags(auth=True, priv=False, reportable=True)), (b'\x07', V3Flags(auth=True, priv=True, reportable=True))]) def test_authflags(bytevalue, expected): snmp_value = OctetString(bytevalue) result = V3Flags....
def test_requeuing(tmp_path: Path) -> None: func = helpers.FunctionSequence(verbose=True) for x in range(20): func.add(test_core.do_nothing, x=x, sleep=1) executor = local.LocalExecutor(tmp_path, max_num_timeout=1) executor.update_parameters(timeout_min=(3 / 60), signal_delay_s=1) job = exec...
def gate_request(method='GET', uri=None, headers={}, data={}, params={}): response = None url = '{host}{uri}'.format(host=API_URL, uri=uri) if GATE_AUTHENTICATION: if ('google_iap' in GATE_AUTHENTICATION): iap_response = get_google_iap_bearer_token(GATE_AUTHENTICATION['google_iap']['oaut...
def test_custom_form(): (app, admin) = setup() class TestForm(form.BaseForm): pass view = MockModelView(Model, form=TestForm) admin.add_view(view) assert (view._create_form_class == TestForm) assert (view._edit_form_class == TestForm) assert (not hasattr(view._create_form_class, 'col...
def get_compat_id(metadata, *, short=True): data = [metadata['hostname'], metadata['platform'], metadata.get('perf_version'), metadata['performance_version'], metadata['cpu_model_name'], metadata.get('cpu_freq'), metadata['cpu_config'], metadata.get('cpu_affinity')] h = hashlib.sha256() for value in data: ...
class Starred(expr): _fields = ('value', 'ctx') _attributes = ('lineno', 'col_offset') def __init__(self, value, ctx=None, lineno=0, col_offset=0, **ARGS): expr.__init__(self, **ARGS) self.value = value self.ctx = ctx self.lineno = int(lineno) self.col_offset = int(co...
def test_migrating_with_alternative_versions_data_1(migration_test_data, create_pymel, create_maya_env): data = migration_test_data pm = create_pymel maya_env = create_maya_env migration_recipe = {data['ext2'].id: {'new_parent_id': data['assets_task2'].id}, data['ext2_look_dev'].id: {'new_parent_id': da...
class TestApiBlueprint(): class TestRoot(): def test_should_have_links(self, test_client: FlaskClient): response = test_client.get('/') assert (_get_ok_json(response) == {'links': {'pdfalto': '/pdfalto'}}) class TestPdfAlto(): def test_should_show_form_on_get(self, test_c...
class PrivateComputationGameRepository(MPCGameRepository): def __init__(self) -> None: self.private_computation_game_config: Dict[(str, GameNamesValue)] = PRIVATE_COMPUTATION_GAME_CONFIG def get_game(self, name: str) -> MPCGameConfig: if (name not in self.private_computation_game_config): ...
class OptionPlotoptionsPyramidOnpointConnectoroptions(Options): def dashstyle(self): return self._config_get(None) def dashstyle(self, text: str): self._config(text, js_type=False) def stroke(self): return self._config_get(None) def stroke(self, text: str): self._config(t...
class SessionStats(): def __init__(self, server_addr, peer, file_path): self.peer = peer self.server_addr = server_addr self.file_path = file_path self.error = {} self.options = {} self.start_time = time.time() self.packets_sent = 0 self.packets_acked ...
('cuda.pad_last_dim.func_call') def gen_function_call(func_attrs, indent=' '): x = func_attrs['inputs'][0] xshape = x._attrs['shape'] xshape_args = [('&' + dim._attrs['name']) for dim in xshape] y = func_attrs['outputs'][0] yshape = y._attrs['shape'] yshape_args = [('&' + dim._attrs['name']) fo...
def test_send_monthly_invoice(db): TicketFeesFactory(service_fee=10.23, maximum_fee=11, country='global') test_order = OrderSubFactory(status='completed', event__state='published', completed_at=monthdelta(this_month_date(), (- 1)), amount=100) (role, _) = get_or_create(Role, name='owner', title_name='Owner'...
def getKerberosTGT(clientName, password, domain, lmhash, nthash, aesKey='', kdcHost=None, requestPAC=True, serverName=None, kerberoast_no_preauth=False): if isinstance(lmhash, str): try: lmhash = unhexlify(lmhash) except TypeError: pass if isinstance(nthash, str): ...
def fortios_emailfilter(data, fos): fos.do_member_operation('emailfilter', 'block-allow-list') if data['emailfilter_block_allow_list']: resp = emailfilter_block_allow_list(data, fos) else: fos._module.fail_json(msg=('missing task body: %s' % 'emailfilter_block_allow_list')) return ((not ...
def compile_decompile(table, ttFont): writer = OTTableWriter(tableTag='COLR') table = deepcopy(table) table.compile(writer, ttFont) data = writer.getAllData() reader = OTTableReader(data, tableTag='COLR') table2 = table.__class__() table2.decompile(reader, ttFont) return table2
class FallbackTesting_RegularChainSyncer(Service): class HeaderSyncer_OnlyOne(): def __init__(self, real_syncer): self._real_syncer = real_syncer async def new_sync_headers(self, max_batch_size): async for headers in self._real_syncer.new_sync_headers(1): (yie...
class SACTest(absltest.TestCase): def test_sac(self): environment = fakes.ContinuousEnvironment(action_dim=2, observation_dim=3, episode_length=10, bounded=True) spec = specs.make_environment_spec(environment) agent_networks = sac.make_networks(spec, policy_layer_sizes=(32, 32), critic_layer...