code
stringlengths
281
23.7M
def test(): assert Token.has_extension('reversed'), 'Voce registrou a extensao no token?' ext = Token.get_extension('reversed') assert (ext[2] is not None), 'Voce definiu o getter corretamente?' assert ('getter=get_reversed' in __solution__), 'Voce atribuiu a funcao get_reversed como a funcao getter?' ...
class Network(): def __init__(self, latency): self.nodes = [] self.latency = latency self.time = 0 self.msg_arrivals = {} def broadcast(self, msg): for (i, n) in enumerate(self.nodes): delay = self.latency() if ((self.time + delay) not in self.msg_...
class MatrixInverseRootTest(unittest.TestCase): def test_matrix_inverse_root_scalar(self): A = torch.tensor(2.0) root = 2 exponent_multiplier = 1.82 with self.subTest('Test with scalar case.'): self.assertEqual((A ** ((- 1.82) / 2)), matrix_inverse_root(A, root=root, expo...
class TestWeightedMinHashLSH(unittest.TestCase): def test_init(self): lsh = MinHashLSH(threshold=0.8) self.assertTrue(lsh.is_empty()) (b1, r1) = (lsh.b, lsh.r) lsh = MinHashLSH(threshold=0.8, weights=(0.2, 0.8)) (b2, r2) = (lsh.b, lsh.r) self.assertTrue((b1 < b2)) ...
class OptionSeriesLollipopStatesHoverMarker(Options): def enabled(self): return self._config_get(None) def enabled(self, flag: bool): self._config(flag, js_type=False) def enabledThreshold(self): return self._config_get(2) def enabledThreshold(self, num: float): self._con...
_module() class SimilarClusterEncoder(nn.Module): def __init__(self, n_clusters: int=128, input_size: int=256, output_size: int=256, restore_path: str=None): super().__init__() self.cluster_centers = nn.Parameter(torch.rand(n_clusters, input_size), requires_grad=True) if (restore_path is not...
class OptionPlotoptionsGaugeSonificationDefaultinstrumentoptionsMappingPlaydelay(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, tex...
def validate_types_attribute(structured_data): validate_has_attribute('types', structured_data) for struct_name in structured_data['types']: if (not isinstance(struct_name, str)): raise ValidationError(f'Struct Name of `types` attribute should be a string, but got type `{type(struct_name)}`'...
class BaseJsonReporter(base.BaseReporter): REPORTING_PERIOD = 300 REPORTING_FORMAT = '' REPORTING_VERSION = 1 PRODUCER_UUID = str(uuid.uuid1()) def __init__(self, *args): if (not args): raise error.SnmpsimError(('Missing %s parameter(s). Expected: <method>:<reports-dir>[:dumping-...
def parse_chart_prod_data(raw_data: str, zone_key: ZoneKey=ZoneKey('KR'), logger: Logger=getLogger(__name__)) -> ProductionBreakdownList: production_list = ProductionBreakdownList(logger) data_source = re.search('var ictArr = (\\[\\{.+\\}\\]);', raw_data).group(1) data_source = re.sub('"(localCoal|newRenewa...
def _add_attributes_to_log_record(record): transaction = execution_context.get_transaction() transaction_id = (transaction.id if transaction else None) record.elasticapm_transaction_id = transaction_id trace_id = (transaction.trace_parent.trace_id if (transaction and transaction.trace_parent) else None)...
def test_step_one_drop_table(app): db = Database(app, auto_migrate=False) db.define_models(StepOneThing) ops = _make_ops(db) db2 = Database(app, auto_migrate=False) db2.define_models() ops2 = _make_ops(db2, ops) diffs = ops2.as_diffs() assert ((len(diffs) == 1) and (diffs[0][0] == 'remov...
class OptionSeriesBellcurveSonificationContexttracksMappingTremoloSpeed(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 TestIsSimpleCallable(): def test_method(self): class Foo(): def classmethod(cls): pass def valid(self): pass def valid_kwargs(self, param='value'): pass def valid_vargs_kwargs(self, *args, **kwargs): ...
class OptionPlotoptionsAreasplineSonificationDefaultinstrumentoptionsMappingHighpassFrequency(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 ma...
def get_max_level_legend_rare(save_stats: dict[(str, Any)]) -> int: user_rank = helper.calculate_user_rank(save_stats) cleared_eoc_2 = main_story.has_cleared_chapter(save_stats, 1) acient_curse_clear = uncanny.is_ancient_curse_clear(save_stats) catseyes = catseyes_unlocked(save_stats) if (not cleare...
.sphinx(buildername='gettext', srcdir=os.path.join(SOURCE_DIR, 'gettext'), freshenv=True) def test_gettext(app, status, warning, get_sphinx_app_output, file_regression): app.build() assert ('build succeeded' in status.getvalue()) warnings = warning.getvalue().strip() assert (warnings == '') output =...
class TestAllOF13(unittest.TestCase): def setUp(self): mods = [ofp.action, ofp.message, ofp.common, ofp.oxm] self.klasses = [klass for mod in mods for klass in mod.__dict__.values() if (isinstance(klass, type) and issubclass(klass, loxi.OFObject) and (not hasattr(klass, 'subtypes')))] self.k...
class SliceLayerNormTestCase(unittest.TestCase): def __init__(self, *args, **kwargs): super(SliceLayerNormTestCase, self).__init__(*args, **kwargs) torch.manual_seed(0) self._test_id = 0 def _test_slice_layer_norm(self, *, input_nonbatch_shape: List[int]=(16, 64, 1024), n_normalize_over_...
def generate_clozes(sentences: List[str], pdf_path: str, pdf_title: str, page: int): try: path_fld = config['pdf.clozegen.field.pdfpath'] note_title_fld = config['pdf.clozegen.field.pdftitle'] page_fld = config['pdf.clozegen.field.page'] model_name = config['pdf.clozegen.notetype'] ...
def generateArtCC1(iterationsMap, iteration, t): msg = generateGenericMessage('EiffelArtifactCreatedEvent', t, '2.0.0', 'ArtCC1', iteration) link(msg, iterationsMap[iteration]['CDef3'], 'COMPOSITION') link(msg, iterationsMap[iteration]['CDef3'], 'CAUSE') link(msg, findLatestPrevious(iterationsMap, itera...
def extractBlizzardahmsworldWordpressCom(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, ...
.django_db def test_match_only_awards_with_tas(client, monkeypatch, elasticsearch_award_index, award_with_tas, award_without_tas): _setup_es(client, monkeypatch, elasticsearch_award_index) resp = query_by_tas(client, {'require': [_tas_path(BASIC_TAS)]}) assert (resp.json()['results'] == [_award1()])
def _load_measure_tags(path): with open(path) as f: tags = json.load(f) for (tag_name, tag_details) in tags.items(): if isinstance(tag_details.get('description'), list): tag_details['description'] = ' '.join((line.strip() for line in tag_details['description'])) tag_details['...
class Components(): def __init__(self, ui): self.page = ui.page def select(self, records=None, html_code=None, selected=None, width=(100, '%'), height=(None, '%'), profile=None, options=None): width = Arguments.size(width, unit='px') height = Arguments.size(height, unit='px') htm...
def plot_scores(data, color=None, metric='accuracy', s=10): ax = plt.gca() x = ('param_' + data['depth_param_type'].unique()[0]) seaborn.scatterplot(data=data, x=x, y=f'mean_test_{metric}', alpha=0.9, color='blue', label='test', s=s) seaborn.scatterplot(data=data, x=x, y=f'mean_train_{metric}', alpha=0....
class Bot(Html.Html): name = 'Bot' def __init__(self, page: primitives.PageModel, width, height, html_code, options, profile): super(Bot, self).__init__(page, [], css_attrs={'width': width}, html_code=html_code, profile=profile) self.css({'text-align': 'right', 'position': 'fixed', 'bottom': 0, ...
(scope='function') def saas_erasure_order_connection_config(db: Session, saas_erasure_order_config: Dict[(str, Any)], saas_erasure_order_secrets: Dict[(str, Any)]) -> Generator: fides_key = saas_erasure_order_config['fides_key'] connection_config = ConnectionConfig.create(db=db, data={'key': fides_key, 'name': ...
class OptionPlotoptionsScatter3dSonificationDefaultinstrumentoptionsMappingTremoloSpeed(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...
def constructScancodeMap(menukey_map): count = 0 res = '' for (key1, key2) in menukey_map.items(): if (key1 == key2): continue count += 1 res += (KeyScanStrs[key2] + KeyScanStrs[key1]) pass res = (((((16 * '0') + format((count + 1), '#04x')[2:]) + (6 * '0')) +...
class TableView(QtGui.QTableView): _SELECTION_MAP = {'row': (QtGui.QAbstractItemView.SelectionBehavior.SelectRows, QtGui.QAbstractItemView.SelectionMode.SingleSelection), 'rows': (QtGui.QAbstractItemView.SelectionBehavior.SelectRows, QtGui.QAbstractItemView.SelectionMode.ExtendedSelection), 'column': (QtGui.QAbstra...
def _remove_seen_ids(ctrl, id_set): partition_range = range(0, ctrl.config['partitions']) unseen_ids = id_set.copy() for partition_idx in partition_range: (lower_bound, upper_bound) = ctrl.get_id_range_for_partition(partition_idx) for seen_id in id_set: if (lower_bound <= seen_id...
def filter_emailfilter_bword_data(json): option_list = ['comment', 'entries', 'id', 'name'] json = remove_invalid_fields(json) dictionary = {} for attribute in option_list: if ((attribute in json) and (json[attribute] is not None)): dictionary[attribute] = json[attribute] return ...
def pytest_addoption(parser): parser.addoption(OPT_MODEL, action='store', help='Model to test', required=True) parser.addoption(OPT_LANG, action='store', help='Model language', required=True) parser.addoption(OPT_VECTORS, action='store_true', help='Model has vectors') parser.addoption(OPT_PARSER, action...
def guess_new_particle(wordmap): if (wordmap['clitics'] == 'none'): wordmap['clitics'] = None elif (wordmap['particle'] and (wordmap['particle'] == 'ADVERB')): wordmap['clitics'] = 'opt' if wordmap['possessive']: if (wordmap['possessive'] == 'opt'): if (wordmap['harmony']...
def gen_bram36(grid): for tile_name in grid.tiles(): loc = grid.loc_of_tilename(tile_name) gridinfo = grid.gridinfo_at_loc(loc) found = False for (site_name, site_type) in gridinfo.sites.items(): if (site_type == 'RAMBFIFO36E1'): found = True ...
def make_item(item_code=None, properties=None): create_item_attributes() if (not item_code): item_code = frappe.generate_hash(length=16) if frappe.db.exists('Item', item_code): return frappe.get_doc('Item', item_code) item = frappe.get_doc({'doctype': 'Item', 'item_code': item_code, 'ite...
class TestService(Service): TEST_SVC_UUID = '-1234-5678-1234-56789abcdef0' def __init__(self, bus, index): Service.__init__(self, bus, index, self.TEST_SVC_UUID, True) self.add_characteristic(TestCharacteristic(bus, 0, self)) self.add_characteristic(TestEncryptCharacteristic(bus, 1, self...
def test_prolong_de_rham(tp_mesh): from firedrake.preconditioners.pmg import prolongation_matrix_matfree tdim = tp_mesh.topological_dimension() b = Constant(list(range(tdim))) mat = (diag(Constant(([(tdim + 1)] * tdim))) + Constant(([([(- 1)] * tdim)] * tdim))) expr = (dot(mat, SpatialCoordinate(tp_...
class DE76(DeltaE): NAME = '76' def __init__(self, space: str='lab-d65'): self.space = space def distance(self, color: Color, sample: Color, space: (str | None)=None, **kwargs: Any) -> float: if (space is None): space = self.space if (not isinstance(color.CS_MAP[space], C...
.skipif((tqdm is not None), reason='tqdm must be missing') .parametrize('downloader', [HTTPDownloader, FTPDownloader, SFTPDownloader]) def test_downloader_progressbar_fails(downloader): with pytest.raises(ValueError) as exc: downloader(progressbar=True) assert ("'tqdm'" in str(exc.value))
class LoaderMultidexHeader(Unpacker): def __init__(self, apk_obj: APK, dvms, output_dir): super().__init__('loader.multidex.header', 'Unpacker for multidex', apk_obj, dvms, output_dir) def start_decrypt(self, native_lib: str=''): self.logger.info('Starting to decrypt') self.decrypted_pay...
def test_login_via_client_with_proxies(): testutil.add_response('login_response_200') testutil.add_response('api_version_response_200') client = sfdc.client(username=testutil.username, password=testutil.password, client_id=testutil.client_id, client_secret=testutil.client_secret, proxies={' 'localhost:8888/...
def test_combine_condition_nodes(): context = LogicCondition.generate_new_context() condition_handler = ConditionHandler({LogicCondition.initialize_symbol('a', context): ConditionSymbol((cond := Condition(OperationType.less_or_equal, [var('a'), Constant(5, Integer.int32_t())])), LogicCondition.initialize_symbol...
class OptionPlotoptionsSankeySonificationTracksMappingLowpass(Options): def frequency(self) -> 'OptionPlotoptionsSankeySonificationTracksMappingLowpassFrequency': return self._config_sub_data('frequency', OptionPlotoptionsSankeySonificationTracksMappingLowpassFrequency) def resonance(self) -> 'OptionPlo...
def _builds_to_yaml(app): builds = ruamel.yaml.comments.CommentedSeq() for build in app.get('Builds', []): b = ruamel.yaml.comments.CommentedMap() for field in build_flags: v = build.get(field) if ((v is None) or (v is False) or (v == '') or (v == dict()) or (v == list())...
def _to_stream(pitch_lines: List[PitchLine], duration_lines: List[DurationLine]) -> music21.stream.Stream: stream = music21.stream.Stream() for (i, line) in enumerate(pitch_lines): voice = music21.stream.Voice() for (j, item) in enumerate(line): duration = duration_lines[i][j] ...
def assert_naive_datetime_equal_to_tz_datetime(naive_datetime, tz_datetime): if is_windows: delta = (naive_datetime - epoch_naive) microseconds = ((((((delta.days * 24) * 3600) + delta.seconds) * 1000) * 1000) + delta.microseconds) else: microseconds = ((int(time.mktime(naive_datetime.ti...
class OptionSeriesHistogramSonificationTracksMappingNoteduration(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 test_da_morphologizer_spaces(NLP): doc = NLP('Some\nspaces are\tnecessary.') assert (doc[0].pos != SPACE) assert (doc[0].pos_ != 'SPACE') assert (doc[1].pos == SPACE) assert (doc[1].pos_ == 'SPACE') assert (doc[2].pos != SPACE) assert (doc[3].pos != SPACE) assert (doc[4].pos == SPACE...
def generate_lorem_ipsum(n=5, html=True, min=20, max=100): from .constants import LOREM_IPSUM_WORDS from random import choice, randrange words = LOREM_IPSUM_WORDS.split() result = [] for _ in range(n): next_capitalized = True last_comma = last_fullstop = 0 word = None ...
class OptionSeriesTreemapSonificationTracks(Options): def activeWhen(self) -> 'OptionSeriesTreemapSonificationTracksActivewhen': return self._config_sub_data('activeWhen', OptionSeriesTreemapSonificationTracksActivewhen) def instrument(self): return self._config_get('piano') def instrument(s...
def get_values_for_bnf_code(cursor, code): result = cursor.execute('\n SELECT items, quantity, actual_cost, net_cost\n FROM presentation\n WHERE bnf_code=? AND items IS NOT NULL\n ', [code]) rows = list(result) if rows: return [deserialize(value) for value in rows[0]]
class DataLoadWorker(): DONE_TOKEN = 'DONE' def run(env_factory: Callable, trajectories_or_paths: List[Union[(Path, str, TrajectoryRecord)]], reporting_queue: Queue, trajectory_processor: TrajectoryProcessor) -> None: try: env = (env_factory() if env_factory else None) for trajec...
.parametrize('python_version_enum, flytekit_version, expected_image_string', [(PythonVersion.PYTHON_3_9, 'v0.32.0', 'cr.flyte.org/flyteorg/flytekit:py3.9-0.32.0'), (PythonVersion.PYTHON_3_8, '1.31.3', 'cr.flyte.org/flyteorg/flytekit:py3.8-1.31.3')]) def test_set_both(python_version_enum, flytekit_version, expected_imag...
class DropdownHtmlTransform(SphinxPostTransform): default_priority = 200 formats = ('html',) def run(self): matcher = NodeMatcher(nodes.container, type='dropdown') for node in self.document.traverse(matcher): open_marker = nodes.container('', nodes.raw('', nodes.Text(get_opticon(...
.skipif(sys.platform.startswith('darwin'), reason='No flock on MacOS') def test_recent_proxyfile_locked(tmpdir, monkeypatch): monkeypatch.chdir(tmpdir) Path(PROXYFILE_FOR_TESTS).write_text(EXAMPLE_QSTAT_CONTENT, encoding='utf-8') with open(PROXYFILE_FOR_TESTS, encoding='utf-8') as proxy_fd: fcntl.fl...
def secure_filename(filename: str) -> str: if (not filename): raise ValueError('filename may not be an empty string') filename = unicodedata.normalize('NFKD', filename) if filename.startswith('.'): filename = filename.replace('.', '_', 1) return _UNSAFE_CHARS.sub('_', filename)
def extractMundanerealmWordpressCom(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_ty...
class Migration(migrations.Migration): dependencies = [('admin_interface', '0028_theme_show_fieldsets_as_tabs_and_more')] operations = [migrations.AddField(model_name='theme', name='css_generic_link_active_color', field=colorfield.fields.ColorField(blank=True, default='#29B864', help_text='#29B864', image_field...
def test_read_binary_header_fields(mmap=False): f = _segyio.segyiofd(str((testdata / 'small.sgy')), 'r', 0) if mmap: f.mmap() binary_header = f.getbin() with pytest.raises(TypeError): _ = _segyio.getfield([], 0) with pytest.raises(KeyError): _ = _segyio.getfield(binary_header...
def send_chat_action(token, chat_id, action, timeout=None, message_thread_id=None): method_url = 'sendChatAction' payload = {'chat_id': chat_id, 'action': action} if timeout: payload['timeout'] = timeout if (message_thread_id is not None): payload['message_thread_id'] = message_thread_id...
def extractRhekatanWordpressCom(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 format_monodix_s(stuff): s = '' if (stuff in stuff2monodix): s += '<s n= + stuff2monodix[stuff] + />' else: fail_formatting_missing_for(stuff, 'monodix') s = '<s n="ERROR"/>' if ('><' in s): s = s.replace('><', '"/><s n="') elif ('<s n="+' in s): s = s.rep...
(IImageResource) class ImageResource(MImageResource, HasTraits): _ref = Any() absolute_path = Property(Str) name = Str() search_path = List() def create_bitmap(self, size=None): return self.create_image(size) def create_icon(self, size=None): return self.create_image(size) de...
def test_azetidine(): xyz_fn = 'azetidine_not_opt.xyz' geom = get_geom(xyz_fn) dihed_inds = geom.internal.dihedral_indices dihed_inds = np.concatenate((dihed_inds, ((3, 0, 8, 5), (0, 3, 5, 8), (3, 5, 8, 0)))) geom.internal.dihedral_indices = dihed_inds (gaussian_str, pysis_dict) = print_gaussian...
def create_dense_timeseries(map_name, smoothing_fwhm, settings, subcortical_data, subcortical_labels, mesh_settings): if (mesh_settings['meshname'] == '32k_fs_LR'): cifti_output = os.path.join(settings.results_dir, '{}_Atlas_s{}.dtseries.nii'.format(settings.fmri_label, smoothing_fwhm)) else: ci...
class IMalloc(IUnknown): _iid_ = GUID('{-0000-0000-C000-}') _methods_ = [COMMETHOD([], c_void_p, 'Alloc', ([], c_ulong, 'cb')), COMMETHOD([], c_void_p, 'Realloc', ([], c_void_p, 'pv'), ([], c_ulong, 'cb')), COMMETHOD([], None, 'Free', ([], c_void_p, 'py')), COMMETHOD([], c_ulong, 'GetSize', ([], c_void_p, 'pv')...
def test_testclient_headers_behavior(): client = TestClient(mock_service) assert (client.headers.get('user-agent') == 'testclient') client = TestClient(mock_service, headers={'user-agent': 'non-default-agent'}) assert (client.headers.get('user-agent') == 'non-default-agent') client = TestClient(mock...
def _test_correct_response_for_set_extent_competed_type_codes(client): resp = client.post('/api/v2/search/spending_by_award', content_type='application/json', data=json.dumps({'filters': {'award_type_codes': ['A', 'B', 'C', 'D'], 'extent_competed_type_codes': ['extent_competed_test'], 'time_period': [{'start_date':...
def test_data_integrity_test_missing_values_with_different_metrics() -> None: test_dataframe = pd.DataFrame({'target': [None, 0, 0, '']}) suite = TestSuite(tests=[TestNumberOfDifferentMissingValues(missing_values=[0], replace=True, eq=1), TestNumberOfDifferentMissingValues(missing_values=[0], replace=False, eq=...
class Select(Filter): template = 'widgets/filters/select.html' def __init__(self, name: str, label: str, null: bool=True): super().__init__(name, label, null=null) async def get_options(self): async def render(self, request: Request, value: Any): options = (await self.get_options()) ...
class TestBaseStatusAction(unittest.TestCase): def test_cannot_instantiate_base_action(self): with self.assertRaises(TypeError): BaseStatusAction() def test_basic_status_works(self): action_request = EnrichedActionRequest(action='status', body={}) response = StatusActionFacto...
def map_awsstatement_to_policystatement(statement: Dict[(str, Any)]) -> PolicyStatement: resources = (convert_obj_to_list(statement['Resource']) if ('Resource' in statement) else []) return PolicyStatement(effect=statement['Effect'], principals=get_json_values(statement['Principal']), actions=convert_obj_to_lis...
('/catalog/<board_name>') () def api_catalog(board_name): board: BoardModel = board_service.find_board(board_name) if (not board): abort(404) catalog: CatalogModel = posts_service.get_catalog(board) return {'threads': list(map((lambda i: build_thread_object(i)), catalog.threads))}
def fortios_log_fortianalyzer3(data, fos): fos.do_member_operation('log.fortianalyzer3', 'override-setting') if data['log_fortianalyzer3_override_setting']: resp = log_fortianalyzer3_override_setting(data, fos) else: fos._module.fail_json(msg=('missing task body: %s' % 'log_fortianalyzer3_ov...
class USP_GTY_1000BASEX(LiteXModule): dw = 8 tx_clk_freq = .0 rx_clk_freq = .0 def __init__(self, refclk_or_clk_pads, data_pads, sys_clk_freq, refclk_freq=.0, with_csr=True, rx_polarity=0, tx_polarity=0): assert (refclk_freq in [.0, .0]) pcs = PCS(lsb_first=True) self.submodules ...
class PythonShellPlugin(Plugin): BINDINGS = 'envisage.plugins.python_shell.bindings' COMMANDS = 'envisage.plugins.python_shell.commands' VIEWS = 'envisage.ui.workbench.views' id = 'envisage.plugins.python_shell' name = 'Python Shell' bindings = ExtensionPoint(List(Dict), id=BINDINGS, desc="\n\n ...
def test_top_1_fails_with_es_transactions_routed_dangerously(client, monkeypatch, elasticsearch_transaction_index, db): recipient1 = 'c870f759-d7bb-c074-784a-ab5867b1da3f' recipient2 = '0aa0ab7e-efa0-e3f4-6f55-6b0ecaf636e6' baker.make('recipient.RecipientLookup', id=1, recipient_hash=recipient1, legal_busin...
class OptionSeriesVariwideSonificationTracksMappingHighpassFrequency(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 select_api_key(keys, llm_model): import random avail_key_list = [] key_list = keys.split(',') if llm_model.startswith('gpt-'): for k in key_list: if is_openai_api_key(k): avail_key_list.append(k) for k in key_list: if is_freeai_api_key(k): ...
def _parse_liquidation(trace: DecodedCallTrace, child_traces: List[ClassifiedTrace], child_transfers: List[Transfer]) -> Optional[Liquidation]: classifier = get_classifier(trace) if ((classifier is not None) and issubclass(classifier, LiquidationClassifier)): return classifier.parse_liquidation(trace, c...
class ExtendedEmailSchema(EmailSchema): advanced_settings: AdvancedSettingsWithExtendedIdentityTypes = AdvancedSettingsWithExtendedIdentityTypes(identity_types=ExtendedIdentityTypes(email=True, phone_number=False, cookie_ids=[])) _validator def validate_fields(cls, values: Dict[(str, Any)]) -> Dict[(str, An...
_sigpipe def main(): from . import c2profile, utils parser = build_parser() args = parser.parse_args() levels = [logging.WARNING, logging.INFO, logging.DEBUG] level = levels[min((len(levels) - 1), args.verbose)] logging.basicConfig(level=level, datefmt='[%X]', format='%(asctime)s %(name)s %(mess...
class OptionSeriesWindbarbSonificationDefaultspeechoptionsMappingVolume(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 OptionSeriesColumnpyramidSonificationDefaultinstrumentoptionsMappingVolume(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, tex...
class TestCMYKPoperties(util.ColorAsserts, unittest.TestCase): def test_c(self): c = Color('color(--cmyk 0 0 1 0)') self.assertEqual(c['c'], 0) c['c'] = 0.2 self.assertEqual(c['c'], 0.2) def test_m(self): c = Color('color(--cmyk 0 0 1 0)') self.assertEqual(c['m'],...
class OptionSeriesTreegraphMarkerStatesHover(Options): def animation(self) -> 'OptionSeriesTreegraphMarkerStatesHoverAnimation': return self._config_sub_data('animation', OptionSeriesTreegraphMarkerStatesHoverAnimation) def enabled(self): return self._config_get(True) def enabled(self, flag:...
class TestPrivateComputationService(unittest.IsolatedAsyncioTestCase): def setUp(self) -> None: container_svc_patcher = patch('fbpcp.service.container_aws.AWSContainerService') storage_svc_patcher = patch('fbpcp.service.storage_s3.S3StorageService') private_computation_instance_repo_patcher ...
def invfft2(field, vals): if (len(vals) == 1): return [vals[0]] L = invfft2(field, vals[:(len(vals) // 2)]) R = shift(field, invfft2(field, vals[(len(vals) // 2):]), (len(vals) // 2)) o = ([0] * len(vals)) for (j, (l, r)) in enumerate(zip(L, R)): o[j] ^= l for (i, coeff) in e...
.parametrize(('is_wayland', 'expected_package'), [(True, 'qt6-wayland'), (False, 'libxcb-cursor0')]) def test_qt_log_wrapper_platform_plugin_error_on_x(monkeypatch, caplog, is_wayland, expected_package): monkeypatch.setattr(utils, '_is_wayland_display_manager', (lambda : is_wayland)) logger = logging.getLogger(...
def test_multiple_csvs_with_header(spark_session, provide_config): pc = DiskPersistenceBackedSparkCache(**provide_config) dataset_directory = os.sep.join([provide_config['cache_dir'], 'ds_multiline', 't1.csv']) csv_content_1 = 'given_name,family_name\nHans,Doe' csv_content_2 = 'given_name,family_name\nM...
def lazy_import(): from fastly.model.logging_common_response import LoggingCommonResponse from fastly.model.logging_request_caps_common import LoggingRequestCapsCommon from fastly.model.logging_splunk_additional import LoggingSplunkAdditional from fastly.model.logging_tls_common import LoggingTlsCommon ...
def _get_registered_names() -> Dict[(str, List[str])]: import d2go.registry.builtin modules = [d2go.registry.builtin] registered = {} for module in modules: registered_in_module = {f'{module.__name__}.{name}': obj.get_names() for (name, obj) in module.__dict__.items() if isinstance(obj, Registry...
def test_set_environ_for_wayland(monkeypatch): xcursor_size = os.environ.get('XCURSOR_SIZE', '') qt_qpa_platform = os.environ.get('QT_QPA_PLATFORM', '') try: with monkeypatch.context() as m: m.delenv('XCURSOR_SIZE', raising=False) m.delenv('QT_QPA_PLATFORM', raising=False) ...
.parametrize('current_data, reference_data, column_mapping', ((pd.DataFrame(), None, ColumnMapping()), (pd.DataFrame(), pd.DataFrame(), ColumnMapping()), (pd.DataFrame({'my_target': ['1', '2', '3'], '1': [0.1, 0.2, 0.3], '2': [0.9, 0.8, 0.7], '3': [0.9, 0.8, 0.7], 'feature2': ['a', 'b', 'c'], 'datetime': pd.date_range(...
def _save_file_c_rows(published_award_financial, total_rows, start_time, skipped_tas, submission_attributes, reverse): save_manager = BulkCreateManager(FinancialAccountsByAwards) for (index, row) in enumerate(published_award_financial, 1): if (not (index % 1000)): logger.info(f'C File Load: ...
.django_db def test_def_code_count_missing_defc(client, monkeypatch, disaster_account_data, helpers): helpers.patch_datetime_now(monkeypatch, 2022, 12, 31) resp = helpers.post_for_count_endpoint(client, url) assert (resp.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY) assert (resp.data['detail'] ==...
def filter_antivirus_mms_checksum_data(json): option_list = ['comment', 'entries', 'id', 'name'] json = remove_invalid_fields(json) dictionary = {} for attribute in option_list: if ((attribute in json) and (json[attribute] is not None)): dictionary[attribute] = json[attribute] re...
class OptionSeriesPieSonificationDefaultspeechoptionsPointgrouping(Options): def algorithm(self): return self._config_get('last') def algorithm(self, text: str): self._config(text, js_type=False) def enabled(self): return self._config_get(True) def enabled(self, flag: bool): ...