code
stringlengths
281
23.7M
def dynamodb_example_test_dataset_config(dynamodb_connection_config: ConnectionConfig, db: Any, example_datasets: List[Dict]) -> Generator: dataset = example_datasets[11] fides_key = dataset['fides_key'] ctl_dataset = CtlDataset.create_from_dataset_dict(db, dataset) dataset_config = DatasetConfig.create...
def d2q_lb(m0, m1, m2, o0, o1, o2, n0, n1, n2, p0, p1, p2): m0 = mpmath.mpf(m0) m1 = mpmath.mpf(m1) m2 = mpmath.mpf(m2) o0 = mpmath.mpf(o0) o1 = mpmath.mpf(o1) o2 = mpmath.mpf(o2) n0 = mpmath.mpf(n0) n1 = mpmath.mpf(n1) n2 = mpmath.mpf(n2) p0 = mpmath.mpf(p0) p1 = mpmath.mpf(...
def leak(): global system_addr, binsh_addr puts_addr = get_puts_addr() libc = ELF('/lib/x86_64-linux-gnu/libc.so.6') system_addr = ((puts_addr - libc.sym['puts']) + libc.sym['system']) binsh_addr = ((puts_addr - libc.sym['puts']) + 1625431) log.info(('system address: 0x%x' % system_addr)) lo...
def handle_sns(operation_name, service, instance, args, kwargs, context): if (operation_name != 'Publish'): return False span_type = 'messaging' span_subtype = 'sns' span_action = 'send' topic_name = '' if (len(args) > 1): if ('Name' in args[1]): topic_name = args[1][...
class CriticExtension(Extension): def __init__(self, *args, **kwargs): self.config = {'mode': ['view', "Critic mode to run in ('view', 'accept', or 'reject') - Default: view "], 'raw_view': [False, 'Raw view keeps the output as the raw markup for view mode - Default False']} super().__init__(*args, ...
def get_number_cpus(user_n_cpus=None): if user_n_cpus: try: n_cpus = int(user_n_cpus) except: logger.critical('Could note read --n_cpus entry {} as integer'.format(user_n_cpus)) sys.exit(1) else: n_cpus = os.getenv('OMP_NUM_THREADS') if (not n_cpus...
def extractEccentricTranslations(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('True Immortal', 'True Immortal', 'oel'), ('ILK', 'Invincible Leveling King', 'translated'), ('A...
def fetch_exchange(zone_key1: ZoneKey, zone_key2: ZoneKey, session: (Session | None)=None, target_datetime: (datetime | None)=None, logger: Logger=getLogger(__name__)) -> list: sorted_zone_keys = ZoneKey('->'.join(sorted([zone_key1, zone_key2]))) if (sorted_zone_keys not in EXCHANGES): raise NotImplemen...
('/browse', defaults={'path': ''}) ('/browse/<path:path>') def browse(path): sort_property = get_cookie_browse_sorting(path, 'text') (sort_fnc, sort_reverse) = browse_sortkey_reverse(sort_property) try: directory = Node.from_urlpath(path) if (directory.is_directory and (not directory.is_excl...
def get_child_transfers(transaction_hash: str, parent_trace_address: List[int], traces: List[ClassifiedTrace]) -> List[Transfer]: child_transfers = [] for child_trace in get_child_traces(transaction_hash, parent_trace_address, traces): transfer = get_transfer(child_trace) if (transfer is not Non...
_fixtures_to_matrixstore class ApiTestBase(TestCase): fixtures = ['orgs', 'practices', 'practice_listsizes', 'products', 'presentations', 'sections', 'prescriptions', 'chemicals'] api_prefix = '/api/1.0' def setUpTestData(cls): date = Prescription.objects.latest('processing_date').processing_date ...
class OptionPlotoptionsAreasplinerangeTooltipDatetimelabelformats(Options): def day(self): return self._config_get('%A, %e %b %Y') def day(self, text: str): self._config(text, js_type=False) def hour(self): return self._config_get('%A, %e %b, %H:%M') def hour(self, text: str): ...
class Matrix(MatrixBase): def __init__(self, a, bcs, mat_type, *args, **kwargs): MatrixBase.__init__(self, a, bcs, mat_type) options_prefix = kwargs.pop('options_prefix') self.M = op2.Mat(*args, mat_type=mat_type, **kwargs) self.petscmat = self.M.handle self.petscmat.setOptio...
class UnitTestWithNamespace(UnitTestWithMetadataManager): def setUp(self) -> None: super().setUp() self.namespace_name = 'namespace' self.namespace_meta = self.metadata_manager.add_namespace(name=self.namespace_name, properties={'a': 'a'}) self.metadata_manager.flush()
class DBTester(): __test__ = False def setUp(self): self.create_db() self.connection = None connection = self._dbmodule.connect(**self._auth) cursor = connection.cursor() cursor.execute('CREATE TABLE gargleblatz\n (\n a INTEGER\n );') connect...
class MemmapingPool(PicklingPool): def __init__(self, processes=None, temp_folder=None, max_nbytes=1000000.0, mmap_mode='r', forward_reducers=None, backward_reducers=None, verbose=0, context_id=None, prewarm=False, **kwargs): if (forward_reducers is None): forward_reducers = dict() if (b...
class CustomAudienceMixin(): class Schema(object): uid = 'UID' email_hash = 'EMAIL_SHA256' phone_hash = 'PHONE_SHA256' mobile_advertiser_id = 'MOBILE_ADVERTISER_ID' class MultiKeySchema(object): extern_id = 'EXTERN_ID' email = 'EMAIL' phone...
def mock_password_expiration_min_days_is_configured_pass(self, cmd): returncode = 0 stderr = [''] if ('PASS_MIN_DAYS' in cmd): stdout = ['PASS_MIN_DAYS 1'] elif ('shadow' in cmd): stdout = ['root:1', 'vagrant:1'] return SimpleNamespace(returncode=returncode, stderr=stderr, stdout=...
def test_filehandles_closed_when_load_fails(tmpdir, merge_lis_prs): empty = os.path.join(str(tmpdir), 'empty.lis') merge_lis_prs(empty, []) truncated = str(tmpdir.join('truncated.lis')) shutil.copyfile('data/lis/layouts/truncated_15.lis', truncated) openlis = str(tmpdir.join('openlis-error.lis')) ...
class TestNoTunerClasses(): def test_no_tuner_classes(self, monkeypatch): with monkeypatch.context() as m: m.setattr(sys, 'argv', ['']) optuna_config = optuna.create_study(study_name='Tests', direction='minimize') class DummyClass(): val: int = 1 ...
def make_agent(agent_name: str='my_agent', runtime_mode: str='threaded', resources: Optional[Resources]=None, identity: Optional[Identity]=None) -> AEA: wallet = Wallet({DEFAULT_LEDGER: None}) identity = (identity or Identity(agent_name, address=agent_name, public_key=f'public_key_for_{agent_name}')) resour...
def test_query_string_values(): with pytest.raises(ValueError): testing.create_scope(query_string='?catsup=y') with pytest.raises(ValueError): testing.create_scope(query_string='?') for qs in ('', None): scope = testing.create_scope(query_string=qs) assert (scope['query_strin...
class TabSet(): def __init__(self, node): self._nodes = [node] def is_next(self, node): if (self.parent != node.parent): return False if (node.parent.index(node) != (self.indices[(- 1)] + 1)): return False return True def append(self, node): as...
def test_archive_included(monkeypatch): gl = gitlab_util.create_test_gitlab_with_archived(monkeypatch, archived=ArchivedResults.INCLUDE.api_value) gl.load_tree() assert (gl.root.is_leaf is False) assert (len(gl.root.children) == 2) assert (len(gl.root.children[0].children) == 2) assert (len(gl.r...
class MethodRecord(): def __init__(self, name, num_address_in_args, len_args, payable, fallback, all_insns, all_blocks, frac_insns, frac_blocks): self.name = name self.num_address_in_args = num_address_in_args self.len_args = len_args self.payable = payable self.fallback = fa...
.parametrize('strict', (True, False)) .parametrize('data', ('', 123, 291, [b'\x01'], (b'\x01',), {b'\x01'})) def test_abi_decode_wrong_data_param_type_raises(data, strict): with pytest.raises(TypeError, match=f'The `data` value must be of bytes type. Got {type(data)}'): decode(['uint32', 'uint32'], data, st...
class TestElectioneeringByCandidateView(ApiBaseTest): def test_sort_by_candidate_name_descending(self): factories.CandidateHistoryFactory(candidate_id='S001', name='WARNER, MARK', two_year_period=2010, office='S', state='NY') factories.CandidateHistoryFactory(candidate_id='S002', name='BALDWIN, ALIS...
class IPAddressFormat(BaseFormat): errors = {'format': 'Must be a valid IP format.', 'invalid': 'Must be a real IP.'} def is_native_type(self, value: typing.Any) -> bool: return isinstance(value, (ipaddress.IPv4Address, ipaddress.IPv6Address)) def validate(self, value: typing.Any) -> typing.Union[(i...
class Solution(): def diStringMatch(self, s: str) -> List[int]: res = [] start = 0 end = len(s) perm = list(range((len(s) + 1))) for i in s: if (i == 'I'): res.append(perm[start]) start += 1 elif (i == 'D'): ...
.parametrize('input_features', [None, variables_str, np.array(variables_str)]) def test_remove_feature_names_within_pipeline_when_df(df_vartypes, input_features): transformer = Pipeline([('transformer', MockSelector())]) transformer.fit(df_vartypes) features_out = list(df_vartypes.columns)[2:] assert (t...
('/', defaults={'path': ''}) ('/<path:path>') def serve(path: str) -> Response: LOG.info(f'Serving `{path}`...') static_folder = none_throws(application.static_folder) if ((path != '') and os.path.exists(((static_folder + '/') + path))): LOG.info('Found static resource.') return send_from_di...
class MyAdminIndexView(AdminIndexView): ('/') def index(self): if (not login.current_user.is_authenticated): return redirect(url_for('.login_view')) return super().index() ('/login/', methods=('GET', 'POST')) def login_view(self): form = LoginForm(request.form) ...
class TestSessionReset(): .parametrize('state', [State.INITIAL, State.STARTED]) def test_not_reset_when_session_is_running(self, state, session): session.state = state assert (not session.reset()) .parametrize('state,session_type,duration', [(State.ENDED, SessionType.SHORT_BREAK, (5 * 60)), ...
class OptionPlotoptionsHistogramSonificationTracksMappingLowpassFrequency(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: str)...
def main(): descr = 'A verification script for Ragout. It requires a contigs alignment on "true" reference in nucmer coords format. Given an alignment and a "links" file output by Ragout the script finds missassembled contigs and calculates some statistics.' parser = argparse.ArgumentParser(description=descr) ...
def parse_neighbors_graph(neighbors, vars=[]): graph = defaultdict(list) for var in vars: graph[var] = [] specs = [spec.split(':') for spec in neighbors.split(';')] for (v, v_neighbors) in specs: v = v.strip() graph.setdefault(v, []) for u in v_neighbors.split(): ...
class FieldsMatch(FormValidator): show_match = False field_names = None validate_partial_form = True __unpackargs__ = ('*', 'field_names') messages = dict(invalid=_('Fields do not match (should be %(match)s)'), invalidNoMatch=_('Fields do not match'), notDict=_('Fields should be a dictionary')) ...
def assertXMLEqual(test_case, xml1, xml2, message=''): def clean_xml(xml): xml = f'<root>{xml}</root>' return str(re.sub('>\n *<', '><', parseString(xml).toxml())) def xml_to_dict(xml): nodes = re.findall('(<([^>]*)>(.*?)</\\2>)', xml) if (len(nodes) == 0): return xml...
class OptionPlotoptionsBubbleStatesSelect(Options): def animation(self) -> 'OptionPlotoptionsBubbleStatesSelectAnimation': return self._config_sub_data('animation', OptionPlotoptionsBubbleStatesSelectAnimation) def enabled(self): return self._config_get(True) def enabled(self, flag: bool): ...
.usefixtures('use_tmpdir') def test_render_invalid(): prod_wells = {f'PROD{idx}': (0.3 * idx) for idx in range(4)} prod_in = 'well_drill.json' with open(prod_in, 'w', encoding='utf-8') as fout: json.dump(prod_wells, fout) with open('parameters.json', 'w', encoding='utf-8') as fout: json....
class TestNintendo(TestCase): ((Platforms.NINTENDO_SWITCH, '700', 'HAC')) def test_search_by_platform(self, platform, nsuid_prefix, playable_on): result = nintendo.search_by_platform(platform) for (index, data) in enumerate(result): if (index > LIMIT): break ...
def decryptMsg(res, dir_path, wx_path, aeskey): for path in res: if path.startswith('MSG'): CrackWeChatDB.decrypt_msg(((dir_path + '\\') + path), aeskey, (res.index(path) + 1), len(res)) else: CrackWeChatDB.decrypt_msg(((wx_path + '\\') + path), aeskey, (res.index(path) + 1),...
class OptionPlotoptionsScatter3dMarkerStates(Options): def hover(self) -> 'OptionPlotoptionsScatter3dMarkerStatesHover': return self._config_sub_data('hover', OptionPlotoptionsScatter3dMarkerStatesHover) def normal(self) -> 'OptionPlotoptionsScatter3dMarkerStatesNormal': return self._config_sub_...
class HorovodJob(object): worker: Worker = field(default_factory=(lambda : Worker())) launcher: Launcher = field(default_factory=(lambda : Launcher())) run_policy: Optional[RunPolicy] = field(default_factory=(lambda : None)) slots: int = 1 verbose: Optional[bool] = False log_level: Optional[str]...
def check_certificate_pinned_binaries(app): if (len(app.get('AllowedAPKSigningKeys')) > 0): return if (app.get('Binaries') is not None): (yield _('App has Binaries but does not have corresponding AllowedAPKSigningKeys to pin certificate.')) return builds = app.get('Builds') if (b...
def plot_value_counts_tables_ref_curr(feature_name, curr_df, ref_df, id_prfx): additional_plots = [] curr_df = curr_df[(curr_df['count'] != 0)] additional_plots.append(DetailsInfo(title='Current value counts (top 10)', info=table_data(column_names=['value', 'count'], data=curr_df[:10].values))) if (ref_...
class Serializer(Module): def __init__(self, sd_clk, sd_clkdiv, inputs, reset=0, name=None, delay=0): assert (len(inputs) > 0) assert ((len(s) == len(inputs[0])) for s in inputs) data_width = len(inputs) signal_width = len(inputs[0]) cntr_max = (2 * data_width) if (no...
class ZabbixActionContainer(ZabbixBaseContainer): ZABBIX_ID_ATTR = 'actionid' NAME_MAX_LENGTH = 255 QUERY_BASE = frozendict({'output': 'extend', 'selectOperations': 'extend', 'selectFilter': 'extend'}) _BASE_PARAMS_MAPPING = (('name', 'name', trans_name), ('status', 'enabled', trans_bool_inverted), ('de...
def main(): print('Please note that the licence of FTC does not allow you to do much\n with the results or anything, other than including approximate numbers of\n recall for scientific purposes. Please do not look at the differences or\n do any processing with any of the data since it will automatically ma...
def find_user_config_file_from(starting_directory: Optional[Union[(PathLike, str)]]=None) -> Optional[Path]: if (starting_directory is None): current_working_directory = Path.cwd() starting_directory = current_working_directory searching_directory_path = Path(starting_directory).resolve() sh...
def partition(iterable, limit, key=(lambda x: x)): def pop_partition(): sum = 0.0 while ((sum < limit) and iterable): sum += key(iterable[(- 1)]) (yield iterable.pop()) partitions = [] iterable.sort(reverse=True) while iterable: partitions.append(list(pop_...
def test_decompile_magic_length_non_last(empty_font): indextable = empty_font['TSI0'] indextable.extra_indices = [(65530, 3, 0), (65531, 32768, 3), (65532, 0, 32772), (65533, 0, 32772)] ppgm_content = ('0' * 3) cvt_content = ('1' * (32768 + 1)) data = tobytes((ppgm_content + cvt_content)) table ...
def _load_op_durations_from_file(input: Union[(str, Path)]) -> Dict[(str, float)]: if isinstance(input, str): input_path = Path(input) elif isinstance(input, Path): input_path = input else: raise ValueError('str or Path is needed as an input argument') with input_path.open('r') a...
def make_midi_message_from_midi_trigger(midi_trigger, releasing=False, velocity=127, value=127): if midi_trigger.startswith('nn'): return mido.Message(('note_on' if (not releasing) else 'note_off'), note=int(midi_trigger.replace('nn', '')), velocity=velocity, channel=0) elif midi_trigger.startswith('cc'...
class Test_ValidationError(): () def field(self): return DecimalField(model=X, field='foo') () def error(self, *, field): return ValidationError('error', field=field) def test_repr(self, *, error): assert repr(error) def test_str(self, *, error): assert str(error)
class OptionSeriesColumnpyramidSonificationDefaultinstrumentoptionsMappingTremoloSpeed(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(sel...
def get_order_taxes(shopify_order, setting, items): taxes = [] line_items = shopify_order.get('line_items') for line_item in line_items: item_code = get_item_code(line_item) for tax in line_item.get('tax_lines'): taxes.append({'charge_type': 'Actual', 'account_head': get_tax_acco...
def extractVodkatranslationsCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('Ordinary I and Extraordinary Them', 'Ordinary I and Extraordinary Them', 'translated'), ('PRC', ...
.django_db class TestApprovedManager(object): (autouse=True) def setup(self): self.u1 = UserFactory.create() self.top_level_cat = create_category_forum() self.forum_1 = create_forum(parent=self.top_level_cat) self.forum_2 = create_forum(parent=self.top_level_cat) self.for...
class BaseWebArea(abc.ABC): _osci_ranking_dir_name = 'osci-ranking' _osci_ranking_monthly_dir_name = 'monthly' def _join_paths(self, *paths: Union[(str, Path)], create_if_not_exists=False) -> Union[(str, Path)]: raise NotImplementedError() def _save_json(self, path: Union[(str, Path)], json_data...
class LLMEvalResult(): def __init__(self, original_prompt: str, pre_context: str, post_context: str, perturbed_prompts: List[str], perturbed_generations: List[str], result: List[int], metric: List[Dict[(str, Any)]], expected_behavior_desc: str, evaluation_type: Literal[(LLMEvalType.robustness, LLMEvalType.correctne...
.integration_mariadb .integration class TestMariaDBConnector(): def test_mariadb_db_connector(self, api_client: TestClient, db: Session, generate_auth_header, connection_config_mariadb, mariadb_example_secrets) -> None: connector = get_connector(connection_config_mariadb) assert (connector.__class__...
def load_component_public_id(source_path: str, item_type: str) -> PublicId: config = load_yaml(os.path.join(source_path, (item_type + '.yaml'))) item_author = config.get('author', '') item_name = config.get('name', '') item_version = config.get('version', '') return PublicId(item_author, item_name, ...
class ClassWithPropertyDependsOnItems(ClassWithInstanceDefaultInit): discounted = Property(Bool(), depends_on='list_of_infos.age') discounted_n_calculations = Int() def _get_discounted(self): self.discounted_n_calculations += 1 return any(((info.age > 70) for info in self.list_of_infos))
def standardized_confidence_score_picpurify(confidence_score: float, nsfw: bool): if nsfw: if (confidence_score >= 0.8): return 5 elif (confidence_score >= 0.6): return 4 elif (confidence_score >= 0.4): return 3 elif (confidence_score >= 0.2): ...
class GroupChat(JsonDeserializable): def de_json(cls, json_string): if (json_string is None): return None obj = cls.check_json(json_string, dict_copy=False) return cls(**obj) def __init__(self, id, title, **kwargs): self.id: int = id self.title: str = title
def _make_tcp_server_connection(address: str, public_key: str, host: str, port: int): configuration = ConnectionConfig(address=host, port=port, connection_id=TCPServerConnection.connection_id) tcp_connection = TCPServerConnection(configuration=configuration, data_dir=MagicMock(), identity=Identity('name', addre...
class MongoEventStorage(BaseEventStorage): def __init__(self, *args, **kwargs): self.db_conn = self.setup_connection(**kwargs) self.db = None self.server_ip = socket.gethostbyname(socket.gethostname()) def setup_connection(self, **kwargs): db_conf = {'host': kwargs.get('host'), '...
class SELU(): def __init__(self): self.alpha = 1. self.scale = 1. def __call__(self, x): return (self.scale * np.where((x >= 0.0), x, (self.alpha * (np.exp(x) - 1)))) def gradient(self, x): return (self.scale * np.where((x >= 0.0), 1, (self.alpha * np.exp(x))))
def test_complexity(): assert (UnaryOperation(neg, [BinaryOperation(add, [a, b])]).complexity == 2) assert (UnaryOperation(neg, [UnaryOperation(neg, [a])]).complexity == 1) assert (BinaryOperation(add, [a, BinaryOperation(add, [a, b])]).complexity == 3) assert (BinaryOperation(add, [Constant(2), BinaryO...
class _PopupEditor(UIEditor): def init_ui(self, parent): return self.object.edit_traits(view=self.base_view(), parent=parent) def base_view(self): return View(Item(self.name, show_label=False, style='readonly', editor=TextEditor(view=self.popup_view()), padding=(- 4)), kind='subpanel') def p...
class HTTPBytes(HTTPResponse): def __init__(self, status_code: int, body: bytes=b'', headers: Dict[(str, str)]={'content-type': 'text/plain'}, cookies: Dict[(str, Any)]={}): super().__init__(status_code, headers=headers, cookies=cookies) self.body = body async def _send_body(self, send): ...
def test_custom_snapshot_revert_on_reuse(journal_db): custom_checkpoint = (- 1) journal_db.record(custom_checkpoint) auto_checkpoint = journal_db.record() with pytest.raises(ValidationError): journal_db.record(custom_checkpoint) with pytest.raises(ValidationError): journal_db.record(...
def test_log_prob(): var1 = Variable(value=torch.zeros(3), distribution=dist.Bernoulli(0.8)) var2 = var1.replace(value=torch.ones(3)) assert (var1.log_prob.sum() < var2.log_prob.sum()) var3 = var1.replace(distribution=dist.Normal(0.0, 1.0)) assert (var1.log_prob.sum() < var3.log_prob.sum()) var4...
class GpTestFullCovModule(nn.Module): def __init__(self): super().__init__() def forward(self, L, alpha, K_train_test, K_test_test, mean, var=None): pred_mean = (mean + torch.sum((alpha.unsqueeze((- 2)) * K_train_test.unsqueeze((- 1))), dim=1)) v = torch.cholesky_solve(K_train_test, L, u...
class Migration(migrations.Migration): dependencies = [('sites', '0004_auto__1841')] operations = [migrations.RenameField(model_name='scan', old_name='added', new_name='timestamp'), migrations.AddField(model_name='scan', name='enforces_ field=models.BooleanField(default=False), preserve_default=False)]
def test_scalar_real_interpolation(parentmesh, vertexcoords): vm = VertexOnlyMesh(parentmesh, vertexcoords, missing_points_behaviour=None) W = FunctionSpace(vm, 'DG', 0) V = FunctionSpace(parentmesh, 'Real', 0) if (type(parentmesh.topology) is mesh.ExtrudedMeshTopology): with pytest.raises(Value...
def main(page: ft.Page): def items(count): items = [] for i in range(1, (count + 1)): items.append(ft.Container(content=ft.Text(value=str(i)), alignment=ft.alignment.center, width=50, height=50, bgcolor=ft.colors.AMBER, border_radius=ft.border_radius.all(5))) return items def...
.django_db(transaction=True) def test_idv_aggregation_3_level_circular_referencing_idv_and_child(set_up_related_award_objects): child_referencing_parent = modify_award_dict(tp2, {'parent_award_piid': p3['piid'], 'fpds_parent_agency_id': p3['fpds_agency_id']}) true_child = modify_award_dict(p3, {'type': 'A', 'to...
class FidesopsRedis(Redis): def set_with_autoexpire(self, key: str, value: RedisValue, expire_time: int=CONFIG.redis.default_ttl_seconds) -> Optional[bool]: if (not expire_time): expire_time = CONFIG.redis.default_ttl_seconds return self.set(key, value, ex=expire_time) def get_keys_b...
class CoverIconView(EnhancedIconView, AbstractView): __gtype_name__ = 'CoverIconView' icon_spacing = GObject.property(type=int, default=0) icon_padding = GObject.property(type=int, default=0) icon_automatic = GObject.property(type=bool, default=True) display_text_enabled = GObject.property(type=bool...
.parametrize('bytes_arg', (b'abcd', '0x', '', '')) def test_contract_constructor_encoding_strict_errors(contract_with_constructor_args_factory, bytes_arg): with pytest.raises(TypeError, match='One or more arguments could not be encoded to the necessary ABI type.'): contract_with_constructor_args_factory._en...
class S3PathHandler(PathHandler): _strict_kwargs_check = False S3_PREFIX = 's3://' CACHE_SUBDIR_NAME = 's3_cache' def __init__(self, cache_dir: Optional[str]=None, profile: Optional[str]='saml', transfer_config_kwargs: Optional[Dict]=None): self.cache_dir = cache_dir self.profile = profi...
def test_dates_formated_from_pandas(): import pandas as pd df1 = pd.DataFrame([datetime.datetime(2005, 8, 27, 18, 0)], columns=['date']) df2 = pd.DataFrame([datetime.datetime(2005, 8, 26, 18, 0), datetime.datetime(2005, 8, 27, 18, 0)], columns=['date']) ('date', 'date-list(%Y-%m-%d)') def f(date): ...
def open_raw_session_args__init__(self, device=None, open_timeout=open_raw_session_args.thrift_spec[2][4], idle_timeout=open_raw_session_args.thrift_spec[3][4], client_ip=open_raw_session_args.thrift_spec[10][4], client_port=open_raw_session_args.thrift_spec[11][4], uuid=open_raw_session_args.thrift_spec[12][4]): s...
class Templater(Renoir): def __init__(self, **kwargs): kwargs['lexers'] = lexers super().__init__(**kwargs) self._namespaces = {} def _set_reload(self, value): self.cache.changes = value self.cache.load._configure() self.cache.prerender._configure() self.c...
def extractVigneshtranslationsWordpressCom(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 ServiceServicer(object): def GetNodeInfo(self, request, context): context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetSyncing(self, request, context): context.set_code(grp...
class ZServer(object): def __init__(self, client): self.client = client self.logger = client.logger self.is_active = False self.sock = None self.threads = [] def start(self): self.is_active = True try: self.sock = create_connection(self.client....
def main(args: Optional[List[str]]=None) -> None: cli_parser = get_parser() cli_args = cli_parser.parse_args(args) if (cli_args.platform == 'aws'): aws_obj = AwsDeploymentHelperTool(cli_args) action_to_perform = getattr(aws_obj, cli_args.action) action_to_perform() else: ...
(scope='function') def wunderkind_connection_config(db: session, wunderkind_config, wunderkind_secrets) -> Generator: fides_key = wunderkind_config['fides_key'] connection_config = ConnectionConfig.create(db=db, data={'key': fides_key, 'name': fides_key, 'connection_type': ConnectionType.saas, 'access': AccessL...
def learn_action(args): import os import time from lib import MAX_SYSCALLS from lib.ebpf import Probe if os.path.exists(args.data): print(('%s already exists' % args.data)) quit() probe = Probe(args.pid) print(('learning from process %d (%s), saving data to %s ...' % (args.pi...
def _parse_dp(dp_key, dp_conf, acls_conf, meters_conf, routers_conf, vlans_conf): test_config_condition((not isinstance(dp_conf, dict)), 'DP config must be dict') dp = DP(dp_key, dp_conf.get('dp_id', None), dp_conf) test_config_condition((dp.name != dp_key), ('DP key %s and DP name must match' % dp_key)) ...
class EmailObjectBuilder(): def __init__(self, tags: dict, folder: str): self.tags = tags self.folder = folder def set_tags(self, tags: dict): self.tags = tags return self def set_folder(self, folder: str): self.folder = folder return self def build(self) ...
def validate_rpc_transaction_vs_fixture(transaction, fixture): expected = fixture_transaction_in_rpc_format(fixture) stripped = dissoc(transaction, 'hash', 'from', 'yParity') if ('type' not in stripped): actual_transaction = dissoc(stripped, 'chainId') elif (stripped['type'] == '0x1'): a...
class AssembledVector(TensorBase): def integrals(self): raise ValueError('AssembledVector has no integrals') operands = () terminal = True assembled = True def __new__(cls, function): if isinstance(function, AssembledVector): return function elif isinstance(functi...
.parametrize('distance_matrix, expected_distance', [(distance_matrix1, 28), (distance_matrix2, 26), (distance_matrix3, 20)]) def test_return_correct_permutation_distance_initial_node_not_zero(distance_matrix, expected_distance): permutation = [3, 1, 4, 0, 2] distance = compute_permutation_distance(distance_matr...
class TelegramTests(unittest.IsolatedAsyncioTestCase): ("This test doesn't end and is for manual execution only.") async def test_run_bot_in_idle(self) -> None: with LootDatabase(echo=True) as db: async with TelegramBot(Config.get(), db.Session): pass async def test_teleg...
def extractEtherealNovels(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return False tagmap = {'Miracle Doctor, Wild Empress: Genius Summoner': 'Miracle Doctor, Wild Empress: Genius Summoner'} f...
class GRNItemRow(): vendor_code: str vendor_invoice_number: str invoice_date: str sku: str qty: int item_code: str purchase_order: str = '' manufacturing_date: str = '' expiry_date: str = '' batch_number: str = '' shelf_code: str = '' item_details: str = '' mrp: str =...