code
stringlengths
281
23.7M
class VirtualExp(): def __init__(self, *args, **kwargs): self.name = kwargs['name'] self.index = kwargs['index'] self.exp = kwargs['exp'] self.elm = kwargs['elm'] self.blk = kwargs['blk'] self.pc = kwargs['pc'] def __repr__(self): if isinstance(self.exp, l...
def get_solar_capacity_au_nt(target_datetime: datetime) -> (float | None): session = Session() capacity_df = get_opennem_capacity_data(session) capacity_df = filter_capacity_data_by_datetime(capacity_df, target_datetime) capacity_df = capacity_df.loc[(capacity_df['zone_key'] == 'NT1')] capacity_df['...
def gen_methods_text_str(model_obj=None): template = "The periodic & aperiodic spectral parameterization algorithm (version {}) was used to parameterize neural power spectra. Settings for the algorithm were set as: peak width limits : {}; max number of peaks : {}; minimum peak height : {}; peak threshold : {}; and ...
class Data(models.Model): device = models.ForeignKey(Device, related_name='device_data', on_delete=models.CASCADE) field_1 = models.CharField(_('Deger 1'), max_length=10, null=True, blank=False) field_2 = models.CharField(_('Deger 2'), max_length=10, null=True, blank=False) field_3 = models.CharField(_(...
def test_span_labelling(elasticapm_client): elasticapm_client.begin_transaction('test') with elasticapm.capture_span('test', labels={'foo': 'bar', 'ba.z': 'baz.zinga'}) as span: span.label(lorem='ipsum') elasticapm_client.end_transaction('test', 'OK') span = elasticapm_client.events[SPAN][0] ...
def offset_to_line(source_code, bytecode_offset, source_mapping): srcmap_runtime_mappings = source_mapping[0].split(';') srcmap_mappings = source_mapping[1].split(';') mappings = None if ((bytecode_offset < 0) or (len(srcmap_mappings) <= bytecode_offset)): if ((bytecode_offset < 0) or (len(srcma...
(scope='class', autouse=True) def aea_testcase_teardown_check(request): from aea.test_tools.test_cases import BaseAEATestCase (yield) if (request.cls and issubclass(request.cls, BaseAEATestCase) and (getattr(request.cls, '_skipped', False) is False)): assert getattr(request.cls, '_is_teardown_class_...
def test_unconditional_node(): graph = ControlFlowGraph() graph.add_nodes_from((vertices := [BasicBlock(0, []), BasicBlock(1, [])])) graph.add_edges_from([UnconditionalEdge(vertices[0], vertices[1])]) t_cfg = TransitionCFG.generate(graph) true_condition = LogicCondition.initialize_true(LogicConditio...
class CmdCdestroy(CmdChannel): key = 'cdestroy' aliases = [] help_category = 'Comms' locks = 'cmd: not pperm(channel_banned)' account_caller = True def func(self): caller = self.caller if (not self.args): self.msg('Usage: cdestroy <channelname>') return ...
() _context _type_argument _key_argument _analytics def delete(ctx: click.Context, resource_type: str, fides_key: str) -> None: config = ctx.obj['CONFIG'] handle_cli_response(_api.delete(url=config.cli.server_url, resource_type=resource_type, resource_id=fides_key, headers=config.user.auth_header), verbose=Fals...
class BaseFixedEncoder(NumberEncoder): frac_places = None def type_check_fn(value): return (is_number(value) and (not isinstance(value, float))) def illegal_value_fn(value): if isinstance(value, decimal.Decimal): return (value.is_nan() or value.is_infinite()) return False...
class _Date(PythonDataType): def cast_from(self, obj): if isinstance(obj, str): try: return datetime_parse.parse_date(obj) except datetime_parse.DateTimeError: raise TypeMismatchError(obj, self) return super().cast_from(obj)
def _fuse_single_source_parallel_gemms(sorted_graph: List[Tensor]) -> Tuple[(bool, List[Tensor])]: _fusing_ops = {'gemm_rcr', 'gemm_rcr_bias'} for tensor in sorted_graph: fusion_groups = {} for dst in tensor.dst_ops(): op_type = dst._attrs['op'] if (op_type in _fusing_ops...
def extractWhitedovetranslationsWordpressCom(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, na...
class _DefaultWorkerManagerFactory(WorkerManagerFactory): def __init__(self, system_app: (SystemApp | None)=None, worker_manager: WorkerManager=None): super().__init__(system_app) self.worker_manager = worker_manager def create(self) -> WorkerManager: return self.worker_manager
class EngineState(Entity): INFO = {'make': [], 'initialize': [], 'reset': []} def __init__(self, ns, name, simulator, backend, params): self.ns = ns self.name = name self.color = 'grey' self.backend = backend from eagerx.core.specs import EngineStateSpec self.init...
class SearchFilterLayer(SqlalchemyDataLayer): def filter_query(self, query, filter_info, model): without_fulltext = [f for f in filter_info if (f['op'] != 'search')] if (not without_fulltext): return query return super().filter_query(query, without_fulltext, model)
def faba_with_object_class_and_two_awards(award_count_sub_schedule, award_count_submission, defc_codes): basic_object_class = major_object_class_with_children('001', [1]) award1 = _normal_award(156) award2 = _normal_award(212) baker.make('awards.FinancialAccountsByAwards', parent_award_id='basic award 1...
class OptionSeriesPieSonificationTracksMappingTremoloSpeed(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 reiterable(_coconut_has_iter): __slots__ = () def __new__(cls, iterable): if _coconut.isinstance(iterable, _coconut.reiterables): return iterable return _coconut.super(reiterable, cls).__new__(cls, iterable) def get_new_iter(self): (self.iter, new_iter) = tee(self.i...
def test_slave_chat_update_member(bot_group, slave, channel): (added, edited, removed) = slave.send_member_update_status() group = added.chat chat_manager = channel.chat_manager group_key = chat_manager.get_cache_key(group) assert (group_key in chat_manager.cache) group_cache = chat_manager.cach...
def markTightParagraphs(state: StateBlock, idx: int) -> None: level = (state.level + 2) i = (idx + 2) length = (len(state.tokens) - 2) while (i < length): if ((state.tokens[i].level == level) and (state.tokens[i].type == 'paragraph_open')): state.tokens[(i + 2)].hidden = True ...
class Filters(Html.Html): name = 'Filters' requirements = (cssDefaults.ICON_FAMILY,) _option_cls = OptList.OptionsTagItems def __init__(self, page: primitives.PageModel, items, width, height, html_code, helper, options, profile, verbose: bool=False): super(Filters, self).__init__(page, items, ht...
def _init_4bit_linear(source: Module, config: Union[(_8BitConfig, _4BitConfig)], device: torch.device) -> 'bnb.nn.Linear4bit': assert isinstance(config, _4BitConfig) import bitsandbytes as bnb quantized_module = bnb.nn.Linear4bit(input_features=source.in_features, output_features=source.out_features, bias=(...
def test_augmented_assignment_broadcast(): mesh = UnitSquareMesh(1, 1) V = FunctionSpace(mesh, 'BDM', 1) u = Function(V) a = Constant(1) b = Constant(2) u.assign(a) assert np.allclose(u.dat.data_ro, 1) u *= (- (a + b)) assert np.allclose(u.dat.data_ro, (- 3)) u += (b * 2) ass...
class OptionSeriesScatter3dData(Options): def accessibility(self) -> 'OptionSeriesScatter3dDataAccessibility': return self._config_sub_data('accessibility', OptionSeriesScatter3dDataAccessibility) def className(self): return self._config_get(None) def className(self, text: str): self...
class OptionPlotoptionsVariablepieSonificationDefaultspeechoptionsMappingVolume(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...
_os(*metadata.platforms) def main(): masquerade = '/tmp/bash' common.copy_macos_masquerade(masquerade) common.log('Launching fake osascript commands to mimic apple script execution') command = 'osascript with administrator privileges' common.execute([masquerade, 'childprocess', command], shell=True,...
(PRIVACY_REQUEST_TRANSFER_TO_PARENT, status_code=HTTP_200_OK, dependencies=[Security(verify_oauth_client, scopes=[PRIVACY_REQUEST_TRANSFER])], response_model=Dict[(str, Optional[List[Row]])]) def privacy_request_data_transfer(*, privacy_request_id: str, rule_key: str, db: Session=Depends(deps.get_db), cache: FidesopsRe...
def mark_item_unwatched(item_id): log.debug('Mark Item UnWatched: {0}', item_id) url = ('{server}/emby/Users/{userid}/PlayedItems/' + item_id) downloadUtils.download_url(url, method='DELETE') check_for_new_content() home_window = HomeWindow() last_url = home_window.get_property('last_content_url...
def test_to_python_value_and_literal(): ctx = context_manager.FlyteContext.current_context() tf = NumpyArrayTransformer() python_val = np.array([1, 2, 3]) lt = tf.get_literal_type(np.ndarray) lv = tf.to_literal(ctx, python_val, type(python_val), lt) assert (lv.scalar.blob.metadata == BlobMetadat...
def gen_subfile(pkt_bits, note='x10 command', repeat=1): datalines = [] for bits in pkt_bits: data = [9000, (- 4500)] for bit in bits: if (bit == '1'): data.extend((562, (- 1688))) else: data.extend((562, (- 563))) data.extend((562,...
class DQN(): def __init__(self, config, create_env, create_agent): self.config = config self.logger = TFLogger(log_dir=self.config['logdir'], hps=self.config, save_every=self.config['save_every']) self._create_env = create_env self._create_agent = create_agent def _state_dict(sel...
def type_text(data): if (keepmenu.CLIPBOARD is True): type_clipboard(data) return library = 'pynput' if keepmenu.CONF.has_option('database', 'type_library'): library = keepmenu.CONF.get('database', 'type_library') if (library == 'xdotool'): call(['xdotool', 'type', '--', ...
class limits_property(): def __init__(self, minimum_attribute_name, maximum_attribute_name): super().__init__() self._minimum_attribute_name = minimum_attribute_name self._maximum_attribute_name = maximum_attribute_name def __get__(self, instance, owner): return (getattr(instance...
.LinearSolvers def test_step_noslip_FullRun(): petsc_options = initialize_petsc_options context_options_str = "boundary_condition_type='ns'" ns = load_simulation(context_options_str) actual_log = runTest(ns, 'test_2') L1 = actual_log.get_ksp_resid_it_info([(' step2d ', 1.0, 0, 0)]) L2 = actual_l...
class OptionSeriesNetworkgraphSonificationDefaultinstrumentoptionsMapping(Options): def frequency(self) -> 'OptionSeriesNetworkgraphSonificationDefaultinstrumentoptionsMappingFrequency': return self._config_sub_data('frequency', OptionSeriesNetworkgraphSonificationDefaultinstrumentoptionsMappingFrequency) ...
class StarSubmissionResult(object): codeMap = {201: 'New Entry', 202: 'System CR increased', 203: 'Coordinates calculated', 301: 'Distance added', 302: 'Distance CR increased', 303: 'Added verification', 304: 'OK: Needs more data', 305: 'Distance appears to be wrong', 401: 'CALCULATED', 402: 'No solution found, mor...
def test_get_surfaces_from_3dgrid(tmpdir): mygrid = xtgeo.grid_from_file(TESTSETG1) surfs = xtgeo.surface.surfaces.surfaces_from_grid(mygrid, rfactor=2) surfs.describe() assert (surfs.surfaces[(- 1)].values.mean() == pytest.approx(1742.28, abs=0.04)) assert (surfs.surfaces[(- 1)].values.min() == pyt...
def validate_model(model, val_loader): print('Validating the model') model.eval() y_true = [] y_pred = [] with torch.no_grad(): for (step, (x, mel)) in enumerate(val_loader): if (step < 15): (x, mel) = (Variable(x).cuda(), Variable(mel).cuda()) log...
class LocalFilePreferredNamesPreference(widgets.Preference, widgets.CheckConditional): default = ['front', 'cover', 'album'] name = 'covers/localfile/preferred_names' condition_preference_name = 'covers/use_localfile' def __init__(self, preferences, widget): widgets.Preference.__init__(self, pre...
class OptionPlotoptionsCylinderSonificationContexttracksMappingLowpassResonance(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 GetNodeDataTracker(BasePerformanceTracker[(GetNodeDataV65, NodeDataBundles)]): def _get_request_size(self, request: GetNodeDataV65) -> Optional[int]: return len(request.payload) def _get_result_size(self, result: NodeDataBundles) -> int: return len(result) def _get_result_item_count(se...
class ElementConstantNewton(proteus.NonlinearSolvers.NonlinearSolver): def __init__(self, linearSolver, F, J=None, du=None, par_du=None, rtol_r=0.0001, atol_r=1e-16, rtol_du=0.0001, atol_du=1e-16, maxIts=100, norm=l2Norm, convergenceTest='r', computeRates=True, printInfo=True, fullNewton=True, directSolver=False, E...
class TestQCSampleForSolid(unittest.TestCase): def setUp(self): self.d = TestUtils.make_dir() for f in SOLID_FILES.split(): TestUtils.make_file(f, 'lorem ipsum', basedir=self.d) self.qc_dir = TestUtils.make_sub_dir(self.d, 'qc') for f in SOLID_QC_FILES.split(): ...
def find_app_module(): (rv, files, dirs) = (None, [], []) for path in os.listdir(): if any((path.startswith(val) for val in ['.', 'test'])): continue if os.path.isdir(path): if (not path.startswith('_')): dirs.append(path) continue (_, ...
class HtmlStates(): def loading(self, status: bool=True, label: str=None, data: types.JS_DATA_TYPES=None): if (label is not None): self.options.templateLoading = label if (self.options.templateLoading is None): self.options.templateLoading = Default_html.TEMPLATE_LOADING_ONE_...
def test_get_final_config_bibtex(data_regression): cli_config = {'latex_individualpages': False} user_config = {'bibtex_bibfiles': ['tmp.bib']} (final_config, metadata) = get_final_config(user_yaml=user_config, cli_config=cli_config, validate=True, raise_on_invalid=True) assert ('sphinxcontrib.bibtex' i...
def flag_cutpaste_candidates(insertion_from_signature_clusters, deletion_signature_clusters, options): int_duplication_candidates = [] for ins_cluster in insertion_from_signature_clusters: distances = [(del_index, span_position_distance_clusters(del_cluster, ins_cluster, options.position_distance_normal...
class OptionSeriesScatterDataDragdrop(Options): def draggableX(self): return self._config_get(None) def draggableX(self, flag: bool): self._config(flag, js_type=False) def draggableY(self): return self._config_get(None) def draggableY(self, flag: bool): self._config(flag,...
class NCSOConcessionBookmark(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) pct = models.ForeignKey(PCT, null=True, blank=True, on_delete=models.PROTECT) practice = models.ForeignKey(Practice, null=True, blank=True, on_delete=models.PROTECT) created_at = models.DateTimeField(aut...
class EditForumForm(ForumForm): id = HiddenField() def __init__(self, forum, *args, **kwargs): self.forum = forum kwargs['obj'] = self.forum ForumForm.__init__(self, *args, **kwargs) def save(self): data = self.data data.pop('submit', None) data.pop('csrf_toke...
class FipaHandler(Handler): SUPPORTED_PROTOCOL = FipaMessage.protocol_id def setup(self) -> None: def handle(self, message: Message) -> None: fipa_msg = cast(FipaMessage, message) fipa_dialogues = cast(FipaDialogues, self.context.fipa_dialogues) fipa_dialogue = cast(FipaDialogue, fip...
class TestMappedUnion(unittest.TestCase): def test_no_mapped(self): no_mapped = MappedUnion(Int, Float) self.assertFalse(no_mapped.is_mapped) self.assertIsNone(no_mapped.post_setattr) def test_mapped(self): mapped = MappedUnion(None, Str, Map({'yes': True, 'no': False})) ...
class SimpleValuesBuilderTest(unittest.TestCase): def test_build_string(self): value = build_value('some string', str, False) self.assertEqual(value, 'some string') value = build_value('"some string"', str, True) self.assertEqual(value, 'some string') def test_build_int(self): ...
class MicrosoftGraphOAuth2(BaseOAuth2[Dict[(str, Any)]]): display_name = 'Microsoft' logo_svg = LOGO_SVG def __init__(self, client_id: str, client_secret: str, tenant: str='common', scopes: Optional[List[str]]=BASE_SCOPES, name: str='microsoft'): access_token_endpoint = ACCESS_TOKEN_ENDPOINT.format(...
def get_remote_file_url(file_path: str, full_name: str, repo_url: str) -> str: if Path(repo_url).exists(): return GitService.LOCAL.file_url.format(file_path=file_path) for service in GitService: if (service.host in repo_url): return service.file_url.format(full_name=full_name, file_p...
class TestDSLMemoizedBeforeAttribute(TestDSLBase): def test_memoize_before_attribute(self): mock = Mock() def top(context): value = 1 memoized = [] _before def attribute_name(self): memoized.append(True) return (value + ...
def div_cc_c(gen, t, srcs): denom = cmag_c_f(gen, 'mag', [srcs[1]]) ac = gen.emit_binop('*', [srcs[0].re, srcs[1].re], Float) bd = gen.emit_binop('*', [srcs[0].im, srcs[1].im], Float) bc = gen.emit_binop('*', [srcs[0].im, srcs[1].re], Float) ad = gen.emit_binop('*', [srcs[0].re, srcs[1].im], Float) ...
class WatchDog(multiprocessing.Process): def __init__(self, timeout=30): multiprocessing.Process.__init__(self) self.timeout = timeout def run(self): try: while True: if ping.wait(self.timeout): ping.clear() else: ...
class GameRunner(Greenlet): def _run(self) -> None: raise GameError('Abstract') def user_input(self, entities: Sequence[Any], inputlet: Inputlet, timeout: int=25, type: str='single', trans: Optional[InputTransaction]=None): raise GameError('Abstract') def is_aborted(self) -> bool: ra...
class GroupTaggerPlugin(): def get_preferences_pane(self): return gt_prefs def enable(self, exaile): self.exaile = exaile def on_gui_loaded(self): self.track = None self.tag_dialog = None migrate_settings() self.panel = gt_widgets.GroupTaggerPanel(self.exaile)...
class ImageStoreView(APIView): dc_bound = False HTTP_TIMEOUT = 20 HTTP_MAX_SIZE = LOCK_KEY = 'imagestore-update' def __init__(self, request, name, data, many=False): super(ImageStoreView, self).__init__(request) self.data = data self.name = name self.many = many ...
class TestSyncFedShuffleServers(): def _fake_data(self, num_batches=3, batch_size=2, rng: Optional[torch.Generator]=None): dataset = [torch.rand(batch_size, 2, generator=rng) for _ in range(num_batches)] dataset = utils.DatasetFromList(dataset) return utils.DummyUserData(dataset, utils.Sampl...
class Perm021FCCCRTestCase(unittest.TestCase): def _test_perm021fc_ccr(self, test_name='perm021fc_ccr', dtype='float16'): B = 1024 M = 128 K = 745 N = 30 target = detect_target() X = Tensor(shape=[B, K, M], dtype=dtype, name='input_0', is_input=True) W = Tenso...
class ResourceScanner(base_scanner.BaseScanner): def __init__(self, global_configs, scanner_configs, service_config, model_name, snapshot_timestamp, rules): super(ResourceScanner, self).__init__(global_configs, scanner_configs, service_config, model_name, snapshot_timestamp, rules) self.rules_engine...
class MySource(Node): A = Topic(MyMessage1) def __init__(self) -> None: super(MySource, self).__init__() (A) async def source(self) -> AsyncPublisher: for i in range(NUM_MESSAGES): (yield (self.A, MyMessage1(int_field=i))) (await asyncio.sleep((1 / SAMPLE_RATE)))
class WindowsEnableNewAdapterDisrupter(Disrupter): def __init__(self, device, parameters): super().__init__(device, parameters) self._restrict_parameters(must_disrupt=True, must_restore=False) self._primary_adapter = self._find_primary_adapter() def _find_primary_adapter(self): p...
def db_migrate_speaker_doc(db): conn = db.engine.connect() cursor = conn.execute('SELECT * from sessions') dict = [] for row in cursor: dict.append({'name': row['title'], 'link': row['slides_url']}) data = f"'{json.dumps(dict)}'" id = row['id'] conn.execute(f'UPDATE sessi...
class OptionPlotoptionsPyramid3dSonificationDefaultspeechoptionsMappingTime(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: st...
.parametrize('solver', [quartic.QuarticSolver.NUMERIC, quartic.QuarticSolver.HYBRID]) def test_almost_touching_ball_ball_collision(solver: quartic.QuarticSolver): template = System(cue=Cue.default(), table=(table := Table.default()), balls={'1': (ball := Ball.create('1', xy=((table.w / 2), (table.l / 2)))), 'cue': ...
def _ipython(local, banner): from IPython.terminal.embed import InteractiveShellEmbed from IPython.terminal.ipapp import load_default_config InteractiveShellEmbed.clear_instance() shell = InteractiveShellEmbed.instance(banner1=banner, user_ns=local, config=load_default_config()) shell()
class TestImportHelpers(unittest.TestCase): def test_allowed_file(self): request_filename = 'test.pdf' request_extensions = ['pdf', 'zip'] actual_response = _allowed_file(request_filename, request_extensions) self.assertTrue(actual_response) request_filename = 'test.pdf' ...
class AdCampaignDeliveryStatsUnsupportedReasons(AbstractObject): def __init__(self, api=None): super(AdCampaignDeliveryStatsUnsupportedReasons, self).__init__() self._isAdCampaignDeliveryStatsUnsupportedReasons = True self._api = api class Field(AbstractObject.Field): reason_data...
def main(data_source): pipeline = FairMarketcapSF1(pretrained=False, data_source=data_source) base_df = pipeline.data['base'].load() tickers = base_df[((base_df['currency'] == CURRENCY) & base_df['scalemarketcap'].apply((lambda x: (x in SCALE_MARKETCAP))))]['ticker'].values result = pipeline.fit(tickers...
class OptionSeriesColumnSonificationContexttracksMappingPan(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...
def create_extraction_chain(llm: BaseLanguageModel, node: Object, *, encoder_or_encoder_class: Union[(Type[Encoder], Encoder, str)]='csv', type_descriptor: Union[(TypeDescriptor, str)]='typescript', validator: Optional[Validator]=None, input_formatter: InputFormatter=None, instruction_template: Optional[PromptTemplate]...
def _construct_shape(shape: List[List[int]], input_number: int) -> Tuple[(List[IntVar], List[Optional[str]])]: result = [] dim_names = [] num_dynamic = 0 for dim in shape: dim_name = None if (len(dim) == 1): result.append(IntImm(dim[0])) else: dim_name = f...
class Compose(): def __init__(self, project_name: str, env_file: str): self.project_name = project_name self.base_cmd = ('docker', 'compose', '-p', project_name, '--env-file', env_file) def __call__(self, *cmd: str) -> None: file_args = ['-f', 'compose.yaml', '-f', 'overrides/compose.pro...
def build_ordered_output_actions(acl_table, output_list, tunnel_rules=None, source_id=None): output_actions = [] output_ports = [] output_ofmsgs = [] output_inst = [] for action in output_list: for (key, value) in action.items(): if (key == 'pop_vlans'): for _ in ...
class OptionPlotoptionsBubbleSonificationTracksMappingPan(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 paramTimer(): elapsedTimeNS: float = 0.0 def reset(self, newTime: float=0.0) -> None: self.elapsedTimeNS = newTime def incrTimeNS(self, timeNS: float) -> None: self.elapsedTimeNS += timeNS def getTimeUS(self) -> float: return (self.elapsedTimeNS / 1000.0) def getTimeNS(...
class IntroRoom(TutorialRoom): def at_object_creation(self): super().at_object_creation() self.db.tutorial_info = 'The first room of the tutorial. This assigns the health Attribute to the account.' def at_object_receive(self, character, source_location, move_type='move', **kwargs): healt...
def breathing_led(mc, duration): min_brightness = 0 max_brightness = 255 speed = 0.02 period = (2 * math.pi) while True: start_time = time.time() while ((time.time() - start_time) < duration): elapsed_time = (time.time() - start_time) phase = ((((elapsed_time ...
class OptionSeriesAreaLabelStyle(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, js_ty...
def test_no_opts(): runner = CliRunner() result = runner.invoke(pipeline) assert ('run Run a pipeline in your local environment' in result.output) assert ('submit Submit a pipeline to be executed on the server' in result.output) assert ('describe Display pipeline summary' in result.output)...
def test_sa(): K = bytearray.fromhex('10f2e5d6c9a2630580a960856f66b029') C_S = bytearray.fromhex('b0bc5f422f00c64c38e') C_M = bytearray.fromhex('a79060aa4f4638d907e261b4a5a3c612') BTADD_S = bytearray.fromhex('404e36a8bf5f') BTADD_M = bytearray.fromhex('20819A076931') SRES_S = bytearray.fromhex('...
.parametrize('lang', wikiquote.supported_languages()) def test_qotd_author(lang): try: (_, author) = wikiquote.quote_of_the_day(lang=lang) except wikiquote.MissingQOTDException: pytest.skip('No QOTD for {lang}'.format(lang=lang)) assert isinstance(author, str) assert (len(author) > 0)
(firedrake.MixedVectorSpaceBasis) def coarsen_mixedvectorspacebasis(mspbasis, self, coefficient_mapping=None): coarse_V = self(mspbasis._function_space, self, coefficient_mapping=coefficient_mapping) coarse_bases = [] for basis in mspbasis._bases: if isinstance(basis, firedrake.VectorSpaceBasis): ...
def badge_role(role, rawtext, text, lineno, inliner, options={}, content=[]): try: (args, kwargs) = string_to_func_inputs(text) (text, classes) = get_badge_inputs(*args, **kwargs) except Exception as err: msg = inliner.reporter.error(f'badge input is invalid: {err}', line=lineno) ...
class RuleDecoratorMeta(type): def __new__(metaclass, name, bases, namespace): def unvisit(name): return (name[6:] if name.startswith('visit_') else name) methods = [v for (k, v) in namespace.items() if (hasattr(v, '_rule') and isfunction(v))] if methods: from parsimo...
def test_workflow_execution_data_response(): input_blob = _common_models.UrlBlob('in', 1) output_blob = _common_models.UrlBlob('out', 2) obj = _execution.WorkflowExecutionGetDataResponse(input_blob, output_blob, _INPUT_MAP, _OUTPUT_MAP) obj2 = _execution.WorkflowExecutionGetDataResponse.from_flyte_idl(o...
def guess_own_iface(match_ips): if (len(match_ips) == 0): return None for iface in ni.interfaces(): ifa = ni.ifaddresses(iface) if ((ni.AF_LINK not in ifa) or (len(ifa[ni.AF_LINK]) == 0)): logging.debug('{} is has no MAC address, skipped.'.format(iface)) continue ...
class EngineGraph(): def __init__(self, state: Dict): self._state = state def __str__(self): return yaml.dump(self._state) def create(cls, actuators: Optional[List[Dict]]=None, sensors: Optional[List[Dict]]=None): nodes = [] from eagerx.core.entities import EngineNode ...
def exec_composed_command(command: str, line_objs: List[LineMatch]) -> None: if (not command): edit_files(line_objs) return logger.add_event('command_on_num_files', len(line_objs)) command = compose_command(command, line_objs) append_alias_expansion() append_if_invalid(line_objs) ...
class Node_Monitoring(PrometheusNodeMetrics): def __init__(self): super().__init__() self.dashboards = ['default', 'pvc'] def list_dashboards(self): print(self.dashboards) def display_dashboard(self, dashboard, node_name): if (dashboard not in self.dashboards): pr...
def _handle_error_while_loading_component_generic_error(configuration: ComponentConfiguration, e: Exception) -> None: e_str = parse_exception(e) raise AEAPackageLoadingError('Package loading error: An error occurred while loading {} {}: {}'.format(str(configuration.component_type), configuration.public_id, e_st...
def extractTaidatranslationsWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('Nightmare Game', 'Nightmare Game', 'translated'), ('Escape the Chamber', 'Escape the Ch...
.parametrize('key_encoding', (compute_extension_key, compute_leaf_key)) def test_TraversedPartialPath_keeps_node_value(key_encoding): node_key = (0, 15, 9) untraversed_tail = node_key[:1] remaining_key = node_key[1:] node_value = b'unicorns' node = annotate_node([key_encoding(node_key), node_value])...
class FileField(Field): default_error_messages = {'required': _('No file was submitted.'), 'invalid': _('The submitted data was not a file. Check the encoding type on the form.'), 'no_name': _('No filename could be determined.'), 'empty': _('The submitted file is empty.'), 'max_length': _('Ensure this filename has ...