code
stringlengths
281
23.7M
class HelperChrome(): def __init__(self, printer: ColorPrinter, screen_control: 'Controller', flags: ScreenFlags): self.printer = printer self.screen_control = screen_control self.flags = flags self.mode = SELECT_MODE self.width = 50 self.sidebar_y = 0 self.de...
def test_ot_span(tracer: Tracer): with tracer.start_as_current_span('test'): with tracer.start_as_current_span('testspan', kind=SpanKind.CONSUMER): with tracer.start_as_current_span('testspan2'): pass client = tracer.client transaction = client.events[constants.TRANSACTIO...
class SyslogHandler(logging.handlers.SysLogHandler): OVERFLOW_BEHAVIOR_FRAGMENT = 0 OVERFLOW_BEHAVIOR_TRUNCATE = 1 _MINIMUM_MTU_CACHE = {} def __init__(self, address=('localhost', logging.handlers.SYSLOG_UDP_PORT), facility=logging.handlers.SysLogHandler.LOG_USER, socket_type=None, overflow=OVERFLOW_BEH...
class ChannelDetailView(ChannelMixin, ObjectDetailView): template_name = 'website/channel_detail.html' attributes = ['name'] max_num_lines = 10000 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) channel = self.object filename = channel.get_log_f...
class perm021fc_ccr_bias_permute(perm021fc_ccr_bias): def __init__(self, layout='021'): super().__init__() self._attrs['op'] = 'perm021fc_ccr_bias_permute' self._attrs['shape'] = [0] self._attrs['layout'] = 'Permute3DBMM_{}'.format(layout) def __call__(self, a: Tensor, b: Tensor,...
class ModuleEnableNameValidator(object): def __call__(self, form, field): already_enabled = {} for module in form.module_toggle.data.split(','): if (module == ''): return True try: (module_name, stream) = module.strip().split(':') e...
def extractThemanwithoutriceWordpressCom(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, ...
def cmd_run(jobs: Jobs, reqid: RequestID, *, copy: bool=False, force: bool=False) -> None: if copy: raise NotImplementedError if force: raise NotImplementedError if (not reqid): raise NotImplementedError if (not jobs.queues[reqid.workerid].paused): cmd_queue_push(jobs, re...
class perm021fc_ccr(bmm): def __init__(self): super().__init__() self._attrs['op'] = 'perm021fc_ccr' def cal_align_ab(m, n, k): return common.default_align_ab(m, k, self._attrs['inputs'][0].dtype()) self._attrs['f_ab_alignment'] = cal_align_ab def _infer_shapes(self, ...
def test_massW1W1(W): u = TrialFunction(W)[1] v = TestFunction(W)[1] A = assemble((inner(u, v) * dx)) assert (A.M.sparsity.shape == (2, 2)) assert np.allclose(A.M[(0, 0)].values, 0.0) assert np.allclose(A.M[(1, 0)].values, 0.0) assert np.allclose(A.M[(0, 1)].values, 0.0) assert (not np.a...
def test_open_plugin_settings(preference, plugin_engine): plugin_engine.collect() preference.run() Q.map(Q.select(preference.widget, Q.props('name', 'plugin.list')), TV.column(Q.props('title', 'Active')), TV.cell_renderer(0), Q.emit('toggled', 0)) settings_button = Q.select(preference.widget, Q.props('n...
def test_chunk_message_ordering(): mq = MessageQueue(log_time_order=True) push_elements(mq) results: List[QueueItem] = [] while mq: results.append(mq.pop()) assert isinstance(results[0], ChunkIndex) assert (results[0].message_start_time == 1) assert isinstance(results[1], ChunkIndex)...
def render() -> None: global FRAME_PROCESSORS_CHECKBOX_GROUP FRAME_PROCESSORS_CHECKBOX_GROUP = gradio.CheckboxGroup(label=wording.get('frame_processors_checkbox_group_label'), choices=sort_frame_processors(facefusion.globals.frame_processors), value=facefusion.globals.frame_processors) register_ui_component...
class FlowStorePipeSplit(FlowStorePipe): async def open_request(self): self.store_parallel('open_request') async def open_ws(self): self.store_parallel('open_ws') async def close_request(self): self.store_parallel('close_request') async def close_ws(self): self.store_para...
class OptionSeriesColumnrangeSonificationTracksPointgrouping(Options): def algorithm(self): return self._config_get('minmax') def algorithm(self, text: str): self._config(text, js_type=False) def enabled(self): return self._config_get(True) def enabled(self, flag: bool): ...
class EnumStepTypes(Enums): def linear(self): self._set_value() def linear_closed(self): self._set_value('linear-closed') def basis(self): self._set_value() def basis_open(self): self._set_value('basis-open') def basis_closed(self): self._set_value('basis-clos...
_numba def test_spline_jacobian_implementations(): data = CheckerBoard().scatter(size=1500, random_state=1) coords = (data.easting, data.northing) jac_numpy = Spline(engine='numpy').jacobian(coords, coords) jac_numba = Spline(engine='numba').jacobian(coords, coords) npt.assert_allclose(jac_numpy, ja...
def sync_benchmark(func: Callable[(..., Any)], n: int) -> Union[(float, str)]: try: starttime = timeit.default_timer() for _ in range(n): func() endtime = timeit.default_timer() execution_time = (endtime - starttime) return execution_time except Exception: ...
('update', help='Performs an update operation on current bench. Without any flags will backup, pull, setup requirements, build, run patches and restart bench. Using specific flags will only do certain tasks instead of all') ('--pull', is_flag=True, help='Pull updates for all the apps in bench') ('--apps', type=str) ('-...
class OptionSeriesBoxplotSonificationDefaultinstrumentoptionsMappingNoteduration(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...
def generate_gradio_app(model_path_or_url: str, examples: List[str], author_username: str=None) -> str: from video_transformers import VideoModel model = VideoModel.from_pretrained(model_path_or_url) return f''' import gradio as gr from video_transformers import VideoModel model: VideoModel = VideoModel.fro...
def get_random_raw_url_group(num_items): dat = g.session.execute('SELECT url FROM raw_web_pages TABLESAMPLE SYSTEM(:percentage) ORDER BY url;', {'percentage': num_items}) dat = list(dat) ret = [] for (linkurl,) in dat: filtered = raw_url_filtered(linkurl) ret.append((linkurl, filtered)) ...
class ImageFormatTest(unittest.TestCase): def setUp(self): super(ImageFormatTest, self).setUp() self.kwargs = {'name': 'HD', 'width': 1920, 'height': 1080, 'pixel_aspect': 1.0, 'print_resolution': 300} self.test_image_format = ImageFormat(**self.kwargs) def test___auto_name__class_attrib...
def test_base_equals_has_expected_repr(): assert (repr(BaseEquals('foo')) == "<BaseEquals (base == 'foo')>") assert (repr(BaseEquals('foo', with_sub=True)) == "<BaseEquals (base == 'foo' and sub is not None)>") assert (repr(BaseEquals('foo', with_sub=False)) == "<BaseEquals (base == 'foo' and sub is None)>"...
class OptionSeriesTimelineSonificationContexttracksMappingFrequency(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 test_opaque_paint(): pink = Color('pink') white = Color('white') with Image(filename='WIZARD:') as img: img.opaque_paint(target=white, fill=pink, fuzz=(0.25 * img.quantum_range)) assert (img[(0, 0)] == pink) with Image(filename='WIZARD:') as img: img.opaque_paint(target='whit...
class BhToggleStringEscapeModeCommand(sublime_plugin.TextCommand): def run(self, edit): default_mode = sublime.load_settings('bh_core.sublime-settings').get('bracket_string_escape_mode', 'string') if (self.view.settings().get('bracket_highlighter.bracket_string_escape_mode', default_mode) == 'regex'...
_os(*metadata.platforms) def main(): key = 'Environment' value = 'COR_PROFILER_PATH' data = 'temp.dll' with common.temporary_reg(common.HKCU, key, value, data): pass mmc = 'C:\\Users\\Public\\mmc.exe' powershell = 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe' commo...
class ModeCategoryContribution(StrictBaseModelWithAlias): source: (str | None) = Field(None, alias='_source') comment: (str | None) = Field(None, alias='_comment') url: ((str | list[str]) | None) = Field(None, alias='_url') datetime: ((datetime | date) | None) value: (Percentage | None)
class DiceRoll(TraitType): default_value = (1, 1) info_text = 'a tuple of the form (n,m), where both n and m are integers in the range from 1 to 6 representing a roll of a pair of dice' def validate(self, object, name, value): if (isinstance(value, tuple) and (len(value) == 2) and (1 <= value[0] <= ...
def generate_delft_training_data(model_name: str, tei_source_path: str, raw_source_path: str, delft_output_path: str, sciencebeam_parser: ScienceBeamParser): training_tei_parser = get_training_tei_parser_for_model_name(model_name, sciencebeam_parser=sciencebeam_parser) data_generator = get_data_generator_for_mo...
def prompt_user(question: str, options: str, default: str='') -> str: options = options.lower() default = default.lower() assert ((len(default) < 2) and (default in options)) if ('?' not in options): options += '?' prompt_options = ','.join(((o.upper() if (o == default) else o) for o in opti...
def min_score(ar, scorer: Optional[topk_scorer]=None): assert (len(ar) > 0), 'dc.min_score is not defined for empty arrays' if (scorer is None): scorer = alpha_length_normalized() def op_max_score(seqs, score): return np.array(([score] + [scorer(s.logprobs, s) for s in seqs])).min() retu...
def extractSelfTaughtJapanese(item): badwords = ['travel', 'Japanese Study: Intermediate', 'Japanese Study: Advanced', 'contests', 'E-book publishing', 'test', 'grammar', 'research', 'Reviews', 'aside'] if any([(bad in item['tags']) for bad in badwords]): return None (vol, chp, frag, postfix) = extr...
class LiteDRAMInterface(Record): def __init__(self, address_align, settings): rankbits = log2_int(settings.phy.nranks) self.address_align = address_align self.address_width = (((settings.geom.rowbits + settings.geom.colbits) + rankbits) - address_align) self.data_width = (settings.ph...
def DoConfigWrite(stmt_cursor, config, field, expr, before=False): assert isinstance(expr, (LoopIR.Read, LoopIR.StrideExpr, LoopIR.Const)) s = stmt_cursor._node cw_s = LoopIR.WriteConfig(config, field, expr, None, s.srcinfo) if before: (ir, fwd) = stmt_cursor.before()._insert([cw_s]) else: ...
class VideoWidget(Widget): DEFAULT_MIN_SIZE = (100, 100) source = event.StringProp('', settable=True, doc='\n The source of the video. This must be a url of a resource\n on the web.\n ') def _create_dom(self): global window node = window.document.createElement('video') ...
def test_circular_dependency_2_init(circular_dependency_phi_functions, variable_v, variable_u): list_of_phi_functions = circular_dependency_phi_functions list_of_phi_functions[6].substitute(variable_v[6], variable_u[5]) graph = PhiDependencyGraph(list_of_phi_functions) assert ((set(graph.edges) == {(lis...
def extract_step_back(query: str, model: BaseLLM=None) -> Optional[Sentence]: _input = _STEP_BACK_PROMPT.format(question=query) if _DEBUG: print(f'Input: {_input}', file=sys.stderr) if (model is None): model = OpenAI(temperature=0) output = model(_input) if _DEBUG: print(f'Ou...
class QueeningQueue(Service, PeerSubscriber, QueenTrackerAPI): _queen_peer: ETHPeer = None _queen_updated: asyncio.Event _knights: WaitingPeers[ETHPeer] _peasants: WaitingPeers[ETHPeer] subscription_msg_types: FrozenSet[Type[CommandAPI[Any]]] = frozenset() msg_queue_maxsize: int = 2000 _repo...
class Ui_Wallbreaker(object): def setupUi(self, Wallbreaker): Wallbreaker.setObjectName('Wallbreaker') Wallbreaker.resize(822, 612) self.gridLayout_4 = QtWidgets.QGridLayout(Wallbreaker) self.gridLayout_4.setObjectName('gridLayout_4') self.groupBox = QtWidgets.QGroupBox(Wallb...
class Header(object): SIZE = 936 def __init__(self, io): stream = BytesIO(io.read(self.SIZE)) self.signature = stream.read(4) if (self.signature != b'PML_'): raise PMLError('not a Process Monitor backing file (signature missing).') self.version = read_u32(stream) ...
def get_csv_line(jobname, json, index, data, version_str, serverMode, scale_by_TB=1): clat = 'clat' con = 1 verstr = version_str.split('-')[1] fio_version = StrictVersion(verstr) v3_version = StrictVersion('3.0') if (fio_version >= v3_version): clat = 'clat_ns' con = 1000 if ...
class bsn_gentable_clear_request(bsn_header): version = 6 type = 4 experimenter = 6035143 subtype = 48 def __init__(self, xid=None, table_id=None, checksum=None, checksum_mask=None): if (xid != None): self.xid = xid else: self.xid = None if (table_id !...
def name_graph(sorted_graph: List[Tensor]) -> None: global func_cnt global tensor_cnt global func_name_to_tensor_cnt global user_provided_dim _LOGGER.debug(f'before name_graph: func_cnt={func_cnt!r}, tensor_cnt={tensor_cnt!r}, len(func_name_to_tensor_cnt)={len(func_name_to_tensor_cnt)!r}, len(user_p...
class OAuth2ClientCredentialsAuthenticationStrategy(OAuth2AuthenticationStrategyBase): name = 'oauth2_client_credentials' configuration_model = OAuth2BaseConfiguration def add_authentication(self, request: PreparedRequest, connection_config: ConnectionConfig) -> PreparedRequest: access_token = conne...
def downgrade(): op.create_table('booked_ticket', sa.Column('id', sa.INTEGER(), nullable=False), sa.Column('user_id', sa.INTEGER(), autoincrement=False, nullable=True), sa.Column('ticket_id', sa.INTEGER(), autoincrement=False, nullable=True), sa.Column('quantity', sa.INTEGER(), autoincrement=False, nullable=True), ...
(cis_audit.CISAudit, '_get_utcnow', mock_datetime_utcnow) class TestRunTests(): test = cis_audit.CISAudit() test_args = {} test_args['_id'] = '1.1' test_args['type'] = 'test' test_args['levels'] = {'server': 1, 'workstation': 1} test_args['description'] = 'pytest' def test_run_tests_pass(sel...
class TestEndToEndGenerator(UseOef): def setup_class(cls): cls.cwd = os.getcwd() cls.t = tempfile.mkdtemp() shutil.copytree(Path(ROOT_DIR, 'packages'), Path(cls.t, 'packages')) os.chdir(cls.t) cls.private_key_path_1 = os.path.join(cls.t, (DEFAULT_PRIVATE_KEY_FILE + '_1')) ...
def extractNostalgiaOn9ThAvenue(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=frag,...
class TDE4LensDistortionBase(object): def __init__(self, distortion_model=None): self.distortion_model = distortion_model self.data = None def get_data(self, label): max_search_length = 60 start_i = 0 while ((self.data[start_i] != label) and (start_i < max_search_length))...
def test_matrices_charpoly(): for (M, S, is_field) in _all_matrices(): P = _poly_type_from_matrix_type(M) M1234 = M([[1, 2], [3, 4]]) assert (M1234.charpoly() == P([(- 2), (- 5), 1])) M9 = M([[1, 2, 3], [4, 5, 6], [7, 8, 10]]) assert (M9.charpoly() == P([3, (- 12), (- 16), 1]...
_deserializable class DiscordLoader(BaseLoader): def __init__(self): if (not os.environ.get('DISCORD_TOKEN')): raise ValueError('DISCORD_TOKEN is not set') self.token = os.environ.get('DISCORD_TOKEN') def _format_message(message): return {'message_id': message.id, 'content': ...
class InferenceCertificate(): def __init__(self, tracer): self.tracer = tracer self.event_processors = [flatten_streamed_chat_responses, flatten_streamed_openai_completion, fold_logit_bias] def asdict(self, child=False): if (type(self.tracer) is NullTracer): return {'type': '...
_meta(characters.eirin.LunaString) class LunaString(): name = '' description = ',<style=Card.Name></style>,' def clickable(self): return self.accept_cards([characters.eirin.LunaString(self.me)]) def is_complete(self, sk): from thb.cards.base import VirtualCard s = N.skill(charact...
class ResendActivationCodeViaEmailForm(UserCacheMixin, forms.Form): email = forms.EmailField(label=_('Email')) def clean_email(self): email = self.cleaned_data['email'] user = User.objects.filter(email__iexact=email).first() if (not user): raise ValidationError(_('You entered...
(name='api.vm.status.tasks.vm_status_cb', base=MgmtCallbackTask, bind=True) () def vm_status_cb(result, task_id, vm_uuid=None): vm = Vm.objects.select_related('slavevm').get(uuid=vm_uuid) msg = result.get('message', '') json = result.pop('json', None) if ((result['returncode'] == 0) and msg and (msg.fin...
def test_offchain_lookup_raises_for_improperly_formatted_rest_request_response(offchain_lookup_contract, monkeypatch): normalized_address = to_hex_if_bytes(offchain_lookup_contract.address) mock_offchain_lookup_request_response(monkeypatch, mocked_request_url=f' mocked_json_data=WEB3PY_AS_HEXBYTES, json_data_fi...
def matching_phrases_suffixes(x, allowed_phrases, allow_full_matches=False): x = strip_next_token(x) for phrase in allowed_phrases: if (not phrase.startswith(x)): continue if (len(phrase) > len(x)): (yield phrase[len(x):]) elif allow_full_matches: (yie...
class OptionPlotoptionsColumnSonificationContexttracksActivewhen(Options): def crossingDown(self): return self._config_get(None) def crossingDown(self, num: float): self._config(num, js_type=False) def crossingUp(self): return self._config_get(None) def crossingUp(self, num: floa...
def get_parameters(runtime, toolkit, environment): parameters = {'runtime': runtime, 'toolkit': toolkit, 'environment': environment} if (toolkit not in supported_combinations[runtime]): msg = ('Python {runtime} and toolkit {toolkit} not supported by ' + 'test environments') raise RuntimeError(ms...
def import_colors(self, context): hex_strings = bpy.context.window_manager.clipboard.split(',') for i in range(len(hex_strings)): hex_strings[i] = hex_strings[i].strip().strip('#') if ((len(hex_strings[i]) != 6) or (not all(((c in string.hexdigits) for c in hex_strings[i])))): self.r...
class FakeJob(): watcher = FakeWatcher() def __init__(self): self.job_id = str(len(self.watcher.jobs)) self._state = 'UNKNOWN' def _state(self): return self.watcher.get_state(self.job_id) _state.setter def _state(self, state: str): self.watcher.jobs[self.job_id] = sta...
def validateRuleKeys(dat, fname): checkBadValues(dat) keys = list(dat.keys()) valid = ['badwords', 'compound_badwords', 'decompose', 'decomposeBefore', 'baseUrl', 'feeds', 'feedPostfix', 'stripTitle', 'tld', 'FOLLOW_GOOGLE_LINKS', 'allImages', 'fileDomains', 'destyle', 'preserveAttrs', 'type', 'extraStartUr...
def test_acn_lookup_request_serialization(): msg = AcnMessage(dialogue_reference=('', ''), message_id=1, target=0, performative=AcnMessage.Performative.LOOKUP_REQUEST, agent_address='some_address') msg_bytes = AcnMessage.serializer.encode(msg) actual_msg = AcnMessage.serializer.decode(msg_bytes) expecte...
def generate_dataset_config(train_config, kwargs): names = tuple(DATASET_PREPROC.keys()) assert (train_config.dataset in names), f'Unknown dataset: {train_config.dataset}' dataset_config = {k: v for (k, v) in inspect.getmembers(datasets)}[train_config.dataset]() update_config(dataset_config, **kwargs) ...
def assign_field_names(session) -> None: statements = [] for (form, dict_map) in CUSTOM_FORM_IDENTIFIER_NAME_MAP.items(): for (identifier, name) in dict_map.items(): statements.append(f"UPDATE custom_forms SET name = '{name}' WHERE form = '{form}' and field_identifier = '{identifier}';") ...
class IssueQueryResultType(graphene.ObjectType): concatenated_features: str class Meta(): interfaces = (graphene.relay.Node,) issue_id = graphene.ID() issue_instance_id = graphene.ID() run_id = graphene.ID() code = graphene.Int() message = graphene.String() callable = graphene.St...
class CTypesGenericPtr(CTypesData): __slots__ = ['_address', '_as_ctype_ptr'] _automatic_casts = False kind = 'pointer' def _newp(cls, init): return cls(init) def _cast_from(cls, source): if (source is None): address = 0 elif isinstance(source, CTypesData): ...
(('yaml' in cfgdiff.supported_formats), 'requires PyYAML') class YAMLDiffTestcase(CfgDiffTestCase): def test_yaml_same(self): self._test_same(cfgdiff.YAMLDiff, './tests/test_same_1-a.yaml', './tests/test_same_1-b.yaml') def test_yaml_different(self): self._test_different(cfgdiff.YAMLDiff, './tes...
class Read(object): def __init__(self, dir, file): self.dir = dir self.file = file if ((dir is not None) and (file is not None)): self.pth = os.path.join(dir, file) else: self.pth = None def __str__(self): return '{} fastq read'.format(self.file) ...
def validate_model(model, val_loader): print('Validating the model') model.eval() y_true = [] y_pred = [] with torch.no_grad(): for (step, (x, mel)) in enumerate(val_loader): (x, mel) = (Variable(x).cuda(), Variable(mel).cuda()) logits = model.forward_eval(mel) ...
.parametrize('prk,info,length,okm', [('c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5', 'f0f1f2f3f4f5f6f7f8f9', 42, '3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bfd5b'), ('06a6b88c5853361a06104c9ceb35b45cefa193f40c15fc244', 'b0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1...
def test_context_processing(app, client): answer_bp = flask.Blueprint('answer_bp', __name__) template_string = (lambda : flask.render_template_string('{% if notanswer %}{{ notanswer }} is not the answer. {% endif %}{% if answer %}{{ answer }} is the answer.{% endif %}')) _bp.app_context_processor def no...
def extractSayhellomtlSpace(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) in t...
class StubServerProtocolTCP(StubServerProtocol): def connection_made(self, transport): self.transport = transport self.addr = transport.get_extra_info('peername') self.buffer = b'' def data_received(self, data): self.buffer = utils.handle_dns_tcp_data((self.buffer + data), self.r...
def _get_probability_of_entries_kept(k: int, table_index: int) -> float: if (table_index > 5): return 1 pow_2_k = (2 ** k) if (table_index == 5): return (1 - ((1 - (2 / pow_2_k)) ** pow_2_k)) else: return (1 - ((1 - (2 / pow_2_k)) ** (_get_probability_of_entries_kept(k, (table_in...
class URLPathVersioning(BaseVersioning): invalid_version_message = _('Invalid version in URL path.') def determine_version(self, request, *args, **kwargs): version = kwargs.get(self.version_param, self.default_version) if (version is None): version = self.default_version if (...
def extractIdletranslationsWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('Kaifuku Jutsushi no Yarinaoshi', 'Kaifuku Jutsushi no Yarinaoshi ~ Sokushi Mahou to Skil...
('aea.cli.utils.package_utils.is_item_present', return_value=False) .parametrize('vendor', [True, False]) def test_is_item_present_unified(mock_, vendor): contex_mock = mock.MagicMock() contex_mock.agent_config.author = ('some_author' if vendor else 'another_author') public_id_mock = mock.MagicMock(author='...
class PaymentACK(): MAXIMUM_JSON_LENGTH = ((11 * 1000) * 1000) def __init__(self, payment: Payment, memo: Optional[str]=None) -> None: self.payment = payment self.memo = memo def to_dict(self) -> Dict[(str, Any)]: data: Dict[(str, Any)] = {'payment': self.payment.to_dict()} i...
def _make_tensor_usage_records_simple_multistream(par_ops_seq: List[List[Operator]]) -> List[TensorUsageRecord]: num_of_ops = len(par_ops_seq) tensor_records = defaultdict((lambda : TensorUsageRecord(tensor=None, first_op_idx=num_of_ops, last_op_idx=(- 1), size=None))) for (op_idx, par_ops) in enumerate(par...
def test_email_address_parsing(): s = 'my email is: foo"' iocs = find_iocs(s) assert (iocs['email_addresses_complete'] == ['foo"']) assert (iocs['email_addresses'] == ['']) s = 'Abc\\' iocs = find_iocs(s) print(iocs['email_addresses_complete']) print(iocs['email_addresses']) assert (...
.skip ('turbomole') def test_turbomole_cos(this_dir): def calc_getter(charge, mult): calc_kwargs = {'charge': charge, 'mult': mult, 'control_path': (this_dir / 'control_cos'), 'pal': 2} return Turbomole(**calc_kwargs) def gs_calc_getter(): return calc_getter(charge=0, mult=1) bench =...
def extractMoonlightMltBlogspotCom(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...
class OptionPlotoptionsBubbleSonificationContexttracksActivewhen(Options): def crossingDown(self): return self._config_get(None) def crossingDown(self, num: float): self._config(num, js_type=False) def crossingUp(self): return self._config_get(None) def crossingUp(self, num: floa...
class Solution2(): def pathSum(self, root: TreeNode, s: int) -> List[List[int]]: if (root is None): return [] stk = [[root, [], s]] ps = [] while stk: (curr, p, s) = stk.pop() if (curr is None): continue np = (p + [curr....
def backprop_dish(dY, X, *, inplace: bool=False, threads_per_block=128, num_blocks=128): _is_float_array(dY) _is_float_array(X, shape=dY.shape) out = dY if (not inplace): out = _alloc_like(dY, zeros=False) if (dY.dtype == 'float32'): backprop_dish_kernel_float((num_blocks,), (threads...
def _get_images() -> Dict[(str, str)]: ret: Dict[(str, str)] = {} image_names = ['test-auth', 'test-shadow', 'test-stats', 'kat-client', 'kat-server'] if (image := os.environ.get('AMBASSADOR_DOCKER_IMAGE')): ret['emissary'] = image else: image_names.append('emissary') try: su...
class TreeItemDelegate(QtGui.QStyledItemDelegate): def sizeHint(self, option, index): column = index.column() item = self.editor._tree.itemFromIndex(index) (expanded, node, instance) = self.editor._get_node_data(item) column = index.column() renderer = node.get_renderer(objec...
def test_transform_gif(tmp_path, fx_asset): src = str((fx_asset / 'nocomments-delay-100.gif')) dst = str((tmp_path / 'test_transform_gif.gif')) with Image(filename=src) as img: assert (len(img.sequence) == 46) assert (img.size == (350, 197)) for single in img.sequence: as...
class TestPythonChained(util.PluginTestCase): def setup_fs(self): config = self.dedent("\n matrix:\n - name: python\n sources:\n - '{}/**/*.txt'\n aspell:\n lang: en\n d: en_US\n hunspell:\n ...
def test_plot_style_copy_style(): style = PlotStyle('Test', 'red', 0.5, '.', 'o', 2.5) style.setEnabled(False) copy_style = PlotStyle('Copy') copy_style.copyStyleFrom(style) assert (style.name != copy_style.name) assert (style.color == copy_style.color) assert (style.alpha == copy_style.alph...
class TestCursorPagination(CursorPaginationTestsMixin): def setup_method(self): class MockObject(): def __init__(self, idx): self.created = idx class MockQuerySet(): def __init__(self, items): self.items = items def filter(self, q):...
class OptionSeriesArcdiagramSonificationDefaultspeechoptions(Options): def activeWhen(self) -> 'OptionSeriesArcdiagramSonificationDefaultspeechoptionsActivewhen': return self._config_sub_data('activeWhen', OptionSeriesArcdiagramSonificationDefaultspeechoptionsActivewhen) def language(self): retu...
def get_episodes(html, url): if ('_napi' in url): return get_episodes_from_api(html, url) state = get_state(html) check_login(state) deviation = state['']['deviation'] gallery = None for (key, value) in state[''].items(): if key.startswith('folder-deviations-gallery'): ...
class FeatureBar(HasPrivateTraits): parent = Instance(wx.Window) dock_control = Instance(DockControl) control = Instance(wx.Window) completed = Event() bg_color = Color(, allow_none=True) border_color = Color(2458543, allow_none=True) horizontal = Bool(True) def hide(self): if (s...
def test_expanding_sum_multiple_vars(df_time): expected_results = {'ambient_temp_expanding_sum': [np.nan, 31.31, 62.82, 94.97, 127.36, 159.98, 192.48, 225.0, 257.68, 291.44, 325.57, 359.65, 393.35, 427.24, 461.28], 'irradiation_expanding_sum': [np.nan, 0.51, 1.3, 1.95, 2.71, 3.13, 3.62, 4.19, 4.75, 5.49, 6.38, 6.85...
class HeatPerturbation(AbstractPerturbation): temperature_range: Tuple[(pd.NonNegativeFloat, pd.NonNegativeFloat)] = pd.Field((0, inf), title='Temperature range', description='Temparature range in which perturbation model is valid.', units=KELVIN) def sample(self, temperature: Union[(ArrayLike[float], SpatialDa...
_page.route('/table/delete_records', methods=['POST']) def delete_records(): res = check_uuid(all_data['uuid'], request.json['uuid']) if (res != None): return jsonify(res) ids = request.json['ids'] for id in ids: if (id in all_data['data']): all_data['deleted_rows'][id] = 1 ...