code stringlengths 281 23.7M |
|---|
class FTraceCallGraph():
vfname = 'missing_function_name'
def __init__(self, pid, sv):
self.id = ''
self.invalid = False
self.name = ''
self.partial = False
self.ignore = False
self.start = (- 1.0)
self.end = (- 1.0)
self.list = []
self.dep... |
class CustomTransform(TransformComponent):
def __init__(self, transformer: Callable[(..., Any)], **kwargs: Any):
super().__init__()
self.transformer = transformer
self.transformer__kwargs = kwargs
def transformer(self) -> Callable[(..., Any)]:
return self._transformer
def tra... |
def test_drop_last_false():
data = pd.DataFrame({'1': (['a', 'b', 'c'] * 150), '2': (['a', 'b', 'c'] * 150)})
tvae = TVAESynthesizer(epochs=300)
tvae.fit(data, ['1', '2'])
sampled = tvae.sample(100)
correct = 0
for (_, row) in sampled.iterrows():
if (row['1'] == row['2']):
co... |
class Mesh(dict):
def __init__(self, geometry, submesh_types, var_pts):
super().__init__()
self.geometry = geometry
var_pts_input = var_pts
var_pts = {}
for (key, value) in var_pts_input.items():
if isinstance(key, str):
key = getattr(pybamm.standa... |
def squared_l1_prox_pos(x, step=1, weights=None, check=False):
if check:
assert all((x >= 0))
if (weights is None):
weights = np.ones_like(x)
x_over_w = (x / weights)
decr_sort_idxs = np.argsort(x_over_w)[::(- 1)]
x_sort = x[decr_sort_idxs]
weights_sort = weights[decr_sort_idxs]
... |
class TestSquareLattice(QiskitNatureTestCase):
def test_init(self):
rows = 3
cols = 2
edge_parameter = ((1.0 + 1j), (2.0 + 2j))
onsite_parameter = 1.0
boundary_condition = (BoundaryCondition.PERIODIC, BoundaryCondition.OPEN)
square = SquareLattice(rows, cols, edge_par... |
def find_node_with_resource(resource: ResourceInfo, context: NodeContext, haystack: Iterator[Node]) -> ResourceNode:
for node in haystack:
if (isinstance(node, ResourceNode) and (node.resource(context) == resource)):
return node
raise ValueError(f'Could not find a node with resource {resourc... |
def digui(newone, s, yuzhi, www, R, mui):
m = []
numone = []
loo = 0
looc = [[]]
for i in newone:
for j in www:
sample = str((i + j))
mui = (mui + 1)
n = diguipd(s, sample, R)
if ((n >= yuzhi) and (sample not in m)):
if (n > loo... |
class Class_Tools():
def func_str_chaifen(self, encode_type, source_text, length):
try:
changdu = int(length)
except:
return [0, '!', '']
if (changdu > len(source_text)):
return [0, '!', '']
else:
text = [source_text[i:(i + changdu)] fo... |
class NetmapCommand(ops.cmd.DszCommand):
optgroups = {}
reqgroups = []
reqopts = []
defopts = {}
def __init__(self, plugin='netmap', netmap_type=None, **optdict):
ops.cmd.DszCommand.__init__(self, plugin, **optdict)
self.netmap_type = netmap_type
def validateInput(self):
... |
_hook('output_csv')
class OutputCSVHook(ClassyHook):
on_phase_start = ClassyHook._noop
on_start = ClassyHook._noop
def __init__(self, folder, id_key='id', delimiter='\t') -> None:
super().__init__()
self.output_path = f'{folder}/{DEFAULT_FILE_NAME}'
self.file = PathManager.open(self.... |
class TestAssertIsInstance(TestCase):
def test_you(self):
self.assertIsInstance(abc, 'xxx')
def test_me(self):
self.assertIsInstance(123, (xxx + y))
self.assertIsInstance(456, (aaa and bbb))
self.assertIsInstance(789, (ccc or ddd))
self.assertIsInstance(123, (True if You ... |
def build_from_dict(cfg, registry, default_args=None):
assert (isinstance(cfg, dict) and ('type' in cfg))
args = cfg.copy()
obj_type = args.pop('type')
if isinstance(obj_type, str):
clazz = registry[obj_type]
clazz_name = clazz.split('.')[(- 1)]
module_name = clazz[0:((len(clazz)... |
(auto_attribs=True)
class RepairTarget_Detector_Target_Repaired(RepairTarget_Detector_Target_Remaining):
num_original_targetedVuls: int = attr.ib(repr=False)
num_repaired: Union[(int, float)] = math.inf
num_remaining: int = attr.ib(repr=False, init=False, default=attr.Factory((lambda self: ((self.num_origin... |
class traindataset(data.Dataset):
def __init__(self, root, mode, transform=None, num_class=5, multitask=False, args=None):
self.root = os.path.expanduser(root)
self.transform = transform
self.mode = mode
self.train_label = []
self.test_label = []
self.name = []
... |
class encoder(nn.Module):
def __init__(self, dim, nc=1):
super(encoder, self).__init__()
self.dim = dim
nf = 64
self.c1 = dcgan_conv(nc, nf)
self.c2 = dcgan_conv(nf, (nf * 2))
self.c3 = dcgan_conv((nf * 2), (nf * 4))
self.c4 = dcgan_conv((nf * 4), (nf * 8))
... |
class RoofProperty(bpy.types.PropertyGroup):
roof_types = [('FLAT', 'Flat', '', 0), ('GABLE', 'Gable', '', 1), ('HIP', 'Hip', '', 2)]
type: EnumProperty(name='Roof Type', items=roof_types, default='HIP', description='Type of roof to create')
gable_types = [('OPEN', 'Open', '', 0), ('BOX', 'Box', '', 1)]
... |
def perframe_sequence_trainer_noattn(conditioning_input_shapes, conditioning_input_names, input_gt_frames_shape, perframe_painter_model, seq_len, is_done_model=None, n_const_frames=1, do_output_disc_stack=False, n_prev_frames=None, n_prev_disc_frames=1, n_painter_frame_outputs=2):
if (n_prev_frames is None):
... |
class Args():
is_training = False
layers = 1
rnn_size = 100
n_epochs = 3
batch_size = 50
dropout_p_hidden = 1
learning_rate = 0.001
decay = 0.96
decay_steps = 10
sigma = 0
init_as_normal = False
reset_after_session = True
session_key = 'SessionId'
item_key = 'Item... |
class Solution(object):
def findCircleNum(self, M):
visited = ([0] * len(M))
count = 0
for i in range(len(M)):
if (visited[i] == 0):
self.dfs(M, visited, i)
count += 1
return count
def dfs(self, M, visited, i):
for j in range(le... |
class CSNBottleneck3d(Bottleneck3d):
def __init__(self, inplanes, planes, *args, bottleneck_mode='ir', **kwargs):
super(CSNBottleneck3d, self).__init__(inplanes, planes, *args, **kwargs)
self.bottleneck_mode = bottleneck_mode
conv2 = []
if (self.bottleneck_mode == 'ip'):
... |
def test_register_mismatch_method(he_pm: PluginManager) -> None:
class hello():
def he_method_notexists(self):
pass
plugin = hello()
he_pm.register(plugin)
with pytest.raises(PluginValidationError) as excinfo:
he_pm.check_pending()
assert (excinfo.value.plugin is plugin) |
class FC4_LogVol(FC3_LogVol):
removedKeywords = FC3_LogVol.removedKeywords
removedAttrs = FC3_LogVol.removedAttrs
def _getParser(self):
op = FC3_LogVol._getParser(self)
op.add_argument('--bytes-per-inode', dest='bytesPerInode', type=int, version=FC4, help='Specify the bytes/inode ratio.')
... |
def generate_outline(premise, setting, characters, character_strings, instruct_model, generation_max_length, max_sections=5, fixed_outline_length=(- 1), outline_levels=1, model_string='text-davinci-002'):
premise_setting_chars = ((((((('Premise: ' + premise.strip()) + '\n\n') + 'Setting: ') + setting.strip()) + '\n... |
class AutoFeatureExtractor():
def __init__(self):
raise EnvironmentError('AutoFeatureExtractor is designed to be instantiated using the `AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path)` method.')
_list_option_in_docstrings(FEATURE_EXTRACTOR_MAPPING_NAMES)
def from_pretrained(cls,... |
def draw_measure_tag(x, y, dx, dy, name, style=None, fill='bgcolor'):
global bgcolor
if (fill == 'bgcolor'):
fill = bgcolor
tikz_str = ('fill=%s' % fill)
if style:
tikz_str += (',' + style)
if (orientation == 'vertical'):
print(('\\draw[%s] (%f, %f) -- (%f,%f) -- (%f,%f) -- (... |
class Add(ImageOnlyTransform):
identity_param = 0
def __init__(self, values: List[float]):
if (self.identity_param not in values):
values = ([self.identity_param] + list(values))
super().__init__('value', values)
def apply_aug_image(self, image, value=0, **kwargs):
if (va... |
class DataIterator(object):
def __init__(self, args, dataset, batch_size, device=None, is_test=False, shuffle=True):
self.args = args
(self.batch_size, self.is_test, self.dataset) = (batch_size, is_test, dataset)
self.iterations = 0
self.device = device
self.shuffle = shuffle... |
def get_glob(path):
if isinstance(path, str):
return glob.glob(path, recursive=True)
if isinstance(path, os.PathLike):
return glob.glob(str(path), recursive=True)
elif isinstance(path, (list, tuple)):
return list(chain.from_iterable((glob.glob(str(p), recursive=True) for p in path)))... |
def extended_noun_chunks(sentence):
noun_chunks = {(np.start, np.end) for np in sentence.noun_chunks}
(np_start, cur_np) = (0, 'NONE')
for (i, token) in enumerate(sentence):
np_type = (token.pos_ if (token.pos_ in {'NOUN', 'PROPN'}) else 'NONE')
if (np_type != cur_np):
if (cur_np... |
class TestTransformerDelay(unittest.TestCase):
def test_default(self):
tfm = new_transformer()
tfm.delay([1.0])
actual_args = tfm.effects
expected_args = ['delay', '1.000000']
self.assertEqual(expected_args, actual_args)
actual_log = tfm.effects_log
expected_l... |
def parasitic_cphase_compensation(cphase_angle: float) -> Callable[([FermiHubbardParameters], FermiHubbardParameters)]:
def compensate(parameters: FermiHubbardParameters) -> FermiHubbardParameters:
cphase = (cphase_angle / parameters.dt)
if isinstance(parameters.layout, ZigZagLayout):
v ... |
def simple_river_split_gauge_model():
in_flow = 100.0
min_flow_req = 40.0
out_flow = 50.0
model = pywr.core.Model()
inpt = river.Catchment(model, name='Catchment', flow=in_flow)
lnk = river.RiverSplitWithGauge(model, name='Gauge', mrf=min_flow_req, mrf_cost=(- 100), slot_names=('river', 'abstrac... |
def passlib_or_crypt(secret, algorithm, salt=None, salt_size=None, rounds=None, ident=None):
if PASSLIB_AVAILABLE:
return PasslibHash(algorithm).hash(secret, salt=salt, salt_size=salt_size, rounds=rounds, ident=ident)
if HAS_CRYPT:
return CryptHash(algorithm).hash(secret, salt=salt, salt_size=sa... |
class OldGeneratorReach(GeneratorReach):
_digraph: graph_module.BaseGraph
_state: State
_game: GameDescription
_reachable_paths: (dict[(int, list[int])] | None)
_reachable_costs: (dict[(int, int)] | None)
_node_reachable_cache: dict[(int, bool)]
_unreachable_paths: dict[(tuple[(int, int)], R... |
class Driver(uvm_driver):
def build_phase(self):
self.ap = uvm_analysis_port('ap', self)
def start_of_simulation_phase(self):
self.bfm = TinyAluBfm()
async def launch_tb(self):
(await self.bfm.reset())
self.bfm.start_bfm()
async def run_phase(self):
(await self.la... |
.mssql_server_required
class TestStringTypeConversion(unittest.TestCase):
def setUp(self):
self.mssql = mssqlconn()
for (name, size) in VARIABLE_TYPES:
dbtype = name.lower()
identifier = (dbtype if (dbtype == 'text') else ('%s(%d)' % (dbtype, size)))
try:
... |
class AverageWindowAttention(AverageAttention):
def __init__(self, embed_dim, dropout=0.0, bias=True, window_size=0):
super().__init__(embed_dim, dropout, bias)
self.window_size = window_size
def _forward(self, value, mask_trick, mask_future_timesteps):
if (self.window_size == 1):
... |
def binary_search(fre, cand, level):
(low, high) = (0, (len(fre) - 1))
if (low > high):
return (- 1)
while (low < high):
mid = int(((low + high) / 2))
if (cand <= fre[mid][0:(level - 1)]):
high = mid
else:
low = (mid + 1)
if (cand == fre[low][0:(le... |
_REGISTRY.register()
class MSMT17(ImageDataset):
dataset_url = None
dataset_name = 'msmt17'
def __init__(self, root='datasets', **kwargs):
self.dataset_dir = root
has_main_dir = False
for main_dir in VERSION_DICT:
if osp.exists(osp.join(self.dataset_dir, main_dir)):
... |
class Effect6779(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
lvl = src.level
fit.modules.filteredChargeBoost((lambda mod: mod.item.requiresSkill('Skirmish Command')), 'warfareBuff3Multiplier', (src.getModifiedItemAttr('commandStrengthBonus') * lvl), *... |
def test_funcarg(testdir):
script = testdir.makepyfile(SCRIPT_FUNCARG)
result = testdir.runpytest('-v', f'--cov={script.dirpath()}', '--cov-report=term-missing', script)
result.stdout.fnmatch_lines(['*- coverage: platform *, python * -*', 'test_funcarg* 3 * 100%*', '*1 passed*'])
assert (result.ret == 0... |
class BboxHead(nn.Module):
def __init__(self, inchannels=512, num_anchors=3):
super(BboxHead, self).__init__()
self.conv1x1 = nn.Conv2d(inchannels, (num_anchors * 4), kernel_size=(1, 1), stride=1, padding=0)
def forward(self, x):
out = self.conv1x1(x)
out = out.permute(0, 2, 3, 1... |
def test_pype_get_args_no_parent_context():
context = Context({'pype': {'name': 'pipe name', 'args': {'a': 'b'}}})
with get_arb_pipeline_scope(context):
(pipeline_name, args, out, use_parent_context, pipe_arg, skip_parse, raise_error, loader, groups, success_group, failure_group, py_dir, parent) = pype.... |
def plot_time_series(link_matrix=None, coef_matrix=None, var_names=None, order=None, figsize=None, dpi=200, label_space_left=0.1, label_space_top=0.05, label_fontsize=12, alpha=0.001):
if ((link_matrix is None) and (coef_matrix is None)):
raise RuntimeError('link_matrix is None and coef_matrix is None')
... |
.parametrize('column_props,expected', [({'COLUMN_NAME': 'test_column', 'DATA_TYPE': 'bigint', 'CHARACTER_MAXIMUM_LENGTH': None, 'CHARACTER_OCTET_LENGTH': None, 'NUMERIC_PRECISION': None, 'NUMERIC_SCALE': None, 'UDT_NAME': None}, IntType(bits=64, signed=True)), ({'COLUMN_NAME': 'test_column', 'DATA_TYPE': 'int', 'CHARAC... |
class Brightness(object):
def __init__(self, value):
self.value = max(min(value, 1.0), (- 1.0))
def __call__(self, *inputs):
outputs = []
for (idx, _input) in enumerate(inputs):
_input = th.clamp(_input.float().add(self.value).type(_input.type()), 0, 1)
outputs.ap... |
class TestLoader(TestCase):
def test_handles_file(self):
sample = inspect.cleandoc('TAP version 13\n 1..2\n # This is a diagnostic.\n ok 1 A passing test\n not ok 2 A failing test\n This is an unknown line.\n Bail out! This test would abort.\... |
class StorageLookup(BaseDB):
logger = get_extended_debug_logger('eth.db.storage.StorageLookup')
_write_trie: HexaryTrie
_trie_nodes_batch: BatchDB
_historical_write_tries: List[PendingWrites]
def __init__(self, db: DatabaseAPI, storage_root: Hash32, address: Address) -> None:
self._db = db
... |
class FasterRcnnBoxCoder(box_coder.BoxCoder):
def __init__(self, scale_factors=None):
if scale_factors:
assert (len(scale_factors) == 4)
for scalar in scale_factors:
assert (scalar > 0)
self._scale_factors = scale_factors
def code_size(self):
retur... |
class TrainableFidelityQuantumKernel(TrainableKernel, FidelityQuantumKernel):
def __init__(self, *, feature_map: (QuantumCircuit | None)=None, fidelity: (BaseStateFidelity | None)=None, training_parameters: ((ParameterVector | Sequence[Parameter]) | None)=None, enforce_psd: bool=True, evaluate_duplicates: str='off_... |
class GINDeepSigns(nn.Module):
def __init__(self, in_channels, hidden_channels, out_channels, num_layers, k, dim_pe, rho_num_layers, use_bn=False, use_ln=False, dropout=0.5, activation='relu'):
super().__init__()
self.enc = GIN(in_channels, hidden_channels, out_channels, num_layers, use_bn=use_bn, d... |
def _lookups_parts_puzzlenames_protodefs(parts):
parts_dict = dict()
puzzlename_tags_dict = dict()
puzzle_ingredients = dict()
for part in parts:
parts_dict[part.dbref] = part
protodef = proto_def(part, with_tags=False)
del protodef['prototype_key']
puzzle_ingredients[par... |
def check_conversion_tensor_names(model, custom_objects=None):
tf.keras.backend.clear_session()
def get_converted_models_weight_names(converted_model_path) -> set:
converted_weight_names = set()
with tf.compat.v1.Session() as persisted_sess:
with gfile.FastGFile(converted_model_path,... |
def main():
parser = argparse.ArgumentParser(description='SMT-LIB Parser Benchmarking')
parser.add_argument('--base', type=str, nargs='?', help='top-directory of the benchmarks')
parser.add_argument('--count', type=int, nargs='?', default=(- 1), help='number of files to benchmark')
parser.add_argument('... |
.parametrize('p, size', [(np.array(0.5, dtype=config.floatX), None), (np.array(0.5, dtype=config.floatX), []), (np.array(0.5, dtype=config.floatX), [2, 3]), (np.full((1, 2), 0.5, dtype=config.floatX), None)])
def test_bernoulli_samples(p, size):
compare_sample_values(bernoulli, p, size=size, test_fn=(lambda *args, ... |
_plugins((ep for ep in (list(iter_entry_points('rasterio.rio_commands')) + list(iter_entry_points('rasterio.rio_plugins')))))
()
_opt
_opt
('--aws-profile', help='Select a profile from the AWS credentials file')
('--aws-no-sign-requests', is_flag=True, help='Make requests anonymously')
('--aws-requester-pays', is_flag=... |
class SysNlg(AbstractNlg):
def __init__(self, domain, complexity):
super().__init__(domain=domain, complexity=complexity)
self.domain = domain
self.complexity = complexity
def generate_sent(self, actions, domain=None, templates=SysCommonNlg.templates, generator=None, context=None):
... |
def test_osv_skipped_dep():
osv = service.OsvService()
dep = service.SkippedDependency(name='foo', skip_reason='skip-reason')
results: dict[(service.Dependency, list[service.VulnerabilityResult])] = dict(osv.query_all(iter([dep])))
assert (len(results) == 1)
assert (dep in results)
vulns = resul... |
class CallbackQuery(Object, Update):
def __init__(self, *, client: 'pyrogram.Client'=None, id: str, from_user: 'types.User', chat_instance: str, message: 'types.Message'=None, inline_message_id: str=None, data: Union[(str, bytes)]=None, game_short_name: str=None, matches: List[Match]=None):
super().__init__... |
class InlineInputMessage():
def __init__(self, text, syntax=None, preview=True):
self.text = text
self.syntax = syntax
self.preview = preview
def _serialize(self):
args = {'message_text': self.text, 'disable_web_page_preview': (not self.preview)}
syntax = syntaxes.guess_s... |
def test_total():
assert (get_typed_dict_shape(Foo) == Shape(input=InputShape(constructor=Foo, kwargs=None, fields=(InputField(type=int, id='a', default=NoDefault(), is_required=True, metadata=MappingProxyType({}), original=None), InputField(type=str, id='b', default=NoDefault(), is_required=True, metadata=MappingP... |
class RenderTarget(GuiRenderComponent):
source = ShowInInspector(Camera, None)
depth = ShowInInspector(float, 0.0)
canvas = ShowInInspector(bool, True, 'Render Canvas')
flipY = 1
def __init__(self):
super(RenderTarget, self).__init__()
self.setup = False
self.size = Vector2.z... |
def train_legacy_masked_language_model(data_dir, arch, extra_args=()):
train_parser = options.get_training_parser()
train_args = options.parse_args_and_arch(train_parser, (['--task', 'cross_lingual_lm', data_dir, '--arch', arch, '--optimizer', 'adam', '--lr-scheduler', 'reduce_lr_on_plateau', '--lr-shrink', '0.... |
_kernel_api(params={'p': POINTER, 'getattrlistbulk_args': POINTER, 'retval': POINTER})
def hook__getattrlistbulk(ql, address, params):
getattrlistbulk_args = getattrlistbulk_args_t(ql, params['getattrlistbulk_args']).loadFromMem()
dirfd = ql.os.ev_manager.map_fd[getattrlistbulk_args.dirfd]
vfs_attr_pack = q... |
class InstanceNormModel(torch.nn.Module):
def __init__(self):
super(InstanceNormModel, self).__init__()
self.conv1 = torch.nn.Conv2d(10, 20, 3)
self.in1 = torch.nn.InstanceNorm2d(20)
self.relu1 = torch.nn.ReLU()
def forward(self, x):
x = self.conv1(x)
x = self.in1... |
class TimeInstanceNorm(nn.Module):
def __init__(self, eps=1e-05):
super().__init__()
self.eps = eps
def cal_stats(self, x):
(b, c, t) = x.shape
mean = x.mean(1)
std = (x.var(1) + self.eps).sqrt()
mean = mean.view(b, 1, t)
std = std.view(b, 1, t)
re... |
def build_dataset(cfg, default_args=None):
if (cfg['type'] == 'RepeatDataset'):
from .dataset_wrappers import RepeatDataset
dataset = RepeatDataset(build_dataset(cfg['dataset'], default_args), cfg['times'])
else:
dataset = build_from_cfg(cfg, DATASETS, default_args)
return dataset |
def available_readers(as_dict=False, yaml_loader=UnsafeLoader):
readers = []
for reader_configs in configs_for_reader():
try:
reader_info = read_reader_config(reader_configs, loader=yaml_loader)
except (KeyError, IOError, yaml.YAMLError):
LOG.debug('Could not import reade... |
_criterion('model', dataclass=ModelCriterionConfig)
class ModelCriterion(FairseqCriterion):
def __init__(self, task, loss_weights=None, log_keys=None):
super().__init__(task)
self.loss_weights = loss_weights
self.log_keys = log_keys
def forward(self, model, sample, reduce=True):
... |
def problem_checks():
global _problem_checks
if _problem_checks:
return _problem_checks
_problem_checks = {'not-reporting': {'grace-period': datetime.timedelta(hours=4), 'alert-frequency': datetime.timedelta(days=1), 'spec': {'submitted_at': {'$lt': business_days_ago(1)}}, 'filter': not_reporting_fi... |
def single_proc_playground(local_rank, port, world_size, cfg):
torch.distributed.init_process_group(backend='nccl', init_method='tcp://localhost:{}'.format(port), world_size=world_size, rank=local_rank)
torch.cuda.set_device(local_rank)
playground(cfg)
torch.distributed.destroy_process_group() |
.parametrize('rich, higher, expected_format', [(True, True, Qt.TextFormat.RichText), (False, False, Qt.TextFormat.PlainText), (None, False, Qt.TextFormat.PlainText)])
.parametrize('replace', ['test', None])
def test_rich_text(view, qtbot, rich, higher, expected_format, replace):
level = usertypes.MessageLevel.info
... |
def save_atten(imgpath, atten, num_classes=20, base_dir='../save_bins/', idx_base=0):
atten = np.squeeze(atten)
for cls_idx in range(num_classes):
cat_dir = os.path.join(base_dir, idx2catename['voc20'][cls_idx])
if (not os.path.exists(cat_dir)):
os.mkdir(cat_dir)
cat_map = at... |
def get_dataloader(tokenizer, examples, label_list, tag):
logger.info('start prepare input data')
cached_train_features_file = os.path.join(args.input_cache_dir, (tag + 'input.pkl'))
try:
with open(cached_train_features_file, 'rb') as reader:
features = pickle.load(reader)
except:
... |
def main():
args = parse_args()
raw_img = cv2.imread(args.input, 1)
raw_img = cv2.resize(raw_img, (224, 224), interpolation=cv2.INTER_LINEAR)
raw_img = (np.float32(raw_img) / 255)
(image, norm_image) = preprocess_img(raw_img)
model = models.__dict__[args.arch](pretrained=True).eval()
model =... |
('chaperone-procedure*', arity=Arity.geq(2))
def chaperone_procedure_star(args):
(proc, check, keys, vals) = unpack_procedure_args(args, 'chaperone-procedure*')
if ((check is values.w_false) and (not keys)):
return proc
return imp.make_interpose_procedure(imp.W_ChpProcedureStar, proc, check, keys, v... |
def test_smoketest_defaults(cli_runner):
cli_command = 'raiden smoketest'
expected_args = {'debug': (ParameterSource.DEFAULT, False), 'eth_client': (ParameterSource.DEFAULT, EthClient.GETH)}
(_, kwargs) = get_invoked_kwargs(cli_command, cli_runner, 'raiden.ui.cli._smoketest')
assert_invoked_kwargs(kwarg... |
class TestClickThroughRate(unittest.TestCase):
def test_click_through_rate_with_valid_input(self) -> None:
input = torch.tensor([0, 1, 0, 1, 1, 0, 0, 1])
weights = torch.tensor([1.0, 2.0, 1.0, 2.0, 1.0, 2.0, 1.0, 2.0])
torch.testing.assert_close(click_through_rate(input), torch.tensor(0.5))
... |
class AppleScriptLexer(RegexLexer):
name = 'AppleScript'
url = '
aliases = ['applescript']
filenames = ['*.applescript']
version_added = '1.0'
flags = (re.MULTILINE | re.DOTALL)
Identifiers = '[a-zA-Z]\\w*'
Literals = ('AppleScript', 'current application', 'false', 'linefeed', 'missing v... |
.end_to_end()
def test_collect_task_with_expressions(runner, tmp_path):
source = '\n import pytask\n\n .depends_on("in_1.txt")\n .produces("out_1.txt")\n def task_example_1():\n pass\n\n .depends_on("in_2.txt")\n .produces("out_2.txt")\n def task_example_2():\n pass\n '
tmp... |
def setup_distributed():
local_rank = (int(os.environ['LOCAL_RANK']) if ('LOCAL_RANK' in os.environ) else 0)
n_gpu = (int(os.environ['WORLD_SIZE']) if ('WORLD_SIZE' in os.environ) else 1)
is_distributed = (n_gpu > 1)
if is_distributed:
torch.cuda.set_device(local_rank)
dist.init_process_... |
.parametrize('vuln_count, pkg_count, skip_count, print_format', [(1, 1, 0, True), (2, 1, 0, True), (2, 2, 0, True), (0, 0, 0, False), (0, 1, 0, False), (0, 0, 1, True)])
def test_print_format(monkeypatch, vuln_count, pkg_count, skip_count, print_format):
dummysource = pretend.stub(fix=(lambda a: None))
monkeypa... |
class Migration(migrations.Migration):
dependencies = [('domain', '0039_meta')]
operations = [migrations.AlterField(model_name='attribute', name='uri', field=models.URLField(blank=True, help_text='The Uniform Resource Identifier of this attribute (auto-generated).', max_length=640, null=True, verbose_name='URI'... |
class VanillaBlock(nn.Module):
def __init__(self, w_in, w_out, stride, bn_norm, bm=None, gw=None, se_r=None):
assert ((bm is None) and (gw is None) and (se_r is None)), 'Vanilla block does not support bm, gw, and se_r options'
super(VanillaBlock, self).__init__()
self.construct(w_in, w_out, ... |
class DownSample(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=(3, 1, 1), stride=(1, 1, 1), padding=(1, 0, 0), groups=1, bias=False, conv_cfg=dict(type='Conv3d'), norm_cfg=None, act_cfg=None, downsample_position='after', downsample_scale=(1, 2, 2)):
super().__init__()
self.co... |
def apply_across_args(*fns):
def f2(f, *names):
if (names and isinstance(names[0], int)):
if (names == 1):
return f()
else:
return [f() for i in range(names[0])]
if isinstance(names, tuple):
if (len(names) == 1):
nam... |
def test_frd_indexing():
w = np.linspace(0.99, 2.01, 11)
m = 0.6
p = ((- 180) * ((2 * w) - 1))
d = (m * np.exp((((1j * np.pi) / 180) * p)))
frd_gm = FrequencyResponseData(d, w)
(gm, _, _, wg, _, _) = stability_margins(frd_gm, returnall=True)
assert_allclose(gm, [(1 / m), (1 / m)], atol=0.01)... |
_model
def resmlp_24_distilled_224(pretrained=False, **kwargs):
model_args = dict(patch_size=16, num_blocks=24, embed_dim=384, mlp_ratio=4, block_layer=partial(ResBlock, init_values=1e-05), norm_layer=Affine, **kwargs)
model = _create_mixer('resmlp_24_distilled_224', pretrained=pretrained, **model_args)
ret... |
class NomineeList(NominationMixin, ListView):
template_name = 'nominations/nominee_list.html'
def get_queryset(self, *args, **kwargs):
election = Election.objects.get(slug=self.kwargs['election'])
if (election.nominations_complete or self.request.user.is_superuser):
return Nominee.ob... |
def get_next_file(directory, pattern, templates):
files = [f for f in os.listdir(directory) if re.match(pattern, f)]
if (len(files) == 0):
return (templates[0], 0)
def key(f):
index = re.match(pattern, f).group('index')
return (0 if (index == '') else int(index))
files.sort(key=k... |
class CBaseDumper(CEmitter, BaseRepresenter, BaseResolver):
def __init__(self, stream, default_style=None, default_flow_style=None, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None, encoding=None, explicit_start=None, explicit_end=None, version=None, tags=None):
CEmitter.__init__... |
def build_model(model_version, quantize, model_path, device):
if (model_version == 1):
if quantize:
net = quantized_modelv1(pretrained=True, device=device).to(device)
else:
net = modelv1(pretrained=True, device=device).to(device)
elif (model_version == 2):
if quan... |
def _interpolate(raw, input, size=None, scale_factor=None, mode='nearest', align_corners=None):
if ((mode == 'bilinear') and (align_corners == True)):
x = raw(input, size, scale_factor, mode)
name = log.add_layer(name='interp')
log.add_blobs([x], name='interp_blob')
layer = caffe_net... |
def test_load_kasvs_ecdh_kdf_vectors():
vector_data = textwrap.dedent('\n # Parameter set(s) supported: EB EC ED EE\n # CAVSid: CAVSid (in hex: )\n # IUTid: In hex: a1b2c3d4e5\n [EB]\n\n [Curve selected: P-224]\n [SHA(s) supported (Used in the KDF function): SHA224 SHA256 SHA384 SHA512]\n ... |
def built(path, version_string=None):
if version_string:
fname = os.path.join(path, '.built')
if (not os.path.isfile(fname)):
return False
else:
with open(fname, 'r') as read:
text = read.read().split('\n')
return ((len(text) > 1) and (text... |
class Logger(object):
def __init__(self, log_file, command):
self.log_file = log_file
if command:
self._write(command)
def output(self, epoch, enc_losses, dec_losses, training_samples, testing_samples, enc_mAP, dec_mAP, running_time, debug=True, log=''):
log += 'Epoch: {:2} |... |
def remove_embed_floats(root, paper_id):
from lxml.html.builder import IMG
for e in root.xpath('//figure[="ltx_figure"]'):
for c in e:
if ((c.tag != 'img') and (c.tag != 'figcaption')):
e.remove(c)
if ([c.tag for c in e] == ['figcaption']):
img = IMG()
... |
_optics(name='BL')
def solve_beer_lambert(solar_cell: SolarCell, wavelength: NDArray, **kwargs) -> None:
solar_cell.wavelength = wavelength
fraction = np.ones(wavelength.shape)
if hasattr(solar_cell, 'shading'):
fraction *= (1 - solar_cell.shading)
if (hasattr(solar_cell, 'reflectivity') and (so... |
_test
def test_maxpooling1d_legacy_interface():
old_layer = keras.layers.MaxPool1D(pool_length=2, border_mode='valid', name='maxpool1d')
new_layer = keras.layers.MaxPool1D(pool_size=2, padding='valid', name='maxpool1d')
assert (json.dumps(old_layer.get_config()) == json.dumps(new_layer.get_config()))
ol... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.