code
stringlengths
281
23.7M
def initialize_prom_client(distribution, prometheus_url, prometheus_bearer_token): global prom_cli (prometheus_url, prometheus_bearer_token) = instance(distribution, prometheus_url, prometheus_bearer_token) if (prometheus_url and prometheus_bearer_token): bearer = ('Bearer ' + prometheus_bearer_toke...
def disable_import(prefix): realimport = builtins.__import__ def my_import(name, *args, **kwargs): if name.startswith(prefix): raise ImportError return realimport(name, *args, **kwargs) try: builtins.__import__ = my_import (yield) finally: builtins.__i...
class Explara(object): def __init__(self, access_token): self.access_token = access_token self.headers = {'Authorization': ('Bearer ' + self.access_token)} self.base_url = ' def get_events(self): events = requests.post(self.base_url.format('get-all-events'), headers=self.headers)...
def test_fixtures_nose_setup_issue8394(pytester: Pytester) -> None: pytester.makepyfile('\n def setup_module():\n pass\n\n def teardown_module():\n pass\n\n def setup_function(func):\n pass\n\n def teardown_function(func):\n pass\n\n def...
def add_new_params(old_grid, new_grid, old_name, new_name): if new_grid: new_params = set(new_grid.keys()) old_params = set(old_grid.keys()) if (len(old_params.intersection(new_params)) > 0): raise ValueError('Overlap in parameters between {} and {} of the chosen pipeline.'.forma...
.usefixtures('session_app_data') def test_pick_periodic_update(tmp_path, mocker, for_py_version): (embed, current) = (get_embed_wheel('setuptools', '3.6'), get_embed_wheel('setuptools', for_py_version)) mocker.patch('virtualenv.seed.wheels.bundle.load_embed_wheel', return_value=embed) completed = (datetime....
def get_time_display(prev_record: Optional[Record], record: Record) -> Tuple[(str, str, str)]: time_absolute = record.timestamp.isoformat() time_color = '' if prev_record: (time_display, delta_seconds) = nice_time_diff(prev_record.timestamp, record.timestamp) if (delta_seconds <= 10): ...
class Effect5870(BaseEffect): type = 'passive' def handler(fit, ship, context, projectionRange, **kwargs): fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Shield Operation')), 'shieldBonus', ship.getModifiedItemAttr('shipBonusCI2'), skill='Caldari Hauler', **kwargs)
def get_total_memory(unit='G', number_only=False, init_pid=None): from pyrl.utils.data import num_to_str if (init_pid is None): init_pid = os.getpid() process = psutil.Process(init_pid) ret = process.memory_full_info().uss for proc in process.children(): process_info = proc.memory_fu...
def test_indent(caplog): caplog.set_level(logging.INFO) lg = logger.copy() nesting = lg.nesting name = uniqstr() with lg.indent(): lg.report('make', name) assert any((match_report(r, activity='make', content=name, spacing=(ReportFormatter.SPACING * (nesting + 2))) for r in caplog.records...
def first_stage(): ql = Qiling(['rootfs/8086/doogie/doogie.DOS_MBR'], 'rootfs/8086', console=False) ql.add_fs_mapper(128, QlDisk('rootfs/8086/doogie/doogie.DOS_MBR', 128)) ql.os.set_api((26, 4), set_required_datetime, QL_INTERCEPT.EXIT) hk = ql.hook_code(stop, begin=32792, end=32792) ql.run() ql...
def _toWindowsPath(p): pp = p.split('/') if (getFoamRuntime() == 'BashWSL'): if p.startswith('/mnt/'): return ((pp[2].toupper() + ':\\') + '\\'.join(pp[3:])) else: return p.replace('/', '\\') elif (getFoamRuntime() == 'BlueCFD'): if p.startswith('/home/ofuser/...
def _check_resultsets_equal(res1, res2): try: assert np.allclose(res1.species, res2.species) except ValueError: pass assert np.allclose(res1.tout, res2.tout) assert np.allclose(res1.param_values, res2.param_values) if isinstance(res1.initials, np.ndarray): assert np.allclose(...
def download_file(url, path): print('Downloading: {} (into {})'.format(url, path)) progress = [0, 0] def report(count, size, total): progress[0] = (count * size) if ((progress[0] - progress[1]) > 1000000): progress[1] = progress[0] print('Downloaded {:,}/{:,} ...'.for...
class ViewRecords(db.Model, AuditTimeMixin): __tablename__ = 'tb_view_record' id = db.Column(db.Integer, primary_key=True) domain_name = db.Column(db.String(256), nullable=False) record = db.Column(db.String(256), nullable=False) record_type = db.Column(db.String(32), nullable=False) ttl = db.Co...
class Migration(migrations.Migration): dependencies = [('proposals', '0027_auto__0540')] operations = [migrations.AlterField(model_name='historicalproposal', name='video_url', field=models.URLField(blank=True, default='', help_text='Short 1-2 min video describing your talk')), migrations.AlterField(model_name='...
def test_feature_all_scenarios(mocker): feature = Feature(1, 'Feature', 'I am a feature', 'foo.feature', 1, tags=None) feature.scenarios.extend([mocker.MagicMock(id=1), mocker.MagicMock(id=2)]) feature.scenarios.append(mocker.MagicMock(spec=ScenarioOutline, id=3, scenarios=[mocker.MagicMock(id=4), mocker.Ma...
class CORALRegularizer(Regularizer): def __init__(self, l=1): self.uses_learning_phase = 1 self.l = l def set_layer(self, layer): self.layer = layer def __call__(self, loss): if (not hasattr(self, 'layer')): raise Exception('Need to call `set_layer` on ActivityReg...
def decimal_to_binary(decimal_val, max_num_digits=20, fractional_part_only=False): decimal_val_fractional_part = abs((decimal_val - int(decimal_val))) current_binary_position_val = (1 / 2) binary_fractional_part_digits = [] while ((decimal_val_fractional_part >= 0) and (len(binary_fractional_part_digits...
def rtn_sprintf(se: 'SymbolicExecutor', pstate: 'ProcessState'): logger.debug('sprintf hooked') buff = pstate.get_argument_value(0) arg0 = pstate.get_argument_value(1) try: arg0f = pstate.get_format_string(arg0) nbArgs = arg0f.count('{') args = pstate.get_format_arguments(arg0, [...
def test_horovod_example(start_ray_client_server_2_cpus): assert ray.util.client.ray.is_connected() from ray_lightning.examples.ray_horovod_example import train_mnist data_dir = os.path.join(tempfile.gettempdir(), 'mnist_data_') config = {'layer_1': 32, 'layer_2': 64, 'lr': 0.1, 'batch_size': 32} tr...
class CommonBaseTesting(CommonBase): def __init__(self, parent, id=None, *args, **kwargs): if ('test' in kwargs): self.test = kwargs.pop('test') super().__init__(*args, **kwargs) self.parent = parent self.id = id self.args = args self.kwargs = kwargs d...
class Simple_Header_TestCase(ParserTest): def __init__(self, *args, **kwargs): ParserTest.__init__(self, *args, **kwargs) self.ks = '\n%pre-install --interpreter /usr/bin/python --erroronfail --log=/tmp/blah\nls /tmp\n%end\n' def runTest(self): self.parser.readKickstartFromString(self.ks...
def get_cql_models(app, connection=None, keyspace=None): from .models import DjangoCassandraModel models = [] single_cassandra_connection = (len(list(get_cassandra_connections())) == 1) is_default_connection = ((connection == DEFAULT_DB_ALIAS) or single_cassandra_connection) for (name, obj) in inspe...
class KeywordProbInferenceDataset(InferenceDataset): def __init__(self, features: Dict, transforms: Dict, keyword_prob: str, load_into_mem: bool=False, audio_ids: List=None, threshold: Union[(float, str)]=None): super().__init__(features, transforms, load_into_mem=load_into_mem, audio_ids=audio_ids) ...
class Decoder(nn.Module): def __init__(self, d_model, d_ff, d_k, d_v, n_layers, n_heads, len_q): super(Decoder, self).__init__() self.layers = nn.ModuleList([DecoderLayer(d_model, d_ff, d_k, d_v, n_heads, len_q) for _ in range(n_layers)]) def forward(self, dec_inputs, enc_outputs): dec_o...
def error_description(error_code): err_message = {'notLink': "Check the 'link' parameter (Empty or bad)", 'notDebrid': 'Maybe the filehoster is down or the link is not online', 'badFileUrl': 'The link format is not valid', 'hostNotValid': 'The filehoster is not supported', 'notFreeHost': 'This filehoster is not ava...
class Observer(): def __init__(self): self.id = rpc.get_worker_info().id self.env = gym.make('CartPole-v1') self.env.reset(seed=args.seed) def run_episode(self, agent_rref, n_steps): (state, ep_reward) = (self.env.reset()[0], 0) for step in range(n_steps): act...
def tscore(sample1, sample2): if (len(sample1) != len(sample2)): raise ValueError('different number of values') error = (pooled_sample_variance(sample1, sample2) / len(sample1)) diff = (statistics.mean(sample1) - statistics.mean(sample2)) return (diff / math.sqrt((error * 2)))
class CapturableArgumentParser(argparse.ArgumentParser): def __init__(self, *args: Any, **kwargs: Any) -> None: self.stdout = kwargs.pop('stdout', sys.stdout) self.stderr = kwargs.pop('stderr', sys.stderr) super().__init__(*args, **kwargs) def print_usage(self, file: (IO[str] | None)=Non...
.usefixtures('repo_with_no_tags_angular_commits') def test_errors_when_config_file_invalid_configuration(cli_runner: 'CliRunner', update_pyproject_toml: 'UpdatePyprojectTomlFn'): update_pyproject_toml('tool.semantic_release.remote.type', 'invalidType') result = cli_runner.invoke(main, ['--config', 'pyproject.to...
class ReadHoldingRegistersRequest(ReadRegistersRequestBase): function_code = 3 function_code_name = 'read_holding_registers' def __init__(self, address=None, count=None, slave=0, **kwargs): super().__init__(address, count, slave, **kwargs) def execute(self, context): if (not (1 <= self.c...
.end_to_end() .parametrize('flag', ['-e', '--exclude']) .parametrize('pattern', ['*_1.txt', 'to_be_deleted_file_[1]*']) def test_clean_with_excluded_file_via_config(project, runner, flag, pattern): project.joinpath('pyproject.toml').write_text(f'''[tool.pytask.ini_options] exclude = [{pattern!r}]''') result = r...
class AutoencoderTinyBlock(nn.Module): def __init__(self, in_channels: int, out_channels: int, act_fn: str): super().__init__() act_fn = get_activation(act_fn) self.conv = nn.Sequential(nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1), act_fn, nn.Conv2d(out_channels, out_channe...
class SKOptLearner(Optimizer, BaseLearner): def __init__(self, function, **kwargs): self.function = function self.pending_points = set() self.data = collections.OrderedDict() self._kwargs = kwargs super().__init__(**kwargs) def new(self) -> SKOptLearner: return SK...
class PoseResNet(nn.Module): def __init__(self, block, layers, cfg, **kwargs): self.inplanes = 64 self.deconv_with_bias = cfg.POSE_RESNET.DECONV_WITH_BIAS self.input_channels = (kwargs['input_channels'] if ('input_channels' in kwargs) else cfg.POSE_RESNET.INPUT_CHANNELS) self.keep_sc...
class Battleship(commands.Cog): def __init__(self, bot: Bot): self.bot = bot self.games: list[Game] = [] self.waiting: list[discord.Member] = [] def predicate(self, ctx: commands.Context, announcement: discord.Message, reaction: discord.Reaction, user: discord.Member) -> bool: if...
class TestEncodedId(): def test_init_str(self): obj = utils.EncodedId('Hello') assert ('Hello' == obj) assert ('Hello' == str(obj)) assert ('Hello' == f'{obj}') assert isinstance(obj, utils.EncodedId) obj = utils.EncodedId('this/is a/path') assert ('this%2Fis%...
class Solution(object): def getSum(self, a, b): import ctypes sum = 0 carry = ctypes.c_int32(b) while (carry.value != 0): sum = (a ^ carry.value) carry = ctypes.c_int32((a & carry.value)) carry.value <<= 1 a = sum return sum
class Softplus(UnaryScalarOp): def static_impl(x): not_int8 = (str(getattr(x, 'dtype', '')) not in ('int8', 'uint8')) if (x < (- 37.0)): return (np.exp(x) if not_int8 else np.exp(x, signature='f')) elif (x < 18.0): return (np.log1p(np.exp(x)) if not_int8 else np.log1p...
def test_a_decorated_singleton_should_not_override_a_child_provider(): parent_injector = Injector() provided_instance = SingletonB() class MyModule(Module): def provide_name(self) -> SingletonB: return provided_instance child_injector = parent_injector.create_child_injector([MyModule...
def make_reader(): field_names = None def read_line(line): nonlocal field_names print('\t\t\t\t\t', line) reader = csv.reader([line]) row = next(reader) if (field_names is None): field_names = row return None return dict(zip(field_names, ro...
def test__symmetrical_torque_driven_ocp__symmetry_by_constraint(): from bioptim.examples.symmetrical_torque_driven_ocp import symmetry_by_constraint as ocp_module bioptim_folder = os.path.dirname(ocp_module.__file__) ocp_module.prepare_ocp(biorbd_model_path=(bioptim_folder + '/models/cubeSym.bioMod'), phase...
class Zabbix(): def __init__(self, server, user, password, verify=True): self.server = server self.user = user self.password = password s = requests.Session() s.auth = (user, password) self.zapi = ZabbixAPI(server, s) self.zapi.session.verify = verify ...
class SawyerDoorCloseEnvV2(SawyerDoorEnvV2): def __init__(self): goal_low = (0.2, 0.65, 0.1499) goal_high = (0.3, 0.75, 0.1501) super().__init__() self.init_config = {'obj_init_angle': 0.3, 'obj_init_pos': np.array([0.1, 0.95, 0.15], dtype=np.float32), 'hand_init_pos': np.array([(- 0...
def get_dependency_urls(package_name, dependency_list_file): url_delimiter = '-f ' dependency_file_full_path = prepend_bin_path(package_name, dependency_list_file) dependency_list_array = open(dependency_file_full_path).read().splitlines() dependency_urls_list = [] for dependency_line in dependency_...
class LoggingPlugin(): def __init__(self, config: Config) -> None: self._config = config self.formatter = self._create_formatter(get_option_ini(config, 'log_format'), get_option_ini(config, 'log_date_format'), get_option_ini(config, 'log_auto_indent')) self.log_level = get_log_level_for_sett...
def check_improper_torsion(improper: Tuple[(int, int, int, int)], molecule: 'Ligand') -> Tuple[(int, int, int, int)]: for atom_index in improper: try: atom = molecule.atoms[atom_index] bonded_atoms = set() for bonded in atom.bonds: bonded_atoms.add(bonded)...
def preprocess_bilingual_corpora(args: argparse.Namespace, source_dict: Dictionary, char_source_dict: Optional[Dictionary], target_dict: Dictionary, char_target_dict: Optional[Dictionary]): embed_bytes = getattr(args, 'embed_bytes', False) if args.train_source_text_file: args.train_source_binary_path = ...
class BridgeTowerImageProcessingTester(unittest.TestCase): def __init__(self, parent, do_resize: bool=True, size: Dict[(str, int)]=None, size_divisor: int=32, do_rescale: bool=True, rescale_factor: Union[(int, float)]=(1 / 255), do_normalize: bool=True, do_center_crop: bool=True, image_mean: Optional[Union[(float, ...
class HotpotStratifiedBinaryQuestionParagraphPairsDataset(QuestionAndParagraphsDataset): def __init__(self, questions: List[HotpotQuestion], batcher: ListBatcher, fixed_dataset=False, sample_seed=18, add_gold_distractor=True): self.questions = questions self.batcher = batcher self.fixed_data...
class CrowdCounter(nn.Module): def __init__(self, gpus, model_name, pretrained=True): super(CrowdCounter, self).__init__() if (model_name == 'CSRNet_LCM'): from .SCC_Model.CSRNet_LCM import CSRNet_LCM as net elif (model_name == 'VGG16_LCM'): from .SCC_Model.VGG16_LCM ...
class FeatureDictNet(nn.ModuleDict): def __init__(self, model, out_indices=(0, 1, 2, 3, 4), out_map=None, feature_concat=False, flatten_sequential=False): super(FeatureDictNet, self).__init__() self.feature_info = _get_feature_info(model, out_indices) self.concat = feature_concat sel...
def find_resource_info_with_id(info_list: typing.Sequence[T], short_name: str, resource_type: ResourceType) -> T: for info in info_list: if (info.short_name == short_name): return info raise MissingResource(f"{resource_type.name} Resource with short_name '{short_name}' not found in {len(info...
class Subset(torch.utils.data.Dataset): def __init__(self, dataset, indices): self.dataset = dataset self.indices = indices self.group_array = self.get_group_array(re_evaluate=True) self.label_array = self.get_label_array(re_evaluate=True) def __getitem__(self, idx): retu...
class GroupAttention(nn.Module): def __init__(self, d_model, dropout=0.8, no_cuda=False): super(GroupAttention, self).__init__() self.d_model = 256.0 self.linear_key = nn.Linear(d_model, d_model) self.linear_query = nn.Linear(d_model, d_model) self.norm = LayerNorm(d_model) ...
class StateFieldProperty(object): def __init__(self, field, parent_property): self.field = field self.parent_property = parent_property def __get__(self, instance, owner): if instance: if (self.parent_property and hasattr(self.parent_property, '__get__')): ret...
class ESRGAN_model(): def __init__(self, lr_shape, hr_shape, SCALE=4): self.SCALE = SCALE (self.lr_shape, self.hr_shape) = (lr_shape, hr_shape) (self.lr_height, self.lr_width, self.channels) = lr_shape (self.hr_height, self.hr_width, _) = hr_shape self.n_residual_in_residual_...
def _configure_optimizer(learning_rate): if (FLAGS.optimizer == 'adadelta'): optimizer = tf.train.AdadeltaOptimizer(learning_rate, rho=FLAGS.adadelta_rho, epsilon=FLAGS.opt_epsilon) elif (FLAGS.optimizer == 'adagrad'): optimizer = tf.train.AdagradOptimizer(learning_rate, initial_accumulator_valu...
.parametrize('ip, host', [('127.0.0.1', 'localhost'), ('27.0.0.1', 'localhost.localdomain'), ('27.0.0.1', 'local'), ('55.255.255.255', 'broadcasthost'), (':1', 'localhost'), (':1', 'ip6-localhost'), (':1', 'ip6-loopback'), ('e80::1%lo0', 'localhost'), ('f00::0', 'ip6-localnet'), ('f00::0', 'ip6-mcastprefix'), ('f02::1'...
class TestRowAppendableArray(unittest.TestCase): def test_append_1d_arrays_and_trim_remaining_buffer(self): appendable = RowAppendableArray(7) appendable.append_row(np.zeros(3)) appendable.append_row(np.ones(3)) self.assertTrue(np.array_equal(appendable.to_array(), np.array([0, 0, 0,...
class Unfolding_Loss(Loss, ABC): def __init__(self, window_length, hop_length, **kwargs): super().__init__() self.window_length = window_length self.hop_length = hop_length def compute(self, model, mixture_signal, target_signal): target_signal_hat = model.separate(mixture_signal)...
class BertSmallModel(nn.Module): def __init__(self, config, train_embedding=False) -> None: super().__init__() self.model = Bert(config).to(device) self.embedding = copy.deepcopy(self.model.get_input_embeddings().requires_grad_(True)) self.model.set_input_embeddings(nn.Sequential()) ...
def torch_persistent_save(obj, f): if isinstance(f, str): with PathManager.open(f, 'wb') as h: torch_persistent_save(obj, h) return for i in range(3): try: return torch.save(obj, f) except Exception: if (i == 2): logger.error(tr...
class Attempt(object): def __init__(self, value, attempt_number, has_exception): self.value = value self.attempt_number = attempt_number self.has_exception = has_exception def get(self, wrap_exception=False): if self.has_exception: if wrap_exception: r...
class Command(BaseCommand): help = 'Run the ML model on the specified URLs. Results are not stored to the database.' def add_arguments(self, parser): parser.add_argument('urls', nargs='+', help=_('URL to run against')) def handle(self, *args, **kwargs): self.stdout.write((_('Using the model(...
def extract_multipart_formdata(data): _temp = [] REGEX_MULTIPART = '(?is)((Content-Disposition[^\\n]+?name\\s*=\\s*[\\"\']?(?P<name>(.*?))[\\"\']?)(?:;\\s*filename=[\\"\']?(?P<filename>(.*?))[\\"\']?)?(?:\\nContent-Type:\\s*(?P<contenttype>(.*?))\\n)?(?:\\s*)?(?P<value>[\\w\\.\\_\\-\\*\\+\\[\\]\\=\\>\\;\\:\\\'\...
class TestMPM(TestCase): def test_well_posed(self): options = {'thermal': 'isothermal', 'working electrode': 'positive'} model = pybamm.lithium_ion.MPM(options) model.check_well_posedness() model = pybamm.lithium_ion.MPM({'working electrode': 'positive'}, build=False) model.b...
class BetaIncInv(ScalarOp): nfunc_spec = ('scipy.special.betaincinv', 3, 1) def impl(self, a, b, x): return scipy.special.betaincinv(a, b, x) def grad(self, inputs, grads): (a, b, x) = inputs (gz,) = grads return [grad_not_implemented(self, 0, a), grad_not_implemented(self, 0...
class LxFdtDump(gdb.Command): def __init__(self): super(LxFdtDump, self).__init__('lx-fdtdump', gdb.COMMAND_DATA, gdb.COMPLETE_FILENAME) def fdthdr_to_cpu(self, fdt_header): fdt_header_be = '>IIIIIII' fdt_header_le = '<IIIIIII' if (utils.get_target_endianness() == 1): ...
def download_coco(path, overwrite=False): _DOWNLOAD_URLS = [(' '10ad623668ab00c62c096f0ed636d6aff41faca5'), (' '8551ee4bb5860311e79dace7e79cb91e432e78b3'), (' '4950dc9d00dbe1c933ee0170fd2a41')] mkdir(path) for (url, checksum) in _DOWNLOAD_URLS: filename = download(url, path=path, overwrite=overwrite...
def init(): if dist.is_initialized(): return if ('MASTER_ADDR' not in os.environ): os.environ['MASTER_ADDR'] = 'localhost' if ('MASTER_PORT' not in os.environ): os.environ['MASTER_PORT'] = '29500' if ('RANK' not in os.environ): os.environ['RANK'] = '0' if ('LOCAL_RANK...
class RotationTransformer(): valid_reps = ['axis_angle', 'euler_angles', 'quaternion', 'rotation_6d', 'matrix'] def __init__(self, from_rep='axis_angle', to_rep='rotation_6d', from_convention=None, to_convention=None): assert (from_rep != to_rep) assert (from_rep in self.valid_reps) asse...
class PlyData(object): def __init__(self, elements=[], text=False, byte_order='=', comments=[], obj_info=[]): if ((byte_order == '=') and (not text)): byte_order = _native_byte_order self.byte_order = byte_order self.text = text self.comments = list(comments) self...
class _ServerCapabilities(): actions: bool body_markup: bool body_hyperlinks: bool kde_origin_name: bool def from_list(cls, capabilities: List[str]) -> '_ServerCapabilities': return cls(actions=('actions' in capabilities), body_markup=('body-markup' in capabilities), body_hyperlinks=('body-h...
class Effect8104(BaseEffect): type = 'passive' def handler(fit, src, context, projectionRange, **kwargs): lvl = src.level fit.drones.filteredItemIncrease((lambda mod: mod.item.requiresSkill('Salvage Drone Specialization')), 'accessDifficultyBonus', (src.getModifiedItemAttr('specAccessDifficultyB...
class SlackOAuth2Test(OAuth2Test): backend_path = 'social_core.backends.slack.SlackOAuth2' user_data_url = ' access_token_body = json.dumps({'access_token': 'foobar', 'token_type': 'bearer'}) user_data_body = json.dumps({'ok': True, 'user': {'email': '', 'name': 'Foo Bar', 'id': '123456'}, 'team': {'id'...
def test_inner_call_with_dynamic_argument() -> None: node = builder.extract_node('\n def f(x):\n return g(x)\n\n def g(y):\n return y + 2\n\n f(1) #\n ') assert isinstance(node, nodes.NodeNG) inferred = node.inferred() assert (len(inferred) == 1) assert (inferred[0] is Uni...
class Font(BaseObject, EqNeAttrs): bold = 0 character_set = 0 colour_index = 0 escapement = 0 family = 0 font_index = 0 height = 0 italic = 0 name = UNICODE_LITERAL('') struck_out = 0 underline_type = 0 underlined = 0 weight = 400 outline = 0 shadow = 0
class DummyCondStage(): def __init__(self, conditional_key): self.conditional_key = conditional_key self.train = None def eval(self): return self def encode(c: Tensor): return (c, None, (None, None, c)) def decode(c: Tensor): return c def to_rgb(c: Tensor): ...
class cifar_dataloader(): def __init__(self, dataset, r, noise_mode, batch_size, num_workers, root_dir, log, noise_file=''): self.dataset = dataset self.r = r self.noise_mode = noise_mode self.batch_size = batch_size self.num_workers = num_workers self.root_dir = root...
def tags_handler(ctx, param, value): retval = options.from_like_context(ctx, param, value) if ((retval is None) and value): try: retval = dict((p.split('=') for p in value)) except Exception: raise click.BadParameter(("'%s' contains a malformed tag." % value), param=param...
class FlavaImageConfig(PretrainedConfig): model_type = 'flava_image_model' def __init__(self, hidden_size: int=768, num_hidden_layers: int=12, num_attention_heads: int=12, intermediate_size: int=3072, hidden_act: int='gelu', hidden_dropout_prob: float=0.0, attention_probs_dropout_prob: float=0.0, initializer_ra...
class unit_tcn_G(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=9, stride=1): super(unit_tcn_G, self).__init__() pad = int(((kernel_size - 1) / 2)) inter_channels = (out_channels // 4) self.inter_c = inter_channels self.conv = nn.Conv2d(in_channels, out...
class SFTLayer_torch(nn.Module): def __init__(self): super(SFTLayer_torch, self).__init__() self.SFT_scale_conv0 = nn.Conv2d(32, 32, 1) self.SFT_scale_conv1 = nn.Conv2d(32, 64, 1) self.SFT_shift_conv0 = nn.Conv2d(32, 32, 1) self.SFT_shift_conv1 = nn.Conv2d(32, 64, 1) def ...
class TextAccumulator(): def __init__(self, separator: str=''): self._separator = separator self._texts: List[str] = [] def push(self, text: str) -> None: self._texts.append(text) def pop(self) -> Iterator[str]: if (not self._texts): return text = self._se...
class Decorators(NodeNG): _astroid_fields = ('nodes',) nodes: list[NodeNG] def postinit(self, nodes: list[NodeNG]) -> None: self.nodes = nodes def scope(self) -> LocalsDictNodeNG: if (not self.parent): raise ParentMissingError(target=self) if (not self.parent.parent):...
('bot.constants.Channels.incidents', 123) class TestIsIncident(unittest.TestCase): def setUp(self) -> None: self.incident = MockMessage(channel=MockTextChannel(id=123), content='this is an incident', author=MockUser(bot=False), pinned=False, reference=None) def test_is_incident_true(self): self....
def test_bound_crs__example(): proj_crs = ProjectedCRS(conversion=TransverseMercatorConversion(latitude_natural_origin=0, longitude_natural_origin=15, false_easting=2520000, false_northing=0, scale_factor_natural_origin=0.9996), geodetic_crs=GeographicCRS(datum=CustomDatum(ellipsoid='International 1924 (Hayford 190...
def build_valid_col_units(table_units, schema): col_ids = [table_unit[1] for table_unit in table_units if (table_unit[0] == TABLE_TYPE['table_unit'])] prefixs = [col_id[:(- 2)] for col_id in col_ids] valid_col_units = [] for value in schema.idMap.values(): if (('.' in value) and (value[:value.in...
def main(): opts = TrainOptions().parse() if os.path.exists(opts.exp_dir): raise Exception('Oops... {} already exists'.format(opts.exp_dir)) os.makedirs(opts.exp_dir) opts_dict = vars(opts) pprint.pprint(opts_dict) with open(os.path.join(opts.exp_dir, 'opt.json'), 'w') as f: json...
def test_fix_finalizer_func_only(testdir): testdir.makepyfile("\n import time, pytest\n\n class TestFoo:\n\n \n def fix(self, request):\n print('fix setup')\n def fin():\n print('fix finaliser')\n time.sleep(0.1)...
def test_multiple_channel_states(chain_state, token_network_state, channel_properties): open_block_number = 10 open_block_hash = factories.make_block_hash() pseudo_random_generator = random.Random() (properties, pkey) = channel_properties channel_state = factories.create(properties) channel_new_...
def _list_to_acl(entry_list, map_names=1): def char_to_acltag(typechar): if (typechar == 'U'): return posix1e.ACL_USER_OBJ elif (typechar == 'u'): return posix1e.ACL_USER elif (typechar == 'G'): return posix1e.ACL_GROUP_OBJ elif (typechar == 'g'): ...
def test_example(): parser = ArgumentParser() action = make_action(nargs=1) assert (interactive.example(parser, action, {}).strip() == '# --option OPTION') assert (interactive.example(parser, action, {'option': 32}).strip() == '--option 32') action = make_action(nargs=3) example = interactive.ex...
def test_timeheadwaycondition(): cond = OSC.TimeHeadwayCondition('Ego', 20, OSC.Rule.equalTo, True, False) prettyprint(cond.get_element()) cond2 = OSC.TimeHeadwayCondition('Ego', 20, OSC.Rule.equalTo, True, False) cond3 = OSC.TimeHeadwayCondition('Ego', 20, OSC.Rule.equalTo, True, True, routing_algorith...
def test_jaynes_cummings_zero_temperature_spectral_callable(): N = 10 a = qutip.tensor(qutip.destroy(N), qutip.qeye(2)) sp = qutip.tensor(qutip.qeye(N), qutip.sigmap()) psi0 = qutip.ket2dm(qutip.tensor(qutip.basis(N, 1), qutip.basis(2, 0))) kappa = 0.05 a_ops = [((a + a.dag()), (lambda w: (kappa...
class ContextFormatter(ABC): def get_formatters(self) -> MutableMapping: def format_path(cls, path: str, modifier: str) -> str: if (not modifier): return os.path.normpath(path) modifiers = modifier.split(':')[::(- 1)] while (modifiers and (modifiers[(- 1)] == 'parent')): ...
class DescribeInlineShapes(): def it_knows_how_many_inline_shapes_it_contains(self, inline_shapes_fixture): (inline_shapes, expected_count) = inline_shapes_fixture assert (len(inline_shapes) == expected_count) def it_can_iterate_over_its_InlineShape_instances(self, inline_shapes_fixture): ...
def get_current_component_version_from_source_files(component: str, version_file: Optional[str]=None) -> str: all_version_files = get_component_version_files(component, abs_path=True) if version_file: all_version_files = {version_file: all_version_files[version_file]} version = '' if all_version...