code
stringlengths
281
23.7M
class OptionPlotoptionsDumbbellSonificationTracksMappingHighpassResonance(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)...
.usefixtures('prepare_client_test') class ClientTestBase(): def _fake_data(self, num_batches=None, batch_size=None): num_batches = (self.num_batches if (num_batches is None) else num_batches) batch_size = (batch_size or self.batch_size) torch.manual_seed(0) dataset = [torch.rand(batc...
def patch_module(*names: str, new_callable: Any=Mock) -> Iterator: prev = {} class MockModule(types.ModuleType): def __getattr__(self, attr: str) -> Any: setattr(self, attr, new_callable()) return types.ModuleType.__getattribute__(self, attr) mods = [] for name in names: ...
def extractWalkTheJiangHu(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None if ('TTNH Chapter' in item['title']): return buildReleaseMessageWithType(item, 'Transcending the Nine Heav...
class JailsReaderTestCache(LogCaptureTestCase): def _readWholeConf(self, basedir, force_enable=False, share_config=None): configurator = Configurator(force_enable=force_enable, share_config=share_config) configurator.setBaseDir(basedir) configurator.readEarly() configurator.getEarlyO...
class StreamBuffer(): def __init__(self, stream: str): self._buffer = (stream + _CHARS_END) self._index = 0 self._line = 0 self._column = 0 def index(self) -> int: return self._index def line(self) -> int: return self._line def column(self) -> int: ...
class SingletonModuleFactory(ModuleFactory): _parent = Any def __init__(self, *args, **kwargs): HasTraits.__init__(self) self._scene = gcf() if (not ('figure' in kwargs)): self._engine = get_engine() else: figure = kwargs['figure'] self._engine...
def get_images_eval(html, url): base = ' html = html.replace('\n', '') s = re.search("page = '';\\s*(.+?);\\s*var g_comic_name", html).group(1) pages = eval((s + '; pages')) pages = eval(pages) return [(base + page) for page in pages if (page and (not page.lower().endswith('thumbs.db')))]
class TestAccuracyScore(SimpleClassificationTestTopK): name = 'Accuracy Score' def get_value(self, result: DatasetClassificationQuality): return result.accuracy def get_description(self, value: Numeric) -> str: return f'The Accuracy Score is {value:.3g}. The test threshold is {self.get_condi...
class OptionSeriesHistogramPointEvents(Options): def click(self): return self._config_get(None) def click(self, value: Any): self._config(value, js_type=False) def drag(self): return self._config_get(None) def drag(self, value: Any): self._config(value, js_type=False) ...
def test_recover_from_signature_obj(key_api, private_key): signature = key_api.ecdsa_sign(MSGHASH, private_key) public_key = signature.recover_public_key_from_msg_hash(MSGHASH) assert (public_key == signature.recover_public_key_from_msg(MSG)) assert (public_key == private_key.public_key)
class TestFIPA(UseOef): def setup_class(cls): cls.connection1 = _make_oef_connection(FETCHAI_ADDRESS_ONE, DUMMY_PUBLIC_KEY, oef_addr='127.0.0.1', oef_port=10000) cls.connection2 = _make_oef_connection(FETCHAI_ADDRESS_TWO, DUMMY_PUBLIC_KEY, oef_addr='127.0.0.1', oef_port=10000) cls.multiplexe...
class ScaleGeneratorTest(unittest.TestCase): def test_chromatic_scale_with_sharps(self): expected = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'] self.assertEqual(Scale('C').chromatic(), expected) def test_chromatic_scale_with_flats(self): expected = ['F', 'Gb', 'G', ...
def test_describe_dict(): d = OrderedDict() d['desc'] = 'long description' d['list'] = list(range(10)) d['empty'] = None case1 = ' desc : long\n description\n list : 0 1 2 3 4 5\n 6 7 8 9\n empty : None\n\n' buf = StringIO() exclude = parseoptions('') describe_dict(buf,...
class TestCustomCorsMiddleware(): def test_raises(self): with pytest.raises(ValueError, match='passed to allow_origins'): falcon.CORSMiddleware(allow_origins=['*']) with pytest.raises(ValueError, match='passed to allow_credentials'): falcon.CORSMiddleware(allow_credentials=['...
class AgentContext(): __slots__ = ('_shared_state', '_identity', '_connection_status', '_outbox', '_decision_maker_message_queue', '_decision_maker_handler_context', '_task_manager', '_search_service_address', '_decision_maker_address', '_default_ledger_id', '_currency_denominations', '_default_connection', '_defau...
class SparklineTreeNode(TreeNode): sparkline_renderer = SparklineRenderer() word_wrap_renderer = WordWrapRenderer() def get_renderer(self, object, column=0): if (column == 1): return self.sparkline_renderer else: return self.word_wrap_renderer def get_icon(self, o...
class ModeSolverMonitor(AbstractModeMonitor): direction: Direction = pydantic.Field('+', title='Propagation Direction', description='Direction of waveguide mode propagation along the axis defined by its normal dimension.') colocate: bool = pydantic.Field(True, title='Colocate Fields', description='Toggle whethe...
def _get_alias(contract_name: str, path_str: str) -> str: data_path = _get_data_folder().parts path_parts = Path(path_str).parts if (path_parts[:len(data_path)] == data_path): idx = (len(data_path) + 1) return f'{path_parts[idx]}/{path_parts[(idx + 1)]}/{contract_name}' else: ret...
def compile_name(mh, gst, stab, n_name): assert isinstance(mh, Message_Handler) assert isinstance(gst, goto_ast.GOTO_Symbol_Table) assert isinstance(stab, dict) assert isinstance(n_name, m_ast.Name) if isinstance(n_name, m_ast.Identifier): typ = make_type() pretty_name = str(n_name) ...
class ApiTestUtils(TestCase): def test_param_to_list(self): from api.view_utils import param_to_list self.assertEqual(param_to_list('foo'), ['foo']) self.assertEqual(param_to_list('foo,bar'), ['foo', 'bar']) self.assertEqual(param_to_list(None), []) self.assertEqual(param_to_...
def test_context_registry_path_does_not_exist(): with pytest.raises(ValueError, match='Registry path directory provided .* can not be found.'): Context(cwd='.', verbosity='', registry_path='some_path_does_not_exist').registry_path with TemporaryDirectory() as tmp_dir: with cd(tmp_dir): ...
class OptionSeriesCylinderDragdropDraghandle(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): sel...
def create_camera(camera_type: Union[(pygfx.PerspectiveCamera, str)]) -> pygfx.PerspectiveCamera: if isinstance(camera_type, pygfx.PerspectiveCamera): return camera_type elif (camera_type == '2d'): return pygfx.PerspectiveCamera(fov=0) elif (camera_type == '3d'): return pygfx.Perspec...
_set_msg_type(ofproto.OFPT_SET_CONFIG) class OFPSetConfig(MsgBase): def __init__(self, datapath, flags=0, miss_send_len=0): super(OFPSetConfig, self).__init__(datapath) self.flags = flags self.miss_send_len = miss_send_len def _serialize_body(self): assert (self.flags is not None...
_required _required _required('VMS_VM_SNAPSHOT_ENABLED') def snapshot(request, hostname): context = collect_view_data(request, 'vm_list') context['vm'] = vm = get_vm(request, hostname, sr=('dc', 'owner', 'template', 'slavevm')) context['vms'] = vms = get_vms(request) context['vms_tags'] = get_vms_tags(v...
def test_verification_check(config_env: Dict): if (CONFIG_ERROR in config_env.keys()): fail(f'Config Error: {config_env[CONFIG_ERROR]}') if (EXPECTED_VERIFY not in config_env[EXPECTED_RESULTS].keys()): skip(f'Test not requested: {EXPECTED_VERIFY}') if (COSE not in config_env.keys()): ...
def test_get_dataset_rid(mocker, is_integration_test, client, iris_dataset): if (not is_integration_test): mock_get = mocker.patch('requests.Session.request') mock_get.return_value.status_code = 200 mock_get.return_value.json.return_value = {'rid': iris_dataset[0], 'name': 'iris', 'created':...
class Invert(Bijector): def __init__(self, bijector: flowtorch.Lazy, *, shape: torch.Size, context_shape: Optional[torch.Size]=None) -> None: b = bijector(shape=shape) super().__init__(None, shape=shape, context_shape=context_shape) self.bijector = b def forward(self, x: torch.Tensor, co...
def start_new_thread(target, args=(), kwargs=None, daemon=True, use_caller_name=False): if use_caller_name: name = inspect.stack()[1][3] else: name = target.__name__ logging.getLogger(inspect.currentframe().f_back.f_globals.get('__name__')).debug('new thread: {}'.format(name)) if PY2: ...
class OptionPlotoptionsVectorSonificationDefaultspeechoptionsMappingRate(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 PluginManager(): def __init__(self, config, parser, parsed_args, unparsed_argv): self._config = config self._parser = parser self._plugins = {} self.args = parsed_args self.remaining_argv = unparsed_argv def parse_args(self, *keys, default=None): path = (sel...
def repl_absolute(m, base_path): link = m.group(0) try: (scheme, netloc, path, params, query, fragment, is_url, is_absolute) = util.parse_url(m.group('path')[1:(- 1)]) if ((not is_absolute) and (not is_url)): path = util.url2path(path) path = os.path.normpath(os.path.join...
class OptionPlotoptionsScatterSonificationTracks(Options): def activeWhen(self) -> 'OptionPlotoptionsScatterSonificationTracksActivewhen': return self._config_sub_data('activeWhen', OptionPlotoptionsScatterSonificationTracksActivewhen) def instrument(self): return self._config_get('piano') d...
class DataStore(): def add_board(self, model) -> None: raise NotImplementedError def get_board(self, id) -> 'Board': raise NotImplementedError def get_boards(self) -> list['Board']: raise NotImplementedError def update_board(self, model, update): raise NotImplementedError...
def test_check_auth_admin(db): user = create_user(email='', password='password') user.is_admin = True status = AuthManager.check_auth_admin('', 'password') assert (True == status) user = create_user(email='', password='password') user.is_admin = False status = AuthManager.check_auth_admin(''...
def smile(): cap = cv.VideoCapture('/home/ubuntu/emo/face_video_3_2.mp4') out_win = 'l' cv.namedWindow(out_win, cv.WINDOW_NORMAL) cv.setWindowProperty(out_win, cv.WND_PROP_FULLSCREEN, cv.WINDOW_FULLSCREEN) while True: (ret, frame) = cap.read() if (frame is not None): cv.i...
def _single_source_shape_constraint_funcs(src_type: Type[Operator], target_type: Type[Operator]) -> Tuple[(Callable[([Tensor], bool)], Callable[([Tensor], Tensor)])]: def matchFunc(tensor: Tensor) -> bool: src_ops = tensor._attrs['src_ops'] if ((src_ops is None) or (len(src_ops) != 1)): ...
class SchemaspaceCreate(SchemaspaceBase): name_option = CliOption('--name', name='name', description='The name of the metadata instance.') file_option = FileOption('--file', name='file', description='The filename containing the metadata instance. Can be used to bypass individual property arguments.') json_o...
def fortios_certificate(data, fos, check_mode): fos.do_member_operation('certificate', 'remote') if data['certificate_remote']: resp = certificate_remote(data, fos, check_mode) else: fos._module.fail_json(msg=('missing task body: %s' % 'certificate_remote')) if check_mode: return...
class Solution(object): def shortestToChar(self, S, C): (l, l1, s) = (len(S), 0, 1) r = ([None] * l) for (i, c) in enumerate(S): if (c == C): r[i] = 0 l1 += 1 while (l1 < l): for (i, n) in enumerate(r): if (n != ...
_renderer(wrap_type=TestColumnAllUniqueValues) class TestColumnAllUniqueValuesRenderer(TestRenderer): def render_html(self, obj: TestColumnAllUniqueValues) -> TestHtmlInfo: info = super().render_html(obj) column_name = obj.column_name counts_data = obj.metric.get_result().plot_data.counts_of...
(scope='function') def pymssql_connection(request): conn = pymssql.connect(os.environ.get('MSSQL_HOST', 'localhost'), os.environ.get('MSSQL_USER', 'SA'), os.environ.get('MSSQL_PASSWORD', 'Very(!)Secure'), os.environ.get('MSSQL_DATABASE', 'tempdb')) cursor = conn.cursor() cursor.execute("CREATE TABLE test(id...
.parametrize('test_input,expected', [(Action('autoscaling', 'DescribeLaunchConfigurations'), [Action('autoscaling', 'CreateLaunchConfiguration'), Action('autoscaling', 'DeleteLaunchConfiguration')]), (Action('autoscaling', 'CreateLaunchConfiguration'), [Action('autoscaling', 'DeleteLaunchConfiguration'), Action('autosc...
def test_def_rename_only_variable_nested(): string = write_rpc_request(1, 'initialize', {'rootPath': str(test_dir)}) file_path = ((test_dir / 'subdir') / 'test_rename.F90') string += def_request(file_path, 15, 6) (errcode, results) = run_request(string) assert (errcode == 0) ref_res = [[1, 1, st...
def test_rmsd_grad(): rs = RandomState(MT19937(SeedSequence())) n = 3 coords3d = np.eye(3) ref_coords3d = (coords3d + (0.2 * rs.random((n, 3)))) (rmsd, grad) = rmsd_grad(coords3d, ref_coords3d) assert (rmsd == approx(0.0508618)) ref_grad = np.array([[0., (- 0.), (- 0.)], [(- 0.), (- 0.), 0.]...
class TicketTester(UnitTestDBBase): def setUp(self): super(TicketTester, self).setUp() from stalker import Status self.test_status1 = Status(name='N', code='N') self.test_status2 = Status(name='R', code='R') from stalker import Type ticket_types = Type.query.filter((T...
def create_address(details, county_details, state_details, doctype, ref_docname): address = frappe.new_doc('Address') address.address_type = 'Billing' address.address_line1 = details['address1'] address.address_line2 = details['address2'] address.city = details['city'] address.country = county_d...
def test(tmpdir, tb, interface, reset, hdl, simtool, defines=[], gui=False, pytest_run=True): tb_dir = path_join(TEST_DIR, 'test_rmap') beh_dir = path_join(TEST_DIR, 'beh') sim = Simulator(name=simtool, gui=gui, cwd=tmpdir) sim.incdirs += [tmpdir, tb_dir, beh_dir] sim.sources += [path_join(tb_dir, (...
def usage(): print(('%s version %s\nusage: %s [-aeqhCx] [-s server] [-p port] [-c count] [-t type] [-w wait] hostname\n\n -h --help Show this help\n -q --quiet Quiet mode: No extra information, only traceroute output.\n -T --tcp Use TCP as transport protocol\n -x --expert Print expert hin...
def encrypt(body): enc = {'0': '7', '1': '1', '2': 'u', '3': 'N', '4': 'K', '5': 'J', '6': 'M', '7': '9', '8': "'", '9': 'm', '!': 'P', '%': '/', "'": 'n', '(': 'A', ')': 'E', '*': 's', '+': '+', '-': 'f', '.': 'q', 'A': 'O', 'B': 'V', 'C': 't', 'D': 'T', 'E': 'a', 'F': 'x', 'G': 'H', 'H': 'r', 'I': 'c', 'J': 'v', ...
class TraitInstance(TraitHandler): def __init__(self, aClass, allow_none=True, module=''): self._allow_none = allow_none self.module = module if isinstance(aClass, str): self.aClass = aClass else: if (not isinstance(aClass, type)): aClass = aCl...
class ExperimentLogger(ABC): def log_hyperparams(self, params: tp.Union[(tp.Dict[(str, tp.Any)], Namespace)], metrics: tp.Optional[dict]=None) -> None: ... def log_metrics(self, prefix: tp.Union[(str, tp.List[str])], metrics: dict, step: tp.Optional[int]=None) -> None: ... def log_audio(self...
class OptionSeriesTimelineSonificationDefaultspeechoptions(Options): def activeWhen(self) -> 'OptionSeriesTimelineSonificationDefaultspeechoptionsActivewhen': return self._config_sub_data('activeWhen', OptionSeriesTimelineSonificationDefaultspeechoptionsActivewhen) def language(self): return sel...
def get_int_column_roots(grid): for tile_name in sorted(grid.tiles()): loc = grid.loc_of_tilename(tile_name) gridinfo = grid.gridinfo_at_loc(loc) if (gridinfo.tile_type not in INT_TILE_TYPES): continue next_gridinfo = grid.gridinfo_at_loc((loc.grid_x, (loc.grid_y + 1))) ...
class Text(MixHtmlState.HtmlStates, Html.Html): name = 'Text' tag = 'div' _option_cls = OptText.OptionsText def __init__(self, page: primitives.PageModel, text: str, color: str, align: str, width, height, html_code: str, tooltip: str, options, helper: str, profile): super(Text, self).__init__(pa...
class DB(Gbfs): authed = True meta = {'company': ['Deutsche Bahn AG'], 'system': 'deutschebahn'} def __init__(self, tag, meta, key, provider, bbox=None): self.key = key super(DB, self).__init__(tag, meta, FEED_URL.format(provider=provider), bbox=bbox) def auth_headers(self): retu...
class OptionPlotoptionsLollipopSonificationDefaultinstrumentoptions(Options): def activeWhen(self) -> 'OptionPlotoptionsLollipopSonificationDefaultinstrumentoptionsActivewhen': return self._config_sub_data('activeWhen', OptionPlotoptionsLollipopSonificationDefaultinstrumentoptionsActivewhen) def instrum...
def find_available_port(custom_host: Optional[str]=None, custom_range: Optional[range]=None, will_close_then_reopen_socket: bool=False) -> Tuple[(str, int, socket.socket)]: current_host = (custom_host if (custom_host is not None) else _get_ip_address()) current_range = (custom_range if (custom_range is not None...
class TestCanRaiseHTTPError(): (autouse=True) def patch_ patch_ pass def setup_method(self): def no_error(): pass def raise_ raise def raise_generic_error(): raise ValueError('Not HTTP Error') self.no_error = no_error self....
class MyBackgroundMainNode(Node): config: MyBackgroundMainConfig def setup(self) -> None: self.barrier = threading.Barrier(2) async def my_background(self) -> None: with open(self.config.background_filename, 'w') as f: f.write(self.config.string) self.barrier.wait() d...
def create_production_storage(fuel_type: str, production_point: dict[(str, float)], negative_threshold: float) -> tuple[((ProductionMix | None), (StorageMix | None))]: production_value = production_point['value'] production_mix = ProductionMix() storage_mix = StorageMix() if ((production_value < 0) and ...
def save_config(name, config: Dict, overwrite=False): config_path = ((Path(__file__).parent.parent / 'config') / name) if (config_path.exists() and (not overwrite)): raise ValueError(f"pass overwrite=True to overwrite existing config: '{config_path}'") config_obj = configparser.ConfigParser() co...
def upgrade(): op.create_table('sandwiches', sa.Column('id', sa.String(256), primary_key=True), sa.Column('created_at', sa.TIMESTAMP, server_default=sa.func.now()), sa.Column('block_number', sa.Numeric, nullable=False), sa.Column('sandwicher_address', sa.String(256), nullable=False), sa.Column('frontrun_swap_transa...
class Trial(): condition: Condition stimuli: typing.List[Stimulus] results: RESULTS_T = field(default_factory=dict, compare=False) identifier: typing.Optional[int] = field(default=None, compare=False) def __post_init__(self) -> None: for stimulus in self.stimuli: stimulus.trial =...
def checkTcpMssClamp(tcp_mss_clamp_value): if tcp_mss_clamp_value: if tcp_mss_clamp_value.isdigit(): if (int(tcp_mss_clamp_value) < 536): return False elif (tcp_mss_clamp_value == 'None'): return True elif (tcp_mss_clamp_value != 'pmtu'): r...
def extractAlexanderwalesCom(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'), ('worth the candle', 'worth the candle', 'oel'), ('the dark wizard of d...
def get_filesystem_read_write_file_details(io, metadata, event, details_io, extra_detail_io): event.category = ('Read' if (event.operation == 'ReadFile') else 'Write') details_io.seek(4, 1) io_flags_and_priority = read_u32(details_io) io_flags = (io_flags_and_priority & ) priority = ((io_flags_and_p...
class OkLCh(base.OkLCh): def to_string(self, parent: Color, *, alpha: (bool | None)=None, precision: (int | None)=None, fit: ((bool | str) | dict[(str, Any)])=True, none: bool=False, color: bool=False, percent: (bool | Sequence[bool])=False, **kwargs: Any) -> str: return serialize.serialize_css(parent, func...
class TestsTOML(): __init__ = _custom_dataclass_init cases: Dict[(str, TestCaseTOML)] def load(cls, toml_path: Path): with toml_path.open('rb') as f: data = tomllib.load(f) return cls({uuid: TestCaseTOML(uuid, *opts) for (uuid, opts) in data.items() if (opts.get('include', None) ...
class AttachedWindow(Gtk.Window): __gsignals__ = {'show': 'override'} def __init__(self, parent): Gtk.Window.__init__(self, Gtk.WindowType.TOPLEVEL) self.set_decorated(False) self.props.skip_taskbar_hint = True self.set_keep_above(True) self.realize() self.get_win...
class _MagiclinkReferencePattern(_MagiclinkShorthandPattern): def process_issues(self, el, provider, user, repo, issue): issue_type = issue[:1] issue_value = issue[1:] if (issue_type == '#'): issue_link = PROVIDER_INFO[provider]['issue'] issue_label = self.labels.get(...
def test_component_loading_module_not_found_error_non_framework_package(component_configuration): with mock.patch.object(Protocol, 'from_config', side_effect=ModuleNotFoundError("No module named 'generic.package'")): with pytest.raises(ModuleNotFoundError): load_component_from_config(component_c...
class ButtonMenuItem(): name = 'Button Menu Item' def __init__(self, page: primitives.PageModel, component_id: str, container: Html.Html): (self.component_id, self.page) = (component_id, page) (self.container, self._js, self._events) = (container, None, []) def js(self) -> JsComponents.Menu:...
def entry_points(*, group: str) -> 'metadata.EntryPoints': if (sys.version_info >= (3, 10)): return metadata.entry_points(group=group) epg = metadata.entry_points() if ((sys.version_info < (3, 8)) and hasattr(epg, 'select')): return epg.select(group=group) return epg.get(group, [])
.provider(fields.Dictionary({}, description='Most client middleware has no constructor arguments, but subclasses can override this schema')) class ClientMiddleware(object): def request(self, send_request): return send_request def response(self, get_response): return get_response
def custom_break_flow(self): if (self.name in (conditional_branch + unconditional_branch)): return True if self.name.startswith('LOOP'): return True if self.name.startswith('RET'): return True if self.name.startswith('INT'): return True if self.name.startswith('SYS'):...
def _register_worker_signals(client) -> None: def worker_shutdown(*args, **kwargs) -> None: client.close() def connect_worker_process_init(*args, **kwargs) -> None: signals.worker_process_shutdown.connect(worker_shutdown, dispatch_uid='elasticapm-shutdown-worker', weak=False) signals.worker_...
def kernel_name(op, func_attrs): from cutlass_lib import library threadblock = op.tile_description.procedural_name() extended_name = op.extended_name() opcode_class_name = library.OpcodeClassNames[op.tile_description.math_instruction.opcode_class] layout = op.layout_name() align_ab = op.A.alignm...
_dataloader('youtube-to-text') class YoutubeToTextDataloader(SpeechToTextDataloader): def from_youtube(cls, source: Union[(Path, str)], target: Union[(Path, str)]) -> YoutubeToTextDataloader: assert (AudioSegment is not None) assert (youtube_dl is not None) source_list = [download_youtube_vi...
('llama_recipes.finetuning.train') ('llama_recipes.finetuning.LlamaForCausalLM.from_pretrained') ('llama_recipes.finetuning.LlamaTokenizer.from_pretrained') ('llama_recipes.finetuning.get_preprocessed_dataset') ('llama_recipes.finetuning.optim.AdamW') ('llama_recipes.finetuning.StepLR') def test_batching_strategy(step_...
class TestSuperFencesCustomException(util.MdCase): extension = ['pymdownx.superfences'] extension_configs = {'pymdownx.superfences': {'custom_fences': [{'name': 'test', 'class': 'test', 'format': custom_format, 'validator': custom_validator_except}]}} def test_custom_fail_exception(self): with self....
def main(): segmk = Segmaker('design.bits') tiledata = {} pipdata = {} ignpip = set() with open(os.path.join(os.getenv('FUZDIR'), '..', 'piplist', 'build', 'clk_bufg', 'clk_bufg_bot_r.txt')) as f: for l in f: (tile_type, dst, src) = l.strip().split('.') if (tile_type ...
def test_bad_whitelist(utils): badConfig = {'elements_in': ['sel1/an1/el1']} badAn = EmptyAnalyser(badConfig, 'whitelistErrorAnalyser', LocalStorage(folder=utils.TEMP_ELEMENT_DIR)) with pytest.raises(InvalidAnalyserElements, match="'elements_in' you specified does not exist"): badAn.start_analysing(...
def option_parser(): parser = argparse.ArgumentParser() parser.add_argument('--texture_feat_file', type=str, help='pickle file with texture features of pieces') parser.add_argument('--shape_feat_file', type=str, help='pickle file with shape features of pieces') parser.add_argument('--dataset_dir', type=...
def make_keck_atmospheric_layers(input_grid): heights = np.array([0, 2100, 4100, 6500, 9000, 12000, 14800]) velocities = np.array([6.7, 13.9, 20.8, 29.0, 29.0, 29.0, 29.0]) outer_scales = np.array([20, 20, 20, 20, 20, 20, 20]) Cn_squared = (np.array([0.369, 0.219, 0.127, 0.101, 0.046, 0.111, 0.027]) * 1...
class TASProgramActivityList(PaginationMixin, AgencyBase): endpoint_doc = 'usaspending_api/api_contracts/contracts/v2/agency/treasury_account/tas/program_activity.md' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.params_to_validate = ['fiscal_year', 'filter'] ...
def main(): segmk = Segmaker('design.bits') designdata = {} tiledata = {} pipdata = {} ppipdata = {} ignpip = set() all_clks = {} piplists = ['cmt_top_l_upper_t.txt', 'cmt_top_r_upper_t.txt'] wirelists = ['cmt_top_l_upper_t_wires.txt', 'cmt_top_r_upper_t_wires.txt'] ppiplists = [...
def _filter_node_ids(unique_ids: List[str], fal_dbt: FalDbt, selectors: List[str], nodeGraph: NodeGraph) -> List[str]: output = set() union = parse_union(selectors) for intersection in union.components: try: plan_outputs = [set(SelectorPlan(selector, unique_ids, fal_dbt).execute(nodeGrap...
def parse(repo, tag): with open(os.path.join(current_dir, 'tags', repo, repo, 'emoji.json'), 'r') as f: emojis = json.loads(f.read()) emoji_db = {} shortnames = set() aliases = {} for v in emojis.values(): shortnames.add(v['shortname']) emoji_db[v['shortname']] = {'name': v['...
class NodeModel(): def __init__(self, grid, connections, tile_wires, node_wires, progressbar=None): self.grid = grid self.connections = connections self.tile_wires = tile_wires self.specific_node_wires = set(node_wires['specific_node_wires']) node_pattern_wires = node_wires['...
def launch_job(args, j): img = j['image'] if ('/' in img): pull_image(args.sudo, img) c = [] if args.sudo: c += ['sudo'] c += ['docker', 'run'] if args.background: c += ['-d'] else: c += ['-it'] work_dir = os.path.abspath(os.path.dirname(__file__)) pro...
class OptionPlotoptionsCylinderSonificationContexttracksMappingHighpassResonance(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, tex...
def wrap_workflow_list_response(workflow_list: List[WorkflowProto]): if ((workflow_list is None) or (len(workflow_list) == 0)): return Response(return_code=str(RESOURCE_DOES_NOT_EXIST), error_msg=ReturnCode.Name(RESOURCE_DOES_NOT_EXIST).lower(), data=None) else: list_proto = WorkflowListProto(wo...
class _HVMType(models.Model): Hypervisor_KVM = 1 Hypervisor_BHYVE = 2 Hypervisor_NONE = 3 HVM_TYPE = ((Hypervisor_KVM, _('KVM hypervisor')), (Hypervisor_BHYVE, _('BHYVE hypervisor')), (Hypervisor_NONE, _('NO hypervisor'))) HVM_TYPE_GUI = ((Hypervisor_KVM, _('KVM')), (Hypervisor_BHYVE, _('BHYVE'))) ...
class Group(db.Model, helpers.Serializer): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(127)) fas_name = db.Column(db.String(127), unique=True) def at_name(self): return u'{}'.format(self.name) def __str__(self): return self.__unicode__() def __unicode_...
class DatePicker(Control): def __init__(self, ref: Optional[Ref]=None, expand: Optional[Union[(bool, int)]]=None, col: Optional[ResponsiveNumber]=None, opacity: OptionalNumber=None, tooltip: Optional[str]=None, visible: Optional[bool]=None, disabled: Optional[bool]=None, data: Any=None, open: bool=False, value: Opt...
def test_butterworth_raises_exception_with_cutoff_having_its_biggest_value_bigger_than_frequency_divided_by_2(trace): with pytest.raises(ValueError): scared.signal_processing.butterworth(trace, 15, [1, 10], filter_type=scared.signal_processing.FilterType.BAND_PASS) with pytest.raises(ValueError): ...
def swapuvs(self, context): uv_layers = bpy.context.object.data.uv_layers if ((uv_layers.active_index == 0) and (not self.is_down)): return {'FINISHED'} elif ((uv_layers.active_index == (len(uv_layers) - 1)) and self.is_down): return {'FINISHED'} def get_index(name): return [i fo...
class CourseSerializers(serializers.ModelSerializer): add_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', required=False, read_only=True) image = serializers.ImageField(required=False) user = UserSerializer(read_only=True) courselist_set = AddtutorialSerializers(many=True) class Meta():...