code
stringlengths
281
23.7M
def get_and_load_typeclasses(parent=None, excluded_parents=None): import evennia evennia._init() tmap = get_all_typeclasses(parent=parent) excluded_parents = (excluded_parents or []) tpaths = [path for (path, tclass) in tmap.items() if (not any((inherits_from(tclass, excl) for excl in excluded_paren...
class ReturningHandler(THBEventHandler): interested = ['action_before'] def handle(self, evt_type, act): if ((evt_type == 'action_before') and isinstance(act, PrepareStage)): tgt = act.target if (not tgt.has_skill(Returning)): return act g = self.game ...
class _01_LinuxExpandMacros(BaseClasses.AfterPass): regex_base = re.compile('([A-Za-z0-9,_-]+)\\.o|\\$\\(([A-Za-z0-9,_-]+)\\)') def __init__(self, model, arch): super(_01_LinuxExpandMacros, self).__init__(model, arch) def expand_macro(self, name, path, condition, already_expanded, parser, maxdepth=3...
class OptionSeriesColumnSonificationDefaultspeechoptionsMappingPitch(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('undefined') def mapTo(self, text: st...
class RangeSlider(ConstrainedControl): def __init__(self, start_value: [float], end_value: [float], ref: Optional[Ref]=None, key: Optional[str]=None, width: OptionalNumber=None, height: OptionalNumber=None, left: OptionalNumber=None, top: OptionalNumber=None, right: OptionalNumber=None, bottom: OptionalNumber=None,...
() ('--local-dir', default='./tmp/diffusers-pipeline/stabilityai/stable-diffusion-v2', help='the local diffusers pipeline directory') ('--width', default=512, help='Width of generated image') ('--height', default=512, help='Height of generated image') ('--prompt', default='A fantasy landscape, trending on artstation', ...
class AmazonApi(ProviderInterface, AmazonOcrApi, AmazonAudioApi, AmazonImageApi, AmazonTextApi, AmazonTranslationApi, AmazonVideoApi): provider_name = 'amazon' def __init__(self, api_keys: Dict={}) -> None: self.api_settings = load_provider(ProviderDataEnum.KEY, 'amazon', api_keys=api_keys) self...
.usefixtures('use_tmpdir') def test_template_multiple_input(): with open('template', 'w', encoding='utf-8') as template_file: template_file.write(mulitple_input_template) with open('parameters.json', 'w', encoding='utf-8') as json_file: json_file.write(json.dumps(default_parameters)) with op...
class TestDependencyManager(): def setup(self): self.deps = DependencyManager([SecretDependency(), ServiceDependency(), IngressClassesDependency()]) def test_cyclic(self): a = self.deps.for_instance(object()) b = self.deps.for_instance(object()) c = self.deps.for_instance(object(...
def send_installation_email(event_name, postinstall_email, attendee): email = EmailMultiAlternatives() first_name = attendee.first_name last_name = attendee.last_name email.subject = get_installation_subject(first_name, last_name, event_name) email.from_email = postinstall_email.contact_email em...
_module() class ISTFTNet(pl.LightningModule): def __init__(self, checkpoint_path: str='checkpoints/istft_net/g_', config_file: Optional[str]=None, use_natural_log: bool=True, **kwargs): super().__init__() if (config_file is None): config_file = (Path(checkpoint_path).parent / 'config.jso...
def print_cid_info(buttons): cnt = buttons.get_count() cids = [] print('### CID INFO ###') print(' CID TID virtual persist divert reprog fntog hotkey fkey mouse pos group gmask rawXY') for i in range(cnt): cid_info = buttons.get_cid_info(i) cids += [cid_info['cid']] ...
def fortios_log_tacacsplusaccounting(data, fos): fos.do_member_operation('log.tacacs+accounting', 'setting') if data['log_tacacsplusaccounting_setting']: resp = log_tacacsplusaccounting_setting(data, fos) else: fos._module.fail_json(msg=('missing task body: %s' % 'log_tacacsplusaccounting_se...
def add_to_sent(analyses, surf): global sent tags = set() for analysis in analyses: parts = analysis[0].split('][') for part in parts: tag = part.rstrip(']').lstrip('[') tags.add(tag) tags.add(('SURF=' + surf)) sent.append(tags) if ('BOUNDARY=SENTENCE'...
def fade_in(main, exaile): logger.debug('fade_in() called.') temp_volume = (settings.get_option('plugin/multialarmclock/fade_min_volume', 0) / 100.0) fade_max_volume = (settings.get_option('plugin/multialarmclock/fade_max_volume', 100) / 100.0) fade_inc = (settings.get_option('plugin/multialarmclock/fad...
def info(patch, fsize): fpatch = BytesIO(patch) (data_pointers_blocks_present, code_pointers_blocks_present, data_pointers_header, code_pointers_header, from_data_offset, from_data_begin, from_data_end, from_code_begin, from_code_end) = unpack_pointers_header(fpatch) bw_header = Blocks.unpack_header(fpatch)...
class TestBenchmarks(unittest.TestCase): def test_lists_vs_dicts(self): list_time = timeit('item = l[9000]', 'l = [0] * 10000') dict_time = timeit('item = d[9000]', 'd = {x: 0 for x in range(10000)}') self.assertTrue((list_time < dict_time), ('%s < %s' % (list_time, dict_time))) def test...
class proj_spsd(proj): def __init__(self, **kwargs): super(proj_spsd, self).__init__(**kwargs) def _prox(self, x, T): isreal = np.isreal(x).all() sol = ((x + np.conj(x.T)) / 2) (D, V) = np.linalg.eig(sol) D = np.real(D) if isreal: V = np.real(V) ...
def DoRearrangeDim(decl_cursor, permute_vector): decl_s = decl_cursor._node assert isinstance(decl_s, (LoopIR.Alloc, LoopIR.fnarg)) all_permute = {decl_s.name: permute_vector} def permute(buf, es): permutation = all_permute[buf] return [es[i] for i in permutation] def check_permute_w...
class TestRecoveryStats(): ('esrally.metrics.EsMetricsStore.put_doc') def test_no_metrics_if_no_pending_recoveries(self, metrics_store_put_doc): response = {} cfg = create_config() metrics_store = metrics.EsMetricsStore(cfg) client = Client(indices=SubClient(recovery=response)) ...
class BackupStatus(object): UNDEFINED = (- 1) RUNNING = 1 COMPLETED = 2 CANCELLED = 3 INTERRUPTED = 4 FAILED = 5 RESTORED = 6 ALL = 999 text = {UNDEFINED: 'undefined', RUNNING: 'running', COMPLETED: 'completed', CANCELLED: 'cancelled', INTERRUPTED: 'interrupted', FAILED: 'failed', RE...
def fence_generic_format(math, language='math', class_name='arithmatex', options=None, md=None, wrap='\\[\n%s\n\\]', **kwargs): classes = kwargs['classes'] id_value = kwargs['id_value'] attrs = kwargs['attrs'] classes.insert(0, class_name) id_value = (' id="{}"'.format(id_value) if id_value else '')...
def extractPerpetualdaydreamsCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('iwal', 'I Won a Lottery So I Moved to the Other World', 'translated'), ('fpyq', 'Fei Pin Ying Q...
def _format_html_time_tag(datetime, what_to_display): if (what_to_display == 'date-only'): content = babel_format_date(datetime, locale=_get_user_locale()) elif (what_to_display == 'time-only'): content = babel_format_time(datetime, format='short', locale=_get_user_locale()) elif (what_to_di...
class User(auth_models.User): class Meta(): proxy = True verbose_name = '' verbose_name_plural = '' token_signer = itsdangerous.TimestampSigner(settings.SECRET_KEY) def token(self): data = base64.b64encode(msgpack.dumps({'type': 'user', 'id': self.id})) return self.to...
def use_androguard(): try: import androguard if use_androguard.show_path: logging.debug(_('Using androguard from "{path}"').format(path=androguard.__file__)) use_androguard.show_path = False if (options and options.verbose): logging.getLogger('androguard.a...
def checksum_by_chunk(table_name, columns, pk_list, range_start_values, range_end_values, chunk_size, using_where, force_index: str='PRIMARY') -> str: if using_where: row_range = get_range_start_condition(pk_list, range_start_values) where_clause = ' WHERE {} '.format(row_range) else: wh...
class DummyNonRetryableStageFlow(PrivateComputationBaseStageFlow): CREATED = PrivateComputationStageFlowData(initialized_status=PrivateComputationInstanceStatus.CREATION_INITIALIZED, started_status=PrivateComputationInstanceStatus.CREATION_STARTED, completed_status=PrivateComputationInstanceStatus.CREATED, failed_s...
class TTVisitorTest(object): def getpath(testfile): path = os.path.dirname(__file__) return os.path.join(path, 'data', testfile) def test_ttvisitor(self): font = TTFont(self.getpath('TestVGID-Regular.otf')) visitor = TestVisitor() visitor.visit(font, 1) assert (le...
def add_QueryServicer_to_server(servicer, server): rpc_method_handlers = {'Allowance': grpc.unary_unary_rpc_method_handler(servicer.Allowance, request_deserializer=cosmos_dot_feegrant_dot_v1beta1_dot_query__pb2.QueryAllowanceRequest.FromString, response_serializer=cosmos_dot_feegrant_dot_v1beta1_dot_query__pb2.Quer...
class Mode(ModeAncestor): MONO = auto() L = auto() I = auto() F = auto() P = auto() RGB = auto() RGBX = auto() RGBA = auto() CMYK = auto() YCbCr = auto() LAB = auto() HSV = auto() RGBa = auto() LA = auto() La = auto() PA = auto() I16 = auto() I16L ...
def test_decorations(manager_nospawn, minimal_conf_noscreen): config = minimal_conf_noscreen decorated_widget = widget.ScriptExit(decorations=[RectDecoration(), BorderDecoration(), RectDecoration(radius=0, filled=True)]) config.screens = [libqtile.config.Screen(top=libqtile.bar.Bar([decorated_widget], 10))]...
def copy_and_replace(bmg_original: BMGraphBuilder, transformer_creator: Callable[([Cloner, Sizer], NodeTransformer)]) -> typing.Tuple[(BMGraphBuilder, ErrorReport)]: cloner = Cloner(bmg_original) transformer = transformer_creator(cloner, cloner.sizer) for original in bmg_original.all_nodes(): inputs...
.parametrize('ref, K0_ref, K_unitless_ref', ((DuschinskyRef.INITIAL, 0., 1.), (DuschinskyRef.FINAL, (- 0.), (- 1.)))) def test_duschinsky(ref, K0_ref, K_unitless_ref): L_init = np.array([[(- 0.)], [0.0], [0.0], [0.], [0.0], [0.0]]) L_final = np.array([[(- 0.)], [0.0], [0.0], [0.], [0.0], [0.0]]) coords3d_in...
def test_trace_parent_wrong_trace_options_field(caplog): header = '00-0af7651916cd43dd8448eb211c80319c-b7ad6b-xx' with caplog.at_level('DEBUG', 'elasticapm.utils'): trace_parent = TraceParent.from_string(header) assert (trace_parent is None) assert_any_record_contains(caplog.records, 'Invalid tr...
def _get_completion_help() -> str: from hydra.core.plugins import Plugins from hydra.plugins.completion_plugin import CompletionPlugin completion_plugins = Plugins.instance().discover(CompletionPlugin) completion_info: List[str] = [] for plugin_cls in completion_plugins: assert issubclass(pl...
class PanedCollapsible(Gtk.Paned): __gtype_name__ = 'PanedCollapsible' collapsible1 = GObject.property(type=bool, default=False) collapsible2 = GObject.property(type=bool, default=False) Paned = enum(DEFAULT=1, EXPAND=2, COLLAPSE=3) collapsible_y = GObject.property(type=int, default=0) collapsib...
def test_matrices_div(): for (M, S, is_field) in _all_matrices(): M1234 = M([[1, 2], [3, 4]]) if is_field: assert ((M1234 / 2) == M([[(S(1) / 2), S(1)], [(S(3) / 2), 2]])) assert ((M1234 / S(2)) == M([[(S(1) / 2), S(1)], [(S(3) / 2), 2]])) assert raises((lambda : ...
class AssignConfigCursor(StmtCursor): def config(self) -> Config: assert isinstance(self._impl, C.Node) assert isinstance(self._impl._node, LoopIR.WriteConfig) return self._impl._node.config def field(self) -> str: assert isinstance(self._impl, C.Node) assert isinstance(s...
def git_push(ctx): new_version = version.__version__ values = list(map((lambda x: int(x)), new_version.split('.'))) local(ctx, f'git add {project_name}/version.py version.py') local(ctx, 'git commit -m "updated version"') local(ctx, f'git tag {values[0]}.{values[1]}.{values[2]}') local(ctx, 'git...
class DummyAdvanced(Computation): def __init__(self, arr, coeff): Computation.__init__(self, [Parameter('C', Annotation(arr, 'io')), Parameter('D', Annotation(arr, 'io')), Parameter('coeff1', Annotation(coeff)), Parameter('coeff2', Annotation(coeff))]) def _build_plan(self, plan_factory, device_params, ...
def _get_package_data(module, rel_path): if ((module.__spec__ is None) or (module.__spec__.submodule_search_locations is None)): module_dir_path = os.path.dirname(module.__file__) path = os.path.join(module_dir_path, *rel_path.split('/')) with open(path, 'rb') as fp: return fp.re...
def generate_oura_activity_content(date): if ((not date) or (date == datetime.today().date())): date = app.session.query(func.max(ouraActivitySummary.summary_date))[0][0] df = pd.read_sql(sql=app.session.query(ouraActivitySummary).filter((ouraActivitySummary.summary_date == date)).statement, con=engine,...
def setup_memory(avatar, memory, record_memories=None): if (memory.emulate is not None): emulate = getattr(peripheral_emulators, memory.emulate) else: emulate = None log.info(('Adding Memory: %s Addr: 0x%08x Size: 0x%08x' % (memory.name, memory.base_addr, memory.size))) avatar.add_memory...
def appy_partial_on_base_config(base, partial): new_config = FakeConfig(base) new_config.VM_CONTROLLER = partial['VM_CONTROLLER'] new_config.VM_NAME = partial['VM_NAME'] new_config.SNAPSHOT_NAME = partial['SNAPSHOT_NAME'] new_config.UNPACKER_CONFIG['host_port'] = partial['host_port'] new_config....
class _NoneTrait(TraitType): info_text = 'None' default_value = None default_value_type = DefaultValue.constant def __init__(self, **metadata): default_value = metadata.pop('default_value', None) if (default_value is not None): raise ValueError('Cannot set default value {} fo...
def fortios_log_fortianalyzer(data, fos): fos.do_member_operation('log.fortianalyzer', 'override-setting') if data['log_fortianalyzer_override_setting']: resp = log_fortianalyzer_override_setting(data, fos) else: fos._module.fail_json(msg=('missing task body: %s' % 'log_fortianalyzer_overrid...
class Sigmoid(Fixed): codomain = constraints.unit_interval def _forward(self, x: torch.Tensor, params: Optional[Sequence[torch.Tensor]]) -> Tuple[(torch.Tensor, Optional[torch.Tensor])]: y = clipped_sigmoid(x) ladj = self._log_abs_det_jacobian(x, y, params) return (y, ladj) def _inve...
def test_text_align_enum(): r = ft.Text() assert (r.text_align == ft.TextAlign.NONE) assert (r._get_attr('textAlign') is None) r = ft.Text(text_align=ft.TextAlign.RIGHT) assert isinstance(r.text_align, ft.TextAlign) assert (r.text_align == ft.TextAlign.RIGHT) assert (r._get_attr('textAlign')...
class TestDataFrameInit(): def test_init(self): with pytest.raises(ValueError): ed.DataFrame() with pytest.raises(ValueError): ed.DataFrame(es_client=ES_TEST_CLIENT) with pytest.raises(ValueError): ed.DataFrame(es_index_pattern=FLIGHTS_INDEX_NAME) ...
('/backend/update/', methods=['POST', 'PUT']) def backend_update(): debug_output(flask.request.json, 'RECEIVED:') update = flask.request.json for build in update.get('builds', []): if ((build['status'] == 0) or (build['status'] == 1)): build_results.append(build) started_buil...
class SDPHYCMDR(LiteXModule): def __init__(self, sys_clk_freq, cmd_timeout, cmdw, busy_timeout=1): self.pads_in = pads_in = stream.Endpoint(_sdpads_layout) self.pads_out = pads_out = stream.Endpoint(_sdpads_layout) self.sink = sink = stream.Endpoint([('cmd_type', 2), ('data_type', 2), ('leng...
def test_configuration_set_via_cmd_and_default_config(hydra_sweep_runner: TSweepRunner) -> None: sweep = hydra_sweep_runner(calling_file='tests/test_ax_sweeper_plugin.py', calling_module=None, task_function=quadratic, config_path='config', config_name='config.yaml', overrides=['hydra/launcher=basic', 'hydra.sweeper...
class OptionPlotoptionsLollipopStatesSelect(Options): def animation(self) -> 'OptionPlotoptionsLollipopStatesSelectAnimation': return self._config_sub_data('animation', OptionPlotoptionsLollipopStatesSelectAnimation) def enabled(self): return self._config_get(True) def enabled(self, flag: bo...
def initLogging(logLevel=logging.INFO): global LOGGING_INITIALIZED if LOGGING_INITIALIZED: print('ERROR - Logging initialized twice!') try: print(traceback.format_exc()) return except Exception: pass LOGGING_INITIALIZED = True print('Setting up...
_api.route((api_url + 'departments/'), methods=['GET']) _auth.login_required def get_departments(): page = request.args.get('page', 1, type=int) per_page = min(request.args.get('per_page', app.config['posts_per_page'], type=int), 100) data = FlicketDepartment.to_collection_dict(FlicketDepartment.query.order...
def extractSleepykoreanWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None if ('lucia' in item['tags']): return buildReleaseMessageWithType(item, 'Lucia', vol, chp, frag=f...
class FieldOutFileInfo(FieldFileInfo): def __init__(self, fimeta): super().__init__(fimeta) if (self.param.form_type == 'text'): self.link_name = request.form[self.key] self.file_suffix = request.form[self.key] else: self.file_suffix = '.out' def save(...
def _load_hardware_key(keyfile): key = keyfile.read() if (len(key) not in [16, 24, 32, 64]): raise esptool.FatalError(('Key file contains wrong length (%d bytes), 16, 24, 32 or 64 expected.' % len(key))) if (len(key) == 16): key = _sha256_digest(key) print('Using 128-bit key (extende...
class CopilotOperator(MapOperator[(TriggerReqBody, Dict[(str, Any)])]): def __init__(self, **kwargs): super().__init__(**kwargs) self._default_prompt_manager = PromptManager() async def map(self, input_value: TriggerReqBody) -> Dict[(str, Any)]: from dbgpt.serve.prompt.serve import SERVE...
def contact_exists(sendgrid_erasure_identity_email: str, sendgrid_secrets): base_url = f" body = {'emails': [sendgrid_erasure_identity_email]} headers = {'Authorization': f"Bearer {sendgrid_secrets['api_key']}"} contact_response = requests.post(url=f'{base_url}/v3/marketing/contacts/search/emails', head...
class DatasetHasOpenTransactionError(FoundryAPIError): def __init__(self, dataset_rid: str, open_transaction_rid: str, response: (requests.Response | None)=None): super().__init__((f'''Dataset {dataset_rid} already has open transaction {open_transaction_rid}. ''' + (response.text if (response is not None) e...
def test_transfer16_bulk(la: LogicAnalyzer, slave: SPISlave): la.capture(4, block=False) value = slave.transfer16_bulk([WRITE_DATA16, WRITE_DATA16]) la.stop() (sck, sdo, cs, sdi) = la.fetch_data() sdi_initstate = la.get_initial_states()[SDI[0]] assert (len(cs) == (CS_START + CS_STOP)) assert...
class MongoFileField(fields.FileField): widget = widgets.MongoFileInput() def __init__(self, label=None, validators=None, **kwargs): super(MongoFileField, self).__init__(label, validators, **kwargs) self._should_delete = False def process(self, formdata, data=unset_value, extra_filters=None)...
def process_message_call(message: Message, env: Environment) -> MessageCallOutput: if (message.target == Bytes0(b'')): is_collision = account_has_code_or_nonce(env.state, message.current_target) if is_collision: return MessageCallOutput(Uint(0), U256(0), tuple(), set(), AddressCollision(...
class ReflectionServiceServicer(object): def ListAllInterfaces(self, request, context): context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def ListImplementations(self, request, context): ...
def test_create_and_link_node(): def t1(a: typing.Union[(int, typing.List[int])]) -> typing.Union[(int, typing.List[int])]: return a with pytest.raises(FlyteAssertion, match='Cannot create node when not compiling...'): ctx = context_manager.FlyteContext.current_context() create_and_link_...
_gui class TestTasksApplication(unittest.TestCase): def setUp(self): self.tmpdir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.tmpdir) _with_flaky_pyside def test_layout_save_with_protocol_3(self): state_location = self.tmpdir app = TasksApplication(state_location=...
(params=grpc_server_fixture_params) def grpc_client_and_server_url(env_fixture, request): env = {k: v for (k, v) in env_fixture.items()} if (request.param == 'async'): env['GRPC_SERVER_ASYNC'] = '1' (server_proc, free_port) = setup_grpc_server(env) server_addr = f'localhost:{free_port}' test...
def init_emb_lookup(collectiveArgs, commsParams, backendFuncs): try: from fbgemm_gpu.split_embedding_utils import generate_requests from fbgemm_gpu.split_table_batched_embeddings_ops import ComputeDevice, EmbeddingLocation, OptimType, SplitTableBatchedEmbeddingBagsCodegen except ImportError: ...
class RpcReceiver(): def __init__(self): super().__init__() self.requests = dict() self.request_timeout = 10 self.recv_size = 4096 self.check_timeouts_task = None self.check_timeouts_sleep = None def addCall(self, xid): if (xid in self.requests): ...
def doSingleSearch(phash): print('Search for: ', phash) phash = int(phash) hash_print(phash) print(phash) print("Finding files similar to: '{}'".format(phash)) remote = rpyc.connect('localhost', 12345) commons = remote.root.single_phash_search(phash=phash) print('Common files:') for ...
def order_nested_filter_tree_object(nested_object): if (not isinstance(nested_object, dict)): return order_nested_object(nested_object) return OrderedDict([(key, (sorted(nested_object[key]) if ((key in ('require', 'exclude')) and isinstance(nested_object[key], list)) else order_nested_object(nested_obje...
class TestBookmarkUtilsSavingsPossible(TestBookmarkUtilsSavingsBase): def setUp(self): super(TestBookmarkUtilsSavingsPossible, self).setUp() _makeCostSavingMeasureValues(self.measure, self.practice, [0, 1500, 2000]) def test_possible_savings_for_practice(self): finder = bookmark_utils.In...
def _handle_comparison(p: Pattern, s: str) -> PatternRule: op = ast.Attribute(value=ast.Name('operator', ctx=ast.Load()), attr=s, ctx=ast.Load()) return PatternRule(assign(value=binary_compare(p)), (lambda a: ast.Assign(a.targets, _make_bmg_call('handle_function', [op, ast.List(elts=[a.value.left, a.value.compa...
class OptionSeriesVennSonificationDefaultinstrumentoptionsMappingHighpassFrequency(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...
class VehicleLinks(object): swagger_types = {'alerts': 'Link', 'last_position': 'Link', 'maintenance': 'Link', '_self': 'Link', 'status': 'Link', 'telemetry': 'Link', 'trips': 'Link'} attribute_map = {'alerts': 'alerts', 'last_position': 'lastPosition', 'maintenance': 'maintenance', '_self': 'self', 'status': '...
def test_headerdb_canonical_header_retrieval_by_number(headerdb, genesis_header): headerdb.persist_header(genesis_header) headers = mk_header_chain(genesis_header, length=10) headerdb.persist_header_chain(headers) actual = headerdb.get_canonical_block_header_by_number(genesis_header.block_number) as...
def test_print_tree_yaml(monkeypatch): gl = gitlab_util.create_test_gitlab(monkeypatch) gl.load_tree() from gitlabber.format import PrintFormat import yaml with output_util.captured_output() as (out, err): gl.print_tree(PrintFormat.YAML) output = yaml.safe_load(out.getvalue()) ...
class Solution(object): def spiralMatrixIII(self, R, C, r0, c0): def change_dire(dire): if ((dire[0] == 0) and (dire[1] == 1)): return [1, 0] elif ((dire[0] == 1) and (dire[1] == 0)): return [0, (- 1)] elif ((dire[0] == 0) and (dire[1] == (...
def test(config, ini_config_file_1): config.from_ini(ini_config_file_1) assert (config() == {'section1': {'value1': '1'}, 'section2': {'value2': '2'}}) assert (config.section1() == {'value1': '1'}) assert (config.section1.value1() == '1') assert (config.section2() == {'value2': '2'}) assert (con...
class TimeCode(object): def __init__(self, success_msg=None, sc='green', fc='red', failure_msg=None, run=Run(), quiet=False, suppress_first=0): self.run = run self.run.single_line_prefixes = {0: ' ', 1: ' '} self.quiet = quiet self.suppress_first = suppress_first (self.sc, se...
def get_combo_operator(data, comboText, con): if (data == _constants.FIELD_PROC_PATH): return (Config.RULE_TYPE_SIMPLE, Config.OPERAND_PROCESS_PATH, con.process_path) elif (data == _constants.FIELD_PROC_ARGS): if ((len(con.process_args) == 0) or (con.process_args[0] == '')): return (...
def test_error_if_df_contains_negative_values(df_vartypes): df_neg = df_vartypes.copy() df_neg.loc[(1, 'Age')] = (- 1) transformer = BoxCoxTransformer() with pytest.raises(ValueError): transformer.fit(df_neg) transformer = BoxCoxTransformer() transformer.fit(df_vartypes) with pytest....
class TestPutMessagingConfigSecretTwilioEmail(): (scope='function') def url(self, messaging_config_twilio_email) -> str: return (V1_URL_PREFIX + MESSAGING_SECRETS).format(config_key=messaging_config_twilio_email.key) (scope='function') def payload(self): return {MessagingServiceSecrets.T...
def test_select1(compiler): def select1(x: f32): zero: f32 zero = 0.0 two: f32 two = 2.0 x = select(x, zero, two, x) actual = np.array([(- 4.0), 0.0, 4.0], dtype=np.float32) expected = (((actual < 0) * 2.0) + ((actual >= 0) * actual)) fn = compiler.compile(select1...
def test_serialize_model_shims_roundtrip_bytes(): fwd = (lambda model, X, is_train: (X, (lambda dY: dY))) test_shim = SerializableShim(None) shim_model = Model('shimmodel', fwd, shims=[test_shim]) model = chain(Linear(2, 3), shim_model, Maxout(2, 3)) model.initialize() assert (model.layers[1].sh...
class CMY(Space): BASE = 'srgb' NAME = 'cmy' SERIALIZE = ('--cmy',) CHANNELS = (Channel('c', 0.0, 1.0, bound=True), Channel('m', 0.0, 1.0, bound=True), Channel('y', 0.0, 1.0, bound=True)) CHANNEL_ALIASES = {'cyan': 'c', 'magenta': 'm', 'yellow': 'y'} WHITE = WHITES['2deg']['D65'] def to_base...
class Preferences(Gtk.Dialog): AUTOSTART_DIR = '{}/.config/autostart'.format(os.getenv('HOME')) AUTOSTART_PATH = '{}/.config/autostart/indicator-sysmonitor.desktop'.format(os.getenv('HOME')) DESKTOP_PATH = '/usr/share/applications/indicator-sysmonitor.desktop' sensors_regex = re.compile('{.+?}') SET...
class SetActivePerspectiveAction(WorkbenchAction): enabled = Delegate('perspective') id = Delegate('perspective') name = Delegate('perspective') style = 'radio' perspective = Instance(IPerspective) def destroy(self): self.window = None def perform(self, event): self.window.ac...
def define_paired_EDs(num_pairs, input_nc, z_nc, ngf, K, bottleneck, n_downsample_global=3, n_blocks_global=9, max_mult=16, norm='instance', gpu_ids=[], vaeLike=False): norm_layer = get_norm_layer(norm_type=norm) list_of_encoders = [] list_of_decoders = [] for i in range(num_pairs): encoder = E_...
class Reviewer(models.Model): objects = EventUserManager() created_at = models.DateTimeField(_('Created At'), auto_now_add=True) updated_at = models.DateTimeField(_('Updated At'), auto_now=True) event_user = models.ForeignKey(EventUser, verbose_name=_('Event User'), blank=True, null=True) def __str_...
_os(*metadata.platforms) def main(): masquerade = '/tmp/sed' if (common.CURRENT_OS == 'linux'): source = common.get_path('bin', 'linux.ditto_and_spawn') common.copy_file(source, masquerade) else: common.create_macos_masquerade(masquerade) common.log('Executing fake sed command fo...
class MakeBuild(DistutilsBuild): def run(self): DistutilsBuild.run(self) if (not find_executable('make')): sys.exit("ERROR: 'make' command is unavailable") try: subprocess.check_call(['make']) except subprocess.CalledProcessError as e: sys.exit('Co...
class JSONWebTokenMiddleware(): def __init__(self): self.cached_allow_any = set() if jwt_settings.JWT_ALLOW_ARGUMENT: self.cached_authentication = PathDict() def authenticate_context(self, info, **kwargs): root_path = info.path[0] if (root_path not in self.cached_allo...
def test_round_trip_ttx(font): table = table_S_V_G_() for (name, attrs, content) in parseXML(OTSVG_TTX): table.fromXML(name, attrs, content, font) compiled = table.compile(font) table = table_S_V_G_() table.decompile(compiled, font) assert (getXML(table.toXML, font) == OTSVG_TTX)
class P2PLibp2pConnection(Connection): connection_id = PUBLIC_ID DEFAULT_MAX_RESTARTS = 5 def __init__(self, **kwargs: Any) -> None: super().__init__(**kwargs) ledger_id = self.configuration.config.get('ledger_id', DEFAULT_LEDGER) if (ledger_id not in SUPPORTED_LEDGER_IDS): ...
def get_pcie_int_tiles(grid, pcie_loc): def get_site_at_loc(loc): gridinfo = grid.gridinfo_at_loc(loc) sites = list(gridinfo.sites.keys()) if (len(sites) and sites[0].startswith('SLICE')): return sites[0] return None pcie_int_tiles = list() for tile_name in sorted...
class ConfigLoaderImpl(ConfigLoader): def __init__(self, config_search_path: ConfigSearchPath) -> None: self.config_search_path = config_search_path self.repository = ConfigRepository(config_search_path=config_search_path) def validate_sweep_overrides_legal(overrides: List[Override], run_mode: R...
class AbstractSerializer(): def __init__(self, extensions=None): super().__init__() self._extensions = (extensions or []).copy() def decode(self, s, **kwargs): raise NotImplementedError() def encode(self, d, **kwargs): raise NotImplementedError() def extensions(self): ...