code
stringlengths
281
23.7M
def test_surface(surface_data): (xdata, ydata) = surface_data sp = csaps.NdGridCubicSmoothingSpline(xdata, ydata) noisy_s = sp(xdata) assert isinstance(sp.smooth, tuple) assert (len(sp.smooth) == 2) assert isinstance(sp.spline, csaps.NdGridSplinePPForm) assert (noisy_s.shape == ydata.shape)
class DB2Cursor(object): arraysize = 1 def __init__(self, connection): self.connection = connection self.stmt = None def execute(self, query): self.stmt = self.connection.execute(query) def executemany(self, query): raise NotSupportedError def fetchone(self): ...
class LinkedInOAuth2(BaseOAuth2[Dict[(str, Any)]]): display_name = 'LinkedIn' logo_svg = LOGO_SVG def __init__(self, client_id: str, client_secret: str, scopes: Optional[List[str]]=BASE_SCOPES, name: str='linkedin'): super().__init__(client_id, client_secret, AUTHORIZE_ENDPOINT, ACCESS_TOKEN_ENDPOIN...
(CLIENT_BY_ID, dependencies=[Security(verify_oauth_client, scopes=[CLIENT_DELETE])]) def delete_client(client_id: str, db: Session=Depends(get_db)) -> None: client = ClientDetail.get(db, object_id=client_id, config=CONFIG) if (not client): return logger.info('Deleting client') client.delete(db)
class Migration(migrations.Migration): dependencies = [('manager', '0024_auto__2349')] operations = [migrations.RemoveField(model_name='activity', name='type'), migrations.AlterField(model_name='activity', name='activity_type', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='manager.Act...
def update(name, score): replace = False highscores = find() if (highscores['names'] == []): highscores['names'].append(name) highscores['scores'].append(score) else: if (len(highscores['names']) < 5): inserted = False else: inserted = True ...
def find_parent_dir_containing(target: str, max_up: int=6, initial_dir: str=os.getcwd()) -> str: cur = initial_dir while ((not os.path.exists(os.path.join(cur, target))) and (max_up > 0)): cur = os.path.relpath(os.path.join(cur, '..')) max_up = (max_up - 1) if (max_up == 0): raise OS...
class Chart(MixHtmlState.HtmlOverlayStates, Html.Html): name = 'Highcharts' tag = 'div' requirements = ('highcharts',) _chart__type = None _option_cls = OptChartHighcharts.OptionsHighcharts builder_name = 'Hcharts' def __init__(self, page: primitives.PageModel, width, height, html_code, opti...
def get_latents(sequence): sequence = np.array(mel) sequence = Variable(torch.from_numpy(sequence)).unsqueeze(0) sequence = sequence.cuda() with torch.no_grad(): (latents, entropy) = model.quantizer.get_quantizedindices(sequence.unsqueeze(2)) return (latents, entropy)
def set_item(d, keys, value): item = d i = 0 j = len(keys) while (i < j): key = keys[i] if (i < (j - 1)): item = _get_or_new_item_value(item, key, keys[(i + 1)]) i += 1 continue _set_item_value(item, key, value) break
class MetadataResourceHandler(HttpErrorMixin, APIHandler): async def get(self, schemaspace, resource): schemaspace = url_unescape(schemaspace) resource = url_unescape(resource) parent = self.settings.get('elyra') try: metadata_manager = MetadataManager(schemaspace=schemas...
def _pack_binary(x, write): sz = len(x) if (sz <= ((2 ** 8) - 1)): write(b'\xc4') write(_struct_pack('B', sz)) write(x) elif (sz <= ((2 ** 16) - 1)): write(b'\xc5') write(_struct_pack('>H', sz)) write(x) elif (sz <= ((2 ** 32) - 1)): write(b'\xc6')...
class EqlLexer(RegexLexer): name = 'Event Query Language' aliases = ['eql'] filenames = ['*.eql'] _sign = '[\\-+]' _integer = '\\d+' _float = '\\d*\\.\\d+([Ee][-+]?\\d+)?' _time_units = 's|sec\\w+|m|min\\w+|h|hour|hr|d|day' _name = '[a-zA-Z][_a-zA-Z0-9]*' _pipe_names = set(list_pipes...
class _UnitTestDbPartsNoneConfig(DefaultConfig): ENV_CODE = 'utdbpn' USASPENDING_DB_HOST: str = None USASPENDING_DB_PORT: str = None USASPENDING_DB_NAME: str = None USASPENDING_DB_USER: str = None USASPENDING_DB_PASSWORD: SecretStr = None BROKER_DB_HOST: str = None BROKER_DB_PORT: str = ...
def test_geodetic_distance_vs_spherical(): ellipsoid = bl.WGS84 point_a = ((- 69.3), (- 36.4), 405) point_b = ((- 71.2), (- 33.3), 1025) dist = distance(point_a, point_b, coordinate_system='geodetic', ellipsoid=ellipsoid) point_a_sph = ellipsoid.geodetic_to_spherical(*point_a) point_b_sph = elli...
def test_ignore_small_changes_both(test_id: str, dbt_project: DbtProject): now = datetime.utcnow() data = ([{TIMESTAMP_COLUMN: cur_date.strftime(DATE_FORMAT)} for cur_date in generate_dates(base_date=now, step=timedelta(days=1)) if (cur_date < (now - timedelta(days=1)))] * 30) data += ([{TIMESTAMP_COLUMN: (...
class Solution(object): def maximumProduct(self, nums): if (len(nums) == 3): return ((nums[0] * nums[1]) * nums[2]) positive = sorted([n for n in nums if (n >= 0)]) negative = sorted([n for n in nums if (n < 0)]) cs1 = positive[(- 3):] cs2 = negative[:2] i...
def plot_gamut_in_space(space, gamut, title='', dark=False, resolution=200, opacity=1.0, edges=False, size=(800, 800), camera=None, aspect=None, projection='perspective'): io.templates.default = ('plotly_dark' if dark else 'plotly') if (resolution == 50): resolution = 51 if (camera is None): ...
class Layer(): def __init__(self, data): self._data = data self._style = data.default_style def add_action(self, actions): if self._data: actions.append(self._data) if self._style: actions.append(self._style) def style(self, style): self._style...
def symlink(target, link_name): (link_path, _) = os.path.split(link_name) if (len(link_path) == 0): target_check = target else: if (not os.path.isdir(link_path)): print(f'Creating directory for link: {link_path}') os.makedirs(link_path) target_check = os.path....
class GenerateOperatorWidgets(QtWidgets.QDialog): _DEFAULT_WINDOW_WIDTH = 500 _MAX_INPUT_VARIABLES_COUNT = 5 _MAX_OUTPUT_VARIABLES_COUNT = 5 _MAX_ATTRIBUTES_COUNT = 10 def __init__(self, opset=DEFAULT_OPSET, parent=None) -> None: super().__init__(parent) self.setModal(False) ...
_router.get('/item/{item_uid}/revision/', response_model=CollectionItemRevisionListResponse, dependencies=PERMISSIONS_READ) def item_revisions(item_uid: str, limit: int=50, iterator: t.Optional[str]=None, prefetch: Prefetch=PrefetchQuery, user: UserType=Depends(get_authenticated_user), items: CollectionItemQuerySet=Dep...
class OptionPlotoptionsLineSonificationTracksMappingHighpass(Options): def frequency(self) -> 'OptionPlotoptionsLineSonificationTracksMappingHighpassFrequency': return self._config_sub_data('frequency', OptionPlotoptionsLineSonificationTracksMappingHighpassFrequency) def resonance(self) -> 'OptionPlotop...
class DataModelBuilderTest(ForsetiTestCase): def test_all_enabled(self): builder = data_model_builder.DataModelBuilder(FAKE_GLOBAL_CONFIGS, fake_data_models.ALL_ENABLED, mock.MagicMock(), '') data_model_pipeline = builder.build() self.assertEqual(1, len(data_model_pipeline)) expected...
class TestPatient(FrappeTestCase): def test_customer_created(self): frappe.db.sql('delete from `tabPatient`') frappe.db.set_value('Healthcare Settings', None, 'link_customer_to_patient', 1) patient = create_patient() self.assertTrue(frappe.db.get_value('Patient', patient, 'customer')...
def get_practitioner_billing_details(practitioner, is_inpatient): service_item = None practitioner_charge = None if is_inpatient: fields = ['inpatient_visit_charge_item', 'inpatient_visit_charge'] else: fields = ['op_consulting_charge_item', 'op_consulting_charge'] if practitioner: ...
def test_encoder(ref_encoder: CLIPVisionModelWithProjection, our_encoder: CLIPImageEncoderH, test_device: torch.device): x = torch.randn(1, 3, 224, 224).to(test_device) with no_grad(): ref_embeddings = ref_encoder(x).image_embeds our_embeddings = our_encoder(x) assert (ref_embeddings.shape =...
def getSignificantlySimilarArches(filePath, distance=4): log = logging.getLogger('Main.DedupServer') try: ck = ArchChecker(filePath, pathNegativeFilter=settings.masked_path_prefixes) return ck.getSignificantlySimilarArches(searchDistance=distance) except Exception: log.critical('Exce...
class TokenResponse(ModelComposed): allowed_values = {('scope',): {'GLOBAL': 'global', 'PURGE_SELECT': 'purge_select', 'PURGE_ALL': 'purge_all', 'GLOBAL:READ': 'global:read'}} validations = {} _property def additional_properties_type(): lazy_import() return (bool, date, datetime, dict, f...
class CyclicRegionFinderDream(CyclicRegionFinder): def __init__(self, t_cfg: TransitionCFG, asforest: AbstractSyntaxForest): super().__init__(t_cfg, asforest) self.abnormal_entry_restructurer = AbnormalEntryRestructurer(t_cfg, asforest) self.abnormal_exit_restructurer = AbnormalExitRestructu...
class OptionSeriesPieSonificationDefaultinstrumentoptionsMappingHighpass(Options): def frequency(self) -> 'OptionSeriesPieSonificationDefaultinstrumentoptionsMappingHighpassFrequency': return self._config_sub_data('frequency', OptionSeriesPieSonificationDefaultinstrumentoptionsMappingHighpassFrequency) ...
def get_language_name_from_code(isocode: str) -> str: if (isocode is None): return '' if (isocode == AUTO_DETECT): return AUTO_DETECT_NAME if ('-' not in isocode): language = (pycountry.languages.get(alpha_2=isocode) if (len(isocode) == 2) else pycountry.languages.get(alpha_3=isocode...
def test_create_backfiller_error(): no_schedule = LaunchPlan.get_or_create(workflow=example_wf, name='nos', fixed_inputs={'v': 10}) rate_schedule = LaunchPlan.get_or_create(workflow=example_wf, name='rate', fixed_inputs={'v': 10}, schedule=FixedRate(duration=timedelta(days=1))) start_date = datetime(2022, 1...
def nnc_jit(f: Callable[(P, R)], static_argnums: Optional[Tuple[int]]=None) -> Callable[(P, R)]: try: from beanmachine.ppl.inference.proposer.nnc.utils import nnc_jit as raw_nnc_jit except Exception as e: logger.warning(f'''Fails to initialize NNC due to the following error: {str(e)} Falling bac...
class StrideExprCursor(ExprCursor): def name(self) -> str: assert isinstance(self._impl, C.Node) assert isinstance(self._impl._node, LoopIR.StrideExpr) return self._impl._node.name.name() def dim(self) -> int: assert isinstance(self._impl, C.Node) assert isinstance(self._...
def ast_innerWhile_simple_condition_complexity() -> AbstractSyntaxTree: true_value = LogicCondition.initialize_true((context := LogicCondition.generate_new_context())) ast = AbstractSyntaxTree((root := SeqNode(true_value)), condition_map={logic_cond('x1', context): Condition(OperationType.less, [Variable('a'), ...
class WafFirewall(ModelNormal): allowed_values = {} validations = {} _property def additional_properties_type(): lazy_import() return (bool, date, datetime, dict, float, int, list, str, none_type) _nullable = False _property def openapi_types(): lazy_import() ...
def append_tei_children_list_and_get_whitespace(children: T_ElementChildrenList, semantic_content: SemanticContentWrapper, pending_whitespace: str, context: TeiElementFactoryContext) -> str: (tail_children, tail_whitespace) = get_tei_children_and_whitespace_for_semantic_content(semantic_content, context=context) ...
class Migration(migrations.Migration): initial = True dependencies = [] operations = [migrations.CreateModel(name='Setting', fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(help_text='(e.g. SETTING_NAME)', max_length=50, un...
class FuseExpandBmmTestCase(unittest.TestCase): def setUpClass(cls) -> None: torch.manual_seed(0) def __init__(self, *args, **kwargs): super(FuseExpandBmmTestCase, self).__init__(*args, **kwargs) self.test_count = 0 def _compile_and_check(self, Y, test_name, expected_num_ops, expecte...
class _TestSlideFixture(): def _register_assertion(self, assertion: Callable) -> None: self._assertions.append(assertion) def __enter__(self) -> '_TestSlideFixture': self._assertions: List[Callable] = [] testslide_module.mock_callable.register_assertion = self._register_assertion ...
class OptionSeriesItemSonificationTracksMappingTremolo(Options): def depth(self) -> 'OptionSeriesItemSonificationTracksMappingTremoloDepth': return self._config_sub_data('depth', OptionSeriesItemSonificationTracksMappingTremoloDepth) def speed(self) -> 'OptionSeriesItemSonificationTracksMappingTremoloSp...
def test_url_blank_params(): q = QueryParams('a=123&abc&def&b=456') assert ('a' in q) assert ('abc' in q) assert ('def' in q) assert ('b' in q) val = q.get('abc') assert (val is not None) assert (len(val) == 0) assert (len(q['a']) == 3) assert (list(q.keys()) == ['a', 'abc', 'def...
class _RecipientSearchText(_Filter): underscore_name = 'recipient_search_text' def generate_elasticsearch_query(cls, filter_values: List[str], query_type: _QueryType, **options) -> ES_Q: recipient_search_query = [] fields = ['recipient_name'] for filter_value in filter_values: ...
class Controller(controller.ControllerProto): CONTROLLER_ID = 1 CONTROLLER_NAME = 'Domoticz HTTP' def __init__(self, controllerindex): controller.ControllerProto.__init__(self, controllerindex) self.usesID = True self.usesAccount = True self.usesPassword = True self.a...
class PickledWidget(Textarea): def render(self, name, value, attrs=None, renderer=None): repr_value = repr(value) if (attrs is not None): attrs['name'] = name else: attrs = {'name': name} attrs['cols'] = 30 rows = 1 if (isinstance(value, str) a...
def tas_submissions_across_multiple_years(): dabs = baker.make('submissions.DABSSubmissionWindowSchedule', submission_reveal_date=f'{CURRENT_FISCAL_YEAR}-10-09', submission_fiscal_year=CURRENT_FISCAL_YEAR, submission_fiscal_month=12, submission_fiscal_quarter=4, is_quarter=False, period_start_date=f'{CURRENT_FISCAL...
def create_pw_dict(data: List[List[Tuple[(str, str)]]]) -> Dict[(str, List[Tuple[(str, float)]])]: model = dict() for sentence in data: for (i, (_, curr_pos)) in enumerate(sentence): prev_word = (sentence[(i - 1)][0] if (i > 0) else DUMMY) model.setdefault(prev_word, Counter()).u...
('gitlabber.cli.logging') ('gitlabber.cli.sys') ('gitlabber.cli.os') ('gitlabber.cli.log') ('gitlabber.cli.GitlabTree') def test_args_logging(mock_tree, mock_log, mock_os, mock_sys, mock_logging): args_mock = mock.Mock() args_mock.return_value = Node(name='test', version=None, verbose=True, include='', exclude=...
.skipif(version.is_version_plus('1.4.0'), reason='mocking <1.4 modules') ('dbt.contracts.graph.parsed.ParsedModelNode') ('fal.dbt.FalDbt') def test_add_before_scripts(parsed_node, fal_dbt_class): graph = nx.DiGraph() node_lookup = {} modelA = create_mock_model(parsed_node, 'modelA', [], [], before_script_pa...
class IPv6Ecn(MatchTest): def runTest(self): match = ofp.match([ofp.oxm.eth_type(34525), ofp.oxm.ip_ecn(2)]) matching = {'dscp=4 ecn=2': simple_tcpv6_packet(ipv6_tc=18), 'dscp=6 ecn=2': simple_tcpv6_packet(ipv6_tc=26)} nonmatching = {'dscp=4 ecn=0': simple_tcpv6_packet(ipv6_tc=16), 'dscp=4 e...
class groupby_test_case(unittest.TestCase): def test_groupby(self): ls = [{'id': 1, 'name': 'John'}, {'id': 2, 'name': 'Frank'}, {'id': 3, 'name': 'Tony'}, {'id': 4, 'name': 'Jimmy'}, {'id': 3, 'name': 'Sam'}, {'id': 1, 'name': 'Charles'}, {'id': 3, 'name': 'Bob'}, {'id': 4, 'name': 'Paul'}, {'id': 1, 'name...
class TestWeightedMinHashLSHCassandra(unittest.TestCase): ((not DO_TEST_CASSANDRA), 'Skipping test_cassandra__init') def test_cassandra__init(self): lsh = MinHashLSH(threshold=0.8, storage_config=STORAGE_CONFIG_CASSANDRA) self.assertTrue(lsh.is_empty()) (b1, r1) = (lsh.b, lsh.r) ...
class ChainSyncPerformanceTracker(): def __init__(self, head: BlockHeaderAPI) -> None: self.prev_head = head self.latest_head = head self.timer = Timer() self.blocks_per_second_ema = EMA(initial_value=0, smoothing_factor=0.05) self.transactions_per_second_ema = EMA(initial_va...
def test_dataset_missing_values_metric_different_missing_values() -> None: test_dataset = pd.DataFrame({'category_feature_1': ['', 'n/a', '3'], 'category_feature_2': ['', None, np.inf], 'numerical_feature_1': [3, (- 9999), 0], 'numerical_feature_2': [0, None, (- np.inf)], 'prediction': [1, pd.NaT, 1], 'target': [No...
class CommonKData(BaseDocType): id = Keyword() timestamp = Date() updateTimestamp = Date() securityId = Keyword() code = Keyword() name = Keyword() open = Float() close = Float() high = Float() low = Float() volume = Float() turnover = Float() class Meta(): do...
def _vm_save_ip_from_json(vm, net, ipaddress, allowed_ips=False): try: ip = net.ipaddress_set.get(ip=ipaddress) except IPAddress.DoesNotExist: ip = IPAddress(subnet=net, ip=ipaddress, usage=IPAddress.VM_REAL) logger.warning('Adding new IP %s into subnet %s for server %s', ip.ip, net.name...
class Tick(Html.Html): requirements = (cssDefaults.ICON_FAMILY,) name = 'Tick' tag = 'span' def __init__(self, page: primitives.PageModel, position: str, icon: str, text: str, tooltip: str, width: tuple, height: tuple, html_code: str, options: Optional[dict], profile: Optional[Union[(bool, dict)]], verb...
class EmbeddedSequenceTests(unittest.TestCase): def setUp(self): self.data = range(0, 9) def test_embedded_sequence_1_4(self): self.assertEqual(embed_seq(self.data, 1, 4).all(), numpy.asarray([[0.0, 1.0, 2.0, 3.0], [1.0, 2.0, 3.0, 4.0], [2.0, 3.0, 4.0, 5.0], [3.0, 4.0, 5.0, 6.0], [4.0, 5.0, 6.0,...
class InventoryImporter(object): def __init__(self, session, readonly_session, model, dao, service_config, inventory_index_id, *args, **kwargs): del args, kwargs self.readonly_session = readonly_session self.session = session self.model = model self.dao = dao self.ser...
.django_db def test_agg_fields(monkeypatch, aggregate_models): request = Mock() request.query_params = {} request.data = {'field': 'total_obligation', 'group': 'type', 'show_nulls': True} a = AggregateQuerysetMixin() agg = a.aggregate(request=request, queryset=Award.objects.all()) assert (agg.co...
def _create_plot_component(): xs = linspace(0, 10, 600) ys = linspace(0, 5, 600) (x, y) = meshgrid(xs, ys) z = exp(((- ((x ** 2) + (y ** 2))) / 100)) pd = ArrayPlotData() pd.set_data('imagedata', z) plot = Plot(pd) img_plot = plot.img_plot('imagedata', xbounds=(0, 10), ybounds=(0, 5), co...
class OptionAutoComplete(OptionsInput): def appendTo(self): return self._config_get(None) def appendTo(self, value): self._config(value) def autoFocus(self): return self._config_get(False) def autoFocus(self, value: bool): self._config(value) def classes(self): ...
.slow .skipif((not has_bitsandbytes), reason='requires bitsandbytes') def test_quantization_on_non_gpu(): with pytest.raises(ValueError, match='only be performed on CUDA'): model = DollyV2Generator.from_hf_hub(name='databricks/dolly-v2-3b', device=None, quantization_config=BitsAndBytesConfig.for_8bit()) ...
def merge(a, b, path=None): if (path is None): path = [] for key in b: if isinstance(b[key], EntitySpec): b[key] = b[key].params if isinstance(b[key], SpecView): b[key] = b[key].to_dict() if (key in a): if (isinstance(a[key], dict) and isinstan...
def update_user_data(cognito_user_id, body): response = table.update_item(Key={'PK': ('USER#' + cognito_user_id), 'SK': ('USER#' + cognito_user_id)}, UpdateExpression='set #alias = :u, #pinyin = :p, #emoji = :e, #char = :c', ExpressionAttributeNames={'#alias': 'User alias', '#pinyin': 'User alias pinyin', '#emoji':...
.django_db(transaction=True) def test_download_failure_with_two_defc(client, monkeypatch, awards_and_transactions, elasticsearch_award_index): download_generation.retrieve_db_string = Mock(return_value=get_database_dsn_string()) setup_elasticsearch_test(monkeypatch, elasticsearch_award_index) resp = _post(c...
class SocialAuthTests(mixins.SocialAuthMixin, SchemaTestCase): query = '\n mutation SocialAuth($provider: String!, $accessToken: String!) {\n socialAuth(provider: $provider, accessToken: $accessToken) {\n social {\n uid\n extraData\n }\n }\n }' class Mutations(gra...
class Probe(object): def __init__(self, target_pid, max_syscalls=MAX_SYSCALLS): self.target_pid = target_pid self.comm = comm_for_pid(self.target_pid) if (self.comm is None): print(("can't find comm for pid %d" % self.target_pid)) quit() self.max_syscalls = ma...
def example(page): size = 15 gap = 3 duration = 2000 c1 = colors.PINK_500 c2 = colors.AMBER_500 c3 = colors.LIGHT_GREEN_500 c4 = colors.DEEP_PURPLE_500 all_colors = [colors.AMBER_400, colors.AMBER_ACCENT_400, colors.BLUE_400, colors.BROWN_400, colors.CYAN_700, colors.DEEP_ORANGE_500, col...
('bodhi.server.buildsys.log.debug') class TestWaitForTasks(): ('bodhi.server.buildsys.time.sleep') def test_wait_on_unfinished_task(self, sleep, debug): tasks = [1, 2, 3] session = mock.MagicMock() session.taskFinished.side_effect = [True, False, False, True, True] session.getTas...
def extractXiaoyaoiplaygroundWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('The Shamans Poison', 'Poison of the Human Panacea', 'translated'), ('Poison of the Hum...
def exposed_load_feed_names_from_file(json_file): with open(json_file) as fp: df = json.load(fp) for (url, title) in df.items(): try: with db.session_context() as sess: fname = WebMirror.OutputFilters.util.feedNameLut.getNiceName(sess, url, debug=True) ...
class Consist(Model): email = Field() url = Field() ip = Field() image = Field.upload() emails = Field.string_list() emailsplit = Field.string_list() validation = {'email': {'is': 'email'}, 'url': {'is': 'url'}, 'ip': {'is': 'ip'}, 'image': {'is': 'image'}, 'emails': {'is': 'list:email'}, 'e...
class OptionPlotoptionsPieSonificationContexttracksMappingTime(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...
class FirmwareHeader(): header_length = 1024 magic_string = b'\x10\x12 \x03' def __init__(self, file_content: bytes, offset: int=0, is_subheader: bool=False): self.file_content = file_content self.is_subheader = is_subheader self.offset = offset header_content = file_content[...
def test_batch_stateful_many(): uid_generator = string_generator() request_info1 = dm.RequestInfo(input=np.array(range(10)), parameters={'gif_id': 12}) request_object1 = dm.RequestObject(uid=next(uid_generator), source_id='internal_123_123', request_info=request_info1, model=stub_stateful_model) request...
class _FlowSpecBitmask(_FlowSpecOperatorBase): NOT = (1 << 1) MATCH = (1 << 0) _comparison_conditions = {'!=': NOT, '==': MATCH} _bitmask_flags = {} def _to_value(cls, value): try: return cls.__dict__[value] except KeyError: raise ValueError(('Invalid params: ...
class OptionSeriesWindbarbSonificationContexttracksMappingGapbetweennotes(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)...
(private_key_bytes=private_key_st) def test_public_key_compression_is_equal(private_key_bytes, native_key_api, coincurve_key_api): native_public_key = native_key_api.PrivateKey(private_key_bytes).public_key coincurve_public_key = coincurve_key_api.PrivateKey(private_key_bytes).public_key native_compressed_p...
def split(grpc_path, with_scheme=False): url = grpc_path if (not grpc_path): url = nmduri() if (url and (not url.startswith('grpc://'))): raise ValueError(('Invalid grpc path to split: %s; `grpc` scheme missed!' % grpc_path)) url_parse_result = urlparse(url) if with_scheme: r...
def do_stats_numeric(series: pd.Series, updated_dict: dict): stats = updated_dict['stats'] stats['max'] = series.max() stats['mean'] = series.mean() for (percentile, value) in series.quantile([0.95, 0.75, 0.5, 0.25, 0.05]).to_dict().items(): stats[f'perc{int((percentile * 100))}'] = value st...
def install(path: str, packages: list=None, node_server: bool=False, update: bool=False, verbose: bool=True, page: primitives.PageModel=None): if (packages is None): if (page is None): raise ValueError('Package or page must be defined') packages = page.imports.requirements if node_se...
class OptionSeriesTreegraphSonificationDefaultspeechoptionsActivewhen(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:...
.integration_mysql .integration class TestMySQLConnectionTestSecretsAPI(): (scope='function') def url(self, oauth_client, policy, connection_config_mysql) -> str: return f'{V1_URL_PREFIX}{CONNECTIONS}/{connection_config_mysql.key}/test' def test_connection_configuration_test_not_authenticated(self, ...
class JournalEntryLineDetailTests(unittest.TestCase): def test_init(self): journalentry = JournalEntryLineDetail() self.assertEqual(journalentry.PostingType, '') self.assertEqual(journalentry.TaxApplicableOn, 'Sales') self.assertEqual(journalentry.TaxAmount, 0) self.assertEqu...
def test_global_blueprint(dash_duo): app = _get_basic_dash_proxy() clientside_callback('function(x){return x;}', Output('log_client', 'children'), Input('btn', 'n_clicks')) (Output('log_server', 'children'), Input('btn', 'n_clicks')) def update_log(n_clicks): return n_clicks _basic_dash_prox...
class OptionSeriesTilemapSonificationDefaultinstrumentoptionsActivewhen(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, nu...
class OptionPlotoptionsGaugeSonificationDefaultinstrumentoptionsMappingNoteduration(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, ...
class JsBoolean(JsObject.JsObject): _jsClass = 'Boolean' def __init__(self, data, js_code: Optional[str]=None, set_var: bool=False, is_py_data: bool=True, page: Optional[primitives.PageModel]=None, component: primitives.HtmlModel=None): if ((not hasattr(data, 'varName')) and is_py_data): is_...
class ToolHistoryMixin(HasTraits): reset_state_key = Instance(KeySpec, args=('Esc',)) prev_state_key = Instance(KeySpec, args=('Left', 'control')) next_state_key = Instance(KeySpec, args=('Right', 'control')) _history = List _history_index = Int def _next_state_pressed(self): pass de...
class flow_stats_reply(stats_reply): version = 6 type = 19 stats_type = 1 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: ...
class Urlify(Validator): message = 'Not convertible to url' def __init__(self, maxlen=80, check=False, keep_underscores=False, message=None): super().__init__(message=message) self.maxlen = maxlen self.check = check self.message = message self.keep_underscores = keep_unde...
class WebsocketProviderV2(PersistentConnectionProvider): logger = logging.getLogger('web3.providers.WebsocketProviderV2') is_async: bool = True _max_connection_retries: int = 5 def __init__(self, endpoint_uri: Optional[Union[(URI, str)]]=None, websocket_kwargs: Optional[Dict[(str, Any)]]=None, request_t...
def get_bitwise_code(code_logic): code = ('>' * 7) code += '[-]' code += '>' code += '>[-]<' code += '[-][' code += '<' code += ('<[-]' * 5) code += '++' code += '<<' code += '[' code += '-' code += '>>-' code += '[>+>>+<<<-]>[<+>-]' code += '>>' code += '>>+<...
class TestRunShell(): def test_should_call_and_populate_defaults(self): cmd = ['/usr/bin/env', 'true'] process = run_shell(cmd) assert (process.returncode == 0) assert (process.args == cmd) assert (not process.stderr) assert (not process.stdout) def test_should_ca...
class SVGParser(HTMLParser): output = '' ignore = 0 ignore_path = 0 def handle_starttag(self, tag, attrs): if ((tag == 'path') and ('d' not in [a[0] for a in attrs])): self.ignore_path += 1 return if ((tag == 'metadata') or tag.startswith('rdf') or tag.startswith(...
def form_partitions(sv_signatures, max_distance): sorted_signatures = sorted(sv_signatures, key=(lambda evi: evi.get_key())) partitions = [] current_partition = [] for signature in sorted_signatures: if ((len(current_partition) > 0) and (current_partition[(- 1)].downstream_distance_to(signature)...
class AnaphoricityScorer(nn.Module): def __init__(self, in_features: int, hidden_size, depth, dropout): super().__init__() hidden_size = hidden_size if (not depth): hidden_size = in_features layers = [] for i in range(depth): layers.extend([torch.nn.Li...
def test_load(config): config.load() assert (config() == {'section1': {'value1': '11', 'value11': '11'}, 'section2': {'value2': '2'}, 'section3': {'value3': '3'}}) assert (config.section1() == {'value1': '11', 'value11': '11'}) assert (config.section1.value1() == '11') assert (config.section1.value1...