code
stringlengths
281
23.7M
def test_component_add_bad_dep(): builder = AEABuilder() builder.set_name('aea_1') builder.add_private_key('fetchai') connection = _make_dummy_connection() connection.configuration.pypi_dependencies = {'something': Dependency('something', '==0.1.0')} builder.add_component_instance(connection) ...
class Migration(migrations.Migration): dependencies = [('dmd', '0002_auto__1443'), ('frontend', '0046_auto__1412')] operations = [migrations.CreateModel(name='NCSOConcession', fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('date', models.DateField(db_...
def test_get_quarter_from_period(): assert (fyh.get_quarter_from_period(2) == 1) assert (fyh.get_quarter_from_period(3) == 1) assert (fyh.get_quarter_from_period(4) == 2) assert (fyh.get_quarter_from_period(5) == 2) assert (fyh.get_quarter_from_period(6) == 2) assert (fyh.get_quarter_from_period...
def test_existing_mnemonic_bls_withdrawal() -> None: my_folder_path = os.path.join(os.getcwd(), 'TESTING_TEMP_FOLDER') clean_key_folder(my_folder_path) if (not os.path.exists(my_folder_path)): os.mkdir(my_folder_path) runner = CliRunner() inputs = ['TREZOR', 'abandon abandon abandon abandon ...
def filter_firewall_policy46_data(json): option_list = ['action', 'comments', 'dstaddr', 'dstintf', 'fixedport', 'ippool', 'logtraffic', 'logtraffic_start', 'name', 'per_ip_shaper', 'permit_any_host', 'policyid', 'poolname', 'schedule', 'service', 'srcaddr', 'srcintf', 'status', 'tcp_mss_receiver', 'tcp_mss_sender'...
def get_possible_modes() -> set[str]: modes = set() with open('web/src/utils/constants.ts', encoding='utf-8') as file_: search = re.search('^export const modeOrder = (\\[$.*?^]) as const;$', file_.read(), flags=(re.DOTALL | re.MULTILINE)) if (search is not None): group = search.group...
class MystReferenceResolver(ReferencesResolver): default_priority = 9 def log_warning(self, target: (None | str), msg: str, subtype: MystWarnings, **kwargs: Any): if (target and self.config.nitpick_ignore and (('myst', target) in self.config.nitpick_ignore)): return if (target and se...
class ImpalaEvents(ABC): _epoch_stats(np.nanmean, input_name='time') _epoch_stats(np.nanmean, input_name='percent') def time_dequeuing_actors(self, time: float, percent: float): _epoch_stats(np.nanmean, input_name='time') _epoch_stats(np.nanmean, input_name='percent') def time_collecting_actors(...
class OptionSeriesNetworkgraphSonificationDefaultinstrumentoptionsMappingLowpassResonance(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(...
def test_always_transact(plugintester, mocker, chain): mocker.spy(chain, 'undo') result = plugintester.runpytest() result.assert_outcomes(passed=2) assert (chain.undo.call_count == 0) result = plugintester.runpytest('--coverage') result.assert_outcomes(passed=2) assert (chain.undo.call_count...
def fetch_cfda_id_title_by_number(cfda_number: str) -> Optional[Tuple[(int, str)]]: columns = ['id', 'program_title'] result = Cfda.objects.filter(program_number=cfda_number).values(*columns).first() if (not result): logger.warning('{} not found for cfda_number: {}'.format(','.join(columns), cfda_nu...
def get_table_stats(dp, waiters, to_user=True): stats = dp.ofproto_parser.OFPTableStatsRequest(dp, 0) msgs = [] ofctl_utils.send_stats_request(dp, stats, waiters, msgs, LOG) tables = [] for msg in msgs: stats = msg.body for stat in stats: s = stat.to_jsondict()[stat.__cla...
def deb_kernel(packages, kernel_version, current_version, variant=None): if (current_version.startswith(kernel_version) and (not variant)): return current_version import re kernels = set() kernels_add = kernels.add (current_version, current_variant) = re.match('^([0-9-.]+)(-[a-z0-9]+)?$', cu...
class Strategy(): def __init__(self, symbols, capital, start, end, options=default_options): self.symbols = symbols self.capital = capital self.start = start self.end = end self.options = options.copy() self.ts = None self.rlog = None self.tlog = None ...
_module() class NaiveProjectionEncoder(nn.Module): def __init__(self, input_size, output_size, use_embedding: bool=False, use_neck: bool=False, neck_size: int=8, preprocessing=None): super().__init__() self.use_embedding = use_embedding self.input_size = input_size self.output_size =...
def monitor(exit_event, wait): wait = max(0.1, wait) rapl_power_unit = (0.5 ** readmsr('MSR_RAPL_POWER_UNIT', from_bit=8, to_bit=12, cpu=0)) power_plane_msr = {'Package': 'MSR_INTEL_PKG_ENERGY_STATUS', 'Graphics': 'MSR_PP1_ENERGY_STATUS', 'DRAM': 'MSR_DRAM_ENERGY_STATUS'} prev_energy = {'Package': ((rea...
def extractVictoriatranslationBlogspotCom(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,...
class Danmu_layer(): def __init__(self, frame_w, frame_h, danmu_txt): self.frame_w = frame_w self.frame_h = frame_h self.track_h = 100 self.track_num = int((self.frame_h / self.track_h)) self.background = self.create_trans_background() self.tracks_color = [(255, 255, ...
class ReadEnum(Read[EnumT]): __slots__ = ('enum_type',) def __init__(self, enum_type: Type[EnumT]) -> None: self.enum_type = enum_type def __call__(self, io: IO[bytes]) -> Iterator[EnumT]: value = read_unsigned_varint(io) try: (yield self.enum_type(value)) except ...
class OptionPlotoptionsTimelineSonificationTracksMappingHighpassFrequency(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 compute_com_and_com_vel(pb_client, body_id, indices=None): if (indices is None): indices = range((- 1), pb_client.getNumJoints(body_id)) total_mass = 0.0 com = np.zeros(3) com_vel = np.zeros(3) for i in indices: di = pb_client.getDynamicsInfo(body_id, i) mass = di[0] ...
class StaticRadicli(Radicli): data: StaticData disable: bool debug: bool def __init__(self, data: StaticData, disable: bool=False, debug: bool=False, converters: ConvertersType=SimpleFrozenDict()) -> None: super().__init__(prog=data['prog'], help=data['help'], version=data['version'], extra_key=...
def downgrade(): with op.batch_alter_table('user', schema=None) as batch_op: batch_op.drop_constraint(None, type_='unique') batch_op.alter_column('id', existing_type=sqlalchemy_utils.types.uuid.UUIDType(), type_=sa.NUMERIC(precision=16), existing_nullable=False) batch_op.drop_column('task_id...
_required _required _POST def password_change(request): status = 200 pform = ChangePasswordForm(request.user, request.POST) if pform.is_valid(): status = pform.save(request) if (status == 200): messages.success(request, _('Your password was successfully changed')) ret...
class OptionPlotoptionsVectorSonificationTracksMappingPlaydelay(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 set_attributes(): parser = argparse.ArgumentParser(description='FB fio Synthetic Benchmark Suite for storage ver 3.6.0') parser.add_argument('-d', action='store', dest='device', type=str, help='(Required) device path for single device target, ALL for alldata devices, or ALLRAID for all mdraid devices', requ...
class NameOrTotalTupleCommandHandler(MethodCommandHandler): def handle(self, params: str) -> Payload: name: Optional[str] = None (param, name) = split(params) all_params = ((param == '*') or (param == '*;')) params_join = param.endswith(';') total = True index_join = ...
class queue_stats_reply(stats_reply): version = 1 type = 17 stats_type = 5 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 OptionsChat(Options): def dated(self): return self._config_get(True) def dated(self, flag: bool): if flag: self.component.jsImports.add('moment') self._config(flag) def readonly(self): return self._config_get(True) def readonly(self, flag: bool): ...
class ExaError(Exception): def __init__(self, connection, message): self.connection = connection self.message = message super().__init__(self, message) def get_params_for_print(self): return {'message': self.message, 'dsn': self.connection.options['dsn'], 'user': self.connection....
.skipif((redis.VERSION < (3,)), reason='pubsub not available as context manager in redis-py 2') .integrationtest def test_publish_subscribe(instrument, elasticapm_client, redis_conn): elasticapm_client.begin_transaction('transaction.test') with capture_span('test_publish_subscribe', 'test'): redis_conn....
_HEADS_REGISTRY.register() class StandardROIHeadsWithSubClass(StandardROIHeads): def __init__(self, cfg, input_shape): super().__init__(cfg, input_shape) self.subclass_on = cfg.MODEL.SUBCLASS.SUBCLASS_ON if (not self.subclass_on): return self.num_subclasses = cfg.MODEL.SU...
class ExtentDialog(HasTraits): data_x_min = Float data_x_max = Float data_y_min = Float data_y_max = Float data_z_min = Float data_z_max = Float x_min = Range('data_x_min', 'data_x_max', 'data_x_min') x_max = Range('data_x_min', 'data_x_max', 'data_x_max') y_min = Range('data_y_min',...
class ShfeTradingCalendarSpider(scrapy.Spider): name = 'shfe_trading_calendar_spider' custom_settings = {} def __init__(self, name=None, **kwargs): super().__init__(name, **kwargs) self.saved_trading_dates = get_trading_calendar(security_type='future', exchange='shfe') self.trading_d...
def get_constructor(osm_data: OSMData) -> Constructor: flinger: MercatorFlinger = MercatorFlinger(BoundaryBox((- 0.01), (- 0.01), 0.01, 0.01), 18, osm_data.equator_length) constructor: Constructor = Constructor(osm_data, flinger, SHAPE_EXTRACTOR, CONFIGURATION) constructor.construct_ways() return constr...
def test_point_gauge_output(): filename = 'test_gauge_output.csv' silent_rm(filename) p = PointGauges(gauges=((('u0',), ((0, 0, 0), (1, 1, 1))),), fileName=filename) time_list = [0.0, 1.0, 2.0] run_gauge(p, time_list) correct_gauge_names = ['u0 [ 0 0 0]', 'u0 [ 1 ...
def strict_delete(self, match, priority=None): msg4 = ofp.message.flow_delete_strict() msg4.out_port = ofp.OFPP_NONE msg4.buffer_id = msg4.match = match if (priority != None): msg4.priority = priority self.controller.message_send(msg4) do_barrier(self.controller)
class LayoutPageCoordinates(NamedTuple): x: float y: float width: float height: float page_number: int = 0 def from_bounding_box(bounding_box: BoundingBox, page_number: int=0) -> 'LayoutPageCoordinates': return LayoutPageCoordinates(x=bounding_box.x, y=bounding_box.y, width=bounding_box....
class SyntenyBackend(): backends = {} def __init__(self): self.target_fasta = None self.threads = None self.blocks = None def make_permutations(self, recipe, blocks, output_dir, overwrite, threads): self.target_fasta = recipe['genomes'][recipe['target']].get('fasta') ...
def get_episodes(html, url): id = int(re.search('mc(\\d+)', url).group(1)) if (id not in comic_detail): comic_detail.load(id) detail = comic_detail.pop(id) return [Episode('{} - {}'.format(ep['short_title'], ep['title']), urljoin(url, '/mc{}/{}?from=manga_detail'.format(id, ep['id']))) for ep in...
class AclResponseAllOf(ModelNormal): allowed_values = {} validations = {} _property def additional_properties_type(): return (bool, date, datetime, dict, float, int, list, str, none_type) _nullable = False _property def openapi_types(): return {'service_id': (str,), 'version'...
class OptionPlotoptionsWaterfallSonificationTracksMappingGapbetweennotes(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 PublishItem(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() ...
class EnumInstance(object): def __init__(self, enum, value): self.enum = enum self.value = value def __eq__(self, value): if (isinstance(value, EnumInstance) and (value.enum is not self.enum)): return False if hasattr(value, 'value'): value = value.value ...
class TrainingTimeEstimator(): def __init__(self, total_users: int, users_per_round: int, epochs: int, training_dist: IDurationDistribution, num_examples: Optional[List[int]]=None): self.total_users = total_users self.users_per_round = users_per_round self.epochs = epochs self.rounds...
def main(): data = load_iris() X = data['data'] y = data['target'] X = X[(y != 0)] y = y[(y != 0)] y -= 1 (X_train, X_test, y_train, y_test) = train_test_split(X, y, test_size=0.33) clf = LogisticRegression() clf.fit(X_train, y_train) y_pred = np.rint(clf.predict(X_test)) acc...
def integrate_spherical_annulus_volume(MeshClass, radius=1000, refinement=2): m = MeshClass(radius=radius, refinement_level=refinement) layers = 10 layer_height = (1.0 / (radius * layers)) mesh = ExtrudedMesh(m, layers, layer_height=layer_height, extrusion_type='radial') fs = FunctionSpace(mesh, 'CG...
def _download_file_python(url: str, target_path: Path) -> Path: import shutil import tempfile with tempfile.NamedTemporaryFile(delete=False) as temp_file: try: file_path = temp_file.name for (progress, total_size) in _stream_url_data_to_file(url, temp_file.name): ...
def update_config_file(updates: Dict[(str, Dict[(str, Any)])], config_path_override: str) -> None: config_path = (config_path_override or load_file(file_names=[DEFAULT_CONFIG_PATH])) current_config = load(config_path) for (key, value) in updates.items(): if (key in current_config): curre...
def hash(x): if isinstance(x, bytes): return hashlib.sha256(x).digest() elif isinstance(x, Point): return hash(x.serialize()) b = b'' for a in x: if isinstance(a, bytes): b += a elif isinstance(a, int): b += a.to_bytes(32, 'little') elif is...
def test_get_firmware_number(backend_db, common_db): assert (common_db.get_firmware_number() == 0) backend_db.insert_object(TEST_FW) assert (common_db.get_firmware_number(query={}) == 1) assert (common_db.get_firmware_number(query={'uid': TEST_FW.uid}) == 1) fw_2 = create_test_firmware(bin_path='con...
def test_multisol(): A = make_integer_matrix() m = GSO.Mat(A) lll_obj = LLL.Reduction(m) lll_obj() solutions = [] solutions = Enumeration(m, nr_solutions=200).enumerate(0, 27, 48.5, 0) assert (len(solutions) == (126 / 2)) for (_, sol) in solutions: sol = IntegerMatrix.from_iterab...
class GetActiveRepositoriesAction(Action): def help_text(cls) -> str: return 'remain only active repos: filter and remove duplicates and skip repos in Blacklist' def name(cls): return 'daily-active-repositories' def _execute(self, day: datetime): return get_daily_active_repositories(...
class TestFlakyMany(AEATestCaseManyFlaky): .flaky(reruns=1) def test_fail_on_first_run(self): file = os.path.join(self.t, 'test_file') if (self.run_count == 1): open(file, 'a').close() raise AssertionError('Expected error to trigger rerun!') assert (self.run_count...
def extractKeisotsunatranslationWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('my old gong has amnesia', 'my old gong has amnesia', 'translated'), ('PRC', 'PRC', ...
class StalkerShotAddAnimationOutputOperator(bpy.types.Operator): bl_label = 'Add Animation Output' bl_idname = 'stalker.shot_add_animation_output_op' stalker_entity_id = bpy.props.IntProperty(name='stalker_entity_id') stalker_entity_name = bpy.props.StringProperty(name='stalker_entity_name') def exe...
(estimator=_estimator_docstring, scoring=_scoring_docstring, cv=_cv_docstring, confirm_variables=_confirm_variables_docstring, variables=_variables_numerical_docstring, missing_values=_missing_values_docstring, variables_=_variables_attribute_docstring, feature_names_in_=_feature_names_in_docstring, n_features_in_=_n_f...
class LinuxNetwork(): def network_services_in_priority_order(): conns = NetworkManager.Settings.ListConnections() conns = list(filter((lambda x: ('autoconnect-priority' in x.GetSettings()['connection'])), conns)) def uint32(signed_integer): return int(ctypes.c_uint32(signed_integ...
.parametrize('ops', ALL_OPS) .parametrize('dtype', FLOAT_TYPES) .parametrize('index_dtype', ['int32', 'uint32']) def test_gather_add(ops, dtype, index_dtype): table = ops.xp.arange(12, dtype=dtype).reshape(4, 3) indices = ops.xp.array([[0, 2], [3, 1], [0, 1]], dtype=index_dtype) gathered = ops.gather_add(ta...
def print_pred(args, screen_name, prediction): if (prediction[0] > prediction[1]): label = 'legit' confidence = prediction[0] if (args.only in (label, None)): print(('%20s legit %f %%' % (screen_name, (prediction[0] * 100.0)))) else: label = 'bot' confiden...
def fortios_extension_controller(data, fos): fos.do_member_operation('extension-controller', 'extender-profile') if data['extension_controller_extender_profile']: resp = extension_controller_extender_profile(data, fos) else: fos._module.fail_json(msg=('missing task body: %s' % 'extension_con...
def plot_line_webgl(viz, env, args): webgl_num_points = 200000 webgl_x = np.linspace((- 1), 0, webgl_num_points) webgl_y = (webgl_x ** 3) viz.line(X=webgl_x, Y=webgl_y, opts=dict(title='{} points using WebGL'.format(webgl_num_points), webgl=True), env=env, win='WebGL demo') return webgl_x
def _remove_builtins(fake_tb): traceback = fake_tb while traceback: frame = traceback.tb_frame while frame: frame.f_globals = dict(((k, v) for (k, v) in frame.f_globals.items() if (k not in dir(builtins)))) frame = frame.f_back traceback = traceback.tb_next
class CssImgH2(CssStyle.Style): _attrs = {'opacity': 0, 'transition': 'all 0.2s ease-in-out', 'text-transform': 'uppercase', 'text-align': 'center', 'position': 'relative', 'padding': '10px', 'margin': '20px 0 0 0'} _hover = {'opacity': 1, 'transform': 'translateY(0px)'} _selectors = {'child': 'h2'} def...
def execute(commands, parameters): for command in commands: click.echo('[EXECUTING] {}'.format(command.format(**parameters))) try: subprocess.check_call([arg.format(**parameters) for arg in command.split()]) except subprocess.CalledProcessError as exc: print(exc) ...
class OptionSeriesVariwideSonificationTracksMappingVolume(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 OptionSeriesFunnelDataDragdropGuideboxDefault(Options): def className(self): return self._config_get('highcharts-drag-box-default') def className(self, text: str): self._config(text, js_type=False) def color(self): return self._config_get('rgba(0, 0, 0, 0.1)') def color(sel...
class Context(): def __init__(self, i3l: Connection, tree: Con, workspace_sequence: Optional[WorkspaceSequence]): self.i3l = i3l self.tree = tree self.focused = tree.find_focused() self.workspace = self.focused.workspace() self.containers = self._sync_containers(self.workspac...
class TestSegmentSentimentAnalysisDataClass(): .parametrize(('kwargs', 'expected'), [_assign_markers_parametrize(segment='Valid segment', sentiment=SentimentEnum.POSITIVE.value, sentiment_rate=0, expected={'sentiment': 'Positive', 'sentiment_rate': 0.0}), _assign_markers_parametrize(segment='Valid segment', sentime...
class RandomInstanceCrop(aug.Augmentation): def __init__(self, crop_scale: Tuple[(float, float)]=(0.8, 1.6), fix_instance=False): super().__init__() self.crop_scale = crop_scale self.fix_instance = fix_instance assert (isinstance(crop_scale, (list, tuple)) and (len(crop_scale) == 2))...
class MockPopenHandle(object): def __init__(self, returncode=None, stdout=None, stderr=None): self.returncode = (returncode or 0) self.stdout = (stdout or 'mock stdout') self.stderr = (stderr or 'mock stderr') def communicate(self): return (self.stdout.encode(), self.stderr.encod...
def test_lp_default_handling(): def t1(a: int) -> NamedTuple('OutputsBC', t1_int_output=int, c=str): a = (a + 2) return (a, ('world-' + str(a))) def my_wf(a: int, b: int) -> (str, str, int, int): (x, y) = t1(a=a) (u, v) = t1(a=b) return (y, v, x, u) lp = launch_plan.L...
class table_feature_prop_wildcards(table_feature_prop): type = 10 def __init__(self, oxm_ids=None): if (oxm_ids != None): self.oxm_ids = oxm_ids else: self.oxm_ids = [] return def pack(self): packed = [] packed.append(struct.pack('!H', self.typ...
(scope='module') def simple_mesh(): nnx = 4 nny = 4 x = ((- 1.0), (- 1.0)) L = (2.0, 2.0) refinementLevels = 2 nLayersOfOverlap = 1 parallelPartitioningType = 0 skipInit = False mlMesh = MeshTools.MultilevelQuadrilateralMesh(nnx, nny, 1, x[0], x[1], 0.0, L[0], L[1], 1.0, refinementLe...
.parametrize('ops', ALL_OPS) .parametrize('dtype', FLOAT_TYPES) def test_backprop_reduce_mean(ops, dtype): dX = ops.backprop_reduce_mean(ops.xp.arange(1, 7, dtype=dtype).reshape(2, 3), ops.xp.array([4, 2], dtype='int32')) assert (dX.dtype == dtype) ops.xp.testing.assert_allclose(dX, [[0.25, 0.5, 0.75], [0.2...
class ElyraPropertyList(list): def to_dict(self: List[ElyraPropertyListItem], use_prop_as_value: bool=False) -> Dict[(str, str)]: prop_dict = {} for prop in self: if ((prop is None) or (not isinstance(prop, ElyraPropertyListItem))): continue prop_key = prop.ge...
class OptionSeriesVariablepieSonificationDefaultspeechoptionsMappingRate(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):...
.skipcomplex def test_p_independence_hgrad(mesh, variant): family = 'Lagrange' expected = ([16, 12] if (mesh.topological_dimension() == 3) else [9, 7]) solvers = ([fdmstar] if (variant is None) else [fdmstar, facetstar]) for degree in range(3, 6): element = FiniteElement(family, cell=mesh.ufl_ce...
('bodhi.server.scripts.sar.initialize_db', mock.Mock()) class TestSar(BasePyTestCase): def test_invalid_user(self): runner = testing.CliRunner() r = runner.invoke(sar.get_user_data, [('--username=' + 'invalid_user')]) assert (r.exit_code == 0) assert (r.output == '') def test_inv...
def naics_test_data(db): baker.make('search.AwardSearch', award_id=1, latest_transaction_id=1) baker.make('search.AwardSearch', award_id=2, latest_transaction_id=2) baker.make('search.AwardSearch', award_id=3, latest_transaction_id=3) baker.make('search.AwardSearch', award_id=4, latest_transaction_id=4)...
class BucketsAclScanner(base_scanner.BaseScanner): def __init__(self, global_configs, scanner_configs, service_config, model_name, snapshot_timestamp, rules): super(BucketsAclScanner, self).__init__(global_configs, scanner_configs, service_config, model_name, snapshot_timestamp, rules) self.rules_en...
class TestHTTPStatus(): def test_raise_status_in_before_hook(self, client): response = client.simulate_request(path='/status', method='GET') assert (response.status == falcon.HTTP_200) assert (response.status_code == 200) assert (response.headers['x-failed'] == 'False') asser...
def _get_kwargs(*, client: Client, user_id: str, lock: bool) -> Dict[(str, Any)]: url = '{}/admin/users/lock'.format(client.base_url) headers: Dict[(str, str)] = client.get_headers() cookies: Dict[(str, Any)] = client.get_cookies() params: Dict[(str, Any)] = {} params['user_id'] = user_id params...
def test_request_bad_port(django_elasticapm_client): request = WSGIRequest(environ={'wsgi.input': io.BytesIO(), 'REQUEST_METHOD': 'POST', 'SERVER_NAME': 'testserver', 'SERVER_PORT': '${port}', 'CONTENT_TYPE': 'text/html', 'ACCEPT': 'text/html'}) request.read(1) django_elasticapm_client.capture('Message', me...
def run_gauge(p, time_list, nd=3, total_nodes=None): (model, initialConditions) = gauge_setup(nd, total_nodes) p.attachModel(model, None) m = model.levelModelList[(- 1)] m.setInitialConditions(initialConditions, time_list[0]) m.timeIntegration.tLast = time_list[0] tCount = 0 p.calculate() ...
def run_spinner(spinner): global ACTIVE_SPINNER try: if ((not isinstance(sys.stderr, DummyFile)) and SPINNER_ENABLED): spinner.start() spinner_started = True save_stdout = sys.stdout save_stderr = sys.stderr sys.stdout = DummyFile(sys.stdout, s...
class ContextGenerator(object): def __init__(self, default_ctx): self.default_ctx = ManifestContext(default_ctx) self.ctx_by_project = {} def set_value_for_project(self, project_name, key, value): project_ctx = self.ctx_by_project.get(project_name) if (project_ctx is None): ...
class OptionSeriesNetworkgraphSonificationDefaultinstrumentoptionsMappingVolume(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...
def test_jinja_template_rendering_without_examples(example_text): nlp = spacy.blank('en') doc = nlp.make_doc(example_text) llm_ner = make_summarization_task(examples=None, max_n_words=10) prompt = list(llm_ner.generate_prompts([doc]))[0] assert (prompt.strip() == f""" You are an expert summarization...
class OnUserRoleCreated(TaskBase): __name__ = 'on_user_role_created' async def run(self, user_id: str, role_id: str, workspace_id: str): workspace = (await self._get_workspace(uuid.UUID(workspace_id))) async with self.get_workspace_session(workspace) as session: role_repository = Rol...
_heads([Derivative, RealDerivative, ComplexDerivative, ComplexBranchDerivative, MeromorphicDerivative]) def tex_Derivative(head, args, **kwargs): argstr = [arg.latex(**kwargs) for arg in args] assert ((len(args) == 2) and (args[1].head() == For)) forargs = args[1].args() if (len(forargs) == 2): ...
class ScanQRTextEdit(ButtonsTextEdit, MessageBoxMixin): def __init__(self, text='', allow_multi=False): ButtonsTextEdit.__init__(self, text) self.allow_multi = allow_multi self.setReadOnly(0) self.addButton('file.png', self.file_input, _('Read file')) icon = ('qrcode_white.pn...
def dump_keepalive_packet(packet): if (logging.getLogger().getEffectiveLevel() > 5): return if (packet.subtype == 'stype_status'): logging.log(5, 'keepalive {} model {} ({}) player {} ip {} mac {} devcnt {} u2 {} u3 {}'.format(packet.subtype, packet.model, packet.device_type, packet.content.play...
() def reply_to_message_update_type(reply_to_message): edited_message = None channel_post = None edited_channel_post = None inline_query = None chosen_inline_result = None callback_query = None shipping_query = None pre_checkout_query = None poll = None poll_answer = None my_...
def collate_fn(batch: List[Tuple[(Tensor, str)]], gpt2_type: str='distilgpt2', max_length: int=1024) -> Tuple[(Tensor, Tensor, Tensor)]: tokenizer = get_tokenizer(gpt2_type) (bos, eos) = (tokenizer.bos_token, tokenizer.eos_token) encoded = tokenizer.batch_encode_plus([f'{bos}{random.choice(y)}{eos}' for (_,...
class TestPickable(): def test_pickable_attribute(self): attribute_foo = Attribute('foo', int, True, 'a foo attribute.') try: pickle.dumps(attribute_foo) except Exception: pytest.fail('Error during pickling.') def test_pickable_data_model(self): attribute_...
def setup_regtest(app_state) -> HeadersRegTestMod: while True: try: regtest_import_privkey_to_node() delete_headers_file(app_state.headers_filename()) (Net._net.CHECKPOINT, Net._net.VERIFICATION_BLOCK_MERKLE_ROOT) = calculate_regtest_checkpoint(Net.MIN_CHECKPOINT_HEIGHT) ...
def update_row(row, result, latitude_column='latitude', longitude_column='longitude', geojson=False, spatialite=False, raw=''): if geojson: row[GEOMETRY_COLUMN] = {'type': 'Point', 'coordinates': [result.longitude, result.latitude]} elif spatialite: row[GEOMETRY_COLUMN] = f'POINT ({result.longit...
class AuditLoggingRulesEngine(bre.BaseRulesEngine): def __init__(self, rules_file_path, snapshot_timestamp=None): super(AuditLoggingRulesEngine, self).__init__(rules_file_path=rules_file_path, snapshot_timestamp=snapshot_timestamp) self.rule_book = None def build_rule_book(self, global_configs=N...
class OptionSeriesBellcurveStatesSelectHalo(Options): def attributes(self): return self._config_get(None) def attributes(self, value: Any): self._config(value, js_type=False) def opacity(self): return self._config_get(0.25) def opacity(self, num: float): self._config(num,...