code
stringlengths
281
23.7M
class OptionSeriesDependencywheelSonificationTracksMappingNoteduration(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 SymbolicBitvecGenerator(): def __init__(self): self.unique_vector_name_counter = {} def get_sym_bitvec(self, constraint_type, gen, bv_size=256, unique=False, **kwargs): vector_name = ConstraintType[constraint_type.name].value label_template = (vector_name + '_gen{}') for k ...
def test_to_disk_writes_minified_manifest_as_default(manifest_dir): build({}, package_name('package'), manifest_version('ethpm/3'), version('1.0.0'), write_to_disk(manifest_root_dir=manifest_dir, manifest_name='1.0.0.json'), validate()) actual_manifest = (manifest_dir / '1.0.0.json').read_text() assert (act...
def test_regression(df_enc): random = np.random.RandomState(42) y = random.normal(0, 0.1, len(df_enc)) encoder = DecisionTreeEncoder(regression=True, random_state=random) encoder.fit(df_enc[['var_A', 'var_B']], y) X = encoder.transform(df_enc[['var_A', 'var_B']]) transf_df = df_enc.copy() tr...
def modexp_lr_k_ary(a, b, n, k=5): base = (2 << (k - 1)) table = ([1] * base) for i in range(1, base): table[i] = ((table[(i - 1)] * a) % n) r = 1 for digit in reversed(_digits_of_n(b, base)): for i in range(k): r = ((r * r) % n) if digit: r = ((r * ta...
class TestExtractGridFilter(unittest.TestCase): def make_scatter(self): pd = tvtk.PolyData() pd.points = (100 + (100 * random.random((1000, 3)))) verts = arange(0, 1000, 1) verts.shape = (1000, 1) pd.verts = verts pd.point_data.scalars = random.random(1000) pd...
class TestRepositoryExists(TestCase): def test_missing_arg(self): client = Mock() with pytest.raises(MissingArgument, match='No value for "repository" provided'): repository_exists(client) def test_repository_in_results(self): client = Mock() client.snapshot.get_repos...
.django_db def test_child_recipient_failures(client): create_recipient_profile_test_data(*TEST_RECIPIENT_PROFILES.values()) create_recipient_lookup_test_data(*TEST_RECIPIENT_LOOKUPS.values()) create_transaction_test_data() non_existent_duns = '' resp = client.get(recipient_children_endpoint(non_exis...
class EclrunConfig(): def __init__(self, config: EclConfig, version: str): self.simulator_name: str = config.simulator_name self.run_env: Optional[Dict[(str, str)]] = self._get_run_env(config.get_eclrun_env()) self.version: str = version def _get_run_env(self, eclrun_env: Optional[Dict[(...
def encode_numpy(obj, chain=None): if (not has_numpy): return (obj if (chain is None) else chain(obj)) if (has_cupy and isinstance(obj, cupy.ndarray)): obj = obj.get() if isinstance(obj, np.ndarray): if (obj.dtype.kind == 'V'): kind = b'V' descr = obj.dtype.de...
def test_base_types(): test_value = list([np.random.random((4, 2))]) out_value = map_nested_structure(test_value, mapping=(lambda x: torch.from_numpy(x)), in_place=True) def foo(elem): elem[0] = (elem[0] * 2) foo(test_value) assert (test_value is out_value) assert (test_value[0] is out_v...
class VectorList(list): def __init__(self, session, module_name): self.session = session self.module_name = module_name list.__init__(self) def find_first_result(self, names=[], format_args={}, condition=None, store_result=False, store_name=''): if (not callable(condition)): ...
class PythonShellPane(TaskPane): id = 'pyface.tasks.contrib.python_shell.pane' name = 'Python Shell' editor = Instance(PythonShell) bindings = List(Dict) commands = List(Str) def create(self, parent): logger.debug('PythonShellPane: creating python shell pane') self.editor = Pytho...
def get_entities_in_file(filename: pathlib.Path, should_delete: bool) -> Entities: flyte_ctx = context_manager.FlyteContextManager.current_context().new_builder() module_name = os.path.splitext(os.path.relpath(filename))[0].replace(os.path.sep, '.') with context_manager.FlyteContextManager.with_context(flyt...
() _context _option('--language', callback=captive_prompt_callback((lambda language: fuzzy_reverse_dict_lookup(language, INTL_LANG_OPTIONS)), choice_prompt_func((lambda : 'Please choose your language'), get_first_options(INTL_LANG_OPTIONS))), default='English', help='The language you wish to use the CLI in.', prompt=ch...
_default class LiveLocationAttachment(LocationAttachment): name = attr.ib(None, type=Optional[str]) expires_at = attr.ib(None, type=Optional[datetime.datetime]) is_expired = attr.ib(None, type=Optional[bool]) def _from_pull(cls, data): return cls(id=data['id'], latitude=((data['coordinate']['lat...
def compute_mean_similarities(results, ignore_query=False): similarities = [] for (query_key_1, result) in results: sims = [x[1] for x in result if ((not ignore_query) or (x[0] != query_key_1))] if (len(sims) == 0): similarity = None else: similarity = np.mean(sim...
(scope='session') def db_container(docker_backend, docker_network): image = docker_backend.ImageClass(os.environ.get('BODHI_INTEGRATION_POSTGRESQL_IMAGE', 'quay.io/bodhi-ci/postgresql'), tag='latest') run_opts = ['--rm', '-e', 'POSTGRES_HOST_AUTH_METHOD=trust', '--name', 'database', '--network', docker_network....
class ScheduleDialog(QDialog): def __init__(self, note, parent): QDialog.__init__(self, parent, ((Qt.WindowType.WindowSystemMenuHint | Qt.WindowType.WindowTitleHint) | Qt.WindowType.WindowCloseButtonHint)) self.mw = aqt.mw self.parent = parent self.note = note self.setup_ui()...
class Cast(SqlTree): type: Type value: Sql def _compile(self, qb): if ((qb.target == mysql) and (self.type <= T.string)): t = 'char' else: t = _compile_type(qb.target, self.type.as_nullable()) return (([f'CAST('] + self.value.compile_wrap(qb).code) + [f' AS {t...
def test_deployment_addresses_genesis_hash(network): manifest = ethpm.get_manifest('ipfs://testipfs-complex') ropsten = ethpm.get_deployment_addresses(manifest, 'ComplexNothing', ROPSTEN_GENESIS_HASH) assert (len(ropsten) == 1) network.connect('ropsten') assert (ropsten == ethpm.get_deployment_addre...
def test_precision_value_judged_only_scores(): current = pd.DataFrame(data=dict(user_id=['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'], prediction=[1.25, 1.0, 0.3, 0.9, 0.8, 0.7, 1.0, 0.5, 0.3], target=[1, 0, 0, 0, 0, 0, 0, 0, 1])) metric = PrecisionTopKMetric(k=3, no_feedback_users=True) report = Report(met...
class DefaultRAGGraphFactory(RAGGraphFactory): def __init__(self, system_app=None, default_model_name: str=None, **kwargs: Any) -> None: super().__init__(system_app=system_app) self._default_model_name = default_model_name self.kwargs = kwargs from dbgpt.rag.graph_engine.graph_engine...
class XLMRPreDecoder(FairSeqPreDecoder): def __init__(self, *, bos_id: int, eos_id: int): self.bos_id = bos_id self.eos_id = eos_id super(XLMRPreDecoder, self).__init__(bos_id=bos_id, eos_id=eos_id, piece_updater=XLMRPreDecoder._fairseq_to_sentencepiece) def _fairseq_to_sentencepiece(pie...
class TestDataStreamStats(): def test_failure_if_feature_not_implemented_in_version(self): clients = {'default': Client(info={'version': {'number': '7.6.0'}})} cfg = create_config() metrics_store = metrics.EsMetricsStore(cfg) telemetry_params = {'data-stream-stats-sample-interval': r...
class FQP(object): degree: int = 0 field_modulus: Union[(int, None)] = None mc_tuples: Union[(List[Tuple[(int, int)]], None)] = None def __init__(self, coeffs: Sequence[IntOrFQ], modulus_coeffs: Sequence[IntOrFQ]=()) -> None: if (self.field_modulus is None): raise AttributeError("Fie...
class TestConfigYamlDict(unittest.TestCase): test_filename = './config.yaml' test_dict = {'test_dict': [{'test_key_1': 'test_value_1'}, {'test_key_1': 'test_value_2'}]} valid_data = json.dumps(test_dict) invalid_data = '\n test_dict:\n test_key_1: test_value_1\n test_key_2\n ' ('...
def main(): ap = argparse.ArgumentParser(description='Merge master TSV with additional lexemes in batch') ap.add_argument('--quiet', '-q', action='store_false', dest='verbose', default=False, help='do not print output to stdout while processing') ap.add_argument('--verbose', '-v', action='store_true', defau...
class RMTTestRDepPriority(object): def rmttest_positive_01(self): config = TestConfig() reqset = RequirementSet(config) req1 = Requirement('Name: A\nType: master requirement\nSolved by: B', 'A', None, None, None) reqset.add_requirement(req1) req2 = Requirement('Name: B\nType:...
class VersionStatusType(sqlalchemy.types.TypeDecorator): impl = sqlalchemy.Integer cache_ok = True def process_bind_param(self, value: Optional[Union[(int, str, VersionStatus)]], dialect) -> Optional[int]: if (value is None): return None elif isinstance(value, int): r...
class PropertyPreprocessorNode(RegistryNode): type = NodeTypes.PREPROCESSOR def configured_preprocessor(self): return self.config(self.item.get('properties', {})) def process_arg(self, arg, node, raw_args): return self.configured_preprocessor.process_arg(arg, node, raw_args) def imports(...
def handle_hard_error(): global SESSION_ID, HARD_FAILS, HS_DELAY if (HS_DELAY == 0): HS_DELAY = 60 elif (HS_DELAY < (120 * 60)): HS_DELAY *= 2 if (HS_DELAY > (120 * 60)): HS_DELAY = (120 * 60) HARD_FAILS += 1 if (HARD_FAILS == 3): SESSION_ID = None
class BaseFilter(object): report_fields = ('name', 'passed_unchanged', 'passed_changed', 'failed', 'total_filtered', 'proportion_passed') def __init__(self, listener=None): self.passed_unchanged = 0 self.passed_changed = 0 self.failed = 0 self.listener = listener def filter_r...
def graphs_test9(): cfg = ControlFlowGraph() cfg.add_nodes_from((vertices := [BasicBlock(0, [Assignment(ListOperation([]), Call(imp_function_symbol('__x86.get_pc_thunk.bx'), [], Pointer(CustomType('void', 0), 32), 1)), Assignment(ListOperation([]), Call(imp_function_symbol('printf'), [Constant(5328, Pointer(Cus...
def remove_empty_containers(row: RecursiveRow) -> RecursiveRow: if isinstance(row, dict): for (key, value) in row.copy().items(): if isinstance(value, (dict, list)): value = remove_empty_containers(value) if (value in [{}, []]): del row[key] elif i...
def main(): module_spec = schema_to_module_spec(versioned_schema) mkeyname = 'name' fields = {'access_token': {'required': False, 'type': 'str', 'no_log': True}, 'enable_log': {'required': False, 'type': 'bool', 'default': False}, 'vdom': {'required': False, 'type': 'str', 'default': 'root'}, 'member_path':...
('wiring_config', [containers.WiringConfiguration(modules=['.module'], packages=['.package'])]) def test_relative_names_with_auto_package(): service = module.test_function() assert isinstance(service, Service) from samples.wiring.package.subpackage.submodule import test_function service = test_function(...
('Updater._write_updates_status_flag_to_disk') def test_should_run_updater_invalid_timestamp(mocked_write): TEST_INTERVAL = 3600 with mock.patch('Updater.last_required_reboot_performed') as mocked_last: mocked_last.return_value = True with mock.patch('Updater.read_dom0_update_flag_from_disk') as...
class TestNCLS(object): def setup_class(cls): pass def teardown_class(cls): pass def setup_method(self, method): reload(ncls) self.pList = [ncls_p] self.nList = [ncls_n] self.sList = [default_s] self.so = default_so self.so.tnList = self.nList[...
class SimpleVizGroup(lg.Group): INPUT = lg.Topic(RandomMessage) PLOT: ScatterPlot WINDOW: Window def setup(self) -> None: self.PLOT.configure(ScatterPlotConfig(x_field='x', y_field='y', labels={'bottom': 'Bottom Label', 'left': 'Left Label'}, styles={'red': ScatterPlotStyle(symbol='x', symbolSiz...
class JsNvd3Bar(JsNvd3): chartFnc = 'discreteBarChart' def x(self, column=None, js_funcs=None, profile=False): if (column is not None): self.fnc(('x(function(d){return d.%s})' % column)) elif (js_funcs is not None): self.fnc(('x(%s)' % JsUtils.jsConvertFncs(js_funcs, toSt...
def test_normalize_smallest_cool(capsys): outfile_one = NamedTemporaryFile(suffix='.cool', delete=False) outfile_one.close() outfile_two = NamedTemporaryFile(suffix='.cool', delete=False) outfile_two.close() args = '--matrices {} {} --normalize smallest -o {} {}'.format(matrix_one_cool, matrix_two_c...
def get_labeled_model_data_list_for_layout_document(layout_document: LayoutDocument, model: Model, document_features_context: DocumentFeaturesContext) -> Sequence[LabeledLayoutModelData]: data_generator = model.get_data_generator(document_features_context=document_features_context) model_data_list: Sequence[Lay...
class OptionPlotoptionsBarOnpoint(Options): def connectorOptions(self) -> 'OptionPlotoptionsBarOnpointConnectoroptions': return self._config_sub_data('connectorOptions', OptionPlotoptionsBarOnpointConnectoroptions) def id(self): return self._config_get(None) def id(self, text: str): ...
def includeme(config): settings = config.registry.settings session_provider_callable_config = settings.get(('%s.session_provider_callable' % CONFIG_KEY)) try_global_session = False if (not session_provider_callable_config): def session_provider_callable(request): return get_db_sessio...
class FLCoreLogger(): _instance = None def __new__(cls): if (cls._instance is None): cls._instance = super().__new__(cls) process_name = get_process_name() fmt = '{}[%(process)d] %(levelname)s: %(module)s: %(name)s: %(message)s'.format(process_name) cls.fo...
class _PyperfComparison(): kind: Optional[str] = None def from_raw(cls, raw: Any, *, fail: Optional[bool]=None) -> Optional['_PyperfComparison']: if (not raw): if fail: raise ValueError(f'missing {cls.kind}') return None elif isinstance(raw, cls): ...
_required _required def tasklog(request, hostname): context = collect_view_data(request, 'node_list') context['node'] = node = get_node(request, hostname) context['nodes'] = (node,) context['submenu_auto'] = '' nss = node.nodestorage_set.all().extra(select={'strid': 'CAST(id AS text)'}).values_list(...
def sram_test(comm, port): wb = comms[comm](port=port, csr_csv='csr.csv') wb.open() def mem_dump(base, length): for addr in range(base, (base + length), 4): if ((addr % 16) == 0): if (addr != base): print('') print('0x{:08x}'.format(add...
def nvmlUnitGetDevices(unit): c_count = c_uint(nvmlUnitGetDeviceCount(unit)) device_array = (c_nvmlDevice_t * c_count.value) c_devices = device_array() fn = _nvmlGetFunctionPointer('nvmlUnitGetDevices') ret = fn(unit, byref(c_count), c_devices) _nvmlCheckReturn(ret) return bytes_to_str(c_dev...
def sample_noise(size: tuple[(int, ...)], offset_noise: float=0.1, device: (Device | str)='cpu', dtype: (DType | None)=None, generator: (Generator | None)=None) -> Tensor: device = Device(device) noise = randn(*size, generator=generator, device=device, dtype=dtype) return (noise + (offset_noise * randn(*siz...
class TestDecisionId(TestCase): def setUp(self) -> None: pass def test_str(self): decision_id = DecisionId(DecisionTarget.ACTIVITY, 123) s = str(decision_id) self.assertIn(str(DecisionTarget.ACTIVITY), s) self.assertIn('123', s) def test_hash(self): d1 = Decis...
class MachineRequirements(): machine_type: str keep_alive: int = FAL_SERVERLESS_DEFAULT_KEEP_ALIVE base_image: (str | None) = None exposed_port: (int | None) = None scheduler: (str | None) = None scheduler_options: (dict[(str, Any)] | None) = None max_concurrency: (int | None) = None max...
class OptionSeriesScatter3dLabel(Options): def boxesToAvoid(self): return self._config_get(None) def boxesToAvoid(self, value: Any): self._config(value, js_type=False) def connectorAllowed(self): return self._config_get(False) def connectorAllowed(self, flag: bool): self....
class LESPeerRequestHandler(BasePeerRequestHandler): async def handle_get_block_headers(self, peer: LESProxyPeer, cmd: commands.GetBlockHeaders) -> None: self.logger.debug('Peer %s made header request: %s', peer, cmd) headers = (await self.lookup_headers(cmd.payload.query)) self.logger.debug...
def test_rollouts_from_python(): (env, agent) = (GymMazeEnv('CartPole-v0'), DummyCartPolePolicy()) sequential = SequentialRolloutRunner(n_episodes=2, max_episode_steps=2, deterministic=False, record_trajectory=False, record_event_logs=False, render=False) sequential.maze_seeding = MazeSeeding(env_seed=1234,...
class ContextInjector(logging.Filter): def filter(self, record): current_process = ContextInjector.get_current_process() current_hostname = socket.gethostname() record.host = current_hostname record.proc = current_process record.pid = '-' if (not isinstance(current_pr...
def _verify_bucket(bucket, expected_name): assert (bucket.name == expected_name) file_name = 'data_{0}.txt'.format(int(time.time())) blob = bucket.blob(file_name) blob.upload_from_string('Hello World') blob = bucket.get_blob(file_name) assert (blob.download_as_string().decode() == 'Hello World')...
def test_medium_interp(): coord_interp = td.Coords(**{ax: np.linspace((- 2), 2, (20 + ind)) for (ind, ax) in enumerate('xyz')}) orig_data = make_scalar_data() data_fit_nearest = coord_interp.spatial_interp(orig_data, 'nearest') data_fit_linear = coord_interp.spatial_interp(orig_data, 'linear') asser...
class LocalShellConnector(Connector): def execute(self, cmd, root=False): if ((not root) and (os.geteuid() == 0)): return execute_subprocess((['sudo', '-u', tools_user()[1]] + cmd)) if root: cmd = (['sudo', '-n'] + cmd) return execute_subprocess(cmd) def push(self...
def extractSporadicsporesBlogspotCom(item): if ('Songs' in item['tags']): return None (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('Chairman Husband Too Boorish', 'Chair...
.parametrize('custom_fields_dict, expected_custom_fields', [({}, {'minSuccessRatio': 1.0}), ({'concurrency': 99}, {'parallelism': '99', 'minSuccessRatio': 1.0}), ({'min_success_ratio': 0.271828}, {'minSuccessRatio': 0.271828}), ({'concurrency': 42, 'min_success_ratio': 0.31415}, {'parallelism': '42', 'minSuccessRatio':...
class OptionPlotoptionsBarSonificationTracksMappingVolume(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: str): self._...
class GaussianTanhTransformedHead(): mean: jnp.ndarray log_std: jnp.ndarray def sample(self, seed): return reparameterize_gaussian_and_tanh(self.mean, self.log_std, seed, return_log_pi=False) def sample_and_log_prob(self, key): return reparameterize_gaussian_and_tanh(self.mean, self.log_...
class Collection(Filter): filters = List(Instance(PipelineBase), record=True) _pipeline_ready = Bool(False) def __set_pure_state__(self, state): handle_children_state(self.filters, state.filters) super(Collection, self).__set_pure_state__(state) def default_traits_view(self): le ...
def extractYuNSTranslations(item): if ('(Manga)' in item['title']): return None (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol or frag)) or ('preview' in item['title'].lower())): return None titlemap = [('Akashic Records of the Bastard Ma...
class OptionSeriesScatter3dAccessibilityPoint(Options): def dateFormat(self): return self._config_get(None) def dateFormat(self, text: str): self._config(text, js_type=False) def dateFormatter(self): return self._config_get(None) def dateFormatter(self, value: Any): self....
def compare_and_connect_edge(node_id, nodes, motions, frames_compare, w_joints, w_joint_pos, w_joint_vel, w_root_pos, w_root_vel, w_ee_pos, w_ee_vel, w_trajectory, diff_threshold, num_comparison, verbose): node = nodes[node_id] res = [] num_nodes = len(nodes) motion_idx = node['motion_idx'] frame_en...
class HexaryTrie(): __slots__ = ('db', 'root_hash', 'is_pruning', '_ref_count', '_pending_prune_keys') BLANK_NODE_HASH = BLANK_NODE_HASH BLANK_NODE = BLANK_NODE def __init__(self, db, root_hash=BLANK_NODE_HASH, prune=False, ref_count=None): self.db = db validate_is_bytes(root_hash) ...
class gcodeParser(QObject): sig_log = pyqtSignal(int, str) def __init__(self): super().__init__() (str) def noComment(self, gcodeLine: str): line = '' line_flags = 0 for c in gcodeLine: if line_flags: if (c == ')'): if (line...
_util.copy_func_kwargs(AppDistributionOptions) def on_new_tester_ios_device_published(**kwargs) -> _typing.Callable[([OnNewTesterIosDevicePublishedCallable], OnNewTesterIosDevicePublishedCallable)]: options = AppDistributionOptions(**kwargs) def on_new_tester_ios_device_published_inner_decorator(func: OnNewTest...
class OptionPlotoptionsPackedbubbleSonificationContexttracksMappingNoteduration(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text...
class FileInfo(HasPrivateTraits): file_name = File() name = Property() size = Property() time = Property() date = Property() _property def _get_name(self): return basename(self.file_name) _property def _get_size(self): return getsize(self.file_name) _property ...
class OptionSeriesTilemapDataEvents(Options): def click(self): return self._config_get(None) def click(self, value: Any): self._config(value, js_type=False) def drag(self): return self._config_get(None) def drag(self, value: Any): self._config(value, js_type=False) de...
('pip', context_settings={'ignore_unknown_options': True, 'help_option_names': []}, help='For pip help use `bench pip help [COMMAND]` or `bench pip [COMMAND] -h`') ('args', nargs=(- 1)) _context def pip(ctx, args): import os from bench.utils.bench import get_env_cmd env_py = get_env_cmd('python') os.exe...
.parametrize('_input_type, expected_esd_err, message_to_encode', (('Custom type with extra properties in types', {'expected_exception': KeyError, 'match': 'age'}, {'types': {'EIP712Domain': [{'name': 'name', 'type': 'string'}], 'Person': [{'name': 'name', 'type': 'string'}, {'name': 'age', 'type': 'uint256'}]}, 'primar...
def test_nested_list(): length = ((), b'a', (b'b', b'c', b'd')) def dec(): return rlp.decode_lazy(rlp.encode(length)) assert isinstance(dec(), Sequence) assert (len(dec()) == len(length)) assert (evaluate(dec()) == length) with pytest.raises(IndexError): dec()[0][0] with pyte...
class ElevatedButton(ConstrainedControl): def __init__(self, text: Optional[str]=None, ref: Optional[Ref]=None, key: Optional[str]=None, width: OptionalNumber=None, height: OptionalNumber=None, left: OptionalNumber=None, top: OptionalNumber=None, right: OptionalNumber=None, bottom: OptionalNumber=None, expand: Unio...
def _parse_user_flags(): try: idx = list(sys.argv).index('--user-flags') user_flags_file = sys.argv[(idx + 1)] except (ValueError, IndexError): user_flags_file = '' if (user_flags_file and os.path.isfile(user_flags_file)): from ryu.utils import _import_module_file _im...
def test_capture_serverless_api_gateway_v2(event_api2, context, elasticapm_client): os.environ['AWS_LAMBDA_FUNCTION_NAME'] = 'test_func' _serverless def test_func(event, context): with capture_span('test_span'): time.sleep(0.01) return {'statusCode': 200, 'headers': {'foo': 'bar'...
class Copr(db.Model, helpers.Serializer, CoprSearchRelatedData): __table__ = outerjoin(_CoprPublic.__table__, _CoprPrivate.__table__) id = column_property(_CoprPublic.__table__.c.id, _CoprPrivate.__table__.c.copr_id) user = db.relationship('User', backref=db.backref('coprs')) group = db.relationship('Gr...
class QOFPrevalence(models.Model): pct = models.ForeignKey(PCT, null=True, blank=True, on_delete=models.PROTECT) practice = models.ForeignKey(Practice, null=True, blank=True, on_delete=models.PROTECT) start_year = models.IntegerField() indicator_group = models.CharField(max_length=10) register_descr...
def _tuple_forward(layer: Model[(Ragged, Ragged)], X: RaggedData, is_train: bool) -> Tuple[(RaggedData, Callable)]: (Yr, get_dXr) = layer(Ragged(*X), is_train) def backprop(dY: RaggedData) -> RaggedData: dXr = get_dXr(Ragged(*dY)) return (dXr.data, dXr.lengths) return ((Yr.data, Yr.lengths),...
def extractSoulreaperchroniclesBlogspotCom(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...
class Msg(object): def SetWithdrawAddress(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary(request, target, '/cosmos.distribution.v1beta1.Msg/SetWithdrawAddr...
class ValvePipeline(ValveManagerBase): def __init__(self, dp): self.dp = dp self.vlan_table = dp.tables['vlan'] self.classification_table = dp.classification_table() self.output_table = dp.output_table() self.egress_table = None self.egress_acl_table = None if...
def pwn(): payload = ('A' * (108 + 4)) payload += p32(read_plt) payload += p32(pppr_addr) payload += p32(0) payload += p32(binsh_addr) payload += p32(8) payload += p32(system_addr) payload += p32(_start_addr) payload += p32(binsh_addr) io.send(payload) io.send('/bin/sh\x00') ...
def test(): assert ('from spacy.tokens import Doc' in __solution__), 'Doc?' assert (len(spaces) == 4), 'Doc?' assert all((isinstance(s, bool) for s in spaces)), 'spaces' assert ([int(s) for s in spaces] == [0, 0, 0, 0]), '?' assert (doc.text == '!'), 'Doc?' __msg__.good('Nice!')
class RectDecoration(_Decoration, GroupMixin): defaults = [('filled', False, 'Whether to fill shape'), ('radius', 4, 'Corner radius as int or list of ints [TL TR BR BL]. 0 is square'), ('colour', '#000000', 'Colour for decoration'), ('line_width', 0, 'Line width for decoration'), ('line_colour', '#ffffff', 'Colour ...
class NoAuth(base.AbstractAuthenticationService): SERVICE_ID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 1) def hashPassphrase(self, authKey): return def localizeKey(self, authKey, snmpEngineID): return def authenticateOutgoingMsg(self, authKey, wholeMsg): raise error.StatusInformation(errorI...
class CatalogItemAppLinks(AbstractObject): def __init__(self, api=None): super(CatalogItemAppLinks, self).__init__() self._isCatalogItemAppLinks = True self._api = api class Field(AbstractObject.Field): android = 'android' ios = 'ios' ipad = 'ipad' iphone ...
class Choropleth(GraphChartJs.Chart): name = 'ChartJs Choropleth' tag = 'canvas' requirements = ('chartjs-chart-geo',) geo_map = ' _option_cls = OptChartJs.OptionsGeo _chart__type = 'choropleth' builder_name = 'GeoChoropleth' def options(self) -> OptChartJs.OptionsGeo: return sup...
def update_export_kwargs_from_export_method(old_f): def new_f(cls, model, input_args, save_path, export_method, **export_kwargs): if (export_method is not None): assert isinstance(export_method, str) original_export_method = export_method if ('_mobile' in export_method): ...
def _test_success_with_all_filters_place_of_performance_county(client): resp = client.post('/api/v2/search/spending_by_geography', content_type='application/json', data=json.dumps({'scope': 'place_of_performance', 'geo_layer': 'county', 'filters': non_legacy_filters()})) assert (resp.status_code == status.HTTP_...
class SizeNode(GivElm): total = 0 def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.size = kwargs['size'] def __repr__(self): return str(self.size) def __str__(self): return repr(self) def stat(self): super().stat() SizeNode.t...
class OefSearchDialogue(BaseOefSearchDialogue): __slots__ = ('_is_seller_search',) def __init__(self, dialogue_label: DialogueLabel, self_address: Address, role: Dialogue.Role, message_class: Type[OefSearchMessage]=OefSearchMessage) -> None: BaseOefSearchDialogue.__init__(self, dialogue_label=dialogue_l...
def test_deposit_sets_end_dynasty(concise_casper, funded_account, validation_key, deposit_amount, deposit_validator): validator_index = deposit_validator(funded_account, validation_key, deposit_amount) expected_end_dynasty = assert (concise_casper.validators__end_dynasty(validator_index) == expected_end_dy...
class _CRG(Module, AutoCSR): def __init__(self, platform, sys_clk_freq): self.rst = Signal() self.clock_domains.cd_sys_pll = ClockDomain() self.clock_domains.cd_sys = ClockDomain() self.clock_domains.cd_sys4x = ClockDomain(reset_less=True) self.clock_domains.cd_clk200 = Clock...
def test_mem_from_cgroup2_max_handling(elasticapm_client, tmpdir): proc_stat_self = os.path.join(tmpdir.strpath, 'self-stat') proc_stat = os.path.join(tmpdir.strpath, 'stat') proc_meminfo = os.path.join(tmpdir.strpath, 'meminfo') cgroup2_memory_limit = os.path.join(tmpdir.strpath, 'slice', 'memory.max')...
.parametrize('series_of_diffs, expected_updates, expected_deletions', (((), {}, []), (({}, {}), {}, []), (({b'1': b'1'}, {b'1': None}), {}, [b'1']), (({b'1': b'1'}, {b'1': b'2'}), {b'1': b'2'}, []), (({b'1': None},), {}, [b'1']), (({b'2': b'3'},), {b'2': b'3'}, []))) def test_db_diff_inspection(series_of_diffs, expecte...