code
stringlengths
281
23.7M
('nested_recursive', [True, False]) def test_convert_and_recursive_node(instantiate_func: Any, nested_recursive: bool) -> None: cfg = {'_target_': 'tests.instantiate.SimpleClass', 'a': {'_target_': 'tests.instantiate.SimpleClass', '_convert_': 'all', '_recursive_': nested_recursive, 'a': {}, 'b': []}, 'b': None} ...
class Consumer(StreamConsumer): def __init__(self, stream_interface: StreamInterface, sample_callback: LabgraphCallback, mode: Mode=Mode.SYNC, stream_id: Optional[str]=None) -> None: super(Consumer, self).__init__(**{'si': stream_interface, 'sampleCb': self._to_cthulhu_callback(sample_callback), 'async': (m...
def _create_plot_component(): x = linspace((- 2.0), 10.0, 100) pd = ArrayPlotData(index=x) for i in range(5): pd.set_data(('y' + str(i)), jn(i, x)) plot = Plot(pd, title='Line Plot', padding=50, border_visible=True) plot.legend.visible = True plot.plot(('index', 'y0', 'y1', 'y2'), name='...
class _BGPPathAttributeAsPathCommon(_PathAttribute): _AS_SET = 1 _AS_SEQUENCE = 2 _SEG_HDR_PACK_STR = '!BB' _AS_PACK_STR = None _ATTR_FLAGS = BGP_ATTR_FLAG_TRANSITIVE def __init__(self, value, as_pack_str=None, flags=0, type_=None, length=None): super(_BGPPathAttributeAsPathCommon, self)...
def has_value_for_key(datapoint: dict[(str, Any)], key: str, logger: Logger): value = datapoint['production'].get(key, None) if ((value is None) or math.isnan(value)): logger.warning(f"Required generation type {key} is missing from {datapoint['zoneKey']}", extra={'key': datapoint['zoneKey']}) re...
def test_offset_with_unparsable_string_connector_param_reference(response_with_body): config = OffsetPaginationConfiguration(incremental_param='page', increment_by=1, limit={'connector_param': 'limit'}) connector_params = {'limit': 'ten'} request_params: SaaSRequestParams = SaaSRequestParams(method=HTTPMeth...
class OoxmlFilter(odf.OdfFilter): def __init__(self, options, default_encoding='utf-8'): super().__init__(options, default_encoding) def get_default_config(self): return {} def setup(self): self.additional_context = '' self.comments = False self.attributes = [] ...
class BodhiMessage(message.Message): def app_icon(self) -> str: return ' def app_name(self) -> str: return 'bodhi' def agent(self) -> typing.Union[(str, None)]: warnings.warn('agent property is deprecated, please use agent_name instead', DeprecationWarning, stacklevel=2) retu...
def handle_autospec(spec_abspath, spec_basename, args): result = spec_abspath if rpmautospec_used(spec_abspath): git_dir = check_output(['git', 'rev-parse', '--git-dir']) git_dir = git_dir.decode('utf-8').strip() if os.path.exists(os.path.join(git_dir, 'shallow')): logging.in...
def test_dfsr_subtype1(tmpdir, merge_lis_prs): fpath = os.path.join(str(tmpdir), 'dfsr-subtype1.lis') content = ((headers + ['data/lis/records/curves/dfsr-subtype1.lis.part']) + trailers) merge_lis_prs(fpath, content) with lis.load(fpath) as (f,): dfs = f.data_format_specs()[0] ch1 = dfs...
class ReferenceTask(ReferenceEntity, PythonFunctionTask): def __init__(self, project: str, domain: str, name: str, version: str, inputs: Dict[(str, type)], outputs: Dict[(str, Type)]): super().__init__(TaskReference(project, domain, name, version), inputs, outputs) self._task_resolver = None
class OptionSeriesStreamgraphAccessibilityPoint(Options): def dateFormat(self): return self._config_get(None) def dateFormat(self, text: str): self._config(text, js_type=False) def dateFormatter(self): return self._config_get(None) def dateFormatter(self, value: Any): sel...
class FieldsetInFilesWithJsonIndex(FieldsetInFilesWithDBIndex): DBCLASS = JsonFileDatabase _method def _lookup_parts(self): return self.db.lookup_parts() def part(self, n): return self._lookup_parts()[n] def number_of_parts(self): return len(self._lookup_parts())
class OptionSeriesBubbleEvents(Options): def afterAnimate(self): return self._config_get(None) def afterAnimate(self, value: Any): self._config(value, js_type=False) def checkboxClick(self): return self._config_get(None) def checkboxClick(self, value: Any): self._config(v...
def extractRoontalesCom(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 tagma...
.parametrize('test_file_nonce', ['ttNonce/TransactionWithHighNonce32.json', 'ttNonce/TransactionWithHighNonce64Minus2.json']) def test_nonce(test_file_nonce: str) -> None: test = load_tangerine_whistle_transaction(test_dir, test_file_nonce) tx = rlp.decode_to(Transaction, test['tx_rlp']) result_intrinsic_ga...
def parse_hex(color: str) -> tuple[(Vector, float)]: length = len(color) if (length in (7, 9)): return ([norm_hex_channel(color[1:3]), norm_hex_channel(color[3:5]), norm_hex_channel(color[5:7])], (norm_hex_channel(color[7:9]) if (length == 9) else 1.0)) else: return ([norm_hex_channel((color...
class Metrics(object): def __init__(self, model, task='classification'): self.model = model self.task = task self.metric_names = None self.metrics_fn = self._infer() def evaluate(self, loss, output, target, **kwargs): return self.metrics_fn(loss, output, target, **kwargs)...
class ImageStoreImageView(APIView): dc_bound = False def __init__(self, request, name, uuid, data): super(ImageStoreImageView, self).__init__(request) self.data = data self.name = name self.uuid = uuid repositories = ImageStore.get_repositories(include_image_vm=request.us...
class RequestLogMiddleware(object): def __init__(self, get_response): self.get_response = get_response self.request_keys = ('method', 'path_info', 'scheme', 'user') self.request_meta_keys = ('REMOTE_ADDR', 'HTTP_USER_AGENT', 'HTTP_REFERER', 'HTTP_HOST', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_I...
class RL_Batcher(): def reset(self, agent_info=DictTensor({}), env_info=DictTensor({})): assert (agent_info.empty() or (agent_info.device() == torch.device('cpu'))), 'agent_info must be on CPU' assert (env_info.empty() or (env_info.device() == torch.device('cpu'))), 'env_info must be on CPU' ...
def fetch_production(zone_key: str='IN-PB', session: (Session | None)=None, target_datetime: (datetime | None)=None, logger: Logger=getLogger(__name__)) -> list[dict]: if target_datetime: raise NotImplementedError('The IN-PB production parser is not yet able to parse past dates') s = (session or Session...
class Client(): def __enter__(self) -> Self: return self def __exit__(self, exc_type: Any, exc_value: Any, exc_traceback: Any) -> None: if (self.websocket is not None): self.loop.run_until_complete(self.websocket.close()) self.loop.close() async def __aenter__(self) -> 'C...
def test_update_from_dict(): s = search.Search() s.update_from_dict({'indices_boost': [{'important-documents': 2}]}) s.update_from_dict({'_source': ['id', 'name']}) s.update_from_dict({'collapse': {'field': 'user_id'}}) assert ({'indices_boost': [{'important-documents': 2}], '_source': ['id', 'name'...
class CustomColorEditor(BaseSimpleEditor): def init(self, parent): self.control = self._panel = parent = TraitsUIPanel(parent, (- 1)) sizer = wx.BoxSizer(wx.HORIZONTAL) text_control = wx.TextCtrl(parent, (- 1), self.str_value, style=wx.TE_PROCESS_ENTER) text_control.Bind(wx.EVT_KILL_...
class OptionTick(Options): def centered(self): return self._config_get(True) def centered(self, flag): self._config(flag) def autorotate(self): return self._config_get(None) def autorotate(self, flag): self._config(flag) def format(self, js_funcs: etypes.JS_FUNCS_TYPE...
class Remote_(): def needs_handle_on_a_Connection(self): c = _Connection('host') assert (Remote(context=c).context is c) class env(): def replaces_when_replace_env_True(self, remote): env = _runner().run(CMD, env={'JUST': 'ME'}, replace_env=True).env assert (env =...
class InlineHstoreList(InlineFieldList): def process(self, formdata, data=unset_value, extra_filters=None): if isinstance(data, dict): data = [KeyValue(k, v) for (k, v) in iteritems(data)] super(InlineHstoreList, self).process(formdata, data, extra_filters) def populate_obj(self, obj...
class DataType(Enum): TEXT = DirectDataType.TEXT.value YOUTUBE_VIDEO = IndirectDataType.YOUTUBE_VIDEO.value PDF_FILE = IndirectDataType.PDF_FILE.value WEB_PAGE = IndirectDataType.WEB_PAGE.value SITEMAP = IndirectDataType.SITEMAP.value XML = IndirectDataType.XML.value DOCX = IndirectDataType....
class StepIndexFiber(AgnosticOpticalElement): def __init__(self, core_radius, NA, fiber_length, position=None): super().__init__(False, True) self._core_radius = core_radius self._NA = NA self.fiber_length = fiber_length self._position = (np.zeros((2,)) if (position is None) ...
def extractLygarTranslations(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None if ((('elf tensei' in item['tags']) or ('elf tensei' in item['title'].lower())) and (not ('news' in item['tags'...
class TestConverteFParaC(TestCase): def test_do_ze(self): valores = [(32, 0), ((- 40), (- 40))] for (input_, output) in valores: with self.subTest(input_=input_, output=output): self.assertEqual(converte_F_para_C(input_), output) def test_deve_retornar_0_quando_recebe...
def SendEmail(subject, recipient, message): try: p = subprocess.Popen(('mutt', '-s', subject, recipient), stdin=subprocess.PIPE) p.stdin.write(message) p.stdin.close() p.wait() return True except Exception as ex: logging.error('SendMail failed to send email via mu...
class VmTemplate(_VirtModel, _JsonPickleModel, _OSType, _HVMType, _DcMixin, _UserTasksModel): DEFINE_KEYS = ('vm_define', 'vm_define_disk', 'vm_define_nic', 'vm_define_snapshot', 'vm_define_backup') ACCESS = ((_VirtModel.PUBLIC, _('Public')), (_VirtModel.PRIVATE, _('Private')), (_VirtModel.DELETED, _('Deleted')...
_meta(actions.AskForCard) class AskForCard(): def sound_effect_after(self, act): c = act.card if (not c): return if (act.card_usage != 'use'): return meta = getattr(c, 'ui_meta', None) se = getattr(meta, 'sound_effect', None) return (se and se(...
def _validate_network(network, required): missing = [i for i in required if (i not in network)] if missing: raise ValueError(f"Network is missing required field(s): {', '.join(missing)}") unknown = [i for i in network if (i not in (required + OPTIONAL))] if unknown: raise ValueError(f"Un...
class OptionPlotoptionsVennDatalabelsTextpath(Options): def attributes(self): return self._config_get(None) def attributes(self, value: Any): self._config(value, js_type=False) def enabled(self): return self._config_get(False) def enabled(self, flag: bool): self._config(f...
def test_superposition(wave: WaveformGenerator, scope: Oscilloscope): frequency = 1000 amplitude1 = 2 amplitude2 = 1 def super_sine(x): return ((amplitude1 * np.sin(x)) + (amplitude2 * np.sin((5 * x)))) wave.load_function('SI1', super_sine, [0, (2 * np.pi)]) wave.generate('SI1', frequenc...
def gather_imports(fips_dir, proj_dir): imported = OrderedDict() ws_dir = util.get_workspace_dir(fips_dir) (success, deps) = get_all_imports_exports(fips_dir, proj_dir) unique_defines = {} unique_modules = {} if success: for proj_name in deps: imports = deps[proj_name]['impor...
class TestAnalysisSkipping(): class PluginMock(): DEPENDENCIES = [] def __init__(self, version, system_version): self.VERSION = version self.NAME = 'test plug-in' if system_version: self.SYSTEM_VERSION = system_version class BackendMock(): ...
def write_image(htmlhandle, colwidth, href, src, label): htmlhandle.write('\n <div class="theme-table-image col-sm-{colwidth}">\n <a href="{href}"><img src="{src}" class="img-responsive img-rounded">{label}</a><br>\n </div>\n '.format(colwidth=colwidth, href=href, src=src, label=label))
def test_delete_firmware(backend_db, admin_db, common_db): (fw, parent, child) = create_fw_with_parent_and_child() backend_db.insert_multiple_objects(fw, parent, child) admin_db.delete_firmware(fw.uid) assert (common_db.exists(fw.uid) is False) assert (common_db.exists(parent.uid) is False), 'should...
def sanitise_url_path(path: str) -> str: path = unquote(path) path = os.path.normpath(path) for token in path.split('/'): if ('..' in token): logger.warning(f'Potentially dangerous use of URL hierarchy in path: {path}') raise MalisciousUrlException() return path
class SeqNodeSerializer(AbstractSyntaxTreeNodeSerializer): def serialize(self, node: SeqNode) -> Dict: return super().serialize(node) def deserialize(self, data: dict) -> SeqNode: return SeqNode(reaching_condition=LogicCondition.deserialize(data['rc'], self._group.new_context))
class OptionsPopupWidget(OptionsWidget): __gsignals__ = {'item-clicked': (GObject.SIGNAL_RUN_LAST, None, (str,))} def __init__(self, *args, **kwargs): OptionsWidget.__init__(self, *args, **kwargs) self._popup_menu = Gtk.Menu() def update_options(self): self.clear_popupmenu() ...
class TestUserSearchApi(ZenpyApiTestCase): def test_raises_zenpyexception_when_neither_query_nor_external_id_are_set(self): with self.assertRaises(ZenpyException): self.zenpy_client.users.search() def test_raises_zenpyexception_when_both_query_and_external_id_are_set(self): with self...
class CRR(Layout): ck_layout_a = 'ck::tensor_layout::gemm::ColumnMajor' ck_layout_b = 'ck::tensor_layout::gemm::RowMajor' ck_layout_c = 'ck::tensor_layout::gemm::RowMajor' stride_a = 'M' stride_b = 'N' stride_c = 'N' args_parse = '\n int64_t M = std::stoi(argv[1]);\n int64_t N = std::stoi(...
class SimpleCache(): def __init__(self, size: int=100): self._size = size self._data: OrderedDict[(str, Any)] = OrderedDict() def cache(self, key: str, value: Any) -> Tuple[(Any, Dict[(str, Any)])]: evicted_items = None if (key not in self._data): while (len(self._dat...
(params=['interval', 'square', 'quad-square']) def uniform_mesh(request): if (request.param == 'interval'): base = UnitIntervalMesh(4) elif (request.param == 'square'): base = UnitSquareMesh(5, 4) elif (request.param == 'quad-square'): base = UnitSquareMesh(4, 6, quadrilateral=True) ...
class Autosplit(Layout): def __init__(self, layout_name: LayoutName, workspace_name: str): super().__init__(layout_name, workspace_name) def swap_mark_last(self) -> bool: return False def _params(self) -> List[Any]: return [] def anchor_mark(self) -> Optional[str]: return...
def pick_destinations(argv, tdb): numSystems = len(tdb.systemByName) if (numSystems < 1): raise UsageError(argv, "Can't --pick random systems: Your TD database doesn't contain any systems.") num = min(argv.pick, numSystems) systems = tdb.systemByName try: gamma = tdb.lookupAdded('Gam...
('/', defaults={'path': ''}) ('/<path:path>') def catch_all(path): if (not path.startswith('/')): path = ('/' + path) if path.startswith('//'): path = path[1:] status_code = 403 headers = {'X-Test': 'Should not be seen.'} if path.startswith('/ambassador/'): status_code = 200 ...
def save_model(model, file_name, file_path=None, append=False, save_results=False, save_settings=False, save_data=False): obj_dict = dict_array_to_lst(model.__dict__) keep = set(((((OBJ_DESC['results'] + OBJ_DESC['meta_data']) if save_results else []) + (OBJ_DESC['settings'] if save_settings else [])) + (OBJ_DE...
class OptionSeriesSankeySonificationTracksMappingNoteduration(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): se...
def get_vm_backups(request, vm): (user_order_by, order_by) = get_order_by(request, api_view=VmBackupList, db_default=('-id',), user_default=('-created',)) bkps = get_pager(request, Backup.objects.select_related('node', 'vm', 'define').filter(vm=vm).order_by(*order_by), per_page=50) return {'order_by': user_...
() _option _option ('--environment', default=None, help='Name of EDM environment to build docs for.') ('--error-on-warn/--no-error-on-warn', default=True, help='Turn warnings into errors? [default: --error-on-warn] ') def docs(edm, runtime, environment, error_on_warn): parameters = get_parameters(edm, runtime, env...
class OptionSeriesGaugeDataDragdropDraghandle(Options): def className(self): return self._config_get('highcharts-drag-handle') def className(self, text: str): self._config(text, js_type=False) def color(self): return self._config_get('#fff') def color(self, text: str): se...
def load_and_fetch_c_hybrid_plugin_info(plugin_name: str, is_config: bool, plugin_type='south') -> Dict: plugin_info = None if (plugin_type == 'south'): config_items = ['default', 'type', 'description'] optional_items = ['readonly', 'order', 'length', 'maximum', 'minimum', 'rule', 'deprecated', ...
class table_stats_reply(stats_reply): version = 5 type = 19 stats_type = 3 def __init__(self, xid=None, flags=None, entries=None): if (xid != None): self.xid = xid else: self.xid = None if (flags != None): self.flags = flags else: ...
def create_annotations(figures: typing.Figures, num_chains: int) -> typing.Annotations: renderers = [] for (_, fig) in figures.items(): renderers.extend(PropertyValueList(fig.renderers)) legend_items = [] for chain in range(num_chains): chain_index = (chain + 1) chain_name = f'ch...
class BashSession(Tool): name: str = 'Bash Session' def __init__(self, timeout: (float | None)=None): self.timeout = timeout (self.master_fd, self.slave_fd) = pty.openpty() self.bash_process = subprocess.Popen(['bash'], stdin=self.slave_fd, stdout=self.slave_fd, stderr=subprocess.STDOUT,...
class OptionSeriesItemOnpointConnectoroptions(Options): def dashstyle(self): return self._config_get(None) def dashstyle(self, text: str): self._config(text, js_type=False) def stroke(self): return self._config_get(None) def stroke(self, text: str): self._config(text, js_...
class SerializerGroup(Serializer[T]): def __init__(self): self._serializers: Dict[(str, Serializer)] = {} self.new_context = LogicCondition.generate_new_context() def register(self, serializeable_class: type, serializer: Serializer): self._serializers[serializeable_class.__name__] = seri...
class Record(): def __init__(self, rdata_type, *args, rtype=None, rname=None, ttl=None, **kwargs): if isinstance(rdata_type, RD): self._rtype = TYPE_LOOKUP[rdata_type.__class__] rdata = rdata_type else: self._rtype = TYPE_LOOKUP[rdata_type] if ((rdata_...
class DebugAdapter(HTTPAdapter): def __init__(self, wrapped_session=None): self.session = (Session() if (wrapped_session is None) else wrapped_session) super().__init__() def send(self, request, **kwargs): debug_request(request) response = self.session.send(request, **kwargs) ...
def assert_model_hf_serialization_roundtrip(model_class: Type[FromHFHub], model_name: str, torch_device: torch.device, *, model_revision: str='main', atol: float=1e-05, rtol: float=1e-05, trust_remote_code: bool=False, optional_hf_config_keys: Set[str]=set()): orig_model = model_class.from_hf_hub(name=model_name, r...
class HttpDialogues(BaseHttpDialogues): def __init__(self, self_address: Address, **kwargs) -> None: def role_from_first_message(message: Message, receiver_address: Address) -> BaseDialogue.Role: return HttpDialogue.Role.CLIENT BaseHttpDialogues.__init__(self, self_address=self_address, ...
class StepLRScheduler(OptimizerScheduler): def __init__(self, *, optimizer: Optimizer, **kwargs): init_self_cfg(self, component_class=__class__, config_class=StepLRSchedulerConfig, **kwargs) super().__init__(optimizer=optimizer, **kwargs) self._scheduler = StepLR(optimizer=optimizer, step_si...
def get_matching_blocks(from_addresses, to_addresses): from_offsets = [] to_offsets = [] for i in range((len(from_addresses) - 1)): from_offsets.append((from_addresses[(i + 1)] - from_addresses[i])) for i in range((len(to_addresses) - 1)): to_offsets.append((to_addresses[(i + 1)] - to_ad...
def save_groups(filename, model): data = {'clients': {}, 'groups': []} uid = 0 uid_pairs = {} saved_clients = [] for group in model: group = group[G_INSTANCE] for cln in group.get_members(): if (cln not in saved_clients): saved_clients.append(cln) for ...
.parametrize('wave, J, mode', [('db1', 1, 'zero'), ('db1', 3, 'zero'), ('db3', 1, 'symmetric'), ('db2', 2, 'symmetric'), ('db3', 2, 'reflect'), ('db2', 3, 'periodization'), ('db4', 2, 'zero'), ('bior2.4', 2, 'periodization'), ('db1', 1, 'zero'), ('db1', 3, 'zero'), ('db2', 3, 'periodization'), ('db4', 2, 'zero'), ('bio...
class stream_adder(Module): def __init__(self): self.sink_valid = Signal() self.sink_last = Signal() self.sink_data = Signal(8) self.sink_ready = Signal() self.source_valid = Signal() self.source_last = Signal() self.source_data = Signal(8) self.source...
class SpotRequest(): def __init__(self, e, d): (self.e, self.d) = (e, d) self._load() def get(cls, e, srid): d = e._get_request(srid) if (d is None): return None return cls(e, d) def from_instance(cls, e, inst): inst = e.get_instance(inst) ...
def complex_storage_prompt_template(): content = 'Database name: {db_name} Table structure definition: {table_info} User Question:{user_input}' return StoragePromptTemplate(prompt_name='chat_data_auto_execute_prompt', content=content, prompt_language='en', prompt_format='f-string', input_variables='db_name,tabl...
class TestValidateFromTag(BasePyTestCase): class UnknownTagDevBuildsys(buildsys.DevBuildsys): def listTagged(self, tag, *args, **kwargs): raise koji.GenericError(f'Invalid tagInfo: {tag!r}') def getTag(self, tag, **kwargs): return None class NoBuildsDevBuildsys(buildsys.D...
def place_metrics(user_statuses): total = len(user_statuses) if (total == 0): return (0, 0, 0, 0, 0) unique = Counter() for s in user_statuses: if (('place' in s) and (s['place'] is not None)): unique.update([s['place']['id']]) tot_statuses_with_place = sum([c for (e, c) ...
class BCBase(object): .EventDecorator() def __init__(self, V, sub_domain): if (isinstance(V.finat_element, (finat.Argyris, finat.Morley, finat.Bell)) or (isinstance(V.finat_element, finat.Hermite) and (V.mesh().topological_dimension() > 1))): raise NotImplementedError(('Strong BCs not implem...
.bigtest def test_hcpvfz1(tmpdir, generate_plot): logger.info('Name is %s', __name__) logger.info('Import roff...') grd = xtgeo.grid_from_file(ROFF1_GRID, fformat='roff') st = xtgeo.gridproperty_from_file(ROFF1_PROPS, name='Oil_HCPV') to = xtgeo.gridproperty_from_file(ROFF1_PROPS, name='Oil_bulk') ...
def run_ciftify_recon_all(settings, participant_label): if can_skip_ciftify_recon_all(settings, participant_label): logger.info('Skipping ciftify_recon_all for sub-{}'.format(participant_label)) return run_cmd = ['ciftify_recon_all', '--n_cpus', str(settings.n_cpus), '--ciftify-work-dir', settin...
def test_partial_async_ws_endpoint(test_client_factory): test_client = test_client_factory(app) with test_client.websocket_connect('/partial/ws') as websocket: data = websocket.receive_json() assert (data == {'url': 'ws://testserver/partial/ws'}) with test_client.websocket_connect('/partial/...
class OptionSeriesAreasplinerangeDataDragdropGuideboxDefault(Options): def className(self): return self._config_get('highcharts-drag-box-default') def className(self, text: str): self._config(text, js_type=False) def color(self): return self._config_get('rgba(0, 0, 0, 0.1)') def ...
def test_errors_dict_interface(): validator = Object(properties={'example': Integer()}) (value, error) = validator.validate_or_error({'example': 'abc'}) assert (dict(error) == {'example': 'Must be a number.'}) validator = Object(properties={'example': Integer()}) (value, error) = validator.validate_...
class OptionPlotoptionsCylinderSonificationTracksMappingTime(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...
class DNSClientProtocolUDP(DNSClientProtocol): def connection_made(self, transport): self.send_helper(transport) self.transport.sendto(self.dnsq.to_wire()) def datagram_received(self, data, addr): dnsr = dns.message.from_wire(data) self.receive_helper(dnsr) self.transport...
def main(): init_angles = [[(- 60), 0, 0, (- 90), 0, (- 90), (- 0.79)], [0, (- 49), 0, (- 100), 0, (- 45), (- 0.79)], [(- 3.16), (- 11.77), 0.17, (- 100), (- 0.52), (- 3.25), 1.23], [3.25, (- 8.61), 0.17, (- 99.14), 1.14, (- 2.81), (- 0.79)], [(- 10.01), (- 6.85), 0.17, (- 99.49), (- 2.63), (- 2.81), 3.07]] mc....
def pytest_report_header(config): (tps, tp_ids) = get_threads(config) devices = dict(((tp.device_id, tp.device_full_name) for tp in tps)) if (len(devices) == 0): raise ValueError('No devices match the criteria') print('Running tests on:') for device_id in sorted(devices): print((((' ...
class Perceptron(): def __init__(self, n_iterations=20000, activation_function=Sigmoid, loss=SquareLoss, learning_rate=0.01): self.n_iterations = n_iterations self.learning_rate = learning_rate self.loss = loss() self.activation_func = activation_function() self.progressbar =...
class OptionPlotoptionsArcdiagramDatalabelsTextpath(Options): def attributes(self): return self._config_get(None) def attributes(self, value: Any): self._config(value, js_type=False) def enabled(self): return self._config_get(False) def enabled(self, flag: bool): self._co...
def selector(pattern: str) -> Callable[([QM], QM)]: def wrapper(fn: QM) -> QM: selector = fn.__name__.replace('select_', '').lower() SELECTORS[selector] = pattern signature = inspect.signature(fn) arg_names = list(signature.parameters)[1:] (fn) def wrapped(self: Q, *a...
.parametrize('input, result', [('1', ['1']), ('1,2,3', ['1', '2', '3']), ('[1,2,3]', ['1', '2', '3']), ('(1,2,3)', ['1', '2', '3']), ('{1,2,3}', ['1', '2', '3']), ('1 2 3', ['1', '2', '3']), ('1 2 3', ['1', '2', '3'])]) def test_normalize_input_list(input, result): assert (normalize_input_list(input) == result)
class ThreadExecutor(AbstractMultipleExecutor): def _set_executor_pool(self) -> None: self._executor_pool = ThreadPoolExecutor(max_workers=len(self._tasks)) def _start_task(self, task: AbstractExecutorTask) -> TaskAwaitable: return cast(TaskAwaitable, self._loop.run_in_executor(self._executor_po...
def test_basic_api(setup): print('') print('start basic test...') mc.set_color(0, 255, 0) time.sleep(0.1) zero = [0, 0, 0, 0, 0, 0] mc.send_angles(zero, sp) time.sleep(2) angles = mc.get_angles() print(angles) print('check angle ', end='') for angle in angles: assert ...
class Timewarrior(IntervalModule): format = '{duration}' duration_format = '{years}y{months}m{days}d{hours}h{minutes}m{seconds}s' enable_stop = True enable_continue = True color_running = '#00FF00' color_stopped = '#F00000' on_rightclick = 'stop_or_continue' track = None settings = (...
class Test(unittest.TestCase): def test_LoadTypeLibEx(self): dllname = 'scrrun.dll' with self.assertRaises(WindowsError): LoadTypeLibEx('<xxx.xx>') tlib = LoadTypeLibEx(dllname) self.assertTrue(tlib.GetTypeInfoCount()) tlib.GetDocumentation((- 1)) self.ass...
class VRMLImporter(Source): __version__ = 0 file_name = Str('', enter_set=True, auto_set=False, desc='the VRML file name') reader = Instance(tvtk.VRMLImporter, args=(), allow_none=False, record=True) output_info = PipelineInfo(datasets=['none']) _file_path = Instance(FilePath, args=()) view = Vi...
def test_schema_migration_reader_union(): schema = {'type': 'record', 'name': 'test_schema_migration_reader_union', 'fields': [{'name': 'test', 'type': 'int'}]} new_schema = {'type': 'record', 'name': 'test_schema_migration_reader_union', 'fields': [{'name': 'test', 'type': ['string', 'int']}]} new_file = B...
def egrep2xerox(s, multichars=None): if (('[' in s) and (']' in s)): left_parts = s.split('[') prefix = left_parts[0] right_parts = ''.join(left_parts[1:]).split(']') infix_class = right_parts[0] suffix = ''.join(right_parts[1:]) s = ((((prefix + '[') + '|'.join(infix...
class OptionSeriesColumnSonificationTracksMappingLowpass(Options): def frequency(self) -> 'OptionSeriesColumnSonificationTracksMappingLowpassFrequency': return self._config_sub_data('frequency', OptionSeriesColumnSonificationTracksMappingLowpassFrequency) def resonance(self) -> 'OptionSeriesColumnSonifi...
def fill_variable_assignments(code, starting_assignments): out = {k: f_inner(v) for (k, v) in starting_assignments.items()} out[None] = f_inner(0) eqs = to_assembly(code) for (variables, coeffs) in eqs: (in_L, in_R, output) = variables out_coeff = coeffs.get('$output_coeff', 1) p...
def test_sim_plane_wave_error(): medium_bg = td.Medium(permittivity=2) medium_air = td.Medium(permittivity=1) medium_bg_diag = td.AnisotropicMedium(xx=td.Medium(permittivity=1), yy=td.Medium(permittivity=2), zz=td.Medium(permittivity=3)) medium_bg_full = td.FullyAnisotropicMedium(permittivity=[[4, 0.1, ...