code
stringlengths
281
23.7M
def buildFKeyStmt(conn, tableName, key): unqIndex = getUniqueIndex(conn, key['table']) keyList = getFKeyList(conn, key['table']) keyStmt = [] for colName in unqIndex: keyKey = search_keyList(keyList, colName) if keyKey: newStmt = buildFKeyStmt(conn, key['table'], keyKey) ...
class ExtendedNotifiers(HasTraits): def __init__(self, **traits): ok_listeners = [self.method_listener_0, self.method_listener_1, self.method_listener_2, self.method_listener_3, self.method_listener_4] for listener in ok_listeners: self._on_trait_change(listener, 'ok', dispatch='extended...
def collect_general_telemetry_data(session, telemetry_user): endpoints = session.query(Endpoint.name).all() blueprints = set((get_blueprint(endpoint) for (endpoint,) in endpoints)) no_of_endpoints = len(endpoints) no_of_blueprints = len(blueprints) counts = session.query(Endpoint.monitor_level, func...
class TestGetRegexCleanedLayoutBlockWithPrefixSuffix(): def test_should_return_original_block_for_non_matching_regex(self): layout_block = LayoutBlock.for_text('test') (prefix_block, cleaned_block, suffix_block) = get_regex_cleaned_layout_block_with_prefix_suffix(layout_block, 'other') asser...
def _parse_cache_to_checkpoint_action_required(cache: dict[(str, Any)]) -> CheckpointActionRequired: collection = (CollectionAddress(cache['collection']['dataset'], cache['collection']['collection']) if cache.get('collection') else None) action_needed = ([ManualAction(**action) for action in cache['action_neede...
class StubEditor(Editor): is_event = Bool() auxiliary_value = Any() auxiliary_list = List() auxiliary_event = Event() auxiliary_cv_int = Int(sync_value='from') auxiliary_cv_float = Float() def init(self, parent): self.control = FakeControl() self.is_event = self.factory.is_ev...
def pytest_collection_modifyitems(config, items): if config.getoption('--network'): global _dev_network _dev_network = config.getoption('--network') if config.getoption('--evm'): target = 'evm' else: target = config.getoption('--target') for (flag, fixture) in TARGET_OPTS...
def get_stock_rating_data(debug=False): global data_to_add global allStockData counter = 0 print('\nCalculating Stock Ratings...\n') with tqdm(total=allStockData.shape[0]) as pbar: for row in allStockData.iterrows(): (ticker, sector) = (row[1]['Ticker'], row[1]['Sector']) ...
_required _required _POST def settings_form(request, hostname): if (hostname is None): vm = None else: vm = get_vm(request, hostname) if request.user.is_admin(request): action = None form = AdminServerSettingsForm(request, vm, request.POST, prefix='opt') else: act...
class IndexWrapperForCfGrib(): def __init__(self, index=None, ignore_keys=[]): self.index = index self.ignore_keys = ignore_keys def __getstate__(self): return dict(index=serialise_state(self.index), ignore_keys=self.ignore_keys) def __setstate__(self, state): self.index = de...
class OptionSeriesErrorbarSonificationDefaultinstrumentoptionsMappingPan(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 OptionSonificationGlobalcontexttracksMappingPlaydelay(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...
(arrays_OI_O_BI(max_batch=8, max_out=8, max_in=8)) def test_dropout_gives_zero_gradients(W_b_input): model = chain(get_model(W_b_input), Dropout(1.0)) (nr_batch, nr_out, nr_in) = get_shape(W_b_input) (W, b, input_) = W_b_input for node in model.walk(): if (node.name == 'dropout'): no...
class UtilsTest(unittest.TestCase): def test_json_hook(self): example_input = {'date': '/Date(+1300)/'} self.assertEqual(xero.utils.json_load_object_hook(example_input), {'date': datetime.datetime(2015, 3, 21, 0, 0)}) example_input = {'date': '2015-04-29T00:00:00'} self.assertEqual(x...
def get_datasets(root: str): transform_train = transforms.Compose([transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.201))]) transform_cv = transforms.Compose([transforms.ToTensor(), transforms.Normal...
class conn_tracking_zone(oxm): type_len = 119810 def __init__(self, value=None): if (value != None): self.value = value else: self.value = 0 return def pack(self): packed = [] packed.append(struct.pack('!L', self.type_len)) packed.appen...
def main(): module_spec = schema_to_module_spec(versioned_schema) mkeyname = None fields = {'access_token': {'required': False, 'type': 'str', 'no_log': True}, 'enable_log': {'required': False, 'type': 'bool', 'default': False}, 'vdom': {'required': False, 'type': 'str', 'default': 'root'}, 'member_path': {...
class TyperTest(unittest.TestCase): def test_typer(self) -> None: self.maxDiff = None bmg = BMGraphBuilder() c0 = bmg.add_constant(0.0) c1 = bmg.add_constant(1.0) c2 = bmg.add_constant(2.0) c3 = bmg.add_constant(3.0) norm = bmg.add_normal(c0, c1) ns = ...
class EvalTableFilter(TableFilter): name = 'Default evaluation filter' expression = Expression filter_view = Group('expression') def filter(self, object): if (self._traits is None): self._traits = object.trait_names() try: return eval(self.expression_, globals(), ...
def extractOtherworldsinwordWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('riad', 'The Roommates Were Ecstatic to See Their Roommate in a Dress', 'translated'), (...
class AcceptHeaderVersioning(BaseVersioning): invalid_version_message = _('Invalid version in "Accept" header.') def determine_version(self, request, *args, **kwargs): media_type = MediaType(request.accepted_media_type) version = media_type.params.get(self.version_param, self.default_version) ...
.django_db def test_award_count_cfo_agencies_only(client, monkeypatch, award_data, helpers, elasticsearch_award_index): setup_elasticsearch_test(monkeypatch, elasticsearch_award_index) helpers.mock_current_fiscal_year(monkeypatch) resp = client.get(url.format(filters='?group=cfo')) results = resp.data['...
def distance_matrix_new(target, leaf_only=False, topological=False): t = target.root real_outgroup = t.children[0] t.set_outgroup(target) n2dist = {target: 0} for n in target.get_descendants('preorder'): n2dist[n] = (n2dist[n.up] + (topological or n.dist)) sister = target.get_sisters()[0...
def _partial_quarterly_schedule_for_year(year): for quarter in range(1, 4): baker.make('submissions.DABSSubmissionWindowSchedule', is_quarter=True, submission_fiscal_year=year, submission_fiscal_quarter=quarter, submission_fiscal_month=(quarter * 3), submission_reveal_date=f'{year}-{(quarter * 3)}-15')
def test_caller_with_block_identifier(w3, math_contract): start_num = w3.eth.get_block('latest').number assert (math_contract.caller.counter() == 0) w3.provider.make_request(method='evm_mine', params=[5]) math_contract.functions.incrementCounter().transact() math_contract.functions.incrementCounter(...
class THBattleUTBootstrap(BootstrapAction): game: THBattle def __init__(self, params: Dict[(str, Any)], items: Dict[(Player, List[GameItem])], players: BatchList[Player]): self.source = self.target = None self.params = params self.items = items self.players = players def appl...
class OptionPlotoptionsBarSonificationDefaultinstrumentoptionsMappingTime(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 OptionSeriesScatter3dDataMarkerStatesSelect(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._conf...
class AssetBuildingTestRunner(DiscoverRunner): os.environ['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = '0.0.0.0:6080-6580' def build_suite(self, test_labels, extra_tests=None, **kwargs): if ((os.environ.get('TEST_SUITE', '') == 'functional') and (len(test_labels) == 0)): test_labels = ['frontend.tes...
def test_multi_stage_build_batch(): uid_generator = string_generator() request_info1 = dm.RequestInfo(input=np.array(range(10)), parameters={'gif_id': 12}) request_object1 = dm.RequestObject(uid=next(uid_generator), request_info=request_info1, source_id='internal_123_124', model=stub_model) request_info...
class Migration(migrations.Migration): dependencies = [('wagtailcore', '0030_index_on_pagerevision_created_at'), ('home', '0015_auto__0102')] operations = [migrations.CreateModel(name='FormField', fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('sort_o...
def test_container_error(): obj = errors.ContainerError('code', 'my message', errors.ContainerError.Kind.RECOVERABLE, execution.ExecutionError.ErrorKind.SYSTEM) assert (obj.code == 'code') assert (obj.message == 'my message') assert (obj.kind == errors.ContainerError.Kind.RECOVERABLE) assert (obj.or...
('cuda.grouped_fmha_style_b2b_bmm.func_call') def grouped_fmha_style_b2b_bmm_gen_function_call(func_attrs, indent=' '): assert (len(func_attrs['outputs']) == 1) assert (len(func_attrs['inputs']) in (3, 4)) output_name = func_attrs['outputs'][0]._attrs['name'] q_name = func_attrs['inputs'][0]._attrs['na...
def _split(ops: Ops, Xp: Padded) -> Tuple[(Padded, Padded)]: half = (Xp.data.shape[(- 1)] // 2) X_l2r = Xp.data[cast(Tuple[(slice, slice)], (..., slice(None, half)))] X_r2l = Xp.data[cast(Tuple[(slice, slice)], (..., slice(half)))] return (Padded(X_l2r, Xp.size_at_t, Xp.lengths, Xp.indices), Padded(X_r2...
class OptionSeriesPyramidAccessibility(Options): def description(self): return self._config_get(None) def description(self, text: str): self._config(text, js_type=False) def descriptionFormat(self): return self._config_get(None) def descriptionFormat(self, text: str): sel...
def get_security_info(esp, args): si = esp.get_security_info() print() title = 'Security Information:' print(title) print(('=' * len(title))) print('Flags: {:#010x} ({})'.format(si['flags'], bin(si['flags']))) print('Key Purposes: {}'.format(si['key_purposes'])) if ((si['chip_id'] is not...
class VersionTreeModel(QtGui.QStandardItemModel): def __init__(self, flat_view=False, *args, **kwargs): QtGui.QStandardItemModel.__init__(self, *args, **kwargs) logger.debug('VersionTreeModel.__init__() is started') self.root = None self.root_versions = [] self.reference_reso...
_oriented class SPHSolver(): method_WCSPH = 0 method_PCISPH = 1 method_DFSPH = 2 methods = {'WCSPH': method_WCSPH, 'PCISPH': method_PCISPH, 'DFSPH': method_DFSPH} material_fluid = 1 material_bound = 0 materials = {'fluid': material_fluid, 'bound': material_bound} def __init__(self, res, ...
class VPNApplicationBuilder(Builder): VPNs = {'express_vpn': {'macos': {'app': '/Applications/ExpressVPN.app'}, 'windows': {'app': windows_safe_path('C:\\Program Files (x86)\\ExpressVPN\\xvpn-ui\\ExpressVpn.exe'), 'tap': 'ExpressVPN Tap Adapter'}, 'linux': {'app': '/usr/bin/expressvpn'}}} def name(): re...
class OptionPlotoptionsSankeyLabelStyle(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._config(text...
def extractTrackingFeedpressIt(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_type) i...
class ExampleAutoSchemaDuplicate2(generics.GenericAPIView): serializer_class = ExampleSerializerModel schema = AutoSchema(component_name='Duplicate') def get(self, *args, **kwargs): from datetime import datetime now = datetime.now() serializer = self.get_serializer(data=now.date(), d...
class TestMacOSPacketCaptureConnectWhenNoNetwork(LocalPacketCaptureTestCase): def __init__(self, devices, config): super().__init__(devices, config) self.original_active_services = None def test(self): services = self.localhost['network_tool'].network_services_in_priority_order() ...
def test_setup_argparser(): log_file_path = 'any/given/path' args = setup_argparser('test', 'test description', command_line_options=['script_name', '--log_file', log_file_path, 'ANY_FILE']) assert (args.debug is False) assert (args.log_file == log_file_path) assert (args.log_level is None)
def setup_windows_console(): if ((not sys.platform.startswith('win')) or ('MSYSTEM' in os.environ) or ('CYGWIN' in os.environ)): return force_console = (('-v' in sys.argv) or ('--verbose' in sys.argv)) if ((not _create_or_attach_console(create=force_console, title='ElectrumSV Console')) and force_co...
class CyclopolisStation(BikeShareStation): def __init__(self, name, latitude, longitude, bikes, free, extra): super(CyclopolisStation, self).__init__() self.name = name self.latitude = latitude self.longitude = longitude self.bikes = bikes self.free = free sel...
def get_class(path: str) -> type: try: cls = _locate(path) if (not isinstance(cls, type)): raise ValueError((f"Located non-class of type '{type(cls).__name__}'" + f" while loading '{path}'")) return cls except Exception as e: log.error(f'Error getting class at {path}:...
def test_transformer_on_integer_variables(): df = pd.DataFrame({'var1': [0, 1, 0, 2, 3, 4, 5, 6, 8, 10], 'var2': [12, 11, 10, 15, 13, 12, 11, 10, 10, 20]}) dft = pd.DataFrame({'var1': {0: 0.0, 1: 0., 2: 0.0, 3: 1., 4: 1., 5: 2., 6: 2., 7: 2., 8: 3., 9: 3.}, 'var2': {0: 0., 1: 0., 2: 0., 3: 0., 4: 0., 5: 0., 6: ...
def serialize(A): if isinstance(A, str): return (0, A) if isinstance(A, numpy.ndarray): dt = A.dtype if ((not dt.isnative) or (dt.num < 1) or (dt.num >= len(dataType))): return (DATATYPE_UNKNOWN, None) ft = dataType[dt.num] if (ft == (- 1)): return...
class DiscountCode(SoftDeletionModel): __tablename__ = 'discount_codes' __table_args__ = (UniqueConstraint('event_id', 'code', 'deleted_at', name='uq_event_discount_code'),) id = db.Column(db.Integer, primary_key=True) code = db.Column(CIText, nullable=False) discount_url = db.Column(db.String) ...
def main(): segmk = Segmaker('design.bits') fuz_dir = os.getenv('FUZDIR', None) assert fuz_dir with open(os.path.join(fuz_dir, 'attrs.json'), 'r') as attr_file: attrs = json.load(attr_file) print('Loading tags') with open('params.json') as f: params = json.load(f) site = ...
def fortios_firewall_schedule(data, fos, check_mode): fos.do_member_operation('firewall.schedule', 'recurring') if data['firewall_schedule_recurring']: resp = firewall_schedule_recurring(data, fos, check_mode) else: fos._module.fail_json(msg=('missing task body: %s' % 'firewall_schedule_recu...
def test_rule_get_storage_destination_local(db: Session, policy: Policy, storage_config: StorageConfig, storage_config_default_local: StorageConfig) -> None: rule: Rule = policy.rules[0] rule_storage_config = rule.get_storage_destination(db) assert (rule_storage_config == storage_config) rule.storage_de...
class SSHCommandSessionTest(AsyncTestCase): def setUp(self) -> None: super().setUp() self.mock_options = {} self.mocks = MockService(self.mock_options, self._loop) test_device = self.mock_device('test-dev-1') self.devinfo = self._run_loop(self.mocks.device_db.get(test_device)...
.parametrize('ops', ALL_OPS) .parametrize('dtype', FLOAT_TYPES) def test_reduce_first(ops, dtype): X = ops.asarray2f([[1.0, 6.0], [2.0, 7.0], [3.0, 8.0], [4.0, 9.0], [5.0, 10.0]], dtype=dtype) lengths = ops.asarray1i([3, 2]) (Y, starts_ends) = ops.reduce_first(X, lengths) ops.xp.testing.assert_array_equ...
def create_post(board: BoardModel, thread: ThreadModel, post: PostModel, sage: bool) -> Tuple[(PostResultModel, int, int)]: start_time = now() with session() as s: post_orm_model = post.to_orm_model() s.add(post_orm_model) to_thread_orm_model = s.query(ThreadOrmModel).filter_by(id=thread...
def commit_changes(changes: t.List[str]) -> CommittedChanges: log.info('Committing updates') body: t.Optional[str] if (len(changes) > 1): subject = 'Update {} modules'.format(len(changes)) body = '\n'.join(changes) message = ((subject + '\n\n') + body) else: subject = cha...
_blueprint.route('/api/packages/wiki/') _blueprint.route('/api/packages/wiki') def api_packages_wiki_list(): project_objs = models.Project.all(Session) projects = [] for project in project_objs: for package in project.packages: tmp = f'* {package.package_name} {project.regex} {project.ve...
class OptionPlotoptionsBulletStatesSelect(Options): def animation(self) -> 'OptionPlotoptionsBulletStatesSelectAnimation': return self._config_sub_data('animation', OptionPlotoptionsBulletStatesSelectAnimation) def borderColor(self): return self._config_get('#000000') def borderColor(self, t...
def update(proj_dir): check_exists_with_error() if (not has_local_changes(proj_dir)): subprocess.call('git pull', cwd=proj_dir, shell=True) update_submodule(proj_dir) return True else: log.warn('skipping {}, uncommitted or unpushed changes!'.format(proj_dir)) return F...
class OptionPlotoptionsAreasplinerangeSonificationDefaultinstrumentoptionsMappingFrequency(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...
class FFmpegBackend(BaseEncodingBackend): name = 'FFmpeg' def __init__(self) -> None: self.params: List[str] = ['-threads', str(settings.VIDEO_ENCODING_THREADS), '-y', '-strict', '-2'] self.ffmpeg_path: str = getattr(settings, 'VIDEO_ENCODING_FFMPEG_PATH', which('ffmpeg')) self.ffprobe_p...
.parametrize('file_name, max_context', [('gsub_51', 2), ('gsub_52', 2), ('gsub_71', 1), ('gpos_91', 1)]) def test_max_ctx_calc_features_ttx(file_name, max_context): ttx_path = os.path.join(os.path.dirname(__file__), 'data', '{}.ttx'.format(file_name)) font = TTFont() font.importXML(ttx_path) assert (max...
class OptionPlotoptionsVariwideSonificationDefaultinstrumentoptionsMappingTime(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:...
(frozen=True) class ProductionChildInfo(): child_name: str production_name: str symbol: type symbol_optional: bool arity: ProductionChildArity annotation: Any def validate_child(self, child): def error(msg): raise GrammarError(msg) if (child is None): ...
def gen_dsps(): db = Database(util.get_db_root(), util.get_part()) grid = db.grid() for tile_name in sorted(grid.tiles()): loc = grid.loc_of_tilename(tile_name) gridinfo = grid.gridinfo_at_loc(loc) sites = [] for (site_name, site_type) in gridinfo.sites.items(): i...
class _PaletteTool(HasTraits): group = Any() def __init__(self, tool_palette, image_cache, item, show_labels): self.item = item self.tool_palette = tool_palette action = self.item.action label = action.name if (action.style == 'widget'): raise NotImplementedEr...
def _iter_avro_records(decoder, header, codec, writer_schema, named_schemas, reader_schema, options): sync_marker = header['sync'] read_block = BLOCK_READERS.get(codec) if (not read_block): raise ValueError(f'Unrecognized codec: {codec}') block_count = 0 while True: try: ...
class Trainer(): def __init__(self, model: Union[(PreTrainedModel, nn.Module)]=None, args: TrainingArguments=None, train_dataset: Dataset=None, eval_dataset: Optional[Dataset]=None): if (args is None): output_dir = 'tmp_trainer' logger.info(f'No `TrainingArguments` passed, using `out...
.parametrize('name,kwargs,in_data,out_data', TEST_CASES) def test_layers_from_config(name, kwargs, in_data, out_data): cfg = {'': name, **kwargs} filled_cfg = registry.fill({'config': cfg}) assert srsly.is_json_serializable(filled_cfg) model = registry.resolve({'config': cfg})['config'] if ('LSTM' i...
def extractDemonictofuWordpressCom(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 obtain_extract_partition_sql(config: dict, is_null_partition: bool=False) -> str: if (not config.get('optional_predicate')): config['optional_predicate'] = 'WHERE' else: config['optional_predicate'] += ' AND ' if is_null_partition: sql = EXTRACT_NULL_PARTITION_SQL else: ...
class TestImages(unittest.TestCase): def test_roundtrip_rgb8(self): arr = np.random.randint(0, 256, size=(240, 360, 3)).astype(np.uint8) msg = ros_numpy.msgify(Image, arr, encoding='rgb8') arr2 = ros_numpy.numpify(msg) np.testing.assert_equal(arr, arr2) def test_roundtrip_mono(se...
.skip_ci ('pyscf') def test_oniom3(): run_dict = {'geom': {'type': 'redund', 'fn': 'lib:oniom3alkyl.pdb'}, 'calc': {'type': 'oniom', 'calcs': {'real': {'type': 'pyscf', 'basis': 'sto3g', 'pal': 2}, 'mid': {'type': 'pyscf', 'basis': '321g', 'pal': 2}, 'high': {'type': 'pyscf', 'basis': '431g', 'pal': 2}}, 'models': ...
class AbstractCrudObject(AbstractObject): def __init__(self, fbid=None, parent_id=None, api=None): super(AbstractCrudObject, self).__init__() self._api = (api or FacebookAdsApi.get_default_api()) self._changes = {} if (parent_id is not None): warning_message = 'parent_id ...
.django_db def test_spending_over_time_funny_dates_ordering(client, monkeypatch, elasticsearch_transaction_index, populate_models): setup_elasticsearch_test(monkeypatch, elasticsearch_transaction_index) group = 'month' test_payload = {'group': group, 'subawards': False, 'filters': {'time_period': [{'start_d...
class OptionSeriesVariwideSonificationTracksMappingTime(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...
.network def test_pooch_logging_level(): with TemporaryDirectory() as local_store: path = Path(local_store) urls = {'tiny-data.txt': (BASEURL + 'tiny-data.txt')} pup = Pooch(path=path, base_url='', registry=REGISTRY, urls=urls) with capture_log('CRITICAL') as log_file: fn...
.unit class TestMergeCredentialsEnvironment(): (os.environ, {'FIDES__CREDENTIALS__POSTGRES_1__CONNECTION_STRING': 'postgresql+psycopg2://fides:env_variable.com:5439/fidesctl_test', 'FIDES__CREDENTIALS__AWS_ACCOUNT_1__REGION': 'us-east-1', 'FIDES__CREDENTIALS__AWS_ACCOUNT_1__ACCESS_KEY_ID': 'ACCESS_KEY_ID_1', 'FIDES...
def extractBujangtranslationWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('PCN', 'Pendekar Cambuk Naga', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous'...
def test_and_qualifier(alice, bob, my_logic): def _is_alice(connection, logic): assert isinstance(alice, ConnectionAPI) return (connection is alice) def _is_my_logic(connection, logic): assert isinstance(logic, LogicAPI) return (logic is my_logic) qualifier = AndQualifier(_is...
def chain_setup(w3): old_chain_id = remove_0x_prefix(to_hex(w3.eth.get_block(0)['hash'])) block_hash = remove_0x_prefix(to_hex(w3.eth.get_block('earliest').hash)) old_chain_uri = f'blockchain://{old_chain_id}/block/{block_hash}' match_data = {old_chain_uri: {'x': 'x'}, f'blockchain://1234/block/{block_h...
class TestGtLtMatchers(): def setup_method(self): self.str = get_search_result_track() def test_gt_bitrate_matcher_true(self): matcher = search._GtMatcher('__bitrate', 100000, (lambda x: x)) self.str.track.set_tag_raw('__bitrate', 128000) assert matcher.match(self.str) def te...
.unit def test_parse_manifest(): expected_result = models.DataCategory(organization_fides_key=1, fides_key='some_resource', name='Test resource 1', description='Test Description') test_dict = {'organization_fides_key': 1, 'fides_key': 'some_resource', 'name': 'Test resource 1', 'description': 'Test Description'...
def simulate_calls_with_limiter(num_calls: int, rate_limit_requests: List[RateLimiterRequest]) -> Dict: limiter: RateLimiter = RateLimiter() call_log = {} for _ in range(num_calls): limiter.limit(requests=rate_limit_requests) current_time = int(time.time()) count = call_log.get(curre...
class OptionSeriesXrangeSonificationDefaultspeechoptionsMappingRate(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 TestMatcher(): def setup_method(self): self.strack = get_search_result_track() self.strack.track.set_tag_raw('artist', ['foo', 'bar']) (search._Matcher, '_matches', return_value=True) def test_match_list_true(self, mock_method): matcher = search._Matcher('artist', 'bar', (lambd...
def init_db(): global _scoped_session global _session_cls global _engine global OrmModelBase _engine = create_engine(connect_string(), pool_size=config.database_pool_size, echo=config.database_echo_sql) _session_cls = sessionmaker(autocommit=False, autoflush=False, bind=_engine) _scoped_sess...
class ScheduleTimeColumn(Column): name = 'schedule_time' display = _('Schedule') size = 80 def __init__(self, *args): Column.__init__(self, *args) self.timeout_id = None event.add_ui_callback(self.on_queue_current_playlist_changed, 'queue_current_playlist_changed', player.QUEUE) ...
class CashFlowStatement(DocType): id = Keyword() securityId = Keyword() code = Keyword() reportPeriod = Date() timestamp = Date() reportEventDate = Date() cashFromSellingCommoditiesOrOfferingLabor = Float() refundOfTaxAndFeeReceived = Float() cashReceivedRelatingToOtherOperatingActiv...
.parametrize('is_admin', [True, False]) def test_user_create_success(dashboard_user, session, is_admin): username = str(uuid.uuid4()) password = str(uuid.uuid4()) response = dashboard_user.post('dashboard/api/user/create', data={'username': username, 'password': password, 'password2': password, 'is_admin': ...
class TestFunctions(): def test_func_default_return_null(self): assert (evalpy('def foo():pass\nprint(foo(), 1)') == 'null 1') assert (evalpy('def foo():return\nprint(foo(), 1)') == 'null 1') def test_func_call_compilation(self): assert (py2js('foo()') == 'foo();') assert (py2js(...
(scope='function') def create_test_repo(create_test_db): data = dict() data['repo1'] = Repository(name='Test Repo 1', code='TR1', linux_path='/test/repo/1/linux/path', windows_path='T:/test/repo/1/windows/path', osx_path='/test/repo/1/osx/path') data['repo2'] = Repository(name='Test Repo 2', code='TR2', lin...
class TestWifiOffWifi(MultimachineTestCase): def test(self): L.describe('Open and connect the VPN application') self.target_device['vpn_application'].open_and_connect() L.describe('Capture traffic') self.capture_device['packet_capturer'].start() L.describe('Generate whatever ...
class AbstractTeiTrainingDataGenerator(TeiTrainingDataGenerator): def __init__(self, root_training_xml_element_path: Sequence[str], training_xml_element_path_by_label: Mapping[(str, Sequence[str])], root_tag: str='tei', use_tei_namespace: bool=True, element_maker: Optional[ElementMaker]=None, reset_training_xml_ele...
def password(v): if ((v == '\n') or (v == ' ')): return 'Password cannot be a newline or space!' if (9 <= len(v) <= 20): if re.search('(.)\\1\\1', v): return 'Weak Password: Same character repeats three or more times in a row' if re.search('(..)(.*?)\\1', v): retu...
def build_integrations_manifest(overwrite: bool, rule_integrations: list=[], integration: str=None) -> None: def write_manifests(integrations: dict) -> None: manifest_file = gzip.open(MANIFEST_FILE_PATH, 'w+') manifest_file_bytes = json.dumps(integrations).encode('utf-8') manifest_file.write...
class TestTrack(): def test_finds_default_challenge(self): default_challenge = track.Challenge('default', description='default challenge', default=True) another_challenge = track.Challenge('other', description='non-default challenge', default=False) assert (default_challenge == track.Track(n...
def upgrade(): op.execute('COMMIT') try: op.execute('SHOW bdr.permit_ddl_locking') op.execute('SET LOCAL bdr.permit_ddl_locking = true') except exc.ProgrammingError: pass op.execute("UPDATE updates SET request = 'stable' WHERE request = 'batched'") op.execute('ALTER TYPE ck_u...
class ForumSerializerss(serializers.ModelSerializer): authors = UserSerializer(read_only=True) category = Forum_plateSerializers(read_only=True) comment_set = CommentSerializers(many=True) add_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', required=False, read_only=True) class Meta(): ...