code
stringlengths
281
23.7M
def third_party_apps_default_dc_modules_and_settings(klass): logger.info('Loading third party apps DEFAULT DC modules and settings.') for (third_party_app, app_dc_settings) in get_third_party_apps_serializer_settings(): try: app_dc_settings.DEFAULT_DC_MODULES except AttributeError: ...
class CursesScreen(ScreenBase): def __init__(self, screen: 'curses._CursesWindow'): self.screen = screen def getmaxyx(self) -> Tuple[(int, int)]: return self.screen.getmaxyx() def refresh(self) -> None: self.screen.refresh() def erase(self) -> None: self.screen.erase() ...
def extractOverlordvolume10BlogspotCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None if ('manga' in item['title'].lower()): return None if ('Overlord' in item['tags']): ...
class OptionPlotoptionsTilemapSonificationTracksMappingTremoloDepth(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 tf_idfs(fables) -> Dict[(str, Dict[(str, int)])]: tfs = term_frequencies(fables) dfs = document_frequencies(fables) out = dict() D = len(tfs) for (dkey, term_counts) in tfs.items(): out[dkey] = {t: (tf * math.log((D / dfs[t]))) for (t, tf) in term_counts.items()} return out
class ScriptedStage(GenericAction): def __init__(self, target): self.source = target self.target = target def apply_action(self): g = self.game from thb.characters.meirin import Meirin from thb.characters.cirno import Cirno from thb.characters.sakuya import Sakuya...
class ObserverLifter(Lifter): HANDLERS: Dict[(Type[T], Callable[([T], V)])] = {} def lift(self, expression: T, **kwargs) -> V: handler = self.HANDLERS.get(expression.__class__, self.lift_unknown) return handler(expression) def lift_unknown(self, expression: T) -> V: def is_omitting_masks...
def ProcessTable(table): found = set() for rec in table.ScriptList.ScriptRecord: if ((rec.ScriptTag == 'DFLT') and (rec.Script.LangSysCount != 0)): tags = [r.LangSysTag for r in rec.Script.LangSysRecord] logging.info('Removing %d extraneous LangSys records: %s', rec.Script.LangSy...
class Console(QtWidgets.QPlainTextEdit): def __init__(self, prompt='>> ', startup_message='', parent=None): QtWidgets.QPlainTextEdit.__init__(self, parent) self.prompt = prompt self.history = [] self.namespace = {} self.construct = [] self.setGeometry(50, 75, 600, 400...
class bad_match_error_msg(error_msg): version = 6 type = 1 err_type = 4 def __init__(self, xid=None, code=None, data=None): if (xid != None): self.xid = xid else: self.xid = None if (code != None): self.code = code else: sel...
def apply_authentication(unauthed_message: Union[(PlainMessage, EncryptedMessage)], credentials: V3, security_engine_id: bytes) -> Union[(PlainMessage, EncryptedMessage)]: if ((credentials.auth is not None) and (not credentials.auth.method)): raise UnsupportedSecurityLevel('Incomplete data for authenticatio...
def search(key, part, forContentOwner=None, forDeveloper=None, forMine=None, relatedToVideoId=None, channelId=None, channelType=None, eventType=None, location=None, locationRadius=None, maxResults=None, onBehalfOfContentOwner=None, order=None, pageToken=None, publishedAfter=None, publishedBefore=None, q=None, regionCod...
class DecimatePro(FilterBase): __version__ = 0 filter = Instance(tvtk.DecimatePro, args=(), allow_none=False, record=True) input_info = PipelineInfo(datasets=['poly_data'], attribute_types=['any'], attributes=['any']) output_info = PipelineInfo(datasets=['poly_data'], attribute_types=['any'], attributes...
class Character(GameObject): classes: ClassVar[Dict[(str, Type[Character])]] = {} ui_meta: ClassVar[CharacterMeta] eventhandlers: ClassVar[List[Type[THBEventHandler]]] = [] categories: ClassVar[Iterable[str]] = () boss_skills: ClassVar[List[Type[Skill]]] = [] skills: List[Type[Skill]] = [] d...
def test_password_retrieval(mailer, db, client): page = client.get('/auth/password_retrieval').data assert ('Email' in page) assert ('Retrieve password' in page) with mailer.store_mails() as mailbox: with client.get('/auth/password_retrieval').context as ctx: with client.post('/auth/...
def downgrade(): op.alter_column('nu_release_item', 'reviewed', existing_type=postgresql.ENUM('unverified', 'valid', 'rejected', name='nu_item_enum'), type_=sa.BOOLEAN(), existing_nullable=False, nullable=False, existing_server_default=sa.text('false')) ENUM(name='pgenum').drop(op.get_bind(), checkfirst=True)
def mgmt_lock(timeout=MGMT_LOCK_TIMEOUT, key_args=(), key_kwargs=(), wait_for_release=False, bound_task=False, base_name=None): def wrap(fun): (fun, assigned=available_attrs(fun)) def inner(*args, **kwargs): if bound_task: params = args[1:] else: ...
class _ORDER(_CSTRUCT): _fields_ = [('Id', ctypes.c_ulonglong), ('Price', ctypes.c_double), ('Amount', ctypes.c_double), ('DealAmount', ctypes.c_double), ('AvgPrice', ctypes.c_double), ('Type', ctypes.c_uint), ('Offset', ctypes.c_uint), ('Status', ctypes.c_uint), ('ContractType', (ctypes.c_char * 31))]
class Linear(_Linear, WeightedModule): def __init__(self, in_features: int, out_features: int, bias: bool=True, device: ((Device | str) | None)=None, dtype: (DType | None)=None) -> None: self.in_features = in_features self.out_features = out_features super().__init__(in_features=in_features,...
class FaucetUntaggedIPv4PolicyRouteTest(FaucetUntaggedTest): CONFIG_GLOBAL = '\nvlans:\n 100:\n description: "100"\n faucet_vips: ["10.0.0.254/24"]\n acl_in: pbr\n 200:\n description: "200"\n faucet_vips: ["10.20.0.254/24"]\n routes:\n - route:\n ...
.skipif((not has_tensorflow), reason='needs TensorFlow') def test_tensorflow_wrapper_serialize_model_subclass(X, Y, input_size, n_classes, answer): import tensorflow as tf input_shape = (1, input_size) ops = get_current_ops() _subclass('foo.v1', X=ops.alloc2f(*input_shape), Y=to_categorical(ops.asarray1...
class CachedModelStreamOperator(StreamifyAbsOperator[(Dict, ModelOutput)]): def __init__(self, cache_manager: CacheManager, **kwargs) -> None: super().__init__(**kwargs) self._cache_manager = cache_manager self._client = LLMCacheClient(cache_manager) async def streamify(self, input_value...
class OptionSeriesParetoSonificationDefaultinstrumentoptionsMappingHighpassResonance(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,...
def weighted_choice(weight_dicts: List[Dict[(str, float)]]) -> str: final_weights = {key: 1.0 for key in weight_dicts[0].keys()} for weights in weight_dicts: for (key, weight) in weights.items(): final_weights[key] *= weights.get(key, 1.0) total_weight = sum(final_weights.values()) c...
def extractWorksofKun(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol or frag)) or ('preview' in item['title'].lower())): return None if ('Apocalypse Cockroach' in item['tags']): return buildReleaseMessageWithType(item, 'Apocalypse Cock...
def run_one_participant(settings, participant_label): find_or_build_fs_dir(settings, participant_label) run_ciftify_recon_all(settings, participant_label) if settings.anat_only: return bolds = find_participant_bold_inputs(participant_label, settings) for bold_input in bolds: if setti...
class WindowedItemsView(WindowedItemsViewT): def __init__(self, mapping: WindowWrapperT, event: Optional[EventT]=None) -> None: self._mapping = mapping self.event = event def __iter__(self) -> Iterator[Tuple[(Any, Any)]]: wrapper = cast(WindowWrapper, self._mapping) return wrappe...
def extractLetsyuriWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('icgsf', 'I, Cute Grass, am Super Fierce!', 'translated'), ('ftbtceo', 'Forced to Become The CEO'...
class CommitteeTotalsCombined(CommitteeTotals): __tablename__ = 'ofec_totals_combined_vw' candidate_contribution = db.Column(db.Numeric(30, 2)) exempt_legal_accounting_disbursement = db.Column(db.Numeric(30, 2)) federal_funds = db.Column(db.Numeric(30, 2)) fundraising_disbursements = db.Column(db.Nu...
([Output('modal-zones', 'children'), Output('modal-zone-title', 'children')], [Input('modal-activity-id-type-metric', 'children')], [State('activity-modal', 'is_open')]) def modal_power_zone(activity, is_open): if (activity and is_open): activity_id = activity.split('|')[0] return (zone_chart(activi...
_register_parser _set_msg_type(ofproto.OFPT_QUEUE_GET_CONFIG_REPLY) class OFPQueueGetConfigReply(MsgBase): def __init__(self, datapath): super(OFPQueueGetConfigReply, self).__init__(datapath) def parser(cls, datapath, version, msg_type, msg_len, xid, buf): msg = super(OFPQueueGetConfigReply, cls...
class AdminSalesByMarketerList(ResourceList): def query(self, _): return self.session.query(User).join(Order, (Order.marketer_id == User.id)).outerjoin(OrderTicket) methods = ['GET'] decorators = (api.has_permission('is_admin'),) schema = AdminSalesByMarketerSchema data_layer = {'model': Use...
class GroupView(APIView): serializer = GroupSerializer dc_bound = False order_by_default = order_by_fields = ('name',) def __init__(self, request, name, data, many=False): super(GroupView, self).__init__(request) self.name = name self.data = data self.many = many ...
def parse_items(itemstring, sort=False): if (not itemstring): return [] itemstring = force_text(itemstring) words = [] buf = [] to_be_split = [] i = iter(itemstring) try: while True: c = six.next(i) if (c == '"'): if buf: ...
class TestWebSocket(BaseEvenniaTest): def setUp(self): super().setUp() self.portal = EvenniaPortalService() evennia.EVENNIA_PORTAL_SERVICE = self.portal self.amp_server_factory = AMPServerFactory(self.portal) self.amp_server = self.amp_server_factory.buildProtocol('127.0.0.1'...
class UserFieldsCreateUpdateDelete(SingleCreateApiTestCase, SingleDeleteApiTestCase, SingleUpdateApiTestCase): __test__ = True ZenpyType = UserField object_kwargs = dict(description='test', title='i am test', key='somethingsomethingsomething') ignore_update_kwargs = ['key'] api_name = 'user_fields'
class HeaderEventFilter(QtCore.QObject): def __init__(self, editor): super().__init__() self.editor = editor def eventFilter(self, obj, event): if (event.type() == QtCore.QEvent.Type.ContextMenu): self.editor._on_column_context_menu(event.pos()) return True ...
class Driver(): def __init__(self, driver_actor, config, es_client_factory_class=client.EsClientFactory): self.logger = logging.getLogger(__name__) self.driver_actor = driver_actor self.config = config self.es_client_factory = es_client_factory_class self.default_sync_es_clie...
def main(): module_spec = schema_to_module_spec(versioned_schema) mkeyname = None fields = {'access_token': {'required': False, 'type': 'str', 'no_log': True}, 'enable_log': {'required': False, 'type': 'bool', 'default': False}, 'vdom': {'required': False, 'type': 'str', 'default': 'root'}, 'member_path': {...
class OptionPlotoptionsLollipopSonificationContexttracksMappingTime(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_empty_submission_types_enum_fail(client, download_test_data): download_generation.retrieve_db_string = Mock(return_value=get_database_dsn_string()) resp = client.post('/api/v2/download/accounts/', content_type='application/json', data=json.dumps({'account_level': 'treasury_account', 'filters': {'submis...
('ecs_deploy.cli.get_client') def test_update_task_one_new_environment_variable(get_client, runner): get_client.return_value = EcsTestClient('acces_key', 'secret_key') result = runner.invoke(cli.update, (TASK_DEFINITION_ARN_1, '-e', 'application', 'foo', 'bar', '-e', 'webserver', 'foo', 'baz')) assert (resu...
def manage_task(args, daccess): tid = args['id'][0] context = args.get('context') options = get_options(args, TASK_MUTATORS, {'deadline': {'None': None}}) if (not daccess.task_exists(tid)): return ('task_not_found', tid) if ((not options) and (context is None) and (args['depends_on'] is None...
class Event(): start: datetime.datetime end: datetime.datetime title: Optional[str] = None description: Optional[str] = None creator: Optional[str] = None status: Optional[str] = None location: Optional[str] = None attendees: Optional[List[str]] = None def from_raw_event(cls, d: dict...
class TD3Config(): min_replay_size: int = 1000 max_replay_size: int = 1000000 replay_table_name: str = adders_reverb.DEFAULT_PRIORITY_TABLE prefetch_size: Optional[int] = None batch_size: int = 256 policy_optimizer: Optional[optax.GradientTransformation] = None critic_optimizer: Optional[opt...
class OptionSeriesBarDragdropGuideboxDefault(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(self, text...
class TProtocolDialogue(Dialogue): INITIAL_PERFORMATIVES: FrozenSet[Message.Performative] = frozenset({TProtocolMessage.Performative.PERFORMATIVE_CT, TProtocolMessage.Performative.PERFORMATIVE_PT}) TERMINAL_PERFORMATIVES: FrozenSet[Message.Performative] = frozenset({TProtocolMessage.Performative.PERFORMATIVE_MT...
.django_db def test_tas_unparsable_no_ata(client, monkeypatch, elasticsearch_award_index, award_with_tas): _setup_es(client, monkeypatch, elasticsearch_award_index) resp = query_by_tas(client, {'require': [['011', '011-0990', '2000/2000-0990-000']]}) assert (resp.status_code == status.HTTP_422_UNPROCESSABLE...
class CommitteeTotalsHouseSenate(CommitteeTotals): __tablename__ = 'ofec_totals_house_senate_mv' all_other_loans = db.Column(db.Numeric(30, 2)) candidate_contribution = db.Column(db.Numeric(30, 2)) loan_repayments = db.Column(db.Numeric(30, 2)) loan_repayments_candidate_loans = db.Column(db.Numeric(...
class Server(): def __init__(self, config: Config) -> None: self.config = config self.server_state = ServerState() self.started = False self.should_exit = False self.force_exit = False self.last_notified = 0.0 def run(self, sockets: (list[socket.socket] | None)=No...
class OptionSeriesTreegraphSonificationDefaultspeechoptionsPointgrouping(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)...
class ToggleCommand(Command): def get_subtitle(self): return 'Toggle items' def check_by_item(self, item): item_toggled = item.copy() status = item['done'] item_toggled['done'] = (not status) return item_toggled def handle_click(self, todos, item_index): todos...
class YDotoolTyper(Typer): def supported() -> bool: return (is_wayland() and is_installed('ydotool')) def name() -> str: return 'ydotool' def get_active_window(self) -> str: return 'not possible with ydotool' def type_characters(self, characters: str, active_window: str) -> None:...
class BaseTableEditor(object): def set_menu_context(self, selection, object, column): self._menu_context = {'selection': selection, 'object': object, 'column': column, 'editor': self, 'info': self.ui.info, 'handler': self.ui.handler} def add_to_menu(self, menu_item): action = menu_item.item.acti...
class TestHidden(_TestGlob): cases = [[('**', '.*'), [('a', '.'), ('a', '..'), ('.aa',), ('.bb',), ('.',), ('..',)], glob.SCANDOTDIR], [('*', '.*'), [('a', '.'), ('a', '..')], glob.SCANDOTDIR], [('.*',), [('.aa',), ('.bb',), ('.',), ('..',)], glob.SCANDOTDIR], [('**', '.*'), [('a', '.'), ('a', '..'), ('.aa',), ('.a...
.parametrize('value,is_valid', (((- 1), True), (0, True), (1, True), (((SECPK1_N // 2) - 1), True), ((SECPK1_N // 2), False))) def test_validate_lt_secpk1n2(value, is_valid): if is_valid: validate_lt_secpk1n2(value) else: with pytest.raises(ValidationError): validate_lt_secpk1n2(valu...
.compilertest def test_mapping_host_ok(): test_yaml = '\n---\napiVersion: getambassador.io/v3alpha1\nkind: Mapping\nmetadata:\n name: good-host-mapping\n namespace: default\nspec:\n host: foo.example.com\n prefix: /wanted_group/\n service: star\n' r = compile_with_cachecheck(test_yaml, errors_ok=True) ...
class SeparateSessionSequenceWrapper(Sequence): def __init__(self, *args, **kwargs): self._graph = tf.Graph() self._session = tf.Session(graph=self._graph) super().__init__(*args, **kwargs) def load_from(self, *args, **kwargs): with self._graph.as_default(): with self...
class ID(Token): def __init__(self, identifier): Token.__init__(self, '') identifier = identifier.strip() if (identifier[0] in ("'", '"')): identifier = identifier[1:(- 1)] self.identifier = identifier def get_name(self): return self.identifier def __repr_...
class OptionSeriesOrganizationSonificationDefaultspeechoptionsMappingPlaydelay(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text:...
class TestMrtlibExtendedTimestampMrtRecord(unittest.TestCase): def test_parse_extended_header(self): body = b'test' buf = (b'\x11\x11\x11\x11' + body) (headers, rest) = mrtlib.ExtendedTimestampMrtRecord.parse_extended_header(buf) ok_(isinstance(headers, list)) eq_(1, len(head...
def block(state: StateCore) -> None: if state.inlineMode: token = Token('inline', '', 0) token.content = state.src token.map = [0, 1] token.children = [] state.tokens.append(token) else: state.md.block.parse(state.src, state.md, state.env, state.tokens)
class FaceEmotions(BaseModel): joy: Optional[int] sorrow: Optional[int] anger: Optional[int] surprise: Optional[int] disgust: Optional[int] fear: Optional[int] confusion: Optional[int] calm: Optional[int] unknown: Optional[int] neutral: Optional[int] contempt: Optional[int] ...
class TVTKGenerator(): def __init__(self, out_dir=''): if (not out_dir): out_dir = tempfile.mkdtemp() self.out_dir = os.path.join(out_dir, 'tvtk_classes') if (not os.path.exists(self.out_dir)): os.makedirs(self.out_dir) self.zip_name = 'tvtk_classes.zip' ...
class Nursery(): def __init__(self) -> None: self._threads: List[threading.Thread] = [] def __enter__(self) -> 'Nursery': return self def __exit__(self, exc_type: Optional[Type[BaseException]]=None, exc_value: Optional[BaseException]=None, traceback: Optional[TracebackType]=None) -> None: ...
def test_category_encoder_outputs_correct_dtype(): df_str = pd.DataFrame({'col1': ['a', 'b', 'c']}) res_str = MatchCategories().fit(df_str).transform(df_str) assert (res_str.dtypes['col1'] == 'category') df_float = pd.DataFrame({'col1': [1.0, 2.0, 3.0]}) tr = MatchCategories(variables=['col1'], igno...
class LinkAttribute(MessageAttribute): title: str = '' description: Optional[str] = None image: Optional[str] = None url: str = '' def __init__(self, title: str, description: Optional[str]=None, image: Optional[str]=None, url: str=''): self.title = title self.description = descriptio...
class Outpin(TimingNode): def __init__(self, resistance, delays): self.resistance = resistance self.delays = delays self.sink_wire = None self.downstream_cap = None self.rc_delay = None def set_sink_wire(self, wire): self.sink_wire = wire def propigate_downstr...
class MyHashSet(object): def __init__(self): self.hsize = 104729 self.ls = [[] for _ in xrange(self.hsize)] def add(self, key): r = (key % self.hsize) ta = self.ls[r] for v in ta: if (v == key): return ta.append(key) def remove(self...
def main(path: Optional[Path]=None, out_dir: Optional[Path]=None): if prefer_gpu(): print('Using gpu!') use_pytorch_for_gpu_memory() if (path is None): config = Config().from_str(CONFIG) else: config = Config().from_disk(path) C = thinc.registry.resolve(config) words_...
class ComputeMatrixRootInverseResidualsTest(unittest.TestCase): def test_matrix_root_inverse_residuals_with_not_two_dim_matrix(self): A = torch.zeros((1, 2, 3)) X_hat = torch.zeros((2, 2)) root = 4 exponent_multiplier = 1.82 self.assertRaisesRegex(ValueError, 'Matrix is not 2...
def extract_entities_for_page(entities: List[Dict[(str, Any)]], page_index: int) -> Dict[(str, Any)]: page_entities = {} for entity in entities: if (entity['page'] == page_index): key_name = entity['name'] key_value = entity['value'] page_entities[key_name] = key_valu...
class MySQLConnector(SQLConnector): secrets_schema = MySQLSchema def build_uri(self) -> str: config = self.secrets_schema(**(self.configuration.secrets or {})) user_password = '' if config.username: user = config.username password = (f':{config.password}' if confi...
def _mock_responder_proto(psk_bytes: bytes) -> NoiseConnection: proto = NoiseConnection.from_name(b'Noise_NNpsk0_25519_ChaChaPoly_SHA256', backend=ESPHOME_NOISE_BACKEND) proto.set_as_responder() proto.set_psks(psk_bytes) proto.set_prologue(b'NoiseAPIInit\x00\x00') proto.start_handshake() return ...
class AdminBaseViewTestMixin(): model = None def test_has_accessible_base_views(self): model = self.model urls = ('admin:{}_{}_changelist', 'admin:{}_{}_add') try: module_name = model._meta.module_name except AttributeError: module_name = model._meta.model...
_ns.route('/<username>/<coprname>/package/<package_name>/status_image/last_build.png') _ns.route('/g/<group_name>/<coprname>/package/<package_name>/status_image/last_build.png') _with_copr def copr_package_icon(copr, package_name): try: package = ComplexLogic.get_package(copr, package_name) except Objec...
('previs') def check_unique_shot_names(progress_controller=None): if (progress_controller is None): progress_controller = ProgressControllerBase() shot_nodes = pm.ls(type='shot') progress_controller.maximum = len(shot_nodes) shot_names = [] shots_with_non_unique_shot_names = [] for shot ...
class LChuv(LCh, Space): BASE = 'luv' NAME = 'lchuv' SERIALIZE = ('--lchuv',) WHITE = WHITES['2deg']['D65'] CHANNELS = (Channel('l', 0.0, 100.0), Channel('c', 0.0, 220.0, limit=(0.0, None)), Channel('h', 0.0, 360.0, flags=FLG_ANGLE)) def to_base(self, coords: Vector) -> Vector: return lc...
class BasePayloadTestCase(unittest.TestCase): def test_failed_to_get_name_lock(self): payload = Payload() payload.skip_named_lock = False with self.assertRaises(OSCError) as err_context: payload.query = Mock(return_value=None) payload.get_osc_lock() self.asser...
class TreeViewer(ContentViewer): STYLE = ((wx.TR_EDIT_LABELS | wx.TR_HAS_BUTTONS) | wx.CLIP_CHILDREN) content_provider = Instance(TreeContentProvider) label_provider = Instance(TreeLabelProvider, ()) selection_mode = Enum('single', 'extended') selection = List() show_images = Bool(True) show...
class OptionLegendTitle(Options): def style(self): return self._config_get({'fontSize': '0.75em', 'fontWeight': 'bold'}) def style(self, value: Any): self._config(value, js_type=False) def text(self): return self._config_get(None) def text(self, text: str): self._config(t...
class HFillMissingWithMean(Estimator, HasInputCol, HasInputCols, HasOutputCols, DefaultParamsReadable, DefaultParamsWritable): model = Param(Params._dummy(), 'model', 'model') _only def __init__(self, inputCols=None, model=None): super(HFillMissingWithMean, self).__init__() self._setDefault(...
class OptionSeriesAreasplinerangeDataDatalabelsTextpath(Options): def attributes(self): return self._config_get(None) def attributes(self, value: Any): self._config(value, js_type=False) def enabled(self): return self._config_get(False) def enabled(self, flag: bool): self...
def _find_iat_from_data_sections(process_controller: ProcessController, image_base: int, section_ranges: List[MemoryRange], exports_dict: Dict[(int, Dict[(str, Any)])]) -> Optional[MemoryRange]: page_size = process_controller.page_size for section_range in section_ranges: page_addr = (image_base + secti...
def fetch_latest_ec_details(award_id: int, mapper: OrderedDict, transaction_type: str) -> dict: (vals, ann) = split_mapper_into_qs(mapper) model = (TransactionFPDS if (transaction_type == 'fpds') else TransactionFABS) retval = model.objects.filter(transaction__award_id=award_id, officer_1_name__isnull=False...
class OptionPlotoptionsStreamgraphSonificationDefaultspeechoptionsMappingVolume(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 extractNyxtranslationHomeBlog(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('garbage brave isekai english translation', 'Garbage Brave: Isekai Ni Shoukan Sare Suterareta Y...
class generic(): file_s_not_found = "File '%s' not found" error_creating_file_s_s = "Error creating file '%s': %s" error_loading_file_s_s = "Error loading file '%s': %s" error_file_s_already_exists = "Error file '%s' already exists" error_url_format = "Expected URL format ' error_parsing_command...
class Output(): def __init__(self): self._os = platform.system() self._style = Style() self._color_status = True if (self._os == 'Windows'): self._color_status = False def _output(self, text, status): symbols = {'success': '[+]', 'warning': '[!]', 'error': '[-...
class MyCalendarThree(): def __init__(self): self.ss = [] self.ee = [] self.k_max = 0 def book(self, s: int, e: int) -> int: bisect.insort_left(self.ss, s) bisect.insort_left(self.ee, e) opened = bisect.bisect_right(self.ss, s) closed = bisect.bisect_right...
class KnowledgeEmailSource(): def __init__(self, config: dict): self.config = config self.config['type'] = 'email' def id(self): return self.config['address'] def user_config_items(cls): return [('address', 'email address'), ('password', 'email password'), ('imap_server', 'im...
def serialise_event_stages_current(save_data: list[int], event_current: dict[(str, Any)]) -> list[int]: unknown_val = event_current['unknown'] total_sub_chapters = (event_current['total'] // unknown_val) stars_per_sub_chapter = event_current['stars'] stages_per_sub_chapter = event_current['stages'] ...
class AggregateStats(base_tests.SimpleProtocol): def runTest(self): request = ofp.message.aggregate_stats_request(table_id=ofp.OFPTT_ALL, out_port=ofp.OFPP_ANY, out_group=ofp.OFPG_ANY, cookie=0, cookie_mask=0) logging.info('Sending aggregate flow stats request') (response, _) = self.controll...
def move(): mc.send_angles(init_angles[0], 50) time.sleep(3) mc.send_angles(init_angles[1], 50) time.sleep(3) gripper_on() mc.send_angles([0.0, (- 26.27), 0.17, (- 72.86), (- 0.17), (- 77.51), 0.0], 50) time.sleep(3) mc.send_angles([(- 2.02), (- 41.74), 0.43, (- 86.13), (- 0.17), (- 46.0...
class LTooltip(): def __init__(self, latlng=None, options: dict=None, selector=None): self._selector = selector (self._js, self.__is_attached) = ([], False) self.varId = ('L.marker(%s)' % latlng) def openTooltip(self, latlng=None, options=None): if (latlng is not None): ...
def test_task_config_is_test_mode(celery_session_app, celery_session_worker): _session_app.task def get_virtualised_worker_config(): return get_config().test_mode celery_session_worker.reload() sync_is_test_mode = get_virtualised_worker_config.run() async_is_test_mode = get_virtualised_worke...
def test_error_log_automatic_in_span_context_manager(tracer): scope = tracer.start_active_span('transaction') with pytest.raises(ValueError): with scope.span: raise ValueError('oops') client = tracer._agent error = client.events[constants.ERROR][0] assert (error['exception']['mes...
def test_equivalent_sources_build_points_bacwkards(coordinates): depth = 4500.0 expected_upward = (coordinates[2] - depth) with warnings.catch_warnings(record=True) as warn: eqs = EquivalentSources(relative_depth=depth) assert (len(warn) == 1) assert issubclass(warn[(- 1)].category, ...
def _register_plugin(plugin: Plugin, is_raising_exception: bool=True) -> None: register_function = _from_group_to_register_callable[plugin.group] try: register_function(plugin.name, entry_point=plugin.entry_point_path) except AEAException: if is_raising_exception: raise
.parametrize('rotation_method, ref_cycle', [('direct', 9), ('fourier', 9)]) def test_dimer(rotation_method, ref_cycle): coords = ((- 0.2), 1.1, 0) geom = Geometry(('X',), coords) N_raw = np.array((0.83, 0.27, 0.0)) dimer_kwargs = {'rotation_method': rotation_method, 'calculator': AnaPot(), 'N_raw': N_ra...