code
stringlengths
281
23.7M
def print_info(node_name, color, id=None, trace_type=None, value=None, date=None, log_level=DEBUG): msg = '' if date: msg += f'[{str(date)[:40].ljust(20)}]' msg += f'[{str(getpid())[:5].ljust(5)}]' msg += f"[{current_thread().name.split('/')[(- 1)][:15].ljust(15)}]" msg += f"[{node_name.spli...
def extractHoshiandme(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return False if ('WATTT' in item['tags']): return buildReleaseMessageWithType(item, 'WATTT', vol, chp, frag=frag, postfix=...
class OptionSeriesBellcurveSonificationDefaultinstrumentoptions(Options): def activeWhen(self) -> 'OptionSeriesBellcurveSonificationDefaultinstrumentoptionsActivewhen': return self._config_sub_data('activeWhen', OptionSeriesBellcurveSonificationDefaultinstrumentoptionsActivewhen) def instrument(self): ...
class Main(flx.Widget): CSS = '\n .flx-Main {background: #eee;}\n ' def init(self): with flx.VFix(): flx.Widget(flex=1) with flx.HFix(flex=2): flx.Widget(flex=1) Drawing(flex=2) flx.Widget(flex=1) flx.Widget(flex=1...
def load_native_plugins(cfg: Config): if (not cfg.plugins_auto_load): print('not auto load_native_plugins') return def load_from_git(cfg: Config): print('async load_native_plugins') branch_name = cfg.plugins_git_branch native_plugin_repo = 'DB-GPT-Plugins' url = '...
class Ack(object): SIGNATURE = 2000 CONST_SIZE = Header.CONST_SIZE def from_raw_data(data: bytes) -> Ack: header = Header() header.parse_raw_data(data) return Ack(header) def from_reader(reader: socket) -> Ack: header = Header.from_reader(reader) return Ack(header...
.benchmark ('orca') .parametrize('fn, geom, charge, mult, ref_energy', S22Bm.geom_iter) def test_s22_set(fn, geom, charge, mult, ref_energy, this_dir): calc = ORCA(keywords='RI-MP2 6-31G** def2-SVP/C tightscf', pal=8, mem=1500, charge=charge, mult=mult) geom.set_calculator(calc) opt_kwargs = {'thresh': 'gau...
class OptionSonificationDefaultinstrumentoptionsPointgrouping(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): ...
class TableTeiTrainingDataGenerator(AbstractTeiTrainingDataGenerator): DEFAULT_TEI_FILENAME_SUFFIX = '.table.tei.xml' DEFAULT_DATA_FILENAME_SUFFIX = '.table' def __init__(self): super().__init__(root_training_xml_element_path=ROOT_TRAINING_XML_ELEMENT_PATH, training_xml_element_path_by_label=TRAININ...
def _step_wizard(caller, raw_string, **kwargs): steps = kwargs.get('steps', []) nsteps = len(steps) istep = kwargs.get('istep', (- 1)) step_direction = kwargs.get('step', 'forward') if (step_direction == 'back'): if (istep <= 0): return 'node_combat' istep = kwargs['istep...
def test_unmined_transaction_wait_for_receipt(w3): w3.middleware_onion.add(unmined_receipt_simulator_middleware) txn_hash = w3.eth.send_transaction({'from': w3.eth.coinbase, 'to': '0xd3CdA913deB6f67967B99D67aCDFa1712C293601', 'value': 123457}) with pytest.raises(TransactionNotFound): w3.eth.get_tran...
class DeleteIndex(Runner): async def __call__(self, es, params): ops = 0 indices = mandatory(params, 'indices', self) only_if_exists = params.get('only-if-exists', False) request_params = params.get('request-params', {}) prior_destructive_setting = None if ((not self....
def test_json_aliases(): ' schema = {'name': 'test_json_aliases', 'type': 'record', 'fields': [{'name': 'field_1', 'type': 'string'}, {'name': 'field_2', 'type': 'long'}]} reader_schema = {'name': 'test_json_aliases', 'type': 'record', 'fields': [{'name': 'new_field_1', 'type': 'string', 'aliases': ['field_...
def _get_fermi_surface(filename, interpolation_factor, properties, mu, decimate_factor, smooth, wigner_seitz, calculate_dimensionality): import numpy as np from pymatgen.electronic_structure.core import Spin from pymatgen.io.vasp.outputs import Vasprun from ifermi.interpolate import FourierInterpolator ...
def read_json(fn, serverMode=False): data = '' if (not fn): return None if (not os.path.isfile(fn)): print(('%s does not exist' % fn)) sys.exit(1) check_if_mounted(fn) f = open(fn) if serverMode: f.seek(0) jsonstr = f.read() jsonstr = ('{' + jsonst...
class ModelGenerator(PipelineStep[(DictEntries, TraceGraph)]): def __init__(self, record_meta_run_issue_instances: bool=False, meta_run_identifier: Optional[int]=None, archive_issue_instances_of_new_issues: bool=True, skip_traces: bool=False) -> None: super().__init__() self.summary: Summary ...
def get_scheme_data(is_jp: bool) -> list[list[int]]: scheme_data = game_data_getter.get_file_latest('DataLocal', 'schemeItemData.tsv', is_jp) if (scheme_data is None): helper.error_text('Failed to get scheme data') return [] scheme_data_data = helper.parse_int_list_list(csv_handler.parse_csv...
def get_uncanny_current() -> dict[(str, Any)]: total_subchapters = next_int(4) stages_per_subchapter = next_int(4) stars = next_int(4) if (total_subchapters < 1): next_int(4) raise Exception('Invalid total subchapters') else: clear_progress = get_length_data(4, 4, (total_subc...
('cuda.conv2d_depthwise_bias.gen_profiler') def gen_profiler(func_attrs, workdir, profiler_filename, shape_template): return common.gen_profiler(func_attrs=func_attrs, workdir=workdir, profiler_filename=profiler_filename, shape_template=shape_template, f_emit_instance=cdw.emit_instance, is_bias=True, is_depthwise=T...
class OptionAccessibility(Options): def announceNewData(self) -> 'OptionAccessibilityAnnouncenewdata': return self._config_sub_data('announceNewData', OptionAccessibilityAnnouncenewdata) def customComponents(self): return self._config_get(None) def customComponents(self, value: Any): ...
def load_data_infile(table_name, col_list, ignore: bool=False, enable_outfile_compression: bool=False) -> str: ignore_str = ('IGNORE' if ignore else '') return 'LOAD DATA INFILE %s {} INTO TABLE `{}`{} CHARACTER SET BINARY ({})'.format(ignore_str, escape(table_name), (' COMPRESSED' if enable_outfile_compression...
def test_handle_generic_model_type(): _registry.layers('my_transform.v1') def my_transform(model: Model[(int, int)]): model.name = 'transformed_model' return model cfg = {'': 'my_transform.v1', 'model': {'': 'Linear.v1'}} model = my_registry.resolve({'test': cfg})['test'] assert isin...
class ClassDatePicker(GrpCls.ClassHtml): def __init__(self, component: primitives.HtmlModel=None, page: primitives.PageModel=None): super(ClassDatePicker, self).__init__(component=component, page=page) self.classList['main'].add(CssToastDatePickerInput(self.page)) self.classList['main'].add(...
def test_filter_nested_array_field(): config = FilterPostProcessorConfiguration(field='attribute.email_contacts', value='') data = {'id': , 'attribute': {'email_contacts': ['']}, 'name': 'Somebody Cool'} processor = FilterPostProcessorStrategy(configuration=config) result = processor.process(data) a...
def tail_ratio(returns, tail_prob=5): if _is_pandas(returns): tail_prob /= 100.0 top = returns.quantile(q=(1 - tail_prob)) bottom = returns.quantile(q=tail_prob) return np.abs((top / bottom)) else: return (np.abs(np.nanpercentile(returns, (100 - tail_prob))) / np.abs(np.n...
.parametrize('beacon_id', [( + 1), , (- 1)]) def test_invalid_beacon_id(beacon_x86_bconfig, beacon_id): client = HttpBeaconClient() with pytest.raises(ValueError, match='^beacon_id must be less or equal than $'): client.run(bconfig=beacon_x86_bconfig, beacon_id=beacon_id, dry_run=True)
class OptionSeriesBellcurveSonificationDefaultinstrumentoptionsMappingHighpassResonance(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(se...
class Index(): def __init__(self, name, using='default'): self._name = name self._doc_types = [] self._using = using self._settings = {} self._aliases = {} self._analysis = {} self._mapping = None def get_or_create_mapping(self): if (self._mapping ...
class Signature(): def __init__(self, contig, start, end, signature, read): self.contig = contig self.start = start self.end = end self.signature = signature self.read = read self.type = None if (self.end < self.start): logging.warning(('Signature ...
class Test_link_trace_message(unittest.TestCase): def setUp(self): self.md_lv = 1 self.version = 1 self.opcode = cfm.CFM_LINK_TRACE_MESSAGE self.use_fdb_only = 1 self.first_tlv_offset = cfm.link_trace_message._TLV_OFFSET self.transaction_id = 12345 self.ttl = ...
class WallStairs(_WallMountedBox): description = 'You are supposed to add holes or slots to the stair tops yourself using Inkscape or another vector drawing or CAD program.\n\nsh gives height of the stairs from front to back. Note that the overall width and height is bigger than the nominal values as walls and the ...
def configure_mongo_connection(key: str, host: str, port: int, dbname: str, username: str, password: str): connection_secrets_data = {'host': host, 'port': port, 'defaultauthdb': dbname, 'username': username, 'password': password} connection_secrets_path = ops_urls.CONNECTION_SECRETS.format(connection_key=key) ...
def _start(): global patch, name, path, monitor global stepsize, clock, prefix, scale_active, scale_transpose, scale_note, scale_duration, offset_active, offset_transpose, offset_note, offset_duration, lock, key, sequencethread stepsize = patch.getfloat('general', 'delay') prefix = patch.getstring('outp...
class TestAccessCodeValidation(TestCase): def test_quantity_pass(self): schema = AccessCodeSchema() original_data = {'data': {}} data = {'min_quantity': 5, 'max_quantity': 10, 'tickets_number': 30} AccessCodeSchema.validate_order_quantity(schema, data, original_data) def test_qua...
class OptionSeriesBarSonificationPointgrouping(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): self._config(f...
def tokenize_dialog(dialog, tokenizer): prompt_tokens = [tokenizer.encode(f"{tokenizer.bos_token}{B_INST} {prompt['content'].strip()} {E_INST}", add_special_tokens=False) for prompt in dialog[::2]] answer_tokens = [tokenizer.encode(f"{answer['content'].strip()} {tokenizer.eos_token}", add_special_tokens=False) ...
class MicroLensArray(OpticalElement): def __init__(self, input_grid, lenslet_grid, focal_length, lenslet_shape=None): self.input_grid = input_grid self.focal_length = focal_length self.mla_grid = lenslet_grid if (lenslet_shape is None): (indices, distances) = closest_poin...
class FaucetUntaggedInfluxDownTest(FaucetUntaggedInfluxTest): def _start_gauge_check(self): return None def test_untagged(self): self.ping_all_when_learned() self._wait_error_shipping() self.verify_no_exception(self.env[self.gauge_controller.name]['GAUGE_EXCEPTION_LOG'])
def _graphs_equal(g1: ControlFlowGraph, g2: ControlFlowGraph) -> bool: if (type(g1) != type(g2)): return False for (x, y) in zip(g1.nodes, g2.nodes): if (x.instructions != y.instructions): from pprint import pprint pprint(x.instructions) pprint(y.instructions)...
def main(page: ft.Page): chart = ft.BarChart(bar_groups=[ft.BarChartGroup(x=0, bar_rods=[ft.BarChartRod(from_y=0, to_y=40, width=40, color=ft.colors.AMBER, tooltip='Apple', border_radius=0)]), ft.BarChartGroup(x=1, bar_rods=[ft.BarChartRod(from_y=0, to_y=100, width=40, color=ft.colors.BLUE, tooltip='Blueberry', bor...
class EmojiPack(models.Model): class Meta(): verbose_name = '' verbose_name_plural = '' id = models.AutoField(**_('ID'), primary_key=True) name = models.CharField(**_(''), max_length=100) avail_to = models.ManyToManyField(Player, **_(''), blank=True, related_name='emoji_sets') def __...
class ArrayNode(_common.FlyteIdlEntity): def __init__(self, node: 'Node', parallelism=None, min_successes=None, min_success_ratio=None) -> None: self._node = node self._parallelism = parallelism self._min_successes = min_successes self._min_success_ratio = min_success_ratio def n...
def setup_selinux_permissive(): original_status = shellexec('getenforce').stdout[0] shutil.copy('/etc/selinux/config', '/etc/selinux/config.bak') shellexec('setenforce 0') shellexec("sed -i '/^SELINUX=/ s/=.*/=permissive/' /etc/selinux/config") (yield None) shellexec(f'setenforce {original_statu...
def test_schema_migration_should_match_name(): ' writer_schema = {'type': 'record', 'name': 'root', 'namespace': 'example.space', 'fields': [{'name': 'id', 'type': 'string'}, {'name': 'data', 'type': ['null', {'type': 'record', 'name': 'SomeData', 'fields': [{'name': 'somedata_id', 'type': 'int'}, {'name': 'som...
class AuthRestClient(Auth): API_URL = '/cosmos/auth/v1beta1' def __init__(self, rest_api: RestClient): self._rest_api = rest_api def Account(self, request: QueryAccountRequest) -> QueryAccountResponse: json_response = self._rest_api.get(f'{self.API_URL}/accounts/{request.address}') r...
class HX711(): def __init__(self, dout, pd_sck, gain=128): self.DOUT = dout self.PD_SCK = pd_sck self.GAIN = 0 self.REFERENCE_UNIT = 1 self.REFERENCE_UNIT_B = 1 self.OFFSET = 1 self.OFFSET_B = 1 self.lastVal = int(0) self.DEBUG_PRINTING = False...
class DependencyGraph(DiGraph): def __init__(self, interference_graph: Optional[InterferenceGraph]=None): super().__init__() self.add_nodes_from(interference_graph.nodes) self.interference_graph = interference_graph def from_cfg(cls, cfg: ControlFlowGraph, interference_graph: Interferenc...
class NAeShop(): FORMAT = ' def __init__(self, game: 'Game'): self.game = game def ca_en(self) -> str: return NAeShop.FORMAT.format(lang='en', country='CA', slug=self.game.slug) def ca_fr(self) -> str: return NAeShop.FORMAT.format(lang='fr', country='CA', slug=self.game.slug) ...
def collect_imports(imports: Set[Any], type_: Any) -> None: if is_list_annotation(type_): collect_imports(imports, get_list_element_type(type_)) type_ = List elif is_dict_annotation(type_): kvt = get_dict_key_value_types(type_) collect_imports(imports, kvt[0]) collect_imp...
class OptionSeriesScatter3dSonificationTracksMappingTremoloDepth(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 SettingsTests(DatabaseTestCase): def setUp(self): super().setUp() self.app = self.flask_app.test_client() self.user = models.User(email='', username='user') user_social_auth = social_models.UserSocialAuth(user_id=self.user.id, user=self.user) self.session.add(self.user)...
def normalize_compiler_output(compiler_output: Dict[(str, Any)]) -> Dict[(str, Any)]: paths_and_names = [(path, contract_name) for path in compiler_output for contract_name in compiler_output[path].keys()] (paths, names) = zip(*paths_and_names) if (len(names) != len(set(names))): duplicates = {name ...
class FakeMprisPlayer(Thread): def __init__(self, *args, **kwargs): Thread.__init__(self, *args, **kwargs) async def start_server(self): bus = (await MessageBus().connect()) prog = TestPlayer('org.mpris.MediaPlayer2') controls = TestPlayerControls('org.mpris.MediaPlayer2.Player')...
def locate_srpm(dirpath): srpm_path = None path_matches = glob.glob(os.path.join(dirpath, '*.src.rpm')) for path_match in path_matches: if os.path.isfile(path_match): srpm_path = path_match break if (not srpm_path): raise RuntimeError('No .src.rpm found at {0}'.fo...
.parametrize('compiled', [True, False]) def test_write_bitfield(compiled): d = '\n struct test {\n uint16 a:1;\n uint16 b:1;\n uint32 c;\n uint16 d:2;\n uint16 e:3;\n };\n ' c = cstruct.cstruct() c.load(d, compiled=False) a = c.test() a.a = 1 a.b ...
def test_metadata_schedule(): s = schedule.Schedule('asdf', '1 3 4 5 6 7') obj = launch_plan.LaunchPlanMetadata(schedule=s, notifications=[]) assert (obj.schedule == s) obj2 = launch_plan.LaunchPlanMetadata.from_flyte_idl(obj.to_flyte_idl()) assert (obj == obj2) assert (obj2.schedule == s)
class MockDataItem(DataItem): def __init__(self, item: dict, container: typing.List[dict]) -> None: self._item = item self._container = container for (key, value) in item.items(): setattr(self, key, value) async def delete(self) -> None: self._container.remove(self._i...
class EVENT_HEADER(ct.Structure): _fields_ = [('Size', ct.c_ushort), ('HeaderType', ct.c_ushort), ('Flags', ct.c_ushort), ('EventProperty', ct.c_ushort), ('ThreadId', ct.c_ulong), ('ProcessId', ct.c_ulong), ('TimeStamp', wt.LARGE_INTEGER), ('ProviderId', GUID), ('EventDescriptor', ep.EVENT_DESCRIPTOR), ('KernelTime...
def assert_pandas_eland_series_equal(left, right, **kwargs): if (not isinstance(left, pd.Series)): raise AssertionError(f'Expected type pd.Series, found {type(left)} instead') if (not isinstance(right, ed.Series)): raise AssertionError(f'Expected type ed.Series, found {type(right)} instead') ...
class OptionSeriesBulletSonificationDefaultinstrumentoptionsMappingGapbetweennotes(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...
def lazy_import(): from fastly.model.pagination import Pagination from fastly.model.pagination_links import PaginationLinks from fastly.model.pagination_meta import PaginationMeta from fastly.model.tls_configuration_response_data import TlsConfigurationResponseData from fastly.model.tls_configuratio...
def create_url(request_url, file_relative_path): url = urlparse(request_url) port = url.port if (port and (url.scheme == SCHEMES.get(url.port, None))): port = None return '{scheme}://{hostname}:{port}{file_relative_path}'.format(scheme=url.scheme, hostname=url.hostname, port=port, file_relative_...
def get_config(a_layout, b_layout, c_layout): def config(func_attrs, dtype='float16'): import cutlass_lib layout_choice = {'c': cutlass_lib.library.LayoutType.ColumnMajor, 'r': cutlass_lib.library.LayoutType.RowMajor} def fproc(op): return common.default_fproc(op=op, a_layout=lay...
_api.route('/v1/vuln/products/<string:product>', methods=['GET']) _api.route('/v1/vuln/products/<string:product>/<string:version>', methods=['GET']) def get_vulns_by_product_and_version(product, version=None): vulns = InternalServer.get_mongodb_driver().get_vulnerabilities(product, version) if (len(vulns) == 0)...
class tundevs(tun_base): def dev_init(self, dev_name): self.register(self.fileno) self.add_evt_read(self.fileno) def handle_ip_packet_from_read(self, ip_packet): self.dispatcher.send_msg_to_tunnel_from_tun(ip_packet) def handle_ip_packet_for_write(self, ip_packet): return ip_...
class AppEngineServiceIterator(ResourceIterator): def iter(self): gcp = self.client try: for (data, metadata) in gcp.iter_gae_services(project_id=self.resource['id']): (yield FACTORIES['appengine_service'].create_new(data, metadata=metadata)) except ResourceNotSup...
def test_centered_product_with_two_frames_of_same_length_and_default_values(traces): expected = _read('centered_product_result_two_frames_same_length.npz') frame = slice(None, 50) frame_2 = slice(None, 50) result = scared.preprocesses.high_order.CenteredProduct(frame_1=frame, frame_2=frame_2)(traces) ...
class OptionSeriesOrganizationPointEvents(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 noop_config(): return f''' [nlp] lang = "en" pipeline = ["llm"] batch_size = 128 [components] [components.llm] factory = "llm" [components.llm.task] _tasks = "spacy.NER.v3" labels = PER,ORG,LOC [components.llm.task.normalizer] = "spacy.LowercaseNormalizer.v1" ...
class stat_v6(loxi.OFObject): def __init__(self, oxs_fields=None): if (oxs_fields != None): self.oxs_fields = oxs_fields else: self.oxs_fields = [] return def pack(self): packed = [] packed.append(('\x00' * 2)) packed.append(struct.pack('!H...
def _integ(img, r, c, rl, cl): r = _clip(r, 0, (img.shape[0] - 1)) c = _clip(c, 0, (img.shape[1] - 1)) r2 = _clip((r + rl), 0, (img.shape[0] - 1)) c2 = _clip((c + cl), 0, (img.shape[1] - 1)) ans = (((img[(r, c)] + img[(r2, c2)]) - img[(r, c2)]) - img[(r2, c)]) return max(0, ans)
class HostHeaderMapping(MappingTest): parent: AmbassadorTest def variants(cls) -> Generator[(Node, None, None)]: for st in variants(ServiceType): (yield cls(st, name='{self.target.name}')) def config(self) -> Generator[(Union[(str, Tuple[(Node, str)])], None, None)]: (yield (self...
def pwn(): reloc_index = ((bss_addr + 28) - rel_plt) r_sym = (((bss_addr + 40) - dynsym) / 16) r_type = 7 r_info = ((r_sym << 8) + (r_type & 255)) fake_reloc = (p32(write_got) + p32(r_info)) st_name = ((bss_addr + 56) - dynstr) st_bind = 1 st_type = 2 st_info = ((st_bind << 4) + (st_...
def test_interference_graph_of_group_first_graph_b(): interference_graph = construct_graph(1) sub_graph = interference_graph.get_subgraph_of(InsertionOrderedSet([v_1, v_2, v_3])) assert (InsertionOrderedSet(sub_graph.nodes) == InsertionOrderedSet([v_1, v_2, v_3])) assert (sub_graph.are_interfering(v_1, ...
def normalize_padding(padding: Optional[List[int]]) -> Optional[Padding]: if (padding and (len(padding) == 1)): return tuple([padding[0], padding[0], padding[0], padding[0]]) if (padding and (len(padding) == 2)): return tuple([padding[0], padding[1], padding[0], padding[1]]) if (padding and ...
class RandomizedResponseMechanism(DPBase): def __init__(self, epsilon, delta=0.0, sensitivity=1, domain=(0, 0)): (self.__epsilon, self.__delta) = self._check_epsilon_delta(epsilon, delta) self.__domain = domain self.__p = ((np.e ** epsilon) / ((np.e ** epsilon) + 1)) def randomize(self, ...
class AdminStatisticsGroupSchema(Schema): class Meta(): type_ = 'admin-statistics-group' self_view = 'v1.admin_statistics_group_detail' inflect = dasherize id = fields.String() groups = fields.Method('number_of_groups') group_events = fields.Method('number_of_group_events') f...
_renderer(wrap_type=TestF1ByClass) class TestF1ByClassRenderer(TestRenderer): def render_html(self, obj: TestF1ByClass) -> TestHtmlInfo: info = super().render_html(obj) curr_matrix = obj.conf_matrix.get_result().current_matrix ref_matrix = obj.conf_matrix.get_result().reference_matrix ...
def get_all_server_datasets(url: AnyHttpUrl, headers: Dict[(str, str)], exclude_datasets: List[Dataset]) -> List[Dataset]: exclude_dataset_keys = [dataset.fides_key for dataset in exclude_datasets] raw_dataset_list = (list_server_resources(url=url, resource_type='dataset', exclude_keys=[str(x) for x in exclude_...
def test(): assert (len(pattern1) == 2), 'El pattern1 deberia describir dos tokens.' assert (len(pattern2) == 2), 'El pattern2 deberia describir dos tokens.' assert (len(pattern1[0]) == 1), 'El primer token de pattern1 solo necesita un atributo.' assert any(((pattern1[0].get(l) == 'adidas') for l in ('L...
class MinHash(object): def __init__(self, num_perm: int=128, seed: int=1, hashfunc: Callable=sha1_hash32, hashobj: Optional[object]=None, hashvalues: Optional[Iterable]=None, permutations: Optional[Tuple[(Iterable, Iterable)]]=None) -> None: if (hashvalues is not None): num_perm = len(hashvalues...
class OptionSonificationGlobalcontexttracksActivewhen(Options): def crossingDown(self): return self._config_get(None) def crossingDown(self, num: float): self._config(num, js_type=False) def crossingUp(self): return self._config_get(None) def crossingUp(self, num: float): ...
def test_chunked_file_size_matches_range_with_range_header(): stat_cache = {__file__: fake_stat_entry()} responder = StaticFile(__file__, [], stat_cache=stat_cache) response = responder.get_response('GET', {'HTTP_RANGE': 'bytes=0-13'}) file_size = 0 assert (response.file is not None) while respo...
class TestRemoveConnectionWithPublicId(): def setup_class(cls): cls.runner = CliRunner() cls.agent_name = 'myagent' cls.cwd = os.getcwd() cls.t = tempfile.mkdtemp() shutil.copytree(Path(CUR_PATH, '..', 'packages'), Path(cls.t, 'packages')) cls.connection_id = str(HTTP...
class OptionPlotoptionsBubbleSonificationDefaultspeechoptionsMappingPlaydelay(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: ...
class InstagramCarousel(AbstractCrudObject): def __init__(self, fbid=None, parent_id=None, api=None): self._isInstagramCarousel = True super(InstagramCarousel, self).__init__(fbid, parent_id, api) class Field(AbstractObject.Field): caption_text = 'caption_text' comment_count = 'c...
def extractTarableTranslations(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol or frag)) or ('preview' in item['title'].lower())): return None tagmap = [("Soushiki Zerozaki's Human Exam", "Soushiki Zerozaki's Human Exam", 'translated')] for...
class NudgeStencilToDown(Operator): bl_idname = 'anima.general_nudge_stencil_to_down' bl_label = 'Nudge Stencil To Down' bl_description = 'Nudges the stencil 1 pixel to Down' def execute(self, context): import bpy brush = bpy.data.brushes['TexDraw'] stencil_pos = brush.stencil_po...
def test_broken_sul(assert_info): with dlis.load('data/chap2/incomplete-sul.dlis') as (f,): obj = f.object('RANDOM_SET3', 'RANDOM_OBJECT3') assert (obj['RANDOM_ATTRIBUTE3'] == [3]) assert (f.storage_label() is None) assert_info('found something that could be parts of a SUL')
def test_translate_sim_spectrum(): sim_params = SimParams([1, 1], [10, 0.5, 1], 0) (freqs, spectrum) = sim_power_spectrum([3, 40], *sim_params) (translated_spectrum, new_sim_params) = translate_sim_spectrum(spectrum, 0.5, sim_params) assert (not np.all((translated_spectrum == spectrum))) assert (new...
def generate_matviews(materialized_views_as_traditional_views: bool=False, parallel_worker_id: str=None) -> None: with connection.cursor() as cursor: cursor.execute(CREATE_READONLY_SQL) cursor.execute(DEPENDENCY_FILEPATH.read_text()) matview_dir = DEFAULT_MATIVEW_DIR if parallel_work...
class OptionPlotoptionsBoxplotSonificationTracks(Options): def activeWhen(self) -> 'OptionPlotoptionsBoxplotSonificationTracksActivewhen': return self._config_sub_data('activeWhen', OptionPlotoptionsBoxplotSonificationTracksActivewhen) def instrument(self): return self._config_get('piano') d...
def create_list_of_mock_enabled_api_resources(): resources = [] for data in feasd.ENABLED_APIS_RESOURCES: apis = mock.MagicMock() apis.data = json.dumps(data['enabled_apis']) apis.parent = mock.MagicMock() apis.parent.name = data['project_name'] apis.parent.full_name = da...
class Blueprint(Generic[T]): def __init__(self, model: T, fields: Opt[FieldMap]=None, pre_save: Opt[SaveHooks]=None, post_save: Opt[SaveHooks]=None, seed: Opt[Seed]=None): from .faker_factory import factory self.factory = factory self._model = model self._fields = (fields or {}) ...
class OptionSeriesBellcurveSonificationContexttracks(Options): def activeWhen(self) -> 'OptionSeriesBellcurveSonificationContexttracksActivewhen': return self._config_sub_data('activeWhen', OptionSeriesBellcurveSonificationContexttracksActivewhen) def instrument(self): return self._config_get('p...
class TableFilterEditor(Handler): editor = Instance(TableEditor) filter = Instance(TableFilter, allow_none=True) edit = Button() new = Button() apply = Button() delete = Button() def init(self, info): if (self.filter is None): self.filter = info.filter.factory.values[0] ...
.parametrize('emoji', ['', '\u200d', '']) def test_usage_merge_spans(nlp, emoji): text = ('This is %s a test' % emoji) doc = nlp(text) assert (len(doc) > 5) nlp.add_pipe('emoji') doc = nlp(text) assert (len(doc) == 5) assert doc._.has_emoji assert doc[2]._.is_emoji assert (len(doc[2]...
def find_bitslips_delays(wb): nbitslips = 8 ndelays = 32 nmodules = 2 nwords = 16 final_bitslip = None final_delay = None for bitslip in range(nbitslips): print('bitslip {:d}: |'.format(bitslip), end='') for delay in range(ndelays): for module in range(nmodules): ...
class ContractApiHandler(Handler): SUPPORTED_PROTOCOL = ContractApiMessage.protocol_id def setup(self) -> None: def handle(self, message: Message) -> None: contract_api_msg = cast(ContractApiMessage, message) contract_api_dialogues = cast(ContractApiDialogues, self.context.contract_api_dialo...
def signature_cache(user_function): cache = {} cache_get = cache.get def cached_function(cls, method): key = _make_key(method) sig = cache_get(key) if (sig is None): sig = user_function(cls, method) cache[key] = sig return sig cached_function.clear...