code stringlengths 101 5.91M |
|---|
class HeckeTriangleGroup(FinitelyGeneratedMatrixGroup_generic, UniqueRepresentation):
Element = HeckeTriangleGroupElement
def __classcall__(cls, n=3):
if (n == infinity):
n = infinity
else:
n = ZZ(n)
if (n < 3):
raise AttributeError('n has to b... |
_function_dispatch(_just_dispatcher)
def ljust(a, width, fillchar=' '):
a_arr = numpy.asarray(a)
width_arr = numpy.asarray(width)
size = long(numpy.max(width_arr.flat))
if numpy.issubdtype(a_arr.dtype, numpy.string_):
fillchar = asbytes(fillchar)
return _vec_string(a_arr, (a_arr.dtype.type, ... |
def _prepare_out_argument(out, dtype, expected_shape):
if (out is None):
return np.empty(expected_shape, dtype=dtype)
if (out.shape != expected_shape):
raise ValueError('Output array has incorrect shape.')
if (not out.flags.c_contiguous):
raise ValueError('Output array must be C-cont... |
class HumanOthelloPlayer():
def __init__(self, game):
self.game = game
def play(self, board):
valid = self.game.getValidMoves(board, 1)
for i in range(len(valid)):
if valid[i]:
print('[', int((i / self.game.n)), int((i % self.game.n)), end='] ')
while ... |
def get_distmult_kg_state_dict(state_dict):
kg_state_dict = dict()
for param_name in ['kg.entity_embeddings.weight', 'kg.relation_embeddings.weight']:
kg_state_dict[param_name.split('.', 1)[1]] = state_dict['state_dict'][param_name]
return kg_state_dict |
class spmatrix():
def _bsr_container(self):
from ._bsr import bsr_matrix
return bsr_matrix
def _coo_container(self):
from ._coo import coo_matrix
return coo_matrix
def _csc_container(self):
from ._csc import csc_matrix
return csc_matrix
def _csr_container(... |
def _train(config):
data_filter = get_squad_data_filter(config)
train_data = read_data(config, 'train', config.load, data_filter=data_filter)
dev_data = read_data(config, 'dev', True, data_filter=data_filter)
update_config(config, [train_data, dev_data])
_config_debug(config)
word2vec_dict = (tr... |
def clean_summary(source):
print('Cleaning source: ', source)
source_summary_dir_base = '../cleaning_phase/'
dest_dir_base = '../finished_summaries/'
spacy_nlp = spacy.load('en_core_web_lg')
source_summary_dir = os.path.join(source_summary_dir_base, source)
dest_dir = os.path.join(dest_dir_base,... |
def socket_write(socket, fn, args):
data_fn = int(fn).to_bytes(4, 'little', signed=False)
data_bytes = pickle.dumps(args)
data_size = len(data_bytes).to_bytes(8, 'little', signed=False)
socket.send(data_fn)
socket.send(data_size)
socket.send(data_bytes) |
class VecPyTorch():
def __init__(self, venv, device):
self.venv = venv
self.num_envs = venv.num_envs
self.observation_space = venv.observation_space
self.action_space = venv.action_space
self.device = device
def setup_scene(self, traj_data, r_idx, args):
(obs, inf... |
def register_Ns3WifiMac_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::WifiMac const &', 'arg0')])
cls.add_method('ConfigureStandard', 'void', [param('ns3::WifiPhyStandard', 'standard')])
cls.add_method('DoDispose', 'void', [], is_virtual=True)
cls.add_method('En... |
def discover_test_cases_recursively(suite_or_case):
if isinstance(suite_or_case, unittest.TestCase):
return [suite_or_case]
rc = []
for element in suite_or_case:
rc.extend(discover_test_cases_recursively(element))
return rc |
def display_chromagraph(audio_file_path, ctr=1):
(y, sr) = librosa.load(audio_file_path)
plt.figure(figsize=(8, 4))
C = librosa.feature.chroma_cqt(y=y, sr=sr)
fig_ax = librosa.display.specshow(C, y_axis='chroma')
plt.colorbar()
plt.title('Chromagram')
plt.savefig(f'{ctr}.png') |
class OpenObjectAction(BaseAction):
valid_actions = {'OpenObject'}
def get_reward(self, state, prev_state, expert_plan, goal_idx):
if (state.metadata['lastAction'] not in self.valid_actions):
(reward, done) = (self.rewards['invalid_action'], False)
return (reward, done)
s... |
class T5_warpper(nn.Module):
def __init__(self, pretrained_model_name_or_path, bg_word='', dtype='bfloat16', loss_type='CE', use_fed_loss=False, fed_loss_num_classes=1000, inference_text=False, inference_prob=False, inference_prob_fast=False, train_positive_only=False, test_constraint=False, vision_port='encoder', ... |
def test_electrocardiogram():
with suppress_warnings() as sup:
sup.filter(category=DeprecationWarning)
ecg = electrocardiogram()
assert (ecg.dtype == float)
assert_equal(ecg.shape, (108000,))
assert_almost_equal(ecg.mean(), (- 0.))
assert_almost_equal(ecg.std(), 0.) |
def dot(A: dace.float32[N], B: dace.float32[N], out: dace.float32[1]):
def product(i: _[0:N]):
(a << A[i])
(b << B[i])
(o >> out(1, (lambda x, y: (x + y))))
o = (a * b) |
def double_backward_for_global(g_dx0, g_db0, g_dg0, dy, x0, b0, g0, rm, rv, axes, decay_rate, eps):
axes0 = [a for a in range(x0.ndim)]
axes = list((set(axes0) - set(axes)))
v_eps_rsqrt1 = ((rv + eps) ** ((- 1.0) / 2.0))
g_x0 = ((g_dg0 * dy) * v_eps_rsqrt1)
g_g0 = F.sum(((g_dx0 * dy) * v_eps_rsqrt1)... |
def train(model, data, train_idx, optimizer, device):
model = model.to(device)
data = data.to(device)
train_idx = train_idx.to(device)
model.train()
optimizer.zero_grad()
out = model(x=data.x, edge_index=data.edge_index)[train_idx]
loss = F.nll_loss(out, data.y.squeeze(1)[train_idx])
los... |
def representative_dataset(input_shape, num_of_inputs=1):
(yield ([np.random.randn(*input_shape).astype(np.float32)] * num_of_inputs)) |
def test_delta_encode() -> None:
patient = femr.datasets.RawPatient(patient_id=123, events=[femr.datasets.RawEvent(start=datetime.datetime(1999, 7, 2), concept_id=1234), femr.datasets.RawEvent(start=datetime.datetime(1999, 7, 2), concept_id=1234), femr.datasets.RawEvent(start=datetime.datetime(1999, 7, 2, 12), conc... |
class MicoGripper(Gripper):
def __init__(self, count: int=0):
super().__init__(count, 'MicoHand', ['MicoHand_joint1_finger1', 'MicoHand_joint1_finger3']) |
def UniformList(name, typ, size=None, parts=None):
assert ((size is not None) ^ (parts is not None))
def serialize(uniform_list):
return b''.join([typ.serialize(obj) for obj in uniform_list])
def deserialize(buf):
nonlocal size
nonlocal parts
if (len(buf) <= 4):
r... |
def test_write_sentences():
with tempfile.TemporaryDirectory() as tempdir:
raw_filename = os.path.join(tempdir, 'raw.tsv')
with open(raw_filename, 'w') as fout:
fout.write(FBK_SAMPLE)
sentences = split_wikiner.read_sentences(raw_filename, 'utf-8')
copy_filename = os.path.... |
def test_execute_python_code_overwrites_file(random_code: str, random_string: str, agent: Agent):
ai_name = agent.ai_name
destination = os.path.join(agent.config.workspace_path, ai_name, 'executed_code', 'test_code.py')
os.makedirs(os.path.dirname(destination), exist_ok=True)
with open(destination, 'w+'... |
class TestRecipe(unittest.TestCase):
def setUp(self):
Recipe.configure({})
self.r1 = Recipe([Recipe.ONION, Recipe.ONION, Recipe.ONION])
self.r2 = Recipe([Recipe.ONION, Recipe.ONION, Recipe.ONION])
self.r3 = Recipe([Recipe.ONION, Recipe.TOMATO])
self.r4 = Recipe([Recipe.ONION,... |
def test_sugar_4():
resi = ['RC5_1_0', 'RG_69_0', 'RU_37_0']
na = ['Phase', 'tm']
(angles_b, rr) = bb.pucker_angles(fname, residues=resi)
stri = ('%20s ' % '#')
for pp in na:
stri += (' %10s ' % pp)
stri += '\n'
for e in range(angles_b.shape[1]):
stri += ('%20s ' % rr[e])
... |
class SimpleSelfAttention2(nn.Module):
def __init__(self, n_in: int, ks=1):
super().__init__()
self.conv = conv1d(n_in, n_in, ks, padding=(ks // 2), bias=False)
self.gamma = nn.Parameter(tensor([0.0]))
self.n_in = n_in
def forward(self, x):
size = x.size()
x = x.v... |
class DatasetExample():
index: int
answers: List[str]
positive_passages: List[DatasetPassage]
other_passages: List[DatasetPassage]
is_gold_positive: bool
query_token_ids: List[int]
def to_tuple(self) -> tuple:
return (self.index, self.answers, [dataclasses.astuple(p) for p in self.po... |
class HTML():
def __init__(self, web_dir, title, image_subdir='', reflesh=0):
self.title = title
self.web_dir = web_dir
self.img_subdir = image_subdir
self.img_dir = os.path.join(self.web_dir, image_subdir)
if (not os.path.exists(self.web_dir)):
os.makedirs(self.w... |
def test_tree_pandas_output_formats():
clusterer = HDBSCAN(gen_min_span_tree=True).fit(X)
if_pandas(clusterer.condensed_tree_.to_pandas)()
if_pandas(clusterer.single_linkage_tree_.to_pandas)()
if_pandas(clusterer.minimum_spanning_tree_.to_pandas)() |
def print_yellow(info, value='', verbose=True):
if (verbose is False):
return
print((((Fore.YELLOW + ('[%s] ' % info)) + Style.RESET_ALL) + str(value))) |
def check_if_correct_cls(args, model, dataloader, sample_list):
if (args.dataset != 'cifar10'):
return sample_list
model.to(args.device)
count = 0
sample_list_selected = []
with torch.no_grad():
model.eval()
for (index, (name, data, label)) in enumerate(dataloader):
... |
def load_glove(glove_pt, idx_to_token):
glove = pickle.load(open(glove_pt, 'rb'))
dim = len(glove['the'])
matrix = []
for i in range(len(idx_to_token)):
token = idx_to_token[i]
tokens = token.split()
if (len(tokens) > 1):
v = np.zeros((dim,))
for token in ... |
class Job(object):
def __init__(self, op_args):
self._op_args = op_args
def op_args(self):
return self._op_args |
def get_full_profiles(graph, model, model_args, model_kwargs, n_iter, profile_ops, max_depth, basic_blocks, force_no_recomp_scopes, save_memory_mode, use_graph_profiler, use_network_profiler):
print('-I- profiling model (recomp)')
(recomputation_times, max_mem_usage_bytes_r) = get_profiles(graph, model, model_a... |
def format_rule(rule, kg):
rule_str = ''
for j in range(len(rule)):
relation_id = int(rule[j])
rel = kg.id2relation[relation_id]
if (not rel.endswith('_inv')):
rule_str += '-{}-> '.format(rel)
else:
rule_str += '<-{}-'.format(rel)
return rule_str |
def test_calculate_precision_multiple():
pred1 = torch.tensor([6, 7, 8, 9, 10], dtype=torch.long)
pred2 = torch.tensor([1, 2, 3, 4, 5], dtype=torch.long)
pred3 = torch.tensor([1, 2, 3, 5, 7, 6], dtype=torch.long)
true1 = torch.tensor([1, 2, 3, 4, 5], dtype=torch.long)
true2 = torch.tensor([1, 2, 3, ... |
def ngram_evaluation_details(data, LM):
details = []
for sentence in data:
counter = collections.Counter()
for (token, context) in sentence:
counter['num_tokens'] += 1
counter['neglogprob'] += (- LM.logprob(token, context))
details.append(counter)
return detai... |
class Frame(object):
def __init__(self, gdbframe):
self._gdbframe = gdbframe
def older(self):
older = self._gdbframe.older()
if older:
return Frame(older)
else:
return None
def newer(self):
newer = self._gdbframe.newer()
if newer:
... |
class AdamGapAware(GapAwareBase):
def __init__(self, optimizer, from_grad=False):
super().__init__(optimizer)
gap_aware_adam_init(optimizer)
def apply_from_grad(self):
opt_state = self.optimizer.state
with torch.no_grad():
for pg in self.optimizer.param_groups:
... |
def sampleInhomogeneousPoissonProc(tt, lam):
N_t = len(tt)
dt = np.diff(tt)
dlam = np.diff(lam)
trapLam = ((0.5 * dt) * ((2 * lam[1:]) - dlam))
cumLam = np.ravel(np.cumsum(trapLam))
cumLam = np.hstack((np.array([0.0]), cumLam))
intLam = cumLam[(- 1)]
N = np.random.poisson(intLam)
Q =... |
def prepare_align(config):
in_dir = config['path']['corpus_path']
out_dir = config['path']['raw_path']
sampling_rate = config['preprocessing']['audio']['sampling_rate']
max_wav_value = config['preprocessing']['audio']['max_wav_value']
cleaners = config['preprocessing']['text']['text_cleaners']
f... |
_utils.test(require=ti.extension.bls)
def test_scatter_1d_trivial():
_test_bls_stencil(1, 128, bs=32, stencil=((0,),), scatter=True) |
class PVTv2(nn.Module):
def __init__(self, model_name: str='B1', pretrained: str=None, num_classes: int=1000, *args, **kwargs) -> None:
super().__init__()
assert (model_name in pvtv2_settings.keys()), f'PVTv2 model name should be in {list(pvtv2_settings.keys())}'
depths = pvtv2_settings[mode... |
def test_complexity_print_changed_only():
class DummyEstimator(TransformerMixin, BaseEstimator):
nb_times_repr_called = 0
def __init__(self, estimator=None):
self.estimator = estimator
def __repr__(self):
DummyEstimator.nb_times_repr_called += 1
return sup... |
def train(epoch, train_idxs):
global lr, train_acc
model.train()
batch_idx = 1
total_loss = 0
correct = 0
X_train = text_features[train_idxs]
Y_train = text_targets[train_idxs]
for i in range(0, X_train.shape[0], config['batch_size']):
if ((i + config['batch_size']) > X_train.sha... |
def get_model_para_number(model):
total_number = 0
for para in model.parameters():
total_number += torch.numel(para)
return total_number |
class Poisson(_SimpleDistributionMixin):
def __init__(self, rate):
(tensorlib, _) = get_backend()
self.rate = rate
self._pdf = tensorlib.poisson_dist(rate)
def expected_data(self):
return self.rate |
class Identity(nn.Module):
def __init__(self):
pass
def forward(self, x):
return x |
_module()
class Recognizer3D_TL(BaseRecognizer):
def __init__(self, backbone, cls_head=None, neck=None, train_cfg=None, test_cfg=None):
super(Recognizer3D_TL, self).__init__(backbone, cls_head, neck, train_cfg, test_cfg)
self.teacher = load_teacher_model().cuda()
self.teacher.eval()
... |
def Zero_Masking(input_tensor, mask_org):
output = input_tensor.clone()
output.mul_(mask_org)
return output |
def model_fields(model, only=None, exclude=None, field_args=None, converter=None):
converter = (converter or ModelConverter())
field_args = (field_args or {})
model_fields = ((f.attname, f) for f in model._meta.fields)
if only:
model_fields = (x for x in model_fields if (x[0] in only))
elif ... |
class Function_Subprogram_Node(FNode):
_attributes = ('name', 'type', 'ret_name')
_fields = ('args', 'specification_part', 'execution_part') |
.parametrize('k_genuine, k_impostor, T_test', [(2, 2, [[0, 1, 3], [0, 1, 4], [0, 2, 3], [0, 2, 4], [1, 0, 3], [1, 0, 4], [1, 2, 3], [1, 2, 4], [2, 0, 3], [2, 0, 4], [2, 1, 3], [2, 1, 4], [3, 4, 1], [3, 4, 2], [3, 5, 1], [3, 5, 2], [4, 3, 1], [4, 3, 2], [4, 5, 1], [4, 5, 2], [5, 3, 1], [5, 3, 2], [5, 4, 1], [5, 4, 2]]),... |
def rank2_ZZ(n=400, min=0, max=(2 ** 64), system='sage'):
if (system == 'sage'):
A = random_matrix(ZZ, (n + 10), n, x=min, y=(max + 1))
t = cputime()
v = A.rank()
return cputime(t)
elif (system == 'magma'):
code = ('\nn := %s;\nA := RMatrixSpace(IntegerRing(), n+10, n)![R... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--config', help='Please give a config.json file with training/model/data/param details')
parser.add_argument('--gpu_id', help='Please give a value for gpu id')
parser.add_argument('--dataset', help='Please give a value for dataset name'... |
def din_model_fn(features, labels, mode, params):
with tf.variable_scope('dense_input'):
dense_input = fc.input_layer(features, params['dense_feature_columns'])
with tf.variable_scope('category_input'):
category_input = fc.input_layer(features, params['category_feature_columns'])
with tf.var... |
def _convert_example_to_features(example, label_list, max_seq_length, tokenizer):
label_map = {label: i for (i, label) in enumerate(label_list)}
tokens_a = tokenizer.tokenize(example.text_a)
if (len(tokens_a) > (max_seq_length - 2)):
tokens_a = tokens_a[:(max_seq_length - 2)]
tokens = ((['[CLS]'... |
def test_custom_rule(testdir, openapi3_base_url):
testdir.make_test(f'''
from hypothesis.stateful import initialize, rule
schema.base_url = "{openapi3_base_url}"
class APIWorkflow(schema.as_state_machine()):
def validate_response(self, response, case):
pass
(data=st.just("foo"))
def some(self, d... |
.parametrize('dtype', [ti.f32, ti.f64])
.parametrize('solver_type', ['LLT', 'LDLT', 'LU'])
.parametrize('ordering', ['AMD', 'COLAMD'])
_utils.test(arch=ti.x64)
def test_sparse_LLT_solver(dtype, solver_type, ordering):
np_dtype = ti.lang.util.to_numpy_type(dtype)
n = 10
A = np.random.rand(n, n)
A_psd = (... |
class omegaconf_no_object_check():
def __init__(self):
self.old_is_primitive = _utils.is_primitive_type
def __enter__(self):
_utils.is_primitive_type = (lambda _: True)
def __exit__(self, type, value, traceback):
_utils.is_primitive_type = self.old_is_primitive |
def register_functions_ns3_Config(module, root_module):
module.add_function('Connect', 'void', [param('std::string', 'path'), param('ns3::CallbackBase const &', 'cb')])
module.add_function('ConnectWithoutContext', 'void', [param('std::string', 'path'), param('ns3::CallbackBase const &', 'cb')])
module.add_f... |
def test_keyword_assert():
N.set(128)
A = np.random.rand(N.get()).astype(np.float32)
B = np.zeros((N.get(),), dtype=np.float32)
C = True
D = True
try:
keyword_assert(A, B, C, D)
except Exception as e:
print(e)
return True
assert np.allclose(A, B) |
_toolkit()
class Terminal(FunctionToolkit):
name_for_human = 'Terminal command executor'
description_for_human = 'Executes commands in a terminal.'
name_for_model = 'Terminal'
description_for_model = "Executes commands in a terminal on the user's local system. Use it to run valid terminal commands for t... |
def make_file(file_name):
if (not os.path.exists(file_name)):
open(file_name, 'a').close()
return file_name |
class IsProbabilityMatrix(Constraint):
def __call__(self, w):
w *= K.cast(K.greater_equal(w, 0.0), K.floatx())
return (w / (K.epsilon() + K.sum(w, axis=0, keepdims=True))) |
class Plateau(Benchmark):
def __init__(self, dimensions=2):
Benchmark.__init__(self, dimensions)
self._bounds = list(zip(([(- 5.12)] * self.N), ([5.12] * self.N)))
self.global_optimum = [[0.0 for _ in range(self.N)]]
self.fglob = 30.0
self.change_dimensionality = True
def... |
def structure_description(G, latex=False):
import re
def correct_dihedral_degree(match):
return ('%sD%d' % (match.group(1), (int(match.group(2)) // 2)))
description = str(G._gap_().StructureDescription())
description = re.sub('(\\A|\\W)D(\\d+)', correct_dihedral_degree, description)
if (not ... |
def check_fuzzer_ready_one(fuzzer):
global ARGS, FUZZERS, TARGET, OUTPUT
ready_path = os.path.join(OUTPUT, TARGET, fuzzer, 'ready')
if (not os.path.exists(ready_path)):
return False
return True |
def destroy_process_group():
global _backend
global _initialized
torch._C._dist_destroy_process_group()
_backend = dist_backend.UNDEFINED
_initialized = 0 |
class Angle():
def __init__(self, va, vb):
self.va = va
self.vb = vb
def theta(self):
theta = math.degrees(math.acos((((self.va.x * self.vb.x) + (self.va.y * self.vb.y)) / (math.hypot(self.va.x, self.va.y) * math.hypot(self.vb.x, self.vb.y)))))
return theta |
.usefixtures('num_cpus', 'io_type')
class StandardTests(BaseTest):
def setup_class(cls):
cls.qbt = None
cls.qbt_type = None
cls.file_str = ''
cls.op1_str = ''
cls.op2_str = ''
cls.param_name = ''
cls.param_list = None
def test_hamiltonian_is_hermitian(self... |
class Few_Shot_CLI(LightningCLI):
def __init__(self, **kwargs) -> None:
super().__init__(**kwargs)
def add_arguments_to_parser(self, parser: LightningArgumentParser) -> None:
parser.add_argument('is_test', type=bool, default=False, help='whether in testing only mode')
parser.add_argument... |
class VizWizEvalDataset(VQAEvalDataset):
def __init__(self, vis_processor, text_processor, vis_root, ann_paths):
super().__init__(vis_processor, text_processor, vis_root, ann_paths)
def __getitem__(self, index):
ann = self.annotation[index]
if ('val' in ann['image']):
image_p... |
class OSBlockINv3(nn.Module):
def __init__(self, in_channels, out_channels, reduction=4, T=4, **kwargs):
super(OSBlockINv3, self).__init__()
assert (T >= 1)
assert ((out_channels >= reduction) and ((out_channels % reduction) == 0))
mid_channels = (out_channels // reduction)
s... |
def test_Unions_enum_null():
filename = os.path.join(SAMPLES_DIR, 'enum_null_test_data.avro')
data = ['TWO', None, 'ONE', None, 'FOUR', None, 'THREE']
assert (ak.from_avro_file(file=filename).to_list() == data) |
class MobileBertForMultipleChoice(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def main():
total_count = 0
greedy_succ = 0
for index in range(7):
with open((((('./attack_mhm_' + str((index * 400))) + '_') + str(((index + 1) * 400))) + '.csv')) as rf:
reader = csv.DictReader(rf)
for row in reader:
total_count += int(row['Query Times'])
... |
class TranslateY(DauphinTransform):
def __init__(self, name=None, prob=1.0, level=0, max_degree=10):
self.max_degree = max_degree
self.value_range = (0, self.max_degree)
super().__init__(name, prob, level)
def transform(self, pil_img, label, **kwargs):
degree = categorize_value(s... |
class Preprocesser(object):
def __init__(self, opt):
self.opt = opt
def read_unimorph_data(self, file):
raise NotImplementedError
def read_data(self, file):
raise NotImplementedError
def match_edit_script(self, short_script, long_script):
raise NotImplementedError
def... |
def get_CTranS_config():
config = ml_collections.ConfigDict()
config.transformer = ml_collections.ConfigDict()
config.KV_size = 512
config.KV_sizec = 512
config.transformer.num_heads = 4
config.transformer.num_layers = 4
config.expand_ratio = 4
config.transformer.embeddings_dropout_rate ... |
def simulator(theta, X0=30, Y0=1, T=20, subsample=10, flatten=True, obs_noise=0.1, rng=None):
if (rng is None):
rng = np.random.default_rng()
x0 = (X0, Y0)
(alpha, beta, gamma, delta) = theta
t_vec = np.linspace(0, T, T)
pp = odeint(_deriv, x0, t_vec, args=(alpha, beta, gamma, delta))
if... |
def grep(filepath, query):
lines = []
with open(filepath, 'r') as f:
for line in f:
if (query in line):
lines.append(line.rstrip())
return lines |
class ConvDecoder(tf.keras.Model):
def __init__(self, units_full=128, init_size=16, num_filters=[64, 32, 16, 8], deconvlay_config=dict(kernel_size=4, strides=2, padding='SAME', activation='relu', kernel_initializer='he_normal'), actlay_config=dict(activation='relu', kernel_initializer='he_normal'), add_init_fin=Tru... |
def require_running_program(function):
(function)
def wrapper(*args, **kwargs):
try:
gdb.selected_frame()
except RuntimeError:
raise gdb.GdbError('No frame is currently selected.')
return function(*args, **kwargs)
return wrapper |
def crappyhist(a, bins=20, width=30, range_=(0, 1)):
(h, b) = numpy.histogram(a, bins)
for i in range(0, bins):
print('{:12.5f} | {:{width}s} {}'.format(b[i], ('#' * int(((width * h[i]) / numpy.amax(h)))), h[i], width=width))
print('{:12.5f} |'.format(b[bins])) |
_utils.test(debug=True, advanced_optimization=False, require=ti.extension.data64, exclude=[ti.vulkan, ti.metal, ti.opengl, ti.gles])
def test_ipow_negative_exp_i64():
_ipow_negative_exp(ti.i64) |
def get_optimizer(name, params):
if (name == 'SGD'):
return partial(torch.optim.SGD, lr=params['lr'], momentum=params['momentum'], weight_decay=params['weight_decay'])
elif (name == 'Adam'):
return partial(torch.optim.Adam, lr=params['lr'], betas=tuple(params['betas']), weight_decay=params['weig... |
class TimeSeriesTransformerForPrediction(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class RoIDataLayer(object):
def __init__(self, roidb, num_classes):
self._roidb = roidb
self._num_classes = num_classes
self._shuffle_roidb_inds()
def _shuffle_roidb_inds(self):
self._perm = np.random.permutation(np.arange(len(self._roidb)))
self._cur = 0
def _get_nex... |
def fpInfinity(s, negative):
_z3_assert(isinstance(s, FPSortRef), 'sort mismatch')
_z3_assert(isinstance(negative, bool), 'expected Boolean flag')
return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, negative), s.ctx) |
def sobel(image, mask=None, *, axis=None, mode='reflect', cval=0.0):
output = _generic_edge_filter(image, smooth_weights=SOBEL_SMOOTH, axis=axis, mode=mode, cval=cval)
output = _mask_filter_result(output, mask)
return output |
def test_allknn_fit_resample_mode():
allknn = AllKNN(kind_sel='mode')
(X_resampled, y_resampled) = allknn.fit_resample(X, Y)
X_gt = np.array([[(- 0.), (- 0.)], [(- 0.), (- 0.)], [(- 0.), (- 0.)], [(- 0.), 0.], [(- 0.), 0.], [1., 0.], [1., 0.], [(- 0.), 0.], [(- 1.), 0.], [0., 0.], [(- 0.), 0.], [0., 0.49880... |
def main(args):
np.random.seed(args.random_seed)
torch.manual_seed(args.random_seed)
print('tr: {}, va: {}'.format(args.training_samples, args.validation_samples))
print('ds: {}, ln: {}'.format(args.dataset, args.label_noise))
ngm_string = '{:f}'.format(args.negative_gaussian_mean)
K = 2
(tr... |
_grad()
def evaluate(model, data_loader, tokenizer, device, config, info='None'):
model.eval()
metric_logger = utils.MetricLogger(delimiter=' ')
header = f'{info} Evaluation:'
print_freq = 50
for (image0, image1, text, targets) in metric_logger.log_every(data_loader, print_freq, header):
(i... |
def identity_block(input_tensor, kernel_size, filters, stage, block):
(filters1, filters2, filters3) = filters
if (K.image_data_format() == 'channels_last'):
bn_axis = 3
else:
bn_axis = 1
conv_name_base = ((('res' + str(stage)) + block) + '_branch')
bn_name_base = ((('bn' + str(stage... |
class ModelArguments():
model_name_or_path: str = field(metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'})
config_name: Optional[str] = field(default=None, metadata={'help': 'Pretrained config name or path if not the same as model_name'})
tokenizer_name: Optional[s... |
def test_set_max_len():
nlp = stanza.Pipeline(**{'processors': 'tokenize', 'dir': TEST_MODELS_DIR, 'lang': 'en', 'download_method': None, 'tokenize_max_seqlen': 20})
doc = nlp('This is a doc withaverylongtokenthatshouldbereplaced')
assert (len(doc.sentences) == 1)
assert (len(doc.sentences[0].words) == ... |
def make_plots(statistics_file):
print('\n Make Plots')
with open(statistics_file, 'r') as f:
stats = json.load(f)
output_folder = os.path.split(statistics_file)[0]
FILETYPE = 'eps'
numRows = len(configX)
statNames = ['SSIM $\\uparrow$', 'LPIPS $\\downarrow$']
statTags = ['ssim', 'lp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.