code
stringlengths
281
23.7M
def test_invalid_type(client): resp = client.get(url.format(toptier_code='043', fiscal_year=2020, fiscal_period=8, type='procurementS')) assert (resp.status_code == status.HTTP_400_BAD_REQUEST) response = resp.json() detail = response['detail'] assert (detail == "Field 'type' is outside valid values...
class Function_Signature(Node): def __init__(self): super().__init__() self.n_name = None self.l_inputs = None self.l_outputs = None self.is_constructor = False def loc(self): if self.n_name: return self.n_name.loc() else: raise ICE...
_arg_type(1) def apply_formatters_to_sequence(formatters: List[Any], sequence: List[Any]) -> Generator[(List[Any], None, None)]: if (len(formatters) > len(sequence)): raise IndexError(f'Too many formatters for sequence: {len(formatters)} formatters for {repr(sequence)}') elif (len(formatters) < len(sequ...
_os(*metadata.platforms) (TARGET_APP, common.CMD_PATH) def main(): common.log('Execute files from the Recycle Bin') target_dir = None for recycle_path in RECYCLE_PATHS: if Path(recycle_path).exists(): target_dir = common.find_writeable_directory(recycle_path) if target_dir: ...
class SimsetMixin(MixinMeta): _or_permissions(manage_guild=True) (autohelp=True) async def simset(self, ctx): if (ctx.invoked_subcommand is not None): return guild = ctx.guild gametime = (await self.config.guild(guild).gametime()) htbreak = (await self.config.guil...
def except_handle(tokens): if (len(tokens) == 2): (except_kwd, errs) = tokens asname = None elif (len(tokens) == 3): (except_kwd, errs, asname) = tokens else: raise CoconutInternalException('invalid except tokens', tokens) out = (except_kwd + ' ') if ('list' in tokens...
def uses_ancestry(query): from . import ast if isinstance(query, ast.EqlAnalytic): query = query.query elif (not isinstance(query, ast.EqlNode)): raise TypeError('unsupported type {} to eql.utils.uses_ancestry. Expected {}'.format(type(query), ast.EqlNode)) return any((isinstance(node, a...
def extractWwwVeratalesCom(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) in ta...
.network .skipif((paramiko is None), reason='requires paramiko to run SFTP') def test_sftp_downloader_fail_if_file_object(): with TemporaryDirectory() as local_store: downloader = SFTPDownloader(username='demo', password='password') url = 'sftp://test.rebex.net/pub/example/pocketftp.png' out...
class OptionSeriesBarSonificationTracksMappingLowpass(Options): def frequency(self) -> 'OptionSeriesBarSonificationTracksMappingLowpassFrequency': return self._config_sub_data('frequency', OptionSeriesBarSonificationTracksMappingLowpassFrequency) def resonance(self) -> 'OptionSeriesBarSonificationTracks...
def as_completed(jobs: tp.Sequence[core.Job[core.R]], timeout: tp.Optional[tp.Union[(int, float)]]=None, poll_frequency: float=10) -> tp.Iterator[core.Job[core.R]]: start = time.time() jobs_done: tp.Set[int] = set() while True: if ((timeout is not None) and ((time.time() - start) > timeout)): ...
def test_source_on_clone(): assert ({'_source': {'includes': ['foo.bar.*'], 'excludes': ['foo.one']}, 'query': {'bool': {'filter': [{'term': {'title': 'python'}}]}}} == search.Search().source(includes=['foo.bar.*']).source(excludes=['foo.one']).filter('term', title='python').to_dict()) assert ({'_source': False...
class _RegData(): def __init__(self, rmap): self._rmap = rmap def fifo(self): rdata = self._rmap._if.read(self._rmap.DATA_ADDR) return ((rdata >> self._rmap.DATA_FIFO_POS) & self._rmap.DATA_FIFO_MSK) def fifo(self, val): rdata = self._rmap._if.read(self._rmap.DATA_ADDR) ...
class AdgroupReviewFeedback(AbstractObject): def __init__(self, api=None): super(AdgroupReviewFeedback, self).__init__() self._isAdgroupReviewFeedback = True self._api = api class Field(AbstractObject.Field): field_global = 'global' placement_specific = 'placement_specifi...
def test_create_default_project_workspace_mel_already_exists(create_test_data, trash_bin): data = create_test_data arch = Archiver() tempdir = tempfile.gettempdir() project_path = arch.create_default_project(tempdir) trash_bin.append(project_path) project_path = arch.create_default_project(tempd...
def test_multichannel_containers(audio, nb_channels, multichannel_format): with tmp.NamedTemporaryFile(delete=False, suffix=('.' + multichannel_format)) as tempfile: stempeg.write_stems(tempfile.name, audio, sample_rate=44100, writer=ChannelsWriter()) (loaded_audio, rate) = stempeg.read_stems(tempfi...
class ApertureSetLever(): def __init__(self, exposure_control_system=None, aperture=16): self.exposure_control_system = exposure_control_system self._aperture = aperture def aperture(self): return self._aperture def aperture(self, value): if (self.exposure_control_system.mode...
class TriggerWordsPresence(FeatureDescriptor): words_list: Tuple lemmatize: bool = True def feature(self, column_name: str) -> GeneratedFeature: return trigger_words_presence_feature.TriggerWordsPresent(column_name, self.words_list, self.lemmatize, self.display_name) def for_column(self, column_...
class OptionSeriesBellcurveSonificationDefaultinstrumentoptionsMappingPan(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)...
('/callers/manage/<int:call_no>', methods=['GET', 'POST']) def callers_manage(call_no): post_count = None if (request.method == 'POST'): number = transform_number(request.form['phone_no']) if (request.form['action'] == 'add-permit'): caller = {} caller['NMBR'] = number ...
class OptionPlotoptionsArcdiagramSonificationDefaultinstrumentoptionsMappingTime(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, tex...
def bitwise_sar(evm: Evm) -> None: shift = pop(evm.stack) signed_value = pop(evm.stack).to_signed() charge_gas(evm, GAS_VERY_LOW) if (shift < 256): result = U256.from_signed((signed_value >> shift)) elif (signed_value >= 0): result = U256(0) else: result = U256.MAX_VALUE ...
def test_deepcopy_overridden(): provider = providers.Self() overriding_provider = providers.Provider() provider.override(overriding_provider) provider_copy = providers.deepcopy(provider) overriding_provider_copy = provider_copy.overridden[0] assert (provider is not provider_copy) assert isin...
def parse_production_per_units(xml_text: str) -> (Any | None): values = {} if (not xml_text): return None soup = BeautifulSoup(xml_text, 'html.parser') for timeseries in soup.find_all('timeseries'): resolution = str(timeseries.find_all('resolution')[0].contents[0]) datetime_start...
class NameSpace(dict): _pscript_overload = True def set_nonlocal(self, key): self[key] = 2 def set_global(self, key): self[key] = 3 def use(self, key, how): hows = self.setdefault(key, set()) if isinstance(hows, set): hows.add(how) def add(self, key): ...
class TestDataAvailabilityBasedNotificationRuleOnEgress(): def test_data_availability_north(self, check_eds_installed, reset_fledge, start_notification, reset_eds, start_north, fledge_url, wait_time, skip_verify_north_interface, add_south, retries): put_url = '/fledge/category/ruletest #1' data = {'...
class TestLightSettingsEncoder(): def _check_light_settings(self, light_settings): with pytest.raises(ValueError) as excinfo: check_encoding(messaging.Message(topic='topic', android=messaging.AndroidConfig(notification=messaging.AndroidNotification(light_settings=light_settings)))) retur...
class ResourceUtilTest(ForsetiTestCase): def test_create_resource_is_ok(self): expect_org = Organization(12345) actual_org = resource_util.create_resource(12345, ResourceType.ORGANIZATION) self.assertEqual(expect_org, actual_org) expect_proj = Project('abcd', project_number=54321) ...
class ClassificationDummyMetricResults(MetricResult): class Config(): dict_exclude_fields = {'metrics_matrix'} pd_exclude_fields = {'metrics_matrix'} dummy: DatasetClassificationQuality by_reference_dummy: Optional[DatasetClassificationQuality] model_quality: Optional[DatasetClassificati...
(scope='function') def fullstory_postgres_db(postgres_integration_session): postgres_integration_session = seed_postgres_data(postgres_integration_session, './tests/fixtures/saas/external_datasets/fullstory.sql') (yield postgres_integration_session) drop_database(postgres_integration_session.bind.url)
class TestControllerGenerator(): def controller(self): controller = copy.deepcopy(ControllerGenerator) copier_patch = mock.patch('fastapi_mvc.generators.controller.copier') insert_patch = mock.patch('fastapi_mvc.generators.controller.insert_router_import') controller.copier = copier_...
def test_receipt_processing_with_ignore_flag(event_contract, indexed_event_contract, dup_txn_receipt, wait_for_transaction): event_instance = indexed_event_contract.events.LogSingleWithIndex() returned_logs = event_instance.process_receipt(dup_txn_receipt, errors=IGNORE) assert (len(returned_logs) == 2) ...
.parametrize('content,expected', (('a', [{'body': (['a'], 0)}]), ('---\na', [{'body': (['a'], 1)}]), ('a\n^^^', [{'body': ([], 2), 'header': (['a'], 0)}]), ('a\n+++', [{'body': (['a'], 0), 'footer': ([], 1)}]), ('a\n^^^\nb\n+++\nc', [{'body': (['b'], 2), 'footer': (['c'], 3), 'header': (['a'], 0)}]), ('---\n:card: a', ...
class TestMd5sums(unittest.TestCase): def setUp(self): self.dir = ExampleDirScooby() self.dir.create_directory() self.md5sum_dir = tempfile.mkdtemp() self.checksum_file = os.path.join(self.md5sum_dir, 'checksums') self.reference_checksums = [] for f in self.dir.fileli...
class HeterodoxyAction(UserAction): def apply_action(self): g = self.game sk = self.associated_card assert isinstance(sk, Heterodoxy) card = sk.associated_cards[0] src = self.source victim = self.target tgts = self.target_list[1:] g.players.reveal(card...
def _flag_level(name: str, default=None): level = uuid4() LEVEL_FLAGS[name] = LEVEL_FLAGS.get(name, _LevelFlag(default)) level_flag = LEVEL_FLAGS[name] level_flag.levels.append(level) if (default != level_flag.default): raise FalArgsError(f"Different defaults '{default}' and '{level_flag.def...
class MetadataServerTest(ForsetiTestCase): .object( 'request', autospec=True) def test_issue_ mock_req): mock_req.side_effect = _MockHttpError('Unreachable') with self.assertRaises(errors.MetadataServerHttpError): metadata_server._issue_ '', {}) def test_obtain_ returned_...
def test_multi_index_slicing_block_single(): mask = torch.rand([2, 1, 4]) in_shape = (mask.shape[(- 1)],) select_block = MultiIndexSlicingBlock(in_keys='mask', out_keys='selected', in_shapes=in_shape, select_dim=(- 1), select_idxs=[0]) selected = select_block({'mask': mask}) assert (selected['select...
def test_longitude_continuity(): longitude_360 = np.linspace(0, 350, 36) longitude_180 = np.hstack((longitude_360[:18], (longitude_360[18:] - 360))) latitude = np.linspace((- 90), 90, 36) (s, n) = ((- 90), 90) (w, e) = (10.5, 20.3) for longitude in [longitude_360, longitude_180]: coordin...
def test_reset_settings(): default = 'parse' non_default = 'raw' try: settings = Settings(organization='normcap_TEST') settings.setValue('mode', non_default) assert (settings.value('mode') == non_default) settings.reset() assert (settings.value('mode') == default) ...
class cached_property(): def __init__(self, func: Callable) -> None: self.func = func self.attrname = None self.__doc__ = func.__doc__ self.lock = RLock() def __set_name__(self, _: Any, name: Any) -> None: if (self.attrname is None): self.attrname = name ...
def user_remove_moderator(moderator: ModeratorModel, board: BoardModel, username: str): member = find_moderator_username(username) if (not member): raise ArgumentError('Moderator not found') if has_any_of_board_roles(member, board, [roles.BOARD_ROLE_CREATOR]): raise ArgumentError('Cannot rem...
class VRRPStatistics(object): def __init__(self, name, resource_id, statistics_interval): self.name = name self.resource_id = resource_id self.statistics_interval = statistics_interval self.tx_vrrp_packets = 0 self.rx_vrrp_packets = 0 self.rx_vrrp_zero_prio_packets = ...
class RejectRequestsWithEscapedSlashesDisabled(AmbassadorTest): target: ServiceType def init(self): self.target = HTTPBin() def config(self) -> Generator[(Union[(str, Tuple[(Node, str)])], None, None)]: (yield (self, self.format('\n---\napiVersion: getambassador.io/v3alpha1\nkind: Mapping\nn...
def typeof(obj): if isinstance(obj, _simple_types): return type(obj) if isinstance(obj, tuple): return Tuple[tuple((typeof(elem) for elem in obj))] if (isinstance(obj, (list, dict, set)) and (not obj)): raise ValueError(f'Cannot determine the full type of an empty {type(obj)}') i...
def test_chaindb_get_score(chaindb): genesis = BlockHeader(difficulty=1, block_number=0, gas_limit=0) chaindb.persist_header(genesis) genesis_score_key = SchemaV1.make_block_hash_to_score_lookup_key(genesis.hash) genesis_score = rlp.decode(chaindb.db.get(genesis_score_key), sedes=rlp.sedes.big_endian_in...
(IDialog) class Dialog(MDialog, Window): cancel_label = Str() help_id = Str() help_label = Str() ok_label = Str() resizeable = Bool(True) return_code = Int(OK) style = Enum('modal', 'nonmodal') title = Str('Dialog') _connections_to_remove = List(Tuple(Any, Callable)) def _create_...
def _ocr_tables_standarize_cell(cell) -> Cell: is_header = ('COLUMN_HEADER' in cell.entityTypes) return Cell(text=cell.mergedText, row_index=cell.columnIndex, col_index=cell.rowIndex, row_span=cell.rowSpan, col_span=cell.columnSpan, confidence=cell.confidence, is_header=is_header, bounding_box=BoundixBoxOCRTabl...
class TestColumnValueMean(BaseFeatureDataQualityMetricsTest): name: ClassVar = 'Mean Value' def get_stat(self, current: NumericCharacteristics): return current.mean def get_condition_from_reference(self, reference: Optional[ColumnCharacteristics]) -> TestValueCondition: if (reference is not ...
class TestMap8(_MapTest): map_data = {'map': MAP8, 'zcoord': 'map8'} map_display = MAP8_DISPLAY def test_str_output(self): stripped_map = '\n'.join((line.rstrip() for line in str(self.map).split('\n'))) self.assertEqual(MAP8_DISPLAY, stripped_map.replace('||', '|')) ([((2, 0), (2, 2), ('...
_required _required _required def dc_node_list(request): context = collect_view_data(request, 'dc_node_list', mb_addon=SIZE_FIELD_MB_ADDON) context['can_edit'] = can_edit = request.user.is_staff context['all'] = _all = (can_edit and request.GET.get('all', False)) context['qs'] = get_query_string(request...
.django_db def test_contract_pricing(award_data_fixture, elasticsearch_award_index): elasticsearch_award_index.update_index() should = {'match': {'type_of_contract_pricing.keyword': '2'}} query = create_query(should) client = elasticsearch_award_index.client response = client.search(index=elasticsea...
class NullableUUIDForeignKeySourceSerializer(serializers.ModelSerializer): target = serializers.PrimaryKeyRelatedField(pk_field=serializers.UUIDField(), queryset=UUIDForeignKeyTarget.objects.all(), allow_null=True) class Meta(): model = NullableUUIDForeignKeySource fields = ('id', 'name', 'targe...
def get_stattest(reference_data: SparkSeries, current_data: SparkSeries, feature_type: Union[(ColumnType, str)], stattest_func: Optional[PossibleStatTestType]) -> StatTest: if isinstance(feature_type, str): feature_type = ColumnType(feature_type) if (stattest_func is None): return _get_default_s...
class LegacyWafRule(ModelNormal): allowed_values = {} validations = {} _property def additional_properties_type(): return (bool, date, datetime, dict, float, int, list, str, none_type) _nullable = False _property def openapi_types(): return {'message': (str,), 'rule_id': (str...
class BaseInfoTarget(): def __init__(self, data_key: str, col: str): self.data_key = data_key self.col = col def calculate(self, data, index: pd.DataFrame) -> pd.DataFrame: base_df = data[self.data_key].load(index['ticker'].values)[['ticker', self.col]] result = pd.merge(index, b...
def profile_callable(func: Callable, cache_flush_slab: torch.Tensor, n_iter: int) -> Tuple[(List[int], List[int])]: if (n_iter <= 0): return ([], []) for _ in range(5): func() with torch.profiler.profile(activities=[torch.profiler.ProfilerActivity.CUDA], record_shapes=True) as prof: ...
class _CoreManager(Activity): def __init__(self): self._common_conf = None self._neighbors_conf = None self._vrfs_conf = None self._core_service = None super(_CoreManager, self).__init__() def _run(self, *args, **kwargs): self._common_conf = kwargs.pop('common_con...
def extractAvert(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if (not (vol or chp or frag)): return False if ('rokujouma' in item['title'].lower()): return buildReleaseMessageWithType(item, 'Rokujouma no Shinryakusha!', vol, chp, frag=frag, postfix=postf...
class op(bpy.types.Operator): bl_idname = 'uv.textools_stitch' bl_label = 'Stitch' bl_description = 'Stitch other Islands to the selection' bl_options = {'REGISTER', 'UNDO'} def poll(cls, context): if (bpy.context.area.ui_type != 'UV'): return False if (not bpy.context.ac...
class SelectFwdSingle(GroupTest): def runTest(self): (port1, port2) = openflow_ports(2) msg = ofp.message.group_add(group_type=ofp.OFPGT_SELECT, group_id=1, buckets=[create_bucket(weight=1, actions=[ofp.action.output(port2)])]) self.controller.message_send(msg) do_barrier(self.contro...
class Migration(migrations.Migration): dependencies = [('forum', '0010_auto__1401')] operations = [migrations.AlterField(model_name='forum', name='level', field=models.PositiveIntegerField(editable=False)), migrations.AlterField(model_name='forum', name='lft', field=models.PositiveIntegerField(editable=False)),...
def load_video_transcript(url, audio_url, page_id='', data_folder='', run_id='', audio2text=True, enable_cache=True): loader = LLMYoutubeLoader() transcript_langs = os.getenv('YOUTUBE_TRANSCRIPT_LANGS', 'en') langs = transcript_langs.split(',') print(f'Loading Youtube transcript, supported language list...
class BatchResponse(): def __init__(self, responses): self._responses = responses self._success_count = len([resp for resp in responses if resp.success]) def responses(self): return self._responses def success_count(self): return self._success_count def failure_count(self...
_stats_type() _set_stats_type(ofproto.OFPMP_TABLE_FEATURES, OFPTableFeaturesStats) _set_msg_type(ofproto.OFPT_MULTIPART_REPLY) class OFPTableFeaturesStatsReply(OFPMultipartReply): def __init__(self, datapath, type_=None, **kwargs): super(OFPTableFeaturesStatsReply, self).__init__(datapath, **kwargs)
class Solution(): def findBall(self, grid: List[List[int]]) -> List[int]: (m, n) = (len(grid), len(grid[0])) def check(row, col): if (row == m): return col new_col = (col + grid[row][col]) if ((new_col == n) or (new_col == (- 1)) or (grid[row][new_...
def test_example_app(tmpdir: Path) -> None: cmd = ['example/banana.py', '-m', ('hydra.run.dir=' + str(tmpdir)), 'hydra.job.chdir=True', 'banana.x=int(interval(-5, 5))', 'banana.y=interval(-5, 10.1)', 'hydra.sweeper.ax_config.max_trials=2'] (result, _) = run_python_script(cmd) assert ('banana.x: range=[-5, 5...
class ResetAllPerspectivesAction(WorkbenchAction): id = 'pyface.workbench.action.reset_all_perspectives' name = 'Reset All Perspectives' def perform(self, event): window = self.window if (window.confirm(MESSAGE) == YES): window.reset_all_perspectives() return
class Serializable(ABC): serializer: 'Serializer' = None def to_dict(self) -> Dict: def serialize(self) -> bytes: if (self.serializer is None): raise ValueError('Serializer is not set. Please set the serializer before serialization.') return self.serializer.serialize(self) de...
class OptionSeriesColumnSonificationDefaultspeechoptionsMappingPlaydelay(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 convert_composable_query_to_string(sql, model=Award, cursor=None): if isinstance(sql, Composable): if (cursor is None): connection = get_connection(model) with connection.cursor() as _cursor: return sql.as_string(_cursor.connection) else: retur...
_module() class NaiveSVCDataset(NaiveDataset): processing_pipeline = [dict(type='PickKeys', keys=['path', 'time_stretch', 'mel', 'contents', 'pitches', 'key_shift', 'speaker']), dict(type='Transpose', keys=[('mel', 1, 0), ('contents', 1, 0)])] collating_pipeline = [dict(type='ListToDict'), dict(type='PadStack',...
def embedding_attention_decoder(decoder_inputs, initial_state, attention_states, cell, num_symbols, embedding_size, num_heads=1, output_size=None, output_projection=None, feed_previous=False, update_embedding_for_previous=True, dtype=tf.float32, scope=None, initial_state_attention=False, attn_num_hidden=128): if (o...
class OptionPlotoptionsPyramidSonificationContexttracksMappingRate(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 WarProcessor(AbstractGamestateDataProcessor): ID = 'wars' DEPENDENCIES = [RulerEventProcessor.ID, CountryProcessor.ID, SystemProcessor.ID, PlanetProcessor.ID] def __init__(self): super().__init__() self._ruler_dict = None self._countries_dict = None self._system_models_...
class OptionSeriesBubbleSonificationDefaultinstrumentoptionsMappingPan(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 prepare_fixed_decimal(data, schema): if (not isinstance(data, decimal.Decimal)): return data scale = schema.get('scale', 0) size = schema['size'] precision = schema['precision'] (sign, digits, exp) = data.as_tuple() if (len(digits) > precision): raise ValueError('The decimal ...
def test_import_objects_DuplicateObject(raw_user): expected_sid = 'S-1-5-21----500' expected_dn = 'CN=ADMINISTRATOR,CN=USERS,DC=TEST,DC=LAB' adds = ADDS() adds.import_objects([raw_user, raw_user]) sid_map_object = adds.SID_MAP[expected_sid] dn_map_object = adds.DN_MAP[expected_dn] assert (le...
def prepare_experiment_dir(experiment_dir, cfg, rank): config_path = osp.join(experiment_dir, 'config.yaml') last_checkpoint_path = find_last_checkpoint_path(experiment_dir) if (last_checkpoint_path is not None): if (rank == 0): logger.info('Resuming the training from checkpoint %s', las...
def test_try_extract_random_fail(): for fp in glob.glob(str((TEST_DATA_DIR / 'random_invalid/*.image'))): test_file = FileObject(file_path=fp) test_file.processed_analysis['file_type'] = {'result': {'mime': 'application/octet-stream'}} test_file.processed_analysis['software_components'] = {'...
def format_capacity(df: pd.DataFrame, target_datetime: datetime) -> dict[(str, Any)]: df = df.copy() df = df.loc[(df['statusDescription'] == 'Operating')] df['mode'] = df['technology'].map(TECHNOLOGY_TO_MODE) df_aggregated = df.groupby(['mode'])[['nameplate-capacity-mw']].sum().reset_index() capacit...
class Migration(migrations.Migration): dependencies = [('references', '0045_disasteremergencyfundcode_url')] operations = [migrations.CreateModel(name='GTASSF133Balances', fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('fiscal_year', models.IntegerFie...
class BaseSkillTestCase(): path_to_skill: Path = Path('.') is_agent_to_agent_messages: bool = True _skill: Skill _multiplexer: AsyncMultiplexer _outbox: OutBox def skill(self) -> Skill: try: value = self._skill except AttributeError: raise ValueError('Ensu...
class NetworkDiscoveryDialog(QDialog, threading.Thread): TIMEOUT = 0.1 display_clear_signal = Signal() display_append_signal = Signal(str) status_text_signal = Signal(str) network_join_request = Signal(int) def __init__(self, default_mcast_group, default_port, networks_count, parent=None): ...
def get_args(): parser = argparse.ArgumentParser('Debin to hack binaries. This script is used to train CRF model with Nice2Predict. Make sure you have enough disk space.') parser.add_argument('--bin_list', dest='bin_list', type=str, required=True, help='list of binaries to train.') parser.add_argument('--bi...
def _assemble_and_send_email(location_slug, post): location = get_object_or_404(Location, slug=location_slug) subject = post.get('subject') recipient = [post.get('recipient')] body = ((post.get('body') + '\n\n') + post.get('footer')) send_from_location_address(subject, body, None, recipient, locatio...
class PatchEncoder(fl.Chain): def __init__(self, in_channels: int=3, dim: int=128, patch_size: int=16) -> None: self.in_channels = in_channels self.dim = dim self.patch_size = patch_size super().__init__(fl.Conv2d(in_channels=in_channels, out_channels=dim, kernel_size=patch_size, str...
class TimestampAligner(Aligner): def __init__(self, lag: float) -> None: self._pq: Optional[TimestampedHeap] = None self.lag: float = lag self.callbacks: Dict[(str, List[LabgraphCallback])] = collections.defaultdict(list) self.active: bool = True self.terminate: bool = False ...
_api.route((api_url + 'uploads/'), methods=['GET']) _api.route((api_url + 'uploads/<int:page>/'), methods=['GET']) _auth.login_required def get_uploads(page=1): uploads = FlicketUploads.query per_page = min(request.args.get('per_page', app.config['posts_per_page'], type=int), 100) data = FlicketUploads.to_c...
class OptionPlotoptionsTilemapSonificationContexttracksMappingRate(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): ...
('config_name,overrides,expected', [param('with_missing', [], DefaultsTreeNode(node=ConfigDefault(path='with_missing'), children=[GroupDefault(group='db', value='???'), ConfigDefault(path='_self_')]), id='with_missing')]) def test_with_missing_and_skip_missing_flag(config_name: str, overrides: List[str], expected: Defa...
def run_pylint(file_path): pylint_process = subprocess.run(f'pylint --output-format=json {file_path}', shell=True, stdout=PIPE, stderr=STDOUT, check=False, text=True) try: pylint_json = json.loads(pylint_process.stdout) except json.JSONDecodeError: logging.warning(f'''Failed to execute pylin...
class TestAdaptationOffer(unittest.TestCase): def test_lazy_loading(self): LAZY_EXAMPLES = 'traits.adaptation.tests.lazy_examples' if (LAZY_EXAMPLES in sys.modules): del sys.modules[LAZY_EXAMPLES] offer = AdaptationOffer(factory=(LAZY_EXAMPLES + '.IBarToIFoo'), from_protocol=(LAZ...
def convert_theme(value, level=3): if (not isinstance(value, str)): return value if ((value[:1] == '') and (value.find(':') >= 2)): try: from .image.image import ImageLibrary info = ImageLibrary.image_info(value) except: info = None if (info is...
def _get_all_summuries(root_log_dir: str): summary_dir = os.path.join(root_log_dir, 'summaries') summary_names = [] if os.path.exists(summary_dir): filenames = os.listdir(summary_dir) for filename in filenames: if filename.endswith('.summary'): summary_names.appen...
def _capture_task_logs(): root_logger = logging.getLogger() root_logger.setLevel(logger.level) root_logger.handlers[:] = logger.handlers info_writer = StreamLogWriter(logger, logging.INFO) warning_writer = StreamLogWriter(logger, logging.WARNING) with redirect_stdout(info_writer), redirect_stder...
class ExecutionSpec(_common_models.FlyteIdlEntity): def __init__(self, launch_plan, metadata, notifications=None, disable_all=None, labels=None, annotations=None, auth_role=None, raw_output_data_config=None, max_parallelism: Optional[int]=None, security_context: Optional[security.SecurityContext]=None, overwrite_ca...
def get_trees_from_file(filename, fileobject=None): fileobject = (fileobject or open(filename, 'rb')) trees = [] def extend(btext, fname): name = os.path.splitext(os.path.basename(fname))[0] trees.extend(get_trees_from_nexus_or_newick(btext, name)) if filename.endswith('.zip'): z...
class TestPlayable(TestIntegrationBase): module = player def setUp(self): super(TestPlayable, self).setUp() self.manager = self.manager_module.MimetypeActionPluginManager(self.app) self.manager.register_mimetype_function(self.player_module.detect_playable_mimetype) def test_playablef...
class Workspace(UUIDModel, CreatedUpdatedAt, MainBase): __tablename__ = 'workspaces' name: Mapped[str] = mapped_column(String(length=255), nullable=False) domain: Mapped[str] = mapped_column(String(length=255), nullable=False) database_type: Mapped[(DatabaseType | None)] = mapped_column(Enum(DatabaseTyp...