code stringlengths 101 5.91M |
|---|
def main(opts):
copy_folder(opts.data_root, opts.out_root)
headsets = [0, 1, 2, 3]
meetings = []
with open(opts.ami_meeting_ids, 'r') as f:
for meetid in f:
meetings.append(meetid.strip())
assert (len(meetings) > 0), 'Looks like meeting list is empty'
sdms = []
if (len(op... |
class FortranIntrinsics():
IMPLEMENTATIONS_AST = {'SELECTED_INT_KIND': SelectedKind, 'SELECTED_REAL_KIND': SelectedKind, 'SUM': Sum, 'PRODUCT': Product, 'ANY': Any, 'COUNT': Count, 'ALL': All, 'MINVAL': MinVal, 'MAXVAL': MaxVal, 'MERGE': Merge}
DIRECT_REPLACEMENTS = {'__dace_selected_int_kind': SelectedKind, '_... |
(reuse_venv=True)
def clean(session):
parser = argparse.ArgumentParser()
parser.add_argument('--headers', action='store_true')
parser.add_argument('--signatures', action='store_true')
parser.add_argument('--tests', action='store_true')
parser.add_argument('--docs', action='store_true')
args = pa... |
def clean_segmentations(mask_path, output_path):
cap_img_path = os.path.join(mask_path, 'capsule')
reg_img_path = os.path.join(mask_path, 'regions')
maybe_mkdir(os.path.join(output_path, 'capsule'))
maybe_mkdir(os.path.join(output_path, 'regions'))
for f in os.listdir(cap_img_path):
cap_img ... |
def convert_sst_general(paths, dataset_name, version):
in_directory = paths['SENTIMENT_BASE']
sst_dir = os.path.join(in_directory, 'sentiment-treebank')
train_phrases = process_sst.get_phrases(version, 'train.txt', sst_dir)
dev_phrases = process_sst.get_phrases(version, 'dev.txt', sst_dir)
test_phra... |
def Toroidal6RegularGrid2dGraph(p, q):
if ((p <= 3) or (q <= 3)):
raise ValueError('parameters p and q must be integers larger than 3')
g = ToroidalGrid2dGraph(p, q)
for (u, v) in g:
g.add_edge((u, v), (((u + 1) % p), ((v + 1) % q)))
g.name('Toroidal Hexagonal Grid graph on {}x{} element... |
def folds_label_combination_pairs_without_evidence(y, folds, order):
combinations_per_row = get_combination_wise_output_matrix(y, order)
all_combinations = get_unique_combinations(combinations_per_row)
return np.sum([len(all_combinations.difference(get_unique_combinations(combinations_per_row[[fold]]))) for... |
def fix_prefix_quotations(summary_content):
ix = 0
fixed_content = []
while (ix < len(summary_content)):
sentence = summary_content[ix]
if (fixed_content and re.match('^[\\"\\\']$', sentence)):
fixed_content[(- 1)] = (fixed_content[(- 1)] + sentence)
ix += 1
e... |
class TransformerMockingjay(TransformerInitModel):
def __init__(self, config, input_dim, output_attentions=False, keep_multihead_output=False, with_input_module=True):
super(TransformerMockingjay, self).__init__(config, output_attentions)
self.with_input_module = with_input_module
if self.wi... |
def CheckSpacingForFunctionCall(filename, line, linenum, error):
fncall = line
for pattern in ('\\bif\\s*\\((.*)\\)\\s*{', '\\bfor\\s*\\((.*)\\)\\s*{', '\\bwhile\\s*\\((.*)\\)\\s*[{;]', '\\bswitch\\s*\\((.*)\\)\\s*{'):
match = Search(pattern, line)
if match:
fncall = match.group(1)
... |
def pad_and_stack(tensors, pad_size=None, value=0):
sizes = [s.shape[0] for s in tensors]
if (not pad_size):
pad_size = max(sizes)
padded = torch.stack([F.pad(input=sent[:pad_size], pad=(0, 0, 0, max(0, (pad_size - size))), value=value) for (sent, size) in zip(tensors, sizes)], dim=0)
return (pa... |
def _JDUTC_to_BJDTDB(JDUTC, ra=0.0, dec=0.0, epoch=2451545.0, pmra=0.0, pmdec=0.0, px=0.0, rv=0.0, loc=None, ephemeris='de430', leap_dir=os.path.join(os.path.dirname(__file__), 'data'), leap_update=True):
(JDTDB, JDTT, warning, error) = JDUTC_to_JDTDB(JDUTC)
clock_corr = ((JDTDB.jd - JDUTC.jd) * 86400.0)
(r... |
def main():
cfg = args_parse()
logger.info(f'load model, model arch: {cfg.MODEL.NAME}')
tokenizer = BertTokenizerFast.from_pretrained(cfg.MODEL.BERT_CKPT)
collator = DataCollator(tokenizer=tokenizer)
(train_loader, valid_loader, test_loader) = make_loaders(collator, train_path=cfg.DATASETS.TRAIN, va... |
def merge_workload(dataset: str, version: str, workload: str, count: int=10) -> None:
queryset = {'train': [], 'valid': [], 'test': []}
labels = {'train': [], 'valid': [], 'test': []}
for i in range(count):
L.info(f'Merge querset {workload}_{i}...')
qs = load_queryset(dataset, f'{workload}_{... |
def get_condition(filename):
c_path = (('data/timbre_model/test/condition/' + filename) + '_condi.npy')
conditon = np.load(c_path).astype(np.float)
return torch.Tensor(conditon).transpose(0, 1) |
class Modulation(Enum):
FSK = 0
SF6 = 6
SF7 = 7
SF8 = 8
SF9 = 9
SF10 = 10
SF11 = 11
SF12 = 12
def __str__(self):
if (self == Modulation.FSK):
return 'Modulation: FSK'
else:
return ('Modulation: LoRa, Spreading Factor ' + self.value) |
class DataLoader():
def __init__(self, config, split, type_='train', lang='en'):
assert (config.extension in ['json'])
self.config = config
self.extension = self.config.extension
self.max_length = self.config.max_length
self.max_tweets = self.config.max_tweets
self.la... |
def storage_gather(storage: SingleProcessTensorStorage, dst_rank: int=0) -> Optional[MultiProcessTensorStorage]:
if isinstance(storage, SingleProcessRamTensorStorage):
return _ram_storage_gather(storage, dst_rank)
elif isinstance(storage, SingleProcessFileTensorStorage):
return _file_storage_gat... |
class MT5EncoderModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def _parametric_plot3d_curve(f, urange, plot_points, **kwds):
from sage.plot.misc import setup_for_eval_on_grid
(g, ranges) = setup_for_eval_on_grid(f, [urange], plot_points)
(f_x, f_y, f_z) = g
w = [(f_x(u), f_y(u), f_z(u)) for u in xsrange(*ranges[0], include_endpoint=True)]
return line3d(w, **kwd... |
def test_RecordArray():
a = ak.Array([[{'x': [1], 'y': [[2]]}], None, [None], [{'x': None, 'y': None}], [{'x': [None], 'y': [None]}], [{'x': [11], 'y': [[None]]}]])
assert (to_list(ak.drop_none(a, axis=1)) == to_list(a[(~ ak.is_none(a, axis=1))]))
assert (to_list(ak.drop_none(a, axis=2)) == [[{'x': [1], 'y'... |
class ReplayBuffer():
def __init__(self, obs_dim, act_dim, size):
self.obs1_buf = np.zeros([size, obs_dim], dtype=np.float32)
self.obs2_buf = np.zeros([size, obs_dim], dtype=np.float32)
self.acts_buf = np.zeros([size, act_dim], dtype=np.float32)
self.rews_buf = np.zeros(size, dtype=n... |
def is_array_like(x) -> bool:
return (hasattr(x, 'shape') and hasattr(x, 'dtype') and hasattr(x, 'T')) |
def save_to_log(logdir, logfile, message):
f = open(((logdir + '/') + logfile), 'a')
f.write((message + '\n'))
f.close()
return |
def sanity_check(state_dict, pretrained_weights):
print("=> loading '{}' for sanity check".format(pretrained_weights))
checkpoint = torch.load(pretrained_weights, map_location='cpu')
state_dict_pre = checkpoint['state_dict']
for (k, k_pre) in zip(list(state_dict.keys()), list(state_dict_pre.keys())):
... |
class TestBeamStep(tf.test.TestCase):
def setUp(self):
super(TestBeamStep, self).setUp()
self.state_size = 10
config = beam_search.BeamSearchConfig(beam_width=3, vocab_size=5, eos_token=0, length_penalty_weight=0.6, choose_successors_fn=beam_search.choose_top_k)
self.config = config
... |
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('--config-file', nargs='?', type=str, help='path to config file')
parser.add_argument('--train-subjects', nargs='?', type=str, help='List of subject-id:s to train on, choosing from range(0,6): ex [0,1,2,3]')
parser.add_argumen... |
def multiprocess_training_loader(process_number: int, _config, _queue: mp.Queue, _wait_for_exit: mp.Event, _local_file, _fasttext_vocab_cached_mapping, _fasttext_vocab_cached_data):
_tokenizer = None
if (_config['preprocessed_tokenized'] == True):
_tokenizer = WordTokenizer(word_splitter=JustSpacesWordS... |
class HKONowcastingFactory(EncoderForecasterBaseFactory):
def __init__(self, batch_size, in_seq_len, out_seq_len, name='hko_nowcasting'):
super(HKONowcastingFactory, self).__init__(batch_size=batch_size, in_seq_len=in_seq_len, out_seq_len=out_seq_len, height=cfg.HKO.ITERATOR.HEIGHT, width=cfg.HKO.ITERATOR.W... |
def tau(a, b, eta):
s = p(a, b, eta)
taus = (s * normal.tau(a, b))
return taus.sum(axis=0) |
def facets_for_RP4():
from sage.groups.perm_gps.permgroup import PermutationGroup
g1 = '(2, 7)(4, 10)(5, 6)(11, 12)'
g2 = '(1, 2, 3, 4, 5, 10)(6, 8, 9)(11, 12, 13, 14, 15, 16)'
G = PermutationGroup([g1, g2])
t1 = (1, 2, 4, 5, 11)
t2 = (1, 2, 4, 11, 13)
facets = []
for g in G:
d =... |
def hide_rename_model(model_name):
model = m_repo.get_model(name=model_name, load_final_checkpoint=True, load_evaluations=True)
for e in m_repo.get_evaluations([x.uuid for x in model.final_checkpoint.evaluations]):
m_repo.hide_evaluation(e.uuid)
new_name = (model_name + f'_hidden_{random.randint(0, ... |
def offsets_to_index(offsets):
toindex = []
for x in range((len(offsets) - 1)):
offset = (offsets[(x + 1)] - offsets[x])
if (offset == 0):
toindex.append(offsets[x])
for y in range(offset):
toindex.append((offsets[x] + y))
return toindex |
def dataset_dest_prefix(args, output_prefix, lang):
base = '{}/{}'.format(args.destdir, output_prefix)
lang_part = ('.{}-{}.{}'.format(args.source_lang, args.target_lang, lang) if (lang is not None) else '')
return '{}{}'.format(base, lang_part) |
def accuracy(y_pred, y_true, topk=(1,)):
maxk = max(topk)
batch_size = y_true.size(0)
(_, pred) = y_pred.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(y_true.view(1, (- 1)).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].contiguous().view((- 1)).float()... |
def forzen_param(model):
flag = False
for (name, param) in model.named_parameters():
if ('10' in name):
flag = True
param.requires_grad = flag
return True |
def move_montgomery(root_folder, truth_csv, destination_root):
root_path = Path(root_folder)
os.makedirs(destination_root, exist_ok=True)
truth = pd.read_csv(truth_csv)
healthy = truth[(truth['No Finding'] == 1)]
disease = truth[(truth['Consolidation'] == 1)]
dst_path = (Path(destination_root) /... |
def main():
char_list = ['a', 'b', 'c', 'd']
img_list = [numpy.zeros((14, 14), dtype='float32'), numpy.zeros((12, 12), dtype='float32')]
transcription_list = [[0, 1, 2], [2, 0, 1]]
out_file_name = 'test.h5'
write_to_hdf(img_list, transcription_list, char_list, out_file_name) |
def perspective_API(data, api_key):
from .perspective import PerspectiveApiScorer
scorer = PerspectiveApiScorer(api_key=api_key)
(scores, all_scores) = ([], [])
for sample in tqdm(data):
all_score = scorer.get_scores(sample['output'])
all_scores.append(all_score)
scores.append((1... |
class Foo():
def __init__(self, x):
self.x = x
def __eq__(self, other):
return (self.__dict__ == other.__dict__) |
def configCLEVR():
config.dataPath = '{dataBasedir}/CLEVR_v1/data'.format(dataBasedir=config.dataBasedir)
config.datasetFilename = 'CLEVR_{tier}_questions.json'
config.wordVectorsFile = './CLEVR_v1/data/glove/glove.6B.{dim}d.txt'.format(dim=config.wrdEmbDim)
config.imageDims = [14, 14, 1024]
config.... |
class Cookies(object):
def store_cookies(cls, name, cookies):
pickled_cookies = json.dumps({'cookies': cookies, 'loginTime': datetime.datetime.now().timestamp()})
cookies_con.hset('account', name, pickled_cookies)
cls.push_in_queue(name)
def push_in_queue(cls, name):
for i in ran... |
_params({'X': ['array-like', 'sparse matrix'], 'y': ['array-like'], 'center': ['boolean'], 'force_finite': ['boolean']}, prefer_skip_nested_validation=True)
def r_regression(X, y, *, center=True, force_finite=True):
(X, y) = check_X_y(X, y, accept_sparse=['csr', 'csc', 'coo'], dtype=np.float64)
n_samples = X.sh... |
class ConvRelationModel(paddle.nn.Layer):
init_weight_attr = paddle.framework.ParamAttr(initializer=nn.initializer.TruncatedNormal(mean=0.0, std=0.01))
init_bias_attr = paddle.framework.ParamAttr(initializer=nn.initializer.Constant(value=0.0))
def __init__(self, input_size=(64, 21, 21), output_size=5, num_f... |
def flat_ner_performance(pred_start, pred_end, pred_span, gold_start, gold_end, gold_span, ner_cate, label_lst, threshold=0.5, dims=2):
cate_idx2label = {idx: value for (idx, value) in enumerate(label_lst)}
up_label_lst = update_label_lst(label_lst)
label2idx = {label: i for (i, label) in enumerate(up_label... |
_cache(maxsize=256, typed=True)
def _compile_pattern(pat, case_sensitive):
if isinstance(pat, bytes):
pat_str = pat.decode('ISO-8859-1')
res_str = translate(pat_str)
res = res_str.encode('ISO-8859-1')
else:
res = translate(pat)
flags = (0 if case_sensitive else re.IGNORECASE)... |
class CUHK02(ImageDataset):
dataset_dir = 'cuhk02'
cam_pairs = ['P1', 'P2', 'P3', 'P4', 'P5']
test_cam_pair = 'P5'
def __init__(self, root='', **kwargs):
self.root = osp.abspath(osp.expanduser(root))
self.dataset_dir = osp.join(self.root, self.dataset_dir, 'Dataset')
required_fil... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--data_dir', type=str, default='data/mwt', help='Root dir for saving models.')
parser.add_argument('--train_file', type=str, default=None, help='Input file for data loader.')
parser.add_argument('--eval_file', type=str, default=No... |
def load_processed_ct_images(npy_filepath, clip_range):
images = np.load(npy_filepath)
num_frames = len(images)
(left, right) = (int((num_frames * clip_range[0])), int((num_frames * clip_range[1])))
images = images[left:right]
num_frames = len(images)
shape = images.shape
if False:
f... |
def deconv(x, channels, kernel=4, stride=2, padding='SAME', use_bias=True, sn=False, scope='deconv'):
with tf.variable_scope(scope):
x_shape = x.get_shape().as_list()
if (padding == 'SAME'):
output_shape = [x_shape[0], (x_shape[1] * stride), (x_shape[2] * stride), channels]
else:... |
.spark
def test_get_csr_matrix(spark, log2):
grouped_log = log2.groupBy('user_idx').agg(sf.collect_list('item_idx').alias('vector_items'), sf.collect_list('relevance').alias('vector_ratings'))
grouped_log = grouped_log.toPandas()
csr_matrix = get_csr_matrix(grouped_log['user_idx'], grouped_log['vector_items... |
class Unetconv_norm_lrelu(nn.Module):
def __init__(self, feat_in, feat_out, kernel_size=(3, 3, 3), padding_size=(1, 1, 1), init_stride=(1, 1, 1), bias=False):
super(Unetconv_norm_lrelu, self).__init__()
self.conv_norm_lrelu = nn.Sequential(nn.Conv3d(feat_in, feat_out, kernel_size, init_stride, paddi... |
class BallQuery(Function):
def forward(ctx, min_radius: float, max_radius: float, sample_num: int, xyz: torch.Tensor, center_xyz: torch.Tensor) -> torch.Tensor:
assert center_xyz.is_contiguous()
assert xyz.is_contiguous()
assert (min_radius < max_radius)
(B, N, _) = xyz.size()
... |
class Mish(Activation):
def __init__(self, activation, **kwargs):
super(Mish, self).__init__(activation, **kwargs)
self.__name__ = 'Mish' |
def remove_unreachable_nodes(graph):
for node in graph.nodes():
if (sum((graph.edge_weight((node, other)) for other in graph.neighbors(node))) == 0):
graph.del_node(node) |
def train_batchrl_agent(dataset, agent_tag, num_steps=120000, results_folder='/tmp/pong_results', seed=0, num_eval_eps=10):
print('Training off-policy agent in batch mode on the dataset...')
blockPrint()
config = make_td3_agent(make_td3_agent(), args=AttrDict(parent_folder=results_folder, env=make_env, max_... |
def _empty_figure(title: str, plot_height: int, plot_width: int) -> Figure:
fig = Figure(x_range=[], y_range=[], plot_height=plot_height, plot_width=plot_width, title=title, x_axis_location='below', tools='hover', toolbar_location=None, background_fill_color='#fafafa')
fig.rect(x=0, y=0, width=0, height=0)
... |
def psnr(img1, img2, mask=None):
b = img1.size(0)
if (not (mask is None)):
b = img1.size(0)
mse_err = ((img1 - img2).pow(2) * mask)
mse_err = (mse_err.view(b, (- 1)).sum(dim=1) / (3 * mask.view(b, (- 1)).sum(dim=1).clamp(min=1)))
else:
mse_err = (img1 - img2).pow(2).view(b, (... |
class CategoricalCNNPolicy(StochasticPolicy):
def __init__(self, env_spec, filters, strides, padding, name='CategoricalCNNPolicy', hidden_sizes=(32, 32), hidden_nonlinearity=tf.nn.relu, hidden_w_init=tf.initializers.glorot_uniform(seed=deterministic.get_tf_seed_stream()), hidden_b_init=tf.zeros_initializer(), outpu... |
_cache
def find_first_content_subclass(cls):
for base_cls in reversed(cls.mro()):
if ((base_cls is not ak.contents.Content) and issubclass(base_cls, ak.contents.Content)):
return base_cls
raise TypeError |
class SpeechTransformerEncoder(nn.Module):
def __init__(self, d_model: int=512, input_dim: int=80, d_ff: int=2048, num_layers: int=6, num_heads: int=8, ffnet_style: str='ff', dropout_p: float=0.3, pad_id: int=0) -> None:
super(SpeechTransformerEncoder, self).__init__()
self.d_model = d_model
... |
class CountEncoder(util.BaseEncoder, util.UnsupervisedTransformerMixin):
prefit_ordinal = True
encoding_relation = util.EncodingRelation.ONE_TO_ONE
def __init__(self, verbose=0, cols=None, drop_invariant=False, return_df=True, handle_unknown='value', handle_missing='value', min_group_size=None, combine_min_... |
def find_ops(optype):
gd = tf.get_default_graph()
return [var for var in gd.get_operations() if (var.type == optype)] |
def train_model_but_load_prev_model_weights(params: Params, serialization_dir: str, prev_best_model: Model, file_friendly_logging: bool=False, recover: bool=False, force: bool=False) -> Model:
prepare_environment(params)
create_serialization_dir(params, serialization_dir, recover)
prepare_global_logging(ser... |
.skipif((not _ti_core.GGUI_AVAILABLE), reason='GGUI Not Available')
_utils.test(arch=supported_archs)
def test_draw_lines():
N = 10
particles_pos = ti.Vector.field(3, dtype=ti.f32, shape=N)
points_pos = ti.Vector.field(3, dtype=ti.f32, shape=N)
def init_points_pos(points: ti.template()):
for i i... |
class VisdomLinePlotter(object):
def __init__(self, env_name='main'):
self.viz = visdom.Visdom()
self.viz.check_connection()
self.env = env_name
self.plots = {}
def plot(self, var_name, split_name, x, y):
if (var_name not in self.plots):
self.plots[var_name] =... |
class TuneAnalysis():
model_kwargs: dict
train_kwargs: dict
metric: float
additional_metrics: dict
search_space: dict
results: Any |
def test1d_mask():
data_pts = np.arange(1000)
np.random.shuffle(data_pts)
bad_idx = np.nonzero((data_pts == 400))
nearest_idx_1 = np.nonzero((data_pts == 399))
nearest_idx_2 = np.nonzero((data_pts == 390))
kdtree = KDTree(data_pts, leafsize=15)
query_pts = np.arange(399.9, 299.9, (- 10))
... |
def string_to_dict(to_convert):
return {s.split('=', 1)[0]: s.split('=', 1)[1] for s in to_convert.split(' ') if (len(s) > 0)} |
def prepare_results(p, r, f):
return '\t{}:\t{}: {:5.2f}\t{}: {:5.2f}\t{}: {:5.2f}'.format(metric, 'P', (100.0 * p), 'R', (100.0 * r), 'F1', (100.0 * f)) |
class netcdf_variable():
def __init__(self, data, typecode, size, shape, dimensions, attributes=None, maskandscale=False):
self.data = data
self._typecode = typecode
self._size = size
self._shape = shape
self.dimensions = dimensions
self.maskandscale = maskandscale
... |
def evaluate(datasource, select, feature_metas, feature_column_names, label_meta, result_table, validation_metrics=['accuracy_score'], is_pai=False, pai_table='', model_params=None, transform_fn=None, feature_column_code=''):
if (not is_pai):
conn = db.connect_with_data_source(datasource)
else:
... |
def test_with_gauss_fluctuations():
x_true = (- 2.0)
minimizer = Minuit()
bounds = ((- 10), 10)
obs = zfit.Space('x', limits=bounds)
mean = zfit.Parameter('mean', 0)
sigma = zfit.Parameter('sigma', 1.0)
model = zfit.pdf.Gauss(obs=obs, mu=mean, sigma=sigma)
npzfile = f'{notebooks_dir}/toy... |
class TestAPSimple(unittest.TestCase):
def setUp(self):
self.car1 = {'trans': (1, 1, 1), 'name': 'car', 'score': 1.0}
self.car2 = {'trans': (3, 3, 1), 'name': 'car', 'score': 0.7}
self.bicycle1 = {'trans': (5, 5, 1), 'name': 'bicycle', 'score': 1.0}
self.bicycle2 = {'trans': (7, 7, 1... |
def copy_docstring_templates(pydoc_files, output_dir):
with open(os.path.join(output_dir, 'docstring_status'), 'w') as status_file:
for pydoc_file in pydoc_files:
file_in = open(pydoc_file, 'r').read()
output_pathname = os.path.join(output_dir, os.path.basename(pydoc_file).replace('_... |
def check_multiwoz_folders(data_folder):
files_str = '/data.json'
if (not os.path.exists((data_folder + files_str))):
err_msg = ('the folder %s does not exist (it is expected in the MultiWOZ dataset)' % (data_folder + files_str))
raise FileNotFoundError(err_msg) |
class SeparableConv2d_aspp(nn.Module):
def __init__(self, inplanes, planes, kernel_size=3, stride=1, dilation=1, bias=False, padding=0):
super(SeparableConv2d_aspp, self).__init__()
self.depthwise = nn.Conv2d(inplanes, inplanes, kernel_size, stride, padding, dilation, groups=inplanes, bias=bias)
... |
def _seg_24():
return [(9400, 'M', u'c'), (9401, 'M', u'd'), (9402, 'M', u'e'), (9403, 'M', u'f'), (9404, 'M', u'g'), (9405, 'M', u'h'), (9406, 'M', u'i'), (9407, 'M', u'j'), (9408, 'M', u'k'), (9409, 'M', u'l'), (9410, 'M', u'm'), (9411, 'M', u'n'), (9412, 'M', u'o'), (9413, 'M', u'p'), (9414, 'M', u'q'), (9415, '... |
def SymmetricPresentation(n):
from sage.groups.perm_gps.permgroup_named import SymmetricGroup
from sage.groups.free_group import _lexi_gen
n = Integer(n)
if (n <= 1):
return FinitelyPresentedGroup(FreeGroup(()), ())
perm_rep = SymmetricGroup(n)
GAP_fp_rep = libgap.Image(libgap.Isomorphis... |
class ImageDecoder(object):
def __init__(self):
self._sess = tf.Session()
self._encoded_jpeg = tf.placeholder(dtype=tf.string)
self._decode_jpeg = tf.image.decode_jpeg(self._encoded_jpeg, channels=3)
def decode_jpeg(self, encoded_jpeg):
image = self._sess.run(self._decode_jpeg, f... |
def test_remove(default_test_case):
stmt_1 = MagicMock(st.Statement)
stmt_2 = MagicMock(st.Statement)
stmt_3 = MagicMock(st.Statement)
default_test_case._statements.extend([stmt_1, stmt_2, stmt_3])
default_test_case.remove(1)
assert (default_test_case._statements == [stmt_1, stmt_3]) |
def define_D(input_nc, ndf, netD, n_layers_D=3, norm='batch', init_type='normal', init_gain=0.02, gpu_ids=[]):
net = None
norm_layer = get_norm_layer(norm_type=norm)
if (netD == 'basic'):
net = NLayerDiscriminator(input_nc, ndf, n_layers=3, norm_layer=norm_layer)
elif (netD == 'n_layers'):
... |
.skipif((ctypes is None), reason='ctypes not available on this python installation')
class TestNdpointerCFunc(object):
def test_arguments(self):
c_forward_pointer.restype = ctypes.c_void_p
c_forward_pointer.argtypes = (ndpointer(ndim=2),)
c_forward_pointer(np.zeros((2, 3)))
assert_ra... |
class ImportantConfigNode(TreeConfigNode):
def modify_label(self, label):
return ('IMPORTANT=' + str(label))
def init2(self, node_name):
self.props['is_important'] = node_name
def get_children(self):
return [] |
def eval_f1(ref, pred):
assert (len(ref) == len(pred) > 0)
precisions = []
recalls = []
for (i, s) in enumerate(pred):
ref_set = set()
for rs in ref[i]:
for w in rs:
ref_set.add(w)
pred_set = set()
for w in s:
pred_set.add(w)
... |
_experiment
def vpg_cartpole(ctxt=None, seed=1):
set_seed(seed)
with LocalTFRunner(snapshot_config=ctxt) as runner:
env = GarageEnv(env_name='CartPole-v1')
policy = CategoricalMLPPolicy(name='policy', env_spec=env.spec, hidden_sizes=(32, 32))
baseline = LinearFeatureBaseline(env_spec=env... |
class ExampleOperation(nn.Module):
def __init__(self, channels):
super(ExampleOperation, self).__init__()
self.seq = nn.Sequential(nn.Conv2d(in_channels=channels, out_channels=channels, kernel_size=(3, 3), padding=1), nn.BatchNorm2d(num_features=channels), nn.ReLU(inplace=True))
def forward(self... |
def process_ptb3_revised(paths, dataset_name, *args):
input_dir = os.path.join(paths['CONSTITUENCY_BASE'], 'english', 'LDC2015T13_eng_news_txt_tbnk-ptb_revised')
if (not os.path.exists(input_dir)):
backup_input_dir = os.path.join(paths['CONSTITUENCY_BASE'], 'english', 'LDC2015T13')
if (not os.pa... |
def test_sdca_hinge(bin_train_data):
(X_bin, y_bin) = bin_train_data
clf = SDCAClassifier(loss='hinge', random_state=0)
clf.fit(X_bin, y_bin)
assert (not hasattr(clf, 'predict_proba'))
assert (clf.score(X_bin, y_bin) == 1.0) |
def run_ger(target: str, n: int, m: int, tile_size_x: int, tile_size_y: int, alpha: float=1, veclen: int=1, eps: float=1e-06):
if (target == 'pure'):
(ger_node, state, sdfg) = pure_graph('pure', dace.float32, veclen)
ger_node.expand(sdfg, state)
sdfg.apply_transformations_repeated([InlineSDF... |
class ShelveDataset(Dataset):
def __init__(self, fname, key=None, norm_and_scale=False):
self.path = Path('{}.dat'.format(fname, 'dat'))
if (not self.path.exists()):
raise RuntimeError('{} does not exist.'.format(self.path))
self.data = shelve.open(str(fname.resolve()))
s... |
def conv3otherRelu(in_planes, out_planes, kernel_size=None, stride=None, padding=None):
if (kernel_size is None):
kernel_size = 3
assert isinstance(kernel_size, (int, tuple)), 'kernel_size is not in (int, tuple)!'
if (stride is None):
stride = 1
assert isinstance(stride, (int, tuple)), '... |
def removespaces(expr):
expr = expr.strip()
if (len(expr) <= 1):
return expr
expr2 = expr[0]
for i in range(1, (len(expr) - 1)):
if ((expr[i] == ' ') and ((expr[(i + 1)] in '()[]{}=+-/* ') or (expr[(i - 1)] in '()[]{}=+-/* '))):
continue
expr2 = (expr2 + expr[i])
... |
def random_planetoid_splits(num_classes, y, train_num, seed):
np.random.seed(seed)
indices = []
for i in range(num_classes):
index = (y == i).nonzero().view((- 1))
index = index[torch.randperm(index.size(0))]
indices.append(index)
train_index = torch.cat([i[:train_num] for i in i... |
def test_tabular_multi_output_independent_masker():
(model, data) = common.basic_xgboost_scenario(100)
common.test_additivity(shap.explainers.ExactExplainer, model.predict_proba, shap.maskers.Independent(data), data) |
class BaseQuantizationConfig(object):
def __init__(self, bit_list: List[int], thresholds_shift: List[int]):
self.bit_list = bit_list
self.thresholds_shift = thresholds_shift
def update_bit_list(self, bit_list):
self.bit_list = bit_list |
.parametrize('implementation, dtype', [pytest.param('pure', dace.float32), pytest.param('pure', dace.float64), pytest.param('MKL', dace.float32, marks=pytest.mark.mkl), pytest.param('MKL', dace.float64, marks=pytest.mark.mkl), pytest.param('cuBLAS', dace.float32, marks=pytest.mark.gpu), pytest.param('cuBLAS', dace.floa... |
def amsterdam_literal_train(listener=False):
data = [('light purple', 0, [(260.0, 45.0, 100.0), (260.0, 100.0, 100.0)]), ('purple', 0, [(260.0, 45.0, 100.0), (260.0, 100.0, 100.0)]), ('light', 0, [(260.0, 45.0, 100.0), (260.0, 100.0, 100.0)]), ('', 0, [(260.0, 45.0, 100.0), (260.0, 100.0, 100.0)]), ('light purple',... |
class SimulationConverter(object):
class Log(object):
def __init__(self, quiet):
self.history = ''
self.quiet = quiet
def __call__(self, string):
if (not self.quiet):
print(string)
self.history += (string + '\n')
def __str__(sel... |
class Keane(Benchmark):
def __init__(self, dimensions=2):
Benchmark.__init__(self, dimensions)
self._bounds = list(zip(([0.0] * self.N), ([10.0] * self.N)))
self.global_optimum = [[7., 7.]]
self.custom_bounds = [((- 1), 0.34), ((- 1), 0.34)]
self.fglob = 0.0
def fun(self,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.