code stringlengths 101 5.91M |
|---|
_utils.test(arch=get_host_arch_list())
def test_assign2_static():
a = ti.field(ti.f32, ())
b = ti.field(ti.f32, ())
def func():
(c, d) = ti.static(b, a)
(c[None], d[None]) = (2, 3)
func()
assert (a[None] == 3)
assert (b[None] == 2) |
class Messages(BaseMessages):
ChatCompleted = 'Congratulations, you successfully completed the task!'
ChatIncomplete = "Sorry, you weren't able to complete the task."
Redirect = 'Sorry, that chat did not meet our acceptance criteria.' |
def prepare_infer_only_dataloader(full_dataset_class_str, dictionary, im_dir, im_suffix, transforms, batch_size=1, indices=None, handle_transforms_within_dataset=False):
(*dataset_str_parts, dataset_class_str) = full_dataset_class_str.split('.')
dataset_class = getattr(importlib.import_module('.'.join(dataset_s... |
def one_hot_bool(x, num_classes: int):
onehot = torch.zeros(x.size(0), num_classes, device=x.device, dtype=torch.bool)
return onehot.scatter_(1, x.unsqueeze(1), 1) |
class LeanPreprocessedJumpToLabelInstruction(LeanPreprocessedCodeElement):
label_name: ScopedName
offset: int
pc_dest: int
condition: Optional[Expression]
def get_exprs(self) -> List[Expression]:
return ([self.condition] if (self.condition is not None) else []) |
def _parse_cmudict(file):
cmudict = {}
for line in file:
if (len(line) and (((line[0] >= 'A') and (line[0] <= 'Z')) or (line[0] == "'"))):
parts = line.split(' ')
word = parts[0]
pronunciation = _get_pronunciation(parts[1])
if pronunciation:
... |
def cxy_wh_2_rect1(pos, sz):
return np.array([((pos[0] - (sz[0] / 2)) + 1), ((pos[1] - (sz[1] / 2)) + 1), sz[0], sz[1]]) |
def test_constructor_mutate_parameter_choose_existing(constructor_mock, default_test_case):
float0 = stmt.FloatPrimitiveStatement(default_test_case, 5.0)
float1 = stmt.FloatPrimitiveStatement(default_test_case, 5.0)
const = stmt.ConstructorStatement(default_test_case, constructor_mock, {'a': float0.ret_val}... |
_utils.in_tempdir
def test_dory_query_by_hashval(location):
testdata = relative_file('data/dory-k31-hashval-queries.txt')
shutil.copyfile(testdata, 'dory-k31-hashval-queries.txt')
copy_dory_catlas()
args = '-k 31 dory_k21/bcalm.unitigs.db dory_k21_r1_mh.pickle'
assert (index_cdbg_by_minhash.main(arg... |
def test_integrate_line_coverage_instrumentation(simple_module):
tracer = ExecutionTracer()
function_callable = getattr(simple_module, 'multi_loop')
adapter = LineCoverageInstrumentation(tracer)
transformer = InstrumentationTransformer(tracer, [adapter])
function_callable.__code__ = transformer.inst... |
def test_batch_to_cuda(conll2003_demo, device):
if device.type.startswith('cpu'):
pytest.skip('test requires cuda, while current session runs on cpu')
torch.cuda.set_device(device)
config = ExtractorConfig('sequence_tagging', ohots=ConfigDict({f: OneHotConfig(field=f, emb_dim=20) for f in Token._bas... |
class LPPool2d(_LPPoolNd):
kernel_size: _size_2_t
stride: _size_2_t
def forward(self, input: Tensor) -> Tensor:
return F.lp_pool2d(input, float(self.norm_type), self.kernel_size, self.stride, self.ceil_mode) |
def register_Ns3VsaManager_methods(root_module, cls):
cls.add_constructor([param('ns3::VsaManager const &', 'arg0')])
cls.add_constructor([])
cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True)
cls.add_method('RemoveAll', 'void', [])
cls.add_method('RemoveByChannel', 'void', [param('uint3... |
def decode_arch_def(arch_def, depth_multiplier=1.0, depth_trunc='ceil', experts_multiplier=1, fix_first_last=False):
arch_args = []
for (stack_idx, block_strings) in enumerate(arch_def):
assert isinstance(block_strings, list)
stack_args = []
repeats = []
for block_str in block_st... |
def apply_wrapper(wrapper, task_or_dataset=None):
if (task_or_dataset is None):
return wrapper
from torchmeta.utils.data import MetaDataset
if isinstance(task_or_dataset, Task):
return wrapper(task_or_dataset)
elif isinstance(task_or_dataset, MetaDataset):
if (task_or_dataset.dat... |
def _concat_dataset(cfg, default_args=None):
from .dataset_wrappers import ConcatDataset
img_dir = cfg['img_dir']
ann_dir = cfg.get('ann_dir', None)
split = cfg.get('split', None)
separate_eval = cfg.pop('separate_eval', True)
num_img_dir = (len(img_dir) if isinstance(img_dir, (list, tuple)) els... |
(Output('add-node-B', 'options'), Input('add-node-B-parent', 'n_clicks'), State('causal-data-state', 'data'))
def update_node_b_dropdown(n_clicks, data_state):
options = []
ctx = dash.callback_context
prop_id = ctx.triggered_id
if (prop_id == 'add-node-B-parent'):
data = (json.loads(data_state) ... |
def divergence(vf: ti.types.ndarray(ndim=2), velocity_divs: ti.types.ndarray(ndim=2)):
for (i, j) in vf:
vl = sample(vf, (i - 1), j)
vr = sample(vf, (i + 1), j)
vb = sample(vf, i, (j - 1))
vt = sample(vf, i, (j + 1))
vc = sample(vf, i, j)
if (i == 0):
vl.x... |
def init_weights(modules, initialize):
for module in modules():
if (isinstance(module, nn.Conv2d) or isinstance(module, nn.ConvTranspose2d) or isinstance(module, nn.Linear)):
if (initialize == 'ortho'):
init.orthogonal_(module.weight)
if (module.bias is not None):... |
def sequence_factory():
return _DummySequenceOutputVariableFactory(RuntimeVariable.CoverageTimeline) |
def tovec_sym(x: dace.float32[N], y: dace.float32[N], z: dace.float32[N]):
def sum(i: _[0:N]):
(xx << x[i])
(yy << y[i])
(zz << z[i])
(out >> z[i])
out = ((xx + yy) + zz) |
def compute_average_flops_cost(self):
batches_count = self.__batch_counter__
flops_sum = 0
for module in self.modules():
if (isinstance(module, torch.nn.Conv2d) or isinstance(module, torch.nn.Linear)):
flops_sum += module.__flops__
return (flops_sum / batches_count) |
.register_keras_serializable()
class FedProxOptimizer(keras.optimizers.Optimizer):
def __init__(self, learning_rate=0.01, mu=0.01, name='FedProxOptimizer', **kwargs):
super().__init__(name=name, **kwargs)
self._set_hyper('learning_rate', learning_rate)
self._set_hyper('mu', mu)
self.... |
def set_gamma_ramp(monitor, ramp):
gammaramp = _GLFWgammaramp()
gammaramp.wrap(ramp)
_glfw.glfwSetGammaRamp(monitor, ctypes.pointer(gammaramp)) |
def faiss_clustering(features, ncentroids, kmeans_niters):
import faiss
d = features.shape[1]
if (kmeans_niters is None):
kmeans_niters = 20
kmeans = faiss.Kmeans(d, ncentroids, niter=kmeans_niters, verbose=False)
kmeans.train(features)
(distances, assignments) = kmeans.index.search(feat... |
class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000):
self.inplanes = 128
super(ResNet, self).__init__()
self.conv1 = conv3x3(3, 64, stride=2)
self.bn1 = nn.BatchNorm2d(64)
self.relu1 = nn.ReLU(inplace=True)
self.conv2 = conv3x3(64, 64)
... |
def test_branch_subscopes_fission():
sdfg = dace.SDFG('branch_subscope_fission')
sdfg.add_symbol('i', dace.int32)
sdfg.add_array('A', [2], dace.int32)
sdfg.add_array('B', [1], dace.int32, transient=True)
sdfg.add_array('C', [1], dace.int32)
init_state = sdfg.add_state('init')
guard_1 = sdfg.... |
def drug_is_taken_in_baseline(index_date, dates):
for date in dates:
if ((index_date - date).days > 0):
return True
return False |
.parametrize('gamma', [0.1, 0.5, 0.9])
def test_valid_gamma(gamma: float) -> None:
check_gamma(gamma) |
def _worker_set_policy_params(g, params, scope=None):
g = _get_scoped_g(g, scope)
g.policy.set_param_values(params) |
def main():
generate_zenodo()
rst_include.include(source='docs/resources/credits_template.rst', target='docs/resources/credits.rst', quiet=False, inplace=False, source_encoding='utf-8', target_encoding='utf-8')
rst_include.include(source='README_TEMPLATE.rst', target='README.rst', quiet=False, inplace=False... |
class SegHead(nn.Module):
def __init__(self, in_ch, mid_ch, num_classes, upscale_factor=8, is_aux=True) -> None:
super().__init__()
out_ch = ((num_classes * upscale_factor) * upscale_factor)
self.conv_3x3 = ConvModule(in_ch, mid_ch, 3, 1, 1)
self.drop = nn.Dropout(0.1)
if is_... |
class NumericColumnTransformer(BaseColumnTransformer):
def __init__(self, key, shape=(1,), dtype='float32'):
self.key = key
self.shape = shape
self.dtype = dtype
def _set_feature_column_names(self, names):
BaseColumnTransformer._set_feature_column_names(self, names)
self.... |
class PriNet2D(nn.Module):
def __init__(self):
super(PriNet2D, self).__init__()
print('PriNet2D...')
self.net = archs.sparse_invar_encoder2D.CustomCNN(18, 1, 3).cuda()
def forward(self, feat_mem, clist_cam, summ_writer, suffix=''):
total_loss = torch.tensor(0.0).cuda()
(B... |
def register_Ns3Dot11sIePeerManagement_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
cls.add_output_stream_operator()
cls.add_constructor([param('ns3::dot11s::IePeerManagement const &', 'arg0')])
cls.add_constructor([])
cls.add_method('DeserializeInformationField', 'uint8_t', [... |
def get_run_env_dict():
d = {}
d['timestamp'] = datetime.datetime.now().timestamp()
d['hostname'] = socket.gethostname()
if ('SLURM_JOB_ID' in os.environ):
d['slurm_job_id'] = int(os.environ['SLURM_JOB_ID'])
if ('SLURM_PROCID' in os.environ):
d['slurm_procid'] = int(os.environ['SLURM... |
def _check_img_dtype(img):
assert isinstance(img, np.ndarray), '[Augmentation] Needs an numpy array, but got a {}!'.format(type(img))
assert ((not isinstance(img.dtype, np.integer)) or (img.dtype == np.uint8)), '[Augmentation] Got image of type {}, use uint8 or floating points instead!'.format(img.dtype)
as... |
class TestEmbeddings(unittest.TestCase):
def setUp(self):
self.methods = [Spectral(), GSVD(), SVD()]
self.bimethods = [GSVD(), SVD()]
def test_undirected(self):
adjacency = test_graph()
n = adjacency.shape[0]
method = Spring()
embedding = method.fit_transform(adja... |
def Norm2d(in_channels):
layer = getattr(cfg.MODEL, 'BNFUNC')
normalizationLayer = layer(in_channels)
return normalizationLayer |
class DistilBertForSequenceClassification():
def __init__(self, *args, **kwargs):
requires_pytorch(self)
def from_pretrained(self, *args, **kwargs):
requires_pytorch(self) |
def _get_all_arcs(graph_parse, is_variable):
assert isinstance(graph_parse, GraphParse)
items = []
for (a_key, b_key) in itertools.combinations(graph_parse.intersection_points, 2):
items.extend(_get_arcs(graph_parse, is_variable, a_key, b_key).iteritems())
return dict(items) |
def main(args):
file_name = f'{args.policy}_{args.env}_{args.seed}'
print('')
print(f'Policy: {args.policy}, Env: {args.env}, Seed: {args.seed}')
print('')
log_path = safe_path(os.path.join(args.log_root, '{}_base'.format(args.env)))
result_path = safe_path(os.path.join(log_path, 'results'))
... |
.make_registry
class BackwardImplementation(abc.ABC):
def backward_can_be_applied(node: nd.Node, state: SDFGState, sdfg: SDFG) -> bool:
return True
def backward(forward_node: nd.Node, context: BackwardContext, given_gradients: typing.List[typing.Optional[str]], required_gradients: typing.List[typing.Opt... |
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... |
class OpenAIGPTDoubleHeadsModel():
def __init__(self, *args, **kwargs):
requires_pytorch(self)
def from_pretrained(self, *args, **kwargs):
requires_pytorch(self) |
class BinaryEncoder(BaseNEncoder):
encoding_relation = utils.EncodingRelation.ONE_TO_M
__init__ = partialmethod(BaseNEncoder.__init__, base=2) |
def mae(y: pd.Series, yhat: pd.Series, lb: pd.Series, ub: pd.Series):
return np.abs((y - yhat)).mean() |
class ListPromptTemplate():
def __init__(self, template: str, input_variables: List[str]):
self.template = template
self.input_variables = input_variables
def build(self, **kwargs) -> str:
for i in self.input_variables:
if (i not in kwargs):
raise ValueError(f... |
def potsdam_classes():
return ['impervious_surface', 'building', 'low_vegetation', 'tree', 'car', 'clutter'] |
class Function_csc(GinacFunction):
def __init__(self):
GinacFunction.__init__(self, 'csc', latex_name='\\csc')
def _eval_numpy_(self, x):
return (1 / sin(x)) |
class Histogram(GraphicPrimitive):
def __init__(self, datalist, options):
import numpy as np
self.datalist = np.asarray(datalist, dtype=float)
if ('normed' in options):
from sage.misc.superseded import deprecation
deprecation(25260, "the 'normed' option is deprecated.... |
def reduce_formulas(formulas):
variable_values = {}
for formula in formulas:
if (formula.signature.id != 'Equals'):
continue
(left, right) = formula.children
if left.is_grounded(['What', 'Which']):
(left, right) = (right, left)
if (isinstance(left.signatur... |
def main(args):
if ('totaltext' in args.result_path.lower()):
gt_folder = 'evaluation/gt/gt_totaltext'
IS_WORDSPOTTING = True
lexicon_paths = ['', 'evaluation/lexicons/totaltext/weak_voc_new.txt']
pair_paths = ['', 'evaluation/lexicons/totaltext/weak_voc_pair_list.txt']
lexic... |
def lie_console():
from sage.repl.rich_output.display_manager import get_display_manager
if (not get_display_manager().is_in_terminal()):
raise RuntimeError('Can use the console only in the terminal. Try %%lie magics instead.')
os.system('bash `which lie`') |
class Ackley01(Benchmark):
def __init__(self, dimensions=2):
Benchmark.__init__(self, dimensions)
self._bounds = list(zip(([(- 35.0)] * self.N), ([35.0] * self.N)))
self.global_optimum = [[0 for _ in range(self.N)]]
self.fglob = 0.0
self.change_dimensionality = True
def f... |
def get_writer(uri, format=None, mode='?', **kwargs):
if ((uri == RETURN_BYTES) and isinstance(format, str)):
uri = ((RETURN_BYTES + '.') + format.strip('. '))
request = Request(uri, ('w' + mode), **kwargs)
if (format is not None):
format = formats[format]
else:
format = formats.... |
def test_jottings():
fname = os.path.join(test_data_path, 'parabola.mat')
read_workspace_vars(fname) |
def register_Ns3AddressValue_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::AddressValue const &', 'arg0')])
cls.add_constructor([param('ns3::Address const &', 'value')])
cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True)
... |
def rotate(img, degrees, **kwargs):
_check_args_tf(kwargs)
if (_PIL_VER >= (5, 2)):
return img.rotate(degrees, **kwargs)
elif (_PIL_VER >= (5, 0)):
(w, h) = img.size
post_trans = (0, 0)
rotn_center = ((w / 2.0), (h / 2.0))
angle = (- math.radians(degrees))
mat... |
class ENet(nn.Module):
def __init__(self, dictionary=None):
super(ENet, self).__init__()
self.dictionary = dictionary
self.dummy_input = torch.zeros(1, 3, 480, 360)
self.num_classes = len(self.dictionary)
self.category = [v for d in self.dictionary for v in d.keys()]
... |
def parse_requirements() -> Tuple[(PackagesType, PackagesType, Set[str])]:
essential_packages: PackagesType = {}
other_packages: PackagesType = {}
duplicates: Set[str] = set()
with open('requirements.txt', 'r') as req_file:
section: str = ''
for line in req_file:
line = line.... |
def draw_cdf_ci(axis, dataset, confidence=0.95, yscale=None, **kwargs):
if (yscale is None):
yscale = axis.gca().get_yscale()
y = __calc_cdf_bins(yscale, axis.gca().get_yaxis())
quantile_buckets = {q: [] for q in y}
total_num_items = 0
for data in dataset:
num_items = len(data)
... |
class Config():
def __init__(self):
self.verbose = True
self.network = 'resnet50'
self.use_horizontal_flips = False
self.use_vertical_flips = False
self.rot_90 = False
self.anchor_box_scales = [128, 256, 512]
self.anchor_box_ratios = [[1, 1], [1, 2], [2, 1]]
... |
_grad()
def test(model, loader, evaluator, device):
model.eval()
(y_true, y_pred) = ([], [])
for (xs, y) in loader:
xs = [x.to(device) for x in xs]
y_true.append(y.to(torch.long))
y_pred.append(model(xs).argmax(dim=(- 1)).cpu())
return evaluator.eval({'y_true': torch.cat(y_true, ... |
def weights_init(module):
if isinstance(module, nn.Conv2d):
nn.init.kaiming_normal_(module.weight, mode='fan_in', nonlinearity='relu')
if (module.bias is not None):
nn.init.zeros_(module.bias)
elif isinstance(module, (nn.BatchNorm2d, nn.GroupNorm)):
nn.init.ones_(module.weigh... |
def CReFF():
args = args_parser()
print('imb_factor:{ib}, non_iid:{non_iid}\nlr_net:{lr_net}, lr_feature:{lr_feature}, num_of_feature:{num_of_feature}\n match_epoch:{match_epoch}, re_training_epoch:{crt_epoch}\n'.format(ib=args.imb_factor, non_iid=args.non_iid_alpha, lr_net=args.lr_net, lr_feature=args.lr_featu... |
def _all_filename(distribution):
if (not distribution):
return 'all.py'
return f"all__{distribution.replace('-', '_')}.py" |
def convert_example_to_features(example: ContractNLIExample, max_seq_length: int, doc_stride: int, max_query_length: int, padding_strategy, labels_available: bool, symbol_based_hypothesis: bool) -> List[IdentificationClassificationFeatures]:
features = []
(all_doc_tokens, orig_to_tok_index, tok_to_orig_index, s... |
_metric('accuracy')
def accuracy(target: Union[(Sequence[int], Sequence[Sequence[int]])], prediction: Union[(Sequence[float], Sequence[Sequence[float]])]) -> float:
if isinstance(target[0], int):
return np.mean((np.asarray(target) == np.asarray(prediction).argmax((- 1))))
else:
correct = 0
... |
def main(config):
(svhn_loader, mnist_loader, svhn_test_loader, mnist_test_loader) = get_loader(config)
solver = Solver(config, svhn_loader, mnist_loader)
cudnn.benchmark = True
if (not os.path.exists(config.model_path)):
os.makedirs(config.model_path)
if (not os.path.exists(config.sample_pa... |
_toolkit()
class Twilio(FunctionToolkit):
name_for_human = 'Twilio'
description_for_human = 'Toolkit for Twilio services.'
name_for_model = 'Twilio'
description_for_model = 'A toolkit for Twilio services, enabling users to send SMS messages, retrieve communication history, manage scheduled actions, retr... |
class PointnetSAModuleVotes(nn.Module):
def __init__(self, *, mlp: List[int], radius: float=None, nsample: int=None, bn: bool=True, use_xyz: bool=True, normalize_xyz: bool=False, sample_uniformly: bool=False, sample_method='fps'):
super().__init__()
self.radius = radius
self.nsample = nsampl... |
_module()
class EmptyCacheHook(Hook):
def __init__(self, before_epoch=False, after_epoch=True, after_iter=False):
self._before_epoch = before_epoch
self._after_epoch = after_epoch
self._after_iter = after_iter
def after_iter(self, runner):
if self._after_iter:
torch.c... |
class TestDummies(TestCore):
def test_get_dummy(self):
Dummy('dummy')
def test_create_dummy(self):
d = Dummy.create(0.01)
self.assertIsInstance(d, Dummy) |
def calculate_fid_given_paths(paths, batch_size, device, dims):
for p in paths:
if (not os.path.exists(p)):
raise RuntimeError(('Invalid path: %s' % p))
block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[dims]
model = InceptionV3([block_idx]).to(device)
(m1, s1) = compute_statistics_of_path(... |
class Module(abc.ABC):
def __init__(self, name):
self._name = name
self._variable_scope = None
self._cached_params = None
self._cached_param_shapes = None
def name(self):
return self._name
def vectorized(self):
def reset(self, do_resets=None):
def state_info_s... |
class PairwiseDistance(Module):
__constants__ = ['norm', 'eps', 'keepdim']
norm: float
eps: float
keepdim: bool
def __init__(self, p: float=2.0, eps: float=1e-06, keepdim: bool=False) -> None:
super(PairwiseDistance, self).__init__()
self.norm = p
self.eps = eps
self.... |
.skipif((not has_pytorch()), reason='Pytorch not installed.')
_utils.test(arch=ti.cuda)
def test_torch_cuda_context():
device = torch.device('cuda:0')
x = torch.tensor([2.0], requires_grad=True, device=device)
assert torch._C._cuda_hasPrimaryContext(0)
loss = (x ** 2)
loss.backward() |
class _DummyEnvPoolTest(absltest.TestCase):
def test_config(self) -> None:
ref_config_keys = ['num_envs', 'batch_size', 'num_threads', 'max_num_players', 'thread_affinity_offset', 'base_path', 'seed', 'gym_reset_return_info', 'state_num', 'action_num', 'max_episode_steps']
default_conf = _DummyEnvSp... |
def CyclicPresentation(n):
n = Integer(n)
if (n < 1):
raise ValueError('finitely presented group order must be positive')
F = FreeGroup('a')
rls = ((F([1]) ** n),)
return FinitelyPresentedGroup(F, rls) |
(name='generate-cert-request')
('-n', '--collaborator_name', required=True, help='The certified common name of the collaborator')
('-s', '--silent', help='Do not prompt', is_flag=True)
('-x', '--skip-package', help='Do not package the certificate signing request for export', is_flag=True)
def generate_cert_request_(col... |
def make_batch_char_elem_into_tensor(batch, entry, pad, maxl=None, minl=None):
max_char_length = min(maxl, max((len(chars) for elem in batch for chars in elem[entry])))
max_char_length = max(max_char_length, minl)
torch_batch = np.full((len(batch), max_char_length, max((len(elem[entry]) for elem in batch)))... |
class BasicTokenizer(object):
def __init__(self, do_lower_case=True, never_split=None, tokenize_chinese_chars=True, strip_accents=None):
if (never_split is None):
never_split = []
self.do_lower_case = do_lower_case
self.never_split = set(never_split)
self.tokenize_chinese... |
def _set_playable_dice(dice: Array) -> Array:
return (((dice[0] == dice[1]) * jnp.array(([dice[0]] * 4), dtype=jnp.int32)) + ((dice[0] != dice[1]) * jnp.array([dice[0], dice[1], (- 1), (- 1)], dtype=jnp.int32))) |
class MFModel(object):
def __init__(self, F, data, lr, reg, random_seed, *args):
np.random.seed(random_seed)
self._factors = F
self._users = data.users
self._items = data.items
self._private_users = data.private_users
self._public_users = data.public_users
sel... |
('/_connect/', methods=['GET'])
def connect():
backend = get_backend()
backend.connect(userid())
return jsonify(success=True) |
def dataio_prepare(hparams):
data_folder = hparams['data_folder']
train_data = sb.dataio.dataset.DynamicItemDataset.from_csv(csv_path=hparams['train_csv'], replacements={'data_root': data_folder})
if (hparams['sorting'] == 'ascending'):
train_data = train_data.filtered_sorted(sort_key='duration')
... |
def otsu_threshold(image, nbins=256):
(hist, bin_centers) = histogram(image.ravel(), nbins)
hist = hist.astype(float)
weight1 = np.cumsum(hist)
weight2 = np.cumsum(hist[::(- 1)])[::(- 1)]
mean1 = (np.cumsum((hist * bin_centers)) / weight1)
mean2 = (np.cumsum((hist * bin_centers)[::(- 1)]) / weig... |
def to_binary(bars, threshold=0.0):
track_is_max = tf.equal(bars, tf.reduce_max(bars, axis=(- 1), keep_dims=True))
track_pass_threshold = (bars > threshold)
out_track = tf.logical_and(track_is_max, track_pass_threshold)
return out_track |
def solve_ivp(fun, t_span, y0, method='RK45', t_eval=None, dense_output=False, events=None, vectorized=False, args=None, **options):
if ((method not in METHODS) and (not (inspect.isclass(method) and issubclass(method, OdeSolver)))):
raise ValueError('`method` must be one of {} or OdeSolver class.'.format(ME... |
def eval_parsing_ap(all_parsings, all_scores, score_thresh, im_dir, ann_fn, num_parsing):
nb_class = num_parsing
ovthresh_seg = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
confidence = []
image_ids = []
Local_segs_ptr = []
for (img_index, parsings) in enumerate(all_parsings):
for (idx,... |
def get_model_4(params):
embedding_weights = pickle.load(open((common.TRAINDATA_DIR + ('/embedding_weights_w2v_%s.pk' % params['embeddings_suffix'])), 'rb'))
graph_in = Input(shape=(params['sequence_length'], params['embedding_dim']))
convs = []
for fsz in params['filter_sizes']:
conv = Convolut... |
class PNEANetV(object):
thisown = _swig_property((lambda x: x.this.own()), (lambda x, v: x.this.own(v)), doc='The membership flag')
__repr__ = _swig_repr
__swig_destroy__ = _snap.delete_PNEANetV
def __init__(self, *args):
_snap.PNEANetV_swiginit(self, _snap.new_PNEANetV(*args))
def Load(self... |
class HTMLTokenizer(object):
def __init__(self, stream, parser=None, **kwargs):
self.stream = HTMLInputStream(stream, **kwargs)
self.parser = parser
self.escapeFlag = False
self.lastFourChars = []
self.state = self.dataState
self.escape = False
self.currentTok... |
def lift(x):
try:
return x.lift()
except AttributeError:
raise ArithmeticError('no lift defined.') |
def mask_rcnn_fcn_head_v1up(model, blob_in, dim_in, spatial_scale):
return mask_rcnn_fcn_head_v1upXconvs(model, blob_in, dim_in, spatial_scale, 2) |
def print_diff(diff_lines, use_color):
if use_color:
diff_lines = colorize(diff_lines)
if (sys.version_info[0] < 3):
sys.stdout.writelines((l.encode('utf-8') for l in diff_lines))
else:
sys.stdout.writelines(diff_lines) |
def main():
dataset = 'fb15k-237'
model_names = ['conve', 'distmult', 'complex']
compare_models(dataset, model_names) |
('Fixing Together cache')
def fix(mongo_uri: str):
source_name: str = 'together'
target_name: str = 'together_rewritten'
source_config = MongoCacheConfig(mongo_uri, collection_name=source_name)
target_config = MongoCacheConfig(mongo_uri, collection_name=target_name)
source_store = create_key_value_s... |
class SawyerSoccerEnvV2(SawyerXYZEnv):
def __init__(self):
goal_low = ((- 0.1), 0.8, 0.0)
goal_high = (0.1, 0.9, 0.0)
hand_low = ((- 0.5), 0.4, 0.05)
hand_high = (0.5, 1, 0.5)
obj_low = ((- 0.1), 0.6, 0.03)
obj_high = (0.1, 0.7, 0.03)
super().__init__(self.mod... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.