code stringlengths 101 5.91M |
|---|
_utils.test(arch=get_host_arch_list())
def test_loop_var_life():
def test():
for i in ti.static(range(8)):
pass
print(i)
with pytest.raises(Exception):
test() |
def ep_rule_condition1(memory_info: 'MemoryInfo', manager: 'MemoryManager', args):
index_upper = args['index_upper']
index_lower = args['index_lower']
target_fidelity = args['target_fidelity']
if ((index_lower <= memory_info.index <= index_upper) and (memory_info.state == 'ENTANGLED') and (memory_info.f... |
def basis_from_generators(gens, ords=None):
if (not gens):
return ([], [])
if (ords is None):
ords = [g.order() for g in gens]
from sage.arith.functions import lcm
lam = lcm(ords)
ps = sorted(lam.prime_factors(), key=lam.valuation)
gammas = []
ms = []
for p in ps:
... |
def uniform_quantize_tensor(tensor_data: np.ndarray, range_min: np.ndarray, range_max: np.ndarray, n_bits: int) -> np.ndarray:
(a, b) = fix_range_to_include_zero(range_min, range_max, n_bits)
delta = ((b - a) / ((2 ** n_bits) - 1))
clipped_tensor = np.clip(tensor_data, a_min=a, a_max=b)
q = ((delta * np... |
def correlation_coefficient_loss(y_true, y_pred):
x = y_true
y = y_pred
mx = K.mean(x)
my = K.mean(y)
(xm, ym) = ((x - mx), (y - my))
r_num = K.sum(tf.multiply(xm, ym))
r_den = K.sqrt(tf.multiply(K.sum(K.square(xm)), K.sum(K.square(ym))))
r = (r_num / r_den)
r = K.maximum(K.minimum(r... |
class Conv2d_tf(nn.Conv2d):
def __init__(self, *args, **kwargs):
super(Conv2d_tf, self).__init__(*args, **kwargs)
self.padding = kwargs.get('padding', 'SAME')
kwargs['padding'] = 0
if (not isinstance(self.stride, Iterable)):
self.stride = (self.stride, self.stride)
... |
def _persist_noise(noise, path):
with path.open(encoding='utf8', mode='w') as f:
f.write(' '.join(noise)) |
def test():
inout = np.ndarray([1], dtype=np.dtype(vec3d.as_ctypes()))
inout[0] = (4.0, 5.0, 6.0)
sdfg(A=inout)
expected = (5.0, 7.0, 9.0)
diff = tuple((abs((x - y)) for (x, y) in zip(inout[0], expected)))
print('Difference:', diff)
assert all(((d <= 1e-05) for d in diff)) |
def tf_idf_sim(claim, lines, freqs=None):
tfidf = OnlineTfidfDocRanker(args, [line['sentence'] for line in lines], freqs)
(line_ids, scores) = tfidf.closest_docs(claim, args.max_sent)
ret_lines = []
for (idx, line) in enumerate(line_ids):
ret_lines.append(lines[line])
ret_lines[(- 1)]['s... |
class BootstrapFewShot(Teleprompter):
def __init__(self, metric=None, teacher_settings={}, max_bootstrapped_demos=4, max_labeled_demos=16, max_rounds=1, max_errors=5):
self.metric = metric
self.teacher_settings = teacher_settings
self.max_bootstrapped_demos = max_bootstrapped_demos
s... |
def test_epoch(flow, test_loader, epoch, device=None, add_noise=True, annealing=False):
if annealing:
anneal_exponent = anneal_schedule(epoch, quiet=True)
else:
anneal_exponent = 0.0
snr_threshold = (2 * anneal_exponent)
anneal_exponent = torch.tensor(anneal_exponent).to(device)
snr_... |
def Newton_polytope_vars_coeffs(polynomial, variables):
R = polynomial.parent()
var_indices = [R.gens().index(x) for x in variables]
result = {}
for (c, m) in polynomial:
e = m.exponents()[0]
v = tuple([e[i] for i in var_indices])
m_red = (m // prod(((x ** i) for (x, i) in zip(va... |
def main_30():
print('outlier: 30%')
fig = plt.figure(figsize=(5, 5), dpi=150)
plot_i = 0
(h1,) = plt.plot(noise_sigmas, ransanc_pnp_add_rel_errors_outlier_30, marker='o', markersize=marker_size, markerfacecolor='none', label='RANSAC EPnP', linewidth=linewidth, color=((255 / 255.0), (150 / 255.0), (150 ... |
_module()
class CosineAnnealingLRWarmRestarts(scheduler.CosineAnnealingWarmRestarts):
def __init__(self, optimizer, T_0, max_epoch=(- 1), T_mult=1, eta_min=0, verbose=False):
super(CosineAnnealingLRWarmRestarts, self).__init__(optimizer, T_0, T_mult=T_mult, eta_min=eta_min, verbose=verbose) |
class MultiMarginLoss(_WeightedLoss):
__constants__ = ['p', 'margin', 'reduction']
margin: float
p: int
def __init__(self, p: int=1, margin: float=1.0, weight: Optional[Tensor]=None, size_average=None, reduce=None, reduction: str='mean') -> None:
super(MultiMarginLoss, self).__init__(weight, siz... |
def test_strides():
from mmdet.core import AnchorGenerator
self = AnchorGenerator([10], [1.0], [1.0], [10])
anchors = self.grid_anchors([(2, 2)], device='cpu')
expected_anchors = torch.tensor([[(- 5.0), (- 5.0), 5.0, 5.0], [5.0, (- 5.0), 15.0, 5.0], [(- 5.0), 5.0, 5.0, 15.0], [5.0, 5.0, 15.0, 15.0]])
... |
def plot_reset_comparison(spk_in, mem_rec, spk_rec, mem_rec0, spk_rec0):
(fig, ax) = plt.subplots(nrows=3, ncols=2, figsize=(10, 6), sharex=True, gridspec_kw={'height_ratios': [0.4, 1, 0.4], 'wspace': 0.05})
splt.raster(spk_in, ax[0][0], s=400, c='black', marker='|')
ax[0][0].set_ylabel('Input Spikes')
... |
def get_abbr_impl():
if hasattr(sys, 'pypy_version_info'):
pyimpl = 'pp'
elif sys.platform.startswith('java'):
pyimpl = 'jy'
elif (sys.platform == 'cli'):
pyimpl = 'ip'
else:
pyimpl = 'cp'
return pyimpl |
def _find_spacepy_dir():
if ('SPACEPY' in os.environ):
parentdir = os.path.abspath(os.path.expanduser(os.environ['SPACEPY']))
if (not os.path.exists(parentdir)):
try:
os.makedirs(parentdir)
except OSError as e:
if (e.errno != errno.EEXIST):
... |
class ReferenceDecoder(Decoder):
name = 'reference'
def __init__(self, decoder_args):
super(ReferenceDecoder, self).__init__(decoder_args)
def decode(self, src_sentence, trgt_sentence):
self.trgt_sentence = (trgt_sentence + [utils.EOS_ID])
self.initialize_predictor(src_sentence)
... |
def worker_single(remote, parent_remote, env_fn_wrapper):
parent_remote.close()
env = env_fn_wrapper.x()
while True:
(cmd, data) = remote.recv()
if (cmd == 'step'):
(ob, select_opponent, reward, done, info) = env.step(data)
if all(done):
(ob, select_op... |
.skipif((sys.version_info.major < 3), reason='not tested for python 2')
_instrumenter
def test_io(scorep_env, instrumenter):
trace_path = get_trace_path(scorep_env)
print('start')
(std_out, std_err) = utils.call_with_scorep('cases/file_io.py', ['--nocompiler', ('--instrumenter-type=' + instrumenter), '--noi... |
def register_Ns3DeviceEnergyModel_methods(root_module, cls):
cls.add_constructor([param('ns3::DeviceEnergyModel const &', 'arg0')])
cls.add_constructor([])
cls.add_method('ChangeState', 'void', [param('int', 'newState')], is_pure_virtual=True, is_virtual=True)
cls.add_method('GetCurrentA', 'double', [],... |
def _get_logger(filename='test_install.log'):
logger = logging.getLogger('test_install.py')
logger.setLevel(logging.DEBUG)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
file_handler = logging.FileHandler(filename)
file_handler.setLevel(logging.DEBUG)
logger... |
class SegformerEncoder(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
drop_path_decays = [x.item() for x in torch.linspace(0, config.drop_path_rate, sum(config.depths))]
embeddings = []
for i in range(config.num_encoder_blocks):
em... |
.parametrize('task,use_bias', [(task, use_bias) for task in ['binary', 'regression'] for use_bias in [True, False]])
def test_PredictionLayer(task, use_bias):
with CustomObjectScope({'PredictionLayer': layers.PredictionLayer}):
layer_test(layers.PredictionLayer, kwargs={'task': task, 'use_bias': use_bias}, ... |
def isEqual(account1, account2):
if (len(account1) != len(account2)):
return False
for i in range(len(account1)):
if (account1[i] != account2[i]):
return False
return True |
def list_dir_recursively_with_ignore(dir_path: str, ignores: List[str]=None, add_base_to_relative: bool=False) -> List[Tuple[(str, str)]]:
assert os.path.isdir(dir_path)
base_name = os.path.basename(os.path.normpath(dir_path))
if (ignores is None):
ignores = []
result = []
for (root, dirs, f... |
def precision_n(candidate, references, n):
ref_max = reduce(max_count, [ngram_count(ref, n) for ref in references])
candidate_ngram_count = ngram_count(candidate, n)
total = sum(candidate_ngram_count.values())
correct = sum(reduce(min_count, (ref_max, candidate_ngram_count)).values())
score = ((corr... |
.hypothesis_nested
def test_cookies(flask_app):
_app.route('/cookies', methods=['GET'])
def cookies():
return jsonify(request.cookies)
schema = schemathesis.from_dict({'openapi': '3.0.2', 'info': {'title': 'Test', 'description': 'Test', 'version': '0.1.0'}, 'paths': {'/cookies': {'get': {'parameters... |
def config_parser():
import configargparse
parser = configargparse.ArgumentParser()
parser.add_argument('--config', is_config_file=True, help='config file path')
parser.add_argument('--expname', type=str, help='experiment name')
parser.add_argument('--basedir', type=str, default='./logs/', help='whe... |
class NullOptimizer(Optimizer):
def __init__(self):
super().__init__(None)
def construct_from_pytorch(self, model_params):
return self
def __getattr__(self, item):
def pass_func(*args, **kwargs):
pass
return pass_func |
def main(args):
file_name = f'{args.policy}_{args.domain_name}_{args.seed}'
print('')
print(f'Policy: {args.policy}, Env: {args.domain_name}, Seed: {args.seed}')
print('')
log_path = safe_path(os.path.join(args.log_root, '{}_{}_damp1'.format(args.domain_name, args.task_name)))
result_path = safe... |
_function
def power(f, k):
if (k == 1):
return f
b = [int(a) for a in reversed(ZZ(k).binary())]
if (sum(b) == 1):
if (b[1] == 1):
return (f ** 2)
else:
return (power(f, ((2 ** b.index(1)) / 2)) ** 2)
else:
return prod((power(f, (2 ** i)) for (i, a)... |
def get_loader(config):
transform_list = []
if config.use_augmentation:
transform_list.append(transforms.RandomHorizontalFlip())
transform_list.append(transforms.RandomRotation(0.1))
transform_list.append(transforms.Scale(config.image_size))
transform_list.append(transforms.ToTensor())
... |
def vae_loss_function(recon_x, x, mu, logvar):
MSE = torch.sum(((recon_x - x) ** 2), (- 1))
KLD = ((- 0.5) * torch.sum((((1 + logvar) - mu.pow(2)) - logvar.exp()), (- 1)))
return (MSE + KLD).mean() |
def dist_location(dist):
egg_link = egg_link_path(dist)
if egg_link:
return normalize_path(egg_link)
return normalize_path(dist.location) |
def load_index(input_path):
(index, rev_index) = ({}, {})
with open(input_path) as f:
for (i, line) in enumerate(f.readlines()):
(v, _) = line.strip().split()
index[v] = i
rev_index[i] = v
return (index, rev_index) |
class ModelExpEmbAttn(ModelTemplate):
def __init__(self, token_emb_mat, glove_emb_mat, tds, cds, tl, scope):
super(ModelExpEmbAttn, self).__init__(token_emb_mat, glove_emb_mat, tds, cds, tl, scope)
self.update_tensor_add_ema_and_opt()
def build_network(self):
_logger.add()
_logge... |
class MeanPool(nn.Module):
def __init__(self, cfg):
super().__init__()
self.cfg = cfg
def forward(self, x):
return x.mean(dim=(- 2)) |
def _asarray_square(A):
A = np.asarray(A)
if ((len(A.shape) != 2) or (A.shape[0] != A.shape[1])):
raise ValueError('expected square array_like input')
return A |
class JSONWriter(EventWriter):
def __init__(self, json_file, window_size=20):
self._file_handle = PathManager.open(json_file, 'a')
self._window_size = window_size
self._last_write = (- 1)
def write(self):
storage = get_event_storage()
to_save = defaultdict(dict)
f... |
def generator_midinet(image, options, reuse=False, name='generator'):
with tf.variable_scope(name):
if reuse:
tf.get_variable_scope().reuse_variables()
else:
assert (tf.get_variable_scope().reuse is False)
h0 = tf.nn.relu(batch_norm(linear(image, (options.df_dim * 16)... |
def screen_diversity(content_values, bins):
(h, w) = np.histogram(content_values, range=((- 1), 1), bins=bins)
return stats.entropy((h + 1), base=2) |
class InferConfig():
config = attr.ib()
config_args = attr.ib()
logdir = attr.ib()
section = attr.ib()
beam_size = attr.ib()
output = attr.ib()
step = attr.ib()
use_heuristic = attr.ib(default=False)
mode = attr.ib(default='infer')
limit = attr.ib(default=None)
output_history... |
def is_supported(method):
if hasattr(method, 'is_supported'):
return method.is_supported
return True |
class Partition7(nn.Module):
LAYER_SCOPES = ['T5ForConditionalGeneration/T5Stack[encoder]/ModuleList[block]/T5Block[21]/ModuleList[layer]/T5LayerSelfAttention[0]/T5LayerNorm[layer_norm]', 'T5ForConditionalGeneration/T5Stack[encoder]/ModuleList[block]/T5Block[21]/ModuleList[layer]/T5LayerSelfAttention[0]/T5Attention... |
class TestModelFromPaper1Config():
(autouse=True)
def setup(self, example_configuration_dir, atomic_dataset):
self.config = Configuration.from_yaml((example_configuration_dir / 'paper1_tardis_configv1.yml'))
self.simulation_state = SimulationState.from_config(self.config, atom_data=atomic_datase... |
class NonNegativeIntegers(UniqueRepresentation, Parent):
def __init__(self):
Parent.__init__(self, category=SetsWithGrading().Infinite(), facade=IntegerRing())
def an_element(self):
return 0
def _repr_(self):
return 'Non negative integers'
def graded_component(self, grade):
... |
def _optimal_transportation_distance(x, y, d):
t0 = time.time()
m = ot.emd2(x, y, d)
logger.debug(('%8f secs for Wasserstein dist. \t#source_nbr: %d, #target_nbr: %d' % ((time.time() - t0), len(x), len(y))))
return m |
_params({'data_home': [str, PathLike, None], 'shuffle': ['boolean'], 'random_state': ['random_state'], 'download_if_missing': ['boolean'], 'return_X_y': ['boolean']}, prefer_skip_nested_validation=True)
def fetch_olivetti_faces(*, data_home=None, shuffle=False, random_state=0, download_if_missing=True, return_X_y=False... |
def GetHitsMP_PNGraph(Graph, NIdHubH, NIdAuthH, MaxIter=20):
return _snap.GetHitsMP_PNGraph(Graph, NIdHubH, NIdAuthH, MaxIter) |
class GradientDescent(GradientOptimizer):
def __init__(self, objective: OptimizationFunction, parametrization: Parametrization, learning_rate: float, normalize_gradient: bool=False):
super().__init__()
self.alpha = learning_rate
self.objective = objective
self.param = parametrization... |
def count_degree(fname: str):
node_counts = {}
line_count = 0
with open(fname, 'r') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
for row in csv_reader:
if (line_count == 0):
line_count += 1
else:
ts = int(row[0])
... |
_properties
class ExpandTransformation(PatternTransformation):
def expressions(clc):
return [sdutil.node_path_graph(clc._match_node)]
def can_be_applied(self, graph: gr.OrderedMultiDiConnectorGraph, expr_index: int, sdfg, permissive: bool=False):
return True
def match_to_str(self, graph: gr.... |
def action_log_probs(policy_logits, actions):
return (- F.nll_loss(F.log_softmax(torch.flatten(policy_logits, 0, 1), dim=(- 1)), torch.flatten(actions, 0, 1), reduction='none').view_as(actions)) |
def test_deep_string_string():
(left, right) = ak.broadcast_arrays([['x', 'yz'], ['hello', 'world', 'foo', 'bar']], ['x', 'y'])
assert (right.to_list() == [['x', 'x'], ['y', 'y', 'y', 'y']]) |
def extract_sentences(dataset_files):
sentences = []
for (text_file, token_file, sentence_file) in dataset_files:
print(('Extracting sentences from %s and tokens from %s from the text file %s' % (sentence_file, token_file, text_file)))
sentences.extend(process_raw_file(text_file, token_file, sen... |
((not have_sympy), 'SymPy not installed')
def test_beta():
x = Symbol('x')
y = Symbol('y')
e1 = sympy.beta(sympy.Symbol('y'), sympy.Symbol('x'))
e2 = beta(y, x)
assert (sympify(e1) == e2)
assert (e2._sympy_() == e1) |
class Metropolis():
def __init__(self, T, random_gen=None):
self.beta = ((1.0 / T) if (T != 0) else float('inf'))
self.random_gen = check_random_state(random_gen)
def accept_reject(self, res_new, res_old):
with np.errstate(invalid='ignore'):
prod = ((- (res_new.fun - res_old.... |
def dimension_eis(X, k=2):
if is_ArithmeticSubgroup(X):
return X.dimension_eis(k)
elif isinstance(X, dirichlet.DirichletCharacter):
return Gamma1(X.modulus()).dimension_eis(k, X)
elif isinstance(X, (int, Integer)):
return Gamma0(X).dimension_eis(k)
raise TypeError(f'argument in d... |
def definite_meek(cg, background_knowledge=None):
cg_new = deepcopy(cg)
Tri = cg_new.find_triangles()
Kite = cg_new.find_kites()
Loop = True
while Loop:
Loop = False
for (i, j, k) in cg_new.definite_non_UC:
if (cg_new.is_fully_directed(i, j) and cg_new.is_undirected(j, k)... |
def list_secular_terms(min_order, max_order, eccentricities=True, inclinations=True):
args_dict = df_arguments_dictionary(max_order)
args = []
Nmax1 = ((max_order // 2) * 2)
Nmin1 = ((min_order // 2) * 2)
for N in range(0, (Nmax1 + 1), 2):
argsN = args_dict[N][0]
nutot_min = max(((Nm... |
def version():
srcdir = os.path.join(cwd, 'spectralDNS')
with open(os.path.join(srcdir, '__init__.py')) as f:
m = re.search("__version__\\s*=\\s*'(.*)'", f.read())
return m.groups()[0] |
class PAN(FPN):
def __init__(self, in_channels, out_channels, add_extra_levels=False, extra_levels=2):
super().__init__(in_channels, out_channels, add_extra_levels, extra_levels)
self.init_weights()
def forward(self, x):
assert (len(x) == len(self.in_channels))
laterals = [latera... |
class InteractionNoise(AbstractNoise):
def transmit(self, actions):
return self.add_self_correct(actions)
def transmit_words(self, utt):
utt = self.add_hesitation(utt)
return self.add_self_restart(utt)
def add_hesitation(self, utt):
tokens = utt.split(' ')
if ((len(to... |
class TestFileIO(unittest.TestCase):
_tmpdir: Optional[str] = None
_tmpfile: Optional[str] = None
_tmpfile_contents = 'Hello, World'
def setUpClass(cls) -> None:
cls._tmpdir = tempfile.mkdtemp()
with open(os.path.join(cls._tmpdir, 'test.txt'), 'w') as f:
cls._tmpfile = f.name... |
def cosine_similarity(a, b, eps=1e-08):
if (np.all((b == 0)) and np.all((a == 0))):
return 1.0
a_flat = a.flatten()
b_flat = b.flatten()
a_norm = tensor_norm(a)
b_norm = tensor_norm(b)
return (np.sum((a_flat * b_flat)) / ((a_norm * b_norm) + eps)) |
def test_dice_loss():
with pytest.raises(AssertionError):
DiceLoss(eps='1')
dice_loss = DiceLoss()
pred = torch.rand(1, 1, 32, 32)
gt = torch.rand(1, 1, 32, 32)
loss = dice_loss(pred, gt, None)
assert isinstance(loss, torch.Tensor)
mask = torch.rand(1, 1, 1, 1)
loss = dice_loss(p... |
class RandomLowLight(object):
def __init__(self, low_light_net, exp_ranges=[0.05, 0.3]):
self.threshold = 0.97
self.exp_range = exp_ranges
self.low_light_net = low_light_net
def __call__(self, img):
exp_degree = random.uniform(*self.exp_range)
(h, w, _) = img.shape
... |
.parametrize('gzip_response', [True, False])
def test_fetch_openml_cache(monkeypatch, gzip_response, tmpdir):
def _mock_urlopen_raise(request, *args, **kwargs):
raise ValueError(('This mechanism intends to test correct cachehandling. As such, urlopen should never be accessed. URL: %s' % request.get_full_url... |
def main():
global MODELS
prompt = SS3Prompt()
prompt.prompt = '(pyss3) >>> '
prompt.doc_header = 'Documented commands (type help <command>):'
Print.set_verbosity(VERBOSITY.VERBOSE)
Print.info(('PySS3 Command Line v%s | Sergio Burdisso (sergio.).\nPySS3 comes with ABSOLUTELY NO WARRANTY. This is... |
def pformat(obj: Any) -> str:
import io
s = io.StringIO()
pprint(obj, file=s)
return s.getvalue() |
class PpmImageFile(ImageFile.ImageFile):
format = 'PPM'
format_description = 'Pbmplus image'
def _token(self, s=b''):
while True:
c = self.fp.read(1)
if ((not c) or (c in b_whitespace)):
break
if (c > b'y'):
raise ValueError('Expect... |
class Distribution_parse_config_files():
def parse_config_files(self, filenames=None):
from configparser import ConfigParser
if (sys.prefix != sys.base_prefix):
ignore_options = ['install-base', 'install-platbase', 'install-lib', 'install-platlib', 'install-purelib', 'install-headers', '... |
.parametrize('device', ['cpu', 'cuda'])
def test_differentiable(device, fl=5, fp=3, B=2, N=4):
unframe = diffsptk.Unframe(fl, fp)
U.check_differentiable(device, unframe, [B, N, fl]) |
def get_single_monitor_data(log_df: pd.DataFrame, monitor_names: Union[(str, List[str])], transformation_name: Optional[str]=None, iteration: Optional[int]=None, event_name: Optional[str]=None) -> Union[(float, List)]:
if (transformation_name is None):
all_transformation_names = log_df[LOG_TRANSFORMATION_KE... |
class Batch3dceCollator(object):
def __init__(self, size_divisible=0):
self.size_divisible = size_divisible
self.num_slice = cfg.INPUT.NUM_SLICES
self.num_image = cfg.INPUT.NUM_IMAGES_3DCE
def __call__(self, batch):
images = ()
targets = []
infos = []
for ... |
class BaselineTrain(nn.Module):
def __init__(self, model_func, num_class, loss_type='softmax'):
super(BaselineTrain, self).__init__()
self.feature = model_func()
if (loss_type == 'softmax'):
self.classifier = nn.Linear(self.feature.final_feat_dim, num_class)
self.clas... |
_SEG_HEADS_REGISTRY.register()
class SemSegFPNHead(nn.Module):
def __init__(self, input_shape: Dict[(str, ShapeSpec)], *, num_classes: int, conv_dims: int, common_stride: int, loss_weight: float=1.0, norm: Optional[Union[(str, Callable)]]=None, ignore_value: int=(- 1)):
super().__init__()
input_shap... |
def get_requires_for_build_wheel(config_settings=None):
config_settings = _fix_config(config_settings)
return _get_build_requires(config_settings, requirements=['setuptools', 'wheel']) |
def get_random_affine():
(dx, dy) = np.random.randint((- 1.7), 1.8, 2)
M = np.float32([[1, 0, dx], [0, 1, dy]])
return M |
def unwrap_checkpoint(m: torch.nn.Module):
for module in m.modules():
if hasattr(module, 'precheckpoint_forward'):
module.forward = module.precheckpoint_forward
del module.precheckpoint_forward
return m |
.parametrize(('r_plot', 'end'), [[[1, 2, 2.1, 2.2, 4, 8, 8, np.inf], 6], [[1, 2, 2.1, 2.2, 2.3, 4, 8, 8, np.inf], 0], [[1, 2, 2.1, 2, np.inf], 0], [[1, 2, 2.1, np.inf], 2]])
def test_extend_upward(r_plot, end):
r_plot = np.array(r_plot)
ratio = (r_plot[:(- 1)] / r_plot[1:])
steep_upward = (ratio <= 0.9)
... |
def read_planar(planar_path, fmt=((1080, 1920), (1080, 1920), (1080, 1920))):
planar_file = np.fromfile(planar_path, dtype=np.uint8)
img = []
accum = 0
for res in fmt:
(h, w) = res
cha = planar_file[accum:(accum + (h * w))].reshape(h, w)
img.append(cha)
accum += (h * w)
... |
def all_reduce_max(tensor_list):
if (get_world_size() == 1):
return
for tensor in tensor_list:
dist.all_reduce(tensor, op=dist.reduce_op.MAX) |
def get_attentiveFP_idx(df, file='./split_and_data/05_BACE_attentiveFP.data'):
(train, valid, test) = load(file)
print(('training set: %s, valid set: %s, test set %s' % (len(train), len(valid), len(test))))
train_idx = df[df.smiles.isin(train.mol)].index
valid_idx = df[df.smiles.isin(valid.mol)].index
... |
class DensePoseDataPointsUVisualizer(DensePoseDataPointsVisualizer):
def __init__(self, **kwargs):
super(DensePoseDataPointsUVisualizer, self).__init__(densepose_data_to_value_fn=_densepose_data_u_for_cmap, **kwargs) |
def generate_partition_state_methods() -> str:
state_dict = generate_state_dict_method()
load_state_dict = generate_load_state_dict_method()
named_parameters = generate_named_parameters_method()
named_buffers = generate_named_buffers_method()
(cpu, cuda, to) = generate_cpu_cuda_to_methods()
retu... |
def df_to_fc(df: pd.DataFrame, lat_colname: str='lat', lon_colname: str='lon') -> ee.FeatureCollection:
df = df.astype('object')
ee_features = []
for i in range(len(df)):
props = df.iloc[i].to_dict()
_geometry = ee.Geometry.Point([props[lon_colname], props[lat_colname]])
ee_feat = ee... |
_section_pattern('arabic', PATS_NUM, int)
_section_pattern('roman_upper', PATS_ROMAN_UPPER, en.roman_to_int)
_section_pattern('roman_lower', PATS_ROMAN_LOWER, en.roman_to_int)
_section_pattern('alph_upper', PATS_ALPH_UPPER, en.alphabet_to_int)
_section_pattern('alph_lower', PATS_ALPH_LOWER, en.alphabet_to_int)
_section... |
def modrelu(input: Tensor, bias: Tensor, inplace: bool=False) -> Tensor:
if input.is_complex():
z_mag = torch.abs(input)
return (F.relu((z_mag + bias)) * (input / z_mag))
else:
return F.relu(input, inplace=inplace) |
_spec([HookScope.GLOBAL])
def before_load_schema(context: HookContext, raw_schema: dict[(str, Any)]) -> None: |
class NottinghamDatabase(RemoteABCFolderDataset):
_info = DatasetInfo(_NAME, _DESCRIPTION, _HOMEPAGE)
_sources = {'nmd': {'filename': 'nottingham_database.zip', 'url': ' 'archive': True, 'size': 142934, 'md5': 'f55c354aaf08bcb6e9b2b3b8d52e4df3', 'sha256': 'f79a4bffe78b16d630d4d69f9c62775a7aa246d0973c4d8714ab6c5... |
def cut(src, tgt, l):
(x, sr) = torchaudio.load(str(src))
assert (sr == 16000)
x = x.squeeze()
target_frames = int((l * sr))
flag = 0
if (target_frames <= x.size(0)):
x = x[:target_frames]
flag = 1
else:
flag = 0
torchaudio.save(str(tgt), x.unsqueeze(0), sr)
r... |
class TyposPerturbation(TextPerturbation):
(frozen=True)
class Description(PerturbationDescription):
prob: float = 0.0
name: str = 'typos'
def __init__(self, prob: float):
self.prob: float = prob
def description(self) -> PerturbationDescription:
return TyposPerturbation.Descr... |
def BatchNorm_reader(reader, version, obj):
if ((version < 2) and hasattr(obj, 'running_std')):
obj.running_var = obj.running_var.pow((- 2)).add((- obj.eps))
del obj.running_std |
_model
def skresnet50(pretrained=False, num_classes=1000, in_chans=3, **kwargs):
sk_kwargs = dict(split_input=True)
default_cfg = default_cfgs['skresnet50']
model = ResNet(SelectiveKernelBottleneck, [3, 4, 6, 3], num_classes=num_classes, in_chans=in_chans, block_args=dict(sk_kwargs=sk_kwargs), zero_init_las... |
def process_paths(args):
suffixes = ['_file', '_dir']
def _recurse(args):
if (('path' in args) and (args['path'] is not None)):
args['path'] = Path(args['path']).resolve()
for (k, v) in args.items():
for suffix in suffixes:
if (k.endswith(suffix) and (v is... |
def test_dlrep_wrong_secrets(group):
g = group.generator()
g1 = (2 * g)
g2 = (5 * g)
x1 = Secret()
x2 = Secret()
p = DLRep(g, ((x1 * g1) + (x2 * g2)))
prover = p.get_prover({x1: 10, x2: 15})
verifier = p.get_verifier()
protocol = SigmaProtocol(verifier, prover)
assert (not protoc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.