code
stringlengths
281
23.7M
def test_caption_truncation(channel, bot_admin, image): msg_body = ''.join((random.choice(string.ascii_letters) for _ in range(100000))) with patch('telegram.Bot.send_document') as mock_send_document: message = channel.bot_manager.send_photo(bot_admin, image, caption=msg_body, prefix='Prefix') a...
class OptionSeriesBarSonificationTracksMappingVolume(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._confi...
def kinetic3d_40(ax, da, A, bx, db, B): result = numpy.zeros((15, 1), dtype=float) x0 = (2.0 * ax) x1 = (((2.0 * bx) + x0) ** (- 1.0)) x2 = ((ax + bx) ** (- 1.0)) x3 = ((x2 * ((ax * A[0]) + (bx * B[0]))) - A[0]) x4 = (- ax) x5 = (x3 ** 2) x6 = (2.0 * (ax ** 2)) x7 = ((- x4) - (x6 * (...
def nlms(x, d, N=4, mu=0.1): nIters = (min(len(x), len(d)) - N) u = np.zeros(N) w = np.zeros(N) e = np.zeros(nIters) for n in range(nIters): u[1:] = u[:(- 1)] u[0] = x[n] e_n = (d[n] - np.dot(u, w)) w = (w + (((mu * e_n) * u) / (np.dot(u, u) + 0.001))) e[n] = ...
class TestScoreEntropy(BaseCheckValueTest): group: ClassVar = RECSYS_GROUP.id name: ClassVar = 'Score Entropy (top-k)' k: int _metric: ScoreDistribution def __init__(self, k: int, eq: Optional[Numeric]=None, gt: Optional[Numeric]=None, gte: Optional[Numeric]=None, is_in: Optional[List[Union[(Numeric...
def aggregate(conf, fedavg_models, client_models, criterion, metrics, flatten_local_models, fa_val_perf, val_data_loader): (_, local_models) = agg_utils.recover_models(conf, client_models, flatten_local_models) client_models = {} for (arch, fedavg_model) in fedavg_models.items(): kt = ZeroShotKTSolv...
('{dst_data} = vmulq_f32({dst_data}, {rhs_data});') def neon_vmul2_4xf32(dst: ([f32][4] Neon), lhs: ([f32][4] Neon), rhs: ([f32][4] Neon)): assert (stride(dst, 0) == 1) assert (stride(lhs, 0) == 1) assert (stride(rhs, 0) == 1) for i in seq(0, 4): dst[i] = (lhs[i] * rhs[i])
class MapProjectTests(DatabaseTestCase): def setUp(self): super().setUp() create_distro(self.session) create_project(self.session) self.client = self.flask_app.test_client() self.user = models.User(email='', username='user') user_social_auth = social_models.UserSocial...
class Conv1d(Module): def __init__(self, in_channels: int, out_channels: int, kernel_size: int, stride: int=1, padding: int=0, dilation: int=1, groups: int=1, dtype: str='float16', bias: bool=False, name: str='conv1d'): super().__init__() self.weight = Parameter(shape=[out_channels, kernel_size, (in...
def get_constructor_abi(contract_abi: ABI) -> ABIFunction: candidates = [abi for abi in contract_abi if (abi['type'] == 'constructor')] if (len(candidates) == 1): return candidates[0] elif (len(candidates) == 0): return None elif (len(candidates) > 1): raise ValueError('Found mul...
def extractThat1VillainessWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('ibmv', 'I Became the Master of the Villain', 'translated'), ('cam', 'The Count and the Ma...
def update_mapping_from_cache(dsk: Dict[(CollectionAddress, Tuple[(Any, ...)])], resources: TaskResources, start_fn: Callable) -> None: cached_results: Dict[(str, Optional[List[Row]])] = resources.get_all_cached_objects() for collection_name in cached_results: dsk[CollectionAddress.from_string(collectio...
def _extract_flat_kerning(font, pairpos_table): extracted_kerning = {} for glyph_name_1 in pairpos_table.Coverage.glyphs: class_def_1 = pairpos_table.ClassDef1.classDefs.get(glyph_name_1, 0) for glyph_name_2 in font.getGlyphOrder(): class_def_2 = pairpos_table.ClassDef2.classDefs.get...
def test_check_instances_dict(): instances = {'a': [('ols-a1', OLS()), ('ols-a2', OLS(offset=1))], 'b': [('ols-b1', OLS()), ('ols-b2', OLS(offset=1))]} out = _check_instances(instances) assert (id(out) == id(instances)) for k in out: ou = out[k] it = instances[k] for i in range(2...
def main(): if (len(sys.argv) < 2): sys.exit('Usage: make-multiple-text.py [file]') filename = sys.argv[1] spec = segyio.spec() spec.sorting = 2 spec.format = 1 spec.samples = [1] spec.ilines = [1] spec.xlines = [1] spec.ext_headers = 4 with segyio.create(filename, spec) ...
class BeamStateBackfill(Service, QueenTrackerAPI): _total_added_nodes = 0 _num_added = 0 _num_missed = 0 _num_accounts_completed = 0 _num_storage_completed = 0 _report_interval = 10 _num_requests_by_peer: typing.Counter[ETHPeer] def __init__(self, db: AtomicDatabaseAPI, peer_pool: ETHPee...
def test_federal_account_update_agency(data_fixture): assert (TreasuryAppropriationAccount.objects.filter(awarding_toptier_agency__isnull=True).count() == 6) assert (TreasuryAppropriationAccount.objects.filter(funding_toptier_agency__isnull=True).count() == 6) assert (FederalAccount.objects.filter(parent_to...
def test(): assert ('in doc.ents' in __solution__), 'Are you iterating over the entities?' assert (iphone_x.text == 'iPhone X'), 'Are you sure iphone_x covers the right tokens?' __msg__.good("Perfect! Of course, you don't always have to do this manually. In the next exercise, you'll learn about spaCy's rule...
class SkuTestSerializer(ExtensionsModelSerializer): class Meta(): model = test_models.Sku fields = ('id', 'variant') expandable_fields = dict(owners=dict(serializer='tests.serializers.OwnerTestSerializer', many=True), model=ModelTestSerializer, manufacturer=dict(serializer=ManufacturerTestSe...
class DummyConnection(Connection): connection_id = PublicId.from_str('fetchai/dummy:0.1.0') def __init__(self, **kwargs): super().__init__(**kwargs) self.state = ConnectionStates.disconnected self._queue = None async def connect(self, *args, **kwargs): self._queue = asyncio.Q...
def create_algorithm(repr: Union[(dict, str)], bms_name=None) -> BaseAlgorithm: classes = dict(soc=SocAlgorithm) (args, kwargs) = ([], {}) if isinstance(repr, dict): repr = dict(repr) name = repr.pop('name') kwargs = repr else: repr = repr.strip().split(' ') name ...
def test_align_coords_interpolate(): geoms = get_geoms(translate=5.0, euler=(0.0, 0.0, 90.0)) interpolated = interpolate(*geoms, 10, kind='lst') all_coords = [geom.coords for geom in interpolated] aligned = align_coords(all_coords) np.testing.assert_allclose(aligned[0], aligned[(- 1)], atol=1e-10)
def test_update_versions_is_working_properly_case_3(create_test_data, create_pymel, create_maya_env): data = create_test_data pm = create_pymel maya_env = create_maya_env data['asset2_model_main_v002'].is_published = True data['asset2_model_main_v003'].is_published = True maya_env.open(data['ass...
def at_search_result(matches, caller, query='', quiet=False, **kwargs): error = '' if (not matches): error = (kwargs.get('nofound_string') or _("Could not find '{query}'.").format(query=query)) matches = None elif (len(matches) > 1): multimatch_string = kwargs.get('multimatch_string'...
def deriveKeysFromUserkey(sid, pwdhash): if (len(pwdhash) == 20): key1 = HMAC.new(pwdhash, (sid + '\x00').encode('utf-16le'), SHA1).digest() return [key1] key1 = HMAC.new(pwdhash, (sid + '\x00').encode('utf-16le'), SHA1).digest() tmpKey = pbkdf2_hmac('sha256', pwdhash, sid.encode('utf-16le')...
def test_duplicates_are_removed(tmp_path: Path) -> None: with run_within_dir(tmp_path): create_files([Path('dir/subdir/file1.py')]) files = PythonFileFinder(exclude=(), extend_exclude=(), using_default_exclude=False).get_all_python_files_in((Path(), Path())) assert (sorted(files) == [Path('d...
class SparkDataFrameFilesystemStoragePlugin(TypeStoragePlugin): def compatible_with_storage_def(cls, system_storage_def): return (system_storage_def is fs_system_storage) def set_object(cls, intermediate_store, obj, _context, _runtime_type, paths): print('kaka Set_object') target_path = ...
def extractSOnlinehomeUs(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 tagm...
class Plugin(plugin.PluginProto): PLUGIN_ID = 217 PLUGIN_NAME = 'Energy (AC) - HDHK modbus AC current sensor (TESTING)' PLUGIN_VALUENAME1 = 'Amper' PLUGIN_VALUENAME2 = 'Amper' PLUGIN_VALUENAME3 = 'Amper' PLUGIN_VALUENAME4 = 'Amper' def __init__(self, taskindex): plugin.PluginProto.__...
class OptionPlotoptionsColumnSonificationContexttracksPointgrouping(Options): def algorithm(self): return self._config_get('minmax') def algorithm(self, text: str): self._config(text, js_type=False) def enabled(self): return self._config_get(True) def enabled(self, flag: bool): ...
class OptionSeriesStreamgraphSonificationContexttracksMappingLowpassResonance(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: ...
class SSHhandler(object): SSH_SESSIONS = {} SSH_AUTH = {} def __init__(self): AES.new = fixed_AES_new self.mutex = threading.RLock() def remove(self, host): try: del SSHhandler.SSH_SESSIONS[host] except Exception: pass def close(self): ...
class ForthTest(unittest.TestCase): def test_parsing_and_numbers_numbers_just_get_pushed_onto_the_stack(self): self.assertEqual(evaluate(['1 2 3 4 5']), [1, 2, 3, 4, 5]) def test_parsing_and_numbers_pushes_negative_numbers_onto_the_stack(self): self.assertEqual(evaluate(['-1 -2 -3 -4 -5']), [(- ...
def appender(filepath, total, results): log.debug('file appender for %s started ...', filepath) print() with open(filepath, 'a+t') as fp: done = 0 while True: on_progress(done, total) line = results.get() if (line is None): break ...
class DeploymentResponseSuccessfulMock(object): status_code = 201 content = {'deployment': {'id': , 'revision': '1.2.3', 'changelog': 'Lorem Ipsum', 'description': 'Lorem ipsum usu amet dicat nullam ea. Nec detracto lucilius democritum in.', 'user': 'username', 'timestamp': '2016-06-21T09:45:08+00:00', 'links':...
.usefixtures('use_tmpdir') def test_gen_data_eq_config(): alt1 = GenDataConfig(name='ALT1', report_steps=[2, 1, 3]) alt2 = GenDataConfig(name='ALT1', report_steps=[2, 3, 1]) alt3 = GenDataConfig(name='ALT1', report_steps=[3]) alt4 = GenDataConfig(name='ALT4', report_steps=[3]) alt5 = GenDataConfig(n...
def filter_cat_names(cat_names: list[tuple[(str, int, int)]]) -> list[tuple[(str, int, int)]]: filtered_cat_ids: list[int] = [] cat_data: list[tuple[(str, int, int)]] = [] for (cat_name, cat_id, cat_form) in cat_names: if (cat_id not in filtered_cat_ids): filtered_cat_ids.append(cat_id) ...
def _run_time(cmd_argv, time_argv, repeat, average): assert (repeat > 1), repeat run_cmd = _get_cmd_runner(time_argv, cmd_argv) header = None aggregate = None for _ in _utils.scriptutil.iter_with_markers(repeat, verbosity=logger): text = run_cmd(capture=True) result = _parse_output(t...
def _get_hg_devstr(idtype='rev'): from os import path if release: raise ValueError('revsion devstring not valid for a release version') try: from mercurial import hg, ui from mercurial.node import hex, short from mercurial.error import RepoError try: based...
def secrets_are_valid(secrets: SUPPORTED_STORAGE_SECRETS, storage_type: Union[(StorageType, str)]) -> bool: if (not isinstance(storage_type, StorageType)): try: storage_type = StorageType[storage_type] except KeyError: raise ValueError('storage_type argument must be a valid S...
class RedisThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.running = True self.enabled = False self.ppqn = 1 self.shift = 0 self.clock = [0] self.key = '{}.note'.format(patch.getstring('output', 'prefix')) def setPpqn(sel...
def main(): module_spec = schema_to_module_spec(versioned_schema) mkeyname = 'name' 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 SqliteWriteDispatcher(): def __init__(self, db_context: 'DatabaseContext') -> None: self._db_context = db_context self._logger = logs.get_logger('sqlite-writer') self._writer_queue: 'queue.Queue[WriteEntryType]' = queue.Queue() self._writer_thread = threading.Thread(target=self...
def test_delete_policy_cascades(db: Session, policy: Policy) -> None: rule = policy.rules[0] target = rule.targets[0] policy.delete(db=db) assert (Rule.get(db=db, object_id=rule.id) is None) assert (RuleTarget.get(db=db, object_id=target.id) is None) assert (Policy.get(db=db, object_id=policy.id...
class OptionSeriesScatterSonificationTracksMappingPlaydelay(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...
class Solution(): def rob(self, root: TreeNode) -> int: def dfs(node): if (node is None): return (0, 0) (l_robbed, l_not_robbed) = dfs(node.left) (r_robbed, r_not_robbed) = dfs(node.right) ret = (((node.val + l_not_robbed) + r_not_robbed), max(...
def maximum_absolute_diff(normalized_density, bottom, top): def neg_absolute_difference(radius): return (- np.abs((normalized_density(radius) - straight_line(radius, normalized_density, bottom, top)))) result = minimize_scalar(neg_absolute_difference, bounds=[bottom, top], method='bounded') radius_s...
class OptionPlotoptionsScatter3dSonificationDefaultinstrumentoptionsMapping(Options): def frequency(self) -> 'OptionPlotoptionsScatter3dSonificationDefaultinstrumentoptionsMappingFrequency': return self._config_sub_data('frequency', OptionPlotoptionsScatter3dSonificationDefaultinstrumentoptionsMappingFreque...
class Migration(migrations.Migration): dependencies = [('django_etebase', '0025_auto__1216')] operations = [migrations.RenameField(model_name='collectioninvitation', old_name='accessLevel', new_name='accessLevelOld'), migrations.RenameField(model_name='collectionmember', old_name='accessLevel', new_name='access...
class CisSpidersItem(Item): idx = Field() spider_name = Field() img = Field() title = Field() abstract = Field() link = Field() date = Field() area = Field() key_words = Field() contact = Field() video = Field() state = Field() project_holder = Field() partner = F...
class ReportData(BaseModel): conv_uid: str template_name: str template_introduce: str = None charts: List[ChartData] def prepare_dict(self): return {'conv_uid': self.conv_uid, 'template_name': self.template_name, 'template_introduce': self.template_introduce, 'charts': [chart.dict() for char...
class AbstractPopStatsDataContainer(AbstractPlayerInfoDataContainer, abc.ABC): def _iterate_budgetitems(self, cd: datamodel.CountryData) -> Iterable[Tuple[(str, float)]]: for pop_stats in self._iterate_popstats(cd): key = self._get_key_from_popstats(pop_stats) val = self._get_value_f...
class ConvTasNetModule(LightningModule): def __init__(self, model: nn.Module, loss: Callable, optim_fn: Callable[(Iterable[Parameter], Optimizer)], metrics: Mapping[(str, Callable)], lr_scheduler: Optional[_LRScheduler]=None) -> None: super().__init__() self.model: nn.Module = model self.los...
class OptionPlotoptionsHistogramStatesInactive(Options): def animation(self) -> 'OptionPlotoptionsHistogramStatesInactiveAnimation': return self._config_sub_data('animation', OptionPlotoptionsHistogramStatesInactiveAnimation) def enabled(self): return self._config_get(True) def enabled(self,...
def is_valid_inputs(output_shapes, c_shapes): msg = '' if (output_shapes == c_shapes): return (True, msg) def _squeeze_leading_1s(shapes): out = [] if (len(shapes) == 0): return out i = 0 for shape in shapes: if (not isinstance(shape, IntImm)):...
def reload_config(conf_file=None): global CACHE_PERIOD_MIN, CACHE_PERIOD_DEFAULT_MIN, CLIPBOARD_CMD, CONF, MAX_LEN, ENV, ENC, SEQUENCE CONF = configparser.ConfigParser() conf_file = (conf_file if (conf_file is not None) else CONF_FILE) if (not exists(conf_file)): try: os.mkdir(os.pat...
def main(): from argparse import ArgumentParser p = ArgumentParser() p.add_argument('-r', '--rx_port', default=5556, help='Port number to receive zmq messages for IO on') p.add_argument('-t', '--tx_port', default=5555, help='Port number to send IO messages via zmq') args = p.parse_args() print('...
class Worker(): def __init__(self, client, notion_ai): self.client = client self.notion_ai = notion_ai self.task_manager = TaskManager(logging, notion_ai) self.logging = logging schedule.every(5).minutes.do(self.background_job) self.stop_run_continuously = self.run_co...
def get_benchmarks(*, _cache={}): benchmarks = {} for (suite, info) in BENCHMARKS.items(): if (suite in _cache): benchmarks[suite] = list(_cache[suite]) continue url = info['url'] reldir = info['reldir'] reporoot = os.path.join(REPOS_DIR, os.path.basename(...
class OptionPlotoptionsCylinderSonificationDefaultinstrumentoptionsMappingHighpassFrequency(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 mapT...
def test_switch_with_loop1(task): var_1 = Variable('var_1', Pointer(Integer(32, True), 32), None, False, Variable('var_28', Pointer(Integer(32, True), 32), 1, False, None)) var_0 = Variable('var_0', Integer(32, True), None, True, Variable('var_10', Integer(32, True), 0, True, None)) task.graph.add_nodes_fro...
.parametrize('arg_type', [List[str], ZipFile, Optional[ZipFile], Union[(ZipFile, str, Path)], CustomGeneric, CustomGeneric[int], CustomGeneric[str], Optional[CustomGeneric]]) def test_static_deserialize_types_custom_deserialize(arg_type): split_string = get_list_converter(str) def convert_zipfile(value: str) ->...
('', doc={'description': ''}) class RestFirmwareGetWithoutUid(RestResourceBase): URL = '/rest/firmware' _accepted(*PRIVILEGES['view_analysis']) (responses={200: 'Success', 400: 'Unknown file object'}, params={'offset': {'description': 'offset of results (paging)', 'in': 'query', 'type': 'int'}, 'limit': {'d...
('globals') def direct_globals(node): assert isinstance(node, (Function_Definition, Script_File)) class Global_Visitor(AST_Visitor): def __init__(self): self.names = set() def visit(self, node, n_parent, relation): if isinstance(node, Global_Statement): se...
class CertStreamThread(Thread): def __init__(self, q, *args, **kwargs): self.q = q self.c = CertStreamClient(self.process, skip_heartbeats=True, on_open=None, on_error=None) super().__init__(*args, **kwargs) def run(self): global THREAD_EVENT while (not THREAD_EVENT.is_se...
.integration class TestGetServerResources(): .integration .parametrize('created_resources', PARAM_MODEL_LIST, indirect=['created_resources']) def test_get_server_resources_found_resources(self, test_config: FidesConfig, created_resources: List) -> None: resource_type = created_resources[0] r...
def test_deepcopy(aggregate): provider_copy = providers.deepcopy(aggregate) assert (aggregate is not provider_copy) assert isinstance(provider_copy, type(aggregate)) assert (aggregate.example_a is not provider_copy.example_a) assert isinstance(aggregate.example_a, type(provider_copy.example_a)) ...
class Action(object): def __init__(self, name, send, params): self.name = name self.send = send self.params = list(params) __pnmltag__ = 'action' def __pnmldump__(self): result = Tree(self.__pnmltag__, None, name=self.name, send=str(self.send)) for param in self.param...
class OptionPlotoptionsVariablepieSonificationTracksMappingHighpassResonance(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: s...
_util.copy_func_kwargs(BillingOptions) def on_plan_update_published(**kwargs) -> _typing.Callable[([OnPlanUpdatePublishedCallable], OnPlanUpdatePublishedCallable)]: options = BillingOptions(**kwargs) def on_plan_update_published_inner_decorator(func: OnPlanUpdatePublishedCallable): _functools.wraps(func...
def get_intermediate_tasks(task1, task2): intermediate_tasks = [] found_orig_task = False for parent in reversed((task2.parents + [task2])): if (parent != task1): intermediate_tasks.append(parent) else: found_orig_task = True break if found_orig_task: ...
class OptionPlotoptionsAreasplineSonificationTracksMappingTremoloSpeed(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 KiwoomOpenApiPlusEagerSomeEventHandler(KiwoomOpenApiPlusEagerAllEventHandler): def __init__(self, control, request, context): super().__init__(control, context) self._request = request def slots(self): names = self.names() slots = [getattr(self, name) for name in names] ...
() def pathy_fixture(): pytest.importorskip('pathy') import shutil import tempfile from pathy import Pathy, use_fs temp_folder = tempfile.mkdtemp(prefix='thinc-pathy') use_fs(temp_folder) root = Pathy('gs://test-bucket') root.mkdir(exist_ok=True) (yield root) use_fs(False) sh...
def is_synced(integration: str, integration_item_code: str, variant_id: Optional[str]=None, sku: Optional[str]=None) -> bool: filter = {'integration': integration, 'integration_item_code': integration_item_code} if variant_id: filter.update({'variant_id': variant_id}) item_exists = bool(frappe.db.ex...
class S3FileAdmin(BaseFileAdmin): def __init__(self, bucket_name, region, aws_access_key_id, aws_secret_access_key, *args, **kwargs): storage = S3Storage(bucket_name, region, aws_access_key_id, aws_secret_access_key) super(S3FileAdmin, self).__init__(*args, storage=storage, **kwargs)
def eye(n: int, m: (int | None)=None, k: int=0) -> Matrix: if (m is None): m = n dlen = (m if ((n > m) and (k < 0)) else (m - abs(k))) a = [] for i in range(n): pos = (i + k) idx = (i if (k >= 0) else pos) d = int((0 <= idx < dlen)) a.append(((([0.0] * clamp(pos, ...
def run(cls, job, eval=True): if (job == 'fit'): (lr, _) = est.get_learner(cls, True, False) lr.dtype = np.float64 else: lr = run(cls, 'fit', False) data = Data(cls, True, False, True) (X, y) = data.get_data((25, 4), 3) if (job in ['fit', 'transform']): ((F, wf), _) =...
class ScheduleBByRecipientID(BaseDisbursementAggregate): __table_args__ = {'schema': 'disclosure'} __tablename__ = 'dsc_sched_b_aggregate_recipient_id_new' recipient_id = db.Column('recipient_cmte_id', db.String, primary_key=True, doc=docs.RECIPIENT_ID) committee = utils.related_committee('committee_id'...
def test_adding_load_balancer_source_ranges(): config = '\nservice:\n loadBalancerSourceRanges:\n - 0.0.0.0/0\n ' r = helm_template(config) assert (r['service'][uname]['spec']['loadBalancerSourceRanges'][0] == '0.0.0.0/0') config = '\nservice:\n loadBalancerSourceRanges:\n - 192.168.0.0/24\n ...
.parametrize(('input_data', 'expected_output'), [({}, False), ({'arch': {}}, False), ({'arch': {'option': {}}}, False), ({'arch': {'error': 'foo'}}, False), ({'arch': {'option': {'error': 'foo'}}}, False), ({'arch': {'option': {'stdout': 'foo', 'stderr': '', 'return_code': '0'}}}, True)]) def test_valid_execution_in_re...
def integration_test() -> int: print('Running `ptr` integration tests (aka run itself)', file=sys.stderr) stats_file = (Path(gettempdir()) / 'ptr_ci_stats') ci_cmd = ['python', 'ptr.py', '-d', '--print-cov', '--run-disabled', '--error-on-warnings', '--stats-file', str(stats_file)] if ('VIRTUAL_ENV' in e...
class RecordMarkerCommandAttributes(betterproto.Message): marker_name: str = betterproto.string_field(1) details: Dict[(str, v1common.Payloads)] = betterproto.map_field(2, betterproto.TYPE_STRING, betterproto.TYPE_MESSAGE) header: v1common.Header = betterproto.message_field(3) failure: v1failure.Failure...
def run(): print('\nmodule top();\n ') sites = list(gen_sites()) assert (len(sites) == 1) (tile_name, int_tiles) = sites[0] DWE = random.randint(0, 1) DI14 = random.randint(0, 1) params = {} params[int_tiles[0]] = DWE params[int_tiles[1]] = DI14 print('\n wire [15:0] di;\n ...
def delete_internal_urls(sess, urls, chunk_size=1000, pbar=True): pbar = tqdm.tqdm(range(0, len(urls), chunk_size), position=1) for chunk_idx in pbar: chunk = urls[chunk_idx:(chunk_idx + chunk_size)] while 1: try: ctbl = version_table(db.WebPages.__table__) ...
def extractAquarilasScenario(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None if ('In That Moment of Suffering' in item['tags']): return buildReleaseMessageWithType(item, 'In That M...
class HomeArrivalNotifier(hass.Hass): def initialize(self): self.listen_state_handle_list = [] self.app_switch = self.args['app_switch'] self.zone_name = self.args['zone_name'] self.input_boolean = self.args['input_boolean'] self.notify_name = self.args['notify_name'] ...
class TestFnMatchEscapes(unittest.TestCase): def check_escape(self, arg, expected, unix=None, raw_chars=True): flags = 0 if (unix is False): flags = fnmatch.FORCEWIN elif (unix is True): flags = fnmatch.FORCEUNIX self.assertEqual(fnmatch.escape(arg), expected)...
class RelationshipTlsSubscriptionTlsSubscription(ModelNormal): allowed_values = {} validations = {} _property def additional_properties_type(): lazy_import() return (bool, date, datetime, dict, float, int, list, str, none_type) _nullable = False _property def openapi_types():...
def test_custom_analyzer_can_collect_custom_items(): trigram = analysis.tokenizer('trigram', 'nGram', min_gram=3, max_gram=3) my_stop = analysis.token_filter('my_stop', 'stop', stopwords=['a', 'b']) umlauts = analysis.char_filter('umlauts', 'pattern_replace', mappings=['u=>ue']) a = analysis.analyzer('m...
class SquaredCategoricalCrossentropy(tf.keras.losses.Loss): def __init__(self, from_logits=False, label_smoothing=0, reduction=tf.keras.losses.Reduction.AUTO, name='squared_categorical_crossentropy'): super(SquaredCategoricalCrossentropy, self).__init__(reduction=reduction, name=name) self.from_logi...
class OptionPlotoptionsAreasplineSonificationTracksMappingGapbetweennotes(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 OptionSeriesArearangeSonificationDefaultinstrumentoptionsMappingTremoloSpeed(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, t...
def map_ecstask_to_containerinstance(task: Dict[(str, Any)]) -> ContainerInstance: container = task['containers'][0] logging.debug(f'The ECS task response from AWS: {task}') ip_v4 = (container['networkInterfaces'][0].get('privateIpv4Address') if (len(container['networkInterfaces']) > 0) else None) statu...
(python=python_versions) def tests(session: Session) -> None: session.install('.') session.install('invoke', 'pytest', 'xdoctest', 'coverage[toml]', 'pytest-cov') try: session.run('inv', 'tests', env={'COVERAGE_FILE': f'.coverage.{platform.system()}.{platform.python_version()}'}) finally: ...
def parse_lanes(lane_expr): fields = lane_expr.split(',') lanes = [] for field in fields: try: i = field.index('-') l1 = int(field[:i]) l2 = int(field[(i + 1):]) for i in range(l1, (l2 + 1)): lanes.append(i) except ValueError: ...
class TaskWindowToggleAction(Action): name = Property(Str, observe='window.active_task.name') style = 'toggle' window = Instance('envisage.ui.tasks.task_window.TaskWindow') def perform(self, event=None): if self.window: self.window.activate() def _get_name(self): if self....
class GetInstanceArgs(object): def __init__(self, node): self.argspec = [] self.arg = {} self.buffer = {} self.net = {} self.task = {} seen = set() for a in (node.args.args + node.args.kwonlyargs): if (a.arg in seen): self._raise(Co...
def extractAriandeltlWordpressCom(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...
_routes.route('/user-details/get-user-id', methods=['GET']) _required def get_user_id(): token = None if ('Authorization' in request.headers): token = request.headers['Authorization'].split(' ')[1] if (not token): return ({'message': 'Authentication Token is missing!', 'data': None, 'error':...