code
stringlengths
281
23.7M
def sendNotification(snmpEngine, authData, transportTarget, contextData, notifyType, *varBinds, **options): def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): cbCtx['errorIndication'] = errorIndication cbCtx['errorStatus'] = errorStatus cbCtx...
def _persist_dump(dump, result_path, config): merged_segments = _merge_dump_segments(dump) offsets = set() offsets.add(0) post_processing_steps = config.get('post_processing_steps', []) if ('pe_carving' in post_processing_steps): for (offset, _) in iterate_pe_headers(merged_segments): ...
def extract_interregional_exchanges(raw_data: list, exchange_key: ZoneKey, logger: Logger) -> ExchangeList: exchanges = ExchangeList(logger) zone_data = [item for item in raw_data if (item['Type'] == MAPPING[exchange_key])] imports = sum((float(item['ImportMW']) for item in zone_data)) exports = sum((fl...
def test_function_node_has_required_entities() -> None: def f(a: int) -> str: pass (ArgumentMessage, ReturnMessage, FunctionNode) = function_to_node(f) input_topic = FunctionNode.INPUT isinstance(input_topic, lg.Topic) assert (input_topic.message_type is ArgumentMessage) output_topic = F...
def upgrade(): op.create_table('copr_dir', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.Text(), nullable=True), sa.Column('main', sa.Boolean(), server_default='0', nullable=False), sa.Column('copr_id', sa.Integer(), nullable=False), sa.ForeignKeyConstraint(['copr_id'], ['copr.id']), sa.Primar...
class OptionSeriesLineSonificationContexttracksMappingLowpass(Options): def frequency(self) -> 'OptionSeriesLineSonificationContexttracksMappingLowpassFrequency': return self._config_sub_data('frequency', OptionSeriesLineSonificationContexttracksMappingLowpassFrequency) def resonance(self) -> 'OptionSer...
def run_update_query(fabs_awards, fpds_awards): loop = asyncio.new_event_loop() statements = [] predicate = f"WHERE tn.award_id IN ({','.join((fabs_awards + fpds_awards))})" all_sql = general_award_update_sql_string.format(predicate=predicate) statements.append(asyncio.ensure_future(async_run_create...
def upgrade(): con = op.get_bind() if (con.engine.dialect.name == 'sqlite'): logger.warning('SQLite is only partially supported for revision {}.'.format(revision)) with op.batch_alter_table('conversations', schema=None) as batch_op: if (con.engine.dialect.name == 'mysql'): batch_...
class DelftModelImpl(ModelImpl): def __init__(self, model_url: str, app_context: AppContext): self.model_url = model_url self.app_context = app_context self._lazy_model = LazyLoaded[Sequence](self._load_model) def __repr__(self) -> str: return ('%s(%r, loaded=%r)' % (type(self)._...
def test_directory_path_without_trailing_slash_redirected(server, files): directory_url = (files.index_url.rpartition('/')[0] + '/') no_slash_url = directory_url.rstrip('/') response = server.get(no_slash_url, allow_redirects=False) location = urljoin(no_slash_url, response.headers['Location']) asse...
def log_syslogd2_override_setting(data, fos): vdom = data['vdom'] log_syslogd2_override_setting_data = data['log_syslogd2_override_setting'] filtered_data = underscore_to_hyphen(filter_log_syslogd2_override_setting_data(log_syslogd2_override_setting_data)) return fos.set('log.syslogd2', 'override-settin...
class FbOAuth(): Fb_AUTH_URI = ' Fb_TOKEN_URI = ' Fb_USER_INFO = (' + 'email,id,name,picture,last_name,first_name,link') SCOPE = ['public_profile', 'email'] def get_client_id(cls): return get_settings()['fb_client_id'] def get_client_secret(cls): return get_settings()['fb_client_...
class OptionSeriesParetoStatesHoverHalo(Options): def attributes(self): return self._config_get(None) def attributes(self, value: Any): self._config(value, js_type=False) def opacity(self): return self._config_get(0.25) def opacity(self, num: float): self._config(num, js_...
class QueryRegexpTask(Task): def __init__(self, field: str, value: str): super().__init__('regexp') self._field = field self._value = value def resolve_task(self, query_params: 'QueryParams', post_processing: List['PostProcessingAction'], query_compiler: 'QueryCompiler') -> RESOLVED_TASK...
def test_comp_documentation(): string = write_rpc_request(1, 'initialize', {'rootPath': str(test_dir)}) file_path = ((test_dir / 'subdir') / 'test_free.f90') string += comp_request(file_path, 21, 37) (errcode, results) = run_request(string) assert (errcode == 0) exp_results = [{'label': 'scaled_...
def __bits_to_bytes(bits): the_bytes = [] byte = 0 for i in range(0, len(bits)): byte = (byte << 1) if bits[i]: byte = (byte | 1) else: byte = (byte | 0) if (((i + 1) % 8) == 0): the_bytes.append(byte) byte = 0 return the_by...
def update_acc_op_mappers_for_ait() -> None: ait_acc_op_mappers = get_ait_acc_op_mappers() custom_ait_acc_op_mappers = get_custom_ait_acc_op_mappers() logger.info('Found %s ait mappers, %s custom ait op mappers', len(ait_acc_op_mappers), len(custom_ait_acc_op_mappers)) for (op_and_target, mapper) in ait...
def offset_set(bset, delta, margin, dir_offset_last_bbox): objects = ((bset.objects_low + bset.objects_high) + bset.objects_cage) delta_max = max(abs(delta.x), abs(delta.y), abs(delta.z)) direction = [0, 0, 0] if (delta_max > 0): for i in range(0, 3): if (abs(delta[i]) == delta_max):...
class XRefBadgeRole(ReferenceRole): def __init__(self, color: Optional[str]=None, *, outline: bool=False) -> None: super().__init__() self.color = color self.outline = outline def run(self) -> Tuple[(List[nodes.Node], List[nodes.system_message])]: options = {'classes': create_bdg...
def test_meta_account_loader_filters_with_multi_word_attr_names(): d = [{'id': '', 'acct status': 'active account'}, {'id': '', 'acct status': 'account suspended'}, {'id': '', 'acct status': 'active account'}] mal = acctload.MetaAccountLoader(d) acct = mal.accounts(exclude={'acct_status': ['active account']...
class JsAnonymous(primitives.JsDataModel): def __init__(self, js_funcs): (self.__strFnc, self.__returnFnc, self.__paramsFnc) = (js_funcs, '', []) def return_(self, value): self.__returnFnc = value return self def params(self, pmts: dict): self.__paramsFnc = pmts retur...
def set_output(kwargs, job, map): if ('return_preds' in kwargs): if kwargs['return_preds']: __no_output__ = False else: __no_output__ = True else: __no_output__ = (job == 'fit') kwargs['return_preds'] = (job != 'fit') if (not map): __no_output_...
class CRUDExternalApi(CRUDApi): def update_by_external_id(self, api_objects): if (not isinstance(api_objects, Iterable)): api_objects = [api_objects] return CRUDRequest(self).put(api_objects, update_many_external=True) def delete_by_external_id(self, api_objects): if (not isi...
class PersistDialoguesStorage(BasicDialoguesStorage): INCOMPLETE_DIALOGUES_OBJECT_NAME = 'incomplete_dialogues' TERMINAL_STATE_DIALOGUES_COLLECTTION_SUFFIX = '_terminal' def __init__(self, dialogues: 'Dialogues') -> None: super().__init__(dialogues) self._skill_component: Optional[SkillCompo...
def test_second_conversion(): timestamps = [('2023-01-01T12:34:56Z', '2023-01-01T12:34:56Z'), ('2023-02-14T14:37:52Z', '2023-02-14T14:37:52Z'), ('2023-03-21T06:43:58Z', '2023-03-21T06:43:58Z'), ('2023-10-06T07:00:00Z', '2023-10-06T07:00:00Z')] for (input_timestamp, expected_output) in timestamps: expect...
class AsyncWitnessDB(AsyncWitnessDataBaseAPI): _recent_blocks_with_witnesses_lookup_key = b'recent-blocks-with-witness-hashes' _max_witness_history = 256 def __init__(self, db: DatabaseAPI) -> None: self.db = db def _make_block_witness_hashes_lookup_key(self, block_hash: Hash32) -> bytes: ...
class TestLaunchServicer(unittest.TestCase): def setUp(self): self.test_get_content_path = ('%s/content_test.txt' % os.getcwd()) self.current_pose = 0 def tearDown(self): try: os.remove(self.test_get_content_path) except Exception: pass def test_get_lo...
class RegisterCallableField(RegisterFieldTemplate): def __init__(self, salt: str, key: ByteString): super(RegisterCallableField, self).__init__(salt, key) def handle_attribute_from_config(self, attr_space: AttributeSpace, builder_space: BuilderSpace): str_field = builder_space.arguments[attr_spa...
class TestSuperFencesClassesIds(util.MdCase): extension = ['pymdownx.superfences'] extension_configs = {} def test_classes(self): self.check_markdown('\n ```{.python .more}\n import test\n ```\n ', '\n <div class="more highlight"><pre><span></sp...
class OptionPlotoptionsVariablepieSonificationTracksMappingRate(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 LlamaDecoder(TransformerDecoder[LlamaConfig], FromHFHub[LlamaConfig]): def __init__(self, config: LlamaConfig, *, device: Optional[torch.device]=None) -> None: super().__init__(config) self.embeddings = TransformerEmbeddings(dropouts=EmbeddingDropouts(embed_output_dropout=Dropout(config.embedd...
def test_staticfiles_prevents_breaking_out_of_directory(tmpdir): directory = os.path.join(tmpdir, 'foo') os.mkdir(directory) path = os.path.join(tmpdir, 'example.txt') with open(path, 'w') as file: file.write('outside root dir') app = StaticFiles(directory=directory) path = app.get_path(...
def load_test_cases(): loaded = [] for filename in filenames: path = os.path.join('tests', 'jsonschema', 'draft7', filename) content = open(path, 'rb').read() test_suite = json.loads(content.decode('utf-8')) for test_cases in test_suite: description = test_cases['desc...
class stravaBestSamples(Base): __tablename__ = 'strava_best_samples' activity_id = Column('activity_id', BigInteger(), index=True, primary_key=True) interval = Column('interval', Integer, index=True, primary_key=True) mmp = Column('mmp', Float()) ftp = Column('ftp', Float()) watts_per_kg = Colum...
def test_phi_function_in_head1(): u1 = Variable('u', Integer.int32_t(), 1) u2 = Variable('u', Integer.int32_t(), 2) v0 = Variable('v', Integer.int32_t(), 0) v1 = Variable('v', Integer.int32_t(), 1) node = BasicBlock(0, [Phi(u1, [v0, u2]), Phi(v1, [v0, u1]), Assignment(u2, BinaryOperation(OperationTy...
.parametrize('literal_value,python_type,expected_python_value', [(Literal(collection=LiteralCollection(literals=[Literal(scalar=Scalar(primitive=Primitive(integer=1))), Literal(scalar=Scalar(primitive=Primitive(integer=2))), Literal(scalar=Scalar(primitive=Primitive(integer=3)))])), typing.List[int], [1, 2, 3]), (Liter...
def _test_correct_response_for_contract_pricing_type_codes(client): resp = client.post('/api/v2/search/spending_over_time', content_type='application/json', data=json.dumps({'group': 'fiscal_year', 'filters': {'contract_pricing_type_codes': ['type_of_contract_pricing_0', 'type_of_contract_pricing_10', 'type_of_cont...
class GDBObject(): def __init__(self, pid, current_path, executable, template_out_path): self.pid = pid self.fifo = f'/tmp/memanz_pipe_{self.pid}' self.current_path = current_path os.putenv('MEMORY_ANALYZER_TEMPLATES_PATH', template_out_path) self.executable = executable ...
def _start(): global patch, name, path, monitor global channels, dividers, count, triggers, channel, divider, thread channels = patch.getstring('clock', 'channel', multiple=True) dividers = patch.getint('clock', 'rate', multiple=True) count = 0 triggers = [] for channel in channels: ...
def load_pipeline(name: str, *, lang: str='', dir: Optional[str]=None, package: str='default', processors: Union[(dict, str)]={}, logging_level: Optional[Union[(int, str)]]=None, verbose: Optional[bool]=None, use_gpu: bool=True, **kwargs) -> Language: config = {'nlp': {'tokenizer': {'kwargs': {}}}} if (lang == ...
.django_db def test_api_key_hash_upgrade() -> None: key_generator = APIKey.objects.key_generator (api_key, generated_key) = APIKey.objects.create_key(name='test') assert api_key.is_valid(generated_key) assert key_generator.using_preferred_hasher(api_key.hashed_key) api_key.hashed_key = make_password...
.parametrize('data', ['univariate', 'ndgrid'], indirect=True) .parametrize('smooth', [0.0, 0.1, 0.25, 0.5, 0.85, 1.0, None]) .parametrize('scale', [0.001, 0.005, 0.25, 0.5, 2.0, 5.0, 100.0, 1000.0]) def test_normalized_smooth(data, smooth, scale): (x, y, xi, *_) = data x2 = ([(scale * np.array(xx, dtype=np.floa...
def run_vector_test(x, degree=1, family='CG'): m = UnitSquareMesh((2 ** x), (2 ** x)) V = VectorFunctionSpace(m, family, degree) xs = SpatialCoordinate(m) expr = (cos(((xs[0] * pi) * 2)) * sin(((xs[1] * pi) * 2))) expr = as_vector([expr, expr]) exact = Function(VectorFunctionSpace(m, 'CG', 5)) ...
def add_NodeServiceServicer_to_server(servicer, server): rpc_method_handlers = {'GetNodeSpec': grpc.unary_unary_rpc_method_handler(servicer.GetNodeSpec, request_deserializer=node__pb2.NodeSpecRequest.FromString, response_serializer=node__pb2.NodeSpecResponse.SerializeToString), 'NodeRestart': grpc.unary_unary_rpc_m...
class RefreshTests(mixins.RefreshMixin, SchemaTestCase): query = '\n mutation RefreshToken($token: String) {\n refreshToken(token: $token) {\n token\n payload\n refreshExpiresIn\n }\n }' class Mutation(graphene.ObjectType): refresh_token = graphql_jwt.Refresh.Field()
class timeit(): def __init__(self, name: str=''): self._name = name self.start_time = None self._start_wall_time = None self._start_process_time = None def __call__(self, func: Callable): (func) def wrapper(*args, **kwargs): with self: ...
class LinuxBefore(BaseClasses.BeforePass): def __init__(self, model, arch): super(LinuxBefore, self).__init__(model, arch) def process(self, parser, basepath): parser.local_vars.create_variable('composite_map', collections.defaultdict(DataStructures.Alternatives)) parser.local_vars.creat...
class Migration(migrations.Migration): dependencies = [('admin_interface', '0027_theme_list_filter_removal_links')] operations = [migrations.AddField(model_name='theme', name='show_fieldsets_as_tabs', field=models.BooleanField(default=False, verbose_name='fieldsets as tabs')), migrations.AddField(model_name='th...
def test_new_message_group(session): data = {'attachments': [], 'body': 'test', 'irisSeqId': '1111111', 'irisTags': ['DeltaNewMessage', 'is_from_iris_fanout'], 'messageMetadata': {'actorFbId': '4321', 'folderId': {'systemFolderId': 'INBOX'}, 'messageId': 'mid.$XYZ', 'offlineThreadingId': '', 'skipBumpThread': False...
def get_gasprice_recs(prediction_table, block_time, block): def get_safelow(): series = prediction_table.loc[((prediction_table['hashpower_accepting'] >= SAFELOW), 'gasprice')] safelow = series.min() return float(safelow) def get_average(): series = prediction_table.loc[((predict...
def test_publish_action(admin_client, mocker, article): from ..admin import UnPublishActionsMixin mocker.spy(UnPublishActionsMixin, 'get_inline_actions') mocker.spy(UnPublishActionsMixin, 'publish') mocker.spy(UnPublishActionsMixin, 'unpublish') assert (article.status == Article.DRAFT) article_u...
def confirm_proper_ordering(group, results): (fiscal_year, period) = (0.0, 0.0) for result in results: assert (int(result['time_period']['fiscal_year']) >= fiscal_year), 'Fiscal Year is out of order!' if (int(result['time_period']['fiscal_year']) > fiscal_year): fiscal_year = int(res...
class ProductModel(Model): class Price(float): def __str__(self): return f'{self:.2f}' products = {'milk': {'price': Price(1.5), 'quantity': 10}, 'eggs': {'price': Price(0.2), 'quantity': 100}, 'cheese': {'price': Price(2.0), 'quantity': 10}} item_type = 'product' def __iter__(self):...
class OptionPlotoptionsNetworkgraphSonificationTracksMappingPan(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 SingleSiteHamiltonianMonteCarlo(BaseInference): def __init__(self, trajectory_length: float, initial_step_size: float=1.0, adapt_step_size: bool=True, adapt_mass_matrix: bool=True, full_mass_matrix: bool=False, target_accept_prob: float=0.8, nnc_compile: bool=True, experimental_inductor_compile: bool=False): ...
(tags=['financial'], description=docs.TOTALS_INAUGURAL_DONATIONS) class InauguralDonationsView(ApiResource): model = models.InauguralDonations schema = schemas.InauguralDonationsSchema page_schema = schemas.InauguralDonationsPageSchema filter_multi_fields = [('committee_id', model.committee_id), ('cycle...
class PM(Module): w3: 'Web3' def get_package_from_manifest(self, manifest: Manifest) -> Package: return Package(manifest, self.w3) def get_package_from_uri(self, manifest_uri: URI) -> Package: return Package.from_uri(manifest_uri, self.w3) def get_local_package(self, package_name: str, e...
def ballFun(): global FUN_UPDATE, money if (money >= 50): FUN_UPDATE += int((FUN_UPDATE / 12)) money -= 50 _thread.start_new_thread(updateLabel, (3, 'You upgraded your toys!')) else: _thread.start_new_thread(updateLabel, (3, "You don't have enough money for new toys!"))
def get_imphash(file_object: FileObject) -> (str | None): if _is_elf_file(file_object): try: with _suppress_stdout(): functions = [f.name for f in lief.ELF.parse(file_object.file_path).imported_functions] if functions: return md5(','.join(sorted(functi...
def test_bias_rotation(): geom = geom_loader('lib:baker_ts/01_hcn.xyz') bonds = ((1, 2, (- 1)), (2, 0, 1)) calc = PySCF('321g', pal=2) dimer_kwargs = {'rotation_method': 'fourier', 'calculator': calc, 'bonds': bonds, 'bias_rotation': True} dimer = Dimer(**dimer_kwargs) geom.set_calculator(dimer)...
class Connection(Stateful): __slots__ = ['heartbeat', 'parameters', '_channel0', '_channels', '_io'] def __init__(self, hostname, username, password, port=5672, **kwargs): super(Connection, self).__init__() self.parameters = {'hostname': hostname, 'username': username, 'password': password, 'por...
def prepare_stderr(): with open(os.path.join(os.environ['rmtoo_test_dir'], 'stderr')) as ms: lines = ms.readlines() with open(os.path.join(os.environ['rmtoo_test_dir'], 'stderr'), 'w') as new_stderr: for line in lines: new_stderr.write(('%s' % hide_volatile(line)))
class TestMMLThreePLMethods(unittest.TestCase): def setUp(self): rng = np.random.default_rng() difficulty = np.linspace((- 1.5), 1.5, 5) discrimination = rng.uniform(0.5, 1.5, 5) thetas = rng.standard_normal(600) guessing = rng.uniform(0, 0.3, 5) syn_data = create_syn...
def test_enum(): string = write_rpc_request(1, 'initialize', {'rootPath': str(test_dir)}) file_path = str(((test_dir / 'diag') / 'test_enum.f90')) string += write_rpc_notification('textDocument/didOpen', {'textDocument': {'uri': file_path}}) (errcode, results) = run_request(string) assert (errcode =...
class ToolkitConfig(libqtile.confreader.Config): def show_menu(qtile): controls = [] for x in range(3): for y in range(3): label = f'{((y + (x * 3)) + 1)}' controls.append(PopupText(label, col=y, row=x, mouse_callbacks={'Button1': lazy.widget['textbox'].up...
_init.register_param_type _init_ack.register_param_type class param_ecn(param): def param_type(cls): return PTYPE_ECN def __init__(self, value=None, length=0): super(param_ecn, self).__init__(value, length) assert ((4 == length) or (0 == length)) assert (None is value)
def _modify(pitch_motif: PitchLine, position: Union[(int, Tuple[(int, int)])], item: Any, in_place: bool=False) -> Optional[PitchLine]: if (not in_place): pitch_motif = deepcopy(pitch_motif) if isinstance(position, int): pitch_motif[position] = item else: (i, j) = position pi...
class OptionPlotoptionsXrangeSonificationDefaultinstrumentoptionsMappingFrequency(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, te...
_meta(thbkof.THBattleKOF) class THBattleKOF(UIMetaBare): name = 'KOF' logo = 'thb-modelogo-kof' description = '<style=B></style>:ROLL,1-2-2-2-2-1\n<style=B></style>:,,,(),,4\n<style=B></style>:3,' roles = {'HIDDEN': {'name': '?', 'sprite': 'role-hidden'}, 'HAKUREI': {'name': '', 'sprite': 'role-hakurei'...
class OptionPlotoptionsBoxplotSonificationContexttracksMappingTremoloSpeed(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 _check_max_alignment(shape: IntVar, dtype: str, error_msg: str) -> None: if (not isinstance(shape, IntImm)): raise RuntimeError(f'shape={shape!r} must be IntImm! ', error_msg) res = (find_max_alignment(shape.value(), dtype) == max(get_alignments(dtype))) if (not res): raise RuntimeError(...
def test_rowclass(db): ret = db.One.insert(foo='test1', bar='test2') db.Two.insert(one=ret, foo='test1', bar='test2') ret._allocate_() assert (type(ret._refrecord) == One._instance_()._rowclass_) row = One.get(ret.id) assert (type(row) == One._instance_()._rowclass_) row = One.first() as...
def is_rlp_structured_access_list(val): if (not is_list_like(val)): return False for item in val: if (not is_list_like(item)): return False if (len(item) != 2): return False (address, storage_keys) = item if (not is_address(address)): r...
def get_gpf_string(center, size_angstrom, rec_fname, rec_types, lig_types, map_prefix=None, dielectric=(- 42), smooth=0.5, spacing=0.375, ff_param_fname=None): (size_x, size_y, size_z) = size_angstrom npts_x = (2 * int((size_x / (2 * spacing)))) npts_y = (2 * int((size_y / (2 * spacing)))) npts_z = (2 *...
class JsonSerializer(Serializer): def serialize(self, obj: Serializable) -> bytes: return json.dumps(obj.to_dict(), ensure_ascii=False).encode(JSON_ENCODING) def deserialize(self, data: bytes, cls: Type[Serializable]) -> Serializable: json_data = json.loads(data.decode(JSON_ENCODING)) ob...
class TestAutoHead(unittest.TestCase): def test_linear_head(self): import torch from video_transformers import AutoHead config = {'name': 'LinearHead', 'hidden_size': 256, 'num_classes': 10, 'dropout_p': 0.1} batch_size = 2 head = AutoHead.from_config(config) input = ...
def main(): a = ArgumentParser() a.add_argument('-a', '--analyser', metavar='AFILE', required=True, help='read analyser model from AFILE') a.add_argument('-i', '--input', metavar='INFILE', type=open, dest='infile', help='source of analysis data') a.add_argument('-v', '--verbose', action='store_true', he...
def train_ppo_for_beginners(args): if args.optimized: from ppo_for_beginners.ppo_optimized import PPO else: from ppo_for_beginners.ppo import PPO from ppo_for_beginners.network import FeedForwardNN hyperparameters = {} total_timesteps = 0 if (args.env == 'Pendulum-v1'): h...
(MASKING, response_model=MaskingAPIResponse, dependencies=[Security(verify_oauth_client_prod, scopes=[MASKING_EXEC])]) def mask_value(request: MaskingAPIRequest) -> MaskingAPIResponse: try: values: List[Any] = request.values masked_values: List[Any] = request.values.copy() masking_strategies...
class IlluminaData(): def __init__(self, illumina_analysis_dir, unaligned_dir='Unaligned'): self.analysis_dir = os.path.abspath(illumina_analysis_dir) self.projects = [] self.undetermined = None self.paired_end = False self.lanes = [] self.format = None self.u...
def gather_tests() -> Dict[(str, List[Dict[(str, Any)]])]: current_dir = os.path.dirname(os.path.abspath(__file__)) agents_dir = os.path.join(current_dir, '..', 'agents') tests = {} for agent_dir in os.listdir(agents_dir): agent_config_file = os.path.join(agents_dir, agent_dir, 'agent.yaml') ...
class GetStarredListRequest(DatClass): drive_id: str = None fields: GetStarredListFields = '*' image_thumbnail_process: str = 'image/resize,w_160/format,jpeg' image_url_process: str = field(default='image/resize,w_1920/format,jpeg', repr=False) url_expire_sec: int = field(default=14400, repr=False) ...
class OptionSeriesTimelineSonificationTracksMappingFrequency(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): sel...
def runCommand(button, pressed, plugin): logging.info(f"[buttonshim] Button Pressed! Loading command from slot '{button}' for button '{NAMES[button]}'") bCfg = plugin.options['buttons'][NAMES[button]] blinkCfg = bCfg['blink'] logging.debug(blink) if (blinkCfg['enabled'] == True): logging.deb...
def test_material_fitter(tmp_path, monkeypatch, set_api_key): fitter = DispersionFitter.from_file('tests/data/nk_data.csv', skiprows=1, delimiter=',') monkeypatch.setattr('tidy3d.web.api.material_fitter.uuid4', (lambda : 'fitter_id')) responses.add(responses.GET, f'{Env.current.web_api_endpoint}/tidy3d/fitt...
def test_interference_graph_graph_loop(construct_graph_loop, variable_v, variable_u, aliased_variable_y): (nodes, cfg) = construct_graph_loop interference_graph = InterferenceGraph(cfg) assert (set(interference_graph.nodes) == {variable_v[9], variable_v[11], variable_u[3], aliased_variable_y[1], aliased_var...
def extractPoopTranslations(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return False if ('WATTT' in item['tags']): return buildReleaseMessageWithType(item, 'WATTT', vol, chp, frag=frag, po...
class OptionPlotoptionsWindbarbTooltipDatetimelabelformats(Options): def day(self): return self._config_get('%A, %e %b %Y') def day(self, text: str): self._config(text, js_type=False) def hour(self): return self._config_get('%A, %e %b, %H:%M') def hour(self, text: str): s...
def format_cell(cell, delim=', ', **kwargs): if isinstance(cell, (list, tuple)): return delim.join(('{}'.format(c) for c in cell)) elif isinstance(cell, (dict, bool)): return json.dumps(cell) elif (cell is None): return '' elif is_number(cell): return cell else: ...
class PatchEncoder(fl.Chain): def __init__(self, in_channels: int, out_channels: int, patch_size: int, device: ((torch.device | str) | None)=None, dtype: (torch.dtype | None)=None) -> None: self.in_channels = in_channels self.out_channels = out_channels self.patch_size = patch_size s...
class Rich_IcmpType(_Rich_Element): def __init__(self, name): self.name = name def __str__(self): return ('icmp-type name="%s"' % self.name) def check(self, family=None): if ((self.name is None) or (len(self.name) < 1)): raise FirewallError(errors.INVALID_ICMPTYPE, str(se...
.parametrize('start_method,target_exec_id,monkeypatch_exec_id_env_var', [('spawn', '', False), ('spawn', 'f', True), ('fork', 'local', False)]) def test_execution_params(start_method: str, target_exec_id: str, monkeypatch_exec_id_env_var: bool, monkeypatch) -> None: if monkeypatch_exec_id_env_var: monkeypat...
class TestCli(unittest.TestCase): def test_get_parser(self) -> None: actual = cli.get_parser() self.assertIsInstance(actual, argparse.ArgumentParser) ('fbpcs.infra.cloud_bridge.cli.AwsDeploymentHelperTool') def test_main(self, mock_deployment_helper_tool: MagicMock) -> None: m_inner ...
def assert_exact_structure(expected, actual, msg=None): (missing, mismatch, mismatch_values, extra) = _check_subset_dict(expected, actual) if (missing or mismatch or extra): msg = make_error_msg_header(msg) if missing: msg = make_missing_error_message(missing, msg) if mismatc...
def split_in_sentences(string: str): sentences = [] string_no_lb = string.replace('\n', ' ') detected_language = lang_detect(string_no_lb, low_memory=False) try: try: sents = wtp.split(string, lang_code=detected_language['lang']) except: logging.info(f'WTP: could ...
def Print(*args, **kwargs): if _ignore_print: return color = kwargs.pop('__color__', 'CYAN') assert ('file' not in kwargs) f = sys.stdout try: msg = ' '.join(args) except: msg = ' '.join((str(x) for x in args)) i = msg.find(START_COLOR) while (i >= 0): wri...
class EngineManager(HasTraits): current_engine = Instance(Engine) def get_engine(self): ce = self.current_engine if (ce is not None): if ((not ce.running) or (ce not in registry.engines.values())): self.current_engine = None if (self.current_engine is not None...
class TestOSSBlobManager(unittest.TestCase): def setUpClass(cls) -> None: if (not os.path.exists(_TMP_FOLDER)): os.mkdir(_TMP_FOLDER) def tearDownClass(cls) -> None: if os.path.exists(_TMP_FOLDER): shutil.rmtree(_TMP_FOLDER) def setUp(self) -> None: file = ope...
def extractWhatifwereWordpressCom(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...
class OptionSeriesDumbbellSonificationTracksMappingVolume(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._...