code
stringlengths
281
23.7M
class BaseDummyPen(object): def __init__(self, *args, **kwargs): self.commands = [] def __str__(self): return _repr_pen_commands(self.commands) def addComponent(self, glyphName, transformation, **kwargs): self.commands.append(('addComponent', (glyphName, transformation), kwargs))
.unit def test_sort_create_update_create() -> None: resource_1 = models.DataCategory(organization_fides_key=1, fides_key='some_resource', name='Test resource 1', description='Test Description') resource_2 = models.DataCategory(organization_fides_key=1, fides_key='another_system', name='Test System 2', descripti...
_meta(characters.sakuya.Dagger) class Dagger(): name = '' description = '<style=Card.Name></style>,<style=Card.Name></style>' def clickable(self): me = self.me if (not (me.cards or me.showncards or me.equips)): return False return self.accept_cards([characters.sakuya.Dagg...
class CountingKubernetesProcessor(KubernetesProcessor): aconf: Config kind: KubernetesGVK key: str def __init__(self, aconf: Config, kind: KubernetesGVK, key: str) -> None: self.aconf = aconf self.kind = kind self.key = key def kinds(self) -> FrozenSet[KubernetesGVK]: ...
class BikeuStation(BikeShareStation): def __init__(self, info): super(BikeuStation, self).__init__() self.latitude = float(info['Latitude']) self.longitude = float(info['Longitude']) self.name = info['Name'] self.bikes = int(info['TotalAvailableBikes']) self.free = (i...
class ReceiverThread(Thread): def __init__(self, client, addr, parent): Thread.__init__(self) self.daemon = True self.client = client self.parent = parent def run(self): data = self.client.recv(1024) if data: self.parent.data_arrived(data) ...
class OptionPlotoptionsNetworkgraphSonificationDefaultinstrumentoptionsMappingHighpassFrequency(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 ...
(scope='function') def served_notice_history_for_tcf_feature(db: Session, fides_user_provided_identity) -> Generator: pref_1 = ServedNoticeHistory.create(db=db, data={'acknowledge_mode': False, 'serving_component': 'tcf_overlay', 'fides_user_device_provided_identity_id': fides_user_provided_identity.id, 'feature': ...
class TestHNSWMinHashJaccard(TestHNSW): def _create_random_points(self, high=50, n=100, dim=10): sets = np.random.randint(0, high, (n, dim)) return MinHash.bulk(sets, num_perm=128) def _create_index(self, minhashes, keys=None): hnsw = HNSW(distance_func=minhash_jaccard_distance, m=16, ef...
def dmenu_pass(command): if (command != 'dmenu'): return None try: dm_patch = (b'P' in run(['dmenu', '-h'], capture_output=True, check=False).stderr) except FileNotFoundError: dm_patch = False color = keepmenu.CONF.get('dmenu_passphrase', 'obscure_color', fallback='#222222') ...
_register_parser _set_msg_type(ofproto.OFPT_CONTROLLER_STATUS) class OFPControllerStatus(MsgBase): def __init__(self, datapath, status=None): super(OFPControllerStatus, self).__init__(datapath) self.status = status def parser(cls, datapath, version, msg_type, msg_len, xid, buf): msg = su...
.parametrize('deprecated_args', (dict(upward=5000.0, spacing=1), dict(upward=5000.0, shape=(6, 6)), dict(upward=5000.0, spacing=1, region=((- 4000.0), 0, 5000.0, 7000.0)), dict(upward=5000.0, shape=(6, 6), region=((- 4000.0), 0, 5000.0, 7000.0)))) def test_error_deprecated_args(coordinates_small, data_small, region, de...
def test_climb_lanczos(): calc = AnaPot() geoms = calc.get_path(2) gs_kwargs = {'perp_thresh': 0.5, 'reparam_check': 'rms', 'climb': True, 'climb_rms': 0.2, 'climb_lanczos': True, 'climb_lanczos_rms': 0.2} gs = GrowingString(geoms, (lambda : AnaPot()), **gs_kwargs) opt_kwargs = {'keep_last': 0, 'rms...
class DropColumnsTestCase(unittest.TestCase): def setUp(self): self.sequences = [SeqRecord(Seq('AAA'), id='s1'), SeqRecord(Seq('A-G'), id='s2'), SeqRecord(Seq('-A-'), id='s3')] def test_basic(self): r = list(transform.drop_columns(self.sequences, [slice(1, None)])) self.assertEqual([i.id...
.object(docker.models.images.ImageCollection, 'list') def test_list_images(mock_list_images): expected_image_tags = ['image:1', 'image:2', 'image:3'] mock_list_images.return_value = map((lambda tag: mock.Mock(tags=[tag])), expected_image_tags) new_docker_image = docker_image.DockerImage() images = new_d...
class TCNFMDecoder(nn.Module): def __init__(self, n_blocks=2, hidden_channels=64, out_channels=6, kernel_size=3, dilation_base=2, apply_padding=True, deploy_residual=False, input_keys=None, z_size=None, output_complete_controls=True): super().__init__() dilation_factor = (((dilation_base ** n_blocks...
class SubmitAsyncSearch(Runner): async def __call__(self, es, params): request_params = params.get('request-params', {}) response = (await es.async_search.submit(body=mandatory(params, 'body', self), index=params.get('index'), params=request_params)) op_name = mandatory(params, 'name', self)...
def fetch_subset(ctx, source, dest, fraction=DEFAULT_FRACTION, log=True): cmd = 'rdbms-subsetter {source} {dest} {fraction}'.format(**locals()) if log: cmd += ' --logarithmic' for table in (FULL_TABLES + EXCLUDE_TABLES): cmd += ' --exclude-table {0}'.format(table) for (table, key) in FOR...
def amazon_video_labels_parser(response): labels = [] for label in response['Labels']: parents = [] for parent in label['Label']['Parents']: if parent['Name']: parents.append(parent['Name']) boxes = [] for instance in label['Label']['Instances']: ...
def example(): from flet_contrib.color_picker import ColorPicker async def open_color_picker(e): e.control.page.dialog = d d.open = True (await e.control.page.update_async()) color_picker = ColorPicker(color='#c8df6f', width=300) color_icon = ft.IconButton(icon=ft.icons.BRUSH, on...
class Range_Expression(Expression): def __init__(self, n_first, t_first_colon, n_last, t_second_colon=None, n_stride=None): super().__init__() assert isinstance(n_first, Expression) assert isinstance(n_last, Expression) assert isinstance(t_first_colon, MATLAB_Token) if t_seco...
.parametrize('range_header, exp_content_range, exp_content', [('bytes=1-3', 'bytes 1-3/16', '123'), ('bytes=-3', 'bytes 13-15/16', 'def'), ('bytes=8-', 'bytes 8-15/16', '89abcdef'), ('words=1-3', None, 'abcdef'), ('bytes=15-30', 'bytes 15-15/16', 'f'), ('bytes=0-30', 'bytes 0-15/16', 'abcdef'), ('bytes=-30', 'bytes 0-1...
class Constraints(): def __init__(self, *args, **kwargs): self.binary = kwargs['binary'] self.constraints = set() self.constraints.add(frozenset(self.binary.functions.functions)) def to_json(self): query = [] for constraint in self.constraints: constraint = li...
class PetersburgVM(ByzantiumVM): fork = 'petersburg' block_class: Type[BlockAPI] = PetersburgBlock _state_class: Type[StateAPI] = PetersburgState create_header_from_parent = staticmethod(create_petersburg_header_from_parent) compute_difficulty = staticmethod(compute_petersburg_difficulty) config...
def home(request): records = Record.objects.all() if (request.method == 'POST'): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if (user is not None): login(request, user) ...
class OptionSeriesPieSonificationTracksMappingPlaydelay(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._co...
class TestFastaChromIterator(unittest.TestCase): def test_fastachromiterator(self): fp = io.StringIO(fasta_data) fasta = FastaChromIterator(fp=fp) expected = (('chr2L', 'Cgacaatgcacgacagagga\nagcagCTCAAGATAccttct'), ('chr2R', 'CTCAAGATAccttctacaga\nCgacaatgcacgacagagga')) nchroms = 0...
def test_should_erase_return_data_with_vm_error(computation): assert (computation.get_gas_remaining() == 100) computation.return_data = b'\x1337' with computation: raise VMError('Triggered VMError for tests') assert computation.should_erase_return_data assert (computation.return_data == b'')
_stats() def compile_model(tensor: Union[(Tensor, List[Tensor])], target: backend.target.Target, workdir: str, test_name: str, profile_devs: List[int]=None, dynamic_profiling_strategy: DynamicProfileStrategy=DynamicProfileStrategy.MAX, dll_name: str='test.so', num_runtimes: int=AIT_DEFAULT_NUM_RUNTIMES, profile_dir: st...
def gpio_commands(cmd): res = False cmdarr = cmd.split(',') cmdarr[0] = cmdarr[0].strip().lower() if (cmdarr[0] == 'gpio'): pin = (- 1) val = (- 1) gi = (- 1) logline = '' try: pin = int(cmdarr[1].strip()) val = int(cmdarr[2].strip()) ...
def parse_rpn(rpn) -> Root: from ast import literal_eval stack = [] for e in rpn.split(' '): if (e == '+'): (b, a) = (stack.pop(), stack.pop()) stack.append(Addition(a, b)) elif (e == '*'): (b, a) = (stack.pop(), stack.pop()) stack.append(Multi...
def test_verify_location_message(base_message): msg = base_message msg.type = MsgType.Location msg.attributes = LocationAttribute(latitude=0.0, longitude=0.0) msg.verify() with pytest.raises(AssertionError) as exec_info: msg.attributes = LocationAttribute(latitude='0.0', longitude=1.0) ...
def remove_from_parent_config(zone_key: ZoneKey): parent_config_path = (ROOT_PATH / f"config/zones/{zone_key.split('-')[0]}.yaml") if parent_config_path.exists(): with YamlFilePatcher(parent_config_path) as f: sub_zone_names = f.content['subZoneNames'] if (zone_key in sub_zone_na...
class ActiveUserSelectorUtils(): def convert_to_probability(user_utility: torch.Tensor, fraction_with_zero_prob: float, softmax_temperature: float, weights=None) -> torch.Tensor: if (weights is None): weights = torch.ones(len(user_utility), dtype=torch.float) num_to_zero_out = math.floor...
def greet_user(): path = Path('user_info.json') user_dict = get_stored_user_info(path) if user_dict: print(f"Welcome back, {user_dict['username']}!") print(f"Hope you've been playing some {user_dict['game']}. ") print(f"Have you seen a {user_dict['animal']} recently?") else: ...
class BaseTemplateAttack(BasePartitionedAttack): def __init__(self, container_building, selection_function, reverse_selection_function, model, convergence_step=None, partitions=None, precision='float32'): super().__init__(selection_function=selection_function, model=model, precision=precision, discriminant=...
def process_specimen(fasm_file, params_json): (sites, diff_tiles) = create_sites_from_fasm(fasm_file) with open(params_json) as f: params = json.load(f) count = 0 for p in params['tiles']: tile = p['tile'] for site in p['site'].split(' '): site_y = (int(site[(site.fin...
def init(model: Model[(SeqT, SeqT)], X: Optional[SeqT]=None, Y: Optional[SeqT]=None) -> None: layer: Model[(ArrayXd, ArrayXd)] = model.layers[0] layer.initialize(X=(_get_array(model, X) if (X is not None) else X), Y=(_get_array(model, Y) if (Y is not None) else Y)) for dim_name in layer.dim_names: v...
class TestAttribute(util.TestCase): MARKUP = '\n <div id="div">\n <p id="0">Some text <span id="1"> in a paragraph</span>.</p>\n <a id="2" href=" <span id="3">Direct child</span>\n <pre id="pre">\n <span id="4">Child 1</span>\n <span id="5">Child 2</span>\n <span id="6">Child 3</span>\n <...
def to_2d(arr: np.ndarray, axis: int) -> np.ndarray: arr = np.asarray(arr) axis = ((arr.ndim + axis) if (axis < 0) else axis) if (axis >= arr.ndim): raise ValueError(f'axis {axis} is out of array axes {arr.ndim}') tr_axes = list(range(arr.ndim)) tr_axes.pop(axis) tr_axes.append(axis) ...
class OptionPlotoptionsPolygonSonificationDefaultinstrumentoptionsMappingFrequency(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 FaucetUntaggedSameVlanIPv6RouteTest(FaucetUntaggedTest): CONFIG_GLOBAL = '\nvlans:\n 100:\n description: "untagged"\n faucet_vips: ["fc00::10:1/112", "fc00::20:1/112"]\n routes:\n - route:\n ip_dst: "fc00::10:0/112"\n ip_gw: "fc00::10:2"\n ...
class TestOFPActionVlanVid(unittest.TestCase): type_ = {'buf': b'\x00\x01', 'val': ofproto.OFPAT_SET_VLAN_VID} len_ = {'buf': b'\x00\x08', 'val': ofproto.OFP_ACTION_VLAN_VID_SIZE} vlan_vid = {'buf': b'<\x0e', 'val': 15374} zfill = (b'\x00' * 2) buf = (((type_['buf'] + len_['buf']) + vlan_vid['buf'])...
('devo ter a seguinte tarefa para fazer') def checar_se_tarefa_esta_para_ser_feita(context): feature_table = context.table['0'] tarefa = {} tarefa['title'] = feature_table['nome'] tarefa['description'] = feature_table['descricao'] tarefa['done'] = literal_eval(feature_table['estado']) response =...
class ExpandableFieldsSerializerMixinTests(SerializerMixinTestCase): def serialize(self, **context): return OwnerTestSerializer(self.owner_tyrell, context=context).data def expand_instance_id(self, instance): return instance.pk def test_no_expansion(self): self.assertDictEqual(self.s...
def test_multi_model_can_from_dict(): model = chain(Maxout(5, 10, nP=2), Maxout(2, 3)).initialize() model_dict = model.to_dict() assert model.can_from_dict(model_dict) assert chain(Maxout(5, 10, nP=2), Maxout(2, 3)).can_from_dict(model_dict) resized = chain(Maxout(5, 10, nP=3), Maxout(2, 3)) ass...
class TestFBNetV3MaskRCNNFPNFP32(RCNNBaseTestCases.TemplateTestCase): def setup_custom_test(self): super().setup_custom_test() self.cfg.merge_from_file('detectron2go://mask_rcnn_fbnetv3g_fpn.yaml') def test_inference(self): self._test_inference() _parameterized_test_export([['_ops', ...
(scope='function') def powerconfig(request, powerwidget): class PowerConfig(libqtile.confreader.Config): auto_fullscreen = True keys = [] mouse = [] groups = [libqtile.config.Group('a')] layouts = [libqtile.layout.Max()] floating_layout = libqtile.resources.default_co...
class DailyDBTestDBCase(UnitTestDBBase): def setUp(self): super(DailyDBTestDBCase, self).setUp() from stalker import Status, StatusList self.status_new = Status.query.filter_by(code='NEW').first() self.status_wfd = Status.query.filter_by(code='WFD').first() self.status_rts = ...
class IndexMeta(DocumentMeta): _document_initialized = False def __new__(cls, name, bases, attrs): new_cls = super().__new__(cls, name, bases, attrs) if cls._document_initialized: index_opts = attrs.pop('Index', None) index = cls.construct_index(index_opts, bases) ...
class TestDeletedTickets(PaginationTestCase): __test__ = True ZenpyType = Ticket api_name = 'tickets' expected_single_result_type = TicketAudit object_kwargs = dict(subject='test', description='test') pagination_limit = 10 def create_objects(self): job_status = self.create_multiple_z...
class EnumsTest(unittest.TestCase): .task(taskno=1) def test_parse_log_level_set_ing(self): self.assertIs(parse_log_level('[INF]: File deleted'), LogLevel.INFO, msg='The Log level is incorrect') .task(taskno=1) def test_parse_log_level_set_wrn(self): self.assertIs(parse_log_level('[WRN]:...
def extractTranslationsdrtWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('iceblade magician', 'The Iceblade Magician Rules over the World', 'translated'), ('worten...
def get_rulesets(ruledir, recurse): if (os.path.isdir(ruledir) and recurse): yaml_files = [y for x in os.walk(ruledir) for y in glob(os.path.join(x[0], '*.yaml'))] elif (os.path.isdir(ruledir) and (not recurse)): yaml_files = get_files(ruledir, 'yaml') elif os.path.isfile(ruledir): y...
class ConfigManager(): data: ConfigData config_entry: ConfigEntry def update(self, config_entry: ConfigEntry): data = config_entry.data options = config_entry.options result = ConfigData() result.name = data.get(CONF_NAME) result.host = data.get(CONF_HOST) res...
class SOEFConnection(Connection): connection_id = PUBLIC_ID DEFAULT_CONNECTION_CHECK_TIMEOUT: float = 15.0 DEFAULT_CONNECTION_CHECK_MAX_RETRIES: int = 3 def __init__(self, **kwargs: Any) -> None: if (kwargs.get('configuration') is None): kwargs['excluded_protocols'] = (kwargs.get('ex...
class PrettyTable(object): def __init__(self, df, tstyle=None, header_row=False, header_col=True, center=False, rpt_header=0): self.df = df self.num_rows = df.shape[0] self.num_cols = df.shape[1] self.header_row = header_row self.header_col = header_col self.style = t...
def test_logout_ise(): testutil.add_response('login_response_200') testutil.add_response('logout_response_500') testutil.add_response('api_version_response_200') client = testutil.get_client() logout = client.logout() assert (logout[0] is None) assert (logout[1].status == 500)
class TestsAchromatic(util.ColorAsserts, unittest.TestCase): def test_achromatic(self): self.assertEqual(Color('#222222').convert('jzczhz').is_achromatic(), True) self.assertEqual(Color('#222222').convert('jzczhz').set('cz', (lambda c: (c + 1e-08))).is_achromatic(), True) self.assertEqual(Co...
def _test_correct_response_for_recipient_location_state_without_geo_filters(client): resp = client.post('/api/v2/search/spending_by_geography', content_type='application/json', data=json.dumps({'scope': 'recipient_location', 'geo_layer': 'state', 'filters': {'time_period': [{'start_date': '2018-10-01', 'end_date': ...
def test_user_card_management(client, msend): assert ('_test_' in settings.STRIPE_PUBLISHABLE_KEY) assert ('_test_' in settings.STRIPE_SECRET_KEY) assert (stripe.api_key in settings.STRIPE_TEST_SECRET_KEY) r = client.post('/register', data={'email': '', 'password': 'uva'}) assert (r.status_code == 3...
class TestCredentialsOffline(): def test_repr(self): c = Credentials('id', 'secret') assert repr(c).startswith('Credentials(') c.close() def test_credentials_initialisation(self): Credentials(client_id='id', client_secret='secret', redirect_uri='uri').close() def test_credent...
class StructuredTransforms1DInterfacesRight(TestCase, Common): def setUp(self): super().setUp() self.seq = nutils.transformseq.StructuredTransforms(x1, (nutils.transformseq.IntAxis(0, 3, 9, 0, True),), 0) self.check = ((x1, i10, e0), (x1, i11, e0), (x1, i12, e0)) self.checkmissing = ...
class _MockAsyncCallableDSL(_MockCallableDSL): _NAME: str = 'mock_async_callable' def __init__(self, target: Union[(str, type)], method: str, caller_frame_info: Traceback, callable_returns_coroutine: bool, allow_private: bool=False, type_validation: bool=True) -> None: self._callable_returns_coroutine =...
def get_installedversion(): json_query = xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "method": "Application.GetProperties", "params": {"properties": ["version", "name"]}, "id": 1 }') json_query = json.loads(json_query) version = 14 if ('result' in json_query): if ('version' in json_query['result'])...
class CacheDecorator(CacheHashMixin): def __init__(self, handler: CacheHandler, key: Optional[str], duration: Union[(int, str, None)]='default'): super().__init__() self._cache = handler self.key = key self.duration = duration self.add_strategy('args') self.add_strate...
def get_lpddr5_phy_init_sequence(phy_settings, timing_settings): from litedram.phy.lpddr5.basephy import FREQUENCY_RANGES from litedram.phy.lpddr5.commands import SpecialCmd, MPC, BankOrganization rl = phy_settings.cl wl = phy_settings.cwl wck_ck_ratio = phy_settings.wck_ck_ratio bl = 16 dq_...
.parametrize('_estimator, _importance', _estimators_importance) def test_feature_importances(_estimator, _importance, df_test): (X, y) = df_test sel = RecursiveFeatureAddition(_estimator, threshold=(- 100)).fit(X, y) _importance.sort(reverse=True) assert (list(np.round(sel.feature_importances_.values, 4...
def stop_task_execution(args): workflow_execution_id = int(args.workflow_execution_id) task_name = args.task_name ops.stop_task_execution(workflow_execution_id=workflow_execution_id, task_name=task_name) print(f'Stopping execution of task: {task_name} of workflow execution: {workflow_execution_id}.')
def test_blobValueOf_specificValues(): test_values = ['Value without newline', 'Value with \nembedded\n newlines', '\nValue with single enclosing newlines\n', '\n\nValue with double enclosing newlines\n\n', '', *[('\n' * c) for c in (1, 2, 3, 10)]] for val in test_values: print(f'blobValueOf() {val!r}')...
class OptionSonificationGlobalcontexttracksMappingFrequency(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...
def sdiv(computation: ComputationAPI) -> None: (numerator, denominator) = map(unsigned_to_signed, computation.stack_pop_ints(2)) pos_or_neg = ((- 1) if ((numerator * denominator) < 0) else 1) if (denominator == 0): result = 0 else: result = (pos_or_neg * (abs(numerator) // abs(denominato...
class PedersenMMRProof(): def __init__(self, root: FQ, position, item: Point, peaks: List[Point], siblings: List[Point]): self.root = root self.position = position self.item = item self.peaks = peaks self.siblings = siblings self.zkp = None assert PedersenMMR....
() ('--input', '-i', 'input_', required=True, help='Input path') ('--output', '-o', help='Output path') ('--all', 'all_', is_flag=True, help='Sync all the things?') ('--overwrite', is_flag=True, help='Overwrite local files') def sync(input_: str, output: str, all_: bool, overwrite: bool) -> None: print('Syncing')
.parametrize('input_exts, input_files, matches', [([], ['test.f', 'test.F', 'test.f90', 'test.F90', 'test.f03', 'test.F03', 'test.f18', 'test.F18', 'test.f77', 'test.F77', 'test.f95', 'test.F95', 'test.for', 'test.FOR', 'test.fpp', 'test.FPP'], ([True] * 16)), ([], ['test.ff', 'test.f901', 'test.f90.ff'], [False, False...
class TestObserverError(unittest.TestCase): def setUp(self): push_exception_handler(reraise_exceptions=True) self.addCleanup(pop_exception_handler) def test_trait_is_not_list(self): team = Team() team.observe((lambda e: None), trait('leader').list_items()) person = Person...
_mgr_cli.command('delete') ('--name', required=True, help='Repository name', type=str) ('--yes', is_flag=True, callback=delete_callback, expose_value=False, prompt='Are you sure you want to delete the repository?') _context def _delete(ctx, name): logger = logging.getLogger('curator.repomgrcli._delete') client ...
class TestVTKDocMassager(unittest.TestCase): def test_doc_massage(self): doc = 'This is a test. All VTK classes and vtk classes\nare named like this: vtkActor, vtkLODProperty,\nvtkXMLDataReader, vtk3DSImporter etc. The methods \nof a VTK object are like GetData, GetOutput, \nSetRepresentationToWireframe. ...
class Tile(object): def __init__(self, tilename, tile_dbs): self.tilename = tilename self.tilename_upper = self.tilename.upper() self.tile_dbs = tile_dbs self.wires = None self.sites = None self.pips = None self.pips_by_name = {} def yield_sites(sites)...
class OptionPlotoptionsAreasplineSonificationContexttracksMappingHighpassFrequency(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...
def check_prescribing_data_in_bigquery(date, bq_client): if (not settings.CHECK_DATA_IN_BQ): return results = bq_client.query(('\n SELECT COUNT(*)\n FROM {hscic}.prescribing_v2\n WHERE month = TIMESTAMP("%s")\n ' % (date,))) assert (results.rows[0][0] > 0)
def quadrupole3d_21(ax, da, A, bx, db, B, R): result = numpy.zeros((6, 6, 3), dtype=float) x0 = ((ax + bx) ** (- 1.0)) x1 = (x0 * ((ax * A[0]) + (bx * B[0]))) x2 = (- x1) x3 = (x2 + R[0]) x4 = (x2 + B[0]) x5 = (x3 * x4) x6 = (2.0 * x5) x7 = (x0 + x6) x8 = (x3 * x7) x9 = (x2 +...
def create_suffix_array(suffix_array, data, suffix_array_algorithm): if (suffix_array_algorithm == 'sais'): sais(data, suffix_array) elif (suffix_array_algorithm == 'divsufsort'): divsufsort(data, suffix_array) else: raise Error('Bad suffix array algorithm {}.'.format(suffix_array_al...
class SocialLinkList(ResourceList): def query(self, view_kwargs): query_ = self.session.query(SocialLink) query_ = event_query(query_, view_kwargs) return query_ view_kwargs = True methods = ['GET'] schema = SocialLinkSchema data_layer = {'session': db.session, 'model': Socia...
def write_file(features: List[str], expected_records: List[Dict[(str, Any)]]) -> bytes: seen_channels: Set[str] = set() seen_schemas: Set[str] = set() output = BytesIO() writer = Writer(output=output, index_types=index_type_from_features(features), compression=CompressionType.NONE, repeat_channels=('rch...
def fat_tree_topology(k): if (not isinstance(k, int)): raise TypeError('k argument must be of int type') if ((k < 1) or ((k % 2) == 1)): raise ValueError('k must be a positive even integer') topo = DatacenterTopology(type='fat_tree') topo.name = ('fat_tree_topology(%d)' % k) n_core =...
class OptionSeriesTimelineSonificationDefaultinstrumentoptionsMappingLowpass(Options): def frequency(self) -> 'OptionSeriesTimelineSonificationDefaultinstrumentoptionsMappingLowpassFrequency': return self._config_sub_data('frequency', OptionSeriesTimelineSonificationDefaultinstrumentoptionsMappingLowpassFre...
class PortalFS(_utils.FSTree): def __init__(self, root: Optional[str]=None): if (root is None): root = '~/BENCH' super().__init__(root) self.jobs = PortalJobsFS(self.root) def currentjob(self) -> str: return self.jobs.requests.current def queues(self) -> queue_mod...
def set_widget_style(widget, dark_theme=False): palette = widget.palette() if dark_theme: palette.setColor(QtGui.QPalette.Window, QtGui.QColor(53, 53, 53)) palette.setColor(QtGui.QPalette.WindowText, QtCore.Qt.white) palette.setColor(QtGui.QPalette.Base, QtGui.QColor(25, 25, 25)) ...
class PyperfResultsFile(): SUFFIX = '.json' COMPRESSED_SUFFIX = '.json.gz' COMPRESSOR = gzip _SUFFIXES = (SUFFIX, COMPRESSED_SUFFIX) def from_raw(cls, raw: Any) -> 'PyperfResultsFile': if (not raw): raise ValueError(raw) elif isinstance(raw, cls): return raw ...
class OptionPlotoptionsAreasplineSonificationTracksMappingNoteduration(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 OptionSeriesStreamgraphSonificationTracksMappingNoteduration(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): ...
_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestTabularEditor(BaseTestMixin, UnittestTools, unittest.TestCase): def setUp(self): BaseTestMixin.setUp(self) def tearDown(self): BaseTestMixin.tearDown(self) (is_wx(), 'Issue enthought/traitsui#752') def test_tabular_editor_single_select...
class ArrayDataModel(AbstractDataModel, HasRequiredTraits): data = _AtLeastTwoDArray() index_manager = Instance(TupleIndexManager, args=()) label_header_type = Instance(AbstractValueType, factory=ConstantValue, kw={'text': 'Index'}, allow_none=False) column_header_type = Instance(AbstractValueType, fact...
(IPythonShell) class PythonShell(MPythonShell, LayoutWidget): command_executed = Event() key_pressed = Event(KeyPressedEvent) def __init__(self, parent=None, **traits): create = traits.pop('create', None) super().__init__(parent=parent, **traits) if create: self.create() ...
class GridDirective(SphinxDirective): has_content = True required_arguments = 0 optional_arguments = 1 final_argument_whitespace = True option_spec = {'gutter': gutter_option, 'margin': margin_option, 'padding': padding_option, 'outline': directives.flag, 'reverse': directives.flag, 'class-container...
def build_file_description(source_file_template, sources): with RetrieveFileFromUri(source_file_template).get_file_object() as f: file_description_text = ''.join(tuple((line.decode('utf-8') for line in f if (not line.startswith(b'#'))))) return file_description_text.format(**{source.source_type: source....
def getModifiers(chart): modifiers = [] asc = chart.getAngle(const.ASC) ascRulerID = essential.ruler(asc.sign) ascRuler = chart.getObject(ascRulerID) moon = chart.getObject(const.MOON) factors = [[MOD_ASC, asc], [MOD_ASC_RULER, ascRuler], [MOD_MOON, moon]] mars = chart.getObject(const.MARS) ...
class TestNumberOfDuplicatedRows(BaseIntegrityValueTest): name: ClassVar = 'Number of Duplicate Rows' def get_condition_from_reference(self, reference: Optional[DatasetSummary]): if (reference is not None): ref_num_of_duplicates = reference.number_of_duplicated_rows curr_number_o...
def get_kube_client(in_cluster: bool=False, config_file: Optional[str]=None) -> client.CoreV1Api: if in_cluster: config.load_incluster_config() elif (config_file is not None): config.load_kube_config(config_file=config_file) else: config.load_kube_config() return client.CoreV1Api...