code
stringlengths
281
23.7M
class Poller(object): def __init__(self, fileno, exceptions, timeout=5): self.select = select self._fileno = fileno self._exceptions = exceptions self.timeout = timeout def fileno(self): return self._fileno def is_ready(self): try: (ready, _, _) = ...
class Persistence(Options): def sort(self): return self._config_get() def sort(self, val): self._config(val) def filter(self): return self._config_get() def filter(self, val): self._config(val) def group(self) -> PersistenceGroup: return self.has_attribute(Per...
def compress_zstd(input_file): import zstandard as zstd output_file = f'{input_file}.zs' cctx = zstd.ZstdCompressor() with open(input_file, 'rb') as f_in, open(output_file, 'wb') as f_out: compressed_data = cctx.compress(f_in.read()) f_out.write(compressed_data) print(f'Compressed fi...
class IDPP(Interpolator): def interpolate(self, initial_geom, final_geom, **kwargs): linear_interpol = super().interpolate(initial_geom, final_geom) idpp_geoms = (([initial_geom] + linear_interpol) + [final_geom]) align_geoms(idpp_geoms) for geom in idpp_geoms: geom.coord...
def test_wallet_storage_database_nonexistent_creates(tmp_path) -> None: wallet_filepath = os.path.join(tmp_path, 'walletfile') storage = WalletStorage(wallet_filepath) try: assert (type(storage._store) is DatabaseStore) assert (storage.get('migration') == MIGRATION_CURRENT) finally: ...
class Dispatcher(object): def __init__(self, comm=None, on=False): self.comm = comm self.on = on def __call__(self, func, func_args, func_kwargs, profile_name=''): if (not self.on): return func(*func_args, **func_kwargs) else: return self.profile_function(...
def named_parameter(**kwargs): if ((kwargs['default'] is False) and (kwargs['conv'] is is_true)): del kwargs['default'] return FlagParameter(value=True, **kwargs) elif (kwargs['conv'] is _implicit_converters[int]): return IntOptionParameter(**kwargs) else: return OptionParame...
class OptionSeriesTimelineStatesInactive(Options): def animation(self) -> 'OptionSeriesTimelineStatesInactiveAnimation': return self._config_sub_data('animation', OptionSeriesTimelineStatesInactiveAnimation) def enabled(self): return self._config_get(True) def enabled(self, flag: bool): ...
def test_line_continuations(): file_path = ((test_dir / 'parse') / 'line_continuations.f90') file = FortranFile(str(file_path)) (err_str, _) = file.load_from_disk() assert (err_str is None) try: file.parse() assert True except Exception as e: print(e) assert False
class ForemastRunner(): def __init__(self): debug_flag() self.email = os.getenv('EMAIL') self.env = os.getenv('ENV') self.group = os.getenv('PROJECT') self.region = os.getenv('REGION') self.repo = os.getenv('GIT_REPO') self.runway_dir = os.getenv('RUNWAY_DIR')...
def add_fcos_configs(cfg): cfg.MODEL.FCOS = CN() cfg.MODEL.FCOS.NUM_CLASSES = 80 cfg.MODEL.FCOS.IN_FEATURES = ['p3', 'p4', 'p5', 'p6', 'p7'] cfg.MODEL.FCOS.NUM_CONVS = 4 cfg.MODEL.FCOS.HEAD_NORM = 'GN' cfg.MODEL.FCOS.SCORE_THRESH_TEST = 0.04 cfg.MODEL.FCOS.TOPK_CANDIDATES_TEST = 1000 cfg...
def convert_to_bitvec(val): if isinstance(val, z3.BoolRef): return z3.If(val, z3.BitVecVal(1, 256), z3.BitVecVal(0, 256)) elif isinstance(val, bool): return (z3.BitVecVal(1, 256) if val else z3.BitVecVal(0, 256)) elif isinstance(val, int): return z3.BitVecVal(val, 256) else: ...
class PluginHandler(): def __init__(self, ert: 'EnKFMain', notifier: 'ErtNotifier', plugin_jobs: List['WorkflowJob'], parent_window): self.__ert = ert self.__plugins = [] for job in plugin_jobs: plugin = Plugin(self.__ert, notifier, job) self.__plugins.append(plugin) ...
class TestListIOSApps(BaseProjectManagementTest): _LISTING_URL = ' _LISTING_PAGE_2_URL = ' def test_list_ios_apps(self): recorder = self._instrument_service(statuses=[200], responses=[LIST_IOS_APPS_RESPONSE]) ios_apps = project_management.list_ios_apps() expected_app_ids = set(['1::i...
class DeleteAllSubjects(): class Request(): pass def __init__(self, domain: str, port: str, api_key: str): self.add_subject = SubjectClient(api_key=api_key, domain=domain, port=port) def execute(self) -> dict: result: dict = self.add_subject.delete() return result
.skipif((not can_import('magic')), reason='Libmagic is not installed') def test_mismatching_file_types(local_dummy_txt_file): def t1(path: FlyteFile[typing.TypeVar('txt')]) -> FlyteFile[typing.TypeVar('jpeg')]: return path def my_wf(path: FlyteFile[typing.TypeVar('txt')]) -> FlyteFile[typing.TypeVar('jp...
class Solution(): def minCut(self, s: str) -> int: n = len(s) _cache(None) def isPalindrome(l, r): if (l >= r): return True if (s[l] != s[r]): return False return isPalindrome((l + 1), (r - 1)) _cache(None) d...
class ShanghaiBackwardsHeader(BlockHeaderSedesAPI): def serialize(cls, obj: BlockHeaderAPI) -> List[bytes]: return obj.serialize(obj) def deserialize(cls, encoded: List[bytes]) -> BlockHeaderAPI: num_fields = len(encoded) if (num_fields == 17): return ShanghaiBlockHeader.dese...
def create_perturbed_dataclass(perturbed_ds, perturbations_per_sample: int, original_dataset_size: int, perturbation_type: str): total_perturbations = (len(perturbed_ds.data) * perturbations_per_sample) return PerturbedTextDataset(data=perturbed_ds.data, metadata=perturbed_ds.meta, total_perturbations=total_per...
class Filehead(): version_number: int year: int version_bound: int type_of_grid: TypeOfGrid rock_model: RockModel grid_format: GridFormat def from_egrid(cls, values: list[int]): if (len(values) < 7): raise ValueError(f'Filehead given too few values, {len(values)} < 7') ...
class FiltersAPI(APIClient): def get_filters(self, test_results_totals: Dict[(Optional[str], TotalsSchema)], test_runs_totals: Dict[(Optional[str], TotalsSchema)], models: Dict[(str, NormalizedModelSchema)], sources: Dict[(str, NormalizedSourceSchema)], models_runs: List[ModelRunsSchema]) -> FiltersSchema: ...
class OptionSeriesWindbarbSonificationTracksMappingLowpassResonance(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 test_cli_ethpm_with_type_error_exception(cli_tester, testproject): cli_tester.monkeypatch.setattr('brownie._cli.ethpm._list', (lambda project_path: cli_tester.raise_type_error_exception('foobar'))) cli_tester.run_and_test_parameters('ethpm list', parameters=None) assert (cli_tester.mock_subroutines.call...
def test_working_hours_attribute_is_working_properly(): import copy from stalker import defaults working_hours = copy.copy(defaults.working_hours) working_hours['sun'] = [[540, 1000]] working_hours['sat'] = [[500, 800], [900, 1440]] wh = WorkingHours() wh.working_hours = working_hours as...
def text2kata(text: str) -> str: parsed = pyopenjtalk.run_frontend(text) res = [] for parts in parsed: (word, yomi) = (replace_punctuation(parts['orig']), parts['pron'].replace('', '')) if yomi: if re.match(_MARKS, yomi): if (len(word) > 1): wo...
(scope='function') def manual_dataset_config(integration_manual_config: ConnectionConfig, db: Session, example_datasets: List[Dict]) -> Generator: manual_dataset = example_datasets[8] fides_key = manual_dataset['fides_key'] integration_manual_config.name = fides_key integration_manual_config.key = fides...
def from_ethpm(uri: str) -> 'TempProject': manifest = get_manifest(uri) compiler_config = {'evm_version': None, 'solc': {'version': None, 'optimize': True, 'runs': 200}, 'vyper': {'version': None}} project = TempProject(manifest['package_name'], manifest['sources'], compiler_config) if web3.isConnected(...
class OptionSeriesVennStatesSelect(Options): def animation(self) -> 'OptionSeriesVennStatesSelectAnimation': return self._config_sub_data('animation', OptionSeriesVennStatesSelectAnimation) def enabled(self): return self._config_get(True) def enabled(self, flag: bool): self._config(f...
class MergePipeline(): def __init__(self, pipeline_list: List, execute_merge_on): self.pipeline_list = pipeline_list self.execute_merge_on = execute_merge_on def fit(self, index): for pipeline in self.pipeline_list: pipeline.fit(index) def _single_batch(self, batch): ...
class OptionSeriesAreasplineSonificationContexttracksMappingGapbetweennotes(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: st...
_plot _dependency(plt, 'matplotlib') def plot_spectra(freqs, power_spectra, log_freqs=False, log_powers=False, freq_range=None, colors=None, labels=None, ax=None, **plot_kwargs): ax = check_ax(ax, plot_kwargs.pop('figsize', PLT_FIGSIZES['spectral'])) plot_kwargs = check_plot_kwargs(plot_kwargs, {'linewidth': 2....
def extractNovellibrariumBlogspotCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('Banished to Another World', 'Banished to Another World', 'translated'), ('PRC', 'PRC', 'tra...
class Test(unittest.TestCase): def test_utcnow(self): dt_now = datetime.utcnow() now = udatetime.utcnow() self.assertIsInstance(now, datetime) self.assertEqual(now.year, dt_now.year) self.assertEqual(now.month, dt_now.month) self.assertEqual(now.day, dt_now.day) ...
class Source(Box, AbstractSource, ABC): source_time: SourceTimeType = pydantic.Field(..., title='Source Time', description='Specification of the source time-dependence.', discriminator=TYPE_TAG_STR) _property def plot_params(self) -> PlotParams: return plot_params_source _property def geomet...
class AEATestCaseManyFlaky(AEATestCaseMany): run_count: int = 0 def setup_class(cls) -> None: super(AEATestCaseManyFlaky, cls).setup_class() if (len(cls.method_list) > 1): raise ValueError(f'{cls.__name__} can only contain one test method!') cls.run_count += 1 def teardow...
def _generate_python_code_line(opt): if opt.is_flag(): funcargs = (opt.opttext() + ", action='store_true'") elif opt.is_option(): funcargs = opt.opttext() if (opt.type == ArgType.STRING): choices = opt.value.split(',') if (len(choices) > 1): funcar...
class reversed(_coconut_has_iter): __slots__ = () __doc__ = getattr(_coconut.reversed, '__doc__', '<see help(py_reversed)>') def __new__(cls, iterable): if _coconut.isinstance(iterable, _coconut.range): return iterable[::(- 1)] if ((_coconut.getattr(iterable, '__reversed__', None...
class TestUnshardedLightningDLRM(unittest.TestCase): def test_train_model(self) -> None: num_embeddings = 100 embedding_dim = 10 num_dense = 50 eb1_config = EmbeddingBagConfig(name='t1', embedding_dim=embedding_dim, num_embeddings=num_embeddings, feature_names=['f1', 'f3']) e...
def test_updates_query_total(bodhi_container, db_container): db_ip = db_container.get_IPv4s()[0] query = 'SELECT COUNT(*) FROM updates' conn = psycopg2.connect('dbname=bodhi2 user=postgres host={}'.format(db_ip)) with conn: with conn.cursor() as curs: curs.execute(query) ...
def test_raises_only_field_errors_unexpected_missing(unknown_event_id_field_error, invalid_organization_id_field_error): errors = [unknown_event_id_field_error, invalid_organization_id_field_error] with pytest.raises(pytest.raises.Exception): with raises_only_field_errors({'event_id': 'MISSING'}): ...
def test_ttcompile_ttf_to_woff_without_zopfli(tmpdir): inttx = os.path.join('Tests', 'ttx', 'data', 'TestTTF.ttx') outwoff = tmpdir.join('TestTTF.woff') options = ttx.Options([], 1) options.flavor = 'woff' ttx.ttCompile(inttx, str(outwoff), options) assert outwoff.check(file=True) ttf = TTFo...
def test_write_to_runpath_produces_the_transformed_field_in_storage(snake_oil_field_example, storage): ensemble_config = snake_oil_field_example.ensemble_config experiment_id = storage.create_experiment(parameters=ensemble_config.parameter_configuration) prior_ensemble = storage.create_ensemble(experiment_i...
class TestOSHelpers(unittest.TestCase): def test_current_os(self): for plat in ['linux', 'linux2']: with mock.patch.object(sys, 'platform', plat): self.assertEqual(current_os(), 'linux') with mock.patch.object(sys, 'platform', 'darwin'): self.assertEqual(curre...
def _ragged_forward(layer: Model[(Padded, Padded)], Xr: Ragged, is_train: bool) -> Tuple[(Ragged, Callable)]: list2padded = layer.ops.list2padded padded2list = layer.ops.padded2list unflatten = layer.ops.unflatten flatten = layer.ops.flatten (Yp, get_dXp) = layer(list2padded(unflatten(Xr.data, Xr.le...
class TestTachoMotorSpeedPValue(ptc.ParameterizedTestCase): def test_speed_i_negative(self): with self.assertRaises(IOError): self._param['motor'].speed_p = (- 1) def test_speed_p_zero(self): self._param['motor'].speed_p = 0 self.assertEqual(self._param['motor'].speed_p, 0) ...
class QuadLimbDark(pm.Flat): __citations__ = ('kipping13',) def __init__(self, *args, **kwargs): add_citations_to_model(self.__citations__, kwargs.get('model', None)) shape = kwargs.get('shape', 2) try: if (list(shape)[0] != 2): raise ValueError('the first dim...
class OptionSeriesTilemapSonificationContexttracks(Options): def activeWhen(self) -> 'OptionSeriesTilemapSonificationContexttracksActivewhen': return self._config_sub_data('activeWhen', OptionSeriesTilemapSonificationContexttracksActivewhen) def instrument(self): return self._config_get('piano')...
def extractHereticunboundWordpressCom(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_...
def encrypt(rHost='127.0.0.1', rUsername='user_iptvpro', rPassword='', rDatabase='xtream_iptvpro', rServerID=1, rPort=7999): try: os.remove('/home/xtreamcodes/iptv_xtream_codes/config') except: pass rf = open('/home/xtreamcodes/iptv_xtream_codes/config', 'wb') rf.write(''.join((chr((ord(...
def jwt_none(url, method, headers, body, jwt_loc, jwt_key, jwt_token, jwt_data, scanid=None): encoded_jwt = jwt.encode(jwt_data, '', algorithm='none') if (jwt_loc == 'url'): url = url.replace(value[0], encoded_jwt) if (jwt_loc == 'header'): headers[key] = encoded_jwt jwt_request = req.ap...
class AttachmentView(PermissionRequiredMixin, DetailView): model = Attachment def render_to_response(self, context, **response_kwargs): filename = os.path.basename(self.object.file.name) (content_type, _) = mimetypes.guess_type(self.object.file.name) if (not content_type): co...
class TestOPAWDLParser(unittest.TestCase): def setUp(self): self.parser = OPAWDLParser() self.test_plugin_name = 'test_plugin' self.test_cmd_args_list = ['-a=b', '-c=d'] self.test_opawdl_state = OPAWDLState(plugin_name=self.test_plugin_name, cmd_args_list=self.test_cmd_args_list) ...
.django_db def test_validate_recipient_id_failures(): recipient_id = 'a52a7544-829b-c925-e1ba-d04d3171c09a-P' baker.make('recipient.RecipientProfile', **TEST_RECIPIENT_PROFILES[recipient_id]) def call_validate_recipient_id(recipient_id): try: recipients.validate_recipient_id(recipient_id...
def _parse_pc_validator_config(pc_config: Dict[(str, Any)]) -> PCValidatorConfig: raw_pc_validator_config = pc_config['dependency'].get('PCValidatorConfig') if (not raw_pc_validator_config): storage_svc_region = pc_config['dependency']['StorageService']['constructor']['region'] return PCValidato...
def test_get_architecture_stats(stats_updater, backend_db): insert_test_fw(backend_db, 'root_fw', vendor='foobar') insert_test_fo(backend_db, 'fo1', parent_fw='root_fw', analysis={'cpu_architecture': generate_analysis_entry(summary=['MIPS, 32-bit, big endian (M)'])}) insert_test_fo(backend_db, 'fo2', parent...
class NonlinearAD_SteadyState(LinearAD_SteadyState): def __init__(self, b=1.0, q=2, a=0.5, r=1): LinearAD_SteadyState.__init__(self, b, a) self.r_ = r self.q_ = q if ((q == 2) and (r == 1)): if (b != 0.0): def f(rtmC): return ((rtmC * t...
class FacebookOAuth2(BaseOAuth2[Dict[(str, Any)]]): display_name = 'Facebook' logo_svg = LOGO_SVG def __init__(self, client_id: str, client_secret: str, scopes: Optional[List[str]]=BASE_SCOPES, name: str='facebook'): super().__init__(client_id, client_secret, AUTHORIZE_ENDPOINT, ACCESS_TOKEN_ENDPOIN...
('method', ['resize', 'sample']) def test_resize_and_sample_errors(method): with Image(filename='rose:') as img: with raises(TypeError): getattr(img, method)(width='100') with raises(TypeError): getattr(img, method)(height='100') with raises(ValueError): g...
def test_normalize_availability_on_method(): norm_decorator = normalize('param', ['a', 'b']) availability_decorator_1 = availability(C1) class A(): _decorator _decorator_1 def method1(self, level, param, step): return (level, param, step) assert (A().method1(level='10...
class OptionPlotoptionsVennSonificationTracksMappingGapbetweennotes(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 on_order_completed(order): if (not ((order.status == 'completed') or (order.status == 'placed'))): return create_pdf_tickets_for_holder(order) send_email_to_attendees(order) notify_ticket_purchase_attendee(order) if (order.payment_mode in ['free', 'bank', 'cheque', 'onsite']): or...
('/workflow/task-view') def task_view(): project_id = request.args.get('project_id') workflow_name = request.args.get('workflow_name') project_meta = store.get_project_by_id(project_id) if (project_meta is None): raise Exception('The project({}) for the workflow({}) is not found.'.format(project...
class Migration(migrations.Migration): dependencies = [('bank', '0004_auto__0900')] operations = [migrations.AddField(model_name='transaction', name='date', field=models.DateTimeField(default=django.utils.timezone.now)), migrations.AddField(model_name='transaction', name='updated', field=models.DateTimeField(de...
def _format_json_str(jstr): result = [] inside_quotes = False last_char = ' ' for char in jstr: if ((last_char != '\\') and (char == '"')): inside_quotes = (not inside_quotes) last_char = char if ((not inside_quotes) and (char == '\n')): continue i...
def test_transfer16(la: LogicAnalyzer, slave: SPISlave): la.capture(4, block=False) value = slave.transfer16(WRITE_DATA16) la.stop() (sck, sdo, cs, sdi) = la.fetch_data() sdi_initstate = la.get_initial_states()[SDI[0]] assert (len(cs) == (CS_START + CS_STOP)) assert (len(sck) == SCK_WRITE16)...
class FBetaTopKMetric(TopKMetric): k: int beta: Optional[float] min_rel_score: Optional[int] no_feedback_users: bool _precision_recall_calculation: PrecisionRecallCalculation def __init__(self, k: int, beta: Optional[float]=1.0, min_rel_score: Optional[int]=None, no_feedback_users: bool=False, o...
def test_main_exit_invalid_location(varfont, tmpdir, capsys): fontfile = str((tmpdir / 'PartialInstancerTest-VF.ttf')) varfont.save(fontfile) with pytest.raises(SystemExit): instancer.main([fontfile, 'wght:100']) captured = capsys.readouterr() assert ('invalid location format' in captured.er...
def pretty_print(tree: Tree, name: str='root', depth: int=0) -> None: pad = ((' ' * depth) * 2) print(f'{pad}{name}({tree.value})') if (tree.left is not None): pretty_print(tree.left, name='left', depth=(depth + 1)) if (tree.right is not None): pretty_print(tree.right, name='right', dept...
class PopStatsProcessor(AbstractGamestateDataProcessor): ID = 'pop_stats' DEPENDENCIES = [CountryProcessor.ID, SpeciesProcessor.ID, FactionProcessor.ID, CountryDataProcessor.ID] def __init__(self): super().__init__() self.country_by_planet_id = None def initialize_data(self): sel...
_only_with_numba def test_laplace(): region = ((- 10000.0), 10000.0, (- 10000.0), 10000.0) coords = vd.grid_coordinates(region, shape=(10, 10), extra_coords=300) prisms = [[1000.0, 7000.0, (- 5000.0), 2000.0, (- 1000.0), (- 500)], [(- 4000.0), 1000.0, 4000.0, 10000.0, (- 2000.0), 200]] densities = [2670...
def extractJapmtlWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [("one day, the engagement was suddenly cancelled. ......my little sister's.", "one day, the engageme...
class DecisionEvents(): events: List[HistoryEvent] decision_events: List[HistoryEvent] replay: bool replay_current_time_milliseconds: datetime.datetime next_decision_event_id: int markers: List[HistoryEvent] = field(default_factory=list) def __post_init__(self): for event in self.dec...
(scope='module') def dolt_install(): tmp_dir = tempfile.TemporaryDirectory() dir_path = os.path.dirname(os.path.realpath(__file__)) install_script = os.path.join(dir_path, '..', '..', 'flytekit-dolt', 'scripts', 'install.sh') try: dolt_path = os.path.join(tmp_dir.name, 'dolt') subprocess...
class AttributeGrammar(Grammar): def __init__(self, classes, rule_extractor=..., check_acyclicity=False, **kwargs): super().__init__(classes, **kwargs) if (rule_extractor is ...): raise DeprecationWarning('A rule extractor must be passed explicitly.') self.attributes = {} ...
class OptionPlotoptionsBellcurveSonificationDefaultinstrumentoptionsMappingPitch(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('y') def mapTo(self, text...
class TestComment(): def test_url_flag(self, mocked_client_class): mocked_client_class.send_request.return_value = client_test_data.EXAMPLE_COMMENT_MUNCH runner = testing.CliRunner() result = runner.invoke(cli.comment, ['nodejs-grunt-wrap-0.3.0-2.fc25', 'After installing this I found $100.',...
def extractReleasethatwitchWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('Release that Witch', 'Release that Witch', 'translated')] for (tagname, name, tl_typ...
def draw_background(screen, tile_img_file, field_rect): tile_img = pygame.image.load(tile_img_file).convert_alpha() img_rect = tile_img.get_rect() nrows = (int((screen.get_height() / img_rect.height)) + 1) ncols = (int((screen.get_width() / img_rect.width)) + 1) for y in range(nrows): for x ...
def extractStarveCleric(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol or frag)) or ('preview' in item['title'].lower())): return None if ('protected' in item['title'].lower()): return None tagmap = [("Library of Heaven's Path", "L...
def main(page: Page): page.title = 'MyApp' def window_event(e): if (e.data == 'close'): page.dialog = confirm_dialog confirm_dialog.open = True page.update() page.window_prevent_close = True page.on_window_event = window_event def yes_click(e): pag...
def _add_peaks_dot(model, plt_log, ax, **plot_kwargs): defaults = {'color': PLT_COLORS['periodic'], 'alpha': 0.6, 'lw': 2.5, 'ms': 6} plot_kwargs = check_plot_kwargs(plot_kwargs, defaults) for peak in model.peak_params_: ap_point = np.interp(peak[0], model.freqs, model._ap_fit) freq_point = ...
class Actions(): def __init__(self, endpoint, sdnc): self.endpoint = endpoint self.sdnc = sdnc def mirror_endpoint(self): status = False if self.sdnc: endpoint_data = self.endpoint.endpoint_data if self.sdnc.mirror_mac(endpoint_data['mac'], endpoint_data['...
class SourceHutBackendTests(DatabaseTestCase): def setUp(self): super().setUp() create_distro(self.session) self.create_project() def create_project(self): self.projects = {} project = models.Project(homepage=' name='builds.sr.ht', backend=BACKEND) self.session.ad...
(scope='module', autouse=True) def prepare_db(): dbs_path = pathlib.Path(DBT_PROJECT_DIR, 'dbs') dbs_path.mkdir(exist_ok=True, parents=True) database_file = pathlib.Path(dbs_path, 'database_name.db') database_file.touch() check_call(['dbt', '--log-format', 'json', 'seed', '--project-dir', DBT_PROJEC...
def strhex2float(x, signed=True, n_word=None, n_frac=None, return_sizes=False): x = x.replace('0x', '') if (n_word is None): n_word = (len(x) * 4) x_bin = bin(int(x, 16)) if (len(x_bin[2:]) < n_word): x_bin = (('0b' + ('0' * (n_word - len(x_bin[2:])))) + x_bin[2:]) (val, signed, n_wo...
.frontend_config_overwrite({'results_per_page': 10}) .WebInterfaceUnitTestConfig(database_mock_class=DbMock) class TestAppQuickSearch(): def test_quick_search_file_name(self, test_client): assert (TEST_FW_2.uid in _start_quick_search(test_client, TEST_FW_2.file_name)) def test_quick_search_device_name(s...
def frequency_limit_decorator(key=None, cache_id='nid', msg=',{}!', mode='cache', timeout=TIME_OUT, hook=default_hook_function): def frequency_decorator(fun): (fun) def cache_control(*args, **kwargs): class_obj = args[0] cache_key = (key or class_obj.__class__.__name__) ...
def get_registered_stattest(stattest_func: Optional[PossibleStatTestType], feature_type: ColumnType=None, engine: Type[Engine]=None) -> StatTest: if isinstance(stattest_func, StatTest): return stattest_func if (callable(stattest_func) and (stattest_func not in _registered_stat_test_funcs)): stat...
('add-domain', help='Add a custom domain to a particular site') ('domain') ('--site', prompt=True) ('--ssl-certificate', help='Absolute path to SSL Certificate') ('--ssl-certificate-key', help='Absolute path to SSL Certificate Key') def add_domain(domain, site=None, ssl_certificate=None, ssl_certificate_key=None): ...
def test_issue_60_v0_4_6(): cfg = Config(dtype_notation='Q', rounding='around') t_fxp = Fxp(0.0, 1, n_int=16, n_frac=15, config=cfg) t_int = Fxp(0.0, 1, n_int=13, n_frac=0, config=cfg) arr = [(- 5), 0, 14.8, 7961.625] fullprec = Fxp(arr, like=t_fxp) rounded_direct = Fxp(arr, like=t_int) roun...
def main(): ap = argparse.ArgumentParser(description='Generate Xerox twolcs for Finnish') 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', default=False, help='...
def duno_filtro(img): contrast = ImageEnhance.Contrast(img) contrastado = contrast.enhance(1.1) brightness = ImageEnhance.Brightness(contrastado) brilho = brightness.enhance(1.1) saturation = ImageEnhance.Color(brilho) saturada = saturation.enhance(1.3) saturada.save('beijo_editada.jpg')
class ElementNewton(proteus.NonlinearSolvers.NonlinearSolver): def __init__(self, linearSolver, F, J=None, du=None, par_du=None, rtol_r=0.0001, atol_r=1e-16, rtol_du=0.0001, atol_du=1e-16, maxIts=100, norm=l2Norm, convergenceTest='r', computeRates=True, printInfo=True, fullNewton=True, directSolver=False, EWtol=Tru...
_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestUIWrapperInteractionRegistries(unittest.TestCase): def test_registry_priority(self): registry1 = StubRegistry(handler=(lambda w, l: 1), supported_interaction_classes=[str]) registry2 = StubRegistry(handler=(lambda w, l: 2), supported_interaction_c...
def extractCanemfurryWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None if ((item['tags'] == ['Releases']) or (item['tags'] == ['Uncategorized'])): titlemap = [('TDD Cha...
class DataBase(): dbase: str = '' kfile: str = '' pword: str = None atype: str = None totp: bool = False is_active: bool = False kpo: str = None def __post_init__(self): self.dbase = (realpath(expanduser(self.dbase)) if self.dbase else '') self.kfile = (realpath(expanduse...
class BadgeFieldFormListPost(ResourceList): def before_post(data): require_relationship(['badge_form'], data) if (not has_access('is_coorganizer', badge_form=data['badge_form'])): raise ObjectNotFound({'parameter': 'badge_form'}, f"Custom Form: {data['badge_form']} not found") schema...
_admin_required def BookingManageCreate(request, location_slug): username = '' if (request.method == 'POST'): location = get_object_or_404(Location, slug=location_slug) notify = request.POST.get('email_announce') logger.debug('notify was set to:') logger.debug(notify) try...
class GPTask(HasMentions, HasActivity, Document): on_delete_cascade = ['GP Comment', 'GP Activity'] on_delete_set_null = ['GP Notification'] activities = ['Task Value Changed'] mentions_field = 'description' def before_insert(self): if (not self.status): self.status = 'Backlog' ...
def main(): build_dir = 'gateware' platform = Platform() if ('load' in sys.argv[1:]): prog = platform.create_programmer() prog.load_bitstream(os.path.join(build_dir, 'impl', 'pnr', 'project.fs')) exit() if ('sim' in sys.argv[1:]): ring = RingSerialCtrl() run_simul...