code
stringlengths
281
23.7M
class OutputFilesPage(QWizardPage): def __init__(self, parent=None): super(OutputFilesPage, self).__init__(parent) self.setTitle('Output Files') self.setSubTitle('Specify where you want the wizard to put the generated skeleton code.') self.setPixmap(QWizard.LogoPixmap, QPixmap(':/ima...
class Solution(object): def isValidBST(self, root): return self.isVaild_helper(root, ((- sys.maxint) - 1), sys.maxint) def isVaild_helper(self, root, minVal, maxVal): if (root is None): return True if ((root.val >= maxVal) or (root.val <= minVal)): return False ...
def selfies_to_hot(selfie, largest_selfie_len, alphabet): symbol_to_int = dict(((c, i) for (i, c) in enumerate(alphabet))) selfie += ('[nop]' * (largest_selfie_len - sf.len_selfies(selfie))) symbol_list = sf.split_selfies(selfie) integer_encoded = [symbol_to_int[symbol] for symbol in symbol_list] on...
def process(input_json: str, output_file: str, output_json: str=None, threshold: int=1, keep_punctuation: bool=False, character_level: bool=False, retokenize: bool=False, host_address: str=' zh: bool=True): logfmt = '%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s' logging.basicConfig(level=loggi...
def test_kafka_batch_npartitions(): j1 = random.randint(0, 10000) ARGS1 = {'bootstrap.servers': 'localhost:9092', 'group.id': ('streamz-test%i' % j1), 'enable.auto.commit': False, 'auto.offset.reset': 'earliest'} j2 = (j1 + 1) ARGS2 = {'bootstrap.servers': 'localhost:9092', 'group.id': ('streamz-test%i'...
def configure_logging(config: Configuration, debug: bool) -> None: logging.captureWarnings(capture=True) if debug: logging_level = logging.DEBUG warnings.simplefilter('always') else: logging_level = logging.INFO formatter: logging.Formatter if (not sys.stdin.isatty()): ...
def test_access_token(initialized_db): user = model.user.get_user('devtable') token = create_token(user, 'Some token') assert (token.last_accessed is None) token = access_valid_token(get_full_token_string(token)) assert (token.last_accessed is not None) revoke_token(token) assert (access_val...
class TagListWrapper(abc.Mapping): def __init__(self, taglist, merge=False): self._list = taglist self._merge = merge def __len__(self): return self._list.n_tags() def __iter__(self): for i in range(len(self)): (yield self._list.nth_tag_name(i)) def __getitem_...
class TestPetPhotoEndpoint(BaseTestPetstore): def test_get_valid(self, client, data_gif): client.cookies.set('user', '1') headers = {'Authorization': 'Basic testuser', 'Api-Key': self.api_key_encoded} response = client.get('/v1/pets/1/photo', headers=headers) assert (response.content...
def _stringify_obj(obj: Any) -> str: if ((inspect.isbuiltin(obj) and (obj.__self__ is not None)) or isinstance(obj, types.MethodType)): return f'{_stringify_obj(obj.__self__)}.{obj.__name__}' elif (hasattr(obj, 'decorator') and hasattr(obj, 'instance')): if hasattr(obj.instance, '__name__'): ...
class AMPTrainer(SimpleTrainer): def run_step(self): assert self.model.training, '[AMPTrainer] model was changed to eval mode!' assert torch.cuda.is_available(), '[AMPTrainer] CUDA is required for AMP training!' start = time.perf_counter() data = next(self._data_loader_iter) ...
def find_all_conv_bn_with_activation(model: torch.nn.Module, input_shape: Tuple) -> Dict: device = utils.get_device(model) inp_tensor_list = utils.create_rand_tensors_given_shapes(input_shape, device) connected_graph = ConnectedGraph(model, inp_tensor_list) return find_all_conv_bn_with_activation_in_gra...
def main(): args = parse_args() cfg = Config.fromfile(args.config) if (args.cfg_options is not None): cfg.merge_from_dict(args.cfg_options) if cfg.get('cudnn_benchmark', False): torch.backends.cudnn.benchmark = True cfg.model.pretrained = None cfg.data.test.test_mode = True i...
class DeformNet(nn.Module): def __init__(self, n_cat=6, nv_prior=1024): super(DeformNet, self).__init__() self.n_cat = n_cat self.instance_geometry = nn.Sequential(nn.Conv1d(3, 64, 1), nn.ReLU(), nn.Conv1d(64, 64, 1), nn.ReLU(), nn.Conv1d(64, 64, 1), nn.ReLU()) self.instance_global =...
def test_switch_step_calls_cof(): with pytest.raises(Call) as err: run_step(Context({'switch': [{'case': False, 'call': 'sg1'}, {'case': True, 'call': 'sg2'}]})) cof = err.value assert isinstance(cof, Call) assert (cof.groups == ['sg2']) assert (cof.success_group is None) assert (cof.fai...
class Iterator(): def __init__(self, data): self.data = data self.idx = 0 def hasNext(self) -> bool: return (len(self.data) > self.idx) def next(self): if (len(self.data) > self.idx): temp = self.data[self.idx] self.idx += 1 return temp ...
class Recorder(): def __init__(self, metrics): self.metrics = metrics self.metric2sum = {} self.n_records = 0 self.reset() def reset(self): self.n_records = 0 for metric in self.metrics: self.metric2sum[metric] = 0.0 def record(self, n_records, val...
class TTrueAudioFile(TestCase): def setUp(self): self.song = TrueAudioFile(get_data_path('silence-44-s.tta')) def test_length(self): assert (self.song('~#length') == pytest.approx(3.684, abs=0.001)) def test_audio_props(self): assert (self.song('~#samplerate') == 44100) def test_...
def load_pretrained_weights(p, model): print('Loading pre-trained weights from {}'.format(p['pretraining'])) state_dict = torch.load(p['pretraining'], map_location='cpu')['model'] new_state = {} for (k, v) in state_dict.items(): if k.startswith('module.model_q.'): new_state[k.rsplit(...
class DescribeCharacterStyle(): def it_knows_which_style_it_is_based_on(self, base_get_fixture): (style, StyleFactory_, StyleFactory_calls, base_style_) = base_get_fixture base_style = style.base_style assert (StyleFactory_.call_args_list == StyleFactory_calls) assert (base_style == ...
class TestOptimizer(unittest.TestCase): def test_init(self): params = [torch.nn.Parameter(torch.randn(2, 3, 4))] try: optimizer = Optimizer(torch.optim.Adam(params)) except: self.fail('__init__ failed.') self.assertEquals(optimizer.max_grad_norm, 0) def te...
class InverseEvalresp(FrequencyResponse): respfile = String.T() nslc_id = Tuple.T(4, String.T()) target = String.T(default='dis') instant = Float.T() def __init__(self, respfile, trace, target='dis', **kwargs): FrequencyResponse.__init__(self, respfile=respfile, nslc_id=trace.nslc_id, instan...
def compute_grid_bound(model: MPMModelStruct, state: MPMStateStruct): tid = wp.tid() x = state.particle_q[tid] fx = ((x[0] - (model.dx * 4.0)) * model.inv_dx) fy = ((x[1] - (model.dx * 4.0)) * model.inv_dx) fz = ((x[2] - (model.dx * 4.0)) * model.inv_dx) ix = int(wp.floor(fx)) iy = int(wp.fl...
class ModelArguments(): model_name_or_path: str = field(default='google/vit-base-patch16-224-in21k', metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'}) model_type: Optional[str] = field(default=None, metadata={'help': ('If training from scratch, pass a model type from ...
class PythonConsole(Gtk.ScrolledWindow): def __init__(self, namespace=None, destroy_cb=None): Gtk.ScrolledWindow.__init__(self) self.destroy_cb = destroy_cb self.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC) self.set_shadow_type(Gtk.ShadowType.NONE) self.view = G...
class FigurePlot(): def __init__(self, x_axis_label, y_axis_label, title): self.x_axis_label = x_axis_label self.y_axis_label = y_axis_label self.title = title self.source = ColumnDataSource(data=dict(x=[], y=[])) self.title_object = Title() self.title_object.text = s...
class TestActivate(): expected_msg = "Humanize cannot determinate the default location of the 'locale' folder. You need to pass the path explicitly." def test_default_locale_path_null__file__(self) -> None: i18n = importlib.import_module('humanize.i18n') i18n.__file__ = None with pytest....
class FileFolderNavigator(GridBox): _attribute_decorator('WidgetSpecific', 'Defines wether it is possible to select multiple items.', bool, {}) def multiple_selection(self): return self._multiple_selection _selection.setter def multiple_selection(self, value): self._multiple_selection = ...
def test_export_data_access_groups(simple_project): records = simple_project.export_records(export_data_access_groups=True) for record in records: assert ('redcap_data_access_group' in record) records = simple_project.export_records() for record in records: assert (not ('redcap_data_acce...
class Config(object): def __init__(self, dataset, embedding): self.model_name = 'TextRCNN' self.train_path = (dataset + '/data/train.txt') self.dev_path = (dataset + '/data/dev.txt') self.test_path = (dataset + '/data/test.txt') self.class_list = [x.strip() for x in open((dat...
class AutoModelForTokenClassification(): def __init__(self): raise EnvironmentError('AutoModelForTokenClassification is designed to be instantiated using the `AutoModelForTokenClassification.from_pretrained(pretrained_model_name_or_path)` or `AutoModelForTokenClassification.from_config(config)` methods.') ...
def read_tokenizer(lang_id, g2p_model='latest', device=None, use_lexicon=True): lang_id = normalize_lang_id(lang_id) if (lang_id in lang2tokenizer): return lang2tokenizer[lang_id](lang_id=lang_id, g2p_model=g2p_model, device=device, use_lexicon=use_lexicon) else: return read_g2p_tokenizer(la...
class BaseFragmentBlender(): passes = [] def __init__(self): self.device = get_shared().device self.size = (0, 0) self._combine_pass_pipeline = None self._combine_pass_bind_group = None self._texture_info = {} usg = wgpu.TextureUsage self._texture_info['co...
def preprocess(data_dir, hparams: Hyperparameter, temp_dir='temp', device='cuda:0', max_workers=4): data_dir = os.path.abspath(data_dir) temp_dir = os.path.abspath(temp_dir) mel_dir = os.path.join(temp_dir, 'mels') os.makedirs(mel_dir, exist_ok=True) mel_config = {'sampling_rate': hparams.sample_rat...
class OptimizableInterface(with_metaclass(ABCMeta, object)): def problem_size(self): pass def get_current_point(self): pass def set_current_point(self, current_point): pass current_point = abstractproperty(get_current_point, set_current_point) def compute_objective_function(s...
def shareable_word_hash(hash_bytes: bytes, all_games: list[RandovaniaGame]): rng = Random(sum(((hash_byte * ((2 ** 8) ** i)) for (i, hash_byte) in enumerate(hash_bytes)))) games_left = [] selected_words = [] for _ in range(3): if (not games_left): games_left = list(all_games) ...
.parametrize('text', ('`test identifier`', 'simple_identifier', "query''", '_internal_value', 'get_pubkeys&signatures', 'dict::udict_set_builder', '2+2=2*2', '-alsovalidname', '{hehehe}')) def test_func_identifier(lexer_func, text): assert (list(lexer_func.get_tokens(text))[0] == (Name.Variable, text))
def convert_example_to_feature(data, args): (sums, contexts) = ([], []) for sample in data: if (args.sum_mode == 'final'): sum = sample['FinalSumm'] elif (args.sum_mode == 'user'): sum = sample['UserSumm'] elif (args.sum_mode == 'agent'): sum = sample[...
def _get_plugin_config(): if config.has_option('plugins', 'trayicon_window_hide'): value = config.getboolean('plugins', 'trayicon_window_hide') config.remove_option('plugins', 'trayicon_window_hide') config.set('plugins', 'icon_window_hide', value) pconfig = PluginConfig('icon') pcon...
def ddp(script: str, nnodes: int=1, name: str='ddp_app', role: str='worker', env: Optional[Dict[(str, str)]]=None, *script_args: str) -> specs.AppDef: app_env: Dict[(str, str)] = {} if env: app_env.update(env) entrypoint = os.path.join(specs.macros.img_root, script) ddp_role = specs.Role(name=ro...
def _configure_stderr_logging(*, verbosity=None, verbosity_shortcuts=None): global console_stderr_handler if (console_stderr_handler is not None): _logger.warning('stderr handler already exists') return console_stderr_handler = logging.StreamHandler(sys.stderr) console_stderr_handler.set...
def train(): tf.reset_default_graph() policy_nn = SupervisedPolicy() f = open(relationPath) train_data = f.readlines() f.close() num_samples = len(train_data) saver = tf.train.Saver() with tf.Session() as sess: sess.run(tf.global_variables_initializer()) if (num_samples >...
def test_main_failure(caplog: pytest.LogCaptureFixture, tmp_path: Path) -> None: requirements_file = (tmp_path / 'requirements.txt') requirements_file.touch() source_dir = (tmp_path / 'source') source_dir.mkdir() source_file = (source_dir / 'source.py') source_file.write_text('import pytest') ...
def check_match(condition: models.Match, value: Any) -> bool: if isinstance(condition, models.MatchValue): return (value == condition.value) if isinstance(condition, models.MatchText): return ((value is not None) and (condition.text in value)) if isinstance(condition, models.MatchAny): ...
class LatentBrownianBridgeModel(BrownianBridgeModel): def __init__(self, model_config): super().__init__(model_config) self.vqgan = VQModel(**vars(model_config.VQGAN.params)).eval() self.vqgan.train = disabled_train for param in self.vqgan.parameters(): param.requires_gra...
def test_dataid_elements_picklable(): import pickle from satpy.tests.utils import make_dataid did = make_dataid(name='hi', wavelength=(10, 11, 12), resolution=1000, calibration='radiance') for value in did.values(): pickled_value = pickle.loads(pickle.dumps(value)) assert (value == pickl...
class Incidents(Cog): message_link_embeds_cache = RedisCache() def __init__(self, bot: Bot) -> None: self.bot = bot self.incidents_webhook = None scheduling.create_task(self.fetch_webhook()) self.event_lock = asyncio.Lock() self.crawl_task = scheduling.create_task(self.cr...
class SubQuery(): def __init__(self, subquery: Any, subquery_raw: str, alias: Optional[str]): self.query = subquery self.query_raw = subquery_raw self.alias = (escape_identifier_name(alias) if (alias is not None) else f'subquery_{hash(self)}') def __str__(self): return self.alias...
def run(*cmd: str, capture: bool=False, raise_on_err: bool=True, check_code: t.Callable[([int], bool)]=(lambda c: (c == 0)), **popen_kwargs: t.Any) -> RunReturn: stdout = (subprocess.PIPE if capture else None) stderr = (subprocess.PIPE if capture else None) proc = subprocess.Popen(cmd, stdout=stdout, stderr...
class ThreadLocal(Generic[_StateType]): def __init__(self, default: Callable[([], _StateType)]): self._default = default self._state: WeakKeyDictionary[(Thread, _StateType)] = WeakKeyDictionary() def get(self) -> _StateType: thread = current_thread() if (thread not in self._state...
_edge_encoder('VOCEdge') class VOCEdgeEncoder(torch.nn.Module): def __init__(self, emb_dim): super().__init__() VOC_edge_input_dim = (2 if (cfg.dataset.name == 'edge_wt_region_boundary') else 1) self.encoder = torch.nn.Linear(VOC_edge_input_dim, emb_dim) def forward(self, batch): ...
def createProgram(shaderList): program = glCreateProgram() for shader in shaderList: glAttachShader(program, shader) glLinkProgram(program) status = glGetProgramiv(program, GL_LINK_STATUS) if (status == GL_FALSE): strInfoLog = glGetProgramInfoLog(program) print(('Linker failu...
def process_mnemonics(X_protoset_cumuls, Y_protoset_cumuls, mnemonics_raw, mnemonics_label, order_list, nb_cl_fg, nb_cl, iteration, start_iter): mnemonics = mnemonics_raw[0] mnemonics_array_new = np.zeros((len(mnemonics), len(mnemonics[0]), 32, 32, 3)) mnemonics_list = [] mnemonics_label_list = [] f...
class FileHandler(Configurable): path = Option(filesystem_path, required=True, positional=True, __doc__='Path to use within the provided filesystem.') eol = Option(str, default='\n', __doc__='Character to use as line separator.') mode = Option(str, __doc__='What mode to use for open() call.') encoding =...
def get_all_terminals(tree, is_l_value, insideQuery): if (not isinstance(tree, Node)): return [tree] if isPathExpression(tree): return get_path_expression_terminals(tree, insideQuery) elif isTryExceptExpression(tree): return get_try_except_expression_terminals(tree, insideQuery) ...
class TestContingency(TestCase): def test_chi2_independence(self): np.random.seed(42) (mean, cov) = ([0.5, 0.5], [(1, 0.6), (0.6, 1)]) (x, y) = np.random.multivariate_normal(mean, cov, 30).T data = pd.DataFrame({'x': x, 'y': y}) mask_class_1 = (data > 0.5) data[mask_c...
def test_voltage(): with expected_protocol(Keithley2200, [(b'INST:SEL CH1;VOLT 1.456', None), (b'INST:SEL CH1;VOLT?', 1.456), (b'INST:SEL CH1;MEAS:VOLT?', 1.456), (b'INST:SEL CH3;VOLT 1.456', None)]) as instr: instr.ch_1.voltage_setpoint = 1.456 assert (instr.ch_1.voltage_setpoint == 1.456) ...
def test_write_calibration_data(): invalid_cal_data = VALID_CAL_DATA.copy() invalid_cal_data[1] = 1 invalid_cal_write_xfers = convert_cal_data_to_cal_write_xfers(invalid_cal_data) with expected_protocol(HP3478A, invalid_cal_write_xfers) as instr: instr.write_calibration_data(invalid_cal_data, ve...
class MVArray(np.ndarray): def __new__(cls, input_array): (input_shape, layout, dtype) = _interrogate_nested_mvs(input_array) obj = np.empty(input_shape, dtype=object) for index in np.ndindex(input_shape): obj[index] = _index_nested_iterable(input_array, index) self = obj...
class BIP32_KeyStore(Xpub, Deterministic_KeyStore): type = 'bip32' def __init__(self, d): Xpub.__init__(self, derivation_prefix=d.get('derivation'), root_fingerprint=d.get('root_fingerprint')) Deterministic_KeyStore.__init__(self, d) self.xpub = d.get('xpub') self.xprv = d.get('x...
class SpecParser(Parser[ConfigNamespace]): def __init__(self, spec: ConfigSpec): self.spec = spec def parse(self, key_path: str, raw_config: RawConfig) -> ConfigNamespace: parsed = ConfigNamespace() for (key, spec) in self.spec.items(): assert ('.' not in key), 'dots are not ...
def load_collection_(path, retain_titles): with open(path) as f: collection = [] for line in file_tqdm(f): (_, passage, title) = line.strip().split('\t') if retain_titles: passage = ((title + ' | ') + passage) collection.append(passage) return ...
def test_marker_prefix_does_not_interfere_with_order_marks(test_path): test_path.makepyfile(test_marker='\n import pytest\n\n .order(3)\n def test_a():\n pass\n\n .order(1)\n def test_b():\n pass\n\n .order(2)\n ...
class GenTensorVariable(TensorVariable): def __init__(self, op, type, name=None): super().__init__(type=type, owner=None, name=name) self.op = op def set_gen(self, gen): self.op.set_gen(gen) def set_default(self, value): self.op.set_default(value) def clone(self): ...
_request_params(*docs._get_observations, docs._pagination) def get_observation_species_counts(**params) -> JsonResponse: if (params.get('page') == 'all'): return paginate_all(get, f'{API_V1}/observations/species_counts', **params) else: return get(f'{API_V1}/observations/species_counts', **param...
def pytest_collection_modifyitems(items: List[nodes.Item], config: Config) -> None: deselect_prefixes = tuple((config.getoption('deselect') or [])) if (not deselect_prefixes): return remaining = [] deselected = [] for colitem in items: if colitem.nodeid.startswith(deselect_prefixes):...
def main(args: Optional[Sequence[str]]=None) -> None: parser = ArgumentParser() parser.add_argument('file', nargs='+', help='Validate specified file(s).') parser.add_argument('--errors', choices=('best-match', 'all'), default='best-match', help='Control error reporting. Defaults to "best-match", use "all" t...
('/v1/repository/<apirepopath:repository>/trigger/<trigger_uuid>/activate') _param('repository', 'The full path of the repository. e.g. namespace/name') _param('trigger_uuid', 'The UUID of the build trigger') class BuildTriggerActivate(RepositoryParamResource): schemas = {'BuildTriggerActivateRequest': {'type': 'ob...
def prep_utt2label(utt2labelid_path, label_id_map_path, utt2label_paths): print((('generating utt2labelid(%s) and label_id_map(%s)' % (utt2labelid_path, label_id_map_path)) + (' from utt2labels(%s)' % utt2label_paths))) utt_list = [] label_list = [] for utt2label_path in utt2label_paths: with op...
class InputFeatures(object): def __init__(self, input_ids_spc, input_mask, segment_ids, label_id, polarities=None, valid_ids=None, label_mask=None): self.input_ids_spc = input_ids_spc self.input_mask = input_mask self.segment_ids = segment_ids self.label_id = label_id self.va...
class TestRegister(TestScript): handlers = RAPIDSMS_HANDLERS def testRegister(self): self.assertInteraction('\n > register as someuser\n < Thank you for registering, as someuser!\n ') def testLang(self): self.assertInteraction(('\n > lang english\n ...
class ModelSpec_Modified(object): def __init__(self, matrix, ops, data_format='channels_last'): if (not isinstance(matrix, np.ndarray)): matrix = np.array(matrix) shape = np.shape(matrix) if ((len(shape) != 2) or (shape[0] != shape[1])): raise ValueError('matrix must ...
def TVRegDiffPoint(u, dx, index=None): u = u.flatten() n = len(u) if (index == None): index = int(((n - 1) / 2)) ux = TVRegDiff(u, 1, 0.1, dx=dx, plotflag=False, diffkernel='sq') uxx = TVRegDiff(ux, 1, 0.1, dx=dx, plotflag=False, diffkernel='sq') return (ux[index], uxx[index])
def register_onchain_secret_endstate(end_state: NettingChannelEndState, secret: Secret, secrethash: SecretHash, secret_reveal_block_number: BlockNumber, delete_lock: bool=True) -> None: pending_lock: Optional[HashTimeLockState] = None if is_lock_locked(end_state, secrethash): pending_lock = end_state.se...
.supported(only_if=(lambda backend: backend.cipher_supported(algorithms._CAST5Internal((b'\x00' * 16)), modes.ECB())), skip_message='Does not support CAST5 ECB') class TestCAST5ModeECB(): test_ecb = generate_encrypt_test(load_nist_vectors, os.path.join('ciphers', 'CAST5'), ['cast5-ecb.txt'], (lambda key, **kwargs: ...
def test_smartdevice_examples(mocker): p = asyncio.run(get_device_for_file('HS110(EU)_1.0_1.2.5.json', 'IOT')) mocker.patch('kasa.smartdevice.SmartDevice', return_value=p) mocker.patch('kasa.smartdevice.SmartDevice.update') res = xdoctest.doctest_module('kasa.smartdevice', 'all') assert (not res['fa...
class ChatAction(StringEnum): __slots__ = () CHOOSE_STICKER = 'choose_sticker' FIND_LOCATION = 'find_location' RECORD_VOICE = 'record_voice' RECORD_VIDEO = 'record_video' RECORD_VIDEO_NOTE = 'record_video_note' TYPING = 'typing' UPLOAD_VOICE = 'upload_voice' UPLOAD_DOCUMENT = 'upload...
def dependency_pyserial(func): (func) def wrapper(*args, **kwargs): if (not is_usable()): raise RuntimeError('Printing with Serial requires the pyserial library tobe installed. Please refer to the documentation onwhat to install and install the dependencies for pyserial.') return fun...
class LEDTokenizer(BartTokenizer): pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def _pad(self, encoded_inputs: Union[(Dict[(str, EncodedInput)], BatchEncoding)], max_length: Optional[int]=None, padding_strategy: PaddingStrategy=Paddin...
class Discriminator(nn.Module): def __init__(self, args): super(Discriminator, self).__init__() in_channels = args.n_colors out_channels = 64 depth = 7 def _block(_in_channels, _out_channels, stride=1): return nn.Sequential(nn.Conv2d(_in_channels, _out_channels, 3...
class AdaptedMethod(): def __init__(self, declared_method, arg_names=[], kwarg_name_map={}): self.declared_method = declared_method self.arg_names = arg_names self.kwarg_name_map = kwarg_name_map self.kwarg_name_map_reversed = dict([(sent_name, adapted_to_name) for (adapted_to_name, ...
class Organization(models.Model): name = models.CharField(max_length=200, verbose_name=gettext_lazy('Name'), unique=True, null=False, blank=False) default_template = models.ForeignKey('PetitionTemplate', blank=True, null=True, related_name='+', verbose_name=gettext_lazy('Default petition template'), to_field='i...
class GetChatHistory(): async def get_chat_history(self: 'pyrogram.Client', chat_id: Union[(int, str)], limit: int=0, offset: int=0, offset_id: int=0, offset_date: datetime=utils.zero_datetime()) -> Optional[AsyncGenerator[('types.Message', None)]]: current = 0 total = (limit or ((1 << 31) - 1)) ...
class HSTISR(IntEnum): DCONNI = (1 << 0) DDISCI = (1 << 1) RSTI = (1 << 2) RSMEDI = (1 << 3) RXRSMI = (1 << 4) HSOFI = (1 << 5) HWUPI = (1 << 6) PEP_0 = (1 << 8) PEP_1 = (1 << 9) PEP_2 = (1 << 10) PEP_3 = (1 << 11) PEP_4 = (1 << 12) PEP_5 = (1 << 13) PEP_6 = (1 <<...
class ReportType(str, Enum): INVENTORY = '_GET_FLAT_FILE_OPEN_LISTINGS_DATA_' ALL_LISTINGS = '_GET_MERCHANT_LISTINGS_ALL_DATA_' ACTIVE_LISTINGS = '_GET_MERCHANT_LISTINGS_DATA_' INACTIVE_LISTINGS = '_GET_MERCHANT_LISTINGS_INACTIVE_DATA_' OPEN_LISTINGS = '_GET_MERCHANT_LISTINGS_DATA_BACK_COMPAT_' ...
class Import(ImportBase): __slots__ = ('ids',) __match_args__ = ('ids',) ids: list[tuple[(str, (str | None))]] def __init__(self, ids: list[tuple[(str, (str | None))]]) -> None: super().__init__() self.ids = ids def accept(self, visitor: StatementVisitor[T]) -> T: return visi...
class BaseResponseUnmarshaller(BaseResponseValidator, BaseUnmarshaller): def _unmarshal(self, response: Response, operation: SchemaPath) -> ResponseUnmarshalResult: try: operation_response = self._find_operation_response(response.status_code, operation) except ResponseFinderError as exc:...
def test_logq_globals(three_var_approx): if (not three_var_approx.has_logq): pytest.skip(('%s does not implement logq' % three_var_approx)) approx = three_var_approx (logq, symbolic_logq) = approx.set_size_and_deterministic([approx.logq, approx.symbolic_logq], 1, 0) e = logq.eval() es = symb...
def test_stringify_file_id(): file_id = 'BQACAgIAAx0CAAGgr9AAAgmPX7b4UxbjNoFEO_L0I4s6wrXNJA8AAgQAA4GkuUm9FFvIaOhXWR4E' string = "{'major': 4, 'minor': 30, 'file_type': <FileType.DOCUMENT: 5>, 'dc_id': 2, 'file_reference': b'\\x02\\x00\\xa0\\xaf\\xd0\\x00\\x00\\t\\x8f_\\xb6\\xf8S\\x16\\xe36\\x81D;\\xf2\\xf4#\\x8...
class SeqInfo(): def __init__(self, seq_path): self.info = self.get_seq_info_data(seq_path) def get_obj_name(self, convert=False): if convert: if ('chair' in self.info['cat']): return 'chair' if ('ball' in self.info['cat']): return 'sports ...
class RegistrationPendingForm(Form): def __init__(self, view): super().__init__(view, 'register_pending') if self.exception: self.add_child(Alert(view, self.exception.as_user_message(), 'warning')) actions = self.add_child(ActionButtonGroup(view, legend_text=_('Re-send registrati...
class ResNeXt_with_features(nn.Module): def __init__(self, block, num_blocks, cardinality, bottleneck_width, strides): super().__init__() self.cardinality = cardinality self.bottleneck_width = bottleneck_width self.in_channels = 64 self.conv1 = nn.Conv2d(3, 64, kernel_size=1,...
class GetCategoriesTests(MockPagesTestCase): def test_get_root_categories(self): result = utils.get_categories(BASE_PATH) info = PARSED_CATEGORY_INFO categories = {'category': info, 'tmp': info, 'not_a_page.md': info} self.assertEqual(result, categories) def test_get_categories_w...
def _conversion_checks(item, keys, box_config, check_only=False, pre_check=False): if (box_config['box_duplicates'] != 'ignore'): if pre_check: keys = (list(keys) + [item]) key_list = [(k, _safe_attr(k, camel_killer=box_config['camel_killer_box'], replacement_char=box_config['box_safe_pr...
def _del_unclaimed_lock(end_state: NettingChannelEndState, secrethash: SecretHash) -> None: if (secrethash in end_state.secrethashes_to_lockedlocks): del end_state.secrethashes_to_lockedlocks[secrethash] if (secrethash in end_state.secrethashes_to_unlockedlocks): del end_state.secrethashes_to_un...
def upgrade(op, tables, tester): op.create_table('quotaregistrysize', sa.Column('id', sa.Integer(), nullable=False), sa.Column('size_bytes', sa.BigInteger(), nullable=False, server_default='0'), sa.Column('running', sa.Boolean(), nullable=False, server_default=sa.sql.expression.false()), sa.Column('queued', sa.Bool...
def completer_obj(qtbot, status_command_stub, config_stub, monkeypatch, stubs, completion_widget_stub): monkeypatch.setattr(completer, 'QTimer', stubs.InstaTimer) config_stub.val.completion.show = 'auto' return completer.Completer(cmd=status_command_stub, win_id=0, parent=completion_widget_stub)
def crf(train_image, final_probabilities, train_annotation, number_class): for index_image in xrange(1): image = train_image softmax = final_probabilities[0].squeeze() softmax = softmax.transpose((2, 0, 1)) unary = unary_from_softmax(softmax) unary = np.ascontiguousarray(unar...
def test_guard_against_oversized_packets(): zc = Zeroconf(interfaces=['127.0.0.1']) generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) for i in range(5000): generated.add_answer_at_time(r.DNSText('packet{i}.local.', const._TYPE_TXT, (const._CLASS_IN | const._CLASS_UNIQUE), 500, b'path=/~paulsm/'), ...
def parse_args_and_arch(parser: argparse.ArgumentParser, input_args: List[str]=None, parse_known: bool=False, suppress_defaults: bool=False, modify_parser: Optional[Callable[([argparse.ArgumentParser], None)]]=None): if suppress_defaults: args = parse_args_and_arch(parser, input_args=input_args, parse_known...