code
stringlengths
281
23.7M
def test_mpi_task(serialization_settings: SerializationSettings): (task_config=MPIJob(num_workers=10, num_launcher_replicas=10, slots=1), requests=Resources(cpu='1'), cache=True, cache_version='1') def my_mpi_task(x: int, y: str) -> int: return x assert (my_mpi_task(x=10, y='hello') == 10) asser...
class JsHtmlIFrame(JsHtml.JsHtml): def src(self, src: Union[(str, primitives.JsDataModel)]): src = JsUtils.jsConvertData(src, None) return self.setAttribute('src', src) def srcdoc(self, content: Union[(str, primitives.JsDataModel)]): content = JsUtils.jsConvertData(content, None) ...
class SlaveVmDefine(object): def __init__(self, slave_vm): self.slave_vm = slave_vm self.vm = slave_vm.vm self._nss = {} def get_zpool(disk): try: return disk['zfs_filesystem'].split('/')[0] except (KeyError, IndexError): raise APIValidationError('...
class OptionSeriesFunnelDataDragdrop(Options): def draggableX(self): return self._config_get(None) def draggableX(self, flag: bool): self._config(flag, js_type=False) def draggableY(self): return self._config_get(None) def draggableY(self, flag: bool): self._config(flag, ...
def _config_to_hf(cls, curated_config: GPTNeoXConfig) -> Dict[(str, Any)]: out = config_to_hf(curated_config, [k for (k, _) in HF_CONFIG_KEYS]) if issubclass(cls, DecoderModule): return HF_SPECIFIC_CONFIG_DECODER.merge(out) else: return HF_SPECIFIC_CONFIG_CAUSAL_LM.merge(out)
class bsn_gentable_bucket_stats_request(bsn_stats_request): version = 6 type = 18 stats_type = 65535 experimenter = 6035143 subtype = 5 def __init__(self, xid=None, flags=None, table_id=None): if (xid != None): self.xid = xid else: self.xid = None ...
def _test_state_change(db, client, user, jwt, new_state, state, event_owner=True, error=True): session = get_session(db, user, event_owner=event_owner, state=state) data = json.dumps({'data': {'type': 'session', 'id': str(session.id), 'attributes': {'state': new_state}}}) response = client.patch(f'/v1/sessi...
def perimeter_point_from_centroid(polygon: Polygon, angle: float, output_obj: Optional[dict]=None) -> Point: if (output_obj is None): output_obj = {} max_distance = Point(polygon.bounds[0], polygon.bounds[1]).distance(Point(polygon.bounds[2], polygon.bounds[3])) endpoint = [(polygon.centroid.x + (ma...
class BmmRRRFunction(): def __init__(self, inputs_pool): self._it_pool = 0 self._as = [t['batch_a'] for t in inputs_pool] self._bs = [t['batch_b'] for t in inputs_pool] self._inputs_pool_size = len(inputs_pool) self._module = BmmRRRModule() def next_input(self): s...
class Agent(AgentT, Service): supervisor: SupervisorStrategyT = cast(SupervisorStrategyT, None) _channel: Optional[ChannelT] = None _channel_arg: Optional[Union[(str, ChannelT)]] _channel_kwargs: Dict[(str, Any)] _channel_iterator: Optional[AsyncIterator] = None _sinks: List[SinkT] _actors: ...
class ShellTask(PythonInstanceTask[T]): def __init__(self, name: str, debug: bool=False, script: typing.Optional[str]=None, script_file: typing.Optional[str]=None, task_config: T=None, inputs: typing.Optional[typing.Dict[(str, typing.Type)]]=None, output_locs: typing.Optional[typing.List[OutputLocation]]=None, **kw...
def extractOddnendsCom(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 tagmap...
def test_is_batchable(): assert (ListTransformer.is_batchable(typing.List[int]) is False) assert (ListTransformer.is_batchable(typing.List[str]) is False) assert (ListTransformer.is_batchable(typing.List[typing.Dict]) is False) assert (ListTransformer.is_batchable(typing.List[typing.Dict[(str, FlytePick...
def import_datetime(module_type): global datetime_module, mxDateTime_module module_type = (module_type.lower() if module_type else 'datetime') if (module_type == 'datetime'): if (datetime_module is None): import datetime as datetime_module return datetime_module elif (module_...
class Table(): cushion_segments: CushionSegments pockets: Dict[(str, Pocket)] table_type: TableType model_descr: Optional[TableModelDescr] = field(default=None) height: float = field(default=0.708) lights_height: float = field(default=1.99) def w(self) -> float: x2 = self.cushion_seg...
class Country(): short_name: str alpha2_code: str alpha3_code: str locale: str currency: str region: str country_id: str def __init__(self, shortName, alpha2_code, alpha3_code, locale, currency, region, country_id): self.short_name = shortName self.alpha2_code = alpha2_co...
('/api/ip/<endpoint_id>') def ips(endpoint_id): post_to_back_if_telemetry_enabled(**{'name': f'ip/{endpoint_id}'}) with session_scope() as session: ips_hits = get_ips(session, endpoint_id) dicts = [] for ih in ips_hits: dicts.append({'ip': ih[0], 'hits': ih[1]}) retur...
class RecommendationAttribute(StrEnum): acousticness = 'acousticness' danceability = 'danceability' duration_ms = 'duration_ms' energy = 'energy' instrumentalness = 'instrumentalness' key = 'key' liveness = 'liveness' loudness = 'loudness' mode = 'mode' popularity = 'popularity' ...
def get_stack_schemas(stack_version: Optional[str]='0.0.0') -> OrderedDictType[(str, dict)]: stack_version = Version.parse((stack_version or '0.0.0'), optional_minor_and_patch=True) current_package = Version.parse(load_current_package_version(), optional_minor_and_patch=True) stack_map = load_stack_schema_m...
def test_run_pos_args(): source = 'lmql\n "Summarize this text: {t1}{t2}: [SUMMARY]" where len(TOKENS(SUMMARY)) < 4\n return SUMMARY\n ' r1 = lmql.run_sync(source, 'This is ', 'a test.', model=lmql.model('random', seed=123)) r2 = lmql.run_sync(source, t1='This is ', t2='a test.', model=lmql.model('...
def make_function(name, nargs, function_deps, method_deps): def function_X(self, node): if node.kwarg_nodes: raise JSError(('Function %s does not support keyword args.' % name)) if (len(node.arg_nodes) not in nargs): raise JSError(('Function %s needs #args in %r.' % (name, na...
.parametrize(['obj', 'expected_requirements'], [(_a, [_a]), ((_r := RegisterPair(_a, _b)), [_r, _a, _b]), (Assignment(_a, _b), [_b]), (Assignment(ListOperation([_a]), _b), [_b]), (Assignment(UnaryOperation(OperationType.cast, [_a], contraction=True), _b), [_b]), (Assignment(UnaryOperation(OperationType.dereference, [_a...
class YamlRepository(DiskRepository): file_ending = 'yaml' open_mode_for_loading = 'r' open_mode_for_saving = 'w' def load(self, fp): data = yaml.safe_load(fp) if (not data): raise ClusterError('Empty cluster state file: {0}'.format(fp.name)) cluster = Cluster(**data)...
class MyApp(Mayavi): def run(self): from mayavi.sources.vtk_file_reader import VTKFileReader from mayavi.modules.outline import Outline from mayavi.modules.axes import Axes from mayavi.modules.grid_plane import GridPlane from mayavi.modules.image_plane_widget import ImagePlan...
class MockFullTextModels(FullTextModels): def __init__(self): model_impl_mock = MagicMock('model_impl') self.cv_model_mock = MagicMock(name='cv_model') super().__init__(segmentation_model=SegmentationModel(model_impl_mock), header_model=HeaderModel(model_impl_mock), name_header_model=NameMod...
def DoFuseLoop(f_cursor, s_cursor, unsafe_disable_check=False): proc = f_cursor.get_root() if (f_cursor.next() != s_cursor): raise SchedulingError(f'''expected the two loops to be fused to come one right after the other. However, the statement after the first loop is: {f_cursor.next()._node} , not the p...
class ObjectGroup(MibNode): status = 'current' objects = () description = '' def getStatus(self): return self.status def setStatus(self, v): self.status = v return self def getObjects(self): return getattr(self, 'objects', ()) def setObjects(self, *args, **kwa...
_static def get_conda_executable() -> Path: for path in [_FAL_CONDA_HOME, None]: conda_path = shutil.which(_CONDA_COMMAND, path=path) if (conda_path is not None): return conda_path else: raise RuntimeError('Could not find conda executable. Please install conda or set FAL_COND...
.parametrize('rpc_method', ['eth_getBlockByNumber']) def test_stalecheck_ignores_get_by_block_methods(request_middleware, rpc_method): with patch('web3.middleware.stalecheck._is_fresh', side_effect=[False, True]): request_middleware(rpc_method, []) assert (not request_middleware.web3.eth.get_block.c...
def test_pagination_with_three_items_three_per_page(): from feeder.util.feeder import paginate_response items = ['item1', 'item2', 'item3'] page = paginate_response(items, max_page_size=3) assert (page['size'] == 3) assert (page['data'] == items) assert (page['page'] == 1) assert (page['tota...
def dict_strip(file_1, file_2): with open(file_1, 'r', encoding='utf-8') as fd: list_A = [line.strip().upper() for line in fd if ((line[0] != '#') and (len(line) > 4))] set_A = set(list_A) with open(file_2, 'r', encoding='utf-8') as fd: for line in fd: if _debug: ...
class OptionPlotoptionsTreegraphSonificationDefaultinstrumentoptionsActivewhen(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(s...
class SMTPAction(ActionBase): def __init__(self, jail, name, host='localhost', ssl=False, user=None, password=None, sendername='Fail2Ban', sender='fail2ban', dest='root', matches=None): super(SMTPAction, self).__init__(jail, name) self.host = host self.ssl = ssl self.user = user ...
class GraphQLView(BaseGraphQLView): def format_error(error): formatted = BaseGraphQLView.format_error(error) if (isinstance(error, GraphQLError) and (error.original_error is not None)): error = error.original_error if (not extensions_settings.SHOW_ERROR_MESSAGE_HANDLER(error)): ...
class AbstractFieldProjectionMonitor(SurfaceIntegrationMonitor, FreqMonitor): custom_origin: Coordinate = pydantic.Field(None, title='Local Origin', description="Local origin used for defining observation points. If ``None``, uses the monitor's center.", units=MICROMETER) far_field_approx: bool = pydantic.Field...
def test_catch_invalid_reference_error() -> None: t = generate_graph_resources(3) field(t, 'dr_1', 'ds_1', 'f1').references.append((FieldAddress('I_dont_exist', 'x', 'y'), None)) field(t, 'dr_1', 'ds_1', 'f1').identity = 'email' with pytest.raises(ValidationError): generate_traversal({'email': '...
class CredStore(): path: Path = field(default=DEFAULT_CRED_STORE_FILE) store: dict[(str, Cred)] = field(default_factory=dict) def __post_init__(self): if (not isinstance(self.path, Path)): self.path = Path(self.path) def has_sessions(self) -> bool: for (key, cred) in self.sto...
class KubernetesNamespaceIterator(ResourceIterator): def iter(self): gcp = self.client try: for (data, metadata) in gcp.iter_kubernetes_namespaces(project_id=self.resource.parent()['projectId'], zone=self.resource['zone'], cluster=self.resource['name']): (yield FACTORIES[...
class Benchmark(base_benchmark.BaseBenchmark): def __init__(self, job_control: proto_control.JobControl, benchmark_name: str) -> None: self._benchmark_dir = None super(Benchmark, self).__init__(job_control, benchmark_name) def _validate(self) -> None: verify_source = False images...
def build_riesz_map(V, d): beta = Constant(0.0001) subs = [(1, 3)] if V.mesh().cell_set._extruded: subs += ['top'] x = SpatialCoordinate(V.mesh()) x -= Constant(([0.5] * len(x))) if (V.ufl_element().value_shape == ()): u_exact = exp(((- 10) * dot(x, x))) u_bc = u_exact ...
class RegularNode(Node[Metadata]): def __init__(self, label: str, args: Sequence[Node[Metadata]], kwargs: Mapping[(str, Node[Metadata])], metadata: Metadata, subgraph: Optional[Subgraph]=None) -> None: self._label = label self._args = tuple(args) self._kwargs = dict(kwargs) super()._...
class DeltaRLastRounds(): def __new__(cls, guesses=_np.arange(256, dtype='uint8'), words=None, ciphertext_tag='ciphertext', key_tag='key'): return _decorated_selection_function(_AttackSelectionFunctionWrapped, _delta_last_rounds, expected_key_function=_last_key, words=words, guesses=guesses, target_tag=ciph...
def test_dao_get_list_page(dao): for i in range(20): dao.create(ServeRequest(chat_scene='chat_data', sub_chat_scene='excel', prompt_type='common', prompt_name=f'my_prompt_{i}', content='Write a qsort function in python.', user_name=('zhangsan' if ((i % 2) == 0) else 'lisi'), sys_code='dbgpt')) res = dao...
def evaluate_uni_pos(uni_pos_dict: Dict[(str, List[Tuple[(str, float)]])], data: List[List[Tuple[(str, str)]]]): (total, correct) = (0, 0) for sentence in data: (tokens, gold) = tuple(zip(*sentence)) pred = [t[0] for t in predict_uni_pos_dict(uni_pos_dict, tokens)] total += len(tokens) ...
class SentRouteDetailView(OperatorDetailView): timestamp = fields.DataField('timestamp') filtered = fields.DataField('filtered') path = fields.RelatedViewField('path', 'ryu.services.protocols.bgp.operator.views.bgp.PathDetailView') peer = fields.RelatedViewField('sent_peer', 'ryu.services.protocols.bgp....
class OptionPlotoptionsSunburstSonificationTracksMappingGapbetweennotes(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 ExaQueryError(ExaRequestError): def __init__(self, connection, query, code, message): self.query = query super().__init__(connection, code, message) def get_params_for_print(self): params = super().get_params_for_print() params['session_id'] = self.connection.session_id() ...
def retry(logger=None): def wrapper(fp): async def retry_loop(*args, **kwargs): last_failed_time = (- 1) while True: try: (await fp(*args, **kwargs)) logger.debug(' decorated function %s exited, ending retry loop', fp.__name__) ...
def cleanup_snapshots(): for k in snapshot_list: si = snapshot_list[k] keep_last = keep_last_default if (k in servers_keep_last): keep_last = servers_keep_last[k] if (len(si) > keep_last): si.sort(reverse=True) si = si[keep_last:] for s...
def test_restructure_cfg_dowhile(task): task.graph.add_nodes_from((vertices := [BasicBlock(0, instructions=[Assignment(variable(name='i', version=0), Constant(0)), Assignment(variable(name='x', version=0), Constant(42))]), BasicBlock(1, instructions=[Phi(variable(name='i', version=1), [variable(name='i', version=0)...
def agency_test_data(db): baker.make('search.AwardSearch', award_id=1, latest_transaction_id=1) baker.make('search.AwardSearch', award_id=2, latest_transaction_id=2) baker.make('search.SubawardSearch', broker_subaward_id=1, latest_transaction_id=1, subaward_amount=50, awarding_agency_id=1003, funding_agency...
class OptionPlotoptionsFunnelSonificationDefaultinstrumentoptionsMappingTime(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: s...
def _user_changed(task_id, user_name, dc_name, affected_groups): try: user = User.objects.get(username=user_name) except User.DoesNotExist: if dc_name: _remove_user_from_monitoring_server(dc_name, user_name) elif affected_groups: _remove_user_from_group_related_mo...
class IfStatement(Statement, GotoMixin): condition: Expression true_body: Statement false_body: Optional[Statement] arguments_join = synthesized() def push_variables(self, condition) -> (VarStateMixin.variables_pre {true_body, false_body}): return condition.variables_post def variables_...
class Test_ofctl(unittest.TestCase): def _test(self, name, dp, method, args, request, reply, expected): print(('processing %s ...' % name)) waiters = {} dp.set_reply(reply, waiters) if reply: output = method(dp=dp, waiters=waiters, **args) else: output...
def extractAradescentWordpressCom(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...
def test_restructure_cfg_loop_two_back_edges(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'), Constant(3)]...
class OptionPlotoptionsAreasplineSonificationDefaultinstrumentoptionsMappingVolume(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, t...
class OptionsSparkLineBullet(OptionsSpark): def targetColor(self): return self._config_get(None) def targetColor(self, value): self._config(value) def targetWidth(self): return self._config_get(None) def targetWidth(self, value): self._config(value) def performanceCol...
def normalize_obs(dataset, eps=0.001): mean = dataset['observations'].mean(axis=0) std = (dataset['observations'].std(axis=0) + eps) o_t = ((dataset['observations'] - mean) / std) o_tp1 = ((dataset['next_observations'] - mean) / std) normalized_data = {'observations': o_t, 'next_observations': o_tp1...
class BugRegressionTest(unittest.TestCase): def test_regress_1312(self) -> None: self.maxDiff = None queries = [unif()] observations = {flip(): torch.tensor(1)} observed = BMGInference().to_dot(queries, observations) expected = '\ndigraph "graph" {\n N00[label=Flat];\n N01[...
class _ActionChunker(): def __init__(self, chunk_size: int, max_chunk_bytes: int, serializer: Serializer) -> None: self.chunk_size = chunk_size self.max_chunk_bytes = max_chunk_bytes self.serializer = serializer self.size = 0 self.action_count = 0 self.bulk_actions: L...
.requires_roxar def test_rox_surfaces_dtype_switching(roxar_project): srf = xtgeo.surface_from_roxar(roxar_project, 'TopReek', SURFCAT1, dtype='float32') assert (srf.ncol == 554) assert (srf.values.mean() == pytest.approx(1698.648, abs=0.01)) assert (srf.dtype == np.float32) srf.to_roxar(roxar_proje...
class BsStyles(): def __init__(self, page): self.page = page def remove(self, style: str): self.replate(style, None) return self def replace(self, style: str, new_style: str): for v in self.page.components.values(): if (style in v.attr['class']): i...
class ReferenceSegmenterDataGenerator(ContextAwareLayoutTokenModelDataGenerator): def iter_model_data_for_context_layout_token_features(self, token_features: ContextAwareLayoutTokenFeatures) -> Iterable[LayoutModelData]: (yield token_features.get_layout_model_data([token_features.token_text, token_features....
def extractKarmatranslationsWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('Across a Millennium to Love You', 'Across a Millennium to Love You', 'translated')] ...
class TestIsProgramInfo(unittest.TestCase): def test_is_program_info(self): self.assertTrue(is_program_info('solid0127__FRAG_BC_Run_56_pool_LC_CK_F3_CKSEQ26', 'solid0127__FRAG_BC_Run_56_pool_LC_CK_F3_CKSEQ26.solid_qc.programs')) self.assertTrue(is_program_info('solid0127__FRAG_BC_Run_56_pool_LC_CK_F...
def _show(package_name: str, version: Optional[str]=None) -> None: logger.info(f'Show package [{package_name}], version {version} information on storage ') if version: package_info = onedocker_repo_svc.package_repo.get_package_info(package_name, version) print(f' Package [{package_info.package_n...
class AdAccount(AdAccountMixin, AbstractCrudObject, HasAdLabels): def __init__(self, fbid=None, parent_id=None, api=None): self._isAdAccount = True super(AdAccount, self).__init__(fbid, parent_id, api) class Field(AbstractObject.Field): account_id = 'account_id' account_status = ...
def sortino_ratio(exp_return: FLOAT, downs_risk: FLOAT, risk_free_rate: FLOAT=0.005) -> FLOAT: type_validation(expected_return=exp_return, downside_risk=downs_risk, risk_free_rate=risk_free_rate) if (float(downs_risk) == 0): return np.nan else: return ((exp_return - risk_free_rate) / float(d...
class OptScale(Options): def name(self): return self._config_get() def name(self, text): self._config(text) def type(self): return self._config_get() def type(self, text): self._config(text) def domainMax(self): return self._config_get() def domainMax(self...
class TestPathlibGlobmatch(): cases = [['some/*/*/match', 'some/path/to/match', True, pathlib.G], ['some/**/match', 'some/path/to/match', False], ['some/**/match', 'some/path/to/match', True, pathlib.G], ['some/**/match/', 'some/path/to/match/', False, pathlib.G], ['.', '.', True], ['.', '', True], ['some/*/*/match...
def create_range_iter(arg: Dict[(str, Any)]): def create_tensor(attr: Dict[(str, Any)]): logger.debug(f'{attr}') result = copy.copy(attr) if (ATTR_RANGE in attr): ranges = set(attr[ATTR_RANGE]) for (key, val) in attr.items(): if (key in ranges): ...
_admin_required def LocationEditPages(request, location_slug): location = get_object_or_404(Location, slug=location_slug) if (request.method == 'POST'): action = request.POST['action'] logger.debug(('action=%s' % action)) logger.debug(request.POST) if ('Add Menu' == action): ...
class TerminalFormats(QObject): default_color = QColor('#FFFAFA') default_bg = QColor('#010101') re_code = re.compile('\\x1B\\[(?P<code>.*?)m') def __init__(self, parent=None): QObject.__init__(self, parent) self.current_format = QTextCharFormat() self.current_format.setForegroun...
def get_single_mur(mur_no): with db.engine.connect() as conn: rs = conn.execute(SINGLE_MUR, mur_no) row = rs.first() if (row is not None): mur_id = row['mur_id'] mur = {'type': get_es_type(), 'doc_id': 'mur_{0}'.format(row['mur_no']), 'no': row['mur_no'], 'case_serial...
class OptionSeriesScatterSonificationContexttracksMappingRate(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: str): se...
def test_new_message_user(session): data = {'attachments': [], 'body': 'test', 'irisSeqId': '1111111', 'irisTags': ['DeltaNewMessage'], 'messageMetadata': {'actorFbId': '1234', 'folderId': {'systemFolderId': 'INBOX'}, 'messageId': 'mid.$XYZ', 'offlineThreadingId': '', 'skipBumpThread': False, 'skipSnippetUpdate': F...
class ProxyPopupButton(Gtk.Frame): __gtype_name__ = 'ProxyPopupButton' def __init__(self, *args, **kwargs): super(ProxyPopupButton, self).__init__(*args, **kwargs) self._delegate = None def controller(self): if self._delegate: return self._delegate.controller def cont...
def nthSiblingOfView(view, n): subviews = subviewsOfView(superviewOfView(view)) numViews = fb.evaluateIntegerExpression((('[(id)' + subviews) + ' count]')) idx = fb.evaluateIntegerExpression((((('[(id)' + subviews) + ' indexOfObject:') + view) + ']')) newIdx = (idx + n) while (newIdx < 0): n...
('rocm.fused_elementwise.gen_function') def fused_elementwise_gen_function(func_attrs: Dict[(str, Any)]) -> str: custom_libs = Target.current().get_custom_libs(os.path.dirname(__file__), 'custom_math.h') return elementwise_common.fused_elementwise_gen_function(func_attrs=func_attrs, custom_libs=custom_libs, hea...
class FaceAttributes(BaseModel): headwear: Optional[float] frontal_gaze: Optional[float] eyes_visible: Optional[float] glasses: Optional[float] mouth_open: Optional[float] smiling: Optional[float] brightness: Optional[float] sharpness: Optional[float] pose: VideoFacePoses
class Migration(migrations.Migration): dependencies = [('django_etebase', '0032_auto__1409')] operations = [migrations.AddField(model_name='collection', name='uid', field=models.CharField(db_index=True, max_length=43, null=True, validators=[django.core.validators.RegexValidator(message='Not a valid UID', regex=...
def unregisterReinitialisationCallback(callback): with _reinitialisation_lock: try: _reinitialisation_callbacks.remove(callback) except ValueError: _logger.error('Callback {!r} is not registered'.format(callback)) return False else: _logger.deb...
def _filter_schema(schema, schema_tables, exclude_table_columns): tables = {} for (tbl_name, tbl_data) in schema['tables'].items(): if ((not schema_tables) or (tbl_name in schema_tables)): columns = {} exclude_columns = exclude_table_columns.get(tbl_name, []) for (col...
class FragmentCacheHelper(object): lifetime = 60 prefix = None def __init__(self, store, lifetime=None, prefix=None): self.store = store if (lifetime is not None): self.lifetime = lifetime if (prefix is not None): self.prefix = prefix def not_cached(self, ...
def create_template_simple(): rmap = RegisterMap() rmap.add_registers(Register('DATA', 'Data register', 0).add_bitfields(BitField(width=32, access='rw', hardware='ioe'))) rmap.add_registers(Register('CTRL', 'Control register', 4).add_bitfields(BitField(width=16, access='rw', reset=256, hardware='o'))) r...
def _get_orgs(org_type, org_codes): if (org_type == 'practice'): orgs = Practice.objects.order_by('code').only('code', 'name') if org_codes: orgs = orgs.filter((Q(code__in=org_codes) | Q(ccg_id__in=org_codes))) elif (org_type == 'ccg'): orgs = PCT.objects.filter(org_type='CCG...
def dict_args(func): (func) def wrapped(*args, **kwargs): m = [] p = {} for q in args: if isinstance(q, dict): p.update(q) else: m.append(q) p.update(kwargs) return func(*m, **p) return wrapped
.usefixtures('use_tmpdir') .parametrize('run_path_format', ['realization-<IENS>/iter-<ITER>', 'realization-<IENS>']) .parametrize('active_realizations', [[True], [True, True], [True, False], [False], [False, True]]) def test_delete_run_path(run_path_format, active_realizations): simulation_arguments = EnsembleExper...
def getTrans(): trans = QTranslator() trans.load('./ui/kmain.qm') app.installTranslator(trans) qmNames = ['kmain.qm', 'antiFrida.qm', 'callFunction.qm', 'custom.qm', 'dump_so.qm', 'dumpAddress.qm', 'fart.qm', 'fartBin.qm', 'fdClass.qm', 'jnitrace.qm', 'natives.qm', 'patch.qm', 'port.qm', 'searchMemory.q...
class Timer(): async def _get_time(self) -> float: library = sniffio.current_async_library() if (library == 'trio'): import trio return trio.current_time() else: import asyncio return asyncio.get_event_loop().time() def sync_start(self) -> ...
class WebSocketResponse(): def __init__(self, scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable): self.scope = scope self.receive = receive self.send = send def __await__(self): return self.asgi().__await__() async def asgi(self): while True: ...
('ecs_deploy.cli.get_client') def test_diff(get_client, runner): get_client.return_value = EcsTestClient('acces_key', 'secret_key') result = runner.invoke(cli.diff, (TASK_DEFINITION_FAMILY_1, str(TASK_DEFINITION_REVISION_1), str(TASK_DEFINITION_REVISION_3))) assert (not result.exception) assert (result....
class DriftStatsField(MetricResult): class Config(): dict_exclude_fields = {'characteristic_examples', 'characteristic_words', 'correlations'} field_tags = {'characteristic_examples': {IncludeTags.Render}, 'characteristic_words': {IncludeTags.Render}, 'correlations': {IncludeTags.Render}, 'type': {I...
def extractZelskytranslationsWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('Reverend Insanity', 'Reverend Insanity', 'translated')] for (tagname, name, tl_typ...
class JsHtmlTabs(JsHtml.JsHtml): def __getitem__(self, i: int): return JsHtmlPanel(self, component=self.component, js_code=("%s.firstChild.querySelector('div:nth-child('+ (parseInt(%s)+1) + ')')" % (self.varId, i)), page=self.page) def add_tab(self, name: str): return JsFncs.JsFunctions([JsObjec...
class OptionsCharts(Options): def y_columns(self): return self._config_get(None) _columns.setter def y_columns(self, cols): self._config(cols) def x_axis(self): return self._config_get(None) _axis.setter def x_axis(self, col): self._config(col) def config(self...
class BufferedQueueIterator(QueueIterator): def __init__(self, queue): super().__init__(queue) self._none = object() self._head = self._none def next(self, block=True, timeout=None): if (self._head is not self._none): item = self._head self._head = self._n...
def post_import_hook(): home = get_settings_folder() if (home is None): return '' filename = ((home + os.sep) + 'post_import.py') if os.path.isfile(filename): print('process {0}'.format(filename)) return _run_py_file_command(filename) else: return ''