code
stringlengths
281
23.7M
def _parameters_conversion(converter: callable, argument: str, parameter) -> typing.Any: if (converter is bool): return _convert_to_bool(argument) try: return converter(argument) except Exception as exc: try: name = converter.__name__ except AttributeError: ...
def make_output_filtering_dataframe(spark_context, spark_session): data = [{'id': 1, 'ts': 1, 'feature1': 0, 'feature2': None, 'feature3': 1}, {'id': 1, 'ts': 2, 'feature1': 0, 'feature2': 1, 'feature3': 1}, {'id': 1, 'ts': 3, 'feature1': None, 'feature2': None, 'feature3': None}, {'id': 1, 'ts': 4, 'feature1': 0, ...
def test_copy_method(): m.ExampleMandA.add2c = m.ExampleMandA.add2 m.ExampleMandA.add2d = m.ExampleMandA.add2b a = m.ExampleMandA(123) assert (a.value == 123) a.add2(m.ExampleMandA((- 100))) assert (a.value == 23) a.add2b(m.ExampleMandA(20)) assert (a.value == 43) a.add2c(m.ExampleMa...
def _pad_version(left: List[str], right: List[str]) -> Tuple[(List[str], List[str])]: (left_split, right_split) = ([], []) left_split.append(list(itertools.takewhile((lambda x: x.isdigit()), left))) right_split.append(list(itertools.takewhile((lambda x: x.isdigit()), right))) left_split.append(left[len(...
def create_tf_mixup_batch_augmentation(heads: List[TrainerHeadInterface], mixup_alpha: float) -> Callable: def tf_mixup_batch_augmentation(batch_features, batch_targets): batch_features_shape = tf.shape(batch_features) batch_size = batch_features_shape[0] beta = tfp.distributions.Beta(mixup_...
def test_dynamic_compile_shows_nicely(): import importlib.util import sys src = 'def foo():\n assert 1 == 0\n' name = 'abc-123' spec = importlib.util.spec_from_loader(name, loader=None) module = importlib.util.module_from_spec(spec) code = compile(src, name, 'exec') exec(code, module.__d...
def evaluate(args, model, tokenizer, prefix=''): (dataset, examples, features) = load_and_cache_examples(args, tokenizer, evaluate=True, output_examples=True) if ((not os.path.exists(args.output_dir)) and (args.local_rank in [(- 1), 0])): os.makedirs(args.output_dir) args.eval_batch_size = (args.per...
class DmRaid_TestCase(unittest.TestCase): def runTest(self): data1 = FC6_DmRaidData() data2 = FC6_DmRaidData() self.assertEqual(data1, data2) data1.name = '' data2.name = 'test' self.assertNotEqual(data1, data2) self.assertNotEqual(data2, data1) data1....
class Calculator(QWidget): NumDigitButtons = 10 def __init__(self, parent=None): super(Calculator, self).__init__(parent) self.pendingAdditiveOperator = '' self.pendingMultiplicativeOperator = '' self.sumInMemory = 0.0 self.sumSoFar = 0.0 self.factorSoFar = 0.0 ...
class TestLabeledPriceWithoutRequest(TestLabeledPriceBase): def test_slot_behaviour(self, labeled_price): inst = labeled_price for attr in inst.__slots__: assert (getattr(inst, attr, 'err') != 'err'), f"got extra slot '{attr}'" assert (len(mro_slots(inst)) == len(set(mro_slots(in...
class SampledResponse(FrequencyResponse): frequencies = Array.T(shape=(None,), dtype=float, serialize_as='list') values = Array.T(shape=(None,), dtype=complex, serialize_as='list') left = Complex.T(optional=True) right = Complex.T(optional=True) def __init__(self, frequencies, values, left=None, rig...
def ytest_base(unit, related_prj_dir, related_prj_name, args): keywords = {'DEPENDS': (- 1), 'DATA': (- 1)} (flat_args, spec_args) = _common.sort_by_keywords(keywords, args) unit.set(['TEST-NAME', os.path.basename(flat_args[0])]) unit.set(['SCRIPT-REL-PATH', flat_args[1]]) unit.set(['SOURCE-FOLDER-P...
class AppBaseView(social_app.BaseViewClass): def render_home(self, **extra): context = common_context(web.config[setting_name('AUTHENTICATION_BACKENDS')], load_strategy(), user=self.get_current_user(), plus_id=web.config.get(setting_name('SOCIAL_AUTH_GOOGLE_PLUS_KEY')), **extra) return render.home(*...
_tf class TFXLNetModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = ((TFXLNetModel, TFXLNetLMHeadModel, TFXLNetForSequenceClassification, TFXLNetForTokenClassification, TFXLNetForQuestionAnsweringSimple, TFXLNetForMultipleChoice) if is_tf_available() else ()) all_generati...
class InlineQueryResultDocument(InlineQueryResult): __slots__ = ('reply_markup', 'caption_entities', 'document_url', 'thumbnail_width', 'thumbnail_height', 'caption', 'title', 'description', 'parse_mode', 'mime_type', 'thumbnail_url', 'input_message_content') def __init__(self, id: str, document_url: str, title...
def create_embedding(caption_file: str, vocab_file: str, embed_size: int, output: str, **fasttext_kwargs): caption_df = pd.read_json(caption_file) caption_df['tokens'] = caption_df['tokens'].apply((lambda x: ((['<start>'] + [token for token in x]) + ['<end>']))) sentences = list(caption_df['tokens'].values)...
def get_constant_counts_from_file(infile, has_header, include_count): constant_counts = {} line_iter = iter(infile) lineno = 1 seen = {} filename = infile.name def oopsie(msg): die(f'Unable to process constants file: {msg}, {filename!r} line {lineno}') if has_header: try: ...
def pad_shape(shape, must_be_divisible_by): if (not isinstance(must_be_divisible_by, (tuple, list, np.ndarray))): must_be_divisible_by = ([must_be_divisible_by] * len(shape)) else: assert (len(must_be_divisible_by) == len(shape)) new_shp = [((shape[i] + must_be_divisible_by[i]) - (shape[i] %...
class ImageStorage(): def __init__(self, losses: Iterable[Loss]) -> None: self.target_images_and_guides: Dict[(ComparisonLoss, Tuple[(torch.Tensor, Optional[torch.Tensor])])] = {} self.input_guides: Dict[(Loss, torch.Tensor)] = {} for loss in losses: if isinstance(loss, Compariso...
(msg=DATAREADER_DEPRECATION_WARNING) def default_returns_func(symbol, start=None, end=None): if (start is None): start = '1/1/1970' if (end is None): end = _1_bday_ago() start = get_utc_timestamp(start) end = get_utc_timestamp(end) if (symbol == 'SPY'): filepath = data_path('...
def get_head(head_name, in_index, idx_to_planes, tasks, task_channel_mapping, atrc_genotype_path=None): in_index = [int(i) for i in in_index.split(',')] in_index = (in_index[0] if (len(in_index) == 1) else in_index) if (head_name == 'DemtHead'): from .heads.demt_head import DemtHead partial_...
class BaseImageDataset(torch.utils.data.Dataset): def __init__(self, name, root, image_loader=jpeg4py_loader): self.name = name self.root = root self.image_loader = image_loader self.image_list = [] self.class_list = [] def __len__(self): return self.get_num_image...
def build_model_base(images, model_name, training, override_params=None): assert isinstance(images, tf.Tensor) (blocks_args, global_params) = get_model_params(model_name, override_params) with tf.variable_scope(model_name): model = efficientnet_model.Model(blocks_args, global_params) feature...
_families def test_root_testsuites_tag(pytester: Pytester, run_and_parse: RunAndParse, xunit_family: str) -> None: pytester.makepyfile('\n def test_x():\n pass\n ') (_, dom) = run_and_parse(family=xunit_family) root = dom.get_unique_child assert (root.tag == 'testsuites') suite_...
(order=True) class TransactionChannelDeposit(State): participant_address: Address contract_balance: TokenAmount deposit_block_number: BlockNumber def __post_init__(self) -> None: typecheck(self.participant_address, T_Address) typecheck(self.contract_balance, T_TokenAmount) typech...
def _create_reader_for_fake_data(observation_type: str, fake_dataset: xr.Dataset, filename_info: Optional[dict]=None): from satpy.readers.abi_l2_nc import NC_ABI_L2 if (filename_info is None): filename_info = {'platform_shortname': 'G16', 'scene_abbr': 'C', 'scan_mode': 'M3'} reader_args = ('filenam...
def process_korQuAD(corpus_fname, output_fname): with open(corpus_fname) as f1, open(output_fname, 'w', encoding='utf-8') as f2: dataset_json = json.load(f1) dataset = dataset_json['data'] for article in dataset: w_lines = [] for paragraph in article['paragraphs']: ...
.skip('KAK instability') def test_zzswap_as_syc_2(): (q1, q2) = cirq.LineQubit.range(2) zzs = ZZSwap(zz_exponent=0.123) circuit = zzswap_as_syc(zzs.theta, q1, q2) assert (str(circuit) == '0: PhX(0.145)^(0)Z^-0.2SYCPhX(0.214)^0.576Z^-0.131SYCSYCPhX(-0.0833)^0.576Z^-0.548\n ...
def load_teapot_batch(batch_size=4, target_num=2): (vertices, faces) = nr.load_obj(os.path.join(data_dir, 'teapot.obj')) textures = torch.ones((faces.shape[0], 4, 4, 4, 3), dtype=torch.float32) (vertices, faces, textures) = to_minibatch((vertices, faces, textures), batch_size, target_num) return (vertic...
def poly1305(cipher_encrypt, nonce, ciphertext): otk = cipher_encrypt(nonce, bytes(32)) mac_data = ((ciphertext + bytes((((- len(ciphertext)) % 16) + 8))) + len(ciphertext).to_bytes(8, 'little')) (acc, r, s) = (0, (int.from_bytes(otk[:16], 'little') & ), int.from_bytes(otk[16:], 'little')) for i in rang...
class ConnectionTestCase(TestCase): def setUp(self): self.test_table_name = 'Thread' self.region = 'us-east-1' def test_create_connection(self): conn = TableConnection(self.test_table_name, meta_table=MetaTable(DESCRIBE_TABLE_DATA[TABLE_KEY])) self.assertIsNotNone(conn) def t...
_model('s2t_transformer') class S2TTransformerModel(FairseqEncoderDecoderModel): def __init__(self, encoder, decoder): super().__init__(encoder, decoder) def add_args(parser): parser.add_argument('--conv-kernel-sizes', type=str, metavar='N', help='kernel sizes of Conv1d subsampling layers') ...
class ChannelPadding(nn.Module): def __init__(self, in_planes, out_planes): super(ChannelPadding, self).__init__() self.register_buffer('padding', torch.zeros(((out_planes - in_planes) // 2)).view(1, (- 1), 1, 1)) def forward(self, input): assert (len(input.size()) == 4), 'only support f...
def get_so(atom, a, basis, kmesh): cell = gto.Cell() cell.atom = atom cell.a = a cell.basis = basis cell.space_group_symmetry = True cell.symmorphic = True cell.build() kpts = cell.make_kpts(kmesh, with_gamma_point=True, space_group_symmetry=True) (sos_ks, irrep_ids_ks) = symm_adapte...
class TestCreateGC(EndianTest): def setUp(self): self.req_args_0 = {'attrs': {'function': 7, 'plane_mask': , 'foreground': , 'background': , 'line_width': 61484, 'line_style': 2, 'cap_style': 2, 'join_style': 2, 'fill_style': 0, 'fill_rule': 1, 'tile': , 'stipple': , 'tile_stipple_x_origin': (- 25980), 'til...
class Solution(object): def largestPalindrome(self, n): if (n == 1): return 9 for a in xrange(2, (9 * (10 ** (n - 1)))): hi = ((10 ** n) - a) lo = int(str(hi)[::(- 1)]) if (((a ** 2) - (4 * lo)) < 0): continue if ((((a ** 2)...
class UnboundType(ProperType): __slots__ = ('name', 'args', 'optional', 'empty_tuple_index', 'original_str_expr', 'original_str_fallback') def __init__(self, name: (str | None), args: (Sequence[Type] | None)=None, line: int=(- 1), column: int=(- 1), optional: bool=False, empty_tuple_index: bool=False, original_...
.sphinx(srcdir=srcdir) def test_lazy_tooltips_notlazy(app, status, warning): app.build() path = (app.outdir / '_static/js/hoverxref.js') assert (path.exists() is True) content = open(path).read() chunks = [".each(function () { $(this).removeAttr('title') });"] for chunk in chunks: assert...
.parametrize('username,password', users) .parametrize('project_id', projects) def test_project_export_csvsemicolon(db, client, username, password, project_id): client.login(username=username, password=password) url = reverse('project_export', args=[project_id, 'csvsemicolon']) response = client.get(url) ...
def test_zoom_ratio(): vb = pg.ViewBox(lockAspect=1) vb.setFixedHeight(10) vb.setFixedWidth(10) testRange = pg.QtCore.QRect(0, 0, 10, 10) vb.setRange(testRange, padding=0) expected = [[testRange.left(), testRange.right()], [testRange.top(), testRange.bottom()]] viewRange = vb.getState()['vie...
def validate_subprotocols(subprotocols: Sequence[Subprotocol]) -> None: if (not isinstance(subprotocols, Sequence)): raise TypeError('subprotocols must be a list') if isinstance(subprotocols, str): raise TypeError('subprotocols must be a list, not a str') for subprotocol in subprotocols: ...
class Median(CtrlNode): nodeName = 'MedianFilter' uiTemplate = [('n', 'intSpin', {'min': 1, 'max': 1000000})] def processData(self, data): try: import scipy.ndimage except ImportError: raise Exception('MedianFilter node requires the package scipy.ndimage.') re...
def preprocess_fromnpy_save_to_queue(list_of_images: List[np.ndarray], list_of_segs_from_prev_stage: Union[(List[np.ndarray], None)], list_of_image_properties: List[dict], truncated_ofnames: Union[(List[str], None)], plans_manager: PlansManager, dataset_json: dict, configuration_manager: ConfigurationManager, target_qu...
.parametrize('n,blocks,expected_chunks', [(1, 1, [1]), (2, 1, [2]), (2, 2, ([1] * 2)), (3, 1, [3]), (3, 3, ([1] * 3)), (3, 2, [2, 1]), (7, 2, [4, 3]), (7, 3, [3, 2, 2]), (7, 7, ([1] * 7))]) def test_split_array_chunks__precomputed(n: int, blocks: int, expected_chunks: List[int]) -> None: assert (split_array_chunks(...
def main(_): if (not FLAGS.dataset_dir): raise ValueError('You must supply the dataset directory with --dataset_dir') tf.logging.set_verbosity(tf.logging.INFO) with tf.Graph().as_default(): tf_global_step = slim.get_or_create_global_step() dataset = dataset_factory.get_dataset(FLAGS....
class TestPassedDrivenMilesCompositeMetric(unittest.TestCase): def test_failed_frames(self) -> None: validation_results: Dict[(str, validators.ValidatorOutput)] = {'validator_a': validators.ValidatorOutput(is_valid_scene=False, failed_frames=[15])} metric_results: Dict[(str, torch.Tensor)] = {metric...
def conduct_team_search(username, query, encountered_teams, results): matching_teams = model.team.get_matching_user_teams(query, get_authenticated_user(), limit=5) for team in matching_teams: if (team.id in encountered_teams): continue encountered_teams.add(team.id) results.a...
def segm2json(dataset, results): bbox_json_results = [] segm_json_results = [] for idx in range(len(dataset)): img_id = dataset.img_ids[idx] (det, seg) = results[idx] for label in range(len(det)): bboxes = det[label] for i in range(bboxes.shape[0]): ...
def test_manual_add(tmpdir): workdir_one = os.path.join(str(tmpdir), 'workdir_one') workdir_two = os.path.join(str(tmpdir), 'workdir_two') metadir = os.path.join(str(tmpdir), 'metadir') runner = CliRunner() statefile = os.path.join(str(tmpdir), 'state.json') result = runner.invoke(yadage.manualc...
def test_type_complex_while_labels() -> None: src = "\n i = 0\n while i < 10:\n j = 0\n while j < 5:\n j += 1\n i += 1\n\n if i > 4:\n print('hi')\n\n print('not else')\n " expected_labels = {'True', 'False'} assert (_extract_labels(build_cfg(src...
class Request(testprocess.Line): def __init__(self, data): super().__init__(data) try: parsed = json.loads(data) except ValueError: raise testprocess.InvalidLine(data) assert isinstance(parsed, dict) assert (set(parsed.keys()) == {'path', 'verb', 'stat...
def test_kinesis_subscription_with_starting_position_at_timestamp(): ksub = {'stream': 'arn:aws:kinesis:eu-west-1::stream/services', 'batch_size': 10, 'starting_position_timestamp': '2017-11-01T11:00:00Z'} cfg = config.Config(EX_CONFIG, (EX_CONFIG + '/lambda-with-subscription_at_ts.json')) assert (cfg.raw['...
class ClassicalOptimizer(): def __init__(self, instance, n, K): self.instance = instance self.n = n self.K = K def compute_allowed_combinations(self): f = math.factorial return ((f(self.n) / f(self.K)) / f((self.n - self.K))) def cplex_solution(self): instance...
def main(config: lib.JSONDict, output: Union[(str, Path)], *, force: bool=False) -> Optional[lib.JSONDict]: if (not lib.start(output, force=force)): return None output = Path(output) report = lib.create_report(config) C = lib.make_config(Config, config) delu.random.seed(C.seed) device = ...
def execute_fixture(monkeypatch) -> None: for func in ['check_brew_cmd', 'check_cask', 'set_brewfile_repo', 'set_brewfile_local', 'check_repo', 'repomgr', 'brew_cmd', 'initialize', 'check_input_file', 'edit_brewfile', 'cat_brewfile', 'get_files', 'clean_non_request', 'cleanup', 'install']: def set_func(func...
def set_embedding(z_target, state, nbits, _mol_embedding=mol_fp): if (len(state) == 0): return np.concatenate([np.zeros((1, (2 * nbits))), z_target], axis=1) else: e1 = np.expand_dims(_mol_embedding(state[0]), axis=0) if (len(state) == 1): e2 = np.zeros((1, nbits)) el...
class EncoderLayer(nn.Module): def __init__(self, size, self_attn, feed_forward, group_attn, dropout): super(EncoderLayer, self).__init__() self.self_attn = self_attn self.feed_forward = feed_forward self.group_attn = group_attn self.sublayer = clones(SublayerConnection(size,...
def _get_proposal_section_reviewer_vote_choices(conference): allow_plus_zero_vote = ConferenceSettingConstants.ALLOW_PLUS_ZERO_REVIEWER_VOTE plus_zero_vote_setting = conference.conferencesetting_set.filter(name=allow_plus_zero_vote['name']).first() if plus_zero_vote_setting: plus_zero_vote_setting_v...
class DimShuffle(ExternalCOp): _f16_ok = True check_input = False __props__ = ('input_broadcastable', 'new_order', 'inplace') c_func_file = 'c_code/dimshuffle.c' c_func_name = 'APPLY_SPECIFIC(cpu_dimshuffle)' def params_type(self): return ParamsType(shuffle=lvector, augment=lvector, tran...
def qpos_to_pd_joint_vel(controller: PDJointVelController, qpos): assert (type(controller) == PDJointVelController) assert controller.config.normalize_action delta_qpos = (qpos - controller.qpos) qvel = (delta_qpos * controller._control_freq) (low, high) = (controller.config.lower, controller.config...
class _ModuleProxy(): _module = None def __init__(self, name): self.__dict__['_module_name'] = name def __getattr__(self, name): try: return getattr(self._module, name) except AttributeError: if (self._module is not None): raise imp...
def get_failure_msg_from_onion_error(decrypted_error_packet: bytes) -> OnionRoutingFailureMessage: failure_len = int.from_bytes(decrypted_error_packet[32:34], byteorder='big') failure_msg = decrypted_error_packet[34:(34 + failure_len)] return OnionRoutingFailureMessage.from_bytes(failure_msg)
class SkillTreeView(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.TAB_TRAVERSAL) self.charEditor = self.Parent.Parent self.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW)) ...
.parametrize('line', ['', ';', ';;', ';; ;', '&', '& &', ' && &', '>', "'", '"', '|']) def test_parse_command_only_empty(parser, line): statement = parser.parse_command_only(line) assert (statement == '') assert (statement.args == statement) assert (statement.arg_list == []) assert (statement.comman...
class VectorScaler(SKCMatrixAndWeightTransformerABC): _inherit(SKCMatrixAndWeightTransformerABC._transform_weights) def _transform_weights(self, weights): return scale_by_vector(weights, axis=None) _inherit(SKCMatrixAndWeightTransformerABC._transform_matrix) def _transform_matrix(self, matrix): ...
class PreconditionerTest(): def __init__(self): self.x = (torch.randn(mconfig.M, mconfig.K).cuda().half() / 100) self.y = (torch.randn(mconfig.K, mconfig.N).cuda().half() / 100) self.num_bins = ((2 ** mconfig.num_bits) - 1) self.scale_y = (max(abs(self.y.min()), abs(self.y.max())) / ...
class DesktopWin32WindowSpecificationTests(unittest.TestCase): def setUp(self): Timings.defaults() self.app = Application(backend='win32').start(os.path.join(mfc_samples_folder, u'CmnCtrl3.exe')) self.desktop = Desktop(backend='win32') self.desktop_no_magic = Desktop(backend='win32',...
class AdaBound(Optimizer): def __init__(self, params, lr=0.001, betas=(0.9, 0.999), final_lr=0.1, gamma=0.001, eps=1e-08, weight_decay=0, amsbound=False): if (not (0.0 <= lr)): raise ValueError('Invalid learning rate: {}'.format(lr)) if (not (0.0 <= eps)): raise ValueError('I...
class BarthezTokenizer(PreTrainedTokenizer): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES model_input_names = ['input_ids', 'attention_mask'] def __init__(self, vocab_file, bos_token='<s>'...
def download_cub_metadata(to_path): acsm_val_mat_path = f'{to_path}/val_cub_cleaned.mat' if (not os.path.isfile(acsm_val_mat_path)): acsm_val_mat_url = f' print("Downloading metadata used to form ACSM's CUB validation set") download_url(acsm_val_mat_url, to_path) else: print(...
class COCOInstanceNewBaselineDatasetMapper(): def __init__(self, is_train=True, *, tfm_gens, image_format, mask_format): self.tfm_gens = tfm_gens logging.getLogger(__name__).info('[COCOInstanceNewBaselineDatasetMapper] Full TransformGens used in training: {}'.format(str(self.tfm_gens))) self...
class GRU(nn.Module): def __init__(self, npoint, hidden_dim, input_dim, use_instance_norm): super(GRU, self).__init__() in_ch = (hidden_dim + input_dim) self.convz = PointNetSetAbstraction(npoint=int((npoint / 4)), radius=None, nsample=4, in_channel=in_ch, mlp=[hidden_dim], group_all=False, ...
def _flatten(dico, prefix=None): new_dico = OrderedDict() if isinstance(dico, dict): prefix = ((prefix + '.') if (prefix is not None) else '') for (k, v) in dico.items(): if (v is None): continue new_dico.update(_flatten(v, (prefix + k))) elif isinstan...
def inspect_client_error(val_err: ValueError, eth_node: Optional[EthClient]) -> ClientErrorInspectResult: json_response = str(val_err).replace("'", '"').replace('("', '(').replace('")', ')') try: error = json.loads(json_response) except json.JSONDecodeError: return ClientErrorInspectResult.P...
class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, conv_builder, stride=1, downsample=None): super(Bottleneck, self).__init__() midplanes = (((((inplanes * planes) * 3) * 3) * 3) // (((inplanes * 3) * 3) + (3 * planes))) self.conv1 = nn.Sequential(nn.Conv3d(i...
('/usb_devices.html', methods=['GET']) def usb_devices(): str_devices = subprocess.getoutput('lsusb').split('\n') devices = [] for device in str_devices: devices.append({'bus': device.split(': ID ')[0].split(' ')[1], 'device': device.split(': ID ')[0].split(' ')[3], 'id': device.split(': ID ')[1][:9...
class MessageView(QWidget): update_geometry = pyqtSignal() def __init__(self, parent=None): super().__init__(parent) self._messages: MutableSequence[Message] = [] self._vbox = QVBoxLayout(self) self._vbox.setContentsMargins(0, 0, 0, 0) self._vbox.setSpacing(0) sel...
class MultiSimilarityLoss(GenericPairLoss): def __init__(self, alpha=2, beta=50, base=0.5, **kwargs): super().__init__(mat_based_loss=True, **kwargs) self.alpha = alpha self.beta = beta self.base = base self.add_to_recordable_attributes(list_of_names=['alpha', 'beta', 'base']...
def test_multiprocessing_showcase(): import numpy as np import joblib import time import datetime def func(): n_jobs = 8 size = 3000 print('Creating data: {size}x{size} ... '.format(size=size), end='') a = np.random.random((size, size)) print('done ({size:.02f...
class Votes(models.Model): class Meta(): table = 'votes' user_id = fields.BigIntField(pk=True) is_voter = fields.BooleanField(default=False, index=True) expire_time = fields.DatetimeField(null=True) reminder = fields.BooleanField(default=False) notified = fields.BooleanField(default=Fals...
def create_unet_backbone(bottom_up_layers: List[BottomUpLayer], layers_start: int, layers_end: int, top_down_stack: TopDownStackInterface) -> Nodes: selected_layer_indexes = list(range(layers_start, layers_end)) top_down = bottom_up_layers[selected_layer_indexes[(- 1)]].tensor for layer_index in reversed(se...
class TMPEGInfo(TestCase): def test_not_real_file(self): filename = os.path.join(DATA_DIR, 'silence-44-s-v1.mp3') with open(filename, 'rb') as h: fileobj = BytesIO(h.read(20)) self.failUnlessRaises(MP3Error, MPEGInfo, fileobj) def test_empty(self): fileobj = BytesIO(b...
def compute_cell_extents_grid(bounding_rect=(0.03, 0.03, 0.97, 0.97), num_rows=2, num_cols=6, axis_pad=0.01): (left, bottom, width, height) = bounding_rect height_padding = (axis_pad * (num_rows + 1)) width_padding = (axis_pad * (num_cols + 1)) cell_height = float(((height - height_padding) / num_rows))...
class TestHSAFFileHandler(unittest.TestCase): def setUp(self): try: import pygrib except ImportError: pygrib = None self.orig_pygrib = pygrib sys.modules['pygrib'] = mock.MagicMock() def tearDown(self): sys.modules['pygrib'] = self.orig_pygrib ...
class Layer(aimet_common.layer_database.Layer): def _set_type_specific_params(self, module: tf.Operation): if (module.type == 'Conv2D'): (strides, padding, groups) = aimet_tensorflow.utils.op.conv.get_conv2d_op_params(module) params = aimet_common.layer_database.Conv2dTypeSpecificPar...
_required('wiki.add_wikifile', raise_exception=True) def wiki_file_list(request): if (request.method == 'POST'): try: wiki_file = WikiFile.objects.create(upload_user=request.user, wiki_file=request.FILES.get('upload_wiki_file')) file_name = wiki_file.wiki_file.name.split('/')[(- 1)] ...
_singleton def loadModel(device): ckpt = torch.hub.load_state_dict_from_url(MODELS_URL, map_location=device, check_hash=True) config = Config.deserialize(ckpt['config']) model = Compressor(**config.Model.Params).to(device) model.QuantizationParameter = 'qp_2_msssim' model.load_state_dict(ckpt['model...
def generate_intermediate_ca(opts, parent_certificate_path=p.root_ca_certificate_path(), parent_key_path=p.root_ca_key_path(), suffix=''): print('Will generate intermediate CA with suffix {}'.format(suffix)) print('Using parent certificate path at {}'.format(parent_certificate_path)) print('Using parent key...
def _add_metric_pages(html_file, run_output_paths, report_config, data_frame): _write_header(html_file, 'Distribution of different measures (except SPICE-related, which come later below)') for column_name in COLUMNS_FOR_HISTOGRAM_NON_SPICE: bins = report_config.histogram_bins[column_name] metric...
class NetModule(): def __init__(self, args): self.args = args self.input_shape = (32, 32, 3) self.shapes = [(3, 3, 3, 64), (3, 3, 64, 128), (3, 3, 128, 128), (3, 3, 128, 128), (3, 3, 128, 256), (3, 3, 256, 512), (3, 3, 512, 512), (3, 3, 512, 512), (512, self.args.num_classes)] self.l...
.fast def test_non_air_diluent(verbose=True, plot=False, *args, **kwargs): sf = SpectrumFactory(wavelength_min=4200, wavelength_max=4500, cutoff=1e-23, molecule='CO', isotope='1,2', truncation=5, neighbour_lines=10, path_length=0.1, mole_fraction=0.1, medium='vacuum', optimization=None, verbose=verbose) sf.warn...
class MixNet(nn.Module): mixnet_s = [(16, 16, [3], [1], [1], 1, 1, 'ReLU', 0.0), (16, 24, [3], [1, 1], [1, 1], 2, 6, 'ReLU', 0.0), (24, 24, [3], [1, 1], [1, 1], 1, 3, 'ReLU', 0.0), (24, 40, [3, 5, 7], [1], [1], 2, 6, 'Swish', 0.5), (40, 40, [3, 5], [1, 1], [1, 1], 1, 6, 'Swish', 0.5), (40, 40, [3, 5], [1, 1], [1, 1...
class TestCLI(TestCase): def run_cli(self, argv, files=None, stdin=StringIO(), exit_code=0, **override): arguments = cli.parse_args(argv) arguments.update(override) self.assertFalse(hasattr(cli, 'open')) cli.open = fake_open((files or {})) try: (stdout, stderr) = ...
class HandShaker(): def __init__(self, bsd_socket): self._bsd_socket = bsd_socket def shake_hands_as_host(self, id): message = ('YOTON!%s.%i' % (UID(id).get_hex(), os.getpid())) request = self._recv_during_handshaking() if (not request): return (False, STOP_HANDSHAKE_...
def parse_option(): parser = argparse.ArgumentParser('argument for training') parser.add_argument('--eval_freq', type=int, default=100, help='meta-eval frequency') parser.add_argument('--save_freq', type=int, default=500, help='save frequency') parser.add_argument('--batch_size', type=int, default=64, h...
class Final_Feature(nn.Module): def __init__(self, in_channel, out_channel): super().__init__() self.CBR_1x1 = nn.Sequential(nn.Conv2d(in_channel, out_channel, kernel_size=1, stride=1, padding=0, bias=True), nn.BatchNorm2d(out_channel), nn.ReLU(inplace=True)) self.pool_1_2x2 = nn.MaxPool2d(k...
class Evaluator(): def __init__(self): self.partial_scores = None def eval_hardness(self, sql): count_comp1_ = count_component1(sql) count_comp2_ = count_component2(sql) count_others_ = count_others(sql) if ((count_comp1_ <= 1) and (count_others_ == 0) and (count_comp2_ =...
def comet_pull_weight_by_key(key, projname, epoch, api, rank, deterministic=True): for attempt in range(4): try: tic = time() expt = api.get(cometconfig['workspace'], projname, key) assets = expt.get_asset_list() assets = assets2dict(assets, 'fileName', 'asset...
class TelegramHandler(tornado.web.RequestHandler): __slots__ = ('bot', 'update_queue', 'secret_token') SUPPORTED_METHODS = ('POST',) def initialize(self, bot: 'Bot', update_queue: asyncio.Queue, secret_token: str) -> None: self.bot = bot self.update_queue = update_queue self.secret_t...
def read_tsp_tour(fname): has_tour = False tour = [] with open(fname) as fp: for line in fp: if line.startswith('TOUR_SECTION'): has_tour = True elif line.startswith('EOF'): break elif has_tour: tour.extend((int(node...