code
stringlengths
281
23.7M
class SetCI(SimpleTool): name = 'SetCI' description = 'Configure the commands to run, lint, test the project or lint a file (`{command} {file}` will be used). Input format: `lint: "command", lintfile: "command", test: "command", run: "command"`' structured_desc = 'Configure the commands to run, lint, test t...
def parse(text, encoding='utf-8', handler=None, **defaults): text = u(text, encoding).strip() metadata = defaults.copy() handler = (handler or detect_format(text, handlers)) if (handler is None): return (metadata, text) try: (fm, content) = handler.split(text) except ValueError: ...
def test_setGlyphOrder_also_updates_glyf_glyphOrder(): font = TTFont() font.importXML(os.path.join(DATA_DIR, 'TestTTF-Regular.ttx')) current_order = font.getGlyphOrder() assert (current_order == font['glyf'].glyphOrder) new_order = list(current_order) while (new_order == current_order): ...
class LinkerEntryOffset(LinkerEntry): def __init__(self, segment: Segment): super().__init__(segment, [], Path(), 'linker_offset', 'linker_offset', False) self.object_path = None def emit_entry(self, linker_writer: LinkerWriter): linker_writer._write_symbol(f'{self.segment.get_cname()}_O...
def filter_endpoint_control_forticlient_ems_data(json): option_list = ['address', 'admin_password', 'admin_type', 'admin_username', ' 'listen_port', 'name', 'rest_api_auth', 'serial_number', 'upload_port'] json = remove_invalid_fields(json) dictionary = {} for attribute in option_list: if ((attr...
def sharpe_iid_adjusted(rtns, bench=0, factor=1, log=True): sr = sharpe_iid(rtns, bench=bench, factor=1, log=log) if _is_pandas(rtns): skew = rtns.skew() excess_kurt = rtns.kurtosis() else: skew = ss.skew(rtns, bias=False, nan_policy='omit') excess_kurt = ss.kurtosis(rtns, bi...
def prepare_query(query: str) -> Tuple[(str, List[str])]: statements = sqlparse.parse(query) if (len(statements) != 1): raise ValueError('Only one SQL statement is allowed.') statement: sqlparse.sql.Statement = statements[0] if (statement.get_type() != 'SELECT'): raise ValueError('Only S...
def _start(): global patch, name, path, monitor global pin, delay, scale_duration, offset_duration, lock, trigger pin = {'gpio0': 0, 'gpio1': 1, 'gpio2': 2, 'gpio3': 3, 'gpio4': 4, 'gpio5': 5, 'gpio6': 6, 'gpio7': 7, 'gpio21': 21, 'gpio22': 22, 'gpio23': 23, 'gpio24': 24, 'gpio25': 25, 'gpio26': 26, 'gpio27...
class OptionSeriesBarLabel(Options): def boxesToAvoid(self): return self._config_get(None) def boxesToAvoid(self, value: Any): self._config(value, js_type=False) def connectorAllowed(self): return self._config_get(False) def connectorAllowed(self, flag: bool): self._confi...
.parametrize('type_sep, counter_sep', [('', ''), ('_', '_')]) def test_hungarian_notation_separators(type_sep: str, counter_sep: str): true_value = LogicCondition.initialize_true(LogicCondition.generate_new_context()) ast = AbstractSyntaxTree(CodeNode(Assignment((var := Variable('var_0', I32)), Constant(0)), tr...
class OptionPlotoptionsCylinderStatesHover(Options): def animation(self) -> 'OptionPlotoptionsCylinderStatesHoverAnimation': return self._config_sub_data('animation', OptionPlotoptionsCylinderStatesHoverAnimation) def borderColor(self): return self._config_get(None) def borderColor(self, tex...
def describe_symbol(sym): assert (type(sym) == symtable.Symbol) print('Symbol:', sym.get_name()) for prop in ['referenced', 'imported', 'parameter', 'global', 'declared_global', 'local', 'free', 'assigned', 'namespace']: if getattr(sym, ('is_' + prop))(): print(' is', prop)
def extractPassivetranslationsCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('Hermione and the Genius Magic Formula', 'Hermione and the Genius Magic Formula', 'translated')...
class ShapeStar(): def __init__(self, points, indent=0.61): self.coords = self._calc_coords(points, (1 - indent)) def _calc_coords(self, points, indent): coords = [] from math import cos, pi, sin step = (pi / points) for i in range((2 * points)): if (i % 2): ...
def map_func(context): json_recorder = JsonRecorder(context.from_java(), context.to_java()) try: while True: data = json_recorder.read_record() print(context.index, 'data:', data) sys.stdout.flush() res = json_recorder.write_record(data) print(...
def format_custom_ner_examples(example: Dict): text = example['text'] entities = example['entities'] extracted_entities = [] for entity in entities: category = entity['category'] entity_name = entity['entity'] extracted_entities.append({'entity': entity_name, 'category': category...
class Cell(): def __init__(self): self._watchers = [] self._value = None self.counter = 0 def add_watcher(self, cell): self._watchers.append(cell) def value(self): return self._value def value(self, new_value): self._value = new_value self.counter ...
def serialize_to_folder(pkgs: typing.List[str], settings: SerializationSettings, local_source_root: typing.Optional[str]=None, folder: str='.', options: typing.Optional[Options]=None): if (folder is None): folder = '.' loaded_entities = serialize(pkgs, settings, local_source_root, options=options) p...
.parametrize(('input_data', 'expected_result'), [([('NX enabled', 1696, 0.89122), ('NX disabled', 207, 0.10878), ('Canary enabled', 9, 0.00473)], {'labels': ['NX enabled', 'NX disabled', 'Canary enabled'], 'datasets': [{'data': [1696, 207, 9], 'percentage': [0.89122, 0.10878, 0.00473], 'backgroundColor': ['#4062fa', '#...
def test_machine_should_activate_initial_state(): class CampaignMachine(StateMachine): producing = State() closed = State(final=True) draft = State(initial=True) add_job = (draft.to(draft) | producing.to(producing)) produce = draft.to(producing) deliver = producing.to...
class SurfaceConfig(ParameterConfig): ncol: int nrow: int xori: float yori: float xinc: float yinc: float rotation: float yflip: int forward_init_file: str output_file: Path base_surface_path: str def from_config_list(cls, surface: List[str]) -> Self: options = op...
def assert_decoder_with_cache_output_equals_hf(orig_model: DecoderModule, hf_model: 'transformers.AutoModel', torch_device: torch.device, atol: float, rtol: float, jit_method: JITMethod, with_torch_sdp=False): X_jit = torch.randint(0, hf_model.config.vocab_size, (3, 5), device=torch_device) mask_jit = torch.one...
class DateEditorDemo(HasTraits): single_date = Date() multi_date = List(Date) info_string = Str('The editors for Traits Date objects. Showing both the defaults, and one with alternate options.') multi_select_editor = DateEditor(allow_future=False, multi_select=True, shift_to_select=False, on_mixed_sele...
class Link(object): swagger_types = {'deprecation': 'AlertEndPosition', 'href': 'Url', 'hreflang': 'str', 'name': 'str', 'profile': 'str', 'templated': 'bool', 'title': 'str', 'type': 'str'} attribute_map = {'deprecation': 'deprecation', 'href': 'href', 'hreflang': 'hreflang', 'name': 'name', 'profile': 'profil...
def main(): try: options = parse_options() setup_logging(options) scan_to_graph(['tomate'], graph) app = Application.from_graph(graph) app.Run() if app.IsRunning(): Gdk.notify_startup_complete() except Exception as ex: logger.error(ex, exc_info...
def instantiate_keystore(derivation_type: DerivationType, data: Dict[(str, Any)], parent_keystore: Optional[KeyStore]=None, row: Optional[MasterKeyRow]=None) -> KeyStore: keystore: KeyStore if (derivation_type == DerivationType.BIP32): keystore = BIP32_KeyStore(data, row, parent_keystore) elif (deri...
def moods(request): avatar_list = Avatars.objects.all() key = request.GET.get('key', '') mood_list = Moods.objects.filter(content__contains=key).order_by('-create_date') query_params = request.GET.copy() pager = Pagination(current_page=request.GET.get('page'), all_count=mood_list.count(), base_url=r...
class DomainSerializer(s.ConditionalDCBoundSerializer): _model_ = Domain _update_fields_ = ('owner', 'access', 'desc', 'dc_bound', 'type') _default_fields_ = ('name', 'owner', 'type') _blank_fields_ = frozenset({'desc'}) name_changed = None name = s.RegexField('^[A-Za-z0-9][A-Za-z0-9\\._/-]*$', ...
class Crawler(object): def run(self, resource): raise NotImplementedError('The run function of the crawler') def visit(self, resource): raise NotImplementedError('The visit function of the crawler') def dispatch(self, callback): raise NotImplementedError('The dispatch function of the...
class OptionSeriesWindbarbSonificationTracksMappingVolume(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 handle_pandas(values: List[Dict[(str, Union[(int, str, NotebookNode)])]]) -> List[Tuple[(int, str)]]: output = [] for value in values: index = int(value['index']) data = str(value['data']) df = pd.read_html(data, flavor='lxml') md_df = df[0] for column in md_df.column...
def extractJawzPublications(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol or frag)) or ('preview' in item['title'].lower())): return None if (('Zectas' in item['tags']) and vol and chp): return buildReleaseMessageWithType(item, 'Zecta...
class BookmarksManager(): __PATH = os.path.join(xdg.get_data_dirs()[0], 'bookmarklist.dat') def __init__(self): self.__db_file_lock = threading.RLock() self.__bookmarks = [] self.menu = None self.delete_menu = None self.__setup_menu() self.__load_db() def __se...
class ConvRecordEntry(): exec_entry: str exec_entry_sha1: str dtype_a: int dtype_b: int dtype_c: int dtype_acc: int major_a: int major_b: int major_c: int kh: int kw: int co: int strideh: int stridew: int padh: int padw: int dilateh: int dilatew: i...
([Output('modal-power-curve-chart', 'figure'), Output('modal-power-curve-card', 'style')], [Input('modal-activity-id-type-metric', 'children')], [State('activity-modal', 'is_open')]) def modal_power_curve(activity, is_open): if (activity and is_open): activity_id = activity.split('|')[0] activity_ty...
class DynamicLaunchPlanCommand(click.RichCommand): def __init__(self, name: str, h: str, lp_name: str, **kwargs): super().__init__(name=name, help=h, **kwargs) self._lp_name = lp_name self._lp = None def _fetch_launch_plan(self, ctx: click.Context) -> FlyteLaunchPlan: if self._lp...
class AMX_TILE(StaticMemory): NUM_AMX_TILES = 8 StaticMemory.init_state(NUM_AMX_TILES) tile_dict = {} def reset_allocations(cls): cls.init_state(cls.NUM_AMX_TILES) cls.tile_dict = {} def global_(cls): return '#include <immintrin.h>' def can_read(cls): return False...
class EventTrigger(_typing.TypedDict): eventFilters: _typing_extensions.NotRequired[dict[(str, (str | _params.Expression[str]))]] eventFilterPathPatterns: _typing_extensions.NotRequired[dict[(str, (str | _params.Expression[str]))]] channel: _typing_extensions.NotRequired[str] eventType: _typing_extensio...
class DataView(OverlayPlotContainer): orientation = Enum('h', 'v') default_origin = Enum('bottom left', 'top left', 'bottom right', 'top right') origin = Property(observe='default_origin') index_mapper = Instance(Base1DMapper) value_mapper = Instance(Base1DMapper) index_scale = Enum('linear', 'l...
class Test_UBIFS_Unpacker(TestUnpackerBase): def test_unpacker_selection_generic(self): self.check_unpacker_selection('filesystem/ubifs', 'UBIFS') def test_extraction(self): self.check_unpacking_of_standard_unpack_set(os.path.join(TEST_DATA_DIR, 'test.ubifs'), additional_prefix_folder='')
class OptionSeriesNetworkgraphSonificationTracksMappingVolume(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...
(scope='function') def access_manual_webhook(db, integration_manual_webhook_config) -> ConnectionConfig: manual_webhook = AccessManualWebhook.create(db=db, data={'connection_config_id': integration_manual_webhook_config.id, 'fields': [{'pii_field': 'email', 'dsr_package_label': 'email', 'data_categories': ['user.co...
class TestDocClassificationDataModule(testslide.TestCase): def setUp(self) -> None: super().setUp() self.patcher = patch('torchdata.datapipes.iter.util.cacheholder._hash_check', return_value=True) self.patcher.start() def tearDown(self) -> None: self.patcher.stop() super(...
class TestParseAmass(): def setup_method(self): self.tmp_path = Path(tempfile.mkdtemp()) self.scan = ParseAmassOutput(target_file=__file__, results_dir=str(self.tmp_path), db_location=str((self.tmp_path / 'testing.sqlite'))) self.scan.input = (lambda : luigi.LocalTarget(amass_json)) ...
class ClientKey(ModelNormal): allowed_values = {} validations = {} _property def additional_properties_type(): return (bool, date, datetime, dict, float, int, list, str, none_type) _nullable = False _property def openapi_types(): return {'client_key': (str,), 'signature': (st...
class _S3STSToken(BaseModel): cloud_path: str = Field(alias='cloudpath') user_credential: _UserCredential = Field(alias='userCredentials') def get_bucket(self) -> str: r = urllib.parse.urlparse(self.cloud_path) return r.netloc def get_s3_key(self) -> str: r = urllib.parse.urlpars...
class TestHistoryBuffer(unittest.TestCase): def setUp(self) -> None: super().setUp() np.random.seed(42) def create_buffer_with_init(num_values: int, buffer_len: int=1000000) -> typing.Callable[([], typing.Union[(object, np.ndarray)])]: max_value = 1000 values: np.ndarray = np.ran...
def test_lower_dimension_custom_medium_to_gds(tmp_path): geometry = td.Box(size=(2, 0, 2)) (nx, nz) = (100, 80) x = np.linspace(0, 2, nx) y = np.array([0.0]) z = np.linspace((- 1), 1, nz) f = np.array([td.C_0]) (mx, my, mz, _) = np.meshgrid(x, y, z, f, indexing='ij', sparse=True) data = ...
def get_user(username, password): with session_scope() as session: if (session.query(User).count() == 0): user = User(username=config.username, is_admin=True) user.set_password(password=config.password) session.add(user) user = session.query(User).filter((User.use...
class OptionPlotoptionsArearangeSonificationPointgrouping(Options): def algorithm(self): return self._config_get('minmax') def algorithm(self, text: str): self._config(text, js_type=False) def enabled(self): return self._config_get(True) def enabled(self, flag: bool): sel...
def get_response_with_params(zone_key: str, url, session: (Session | None)=None, params=None): ses = (session or Session()) response: Response = ses.get(url, params=params) if (response.status_code != 200): raise ParserException(zone_key, f'Response code: {response.status_code}') return response
def comparetime(tstr): result = True try: tstr2 = tstr.replace(':', ',') tstr2 = tstr2.replace('==', '=') sides = tstr2.split('=') tleft = sides[0].split(',') tright = sides[1].split(',') tleft[0] = tleft[0].lower() tright[0] = tright[0].lower() l1...
class ArrayAccessDetection(PipelineStage): name = 'array-access-detection' def __init__(self): self._candidates: DefaultDict[(Variable[Pointer], List[Candidate])] self._candidate_offset_classes: Dict[(Variable, OffsetInfo)] def run(self, task: DecompilerTask) -> None: if (not task.op...
def test_approval_request(): testutil.add_response('login_response_200') testutil.add_response('api_version_response_200') testutil.add_response('approval_request_response_200') client = testutil.get_client() body = {'requests': [{'actionType': 'Submit', 'contextId': 'ueBV', 'nextApproverIds': ['j3h...
class PandasFrameWrapper(Wrapper): def __init__(self, frame, **kwargs): self.frame = frame self.lat = 'cannot-find-latitude-column' self.lon = 'cannot-find-longitude-column' self.time = 'time' if ('time' not in self.frame): self.time = 'date' for (lat, lon...
class reiterable(_coconut_has_iter): __slots__ = () def __new__(cls, iterable): if _coconut.isinstance(iterable, _coconut.reiterables): return iterable return _coconut.super(_coconut_reiterable, cls).__new__(cls, iterable) def get_new_iter(self): (self.iter, new_iter) = _...
def test_award_endpoint_parent_award_no_submissions(client, awards_and_transactions): resp = client.get('/api/v2/awards/7/') assert (resp.status_code == status.HTTP_200_OK) assert (json.loads(resp.content.decode('utf-8'))['parent_award'] == expected_contract_award_parent(include_slug=False)) resp = clie...
.parametrize('language, setup_commands', [('py', ['pip install -r requirements.txt', 'python main.py', 'pytest']), ('js', ['npm install', 'node app.js', 'npm test'])]) def test_getting_started_with_language_setup(language, setup_commands, config, config_helper): deps = ['pytest', 'tensorflow', 'python'] summari...
def test_import(): import proteus successful_import = True for m in proteus.__all__: try: module = __import__(('proteus.' + m), fromlist=['proteus']) except: (exc_type, exc_value, exc_traceback) = sys.exc_info() print(repr(traceback.extract_tb(exc_tracebac...
def build_pdf_report(firmware: Firmware, folder: Path) -> Path: _initialize_subfolder(folder, firmware) try: result = run_docker_container('fkiecad/fact_pdf_report', combine_stderr_stdout=True, mem_limit='512m', mounts=[Mount('/tmp/interface/', str(folder), type='bind')]) except (DockerException, Ti...
class OptionPlotoptionsVectorClusterZonesMarker(Options): def enabled(self): return self._config_get(None) def enabled(self, flag: bool): self._config(flag, js_type=False) def fillColor(self): return self._config_get(None) def fillColor(self, text: str): self._config(text...
def test_list_processes(): expected_name_list = ['prefix/image_1', 'prefix/image_2', 'prefix/image_3'] expected_image_list = [] for image_name in expected_name_list: mock_container = mock.Mock() mock_container.name = image_name expected_image_list.append(mock_container) image_fil...
def extractNanashitranslationsWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('Miniature Medical Goddess', 'Miniature Medical Goddess', 'translated'), ("The Wolf Lo...
def configure_connection_params(arg_parser, args, cfg): target_hosts = opts.TargetHosts(args.target_hosts) cfg.add(config.Scope.applicationOverride, 'client', 'hosts', target_hosts) client_options = opts.ClientOptions(args.client_options, target_hosts=target_hosts) cfg.add(config.Scope.applicationOverri...
.django_db def test_federal_account_count_specific(client, agency_account_data): resp = client.get(url.format(code='008', filter='?fiscal_year=2017')) assert (resp.status_code == status.HTTP_200_OK) assert (resp.data['federal_account_count'] == 1) assert (resp.data['treasury_account_count'] == 1) re...
class Store(StoreT[(KT, VT)], Service): def __init__(self, url: Union[(str, URL)], app: AppT, table: CollectionT, *, table_name: str='', key_type: ModelArg=None, value_type: ModelArg=None, key_serializer: CodecArg=None, value_serializer: CodecArg=None, options: Optional[Mapping[(str, Any)]]=None, **kwargs: Any) -> ...
class TestCubicBezier(unittest.TestCase): def test_x_range(self): with self.assertRaises(ValueError): cubic_bezier(1.2, 0, 1, 1) with self.assertRaises(ValueError): cubic_bezier((- 0.2), 0, 1, 1) with self.assertRaises(ValueError): cubic_bezier(0, 0, 1.2, ...
class ZK_helper(object): def __init__(self, ip, port=4370): self.address = (ip, port) self.ip = ip self.port = port def test_ping(self): import subprocess, platform ping_str = ('-n 1' if (platform.system().lower() == 'windows') else '-c 1 -W 5') args = (((('ping '...
.parametrize('catalog_instance_no_server_process', [KFP_COMPONENT_CACHE_INSTANCE], indirect=True) def test_export_kubeflow_format_option(jp_environ, kubeflow_pipelines_runtime_instance, catalog_instance_no_server_process): runner = CliRunner() with runner.isolated_filesystem(): cwd = Path.cwd().resolve(...
class PluginInfo(): name: str module: str doc: str core: bool python_version: VersionType errbot_minversion: VersionType errbot_maxversion: VersionType dependencies: List[str] location: Path = None def load(plugfile_path: Path) -> 'PluginInfo': with plugfile_path.open(enc...
class AbstractStateBackend(): def from_bool_to_str_value(value): value = str(int(value)) if (value not in ['0', '1']): raise ValueError('state value is not 0|1') return value def from_str_to_bool_value(value): value = value.strip() if (value not in ['0', '1'])...
class TLSHInterface(ReadOnlyDbInterface): def get_all_tlsh_hashes(self) -> list[tuple[(str, str)]]: with self.get_read_only_session() as session: query = select(AnalysisEntry.uid, AnalysisEntry.result['tlsh']).filter((AnalysisEntry.plugin == 'file_hashes')).filter((AnalysisEntry.result['tlsh'] !...
def boolean(**kwargs): assert (len(kwargs) == 1) [(boolean_type, children)] = kwargs.items() if (not isinstance(children, list)): children = [children] dsl = defaultdict(list) if (boolean_type in ('must', 'filter')): for child in children: if (list(child) == ['bool']): ...
class OptionSeriesVectorSonificationContexttracksMappingVolume(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): s...
def test_path_curve(): white = Color('WHITE') red = Color('RED') blue = Color('BLUE') with Image(width=50, height=50, background=white) as img: with Drawing() as draw: draw.fill_color = blue draw.stroke_color = red draw.path_start() draw.path_move(...
def device_copy(dst_tensor: Tensor, src_tensor: Tensor, dst_idx: int) -> str: src_name = src_tensor._attrs['name'] dst_ptr = f'params_[{dst_idx}].ptr' shape = ['1'] for dim in dst_tensor._attrs['shape']: if isinstance(dim, IntImm): shape.append(str(dim._attrs['values'][0])) e...
def init_app(): global app, celery, config config = UchanConfig() setup_logging() import uchan.lib.database as database database.init_db() celery = Celery('uchan', loader=CustomCeleryLoader) celery.config_from_object({'result_backend': 'rpc://', 'task_serializer': 'pickle', 'accept_content':...
def test_param_convention_mars_1(): ('parameter', 'variable-list', convention='mars') def values_mars(parameter): return parameter assert (values_mars(parameter='tp') == ['tp']) assert (values_mars(parameter='2t') == ['2t']) assert (values_mars(parameter='t2m') == ['2t']) assert (values_...
def _lua_to_python(lval, return_status=False): import lua lua_globals = lua.globals() if (lval is None): return None if (lua_globals.type(lval) == 'table'): pval = [] for i in lval: if return_status: if (i == 'ok'): return lval[i] ...
class Frontend(Common): model_config = ConfigDict(extra='forbid') class Authentication(BaseModel): model_config = ConfigDict(extra='forbid') enabled: bool user_database: str password_salt: str communication_timeout: int = 60 authentication: Frontend.Authentication res...
def get_dbt_results(project_dir: str, config: RuntimeConfig) -> Optional[RunResultsArtifact]: results_path = os.path.join(config.target_path, 'run_results.json') try: return RunResultsArtifact.read_and_check_versions(results_path) except IncompatibleSchemaError as exc: exc.add_filename(resul...
def _compare_config(ref, other, path=[]): keys = sorted(ref.keys()) remaining = sorted((set(other.keys()) - set(ref.keys()))) delta = [] path.append(None) for key in keys: path[(- 1)] = key ref_value = ref[key] assert (key in other), f"XP config shouldn't be missing any key. ...
def extractBoredtransWordpressCom(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...
def test_table_multiline(header): data = [('hello', ['foo', 'bar', 'baz'], 'world'), ('hello', 'world', ['world 1', 'world 2'])] result = table(data, header=header, divider=True, multiline=True) assert (result == '\nCOL A COL B COL 3 \n----- ----- -------\nhello foo world \n bar ...
def run_component_modeler(monkeypatch, modeler: ComponentModeler): sim_dict = modeler.sim_dict batch_data = {task_name: run_emulated(sim) for (task_name, sim) in sim_dict.items()} monkeypatch.setattr(ComponentModeler, '_run_sims', (lambda self, path_dir: batch_data)) s_matrix = modeler.run(path_dir=mode...
class ExceptionsTestCase(unittest.TestCase): def test_option_not_valid(self): exception = OptionNotValid('Name', 'Value', 'Namespace/') self.assertEqual('Option (Namespace/Name=Value) have invalid name or value', exception.__str__()) def test_local_resource_not_found(self): exception = L...
class TestUserRecord(): .parametrize('data', (INVALID_DICTS + [{}, {'foo': 'bar'}])) def test_invalid_record(self, data): with pytest.raises(ValueError): auth.UserRecord(data) def test_metadata(self): metadata = auth.UserMetadata(10, 20) assert (metadata.creation_timestam...
class UrlSdkLoader(BaseSdkLoader): LOADER_MODE_KEY = 'url' def __init__(self, download_dir: str, url: str): super().__init__(download_dir) self.url = url def get_sdk_component(self, target: str) -> str: log.info(f'Fetching SDK from {self.url}') return self._fetch_file(self.ur...
class MultiResolutionDiscriminator(torch.nn.Module): def __init__(self, resolutions: list[tuple[int]]): super(MultiResolutionDiscriminator, self).__init__() self.discriminators = nn.ModuleList([DiscriminatorR(n_fft=n_fft, hop_length=hop_length, win_length=win_length) for (n_fft, hop_length, win_leng...
def test_errors(): forbidden_error = ForbiddenError({'source': ''}, 'Super admin access is required') assert (forbidden_error.status == 403) not_found_error = NotFoundError({'source': ''}, 'Object not found.') assert (not_found_error.status == 404) server_error = ServerError({'source': ''}, 'Interna...
() def setup_to_pass(): file_rules = ['-a always,exit -F arch=b64 -S chmod -S fchmod -S fchmodat -F auid>=1000 -F auid!= -k perm_mod', '-a always,exit -F arch=b32 -S chmod -S fchmod -S fchmodat -F auid>=1000 -F auid!= -k perm_mod', '-a always,exit -F arch=b64 -S chown -S fchown -S fchownat -S lchown -F auid>=1000 -...
def fastq_parser(infile): with myopen(infile) as f: while True: name = f.readline().strip() if (not name): break seq = f.readline().strip() name2 = f.readline().strip() qual = f.readline().strip() (yield Fastq(name, seq,...
class ColumnRegExpMetric(Metric[DataIntegrityValueByRegexpMetricResult]): column_name: str reg_exp: str top: int _reg_exp_compiled: Pattern def __init__(self, column_name: str, reg_exp: str, top: int=10, options: AnyOptions=None): self.top = top self.reg_exp = reg_exp self.co...
.skipif((not utils.complex_mode), reason='Test specific to complex mode') def test_assign_complex_value(cg1): f = Function(cg1) g = Function(cg1) f.assign((1 + 1j)) assert np.allclose(f.dat.data_ro, (1 + 1j)) f.assign(1j) assert np.allclose(f.dat.data_ro, 1j) g.assign(2.0) f.assign(((1 +...
('cuda.perm102_bmm_rcr.gen_function') def gen_function(func_attrs, exec_cond_template, dim_info_dict): bmm_problem_info = _get_strided_problem_info(func_attrs) problem_args = bmm_common.PROBLEM_ARGS_TEMPLATE.render(mm_info=bmm_problem_info) problem_args_cutlass_3x = bmm_common.PROBLEM_ARGS_TEMPLATE_CUTLASS_...
class ELFStructs(object): def __init__(self, little_endian=True, elfclass=32): assert ((elfclass == 32) or (elfclass == 64)) self.little_endian = little_endian self.elfclass = elfclass self.e_type = None self.e_machine = None self.e_ident_osabi = None def __getsta...
def _create_sales_invoices(unicommerce_order, sales_order, client: UnicommerceAPIClient): from ecommerce_integrations.unicommerce.invoice import create_sales_invoice facility_code = sales_order.get(FACILITY_CODE_FIELD) shipping_packages = unicommerce_order['shippingPackages'] for package in shipping_pac...
def organize_response_per_pages(original_response: Dict[(str, Any)]) -> List[Dict[(str, Any)]]: organized_pages = [] for page_index in range(1, (original_response['metadata']['documents'][0]['pages'] + 1)): page_dict = {'items': []} page_dict.update(extract_entities_for_page(original_response['e...
def compress_bytes(data, offset, dictionary): bits = 0 chunks = split32(data, offset) o = [] for (i, chunk) in enumerate(chunks): if (chunk in dictionary): o.append(bytes([dictionary.index(chunk)])) bits += (2 ** i) elif ((len(chunk) == 32) and (chunk[0] == 0)): ...
class TestConvTransducer(unittest.TestCase): def test_kernel_graph(self): def get_graph(l1, l2, add_skip=False): g = gtn.Graph() g.add_node(True) g.add_node(True) g.add_node() g.add_node(False, True) g.add_node(False, True) ...