code
stringlengths
281
23.7M
def test_mem_from_cgroup_files_dont_exist(elasticapm_client, tmpdir): proc_stat_self = os.path.join(tmpdir.strpath, 'self-stat') proc_stat = os.path.join(tmpdir.strpath, 'stat') proc_meminfo = os.path.join(tmpdir.strpath, 'meminfo') cgroup_memory_limit = os.path.join(tmpdir.strpath, 'memory', 'memory.li...
def genesis_state(address_with_balance, balance, address_with_bytecode, bytecode, address_with_storage): return {address_with_balance: {'balance': balance, 'code': b'', 'nonce': 0, 'storage': {}}, address_with_bytecode: {'balance': 0, 'code': bytecode, 'nonce': 0, 'storage': {}}, address_with_storage: {'balance': 0...
def test_get_device_name_dict(backend_db, frontend_db): insert_test_fw(backend_db, 'fw1', vendor='vendor1', device_class='class1', device_name='name1') insert_test_fw(backend_db, 'fw2', vendor='vendor1', device_class='class1', device_name='name2') insert_test_fw(backend_db, 'fw3', vendor='vendor1', device_c...
class TestNewlinePreservation(unittest.TestCase): def test_newline(self): with tempfile.TemporaryDirectory() as d: fp = os.path.join(d, 'trailingnewline.json') with open(fp, 'w') as f: f.write(MANIFEST_WITH_NEWLINE) with open(fp, 'r') as f: ...
def parse_hmmsearch_file(pfam_file): pfams = {} with open(pfam_file, 'r') as pfamf: for line in pfamf: if line.startswith('#'): continue (pfam, query, evalue, score, qlen, hmmfrom, hmmto, seqfrom, seqto, qcov) = map(str.strip, line.split('\t')) if (que...
def invent_brands_from_generic_bnf_code(generic_code, num_brands=5): assert (0 <= num_brands <= 9) chemical = generic_code[0:9] strength_and_form = generic_code[13:15] products = ['B{}'.format(j) for j in range(num_brands)] return [(((chemical + product) + strength_and_form) + strength_and_form) for...
def get_episodes(html, url): if is_search_page(url): return get_episodes_from_search(html, url) if is_search_ajax(url): return get_episodes_from_search_ajax(html, url) try: return get_episodes_from_ajax_result(html, url) except DataNotFound: pass try: return g...
class PortStats(base_tests.SimpleProtocol): def runTest(self): request = ofp.message.port_stats_request(port_no=ofp.OFPP_ANY) logging.info('Sending port stats request') stats = get_stats(self, request) logging.info('Received %d port stats entries', len(stats)) for entry in st...
def pytest_configure(): from django.conf import settings settings.configure(DEBUG_PROPAGATE_EXCEPTIONS=True, DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}}, SITE_ID=1, SECRET_KEY='not very secret in tests', USE_I18N=True, USE_L10N=True, STATIC_URL='/static/', ROOT_URLCONF='t...
def LLM(prompt, mode='text', gpt4=False): global memory if (len(prompt) > MAX_PROMPT): raise ValueError(f'prompt ({len(prompt)}) too large (max {MAX_PROMPT})') if (mode == 'text'): messages = [{'role': 'system', 'content': LLM_SYSTEM_CALIBRATION_MESSAGE}, {'role': 'user', 'content': prompt}]...
def test_inline_df(): df = pd.DataFrame({'x': [1, 2, 3], 'y': [4, 2, 2]}) assert (len((sql ^ 'SELECT * FROM df')) == 3) assert (len((sql ^ 'SELECT * FROM df a, df b WHERE a.x = b.y')) == 2) assert ((sql_val ^ '\n SELECT COUNT() FROM (\n SELECT * FROM df a\n LEFT JOIN df b ON...
def fuzzgadgets(ch, method, properties, body): (vid, pid, dclass, serial, man, prod, min, max) = body.decode('utf-8').split('!!') chmodgadget = 'chmod a+x tempgadget.sh' creategadget = './tempgadget.sh' removegadget = './removegadget.sh' cprint('Creating new gadget', color='blue') with open('tem...
def _validate_array(datum, schema, named_schemas, parent_ns, raise_errors, options): return (isinstance(datum, (Sequence, array.array)) and (not isinstance(datum, str)) and all((_validate(datum=d, schema=schema['items'], named_schemas=named_schemas, field=parent_ns, raise_errors=raise_errors, options=options) for d...
class queue_stats_request(stats_request): version = 3 type = 18 stats_type = 5 def __init__(self, xid=None, flags=None, port_no=None, queue_id=None): if (xid != None): self.xid = xid else: self.xid = None if (flags != None): self.flags = flags ...
class OptionPlotoptionsAreaSonificationTracksMappingVolume(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....
class OptionPlotoptionsErrorbarOnpointPosition(Options): def offsetX(self): return self._config_get(None) def offsetX(self, num: float): self._config(num, js_type=False) def offsetY(self): return self._config_get(None) def offsetY(self, num: float): self._config(num, js_t...
class Media(): def __init__(self, ui): self.page = ui.page def video(self, value: str='', align: str='center', path: str=None, width: types.SIZE_TYPE=(100, '%'), height: types.SIZE_TYPE=(None, 'px'), html_code: str=None, profile: types.PROFILE_TYPE=None, options: dict=None): width = Arguments.si...
def display_library_view(params): node_id = params.get('view_id') view_info_url = ('{server}/emby/Users/{userid}/Items/' + node_id) data_manager = DataManager() view_info = data_manager.get_content(view_info_url) log.debug('VIEW_INFO : {0}', view_info) collection_type = view_info.get('Collection...
class MockDeviceDB(BaseDeviceDB): def __init__(self, service: 'MockService') -> None: super().__init__(service) self.mock_devices = [self.mock_dev(i) for i in range(1, 10)] def mock_dev(self, idx: int) -> DeviceInfo: addrs = ['fd01:db00:11:{:04x}::a'.format(idx), 'fd01:db00:11:{:04x}::b'...
def _create_plot_component(): x = linspace((- 2.0), 10.0, 40) pd = ArrayPlotData(index=x, y0=jn(0, x)) plot1 = Plot(pd, title='render_style = hold', padding=50, border_visible=True, overlay_border=True) plot1.legend.visible = True lineplot = plot1.plot(('index', 'y0'), name='j_0', color='red', rende...
class ConcatModelBuilder(BaseModelBuilder): def __init__(self, modality_config: Dict[(str, Union[(str, Dict[(str, Any)])])], observation_modality_mapping: Dict[(str, str)], shared_embedding_keys: Optional[Union[(List[str], Dict[(str, List[str])])]]): self._check_modality_config(modality_config) supe...
class DWARFInfo(object): def __init__(self, config, debug_info_sec, debug_aranges_sec, debug_abbrev_sec, debug_frame_sec, eh_frame_sec, debug_str_sec, debug_loc_sec, debug_ranges_sec, debug_line_sec): self.config = config self.debug_info_sec = debug_info_sec self.debug_aranges_sec = debug_ar...
def test_no_flash_fullscreen_false_server_doesnt_flash_fullscreen_windows(no_flash_fullscreen_server: FlashServer) -> None: with new_watched_window() as (window, watcher): set_fullscreen(window) with server_running(no_flash_fullscreen_server): switch_workspace(1) change_focus...
def header(logo_and_title=True): if ('first_run' not in st.session_state): st.session_state.first_run = True for key in ['selected_value', 'filename', 'executed', 'play_karaoke', 'url', 'random_song', 'last_dir', 'player_restart']: st.session_state[key] = None st.session_state.vi...
class TestDynamicNotifiers(unittest.TestCase): def setUp(self): self.exceptions = [] trait_notifiers.push_exception_handler(self._handle_exception) def tearDown(self): trait_notifiers.pop_exception_handler() def _handle_exception(self, obj, name, old, new): self.exceptions.ap...
def test_writePlist_to_path(tmpdir, pl_no_builtin_types): old_plistlib = pytest.importorskip('fontTools.ufoLib.plistlib') testpath = (tmpdir / 'test.plist') old_plistlib.writePlist(pl_no_builtin_types, str(testpath)) with testpath.open('rb') as fp: pl2 = plistlib.load(fp, use_builtin_types=False...
class ColumnValuePlot(Metric[ColumnValuePlotResults]): column_name: str def __init__(self, column_name: str, options: AnyOptions=None): self.column_name = column_name super().__init__(options=options) def calculate(self, data: InputData) -> ColumnValuePlotResults: if (self.column_nam...
def create_or_update_messaging_config(db: Session, config: MessagingConfigRequest) -> MessagingConfigResponse: data = {'key': config.key, 'name': config.name, 'service_type': config.service_type.value} if config.details: data['details'] = config.details.__dict__ messaging_config: MessagingConfig = M...
def extract_transform_load(task: TaskSpec) -> None: if abort.is_set(): logger.warning(format_log(f'Skipping partition #{task.partition_number} due to previous error', name=task.name)) return start = perf_counter() msg = f'Started processing on partition #{task.partition_number}: {task.name}'...
def extractShmeimeiiWordpressCom(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)...
class DateTimeField(WritableField): type_name = 'DateTimeField' type_label = 'datetime' widget = widgets.DateTimeInput form_field_class = forms.DateTimeField default_error_messages = {'invalid': _('Datetime has wrong format. Use one of these formats instead: %s')} empty = None input_formats ...
def dichotomic_pattern_mining(seq2pat_pos: Seq2Pat, seq2pat_neg: Seq2Pat, min_frequency_pos: Num=0.3, min_frequency_neg: Num=0.3) -> Dict[(str, List[list])]: patterns_pos = seq2pat_pos.get_patterns(min_frequency=min_frequency_pos) patterns_neg = seq2pat_neg.get_patterns(min_frequency=min_frequency_neg) patt...
class News(JsPackage): def __init__(self, component: primitives.HtmlModel, js_code: str=None, set_var: bool=True, is_py_data: bool=True, page: primitives.PageModel=None): self.htmlCode = (js_code if (js_code is not None) else component.htmlCode) (self.varName, self.varData, self.__var_def) = (("docu...
class Piece(): def __init__(self, x_pos, y_pos, color): diameter = 0.7 self.x = x_pos self.y = y_pos self.radius = (diameter / 2) self.grabbed = False self.targeted = False self.color = color self.start_x = self.x self.start_y = self.y ...
class GitDriver(): def __init__(self, repodir): self.repodir = Path(repodir) def init(self): self.repodir.mkdir() self.run_command('init') def log(self): output = self.run_command('log', '--format=%s', '--reverse') return output.strip().splitlines() def grep_log(s...
class _Decoration(base.PaddingMixin): defaults = [('padding', 0, 'Default padding'), ('extrawidth', 0, 'Add additional width to the end of the decoration'), ('ignore_extrawidth', False, 'Ignores additional width added by decoration. Useful when stacking decorations on top of a PowerLineDecoration.')] def __init...
def test_validator_tangential_field(): field_dataset = FIELD_SRC.field_dataset field_dataset = field_dataset.copy(update=dict(Ex=None, Ez=None, Hx=None, Hz=None)) with pytest.raises(pydantic.ValidationError): _ = td.CustomFieldSource(size=SIZE, source_time=ST, field_dataset=field_dataset)
def prompt_for_pkce_token(client_id: str, redirect_uri: str, scope=None) -> RefreshingToken: cred = RefreshingCredentials(client_id, redirect_uri=redirect_uri) auth = UserAuth(cred, scope=scope, pkce=True) print('Opening browser for Spotify login...') webbrowser.open(auth.url) redirected = input('Pl...
class EnumParamType(click.Choice): def __init__(self, enum_type: typing.Type[enum.Enum]): super().__init__([str(e.value) for e in enum_type]) self._enum_type = enum_type def convert(self, value: typing.Any, param: typing.Optional[click.Parameter], ctx: typing.Optional[click.Context]) -> enum.Enu...
def test_import_zmap_and_xyz(testpath): mypol2a = xtgeo.polygons_from_file((testpath / PFILE1A), fformat='zmap') mypol2b = xtgeo.polygons_from_file((testpath / PFILE1B)) mypol2c = xtgeo.polygons_from_file((testpath / PFILE1C)) assert (mypol2a.nrow == mypol2b.nrow) assert (mypol2b.nrow == mypol2c.nro...
class Record(object): child_list_key = None def __init__(self, client, id, *args, **kwargs): self._client = client self._id = extract_id(id) self._callbacks = [] if (self._client._monitor is not None): self._client._monitor.subscribe(self) def id(self): re...
class HandshakeV10(): def __init__(self): self.server_version = '5.0.2' self.capability = CapabilitySet((Capability.LONG_PASSWORD, Capability.LONG_FLAG, Capability.CONNECT_WITH_DB, Capability.PROTOCOL_41, Capability.TRANSACTIONS, Capability.SECURE_CONNECTION, Capability.PLUGIN_AUTH)) self.st...
def test_same_instruction_with_different_memory_version(): aliased_x = [Variable('x', Integer.int32_t(), i, is_aliased=True) for i in range(5)] aliased_y = [Variable('y', Integer.int32_t(), i, is_aliased=True) for i in range(5)] esi = Variable('esi', Integer.int32_t(), 3) var_v = [Variable('v', Integer....
class RelationshipMemberCustomer(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_im...
class MockSecretHandler(SecretHandler): def load_secret(self, resource: 'IRResource', secret_name: str, namespace: str) -> Optional[SecretInfo]: return SecretInfo('fallback-self-signed-cert', 'ambassador', 'mocked-fallback-secret', TLSCerts['acook'].pubcert, TLSCerts['acook'].privkey, decode_b64=False)
def reduce(pitch_motif: PitchLine, duration_motif: DurationLine, start: int, end: int, position: str) -> Tuple[(PitchLine, DurationLine)]: duration = sum(duration_motif[start:(end + 1)]) duration_motif = deepcopy(duration_motif) if (position == 'left'): duration_motif[(start - 1)] = (duration_motif[...
def wb_labels_to_csv(wb_labels_txt, csv_out=None): labels = pd.read_csv(wb_labels_txt, header=None, names=['lab', 'R', 'G', 'B', 'alpha'], delim_whitespace=True) labels['A_stack'] = (['one', 'two'] * int((labels.shape[0] / 2))) labels['B_stack'] = pd.Series(range(int((labels.shape[0] / 2)))).repeat(2).value...
('/feed-filters/merge-parsers') _required def mergeFeedParsers(): if ((not ('f1' in request.args)) and ('f2' in request.args)): return render_template('error.html', title='Viewer', message='This function has to have feeds to merge as parameters!') try: f1 = int(request.args['f1']) f2 = i...
class StringTest(AnyTraitTest): def setUp(self): self.obj = StringTrait() _default_value = 'string' _good_values = [10, (- 10), 10.1, (- 10.1), '10', '-10', '10L', '-10L', '10.1', '-10.1', 'string', 1j, [10], ['ten'], {'ten': 10}, (10,), None] _bad_values = [] def coerce(self, value): ...
def resource_img_upload_to(instance, filename): ext = filename.split('.')[(- 1)] filename = ('%s.%s' % (uuid.uuid4(), ext.lower())) upload_path = 'rooms/' upload_abs_path = os.path.join(settings.MEDIA_ROOT, upload_path) if (not os.path.exists(upload_abs_path)): os.makedirs(upload_abs_path) ...
.skip_ci ('xtb') def test_kick(): geom = geom_loader('lib:benzene_and_chlorine.xyz') stoc_kwargs = {'cycle_size': 10, 'radius': 1.25, 'seed': , 'max_cycles': 5} stoc = Kick(geom, **stoc_kwargs) stoc.run() assert (stoc.cur_cycle == 4) assert (len(stoc.new_geoms) == 9) assert (min(stoc.new_ene...
def sync_branch(new_branch, branch_commits, message): for branch in branch_commits: if (not subprocess.call(['git', 'merge', branch, '--ff-only'], encoding='utf-8')): log.debug("merged '{0}' fast forward into '{1}' or noop".format(branch, new_branch)) return branch = next(iter(br...
class PrivateComputationPCF2LocalTestStageFlow(PrivateComputationBaseStageFlow): _order_ = 'CREATED PID_SHARD PID_PREPARE ID_MATCH ID_MATCH_POST_PROCESS ID_SPINE_COMBINER RESHARD PCF2_ATTRIBUTION PCF2_AGGREGATION AGGREGATE' CREATED = PrivateComputationStageFlowData(initialized_status=PrivateComputationInstanceS...
class OptionSeriesWindbarbSonificationTracksMappingRate(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._co...
def launch_green_threads(): pool = eventlet.GreenPool(((CONCURRENCY * 2) + 1)) server_sock = eventlet.green.socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_sock.bind(('localhost', 0)) server_sock.listen(50) addr = ('localhost', server_sock.getsockname()[1]) pool.spawn_n(green_accepter, ...
.command('restore_es_snapshot_downtime') ('repo_name', default=None, required=False) ('snapshot_name', default=None, required=False) ('index_name', default=None, required=False) def restore_es_snapshot_downtime_cli(repo_name, snapshot_name, index_name): legal_docs.restore_es_snapshot_downtime(repo_name, snapshot_na...
def update_popup(view, content, md=True, css=None, wrapper_class=None, template_vars=None, template_env_options=None, **kwargs): disabled = _get_setting('mdpopups.disable', False) if disabled: _debug('Popups disabled', WARNING) return try: html = _create_html(view, content, md, css, ...
_routes.route('/events/<string:event_identifier>/export/speakers/csv', methods=['POST'], endpoint='export_speakers_csv') _event_id _coorganizer def export_speakers_csv(event_id): from .helpers.tasks import export_speakers_csv_task status = request.json.get('status') task = export_speakers_csv_task.delay(eve...
class ImitationEvents(ABC): _epoch_stats(np.nanmean) _stats_grouping('step_id', 'agent_id') def policy_loss(self, step_id: Union[(str, int)], agent_id: int, value: float): _epoch_stats(np.nanmean) _stats_grouping('step_id', 'agent_id') def policy_entropy(self, step_id: Union[(str, int)], agent_i...
class Command(DanubeCloudCommand): args = '[DB name]' help = 'Create database dump.' default_verbosity = 2 options = (CommandOption('-d', '--database', action='store', dest='database', help='Nominates a specific database to dump. Defaults to the "default" database.'), CommandOption('-a', '--data-only', ...
def cbFun(snmpEngine, sendRequesthandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): if errorIndication: print(errorIndication) return if errorStatus: print(('%s at %s' % (errorStatus.prettyPrint(), ((errorIndex and varBindTable[(- 1)][(int(errorIndex) - 1)][0]) or '?...
class OptionPlotoptionsPyramidSonificationDefaultspeechoptionsMapping(Options): def pitch(self) -> 'OptionPlotoptionsPyramidSonificationDefaultspeechoptionsMappingPitch': return self._config_sub_data('pitch', OptionPlotoptionsPyramidSonificationDefaultspeechoptionsMappingPitch) def playDelay(self) -> 'O...
class MImageResource(HasTraits): _image_not_found = None def __init__(self, name, search_path=None): self.name = name if isinstance(search_path, str): _path = [search_path] elif isinstance(search_path, Sequence): _path = search_path elif (search_path is no...
class OptionPlotoptionsStreamgraphSonificationTracksMappingHighpassFrequency(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: s...
def handle_results(report, appname, file_version, item_location, application_cve, application_secure): try: logging.debug('%s with version %s from %s with vulnerability %s. This installation should be updated to at least version %s.', appname, file_version, item_location, application_cve, application_secure...
class TestBstSecondLargest(unittest.TestCase): def test_bst_second_largest(self): bst = Solution(None) self.assertRaises(TypeError, bst.find_second_largest) root = Node(10) bst = Solution(root) node5 = bst.insert(5) node15 = bst.insert(15) node3 = bst.insert(3...
class _Border(_BaseRow): def __init__(self, prev, next, table, borders, window_too_small=None, align=HorizontalAlign.JUSTIFY, padding=D.exact(0), padding_char=None, padding_style='', width=None, height=None, z_index=None, modal=False, key_bindings=None, style=''): assert (prev or next) self.prev = p...
.feature('unit') .story('services', 'core', 'scheduler') class TestSchedulerExceptions(): def test_NotReadyError(self): with pytest.raises(NotReadyError) as excinfo: raise NotReadyError() assert (excinfo.type is NotReadyError) assert issubclass(excinfo.type, RuntimeError) def...
class IngestClient(NamespacedClient): _rewrite_parameters() async def delete_pipeline(self, *, id: str, error_trace: t.Optional[bool]=None, filter_path: t.Optional[t.Union[(str, t.Sequence[str])]]=None, human: t.Optional[bool]=None, master_timeout: t.Optional[t.Union[('t.Literal[-1]', 't.Literal[0]', str)]]=Non...
def _parse_table_summary(conn: RDBMSDatabase, summary_template: str, table_name: str) -> str: columns = [] for column in conn.get_columns(table_name): if column.get('comment'): columns.append(f"{column['name']} ({column.get('comment')})") else: columns.append(f"{column['n...
class WorkflowContextImpl(WorkflowContext): def __init__(self, namespace: str, workflow: Workflow, metadata_manager: MetadataManager): super().__init__(namespace, workflow) self._metadata_manager = metadata_manager def get_state(self, state_descriptor: StateDescriptor) -> State: workflow...
def parameter_count_table(model: nn.Module, max_depth: int=3) -> str: count: typing.DefaultDict[(str, int)] = parameter_count(model) param_shape: typing.Dict[(str, typing.Tuple)] = {k: tuple(v.shape) for (k, v) in model.named_parameters()} table: typing.List[typing.Tuple] = [] def format_size(x: int) ->...
class OptionPlotoptionsBubbleLabelStyle(Options): def fontSize(self): return self._config_get('0.8em') def fontSize(self, num: float): self._config(num, js_type=False) def fontWeight(self): return self._config_get('bold') def fontWeight(self, text: str): self._config(text...
_page.route('/table/edit', methods=['POST']) def table_edit(): try: res = check_uuid(all_data['uuid'], request.json['uuid']) if (res != None): return jsonify(res) id = request.json['id'] field = request.json['field'] new_field_value = request.json['new_field_value...
def test_jobpaths(tmp_path: Path) -> None: assert (utils.JobPaths(tmp_path, '123').stdout == (tmp_path / '123_0_log.out')) assert (utils.JobPaths(tmp_path, '123', 1).stdout == (tmp_path / '123_1_log.out')) assert (utils.JobPaths((tmp_path / 'array-%A-index-%a'), '456_3').stdout == ((tmp_path / 'array-456-in...
def calculate_db_score(start_date): if ah.user_settings['keep_log']: ah.log.debug('Begin function') db_correct = int(db_helper.correct_answer_count(start_date)) if ah.user_settings['tries_eq']: db_wrong = int((db_helper.wrong_answer_count(start_date) / ah.user_settings['tries_eq'])) else...
_renderer(wrap_type=ColumnRegExpMetric) class ColumnRegExpMetricRenderer(MetricRenderer): def _get_counters(dataset_name: str, metrics: DataIntegrityValueByRegexpStat) -> BaseWidgetInfo: percents = round(((metrics.number_of_not_matched * 100) / metrics.number_of_rows), 3) counters = [CounterData(lab...
class SignalGeneratorNode(FunctionGeneratorNode): SAMPLE_TOPIC = lg.Topic(SignalSampleMessage) def setup(self): self._shutdown = asyncio.Event() def cleanup(self): self._shutdown.set() (SAMPLE_TOPIC) async def publish_samples(self) -> lg.AsyncPublisher: while (not self._shutd...
class BackendService(resource.Resource): def __init__(self, **kwargs): super(BackendService, self).__init__(resource_id=kwargs.get('id'), resource_type=resource.ResourceType.BACKEND_SERVICE, name=kwargs.get('name'), display_name=kwargs.get('name')) self.full_name = kwargs.get('full_name') se...
class ExcludeFromFileTestCase(IncludeExcludeMixIn, unittest.TestCase): def test_filter(self): expected = [self.sequences[2], self.sequences[4]] actual = list(transform.exclude_from_file(self.sequences, self.handle)) self.assertEqual(2, len(actual)) self.assertEqual(expected, actual)
class Migration(migrations.Migration): dependencies = [('frontend', '0080_replace_nullboolean')] operations = [migrations.AlterField(model_name='maillog', name='metadata', field=models.JSONField(blank=True, null=True)), migrations.AlterField(model_name='measureglobal', name='cost_savings', field=models.JSONFiel...
class BuildTest(TestCase): def setUpTestData(cls): factory = DataFactory() factory.create_all(start_date='2018-06-01', num_months=6, num_practices=6, num_presentations=6) ccg = PCT.objects.create(code='ABC', org_type='CCG') for i in range(6): ccg.practice_set.create(code=...
def attribute_around_surface_asymmetric(): cubefile = (EXPATH1 / 'ib_test_cube2.segy') surfacefile = (EXPATH2 / 'h1.dat') above = 10 below = 20 mycube = xtgeo.cube_from_file(cubefile) mysurf = xtgeo.surface_from_file(surfacefile, fformat='ijxyz', template=mycube) sabove = mysurf.copy() s...
class OptionSeriesBarSonificationContexttracksMappingVolume(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...
class TestLinearDisplayP3Serialize(util.ColorAssertsPyTest): COLORS = [('color(--display-p3-linear 0 0.3 0.75 / 0.5)', {}, 'color(--display-p3-linear 0 0.3 0.75 / 0.5)'), ('color(--display-p3-linear 0 0.3 0.75)', {'alpha': True}, 'color(--display-p3-linear 0 0.3 0.75 / 1)'), ('color(--display-p3-linear 0 0.3 0.75 /...
class BackupSerializer(_HideNodeSerializer): _model_ = Backup _update_fields_ = ('note',) _default_fields_ = ('hostname', 'vm', 'dc', 'name', 'disk_id') hostname = s.CharField(source='vm_hostname', read_only=True) vm_uuid = s.CharField(source='vm.uuid', read_only=True) vm = s.CharField(source='v...
class Ops(enum.Enum): ADD = 1 MUL = 2 SUB = 3 DIV = 4 SDIV = 5 MOD = 6 SMOD = 7 ADDMOD = 8 MULMOD = 9 EXP = 10 SIGNEXTEND = 11 LT = 16 GT = 17 SLT = 18 SGT = 19 EQ = 20 ISZERO = 21 AND = 22 OR = 23 XOR = 24 NOT = 25 BYTE = 26 KE...
def assert_single_freq_in_range(field_name: str): (field_name, always=True, allow_reuse=True) def _single_frequency_in_range(cls, val: FieldDataset, values: dict) -> FieldDataset: if (val is None): return val source_time = get_value(key='source_time', values=values) (fmin, fm...
class FlytePathResolver(): protocol = 'flyte://' _flyte_path_to_remote_map: typing.Dict[(str, str)] = {} _lock = threading.Lock() def resolve_remote_path(cls, flyte_uri: str) -> typing.Optional[str]: with cls._lock: if (flyte_uri in cls._flyte_path_to_remote_map): ret...
class DIAYNActionModel(nn.Module): def __init__(self, n_observations, n_actions, n_hidden, n_policies): super().__init__() self.linear = nn.Linear(n_observations, n_hidden) self.linear2 = nn.Linear(n_hidden, (n_actions * n_policies)) self.n_policies = n_policies self.n_action...
def get_f_tran_mod(f, N, C): f_parallel = (f.dot(N) * N) f_perp = (f - f_parallel) if (C < 0): lambda_ = get_lambda(f_parallel) f_tran = (f_perp - (lambda_ * f_parallel)) else: perp_rms = get_rms(f_perp) if (perp_rms < (2 * EVANG2AUBOHR)): f_tran = ((0.5 * f_p...
def test_get_canonical_transaction_by_index(chain, tx): if hasattr(chain, 'apply_transaction'): (new_block, _, computation) = chain.apply_transaction(tx) computation.raise_if_error() else: (new_block, receipts, computations) = chain.build_block_with_transactions_and_withdrawals([tx]) ...
class HasDynamicViews(HasTraits): _dynamic_view_registry = Dict(Str, Instance(DynamicView)) def trait_view(self, name=None, view_element=None): result = None if (not isinstance(name, ViewElement)): if ((view_element is None) and ((name is None) or (len(name) < 1))): f...
class OptionsChartShared(abc.ABC): def __init__(self, component: primitives.HtmlModel, page: primitives.PageModel=None): (self.component, self.page) = (component, page) if (page is None): self.page = component.page def x_format(self, js_funcs, profile: Union[(dict, bool)]=None): ...
def test_transaction_name_from_class_based_view(client, django_elasticapm_client): with override_settings(**middleware_setting(django.VERSION, ['elasticapm.contrib.django.middleware.TracingMiddleware'])): client.get(reverse('elasticapm-class-based')) transaction = django_elasticapm_client.events[TRA...
def _sanitize(key, value, **kwargs): if ('sanitize_field_names' in kwargs): sanitize_field_names = kwargs['sanitize_field_names'] else: sanitize_field_names = BASE_SANITIZE_FIELD_NAMES if (value is None): return if isinstance(value, dict): return value if (not key): ...
def main(page: ft.Page): normal_radius = 50 hover_radius = 60 normal_title_style = ft.TextStyle(size=16, color=ft.colors.WHITE, weight=ft.FontWeight.BOLD) hover_title_style = ft.TextStyle(size=22, color=ft.colors.WHITE, weight=ft.FontWeight.BOLD, shadow=ft.BoxShadow(blur_radius=2, color=ft.colors.BLACK5...
def sinkhorn_tensorized(, x, , y, p=2, blur=0.05, reach=None, diameter=None, scaling=0.5, cost=None, debias=True, potentials=False, **kwargs): (B, N, D) = x.shape (_, M, _) = y.shape if (cost is None): cost = cost_routines[p] (C_xx, C_yy) = ((cost(x, x.detach()), cost(y, y.detach())) if debias e...
class OptionPlotoptionsLineSonificationDefaultinstrumentoptionsMappingTime(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...
def _is_jupyter(): try: shell = get_ipython().__class__.__name__ if (shell == 'ZMQInteractiveShell'): return True elif (shell == 'TerminalInteractiveShell'): return False else: return ('google.colab' in str(get_ipython())) except NameError: ...