code stringlengths 101 5.91M |
|---|
def test_option_ignore_between():
for what in ['null', 'true', '2', '2.2', '[]', '[2]', '[2, 2.2]', '{}', '{"z": 2.2}', '{"z": []}', '{"z": [2]}', '{"z": [2, 2.2]}']:
array = ak.from_json((('[{"x": 1, "y": ' + what) + ', "z": true}, {"x": 3, "z": false}]'), schema={'type': 'array', 'items': {'type': ['objec... |
class Encoder(object):
def __init__(self, name, is_train, norm='batch', activation='relu', image_size=128, latent_dim=8, use_resnet=True):
print(' [*] Init Encoder %s', name)
self.name = name
self._is_train = is_train
self._norm = norm
self._activation = activation
se... |
def in_plane_mobility_trans_times_force_pycuda(r_vectors, force, eta, a, *args, **kwargs):
number_of_blobs = np.int32(len(r_vectors))
(threads_per_block, num_blocks) = set_number_of_threads_and_blocks(number_of_blobs)
L = kwargs.get('periodic_length', np.array([0.0, 0.0, 0.0]))
x = real(np.reshape(r_vec... |
.patch('trieste.logging.tf.summary.scalar')
def test_scalar(mocked_summary_scalar: unittest.mock.MagicMock) -> None:
scalar('this', 1, step=1)
scalar('_that', 2, step=2)
with tf.name_scope('foo'):
scalar('this', (lambda : 3), step=3)
scalar('_that', (lambda : 4), step=4)
scalar('brok... |
class DumpSeqPlayDialog(QtWidgets.QDialog):
(Layout=QtWidgets.QGridLayout, apply_=False)
def __init__(self, parent):
self.setWindowTitle('Dump qOut to seqplay')
row = 0
row += 1
self.layout.addWidget(QtWidgets.QLabel('Timestep'), row, 0)
self.timestepLineEdit = QtWidgets.... |
def __scale_shortside(img, target_width, crop_width, method=Image.BICUBIC):
(ow, oh) = img.size
shortside = min(ow, oh)
if (shortside >= target_width):
return img
else:
scale = (target_width / shortside)
return img.resize((round((ow * scale)), round((oh * scale))), method) |
def progress_bar(current, total, msg=None):
global last_time, begin_time
if (current == 0):
begin_time = time.time()
cur_len = int(((TOTAL_BAR_LENGTH * current) / total))
rest_len = (int((TOTAL_BAR_LENGTH - cur_len)) - 1)
sys.stdout.write(' [')
for i in range(cur_len):
sys.stdout... |
def objects_counter_percentile(scan_ids, all_scans, prc):
all_obs_len = list()
for scan_id in all_scans:
if (scan_id in scan_ids):
all_obs_len.append(len(all_scans[scan_id].three_d_objects))
return np.percentile(all_obs_len, prc) |
class AffinePermutationTypeB(AffinePermutationTypeC):
def check(self):
if (not self):
return
k = self.parent().k
if (len(self) != k):
raise ValueError(('length of list must be k=' + str(k)))
reslist = []
for i in self:
r = (i % self.N)
... |
def main():
in_file = 'tgbl-coin_edgelist.csv'
outname = 'tgbl-coin_edgelist_sorted.csv'
sort_edgelist(in_file, outname) |
def main(args):
builder = ModelBuilder()
unet = builder.build_unet(num_class=args.num_class, arch=args.unet_arch, weights=args.weights_unet)
print('Froze the following layers: ')
for (name, p) in unet.named_parameters():
if (p.requires_grad == False):
print(name)
print()
crit... |
def jacobi(M):
if (not M.is_square()):
raise ValueError('the matrix must be square')
dim = M.nrows()
q = [list(row) for row in M]
for i in range((dim - 1)):
for j in range((i + 1), dim):
q[j][i] = q[i][j]
q[i][j] = (q[i][j] / q[i][i])
for k in range((i + 1... |
def enforce_concatenated_form(layout, form):
if ((not layout.is_unknown) and form.is_unknown):
raise AssertionError('merge result should never be of an unknown type unless the layout is unknown')
elif (layout.is_unknown and (not form.is_unknown)):
return form.length_zero_array(highlevel=False).t... |
def extract_N_frames_from_single_video(data_dir, video_name, save_dir, resize, scale=224, num_frames=64):
video_dir = os.path.join(data_dir, video_name)
frame_dir = os.path.join(save_dir, str(num_frames), video_name)
if (not os.path.exists(frame_dir)):
os.makedirs(frame_dir)
vidcap = cv2.VideoCa... |
class Stage2Config():
type: str = 'transformer1d'
vocab_size_txt: int = 16384
vocab_size_img: int = 16384
use_cls_cond: Optional[bool] = None
hparams: Stage2Hparams = Stage2Hparams() |
def build_mobilenetv2():
cnn = torch.hub.load('pytorch/vision', 'mobilenet_v2', pretrained=True)
model = torch.nn.Sequential(*list(cnn.children())[:(- 1)])
model.cuda()
model.eval()
return model |
def test_highlevel():
a = ak.highlevel.Array([[1.1, 2.2, 3.3], [], [4.4, 5.5], [6.6], [7.7, 8.8, 9.9]], check_valid=True)
assert (repr(a) == "<Array [[1.1, 2.2, 3.3], [], ..., [7.7, 8.8, 9.9]] type='5 * var * float64'>")
assert (str(a) == '[[1.1, 2.2, 3.3], [], [4.4, 5.5], [6.6], [7.7, 8.8, 9.9]]')
b = ... |
def test_post():
leaves = {name: Leaf(name=name) for name in ['x_in', 'y_in', 'x_out', 'y_out', 'pre', 'post', 'w']}
delta_w_node = Node([leaves['x_in'], leaves['x_out'], leaves['post']], [1.0, 2.0, 3.0], 1.0, 0.0, identity, sum_ag, name='delta_w', leaves=leaves)
input_coords = [[(- 1.0), 0.0], [1.0, 0.0], ... |
def test_regulartype_numpytype():
t = RegularType(NumpyType('int32'), 5)
assert (str(parser.parse(str(t))) == str(t)) |
def train_fixed_split(loggers, loaders, model, optimizer, scheduler, datasets, **kwargs):
start_epoch = 0
if cfg.train.auto_resume:
start_epoch = load_ckpt(model, optimizer, scheduler)
if (start_epoch == cfg.optim.max_epoch):
logging.info('Checkpoint found, Task already done')
else:
... |
class BiotETHTerm(BiotTerm, ETHTerm):
name = 'dw_biot_eth'
arg_types = (('ts', 'material_0', 'material_1', 'virtual', 'state'), ('ts', 'material_0', 'material_1', 'state', 'virtual'))
arg_shapes = {'material_0': 'S, 1', 'material_1': '1, 1', 'virtual/grad': ('D', None), 'state/grad': 1, 'virtual/div': (1, N... |
class roi_2mlp_head_prd(nn.Module):
def __init__(self, dim_in, roi_xform_func, spatial_scale):
super().__init__()
self.dim_in = dim_in
self.roi_xform = roi_xform_func
self.spatial_scale = spatial_scale
self.dim_out = hidden_dim = cfg.FAST_RCNN.MLP_HEAD_DIM
roi_size = ... |
def fullsubnet_validate(model, validation_loader, writer, dir_to_save, epoch, DEVICE):
validation_loss = 0
batch_num = 0
avg_pesq = 0
avg_stoi = 0
f_score = open(((dir_to_save + '/Epoch_') + ('%d_SCORES' % epoch)), 'a')
model.eval()
with torch.no_grad():
for (inputs, targets) in tool... |
class LieAlgebrasWithBasis(CategoryWithAxiom_over_base_ring):
_base_category_class_and_axiom = (LieAlgebras, 'WithBasis')
def example(self, gens=None):
if (gens is None):
from sage.combinat.partition import Partitions
gens = Partitions()
from sage.categories.examples.lie_... |
class FairseqOptimizer(object):
def __init__(self, args):
super().__init__()
self.args = args
def add_args(parser):
pass
def optimizer(self):
if (not hasattr(self, '_optimizer')):
raise NotImplementedError
if (not isinstance(self._optimizer, torch.optim.Op... |
def convert_processed_lines(processed_lines):
paragraphs = []
sentences = []
for words in processed_lines:
if ((len(words) > 1) and (' ' == words[0])):
words = words[1:]
elif ((len(words) == 1) and (' ' == words[0])):
words = []
sentence = []
for word ... |
()
('input_path')
('--encoding', default='ISO-8859-1')
def convert_io_to_bio_format(input_path: str, encoding: str):
label_history = []
with open(input_path, 'r', encoding=encoding) as in_f, open((input_path + '.bio'), 'w') as out_f:
for original_line in in_f:
line = original_line.strip()
... |
class PBWBasisOfFreeAlgebra(CombinatorialFreeModule):
def __classcall_private__(cls, R, n=None, names=None):
if ((n is None) and (names is None)):
if (not isinstance(R, FreeAlgebra_generic)):
raise ValueError('{} is not a free algebra'.format(R))
alg = R
else:... |
def trans_net(net, input_var, name='TransferedPytorchModel'):
print('Starting Transform, This will take a while')
log.init([input_var])
log.cnet.net.name = name
log.cnet.net.input.extend([log.blobs(input_var)])
log.cnet.net.input_dim.extend(input_var.size())
global NET_INITTED
NET_INITTED = ... |
def getTensorView(tensor, tensor_layout, conv_kind, problem_size, operand):
tensor_ref = getTensorRef(tensor, tensor_layout, conv_kind, problem_size, operand)
if (operand == 'a'):
tensor_coord = cutlass.conv.implicit_gemm_tensor_a_extent(conv_kind, problem_size)
elif (operand == 'b'):
tensor... |
class TFltPrV(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_TFltPrV
def __init__(self, *args):
_snap.TFltPrV_swiginit(self, _snap.new_TFltPrV(*args))
def Load(self, SI... |
class MaxMinFairnessWaterFillingPolicy(Policy, WaterFillingAlgorithm):
def __init__(self, priority_reweighting_policies=None):
self._name = 'MaxMinFairnessWaterFilling'
self._max_min_fairness_perf_policy = MaxMinFairnessWaterFillingPolicyWithPerf(priority_reweighting_policies)
def get_allocation... |
(Output('page-content', 'children'), [Input('url', 'pathname')])
def display_page(pathname):
if (pathname == '/apps/textanalyzer'):
return get_page_divs(textanalyzer.layout())
elif (pathname == '/apps/topicmodel'):
return get_page_divs(topicmodel.layout())
elif (pathname == '/apps/topsources... |
class PrintTree(TreeVisitor):
def __init__(self, start=None, end=None):
TreeVisitor.__init__(self)
self._indent = ''
if ((start is not None) or (end is not None)):
self._line_range = ((start or 0), (end or (2 ** 30)))
else:
self._line_range = None
def inde... |
def get_baseline(training_args, model_args, data_args, model):
baseline_output_dir = (training_args.output_dir + '_baseline')
eval_args = dataclasses.replace(training_args, output_dir=baseline_output_dir)
(trainer, lm_datasets, _, last_checkpoint) = run_clm.get_trainer_and_dataset(model_args, data_args, eva... |
def main():
args = parse_args()
logging.basicConfig(stream=sys.stdout, level=logging.INFO, format='%(message)s')
args.out_dir.mkdir(exist_ok=True)
filenames = list(args.in_dir.rglob('*.mp4'))
if (args.jobs == 1):
pbar = tqdm.tqdm(filenames, ncols=80)
for filename in pbar:
... |
def read_jsonl(file_path: str) -> List[Any]:
all_data = []
with open(file_path, 'r') as f:
for line in f:
line = line.strip()
if line:
data = json.loads(line)
all_data.append(data)
return all_data |
_module()
class CenterNet(SingleStageDetector):
def __init__(self, backbone, neck, bbox_head, train_cfg=None, test_cfg=None, pretrained=None, init_cfg=None):
super(CenterNet, self).__init__(backbone, neck, bbox_head, train_cfg, test_cfg, pretrained, init_cfg)
def merge_aug_results(self, aug_results, wit... |
class LambdaToFunction(ast.NodeTransformer):
def visit_Lambda(self, node: ast.Lambda):
newbody = [ast.Return(value=node.body)]
newnode = ast.FunctionDef(name='_anonymous', args=node.args, body=newbody, decorator_list=[])
newnode = ast.copy_location(newnode, node)
return ast.fix_missi... |
class Project():
PROJECT_FILE = 'project.yml'
VERSIONS_DIR = 'versions'
MISUSES_DIR = 'misuses'
def __init__(self, base_path: str, id: str):
self._base_path = base_path
self.id = id.lower()
self.path = join(base_path, id)
self._versions_path = join(self.path, Project.VERS... |
class ConcatDataset(Dataset):
def cumsum(sequence):
(r, s) = ([], 0)
for e in sequence:
l = len(e)
r.append((l + s))
s += l
return r
def __init__(self, datasets):
super(ConcatDataset, self).__init__()
assert (len(datasets) > 0), 'datase... |
def build_sn_patch_gan_discriminator(x, reuse=False, training=True):
with tf.variable_scope('sn_patch_gan', reuse=reuse):
cnum = 64
x = dis_spectralconv(x, cnum, name='conv1', training=training)
x = dis_spectralconv(x, (cnum * 2), name='conv2', training=training)
x = dis_spectralconv... |
class _DropoutNd(Module):
__constants__ = ['p', 'inplace']
p: float
inplace: bool
def __init__(self, p: float=0.5, inplace: bool=False) -> None:
super(_DropoutNd, self).__init__()
if ((p < 0) or (p > 1)):
raise ValueError('dropout probability has to be between 0 and 1, but go... |
_duration
def ffmpeg_audiowrite(clip, filename, fps, nbytes, buffersize, codec='libvorbis', bitrate=None, write_logfile=False, verbose=True, ffmpeg_params=None, logger='bar'):
if write_logfile:
logfile = open((filename + '.log'), 'w+')
else:
logfile = None
logger = proglog.default_bar_logger... |
class CanonicalHFIndex(HFIndexBase):
def __init__(self, vector_size: int, dataset_name: str='wiki_dpr', dataset_split: str='train', index_name: Optional[str]=None, index_path: Optional[str]=None, use_dummy_dataset=False):
if ((int((index_path is None)) + int((index_name is None))) != 1):
raise V... |
class DefaultDomainNameServiceMerger(ServiceMerger):
def __mergeZone(self, a: Zone, b: Zone, dst: Zone, position: str=''):
names = set()
self._log('merging zone: {}'.format(('(root)' if (position == '') else position)))
for r in a.getRecords():
if (r not in dst.getRecords()):
... |
def sharp_invoke(module, function, args):
functions = modules.get(module)
if functions:
funct = functions.get(function)
if funct:
return text_type(funct(args))
return '' |
def huber_loss(x, delta=1.0):
'Reference:
return tf.compat.v1.where((tf.abs(x) < delta), (tf.square(x) * 0.5), (delta * (tf.abs(x) - (0.5 * delta)))) |
def _listify(obj):
if (obj is None):
return []
elif isinstance(obj, str):
return [obj]
else:
return obj |
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, stride=stride, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv... |
def _get_base_mp_nbits_candidates():
return [(4, 8), (4, 4), (4, 2), (8, 8), (8, 4), (8, 2), (2, 8), (2, 4), (2, 2)] |
def replace_oovs(word_list, vocab, oov_handling, vocab_vectors=None, all_vectors=None):
if (not check_for_oov(word_list, vocab)):
return word_list
for i in range(len(word_list)):
if (word_list[i] in vocab):
continue
if (oov_handling == 'wordnet'):
new_word = find_... |
def test_banded_ode_solvers():
t_exact = np.linspace(0, 1.0, 5)
a_real = np.array([[(- 0.6), 0.1, 0.0, 0.0, 0.0], [0.2, (- 0.5), 0.9, 0.0, 0.0], [0.1, 0.1, (- 0.4), 0.1, 0.0], [0.0, 0.3, (- 0.1), (- 0.9), (- 0.3)], [0.0, 0.0, 0.1, 0.1, (- 0.7)]])
a_real_upper = np.triu(a_real)
a_real_lower = np.tril(a_r... |
class FlaxRobertaModelTester(unittest.TestCase):
def __init__(self, parent, batch_size=13, seq_length=7, is_training=True, use_attention_mask=True, use_token_type_ids=True, use_labels=True, vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37, hidden_act='gelu', hidden_dro... |
class Up(nn.Module):
def __init__(self, in_channels, chan_factor, bias=False):
super(Up, self).__init__()
self.bot = nn.Sequential(nn.Conv2d(in_channels, int((in_channels // chan_factor)), 1, stride=1, padding=0, bias=bias), nn.Upsample(scale_factor=2, mode='bilinear', align_corners=bias))
def f... |
def is_array_param(p):
if ((param_kind(p) == IN_ARRAY) or (param_kind(p) == INOUT_ARRAY) or (param_kind(p) == OUT_ARRAY)):
return True
else:
return False |
_utils.test(arch=supported_archs_cgraph)
def test_arg_mismatched_ndim():
n = 4
def test(pos: ti.types.ndarray(ndim=1)):
for i in range(n):
pos[i] = 2.5
sym_pos = ti.graph.Arg(ti.graph.ArgKind.NDARRAY, 'pos', ti.f32, ndim=2)
g_init = ti.graph.GraphBuilder()
with pytest.raises(Taic... |
def test_light_tokenizer():
light_tokenizer = LightTokenizer()
default_tokenizer = DefaultTokenizer()
assert (light_tokenizer.tokenize(TEST_DOCUMENT) == TEST_TOKENS_SPLIT_BY_SPACE)
assert (default_tokenizer.tokenize(TEST_DOCUMENT) == TEST_TOKENS_BY_DEFAULT_TOKENIZER)
simple_tokenization_test_case: s... |
def jacobi_1d_shared(TSTEPS: dc.int64, A: dc.float64[N], B: dc.float64[N]):
for t in range(1, TSTEPS):
B[1:(- 1)] = (0.33333 * ((A[:(- 2)] + A[1:(- 1)]) + A[2:]))
A[1:(- 1)] = (0.33333 * ((B[:(- 2)] + B[1:(- 1)]) + B[2:])) |
def apply_weight_norm(m):
classname = m.__class__.__name__
if (classname.find('Conv') != (- 1)):
weight_norm(m) |
class RealmTokenizerFast(PreTrainedTokenizerFast):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
slow_tokenizer_class = RealmTo... |
def _seg_58():
return [(93763, 'M', u''), (93764, 'M', u''), (93765, 'M', u''), (93766, 'M', u''), (93767, 'M', u''), (93768, 'M', u''), (93769, 'M', u''), (93770, 'M', u''), (93771, 'M', u''), (93772, 'M', u''), (93773, 'M', u''), (93774, 'M', u''), (93775, 'M', u''), (93776, 'M', u''), (93777, 'M', u''), (93778, ... |
def worker(kwargs) -> Tuple[(Dict[(int, int)], float, float)]:
graph = Graph.from_state(kwargs.pop('graph'))
kwargs['graph'] = graph
meta_algorithm = kwargs.pop('meta_algorithm')
algorithm = kwargs['algorithm']
allocated_seconds = kwargs.pop('allocated_seconds')
objective = kwargs['objective']
... |
class EmbeddingsAlreadyPackagedAsTriplets(BaseTupleMiner):
def mine(self, embeddings, labels, ref_emb, ref_labels):
batch_size = embeddings.size(0)
a = torch.arange(0, batch_size, 3)
p = torch.arange(1, batch_size, 3)
n = torch.arange(2, batch_size, 3)
return (a, p, n) |
def default_str_type(env):
return {'bytes': bytes_type, 'bytearray': bytearray_type, 'str': str_type, 'unicode': unicode_type}.get(env.directives['c_string_type']) |
_module()
class ConcatDataset(_ConcatDataset):
def __init__(self, datasets: list):
super(ConcatDataset, self).__init__(datasets) |
_module()
class PointNet2Encoder(nn.Module):
def __init__(self, in_channels: int, radius: (List[float] or float), num_samples: (List[int] or int), aggr_args: dict, group_args: dict, conv_args: dict, norm_args: dict, act_args: dict, blocks: Optional[List]=None, mlps=None, width: Optional[int]=None, strides: List[int... |
def load_blender_data(basedir, half_res=False, testskip=1):
splits = ['train', 'val', 'test']
metas = {}
for s in splits:
with open(os.path.join(basedir, 'transforms_{}.json'.format(s)), 'r') as fp:
metas[s] = json.load(fp)
all_imgs = []
all_poses = []
counts = [0]
for s ... |
def prepare_paws_qqp():
(train_path, dev_path) = ('', '')
for mode in ['dev_and_test', 'train']:
os.makedirs('../paraphraser/data/processed_datasets/paws_qqp_{}'.format(mode), exist_ok=True)
save_path = '../paraphraser/data/processed_datasets/paws_qqp_{}/paws_qqp_{}.txt'.format(mode, mode)
... |
class BaseColBERT(torch.nn.Module):
def __init__(self, name_or_path, colbert_config=None):
super().__init__()
self.colbert_config = ColBERTConfig.from_existing(ColBERTConfig.load_from_checkpoint(name_or_path), colbert_config)
self.name = (self.colbert_config.model_name or name_or_path)
... |
_utils.test(arch=archs_support_ndarray_ad)
def test_ad_vector_arg():
N = 10
def compute_sum(a: ti.types.ndarray(), p: ti.types.ndarray(), z: ti.math.vec2):
for i in p:
p[i] = (a[i] * z[0])
a = ti.ndarray(ti.math.vec2, shape=N, needs_grad=True)
p = ti.ndarray(ti.math.vec2, shape=N, ne... |
class STL10(CIFAR10):
base_folder = 'stl10_binary'
url = '
filename = 'stl10_binary.tar.gz'
tgz_md5 = '91f7769df0f17e558f3565bffb0c7dfb'
class_names_file = 'class_names.txt'
train_list = [['train_X.bin', '918c2871b30a85fa023e0c44e0bee87f'], ['train_y.bin', '5a34089d4802c674881badbb'], ['unlabele... |
def iterate_over_frames(frequency):
for (_, subject_id) in lps_subjects.items():
print(subject_id)
csv_path = ((frames_dir + subject_id) + '.csv')
print(csv_path)
subject_frames_df = pd.read_csv(csv_path, sep=',')
counter = 0
per_video_counter = 0
for row in s... |
def rescale_img(img_in, new_size_in):
img_in = img_in.resize(new_size_in, resample=Image.BICUBIC)
return img_in |
class EmitSparseGemmInstance():
def __init__(self):
self.gemm_template = '\n // Gemm operator ${operation_name}\n using Operation_${operation_name} = cutlass::gemm::device::SparseGemm<\n ${element_a}, ${layout_a},\n ${element_b}, ${layout_b},\n ${element_c}, ${layout_c},\n ${element_accumulato... |
def Draw(im, mode=None):
try:
return im.getdraw(mode)
except AttributeError:
return ImageDraw(im, mode) |
def fixup(dir):
for (root, dirs, files) in os.walk(dir):
for f in files:
if f.endswith('.h'):
path = ('%s\\%s' % (root, f))
fix_hdr(path) |
_task('translation')
class TranslationTask(LegacyFairseqTask):
def add_args(parser):
parser.add_argument('data', help='colon separated path to data directories list, will be iterated upon during epochs in round-robin manner; however, valid and test dat... |
def save_corpus_segments_to_file(output_filename, input_dict):
with open(output_filename, 'w') as file:
file.write('{\n')
for (key, value) in input_dict.items():
value = value.lstrip()
file.write('"{}": "{}",\n'.format(key, value))
file.write('}\n') |
class TestGeneral(unittest.TestCase):
def setUp(self):
self.task = generate_task(task_generator_id='general')
self.env = CausalWorld(task=self.task, enable_visualization=False)
self.env.reset()
return
def tearDown(self):
self.env.close()
return
def test_determ... |
class All2All(torch.autograd.Function):
def forward(ctx, xs, input_splits=None, output_splits=None):
ctx.input_splits = input_splits
ctx.output_splits = output_splits
ys = (torch.empty_like(xs) if (output_splits is None) else xs.new_empty(size=([sum(output_splits)] + list(xs.size()[1:]))))
... |
class contdist5():
def __init__(self):
self.mode = 0
def pdf(self, x):
return (0.2 * (0.05 + (0.45 * (1 + np.sin(((2 * np.pi) * x))))))
def dpdf(self, x):
return (((0.2 * 0.45) * (2 * np.pi)) * np.cos(((2 * np.pi) * x)))
def cdf(self, x):
return (((x / 10.0) + 0.5) + ((0.... |
def test_close(model=None):
if (model is None):
model = SimpleModel()
state = build_initial_state(model)[0]
open_transition_vp = parse_transitions.OpenConstituent('VP')
assert open_transition_vp.is_legal(state, model)
state = open_transition_vp.apply(state, model)
assert (state.num_opens... |
def sort_specializations(keystring):
ordering = ['bool', 'int8', 'int16', 'int32', 'int64', 'u8', 'uint8', 'u16', 'uint16', 'u32', 'uint32', 'u64', 'uint64', 'float16', 'float32', 'float64', 'float128', 'complex64', 'complex128', 'complex256']
elemsfound = []
keystring = keystring.lower()
while any(((el... |
def _v(m1, m2, hue):
hue = (hue % 1.0)
if (hue < ONE_SIXTH):
return (m1 + (((m2 - m1) * hue) * 6.0))
if (hue < 0.5):
return m2
if (hue < TWO_THIRD):
return (m1 + (((m2 - m1) * (TWO_THIRD - hue)) * 6.0))
return m1 |
def line_stats(example):
line_lengths = [len(line) for line in example['content'].splitlines()]
return {'line_mean': np.mean(line_lengths), 'line_max': max(line_lengths)} |
def main(cfg):
(train_loader, train_loader_ca, train_loader_cb, val_loader_c, val_loader_b, num_query_c, num_query_b, num_classes) = make_data_loader(cfg, use_eraser=True)
model = build_model(num_classes, 'base', pretrain_choice=True)
model = (torch.nn.DataParallel(model).cuda() if torch.cuda.is_available()... |
_fusion('mfb')
class MFB(nn.Module):
def __init__(self, input_dims, output_dim, mm_dim=1200, factor=2, activ_input='relu', activ_output='relu', normalize=False, dropout_input=0.0, dropout_pre_norm=0.0, dropout_output=0.0):
super().__init__()
self.input_dims = input_dims
self.mm_dim = mm_dim
... |
class KnowledgeDistillationLoss(nn.Module):
def __init__(self, reduction='mean', alpha=1.0):
super().__init__()
self.reduction = reduction
self.alpha = alpha
def forward(self, inputs, targets, gt, mask=None):
inputs = inputs.narrow(1, 0, targets.shape[1])
outputs = torch.... |
class ClassifierStudentLoss(object):
def __init__(self, student_model, base_loss, alpha=0.9):
self.student = student_model
self.base_loss = base_loss
self.alpha = alpha
def __call__(self, inputs, targets, teacher_logits, temp=None):
real_batch_size = targets.size(0)
stude... |
def check_fit_args_fix(distfn, arg, rvs):
with np.errstate(all='ignore'), suppress_warnings() as sup:
sup.filter(category=DeprecationWarning, message='.*frechet_')
sup.filter(category=RuntimeWarning, message='The shape parameter of the erlang')
vals = distfn.fit(rvs, floc=0)
vals2 = ... |
class Score(Operation):
operation_type: OperationType = OperationType.score
def __init__(self, num_samples: int=1, combined_scoring: bool=False, scoring_function: Callable[([Union[(List[Dict], Dict)]], Union[(List[float], float)])]=None) -> None:
super().__init__()
self.num_samples: int = num_sa... |
def AssionGroupU(n=None, names='u'):
return CubicBraidGroup(n=n, names=names, cbg_type=CubicBraidGroup.type.AssionU) |
class BatchPolopt(RLAlgorithm):
def __init__(self, env, policy, baseline, scope=None, n_itr=500, start_itr=0, batch_size=5000, max_path_length=500, discount=0.99, gae_lambda=1, plot=False, pause_for_plot=False, center_adv=True, positive_adv=False, store_paths=False, whole_paths=True, fixed_horizon=False, sampler_cl... |
def is_video_file(filename):
filename_lower = filename.lower()
return any((filename_lower.endswith(ext) for ext in VID_EXTENSIONS)) |
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, in_planes, planes, stride=1):
super(BasicBlock, self).__init__()
self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(p... |
def collate_fn_squeeze_pcd_batch_grasp(batch: List) -> Dict:
batch_data = {key: [d[key] for d in batch] for key in batch[0]}
for key in batch_data:
if torch.is_tensor(batch_data[key][0]):
batch_data[key] = torch.stack(batch_data[key])
(offset, count) = ([], 0)
for item in batch_data[... |
def make_main_state(sdfg):
state = sdfg.add_state('spmv')
a_row = state.add_array('A_row_device', ((rows + 1),), itype, transient=True, storage=StorageType.FPGA_Global)
row_to_val_out = state.add_stream('row_to_val', itype, transient=True, storage=StorageType.FPGA_Local)
row_to_col_out = state.add_strea... |
def generate_matchpy_matcher(pattern_list):
matcher = matchpy.ManyToOneMatcher()
for pattern in pattern_list:
matcher.add(matchpy.Pattern(pattern))
return matcher |
('/predict', methods=['POST'])
def predict():
board = np.fromstring(request.form['board'], sep=',').reshape(g.getBoardSize())
use_alpha_zero = True
if use_alpha_zero:
action = np.argmax(mcts.getActionProb(board, temp=0))
else:
action = GreedyRandomPlayer(g).play(board)
resp = Respons... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.