code stringlengths 101 5.91M |
|---|
def main(argv=sys.argv[1:]):
p = argparse.ArgumentParser()
p.add_argument('--contigs-db', help='contigs sqlite database')
p.add_argument('node_list_file', help='a cdbg_ids.txt.gz file')
p.add_argument('-o', '--output')
p.add_argument('-v', '--verbose', action='store_true')
args = p.parse_args(ar... |
class FixedpointObj(ctypes.c_void_p):
def __init__(self, fixedpoint):
self._as_parameter_ = fixedpoint
def from_param(obj):
return obj |
def getCoordPoints(handRight):
handRightPoints = []
handRightX = []
handRightY = []
for x in range(0, len(handRight), 3):
handRightX.append(handRight[x])
for x in range(1, len(handRight), 3):
handRightY.append(handRight[x])
for x in range(len(handRightX)):
handRightPoints... |
def have_prerequisites(debug=True):
try:
from notebook.notebookapp import NotebookApp
return True
except ImportError:
if debug:
import traceback
traceback.print_exc()
return False |
class Program():
def __init__(self, name, version_cmd, version_regex, environment_var=None, debug=False):
self.name = name
self.debug = debug
if ((environment_var is not None) and (environment_var in os.environ)):
if self.debug:
print(self.name, '- getting path fr... |
def run(data_ids: List[int], methods: List[Callable[([], operations.GraphOfOperations)]], budget: float, lm_name: str) -> float:
orig_budget = budget
data_path = os.path.join(os.path.dirname(__file__), 'sorting_032.csv')
data = []
with open(data_path, 'r') as f:
reader = csv.reader(f)
ne... |
def conv1x1_bn_relu(in_planes, out_planes, stride=1):
return nn.Sequential(nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, padding=0), nn.BatchNorm2d(out_planes), nn.ReLU(inplace=True)) |
def _get_item_settings(item, marker=None):
timeout = func_only = None
if (not marker):
marker = item.get_closest_marker('timeout')
if (marker is not None):
settings = _parse_marker(item.get_closest_marker(name='timeout'))
timeout = settings.timeout
func_only = bool(settings.f... |
def test_sine_positional_encoding(num_feats=16, batch_size=2):
with pytest.raises(AssertionError):
module = SinePositionalEncoding(num_feats, scale=(3.0,), normalize=True)
module = SinePositionalEncoding(num_feats)
(h, w) = (10, 6)
mask = (torch.rand(batch_size, h, w) > 0.5).to(torch.int)
as... |
def longest_gap_duration(df: DataFrame, obj_frequencies: DataFrame) -> float:
if (len(obj_frequencies.index) == 0):
return np.nan
lgd = 0
missed_tracks = 0
for gt_tracking_id in obj_frequencies.index:
dfo = df.noraw[(df.noraw.OId == gt_tracking_id)]
matched = set(dfo[(dfo.Type !=... |
def load(model, model_path):
state_dict = torch.load(model_path)
model.load_state_dict({k: v for (k, v) in state_dict.items() if (k in model.state_dict())}) |
def test_arraytype_categorical_1():
pytest.importorskip('pyarrow')
text = str(ak.str.to_categorical(ak.Array(['one', 'one', 'two', 'three', 'one', 'three'])).type)
parsedtype = ak.types.from_datashape(text, highlevel=True)
assert isinstance(parsedtype, ak.types.ArrayType)
assert (str(parsedtype) == ... |
def test_compare_op_int(dynamic_instr, dummy_module):
(dynamic, instr) = dynamic_instr
dummy_module.compare_op_dummy.__code__ = instr.instrument_module(dummy_module.compare_op_dummy.__code__)
res = dummy_module.compare_op_dummy(10, 11)
assert (res == 1)
assert (dynamic.get_all_constants_for(int) == ... |
def color_jitter_rand(image, brightness=0, contrast=0, saturation=0, hue=0, impl='simclrv2'):
with tf.name_scope('distort_color'):
def apply_transform(i, x):
def brightness_foo():
if (brightness == 0):
return x
else:
return ... |
class SubsetExtractor():
def __init__(self, config):
super().__init__()
self.data_dir = config.data_dir
self.save_data_dir = config.save_data_dir
def extract_text(self, type: str):
data_path = self._get_json_path(type)
print(f'Reading json {data_path}')
data_json ... |
def check_edge_case_of_sample_int(sample_without_replacement):
with pytest.raises(ValueError):
sample_without_replacement(0, 1)
with pytest.raises(ValueError):
sample_without_replacement(1, 2)
assert (sample_without_replacement(0, 0).shape == (0,))
assert (sample_without_replacement(1, 1... |
def softmax(logits, dim=(- 1), name=None):
try:
return tf.nn.softmax(logits, dim=dim, name=name)
except TypeError:
return tf.nn.softmax(logits, axis=dim, name=name) |
def test(hparams, run_opts, locales, wer_file='wer_test.txt'):
for locale in locales:
run_on_main(prepare_common_voice, kwargs={'locales': [locale], 'data_folder': hparams['data_folder'], 'max_durations': hparams['max_durations']})
if (locale in ['zh-CN', 'ja']):
hparams['wer_computer'] ... |
class SemistandardTableaux_all(SemistandardTableaux, DisjointUnionEnumeratedSets):
def __init__(self, max_entry=None):
if (max_entry is not PlusInfinity()):
self.max_entry = max_entry
def SST_n(n):
return SemistandardTableaux_size(n, max_entry)
DisjointUni... |
class CoefficientDrifter():
drift_interval: int
transition_period: int = 0
transition_type: str = 'linear'
seasonal: bool = False
base_coefficient_weight: float = 0.0
effective_dim_action_context: Optional[int] = None
effective_dim_context: Optional[int] = None
random_state: int = 12345
... |
def create_go_mask(adata, go2gene):
genes = adata.var_names
gene2index = {g: i for (i, g) in enumerate(genes)}
GO_IDs = sorted(go2gene.keys())
go_mask = []
for go in GO_IDs:
go_genes = go2gene[go]
go_mask.append([gene2index[gene] for gene in go_genes])
return go_mask |
def generate(max_time, n_sequences, filename='stationary_renewal'):
(times, nll) = ([], [])
for _ in range(n_sequences):
s = np.sqrt(np.log(((6 * 6) + 1)))
mu = (((- s) * s) / 2)
tau = lognorm.rvs(s=s, scale=np.exp(mu), size=1000)
lpdf = lognorm.logpdf(tau, s=s, scale=np.exp(mu))... |
class LabelingFunction():
def __init__(self, name, label):
self.name = name
self.label = label |
class iCIFAR100(iData):
use_path = False
train_trsf = [transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ColorJitter(brightness=(63 / 255)), transforms.ToTensor()]
test_trsf = [transforms.ToTensor()]
common_trsf = [transforms.Normalize(mean=(0.5071, 0.4867, 0.4408), std... |
.parametrize('create_solver', [f for (name, f) in ss.solvers.items() if (name != 'yices2')])
def test_identity_visit_basic(create_solver):
solver = create_solver(False)
bv32 = solver.make_sort(ss.sortkinds.BV, 32)
x = solver.make_symbol('x', bv32)
y = solver.make_symbol('y', bv32)
a = solver.make_sy... |
def bs(F, K, V, o='call'):
w = 1
if (o == 'put'):
w = (- 1)
elif (o == 'otm'):
w = ((2 * (K > 1.0)) - 1)
sv = np.sqrt(V)
d1 = ((np.log((F / K)) / sv) + (0.5 * sv))
d2 = (d1 - sv)
P = (((w * F) * norm.cdf((w * d1))) - ((w * K) * norm.cdf((w * d2))))
return P |
class MemnetTest(absltest.TestCase):
def test_simple_run_and_check_shapes(self):
batch_size = 64
vocab_size = 177
embedding_size = 64
sentence_size = 11
memory_size = 320
linear_output_size = 128
num_hops = 2
use_ln = True
def forward_fn(querie... |
class Parser():
def __init__(self, name, batch_size=64, language_code=None):
self._parser = load_trained_model(name)
if torch.cuda.is_available():
self._parser.cuda()
if (language_code is not None):
self._language_code = language_code
else:
self._l... |
def get_imdb(name):
if (name not in __sets):
raise KeyError('Unknown dataset: {}'.format(name))
return __sets[name]() |
def _data_kwargs_from_dataset_key(dataset, key):
if (key in dataset.get_target_list()):
available_for_inference = False
else:
available_for_inference = True
dim = dataset.get_data_dim(key)
shape = ([None] + list(dataset.get_data_shape(key)))
sparse = dataset.is_data_sparse(key)
d... |
class ABCFolderDataset(FolderDataset):
_extension = 'abc'
def read(self, filename: Tuple[(str, Tuple[(int, int)])]) -> Music:
(filename_, (start, end)) = filename
data = []
with open(filename_, encoding='utf-8') as f:
for (idx, line) in enumerate(f):
if ((star... |
def main_train():
kwargs = {'num_workers': 1, 'pin_memory': True}
test_loader = torch.utils.data.DataLoader(datasets.MNIST('./data', train=False, transform=transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])), batch_size=args.test_batch_size, shuffle=True, **kwargs)
model... |
class ResBlock(chainer.Chain):
def __init__(self, ch, norm='instance', activation='relu', equalised=False, separable=False, skip_conv=False):
super(ResBlock, self).__init__()
self.activation = activation_func[activation]
nobias = False
with self.init_scope():
self.c0 = Eq... |
def _dist_matrix(x, y, c):
sqrt_c = (c ** 0.5)
return ((2 / sqrt_c) * artanh((sqrt_c * torch.norm(_mobius_addition_batch((- x), y, c=c), dim=(- 1))))) |
def print_correlation(topk_systems, metric_pairs):
headers = ['metric_pair', 'pearson', 'spearman', 'kendalltau']
print_list = []
for pair in metric_pairs:
if (('bart_en_sim' in pair[1]) or ('bart_sim' in pair[1])):
continue
m1_scores = []
m2_scores = []
for score... |
class LM(sb.core.Brain):
def compute_forward(self, batch, stage):
batch = batch.to(self.device)
(tokens_bos, _) = batch.tokens_bos
logits = self.hparams.model(tokens_bos)
pred = self.hparams.log_softmax(logits)
return pred
def compute_objectives(self, predictions, batch, ... |
def get_plot_label(xm, ym):
template = '%(xlabel)s-%(ylabel)s tradeoff - %(updown)s and to the %(leftright)s is better'
return (template % {'xlabel': xm['description'], 'ylabel': ym['description'], 'updown': get_up_down(ym), 'leftright': get_left_right(xm)}) |
def louvain(G, resolution=1, eps=0.001, unit_weights=True, copy_graph=False):
if copy_graph:
F = G.copy()
else:
F = G
if unit_weights:
for (u, v) in F.edges():
F[u][v]['weight'] = 1
cluster = maximize(F, resolution, eps)
n = len(cluster)
k = len(set(cluster.va... |
def train_fn():
global epoch, args
epoch = 0
while (epoch < args.epochs):
epoch += 1
(loss, jac) = train(epoch)
valid_loss = test(epoch, testloader)
status = (str(os.getpid()) + ' Epoch {}/{} | Loss {:3.4f} | jac {:3.4f}'.format(epoch, args.epochs, loss, jac))
print(s... |
def read_config(config_path):
with open(config_path, 'r') as conf:
config_dict = convert_values(yaml.load(conf, Loader=YamlUniqueLoader))
if ('seml' not in config_dict):
raise ConfigError("Please specify a 'seml' dictionary.")
seml_dict = config_dict['seml']
del config_dict['seml']
f... |
class ModelArgs():
attention_window: int = field(default=512, metadata={'help': 'Size of attention window'})
max_pos: int = field(default=4096, metadata={'help': 'Maximum position'}) |
class MemoryReportBuilder(ReportBuilderBase):
Version = 1
def __init__(self, file=None):
super().__init__(file)
def add_weight_entry(self, weight_name, size_bytes, grad_size_bytes, stack_context):
cursor = self._connection.cursor()
cursor.execute(queries.add_weight_entry, (weight_nam... |
def register_Ns3EpcSgwPgwApplication_methods(root_module, cls):
cls.add_constructor([param('ns3::EpcSgwPgwApplication const &', 'arg0')])
cls.add_constructor([param('ns3::Ptr< ns3::VirtualNetDevice > const', 'tunDevice'), param('ns3::Ptr< ns3::Socket > const', 's1uSocket')])
cls.add_method('AddEnb', 'void',... |
def launch_process_helper(args, proc_env=None, cwd=None):
if (proc_env is None):
proc_env = os.environ.copy()
with subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=proc_env, cwd=cwd) as proc:
(cmd_out, cmd_err) = proc.communicate()
if (cmd_out is not None):
... |
class QueryBertLikeLayer(torch.nn.Module):
def __init__(self, origin: transformers.models.bert.modeling_bert.BertLayer, share_weights: bool=False):
super().__init__()
self.attention = QueryBertLikeAttention(origin.attention, share_weights=share_weights)
if share_weights:
self.int... |
def run(n, stmt, fuzzer_cls):
float_iter = fuzzer_cls(seed=0, dtype=torch.float32).take(n)
int_iter = fuzzer_cls(seed=0, dtype=torch.int32).take(n)
raw_results = []
for (i, (float_values, int_values)) in enumerate(zip(float_iter, int_iter)):
(float_tensors, float_tensor_params, float_params) = f... |
def _build_demo_runner():
class Model(nn.Module):
def __init__(self):
super().__init__()
self.linear = nn.Linear(2, 1)
def forward(self, x):
return self.linear(x)
def train_step(self, x, optimizer, **kwargs):
return dict(loss=self(x))
d... |
def Replace(s, src, dst):
ctx = _get_ctx2(dst, s)
if ((ctx is None) and is_expr(src)):
ctx = src.ctx
src = _coerce_seq(src, ctx)
dst = _coerce_seq(dst, ctx)
s = _coerce_seq(s, ctx)
return SeqRef(Z3_mk_seq_replace(src.ctx_ref(), s.as_ast(), src.as_ast(), dst.as_ast()), s.ctx) |
class Multinomial(Distribution):
arg_constraints = {'probs': constraints.simplex, 'logits': constraints.real}
def mean(self):
return (self.probs * self.total_count)
def variance(self):
return ((self.total_count * self.probs) * (1 - self.probs))
def __init__(self, total_count=1, probs=Non... |
class MulConstant(Module):
def __init__(self, constant_scalar, inplace=False):
super(MulConstant, self).__init__()
self.constant_scalar = constant_scalar
self.inplace = inplace
def updateOutput(self, input):
if self.inplace:
input.mul_(self.constant_scalar)
... |
def get_declr(module: Module, x: EntryBase, with_docs=False):
out = []
if with_docs:
out += get_api_ref(module, x)
ty = type(x)
if (ty is BuiltInType):
out += ['']
elif (ty is Alias):
out += [f'typedef {get_type_name(x.alias_of)} {get_type_name(x)};']
elif (ty is Definiti... |
class Obstacle(PhysicalObject):
def __init__(self, *args, **kwargs):
kwargs['color'] = (80, 80, 80)
super(Obstacle, self).__init__('obstacle.png', *args, **kwargs)
def create_physical_entity(self):
body = self._engine.CreateStaticBody(position=self.physical_position)
body.CreateP... |
class OverlapPatchEmbed(nn.Module):
def __init__(self, img_size=224, patch_size=7, stride=4, in_chans=3, embed_dim=768):
super().__init__()
img_size = to_2tuple(img_size)
patch_size = to_2tuple(patch_size)
self.img_size = img_size
self.patch_size = patch_size
(self.H,... |
def run(dataset, model, str_optimizer, str_preconditioner, runs, epochs, lr, weight_decay, early_stopping, logger, momentum, eps, update_freq, gamma, alpha, hyperparam):
if (logger is not None):
if hyperparam:
logger += f'-{hyperparam}{eval(hyperparam)}'
path_logger = os.path.join(path_r... |
def _coco_box_to_bbox(box):
bbox = np.array([box[0], box[1], (box[0] + box[2]), (box[1] + box[3])], dtype=np.int32)
return bbox |
class NormalizingFlowDensity(nn.Module):
def __init__(self, dim, flow_length, flow_type='planar_flow'):
super(NormalizingFlowDensity, self).__init__()
self.dim = dim
self.flow_length = flow_length
self.flow_type = flow_type
self.mean = nn.Parameter(torch.zeros(self.dim), requ... |
def _os_system(cmd: list, save_log: bool=False):
cmd_str = ''
for s in cmd:
cmd_str += (str(s) + ' ')
if (not save_log):
print('[Running]: {}'.format(cmd_str))
ret = os.system(cmd_str)
if (ret == 0):
print('[Success]: {}'.format(cmd_str))
else:
... |
def test_num_6():
content = ak.contents.numpyarray.NumpyArray(np.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9]))
offsets = ak.index.Index64(np.array([0, 3, 3, 5, 6, 9]))
array = ak.Array(ak.contents.listoffsetarray.ListOffsetArray(offsets, content))
cuda_array = ak.to_backend(array, 'cuda')
as... |
def GenerateSM80_TensorOp_16816(manifest, cuda_version):
if (not CudaToolkitVersionSatisfies(cuda_version, 11, 0)):
return
layouts = [(LayoutType.ColumnMajor, LayoutType.ColumnMajor, LayoutType.ColumnMajor), (LayoutType.ColumnMajor, LayoutType.RowMajor, LayoutType.ColumnMajor), (LayoutType.RowMajor, Lay... |
def match_regex(rgx, span):
m = (re.search(rgx, span.text, re.I) if (type(rgx) is str) else rgx.search(span.text))
if (not m):
return None
(i, j) = m.span()
if (type(span) is Span):
i += span.char_start
j += span.char_start
return Span(i, (j - 1), span.sentence)
retur... |
def prepare_common_voice(data_folder, save_folder, train_tsv_file=None, dev_tsv_file=None, test_tsv_file=None, accented_letters=False, language='en', skip_prep=False):
if skip_prep:
return
if (train_tsv_file is None):
train_tsv_file = (data_folder + '/train.tsv')
else:
train_tsv_file... |
def _is_checked_function(item):
if (not inspect.isfunction(item)):
return False
if item.__name__.startswith('_'):
return False
mod = item.__module__
if ((not mod.startswith('skglm.')) or mod.endswith('estimator_checks')):
return False
return True |
def test_slate_ope_performance_using_independent_log():
n_unique_action = 10
len_list = 3
dim_context = 2
reward_type = 'binary'
random_state = 12345
n_rounds = 1000
reward_structure = 'independent'
click_model = None
behavior_policy_function = linear_behavior_policy_logit
reward... |
def save_results(path, name, img, gt_depth, pred_depth, validmask, cv_mask, costvolume):
savepath = os.path.join(path, name)
device = img.device
(bs, _, h, w) = img.shape
img = (img[(0, ...)].permute(1, 2, 0).detach().cpu().numpy() + 0.5)
gt_depth = gt_depth[(0, ...)].permute(1, 2, 0).detach().cpu()... |
def copy_encoder(hf_encoder, pt_model):
hf_encoder.embeddings.token_embedding.weight = pt_model.token_embedding.weight
hf_encoder.embeddings.position_embedding.weight.data = pt_model.positional_embedding
copy_linear(hf_encoder.final_layer_norm, pt_model.ln_final)
copy_layers(hf_encoder.encoder.layers, p... |
def visualize_size_wise_sampling_scores(filename, tp=False):
key = 'micro'
methods = ['kd_kldiv_wa1', 'cn_lfc_mr', 'kd_kldiv_ilos', 'ce_online_ewc']
lr = {'pamap': '0.01', 'dsads': '0.01', 'twor': '0.1', 'milan': '0.01'}
samplings = ['random', 'icarl', 'kmeans', 'boundary', 'fwsr']
sizes = ([2, 4, 6... |
def results2json(dataset, results, out_file):
if isinstance(results[0], list):
json_results = det2json(dataset, results)
elif isinstance(results[0], tuple):
json_results = segm2json(dataset, results)
elif isinstance(results[0], np.ndarray):
json_results = proposal2json(dataset, resul... |
def combine_parsed_consensus_results(results):
relays = {}
network_stats = {}
(min_unix_time, max_unix_time) = (None, None)
(counts_t, counts_eg, counts_e, counts_g, counts_m) = ([], [], [], [], [])
(weights_t, weights_eg, weights_e, weights_g, weights_m) = ([], [], [], [], [])
for result in res... |
def draw_keypoints(img, corners, color=(0, 255, 0), radius=3, s=3):
img = np.repeat(cv2.resize(img, None, fx=s, fy=s)[(..., np.newaxis)], 3, (- 1))
for c in np.stack(corners).T:
cv2.circle(img, tuple((s * np.flip(c, 0))), radius, color, thickness=(- 1))
return img |
class ExpLeakSqueeze(ExpLeak, SqueezeMixin):
def __init__(self, batch_size=None, num_timesteps=None, **kwargs):
super().__init__(**kwargs)
self.squeeze_init(batch_size, num_timesteps)
def forward(self, input_data: torch.Tensor) -> torch.Tensor:
return self.squeeze_forward(input_data, sup... |
def _conv_block(inputs, filters, alpha, kernel=(3, 3), strides=(1, 1)):
channel_axis = (1 if (K.image_data_format() == 'channels_first') else (- 1))
filters = int((filters * alpha))
x = Conv2D(filters, kernel, padding='same', use_bias=False, strides=strides, name='conv1')(inputs)
x = BatchNormalization(... |
def eval_step(eval_len=args.seq_len, ood=False, n_evals=10):
model.eval()
total_loss = 0.0
total_acc = 0.0
for _ in range(n_evals):
(data, label, op) = rules(args.batch_size, eval_len, args.gt_rules, args.order, args.d_dim, args.data_seed, ood)
data = torch.Tensor(data).to(device)
... |
class TripletLoss(object):
def __init__(self, margin=None):
self.margin = margin
if (margin is not None):
self.ranking_loss = nn.MarginRankingLoss(margin=margin)
else:
self.ranking_loss = nn.SoftMarginLoss()
def __call__(self, global_feat, labels, normalize_featur... |
def test_maximum_bipartite_matching_explicit_zeros_count_as_edges():
data = [0, 0]
indices = [1, 0]
indptr = [0, 1, 2]
graph = csr_matrix((data, indices, indptr), shape=(2, 2))
x = maximum_bipartite_matching(graph, perm_type='row')
y = maximum_bipartite_matching(graph, perm_type='column')
ex... |
class SymforcePyTorchTest(TestCase):
((importlib.util.find_spec('torch') is None), 'Requires PyTorch')
def test_backend_test_function(self) -> None:
import torch
backend_test_function = codegen_util.load_generated_function('backend_test_function', TEST_DATA_DIR)
backend_test_function(tor... |
def plot_entropy(X, attn):
(unif_H, attn_H) = ([], [])
for i in range(len(X)):
L = len(X[i])
h = attn[i][1:(L - 1)]
a = (h * np.log(np.clip(h, a_min=1e-08, a_max=None)))
a = (- a.sum())
unif_H.append(np.log((L - 2)))
attn_H.append(a)
plt.scatter(unif_H, attn_H... |
def got() -> operations.GraphOfOperations:
operations_graph = operations.GraphOfOperations()
plans = operations.Generate(1, 1)
operations_graph.append_operation(plans)
for i in range(1, 3):
list_id = f'List {i}'
sub_list = operations.Selector((lambda thoughts, list_id=list_id: [thought f... |
class RandomJournal():
def __init__(self):
self._entries: List[RandomJournalEntry] = []
self._cur_entry_idx = 0
self._graph_reader_nodes: List[Tuple[(Tensor, rf.RunCtx)]] = []
def append(self, *, distribution: str, mean: Optional[Union[(int, float, Tensor)]]=None, stddev: Optional[Union[... |
def get_topk_classes(explainer, image, k=5):
class_masks = explainer(image)[0].sigmoid()
class_mask_means = class_masks.mean(dim=(1, 2))
(values, topk_classes) = class_mask_means.topk(k)
return (values.cpu().numpy(), topk_classes.cpu().numpy()) |
def define_flags_with_default(**kwargs):
for (key, val) in kwargs.items():
if isinstance(val, ConfigDict):
config_flags.DEFINE_config_dict(key, val)
elif isinstance(val, bool):
absl.flags.DEFINE_bool(key, val, 'automatically defined flag')
elif isinstance(val, int):
... |
.parametrize('func', [ak.covar, ak.corr, ak.linear_fit])
def test_covar(func):
assert isinstance(func([[1, 2, 3, 4], [5], [10]], [[4, 4, 0, 2], [1], [10]], axis=(- 1), highlevel=True), ak.Array)
assert isinstance(func([[1, 2, 3, 4], [5], [10]], [[4, 4, 0, 2], [1], [10]], axis=(- 1), highlevel=False), ak.content... |
def SuperNNova_stats_and_plots_thread(df, settings, plots=True, debug=False):
pd.set_option('max_colwidth', 1000)
print(lu.str_to_greenstr('STATISTICS USED IN SUPERNNOVA'))
baseline(df, settings, plots, debug)
(df_delta, df_delta_ood) = sm.get_delta_metrics(df, settings)
bayesian(df, df_delta, df_de... |
def pdf(x, mu, sigma):
x = ((x - mu) / sigma)
return (numpy.exp(((- (x ** 2)) / 2)) / (numpy.sqrt((2 * numpy.pi)) * sigma)) |
def main():
cfg = get_cfg()
cfg.merge_from_file(args.cfg_file)
cfg.merge_from_list(args.opts)
cfg = infer_cfg(cfg)
cfg.freeze()
if cfg.MODEL_ANALYSE:
model = Generalized_CNN(cfg)
model.eval()
analyser = Analyser(cfg, model, param_details=False)
n_params = analyser... |
def test_UnionArray_FIXME():
content0 = ak.operations.from_iter([[1.1, 2.2, 3.3], [], [4.4, 5.5]], highlevel=False)
content1 = ak.operations.from_iter(['one', 'two', 'three', 'four', 'five'], highlevel=False)
tags = ak.index.Index8([])
index = ak.index.Index32([])
array = ak.contents.UnionArray(tags... |
class Function_Hankel1(BuiltinFunction):
def __init__(self):
BuiltinFunction.__init__(self, 'hankel1', nargs=2, conversions=dict(maple='HankelH1', mathematica='HankelH1', maxima='hankel1', sympy='hankel1', fricas='hankelH1'))
def _evalf_(self, nu, z, parent, algorithm=None):
return _mpmath_utils... |
def pt_project(train_queue, valid_queue, model, architect, criterion, optimizer, epoch, args, infer, query):
def project(model, args):
(num_edge, num_op) = (model.num_edge, model.num_op)
remain_eids = torch.nonzero(model.candidate_flags).cpu().numpy().T[0]
if (args.edge_decision == 'random')... |
def compatible_tags(python_version=None, interpreter=None, platforms=None):
if (not python_version):
python_version = sys.version_info[:2]
platforms = list((platforms or _platform_tags()))
for version in _py_interpreter_range(python_version):
for platform_ in platforms:
(yield Ta... |
def test_invalid_json_minor():
json_str = '{"name": "John", "age": 30, "city": "New York",}'
assert (fix_and_parse_json(json_str, try_to_fix_with_gpt=False) == {'name': 'John', 'age': 30, 'city': 'New York'}) |
def _get_codegen_gemm_opts(node, state, sdfg, adesc, bdesc, cdesc, alpha, beta, cdtype, func) -> Dict[(str, Any)]:
from dace.codegen.common import sym2cpp
from dace.libraries.blas.blas_helpers import get_gemm_opts
((_, _, ashape, astride), (_, _, bshape, bstride), (_, _, cshape, cstride)) = _get_matmul_oper... |
class Dict(object):
def __init__(self, data=None, lower=False, seq_len=50):
self.idxToLabel = {}
self.labelToIdx = {}
self.frequencies = {}
self.lower = lower
self.seq_length = seq_len
self.special = []
if (data is not None):
if (type(data) == str)... |
def np_func_to_list(func):
if (not func.is_numpy_attribute):
return []
return (np_func_to_list(func.obj) + [func.attribute]) |
class ReflectionPad1d(_ReflectionPadNd):
padding: Tuple[(int, int)]
def __init__(self, padding: _size_2_t) -> None:
super(ReflectionPad1d, self).__init__()
self.padding = _pair(padding) |
def is_non_empty_query(query: dict[(str, Any)]) -> bool:
result = []
for (key, values) in query.items():
if (isinstance(values, str) or (not hasattr(values, '__iter__'))):
values = [values]
for value in values:
if (value is not None):
result.append(((key.e... |
class LevitModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class InterfaceFunctionElement(SageObject):
def __init__(self, obj, name):
self._obj = obj
self._name = name
def _repr_(self):
return ('%s' % self._name)
def __call__(self, *args, **kwds):
return self._obj.parent().function_call(self._name, ([self._obj] + list(args)), kwds)
... |
class QATConfig():
def __init__(self, weight_training_method: TrainingMethod=TrainingMethod.STE, activation_training_method: TrainingMethod=TrainingMethod.STE, weight_quantizer_params_override: Dict=None, activation_quantizer_params_override: Dict=None):
self.weight_training_method = weight_training_method
... |
def _dummy_bbox_sampling(proposal_list, gt_bboxes, gt_labels):
num_imgs = 1
feat = torch.rand(1, 1, 3, 3)
assign_config = dict(type='MaxIoUAssigner', pos_iou_thr=0.5, neg_iou_thr=0.5, min_pos_iou=0.5, ignore_iof_thr=(- 1))
sampler_config = dict(type='RandomSampler', num=512, pos_fraction=0.25, neg_pos_u... |
def to_eval_kwargs(args):
kwargs_dict = {'eval_log_dir': args.eval_log_dir, 'log_dir': args.log_dir, 'loss_mode': args.loss_mode, 'run_id': args.run_id}
return kwargs_dict |
_utils.test(arch=supported_archs_taichi_ndarray)
def test_gaussian_kernel():
M_PI = 3.
def gaussian(x, sigma):
return (ti.exp(((- 0.5) * ti.pow((x / sigma), 2))) / (sigma * ti.sqrt((2.0 * M_PI))))
def fill_gaussian_kernel(ker: ti.types.ndarray(ti.f32, ndim=1), N: ti.i32):
sum = 0.0
f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.