code stringlengths 101 5.91M |
|---|
def load_satimage():
data_home = get_data_home()
train_file = os.path.join(data_home, 'satimage.scale.tr')
test_file = os.path.join(data_home, 'satimage.scale.t')
return _todense(_load(train_file, test_file, 'satimage')) |
class LeeBrickellISDAlgorithm(InformationSetAlgorithm):
def __init__(self, code, decoding_interval, search_size=None):
if (search_size is not None):
if ((not isinstance(search_size, (Integer, int))) or (search_size < 0)):
raise ValueError('The search size parameter has to be a po... |
class GAEAEvalTrial(PyTorchTrial):
def __init__(self, context: PyTorchTrialContext) -> None:
self.context = context
self.hparams = AttrDict(context.get_hparams())
self.data_config = context.get_data_config()
self.criterion = nn.CrossEntropyLoss()
self.download_directory = sel... |
def attach_dependencies(doc, response):
if (len(doc.sentences) != len(response.conversions)):
raise ValueError(('Sent %d sentences but got back %d conversions' % (len(doc.sentences), len(response.conversions))))
for (sent_idx, (sentence, conversion)) in enumerate(zip(doc.sentences, response.conversions)... |
class SpeechCommandsDataset(Dataset):
def __init__(self, folder, transform=None, train=True, classes=CLASSES):
all_classes = [d for d in os.listdir(folder) if (os.path.isdir(os.path.join(folder, d)) and (not d.startswith('_')))]
class_to_idx = {classes[i]: i for i in range(len(classes))}
sel... |
def load_banana():
data_home = get_data_home()
train_file = os.path.join(data_home, 'banana', 'banana.all.txt')
return _todense(_load(train_file, None, 'banana')) |
class MemoryChunkArguments(MemoryChunkLonglivedArray):
def setup_args(self):
return je(ri(0, "\n cdef {{ myself.storage_type.c_ptr_type() }} c_args = self._args\n cdef int i\n for i from 0 <= i < len(args):\n {{ myself.storage_type.assign_c_from_py('self._args... |
def _anthropic_create_retry_decorator(llm: ChatOpenAI) -> Callable[([Any], Any)]:
import anthropic
min_seconds = 1
max_seconds = 60
return retry(reraise=True, stop=stop_after_attempt(llm.max_retries), wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds), retry=((((((retry_if_exception_t... |
def mk_lean_auto_spec_name(fn_name: str, namespaces: List[ScopedName]):
prefix = 'auto_spec_'
return get_name_in_open_scopes(ScopedName.from_string(fn_name), namespaces, prefix) |
def all_gather(data, group=None):
if (get_world_size() == 1):
return [data]
if (group is None):
group = _get_global_gloo_group()
if (dist.get_world_size(group) == 1):
return [data]
tensor = _serialize_to_tensor(data, group)
(size_list, tensor) = _pad_to_largest_tensor(tensor,... |
def compile(source, options=None, full_module_name=None, **kwds):
options = CompilationOptions(defaults=options, **kwds)
if (isinstance(source, basestring) and (not options.timestamps)):
return compile_single(source, options, full_module_name)
else:
return compile_multiple(source, options) |
(frozen=True)
class Reference():
output: Output
tags: List[str]
def is_correct(self) -> bool:
return (CORRECT_TAG in self.tags)
def render_lines(self) -> List[str]:
return [f'reference {format_tags(self.tags)}: {format_text(self.output.text)}'] |
def example():
task = generate_task(task_generator_id='picking')
env = CausalWorld(task=task, enable_visualization=True)
env.reset()
for _ in range(50):
(random_intervention_dict, success_signal, obs) = env.do_single_random_intervention()
print('The random intervention performed is ', ra... |
def get_context():
c = NS_context()
c.curl = Array(c.T)
c.W_hat = Function(c.T)
return c |
def run_experiment(argv):
default_log_dir = config.LOG_DIR
now = datetime.datetime.now(dateutil.tz.tzlocal())
rand_id = str(uuid.uuid4())[:5]
timestamp = now.strftime('%Y_%m_%d_%H_%M_%S_%f_%Z')
default_exp_name = ('experiment_%s_%s' % (timestamp, rand_id))
parser = argparse.ArgumentParser()
... |
class ShiftCipher(SymmetricKeyCipher):
def __init__(self, parent, key):
SymmetricKeyCipher.__init__(self, parent, key)
def __eq__(self, other):
return ((type(self) is type(other)) and (self.parent() == other.parent()) and (self.key() == other.key()))
def __call__(self, M):
dom = self... |
class CFGDenoiser(nn.Module):
def __init__(self, model):
super().__init__()
self.inner_model = model
def forward(self, z, sigma, cond, uncond, text_cfg_scale, image_cfg_scale):
cfg_z = einops.repeat(z, '1 ... -> n ...', n=3)
cfg_sigma = einops.repeat(sigma, '1 ... -> n ...', n=3)... |
def run_with_reloader(*args, **kwargs):
from ._reloader import run_with_reloader
return run_with_reloader(*args, **kwargs) |
def get_args(**kwargs):
args = defaults
args = update_args(args, kwargs)
args = process_paths(args)
args = objectify(args)
args.computation.device = 'cpu'
if args.computation.use_gpu:
if (torch.cuda.device_count() > 0):
print('using gpu')
args.computation.device =... |
def convert_kb_vocab(data_dir, cutoff=2):
kb_vocab_file = os.path.join(data_dir, 'celeb_vocab_stats.pkl')
original_vocab_file = os.path.join(data_dir, 'vocab.pkl')
new_vocab_file = os.path.join(data_dir, 'vocab_with_celeb.pkl')
word_counter = pkl.load(open(kb_vocab_file, 'r'))
original_vocab_dict = ... |
def rouge_score(gold: str, pred: str, rouge_type: str, scorer: rouge_scorer.RougeScorer) -> float:
scores = scorer.score(gold, pred)
return scores[rouge_type].fmeasure |
class SawyerCoffeePullEnvV2(SawyerXYZEnv):
def __init__(self):
hand_low = ((- 0.5), 0.4, 0.05)
hand_high = (0.5, 1, 0.5)
obj_low = ((- 0.05), 0.7, (- 0.001))
obj_high = (0.05, 0.75, (+ 0.001))
goal_low = ((- 0.1), 0.55, (- 0.001))
goal_high = (0.1, 0.65, (+ 0.001))
... |
class TuneEvaluatorHoldout(Evaluator):
kind = 'tune_eval_holdout'
def __init__(self, train, test, target, per=None, lossf='rmse', context={}):
super().__init__(context=context)
self.train = load_dataset(train)
self.test = load_dataset(test)
self.lossf = get_lossf(lossf)
s... |
class TestMetrics(object):
.parametrize('m, m_hat, expected', [(np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]]), np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]]), (6, 6, 6)), (np.array([[2, 1, 0], [1, 2, 3], [0, 5, 6]]), np.array([[1, 1, 0], [1, 2, 0], [0, 0, 3]]), (4, 2, 2)), (np.array([[0, 1, 0], [1, 0, 3], [0, 5, 0]]), n... |
def wer(reference, hypothesis, ignore_case=False, delimiter=' '):
(edit_distance, ref_len) = word_errors(reference, hypothesis, ignore_case, delimiter)
if (ref_len == 0):
raise ValueError("Reference's word number should be greater than 0.")
wer = (float(edit_distance) / ref_len)
return wer |
def main(args):
dummy_batch_size = args.max_tokens
if (args.max_tokens is None):
args.max_tokens = 4096
dummy_batch_size = 1024
print(args)
if (not torch.cuda.is_available()):
raise NotImplementedError('Training on CPU is not supported')
torch.cuda.set_device(args.device_id)
... |
def clean_lv_pvn(df: Union[(pd.DataFrame, dd.DataFrame)], column: str, output_format: str='standard', inplace: bool=False, errors: str='coerce', progress: bool=True) -> pd.DataFrame:
if (output_format not in {'compact', 'standard', 'birthdate'}):
raise ValueError(f'output_format {output_format} is invalid. ... |
def load_test_files(root_path, cfg):
spk2idx = {}
npys = cfg['test']['wav_files']
labs = cfg['test']['spk_ids']
Y = []
X = []
for (npy, lab) in zip(npys, labs):
npy_name = os.path.join(root_path, npy)
x = np.load(npy_name)
if (lab not in spk2idx):
spk2idx[lab]... |
class Tag(object):
__slots__ = ['_interpreter', '_abi', '_platform']
def __init__(self, interpreter, abi, platform):
self._interpreter = interpreter.lower()
self._abi = abi.lower()
self._platform = platform.lower()
def interpreter(self):
return self._interpreter
def abi(s... |
_grad()
def test_model(model, data_dir, dataset_list, scale_list, topk_list):
torch.backends.cudnn.benchmark = False
model.eval()
for dataset in dataset_list:
text = '>> {}: Global Retrieval for scale {} with CVNet-Global'.format(dataset, str(scale_list))
print(text)
if (dataset == '... |
class TestConjugateGradientOptimizer(TfGraphTestCase):
def test_cg(self):
a = np.linspace((- np.pi), np.pi, 25).reshape((5, 5))
a = a.T.dot(a)
b = np.linspace((- np.pi), np.pi, 5)
x = cg(a.dot, b, cg_iters=5)
assert np.allclose(a.dot(x), b)
def test_pickleable(self):
... |
class Registry():
mapping = {'builder_name_mapping': {}, 'task_name_mapping': {}, 'processor_name_mapping': {}, 'model_name_mapping': {}, 'lr_scheduler_name_mapping': {}, 'runner_name_mapping': {}, 'state': {}, 'paths': {}}
def register_model(cls, name):
def wrap(model_cls):
from codetf.mode... |
def print_model_with_flops(model, total_flops, total_params, units='GFLOPs', precision=3, ost=sys.stdout, flush=False):
def accumulate_params(self):
if is_supported_instance(self):
return self.__params__
else:
sum = 0
for m in self.children():
sum ... |
def load_ops(result_dir):
(fwd_ops, bwd_ops) = ({}, {})
for opdef in fwd_operators:
op = load_operator(opdef, result_dir, fwd_ops)
fwd_ops[op.name] = op
for opdef in bwd_operators:
op = load_operator(opdef, result_dir, bwd_ops)
bwd_ops[op.name] = op
return (fwd_ops, bwd_o... |
def main(args):
args.override_context = None
args.override_question = None
args.almond_has_multiple_programs = None
args.almond_detokenize_sentence = None
args.do_alignment = None
if (args.main_metric_only and args.extra_metrics):
raise ValueError('Please remove --main_metric_only from y... |
_module()
class FPN(nn.Module):
def __init__(self, in_channels, out_channels, num_outs, start_level=0, end_level=(- 1), add_extra_convs=False, extra_convs_on_inputs=False, relu_before_extra_convs=False, no_norm_on_lateral=False, conv_cfg=None, norm_cfg=None, act_cfg=None, upsample_cfg=dict(mode='nearest')):
... |
def evaluate(iteration):
(gen_i, gen_j) = args.gen_sample.get(args.image_size, (10, 5))
images = []
with torch.no_grad():
for i in range(gen_i):
images.append(G_running_target(fixed_noise[i].cuda(), step=step, alpha=alpha).cpu())
sample_path = f'sample/{args.name}/{str(iteration).zfi... |
def test_transform_for_loop_multi(simple_module, tracer_mock):
adapter = BranchCoverageInstrumentation(tracer_mock)
transformer = InstrumentationTransformer(tracer_mock, [adapter])
simple_module.multi_loop.__code__ = transformer.instrument_module(simple_module.multi_loop.__code__)
assert (simple_module.... |
class VQModel(pl.LightningModule):
def __init__(self, ddconfig, lossconfig, n_embed, embed_dim, ckpt_path=None, ignore_keys=[], image_key='image', colorize_nlabels=None, monitor=None, remap=None, sane_index_shape=False, use_quantize=True, freeze_decoder=False, ckpt_quantize=None):
super().__init__()
... |
class FiniteWords(AbstractLanguage):
def cardinality(self):
if (not self.alphabet()):
return ZZ.one()
return Infinity
def __hash__(self):
return (hash(self.alphabet()) ^ hash('finite words'))
_method
def shift(self):
return InfiniteWords(self.alphabet())
d... |
_test()
def test_constant_type_inference_fpga():
sdfg = make_sdfg()
sdfg.add_constant('constant_array', CONSTANT_ARRAY)
sdfg.add_constant('constant_value', CONSTANT_VALUE)
out = dace.ndarray([CONSTANT_ARRAY.size], dtype=dace.float32)
sdfg(N=CONSTANT_ARRAY.size, output=out)
ref = (CONSTANT_ARRAY ... |
(unsafe_hash=True)
_properties
class DeadDataflowElimination(ppl.Pass):
CATEGORY: str = 'Simplification'
skip_library_nodes = properties.Property(dtype=bool, default=False, desc='If True, does not remove library nodes if their results are unused. Otherwise removes library nodes without side effects.')
remov... |
def _show(image, title):
class UI(tkinter.Label):
def __init__(self, master, im):
if (im.mode == '1'):
self.image = BitmapImage(im, foreground='white', master=master)
else:
self.image = PhotoImage(im, master=master)
super().__init__(master,... |
def gen_model_1label():
na = sympy.Symbol('na', integer=True, positive=True)
nb = sympy.Symbol('nb', integer=True, positive=True)
theta_a = sympy.Symbol('theta_a', real=True, nonnegative=True)
theta_b = sympy.Symbol('theta_b', real=True, nonnegative=True)
t = sympy.Symbol('t', integer=True, nonnegat... |
class CachedBuiltinMethodCallNode(CallNode):
subexprs = ['obj', 'args']
is_temp = True
def __init__(self, call_node, obj, method_name, args):
super(CachedBuiltinMethodCallNode, self).__init__(call_node.pos, obj=obj, method_name=method_name, args=args, may_return_none=call_node.may_return_none, type=... |
class EfficientNetImageProcessorTester(unittest.TestCase):
def __init__(self, parent, batch_size=13, num_channels=3, image_size=18, min_resolution=30, max_resolution=400, do_resize=True, size=None, do_normalize=True, image_mean=[0.5, 0.5, 0.5], image_std=[0.5, 0.5, 0.5]):
size = (size if (size is not None) ... |
def _swig_getattr_nondynamic(self, class_type, name, static=1):
if (name == 'thisown'):
return self.this.own()
method = class_type.__swig_getmethods__.get(name, None)
if method:
return method(self)
if (not static):
return object.__getattr__(self, name)
else:
raise Att... |
def check_samplers_2d_target(name, sampler_orig):
sampler = clone(sampler_orig)
(X, y) = sample_dataset_generator()
y = y.reshape((- 1), 1)
sampler.fit_resample(X, y) |
class GradientStats(object):
def build_gradient_entry(named_parameters):
ave_grads = []
max_grads = []
layers = []
for (n, p) in named_parameters:
if (p.requires_grad and ('bias' not in n)):
layers.append(n)
ave_grads.append(p.grad.abs().me... |
class C2f():
def __init__(self, c1: int, c2: int, n: int=1, shortcut: bool=False, name: str='', g: int=1, e: float=0.5):
self.c = int((c2 * e))
self.cv1 = Conv(c1, (2 * self.c), 1, 1, name=f'{name}.cv1')
self.cv2 = Conv(((2 + n) * self.c), c2, 1, name=f'{name}.cv2')
self.m = [Bottlen... |
def log_details(args):
logging.info('')
logging.info('Arguments received: ')
logging.info('')
for (k, v) in sorted(args.__dict__.items()):
logging.info(f'{k:25}: {v}')
logging.info('\n') |
def visualize_strings(texts, language_code, select=None, colors=None):
lang_pipe = stanza.Pipeline(language_code, processors='tokenize,ner')
for text in texts:
visualize_ner_str(text, lang_pipe, select=select, colors=colors) |
class TestCopyRowsToTensor(hu.HypothesisTestCase):
(input_tensor=get_input_tensors(), **hu.gcs_cpu_only)
def test_copy_rows_to_tensor(self, input_tensor, gc, dc):
dtype = np.random.choice([np.float16, np.float32, np.int32, np.int64], 1)[0]
input_tensor = np.array(input_tensor).astype(dtype)
... |
def calX_term(a, b, c, d):
tot = 0
for n in xrange((d + 1)):
tot += ((binom((- 0.5), n) * ((- 1) ** n)) * HansenCoefficient_term(a, b, c, (d - n)))
return tot |
def inspect_format_method(callable):
if ((not isinstance(callable, (types.MethodType, types.BuiltinMethodType))) or (callable.__name__ not in ('format', 'format_map'))):
return None
obj = callable.__self__
if isinstance(obj, string_types):
return obj |
def setup_fieldsplit_preconditioner(fun: Optional[fenics.Function], ksp: PETSc.KSP, options: _typing.KspOption) -> None:
if (fun is not None):
if (('pc_type' in options.keys()) and (options['pc_type'] == 'fieldsplit')):
function_space = fun.function_space()
if (not (function_space.nu... |
def focal_loss(y_true, y_pred):
y_pred = tf.clip_by_value(y_pred, tf.keras.backend.epsilon(), (1 - tf.keras.backend.epsilon()))
logits = tf.log((y_pred / (1 - y_pred)))
loss = focal_loss_with_logits(logits=logits, targets=y_true, alpha=alpha, gamma=gamma, y_pred=y_pred)
return tf.reduce_mean(loss) |
def train_loop():
data = np.ndarray((args.batchsize, 3, model.insize, model.insize), dtype=np.float32)
data.fill(33333)
total_forward = 0
total_backward = 0
niter = 13
n_dry = 3
label = np.ndarray(args.batchsize, dtype=np.int32)
label.fill(1)
count = 0
timer = Timer()
for i i... |
class Experiments(object):
def __init__(self, experiments):
self._experiments = experiments
def experiments(self):
return self._experiments
def train(self):
for experiment in self._experiments:
Experiments.set_deterministic_on(experiment.seed)
experiment.train... |
def cln_word(word):
if (word[(- 3):] == "'ve"):
return [word[:(- 3)], 'have']
elif (word[(- 2):] == "'d"):
return [word[:(- 2)], ' had']
elif (word[(- 2):] == "'ll"):
return [word[:(- 2)], ' will']
elif (word[(- 2):] == "'m"):
return [word[:(- 2)], ' is']
elif (word[(... |
class OPTDecoderNF(modeling_opt.OPTDecoder):
def __init__(self, config: modeling_opt.OPTConfig):
super().__init__(config)
self.layers = nn.ModuleList([OPTDecoderLayerNF(config) for _ in range(config.num_hidden_layers)])
self.post_init()
def forward(self, *args, **kwargs):
out = s... |
def info(msg: str) -> None:
B = escape_codes['bold_blue']
N = escape_codes['reset']
print(f'{B}:: INFO {msg}{N}', file=sys.stderr, flush=True) |
def test_show_versions(capsys):
with ignore_warnings():
show_versions()
(out, err) = capsys.readouterr()
assert ('python' in out)
assert ('numpy' in out)
info = threadpool_info()
if info:
assert ('threadpoolctl info:' in out) |
class RSHash(BaseModel):
def __init__(self, feature_mins, feature_maxes, sampling_points=1000, decay=0.015, num_components=100, num_hash_fns=1):
self.minimum = feature_mins
self.maximum = feature_maxes
self.m = num_components
self.w = num_hash_fns
self.s = sampling_points
... |
class _PGNMF(NMF):
def __init__(self, n_components=None, solver='pg', init=None, tol=0.0001, max_iter=200, random_state=None, alpha=0.0, l1_ratio=0.0, nls_max_iter=10):
super().__init__(n_components=n_components, init=init, solver=solver, tol=tol, max_iter=max_iter, random_state=random_state, alpha_W=alpha,... |
def set_location_header(request):
url = request.GET.get('next', '/')
response = HttpResponse(status=302)
response['Location'] = url
return response |
def get_key(value, dic, add_1=False, pad=0):
if (add_1 and (value != pad)):
value += 1
if (value == pad):
out = 'pad'
else:
out = list(dic.keys())[list(dic.values()).index(value)]
return out |
class CFuncDeclaratorNode(CDeclaratorNode):
child_attrs = ['base', 'args', 'exception_value']
overridable = 0
optional_arg_count = 0
is_const_method = 0
templates = None
def analyse_templates(self):
if isinstance(self.base, CArrayDeclaratorNode):
from .ExprNodes import TupleN... |
_fl_task(model='model', data_loader='val_loader', device='device')
def validate(model, val_loader, device):
print(f'''
TASK VALIDATE GOT DEVICE {device}
''')
model.eval()
model.to(device)
AVAIL_GPUS = (1 if ('cuda' in device) else 0)
trainer = Trainer(gpus=AVAIL_GPUS, max_epochs=1, callbacks=[Metri... |
def score(system_conllu_file, gold_conllu_file):
evaluation = ud_scores(gold_conllu_file, system_conllu_file)
el = evaluation['Words']
(p, r, f) = (el.precision, el.recall, el.f1)
return (p, r, f) |
def Distinct(*args):
args = _get_args(args)
ctx = _ctx_from_ast_arg_list(args)
if z3_debug():
_z3_assert((ctx is not None), 'At least one of the arguments must be a Z3 expression')
args = _coerce_expr_list(args, ctx)
(_args, sz) = _to_ast_array(args)
return BoolRef(Z3_mk_distinct(ctx.ref... |
class BatchPolopt2(RLAlgorithm, abc.ABC):
def __init__(self, env_spec, policy, baseline, scope=None, max_path_length=500, discount=0.99, gae_lambda=1, center_adv=True, positive_adv=False, fixed_horizon=False, flatten_input=True):
self._env_spec = env_spec
self._policy = policy
self._baseline... |
def test_initialize_local_classifiers_2(digraph_multiple_roots):
digraph_multiple_roots.local_classifier = None
digraph_multiple_roots._initialize_local_classifiers()
assert isinstance(digraph_multiple_roots.local_classifier_, LogisticRegression) |
.parametrize('input_dim, output_dim, hidden_sizes', plain_settings)
def test_std_network_output_values(input_dim, output_dim, hidden_sizes):
init_std = 2.0
module = GaussianMLPModule(input_dim=input_dim, output_dim=output_dim, hidden_sizes=hidden_sizes, init_std=init_std, hidden_nonlinearity=None, std_parameter... |
class FalconInt8Engine(CausalEngine):
config_name: str = 'falcon_int8_engine'
def __init__(self, weights_path: Optional[Union[(str, Path)]]=None):
super().__init__(model_name='tiiuae/falcon-7b', weights_path=weights_path, load_8bit=True, trust_remote_code=True)
self.tokenizer.pad_token = self.to... |
class BertGenerationTokenizer(metaclass=DummyObject):
_backends = ['sentencepiece']
def __init__(self, *args, **kwargs):
requires_backends(self, ['sentencepiece']) |
def test_statement_replace_3(field_mock, default_test_case):
ref = vr.VariableReference(default_test_case, default_test_case.test_cluster.type_system.convert_type_hint(int))
ref_2 = vr.FieldReference(ref, gao.GenericField(default_test_case.test_cluster.type_system.to_type_info(MagicMock), 'foo', default_test_ca... |
class Translator_w_head(nn.Module):
def __init__(self, num_tok, num_tok_out, dim, dim_out, mult=2, depth=5):
super().__init__()
self.trans = translator_tok_dim_v1(num_tok, num_tok_out, dim, dim_out, mult=mult, last_ln=True)
self.tail_1 = translator_tok_dim_v1(num_tok_out, num_tok_out, dim_ou... |
def ansi(s, attr):
if ((os.name != 'nt') and sys.stdout.isatty()):
return ((ansi_codes[attr] + str(s)) + ansi_codes['reset'])
else:
return str(s) |
class StoppingCriteria(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def autolevel(image, footprint, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False):
np_image = np.asanyarray(image)
if (np_image.ndim == 2):
return _apply_scalar_per_pixel(generic_cy._autolevel, image, footprint, out=out, mask=mask, shift_x=shift_x, shift_y=shift_y)
elif (np_image.ndi... |
def write_json(fn, output):
try:
j = json.dumps(output, sort_keys=True, indent=4)
with open(fn, 'w', encoding='utf-8') as f:
print(j, file=f)
except Exception as e:
raise sb.errors.SmartBugsError(e) |
class POI(POIarray):
def __init__(self, parameter, value: (int | float)):
if isinstance(value, Collection):
raise TypeError('A single value for the POI is required.')
super().__init__(parameter=parameter, values=[value])
self._value = value
def value(self):
return sel... |
def p_error(token):
if token:
raise LcmParseError('Unable to parse starting from "{}" on line {}'.format(token.value, token.lineno))
else:
raise LcmParseError('Unexpected end of input') |
class spatial_attn_layer(nn.Module):
def __init__(self, kernel_size=3):
super(spatial_attn_layer, self).__init__()
self.compress = ChannelPool()
self.spatial = BasicConv(2, 1, kernel_size, stride=1, padding=((kernel_size - 1) // 2), relu=False)
def forward(self, x):
x_compress = ... |
def context_decoder_fn_inference(output_fn, encoder_state, embeddings, start_of_sequence_id, end_of_sequence_id, maximum_length, num_decoder_symbols, context_vector, dtype=dtypes.int32, name=None, decode_type='greedy'):
with ops.name_scope(name, 'simple_decoder_fn_inference', [output_fn, encoder_state, embeddings, ... |
def threshold_predictions(y, threshold):
y_out = np.zeros_like(y)
for (ind, pred) in enumerate(y):
y_out[ind] = (1 if (pred > threshold) else 0)
return y_out |
_kl(Beta, Uniform)
def _kl_beta_uniform(p, q):
result = ((- p.entropy()) + (q.high - q.low).log())
result[((q.low > p.support.lower_bound) | (q.high < p.support.upper_bound))] = inf
return result |
def img_to_ndarray(arr: ti.types.ndarray()):
for I in grouped(img):
for c in range(img_c):
arr[(I, c)] = img[I] |
class NodeDataLoader():
def __init__(self, data: Data, stage: Stage, batch_size: Union[(int, Literal['full'])]='full', hops: Optional[int]=None, shuffle: bool=True, drop_last: bool=False, poisson_sampling: bool=False):
self.data = data
self.stage = stage
self.batch_size = batch_size
... |
class GeneralAddAttConvLayer(MessagePassing):
def __init__(self, in_channels, out_channels, improved=False, cached=False, bias=True, **kwargs):
super(GeneralAddAttConvLayer, self).__init__(aggr=cfg.gnn.agg, **kwargs)
self.heads = cfg.gnn.att_heads
self.in_channels = int(((in_channels // self... |
def _replace_tone2_style_dict_to_default(string):
regex = re.compile(RE_TONE2.pattern.replace('$', ''))
d = phonetic_symbol.phonetic_symbol_reverse
def _replace(m):
s = m.group(0)
return (d.get(s) or s)
return regex.sub(_replace, string) |
def on_mouse_motion(x, y, dx, dy):
action[0][0] = (((x / 1920) - 0.5) * 2)
action[0][1] = (((y / 1080) - 0.5) * 2) |
class NonNegativeIntegers(UniqueRepresentation, Parent):
def __init__(self, category=None):
from sage.rings.integer_ring import ZZ
Parent.__init__(self, facade=ZZ, category=InfiniteEnumeratedSets().or_subcategory(category))
def _repr_(self):
return 'Non negative integers'
def __conta... |
(scope='module', autouse=True)
def to_hdf_buffer(hdf_file_path, simulation_verysimple):
simulation_verysimple.simulation_state.to_hdf(hdf_file_path, overwrite=True) |
.mpi
def test_redistribute_matrix_2d_2d_2():
P = dace.symbol('P', dace.int32)
def matrix_2d_2d_2(A: dace.int32[((4 * P), 16)]):
a_grid = dace.comm.Cart_create([2, (P // 2)])
b_grid = dace.comm.Cart_create([P, 1])
B = np.empty_like(A, shape=(8, (8 * P)))
a_arr = dace.comm.Subarray... |
def main(outdir):
pwd = os.path.dirname(__file__)
src_files = (os.path.abspath(__file__), os.path.abspath(os.path.join(pwd, 'functions.json')), os.path.abspath(os.path.join(pwd, '_add_newdocs.py')))
dst_files = ('_ufuncs.pyx', '_ufuncs_defs.h', '_ufuncs_cxx.pyx', '_ufuncs_cxx.pxd', '_ufuncs_cxx_defs.h', '_u... |
def train(hparams, run_opts):
if (hparams['pretrained_wavlm_path'] is not None):
hparams['wavlm'].load_state_dict(torch.load(hparams['pretrained_wavlm_path']))
test(hparams, run_opts, hparams['base_locales'], f'wer_test_before.txt')
for (i, locale) in enumerate(hparams['new_locales']):
old_m... |
class TypeTracerArray(NDArrayOperatorsMixin, ArrayLike):
_dtype: numpy.dtype
_shape: tuple[(ShapeItem, ...)]
def __new__(cls, *args, **kwargs):
raise TypeError("internal_error: the `TypeTracer` nplike's `TypeTracerArray` object should never be directly instantiated")
def __reduce__(self):
... |
class val_Dataset():
def __init__(self, img_list):
self.img_path = opt.path_img
self.img_list = img_list
return
def __getitem__(self, idx):
case_name = self.img_list[idx]
(crop_img, pos_list, tmp_mask) = in_model.get_val_img(self.img_path, case_name)
return_list =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.