code
stringlengths
281
23.7M
def test_inverse_transform_when_encode_unseen(): df1 = pd.DataFrame({'words': ['dog', 'dog', 'cat', 'cat', 'cat', 'bird']}) df2 = pd.DataFrame({'words': ['dog', 'dog', 'cat', 'cat', 'cat', 'frog']}) y = [1, 0, 1, 0, 1, 0] enc = MeanEncoder(unseen='encode') enc.fit(df1, y) dft = enc.transform(df2...
def shrink_to_64(x, N=64): def shrink_singlestring(key, N): if (len(key) >= N): return ((key[:20] + ' ... ') + key[(- 20):]) else: return key if (type(x) == str): return shrink_singlestring(x, N) elif (type(x) == list): return [shrink_singlestring(xx, ...
def mock_audit_rsyslog_sends_logs_to_a_remote_log_host_pass1(self, cmd): returncode = 0 stderr = [''] stdout = [''] if ('action' in cmd): stdout = ['*.* action(type="omfwd" target="192.168.2.100" port="514" protocol="tcp" action.resumeRetryCount="100" queue.type="LinkedList" queue.size="1000")',...
class AdAccountTrackingData(AbstractObject): def __init__(self, api=None): super(AdAccountTrackingData, self).__init__() self._isAdAccountTrackingData = True self._api = api class Field(AbstractObject.Field): tracking_specs = 'tracking_specs' _field_types = {'tracking_specs':...
.network def test_figshare_unspecified_version(): url = FIGSHAREURL url = (url[:url.rindex('.')] + '/') doi = url[4:(- 1)] warning_msg = f"The Figshare DOI '{doi}' doesn't specify which version of " with TemporaryDirectory() as local_store: downloader = DOIDownloader() outfile = os.p...
def test_error_if_contains_na_in_fit(df_enc_na): encoder = WoEEncoder(variables=None) with pytest.raises(ValueError) as record: encoder.fit(df_enc_na[['var_A', 'var_B']], df_enc_na['target']) msg = 'Some of the variables in the dataset contain NaN. Check and remove those before using this transforme...
def main(): res = ResultCode.SUCCESS args = parse_cli_args() (outdated_num, errors_num, updated) = asyncio.run(run_with_args(args)) if errors_num: res |= ResultCode.ERROR if (args.check_outdated and (not updated) and (outdated_num > 0)): res |= ResultCode.OUTDATED sys.exit(res)
def test_link_in_body(response_with_body_link): config = LinkPaginationConfiguration(source='body', path='links.next') request_params: SaaSRequestParams = SaaSRequestParams(method=HTTPMethod.GET, path='/customers', query_params={'page': 'abc'}) paginator = LinkPaginationStrategy(config) next_request: Op...
class GroupsSettingsScannerTest(unittest_utils.ForsetiTestCase): def setUpClass(cls): cls.service_config = FakeServiceConfig() cls.model_name = cls.service_config.model_manager.create(name='groups-settings-scanner-test') (scoped_session, data_access) = cls.service_config.model_manager.get(cl...
class NSEResult(Base): __tablename__ = 'nse_result' __table_args__ = (UniqueConstraint('script_id', 'script_output'),) id = Column(Integer, primary_key=True) script_id = Column(String) script_output = Column(String) nmap_result_id = Column(Integer, ForeignKey('nmap_result.id')) nmap_results ...
def create_empty_data(num_chains: int) -> typing.Data: output = {'marginals': {}, 'forests': {}, 'traces': {}, 'ranks': {}} for chain in range(num_chains): chain_index = (chain + 1) chain_name = f'chain{chain_index}' marginal = {'line': {'x': [], 'y': []}, 'chain': [], 'mean': [], 'bandw...
def find_idx_by_name(df, column, name): idx = df.index[(df[column] == name)] if (len(idx) == 0): raise UserWarning(("In column '%s', there is no element named %s" % (column, name))) if (len(idx) > 1): raise UserWarning(("In column '%s', multiple elements are named %s" % (column, name))) ...
def get_data(session: Session, target_datetime: datetime, extraction_func: Callable[([bytes], pd.DataFrame)], logger: Logger) -> pd.DataFrame: assert (target_datetime is not None), ParserException('NTESMO.py', 'Target datetime cannot be None.') target_date = target_datetime.date() latest_links = construct_l...
.usefixtures('use_tmpdir') def test_validate(file_contents): Path('wpr_diff_idx.txt').write_text('', encoding='utf8') Path('wpr_diff_obs.txt').write_text('', encoding='utf8') print(_validate_conf_content('', _parse_content(file_contents, ''))) assert (_validate_conf_content('', _parse_content(file_conte...
class OptionSeriesLollipopSonificationDefaultspeechoptionsMappingPlaydelay(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 SetOfTensors(collections.abc.Set): _elements: Set[Tuple] def __init__(self, iterable): self._elements = set() for value in iterable: t = (value if isinstance(value, Tensor) else tensor(value)) self._elements.add(tensor_to_tuple(t)) def __iter__(self): re...
class OptionPlotoptionsLineSonificationContexttracksMapping(Options): def frequency(self) -> 'OptionPlotoptionsLineSonificationContexttracksMappingFrequency': return self._config_sub_data('frequency', OptionPlotoptionsLineSonificationContexttracksMappingFrequency) def gapBetweenNotes(self) -> 'OptionPlo...
class FinancialMerchantInformation(BaseModel): name: Optional[StrictStr] = Field(default=None, description='Name of the merchant.') address: Optional[StrictStr] = Field(default=None, description='Address of the merchant.') phone: Optional[StrictStr] = Field(default=None, description='Phone number of the mer...
def upgrade(): op.add_column('flicket_topic', sa.Column('last_updated', sa.DateTime(), server_default='2016-11-21 17:58:26', nullable=True)) print('Updating last_updated dates.') from application import app, db from application.flicket.models.flicket_models import FlicketTicket, FlicketPost def last...
class TestWriteHeader(): def test_not_created_record(record: PyK4ARecord): with pytest.raises(K4AException, match='not created'): record.write_header() def test_double_writing(created_record: PyK4ARecord): created_record.write_header() with pytest.raises(K4AException, match='...
.parametrize('ops', ALL_OPS) .parametrize('dtype', FLOAT_TYPES) .parametrize('reduction_raises', REDUCE_ZERO_LENGTH_RAISES) def test_reduce_zero_seq_length(ops, dtype, reduction_raises): (reduction_str, raises) = reduction_raises reduction = getattr(ops, reduction_str) X = ops.asarray2f([[1.0, 2.0], [3.0, 4...
def test_create_client_defaults(db): client_id = generate_secure_random_string(16) secret = generate_secure_random_string(16) salt = generate_salt() hashed_secret = hash_with_salt(secret.encode('UTF-8'), salt.encode('UTF-8')) client = ClientDetail(id=client_id, salt=salt, hashed_secret=hashed_secret...
def extractSetsugetsukatrifectaWordpressCom(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, nam...
class ClassBasedViewIntegrationTests(TestCase): def setUp(self): self.view = BasicView.as_view() def test_400_parse_error(self): request = factory.post('/', 'f00bar', content_type='application/json') response = self.view(request) expected = {'detail': JSON_ERROR} assert (...
.parametrize('method', ['nearest', 'linear', 'cubic', KNeighbors()], ids=['nearest', 'linear', 'cubic', 'gridder']) def test_project_grid(method): shape = (50, 40) lats = np.linspace(2, 10, shape[1]) lons = np.linspace((- 10), 2, shape[0]) data = np.ones(shape, dtype='float') grid = xr.DataArray(dat...
class NotificationOriginatorLcdConfigurator(AbstractLcdConfigurator): cacheKeys = ['auth', 'name'] _cmdGenLcdCfg = CommandGeneratorLcdConfigurator() def configure(self, snmpEngine, authData, transportTarget, notifyType, contextName, **options): cache = self._getCache(snmpEngine) notifyName =...
def process_save_package(copr, source_type_text, package_name, view, view_method, url_on_success): form = forms.get_package_form_cls_by_source_type_text(source_type_text)() if ('reset' in flask.request.form): try: package = PackagesLogic.get(copr.id, package_name)[0] except IndexErro...
def transform_types_to_list_of_type(m: Dict[(str, type)], bound_inputs: typing.Set[str], list_as_optional: bool=False) -> Dict[(str, type)]: if (m is None): return {} all_types_are_collection = True for (k, v) in m.items(): if (k in bound_inputs): continue v_type = type(v...
def test_forward(): ar = get_net() x = torch.randn(50, dim_x, requires_grad=True) y = ar.forward(x) assert (ar.inverse(y) is x) assert (ar.forward(y) is not x) with set_record_flow_graph(False): y = ar.forward(x) assert (ar.inverse(y) is not x) assert (ar.forward(y) is no...
class Command(BaseCommand): parser = BaseCommand.load_parser(description='SWAT credential management.') subparsers = parser.add_subparsers(dest='subcommand', title='subcommands', required=True) parser_add = subparsers.add_parser('add', description='Add a scope for the authentication', help='Add a scope for ...
class OptionPlotoptionsDependencywheelLabelStyle(Options): def fontSize(self): return self._config_get('0.8em') def fontSize(self, num: float): self._config(num, js_type=False) def fontWeight(self): return self._config_get('bold') def fontWeight(self, text: str): self._co...
def entity_reordering(cell): def points(t): for k in sorted(t.keys()): (yield itertools.repeat(k, len(t[k]))) counter = collections.Counter() topos = (c.get_topology() for c in cell.cells) indices = entity_indices(cell) ordering = numpy.zeros(len(indices), dtype=IntType) for ...
def sample_from_swag(conf, model, client_models, loader=None): swag_model_root = swag.SWAG((model.cuda() if conf.graph.on_cuda else model), no_cov_mat=False, max_num_models=len(client_models)) for (_id, client_model) in client_models.items(): swag_model_root.collect_model(client_model) conf.logger.l...
def make_data(n_rows: int) -> pd.DataFrame: data = {'sepal_length': np.random.random_sample(n_rows), 'sepal_width': np.random.random_sample(n_rows), 'petal_length': np.random.random_sample(n_rows), 'petal_width': np.random.random_sample(n_rows), 'species': np.random.choice(['virginica', 'setosa', 'versicolor'], n_r...
class topk(Operator): def __init__(self, k) -> None: super().__init__() self._attrs['op'] = 'topk' self._attrs['has_profiler'] = True self._attrs['topK'] = k self._attrs['workspace'] = 0 self.exec_key_template = EXEC_KEY_TEMPLATE def _infer_shapes(self, x: Tensor)...
def _load_file(input_file: str) -> Dict: start_time = time.perf_counter() if input_file.endswith('.gz'): with gzip.open(input_file, 'rb') as f1: trace_record = json.loads(f1.read()) elif input_file.endswith('.json'): with open(input_file, 'r') as f2: trace_record = js...
def _remove_black_list_model_of_fastchat(): from fastchat.model.model_adapter import model_adapters black_list_models = [] for adapter in model_adapters: try: if (adapter.get_default_conv_template('/data/not_exist_model_path').name in __BLACK_LIST_MODEL_PROMPT): black_lis...
def test_cat(): c = Catalog() t1 = Test1(c) t2 = Test1(c) t2['num'] = ('testsrc1', 7) subc = Catalog('sub-cat', c) ts1 = Test1(subc) ts1['num'] = ('testsrc2', 8.5) ts2 = Test1(subc, num=('testsrc2', 12.7), f=('testows', 123.45)) ts3 = Test1(subc) ts3['num'] = ('testsrc2', 10.3) ...
class OptionPlotoptionsErrorbarSonificationContexttracksActivewhen(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: fl...
def get_redis_version(): import semantic_version version_string = subprocess.check_output('redis-server --version', shell=True) version_string = version_string.decode('utf-8').strip() version = re.findall('\\d+\\.\\d+', version_string) if (not version): return None version = semantic_ver...
def extractWitchesofgreenwitchWordpressCom(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 XSSerResource(resource.Resource): def __init__(self, name, parent): self.name = str(name) self.parent = parent def render_GET(self, request): if hasattr(self.parent, ('do_' + self.name)): response = getattr(self.parent, ('do_' + self.name))(request) else: ...
.parametrize(('mime_type', 'icon'), [(None, f'{MIME_PATH}unknown.svg'), ('application/zip', f'{MIME_PATH}application-zip.svg'), ('filesystem/some_filesystem', '/static/file_icons/filesystem.svg'), ('application/x-executable', f'{MIME_PATH}application-x-executable.svg'), ('inode/symlink', f'{MIME_PATH}inode-symlink.svg'...
def callback(file_path: str, file: BaseFile): file.name = del_special_symbol(file.name) file_path = del_special_symbol(file_path) (download_path / file_path).mkdir(parents=True, exist_ok=True) cmd = f'{idm} /a /n /d "{file.download_url}" /p "{(download_path / file_path)}" /f "{file.name}"' print(cmd...
def upgrade(): if (op.get_context().dialect.name == 'postgresql'): op.execute('ALTER TABLE versions RENAME CONSTRAINT "pk_versions" TO "pk_versions_old"') op.execute('ALTER TABLE blocks RENAME CONSTRAINT "pk_blocks" TO "pk_blocks_old"') op.execute('ALTER TABLE labels RENAME CONSTRAINT "pk_la...
def test_attention_1d(): in_dict = build_multi_input_dict(dims=[(2, 10), (2, 10), (2, 10)]) self_attn_block = MultiHeadAttentionBlock(in_keys=['in_key_0', 'in_key_1', 'in_key_2'], out_keys=['added_attention', 'attention'], in_shapes=[(10,), (10,), (10,)], num_heads=10, dropout=0.0, bias=False, add_input_to_outp...
class RingControl(Module): def __init__(self, pad, mode, color, nleds, sys_clk_freq): conf = Record([('colors', 24), ('leds', 12)]) ring = RingSerialCtrl(nleds, conf, sys_clk_freq) self.submodules += ring ring_timer = WaitTimer(int((0.05 * sys_clk_freq))) self.submodules += r...
def residual_funptr(form, state): from firedrake.tsfc_interface import compile_form (test,) = map(operator.methodcaller('function_space'), form.arguments()) if (state.function_space() != test): raise NotImplementedError('State and test space must be dual to one-another') if (state is not None): ...
class Main(base.Module): parameters = {'iface': 'wlan0mon', 'count': 10} completions = list(parameters.keys()) def do_execute(self, line): process_list = [] try: for _ in range(int(self.parameters['count'])): name = get_fake_name() mac = get_fake_m...
class OptionSeriesTreemapStatesHoverMarker(Options): def enabled(self): return self._config_get(None) def enabled(self, flag: bool): self._config(flag, js_type=False) def enabledThreshold(self): return self._config_get(2) def enabledThreshold(self, num: float): self._conf...
def print_site(ports, luts, site, site_type): verilog_ports = '' verilog_wires = '' for (port, width) in ports: verilog_ports += '\n .{port}({port}_{site}),'.format(port=port, site=site) verilog_wires += 'wire [{}:0] {}_{};\n'.format((width - 1), port, site) for idx in range(0, wi...
def get_image_bounds(image, background=np.NaN): if (not np.isnan(background)): image = image.astype(float) image[np.where((image == background))] = np.NaN rowmin = np.argmax(np.any((~ np.isnan(image)), axis=0)) rowmax = (image.shape[0] - np.argmax(np.any((~ np.isnan(image[::(- 1)])), axis=0)...
_event class MessageEvent(ThreadEvent): message = attr.ib(type='_models.Message') at = attr.ib(type=datetime.datetime) def _parse(cls, session, data): (author, thread, at) = cls._parse_metadata(session, data) message = _models.MessageData._from_pull(thread, data, author=author.id, created_at...
def get_citations_for_model(model=None, width=79): model = pm.modelcontext(model) if (not hasattr(model, '__citations__')): logging.warning('no citations registered with model') return ('', '') cite = ((list(CITATIONS['pymc3'][0]) + list(CITATIONS['theano'][0])) + list(CITATIONS['arviz'][0])...
def today(request, location_slug): location = get_object_or_404(Location, slug=location_slug) today = timezone.now() bookings_today = Booking.objects.filter((Q(status='confirmed') | Q(status='approved'))).exclude(depart__lt=today).exclude(arrive__gt=today) guests_today = [] for r in bookings_today: ...
.skip .django_db def test_budget_authority_endpoint(model_instances, client): resp = client.get('/api/v2/budget_authority/agencies/000/') assert (resp.status_code == status.HTTP_200_OK) results = resp.json()['results'] assert (len(results) == 4) for result in results: assert ('year' in resul...
def locate_app(script_info, module_name, app_name, raise_if_not_found=True): __traceback_hide__ = True try: __import__(module_name) except ImportError: if sys.exc_info()[2].tb_next: raise NoAppException(f'''While importing {module_name!r}, an ImportError was raised: {traceback.fo...
class UpdaterApp(QDialog, Ui_UpdaterDialog): def __init__(self, should_skip_netcheck: bool=False, parent=None): super(UpdaterApp, self).__init__(parent) self.progress = 0 self._skip_netcheck = should_skip_netcheck self.setupUi(self) self.applyUpdatesButton.setEnabled(True) ...
class TestCH(unittest.TestCase): def test_get_solar_capacity(self): assert (get_solar_capacity_at(arrow.get('2018-01-02').datetime) == 2090) assert (get_solar_capacity_at(arrow.get('2018-01-01 00:00:00+00:00').datetime) == 2090) assert (get_solar_capacity_at(arrow.get('2014-02-01').datetime)...
class Compiler(): def __init__(self, proc, ctxt_name, *, is_public_decl): assert isinstance(proc, LoopIR.proc) self.proc = proc self.ctxt_name = ctxt_name self.env = ChainMap() self.range_env = IndexRangeEnvironment(proc, fast=False) self.names = ChainMap() se...
def _convert_querysets(querysets): results = [] for queryset in querysets: for qu_item in queryset: item = {'type': qu_item.type} if (item['type'] == 0): item['id'] = qu_item.number_str item['name'] = qu_item.name levels = item['id'...
class ContentMatcher(object): def __init__(self, pattern, ignore_case=False, invert_match=False, whole_words=False, literal_pattern=False, max_match_count=sys.maxsize): self.regex = self._create_regex(pattern, ignore_case=ignore_case, whole_words=whole_words, literal_pattern=literal_pattern) if inve...
class VRRPV3StateBackup(VRRPState): def _master_down(self): vrrp_router = self.vrrp_router vrrp_router.send_advertisement() vrrp_router.preempt_delay_timer.cancel() vrrp_router.state_change(vrrp_event.VRRP_STATE_MASTER) vrrp_router.adver_timer.start(vrrp_router.config.adverti...
class ConvertFreesurferSurface(unittest.TestCase): meshes = ciftify_recon_all.define_meshes('/somewhere/hcp/subject_1', '164', ['32'], '/tmp/temp_dir', False) ('ciftify.bin.ciftify_recon_all.run') def test_secondary_type_option_adds_to_set_structure_command(self, mock_run): secondary_type = 'GRAY_WH...
def test_validate_header_fails_on_invalid_parent(noproof_consensus_chain): block1 = noproof_consensus_chain.mine_block() block2 = noproof_consensus_chain.mine_block() vm = noproof_consensus_chain.get_vm(block2.header) with pytest.raises(ValidationError, match='Blocks must be numbered consecutively'): ...
def main(): alice = LocalWallet.generate() ledger = LedgerClient(NetworkConfig.fetchai_stable_testnet()) faucet_api = FaucetApi(NetworkConfig.fetchai_stable_testnet()) alice_balance = ledger.query_bank_balance(alice.address()) while (alice_balance < (10 ** 18)): print('Providing wealth to al...
def test_remove_child_transfers_of_transfers(get_transaction_hashes, get_addresses): [transaction_hash, other_transaction_hash] = get_transaction_hashes(2) [alice_address, bob_address, first_token_address, second_token_address, third_token_address] = get_addresses(5) outer_transfer = Transfer(block_number=1...
.django_db def test_no_intersection(client, monkeypatch, elasticsearch_award_index): baker.make('search.AwardSearch', award_id=1, type='A', latest_transaction_id=1, action_date='2020-10-10') baker.make('search.TransactionSearch', transaction_id=1, action_date='2010-10-01', award_id=1, is_fpds=True) setup_el...
def extractShuuenScansTumblrCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return False if ('WATTT' in item['tags']): return buildReleaseMessageWithType(item, 'WATTT', vol, chp, frag=frag...
class TestParsePubNum(): def test_should_use_none_type_for_unknown_pattern(self): external_identifier = parse_pubnum(LayoutBlock.for_text('xyz')) assert (external_identifier.external_identifier_type is None) assert (external_identifier.value == 'xyz') def test_should_detect_doi_with_labe...
('ecs_deploy.cli.get_client') def test_deploy_without_changing_docker_labels(get_client, runner): get_client.return_value = EcsTestClient('acces_key', 'secret_key') result = runner.invoke(cli.deploy, (CLUSTER_NAME, SERVICE_NAME, '-d', 'webserver', 'foo', 'bar')) assert (result.exit_code == 0) assert (no...
def get_preprocessor(text, implied_any=False, subqueries=None, preprocessor=None): definitions = parse_definitions(text, implied_any=implied_any, subqueries=subqueries, preprocessor=preprocessor) if (preprocessor is None): new_preprocessor = ast.PreProcessor() else: new_preprocessor = prepro...
def gen_library_src(sorted_graph: List[Tensor], max_blob_size: int, max_constant_blob_size: int, workspace: Workspace, workdir: str, output_tensors: List[Tensor], model_name: str='', debug_settings: AITDebugSettings=_DEBUG_SETTINGS, additional_unbound_constants: Optional[List[Tensor]]=None) -> List[Tuple[(str, str)]]: ...
def extractThePlaceClosestToHeaven(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=fr...
def main(): ap = argparse.ArgumentParser(description='Convert Finnish dictionary TSV data into hunspell') 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 ConvertAudio(Analyser): in_etype = Etype.Audio out_etype = Etype.Audio def analyse_element(self, element, config): output_ext = config['output_ext'] FNULL = open(os.devnull, 'w') output = f'/tmp/{element.id}.{output_ext}' out = call(['ffmpeg', '-y', '-i', element.paths[...
class OptionPlotoptionsDumbbellMarker(Options): def enabled(self): return self._config_get(None) def enabled(self, flag: bool): self._config(flag, js_type=False) def enabledThreshold(self): return self._config_get(2) def enabledThreshold(self, num: float): self._config(nu...
def test_arc_to_cubic_bezier(): pen = RecordingPen() parse_path('M300,200 h-150 a150,150 0 1,0 150,-150 z', pen) expected = [('moveTo', ((300.0, 200.0),)), ('lineTo', ((150.0, 200.0),)), ('curveTo', ((150.0, 282.842), (217.157, 350.0), (300.0, 350.0))), ('curveTo', ((382.842, 350.0), (450.0, 282.842), (450....
class OptionPlotoptionsFunnel3dEvents(Options): def afterAnimate(self): return self._config_get(None) def afterAnimate(self, value: Any): self._config(value, js_type=False) def checkboxClick(self): return self._config_get(None) def checkboxClick(self, value: Any): self._c...
def get_ip(cardnum=0): ips = '' if (cardnum == 0): try: cardnum = Settings.NetMan.getprimarydevice() if (Settings.NetworkDevices[cardnum].ip == ''): cardnum = Settings.NetMan.getsecondarydevice() except: ips = '' if (cardnum < len(Settings....
('config_name,overrides,expected', [param('placeholder', [], DefaultsTreeNode(node=ConfigDefault(path='placeholder'), children=[GroupDefault(group='group1'), ConfigDefault(path='_self_')]), id='placeholder'), param('placeholder', ['group1=file1'], DefaultsTreeNode(node=ConfigDefault(path='placeholder'), children=[Group...
class TestBoundingBox(): def test_should_calculate_area(self): bounding_box = BoundingBox(x=101, y=102, width=200, height=50) assert (bounding_box.area == (200 * 50)) def test_should_scale_by_given_ratio(self): assert (BoundingBox(x=1, y=2, width=3, height=4).scale_by(10, 100) == Boundin...
.django_db(transaction=True) def test_download_awards_with_all_sub_awards(client, _award_download_data): download_generation.retrieve_db_string = Mock(return_value=get_database_dsn_string()) filters = {'agency': 'all', 'sub_award_types': all_subaward_types, 'date_type': 'action_date', 'date_range': {'start_date...
class FileLs(BaseTest): folders = [os.path.join(config.base_folder, f) for f in ('test_file_ls/dir1', 'test_file_ls/dir1/dir2', 'test_file_ls/dir1/dir2/dir3', 'test_file_ls/dir1/dir2/dir3/dir4')] def setUp(self): self.session = SessionURL(self.url, self.password, volatile=True) modules.load_modu...
(IEditorManager) class EditorManager(HasTraits): window = Instance('pyface.workbench.api.WorkbenchWindow') def __init__(self, **traits): super().__init__(**traits) self._editor_to_kind_map = weakref.WeakKeyDictionary() return def add_editor(self, editor, kind): self._editor_t...
def extractHonorAndTruthBlogspotCom(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_ty...
class TestShadowGroup(BaseTestMixin, unittest.TestCase): def setUp(self): BaseTestMixin.setUp(self) def tearDown(self): BaseTestMixin.tearDown(self) def test_creation_sets_shadow_first(self): group = Group() ShadowGroup(label='dummy', show_border=True, show_labels=True, show_...
class OptionPlotoptionsCylinderSonificationTracksMappingHighpassResonance(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 TypeThinDefaultConfig(): bool_p_set_def: bool = True int_p_def: int = 10 float_p_def: float = 10.0 string_p_def: str = 'Spock' list_p_float_def: List[float] = [10.0, 20.0] list_p_int_def: List[int] = [10, 20] list_p_str_def: List[str] = ['Spock', 'Package'] list_p_bool_def: List[bo...
class AbstractPairsSequence(AbstractSequence): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.query_preprocessing = self.preprocessings[0] self.support_preprocessing = self.preprocessings[(- 1)] self.query_annotations = self.annotations[0] self.su...
def order_reuses(fields): foreign_reuses = {} self_nestings = {} for (schema_name, schema) in fields.items(): if (not ('reusable' in schema['schema_details'])): continue reuse_order = schema['schema_details']['reusable']['order'] for reuse_entry in schema['schema_details'...
class DropFeatures(BaseSelector): def __init__(self, features_to_drop: List[Union[(str, int)]]): if ((not isinstance(features_to_drop, (str, list))) or (len(features_to_drop) == 0)): raise ValueError(f'features_to_drop should be a list with the name of the variables you wish to drop from the dat...
def main() -> None: parser = argparse.ArgumentParser() parser.add_argument('--from', type=str, required=True, dest='source_path', help='Official checkpoint from e.g. /path/to/dinov2_vits14_pretrain.pth') parser.add_argument('--to', type=str, dest='output_path', default=None, help='Path to save the converte...
class OptionSeriesTimelineMarkerStatesSelect(Options): def enabled(self): return self._config_get(True) def enabled(self, flag: bool): self._config(flag, js_type=False) def fillColor(self): return self._config_get('#cccccc') def fillColor(self, text: str): self._config(te...
class TestFormatDataUseMapForCaching(): def create_dataset(self, db, fides_key, connection_config): ds = Dataset(fides_key=fides_key, organization_fides_key='default_organization', name='Postgres Example Subscribers Dataset', collections=[{'name': 'subscriptions', 'fields': [{'name': 'email', 'data_categori...
def test_reuse_passive_close_ok_ok(unused_tcp_port): custom_range = range(unused_tcp_port, (unused_tcp_port + 1)) (_, port, orig_sock) = port_handler.find_available_port(custom_range=custom_range, custom_host='127.0.0.1', will_close_then_reopen_socket=True) assert (port == unused_tcp_port) assert (orig_...
class Gauge(BaseMetric): __slots__ = (BaseMetric.__slots__ + ('_val',)) def __init__(self, name, reset_on_collect=False, unit=None) -> None: self._val = None super(Gauge, self).__init__(name, reset_on_collect=reset_on_collect) def val(self): return self._val def val(self, value) ...
def create_okta_systems(okta_applications: List[OktaApplication], organization_key: str) -> List[System]: systems = [System(fides_key=application.id, name=application.name, fidesctl_meta=SystemMetadata(resource_id=application.id), description=f'Fides Generated Description for Okta Application: {application.label}',...
def apply_custom_style(ax, **kwargs): if ax.get_title(): ax.title.set_size(kwargs.pop('title_fontsize', TITLE_FONTSIZE)) label_size = kwargs.pop('label_size', LABEL_SIZE) ax.xaxis.label.set_size(label_size) ax.yaxis.label.set_size(label_size) ax.tick_params(axis='both', which='major', labels...
class XMLSerializer(AbstractSerializer): def __init__(self): super().__init__(extensions=['xml']) def decode(self, s, **kwargs): require_xml(installed=xml_installed) kwargs.setdefault('dict_constructor', dict) data = xmltodict.parse(s, **kwargs) return data def encode...