code stringlengths 101 5.91M |
|---|
def run_bipartite_example():
run_on_network_attr('../data/bipartite/Inouye_Pyke_pollinator_web/inouye_bipartite.net', [partial(changeBipartiteDensity, MODE_A), partial(changeBipartiteActivity, MODE_A), partial(changeBipartiteEgoTwoStar, MODE_A), partial(changeBipartiteAlterTwoStar1, MODE_A), partial(changeBipartite... |
def test_scalar_write_shadow_fused():
sdfg = dace.SDFG('scalar_fused')
N = dace.symbol('N')
sdfg.add_array('A', [N], dace.int32)
sdfg.add_array('B', [N], dace.int32)
sdfg.add_array('tmp', [1], dace.int32, transient=True)
init_state = sdfg.add_state('init')
guard_1 = sdfg.add_state('guard_1')... |
class FlipAugmenter(dptspatialaugmenterbase.SpatialAugmenterBase):
def __init__(self, flip_list):
super().__init__(keyword='flip')
self.__flip_list = []
self.__flip = None
self.__setfliplist(flip_list=flip_list)
def __setfliplist(self, flip_list):
if (not (set(flip_list) ... |
class BrewTest(unittest.TestCase):
def setUp(self):
def myhelper(model, val=(- 1)):
return val
if (not brew.has_helper(myhelper)):
brew.Register(myhelper)
self.myhelper = myhelper
def myhelper2(model, val=(- 1)):
return val
if (not brew.has... |
def get_tree(filename):
file_str = open(filename, encoding='utf8', errors='backslashreplace').read()
tree = parser.parse(bytes(file_str, 'utf-8'))
root_node = tree.root_node
return root_node |
def getUserBankAccount(userId, connection):
if isAuthorizedUser(userId):
try:
sql = (("SELECT * FROM user_bank_account WHERE user_id = '" + userId) + "'")
result = connection.execute(sql)
return result
except Exception as e:
logging.error(f'Unable to r... |
def stretch_with_scpml(dxes: fdfd_tools.GridSpacing, axis: int, polarity: int, omega: float, epsilon_effective: float=1.0, thickness: int=10, s_function: s_function_type=None) -> fdfd_tools.GridSpacing:
if (s_function is None):
s_function = prepare_s_function()
dx_ai = dxes[0][axis].astype(complex)
... |
def get_default_frameworks():
frameworks = []
if is_torch_available():
frameworks.append('pt')
if is_tf_available():
frameworks.append('tf')
if is_flax_available():
frameworks.append('flax')
return frameworks |
class BaseMultiModalDataset(abc.ABC):
def feature_columns(self):
pass
def label_columns(self):
pass
def label_types(self):
raise NotImplementedError
def data(self):
pass
def metric(self):
pass
def problem_type(self):
pass |
def test_cartesian():
one = ak.Array(np.arange((((2 * 3) * 5) * 7)).reshape(2, 3, 5, 7).tolist())
two = ak.Array(np.arange((((2 * 3) * 5) * 7)).reshape(2, 3, 5, 7).tolist())
assert (str(ak.operations.cartesian([one, two], axis=0, nested=True).type) == '2 * 2 * (var * var * var * int64, var * var * var * int... |
class DistributionModelTestCase(unittest.TestCase):
def test_prediction_in_eval_should_be_consistent(self):
model = DistributionPredictionModel(input_size=10)
model.eval()
tensor = torch.randn(size=[10])
pred_1 = float(model(tensor))
pred_2 = float(model(tensor))
self... |
def create_lvis_semantic_from_instance(instance_json, sem_seg_root):
os.makedirs(sem_seg_root, exist_ok=True)
lvis_detection = LVIS(instance_json)
def iter_annotations():
for img_id in lvis_detection.get_img_ids():
anns_ids = lvis_detection.get_ann_ids([img_id])
anns = lvis_d... |
def load_tests(loader, tests, pattern):
set_running_script_path()
test_suite = unittest.TestSuite()
for test_group in tests:
for test in test_group:
check_test_defined_in_running_script(test)
test_suite.addTest(test)
return test_suite |
class ProjectiveSpace_rational_field(ProjectiveSpace_field):
def rational_points(self, bound=0):
if (not (bound > 0)):
raise ValueError('argument bound (= %s) must be a positive integer')
n = self.dimension_relative()
Q = [(k - bound) for k in range(((2 * bound) + 1))]
R ... |
class SparseTransformerSentenceEncoderLayer(TransformerSentenceEncoderLayer):
def __init__(self, embedding_dim: float=768, ffn_embedding_dim: float=3072, num_attention_heads: float=8, dropout: float=0.1, attention_dropout: float=0.1, activation_dropout: float=0.1, activation_fn: str='relu', add_bias_kv: bool=False,... |
def test_get_function_description_nested():
module = astroid.parse('\ndef foo():\n def bar():\n return False\n yield 5')
description = get_function_description(get_function_node_from_ast(module, 'foo'))
assert (description.has_return is False)
assert (description.has_yield is True) |
.parametrize('csr_container', CSR_CONTAINERS)
def test_dbscan_precomputed_metric_with_initial_rows_zero(csr_container):
ar = np.array([[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.1, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.1, 0.0, 0.0], [0.0, 0.0, 0.1, 0.1, 0.0, 0.0, 0.... |
class _MultipleMatch(ParseElementEnhance):
def __init__(self, expr, stopOn=None):
super(_MultipleMatch, self).__init__(expr)
self.saveAsList = True
ender = stopOn
if isinstance(ender, basestring):
ender = ParserElement._literalStringClass(ender)
self.not_ender = (... |
class BaseDiscriminator(nn.Module):
def forward(self, x: torch.Tensor) -> Tuple[(torch.Tensor, List[torch.Tensor])]:
raise NotImplemented() |
def openfile(filename, *args, **kwargs):
try:
return gzip.open((filename + '.gz'), *args, **kwargs)
except FileNotFoundError:
return open(filename, *args, **kwargs) |
('/macbert_correct', methods=['POST', 'GET'])
def correct_api():
if (request.method == 'POST'):
data = request.json
logger.info('Received data: {}'.format(data))
text = data['text']
r = macbert_model.correct(text)
return r
elif ('text' in request.args):
text = req... |
class EPOptRunner(BaseRunner):
def run(self, *, paths, epsilon):
multienvs = (self.env.num_envs > 1)
(n_mb_obs, n_mb_rewards, n_mb_actions, n_mb_values, n_mb_dones, n_mb_neglogpacs) = ([[] for _ in range(paths)], [[] for _ in range(paths)], [[] for _ in range(paths)], [[] for _ in range(paths)], [[]... |
class CrystalDiagramAutomorphism(CrystalMorphism):
def __init__(self, C, on_hw, index_set=None, automorphism=None, cache=True):
if (automorphism is None):
automorphism = (lambda i: i)
if (index_set is None):
index_set = ()
self._twist = automorphism
if isinsta... |
def variable_on_cpu(name, shape, initializer, trainable=True):
with tf.device('/cpu:0'):
dtype = (tf.float16 if FLAGS.use_fp16 else tf.float32)
var = tf.get_variable(name, shape, initializer=initializer, dtype=dtype, trainable=trainable)
return var |
def evaluate(model, eval_iterator, do_mi=False, do_contrast_spearmanr=True, latent_space_type='plain', return_pred=False):
eval_contrastive_loss_total = 0
eval_same_label_loss_total = 0
model.eval()
num_eval_batch = 0
contrast_preds = []
contrast_targs = []
with torch.no_grad():
for ... |
def make_index(data_path):
index = {'version': '1.0', 'clips': {}, 'metadata': {'BirdVoxDCASE20k_csvpublic': ['BirdVoxDCASE20k_csvpublic.csv', md5(os.path.join(data_path, 'BirdVoxDCASE20k_csvpublic.csv'))]}}
clips = glob.glob(os.path.join(data_path, '*.wav'))
for clip in tqdm(clips):
clip_id = os.pa... |
def _random_package_name(filename):
return (((_CFG_PACKAGE_NAME + str(uuid.uuid4())[:4]) + '.') + os.path.basename(filename)) |
class ConvertBlock(nn.Module):
def __init__(self, in_channels, out_channels, blocks):
super(ConvertBlock, self).__init__()
self.body = nn.Sequential(nn.Conv2d((in_channels * blocks), ((out_channels * blocks) // 2), 3, 1, 1), nn.ReLU(inplace=True), nn.Conv2d(((out_channels * blocks) // 2), ((out_chan... |
def basic_unit(x, rate):
in_channels = x.shape[3]
x = slim.conv2d(x, in_channels, (1, 1), stride=1, scope='conv1x1_before')
x = separable_conv2d(x, kernel=3, stride=1, rate=rate, activation_fn=None, scope='depthwise')
x = slim.conv2d(x, in_channels, (1, 1), stride=1, scope='conv1x1_after')
return x |
def _calculate_mcd_f0(file_list, gt_root, f0_all, results):
for (i, cvt_wav_path) in enumerate(file_list):
basename = get_basename(cvt_wav_path)
(trgspk, number) = get_trgspk_and_number(basename)
f0min = f0_all[trgspk]['f0min']
f0max = f0_all[trgspk]['f0max']
gt_wav_path = os... |
def test_benchmark_clone(benchmark_test_case):
cloned = benchmark_test_case.clone()
for i in range(BENCHMARK_REPETITIONS):
cloned = cloned.clone()
assert (cloned == benchmark_test_case) |
def initialize():
for i in range(n_particle_x):
for j in range(n_particle_y):
t = mesh(i, j)
x[t] = [(0.1 + ((i * dx) * 0.5)), (0.7 + ((j * dx) * 0.5))]
v[t] = [0, (- 1)]
for i in range((n_particle_x - 1)):
for j in range((n_particle_y - 1)):
eid =... |
def sentence_loader(root_dir):
for doc in DocumentLoader(root_dir):
for sent in doc.sentences:
(yield {'doc_name': doc.name, 'i': sent.i, 'words': sent.words, 'abs_char_offsets': sent.abs_char_offsets, 'pos_tags': sent.pos_tags, 'text': sent.text}) |
def bias_init_with_prob(prior_prob):
bias_init = float((- np.log(((1 - prior_prob) / prior_prob))))
return bias_init |
def test_clean_fuzzy_dist(df_typo_countries: pd.DataFrame) -> None:
df_clean_dist1 = clean_country(df_typo_countries, 'messy_country', fuzzy_dist=1)
df_clean_dist2 = clean_country(df_typo_countries, 'messy_country', fuzzy_dist=2)
df_check_dist1 = df_typo_countries.copy()
df_check_dist1['messy_country_cl... |
class NoiseScheduleVP():
def __init__(self, schedule='discrete', betas=None, alphas_cumprod=None, continuous_beta_0=0.1, continuous_beta_1=20.0):
if (schedule not in ['discrete', 'linear', 'cosine']):
raise ValueError("Unsupported noise schedule {}. The schedule needs to be 'discrete' or 'linear... |
def test_categorical_encoder(device):
from speechbrain.dataio.encoder import CategoricalEncoder
encoder = CategoricalEncoder()
encoder.expect_len(4)
encoder.update_from_iterable('abcd')
integers = encoder.encode_sequence('dcba')
assert all((isinstance(i, int) for i in integers))
assert encod... |
def build_ftrl(model, engine='SIMD', **kwargs):
if (engine == 'SIMD'):
assert core.IsOperator('Ftrl_ENGINE_SIMD')
assert core.IsOperator('SparseFtrl_ENGINE_SIMD')
ftrl_optimizer = FtrlOptimizer(engine=engine, **kwargs)
return _build(model, ftrl_optimizer) |
def load_graph(file_name):
with open(file_name, 'rb') as f:
content = f.read()
graph_def = tf.GraphDef()
graph_def.ParseFromString(content)
with tf.Graph().as_default() as graph:
tf.import_graph_def(graph_def, name='')
return graph |
def add_edge(G, center_feature):
num = center_feature.shape[0]
for i in range(num):
for j in range((i + 1), num):
distance = get_distance(G._node[i]['coordinate'], G._node[j]['coordinate'])
G.add_edge(i, j, weight=distance)
return G |
class CreateDefaultMaterials(bpy.types.Operator):
bl_idname = 'object.create_default_mats'
bl_label = 'Create Default Materials'
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
if (bpy.data.materials.get('ClothMaterial') is None):
mat_name = 'ClothMaterial'
... |
class MeshElementFieldProxy():
def __init__(self, mesh: MeshInstance, element_type: MeshElementType, entry_expr: impl.Expr):
ast_builder = impl.get_runtime().compiling_callable.ast_builder()
self.mesh = mesh
self.element_type = element_type
self.entry_expr = entry_expr
elemen... |
_module()
class BerHuLoss(nn.Module):
def __init__(self, loss_name, loss_weight):
super(BerHuLoss, self).__init__()
def forward(self, pred, label, is_vector=None):
if (not is_vector):
(n, c, h, w) = pred.size()
assert (c == 1)
pred = pred.squeeze()
... |
def get_loader(img_root, gt_root, img_size, batch_size, max_num=float('inf'), istrain=True, shuffle=False, num_workers=0, pin=False):
if istrain:
transform = Compose([RandomScaleCrop((img_size * 2), (img_size * 2)), FixedResize(img_size), RandomHorizontalFlip(), RandomRotation(((- 90), 90)), ToTensor(), Nor... |
class SentenceAnnotation(object):
def __init__(self, text):
self.text = text
self.tokens = []
self.postags = []
self.nltkpostags = []
self.nltklemmas = []
self.foundpos = False
self.stindices = {}
self.enindices = {}
def add_token(self, startend):
... |
def expect_quitall(verbose=False):
for P in expect_objects:
R = P()
if (R is not None):
try:
R.quit(verbose=verbose)
except RuntimeError:
pass
kill_spawned_jobs() |
def get_parser(**parser_kwargs):
def str2bool(v):
if isinstance(v, bool):
return v
if (v.lower() in ('yes', 'true', 't', 'y', '1')):
return True
elif (v.lower() in ('no', 'false', 'f', 'n', '0')):
return False
else:
raise argparse.Argum... |
.core
.parametrize('borders', [{'beta': [1, 2]}, {'lambda_': [1, 2]}])
def test_partial_borders(borders):
model = SLIM()
res = model._prepare_param_borders(borders)
assert (len(res) == len(model._search_space)) |
def convert_checkpoint_helper(max_position_embeddings, orig_state_dict):
for key in orig_state_dict.copy().keys():
val = orig_state_dict.pop(key)
if (('pooler' in key) or ('sen_class' in key)):
continue
else:
orig_state_dict[rename_key(key)] = val
orig_state_dict[... |
class DetectionEvalWrapper(nn.Module):
def __init__(self, model, device):
super(DetectionEvalWrapper, self).__init__()
self.model = model
self.device = device
self.anchor_boxes = Anchors(cfg.MIN_LEVEL, cfg.MAX_LEVEL, cfg.NUM_SCALES, cfg.ASPECT_RATIOS, cfg.ANCHOR_SCALE, cfg.MODEL.IMAG... |
def update(G, B, h):
R = h.parent()
C = set(((h, g) for g in G))
D = set()
while C:
(h, g) = C.pop()
lcm_divides = (lambda rhs: R.monomial_divides(LCM(LM(h), LM(rhs[1])), LCM(LM(h), LM(g))))
if (R.monomial_pairwise_prime(LM(h), LM(g)) or ((not any((lcm_divides(f) for f in C))) an... |
def register_Ns3DsrNetworkKey_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
cls.add_constructor([])
cls.add_constructor([param('ns3::dsr::NetworkKey const &', 'arg0')])
cls.add_instance_attribute('m_ackId', 'uint16_t', is_const=False)
cls.add_instance_attribute('m_destination', ... |
def save_epoch_accuracy(tb, set, iou, miou, epoch):
for i in range(NUM_CLASSES):
tb.add_scalar(('%sAccuracy/%s class accuracy' % (set, trainId2label[i].name)), iou[i], epoch)
tb.add_scalar(('%sAccuracy/Accuracy History [mIoU]' % set), miou, epoch) |
class CyclicPermutationsOfPartition(Permutations):
def __classcall_private__(cls, partition):
partition = tuple(map(tuple, partition))
return super().__classcall__(cls, partition)
def __init__(self, partition):
self.partition = partition
Permutations.__init__(self, category=Finit... |
def test_isotonic_non_regression_inf_slope():
X = np.array([0.0, 4.1e-320, 4.4e-314, 1.0])
y = np.array([0.42, 0.42, 0.44, 0.44])
ireg = IsotonicRegression().fit(X, y)
y_pred = ireg.predict(np.array([0, 2.1e-319, 5.4e-316, 1e-10]))
assert np.all(np.isfinite(y_pred)) |
class OnnxSeq2SeqConfigWithPast(OnnxConfigWithPast):
def outputs(self) -> Mapping[(str, Mapping[(int, str)])]:
common_outputs = super(OnnxConfigWithPast, self).outputs
for (name, axes_names) in common_outputs.items():
sequence_name = ('encoder_sequence' if ('encoder' in name) else 'decod... |
def pad_batch(batch, padding=(- 1)):
max_len = max([len(b) for b in batch])
new_batch = []
for b in batch:
b_ = (np.zeros(max_len, dtype=b.dtype) + padding)
b_[:len(b)] = b
new_batch.append(b_)
return new_batch |
(spacepy.lib.have_libspacepy, 'No C backend')
class BootstrapTestsPython(BootstrapTests):
def setUp(self):
spacepy.lib.have_libspacepy = False
super(BootstrapTestsPython, self).setUp()
def tearDown(self):
super(BootstrapTestsPython, self).tearDown()
spacepy.lib.have_libspacepy = ... |
def vae_loss_mse(y_hat, target, mu, logvar, *, kld_prefactor=1.0):
recon_loss = torch.nn.functional.mse_loss(y_hat, target, reduction='mean')
KLD = (((- 0.5) * torch.sum((((1 + logvar) - mu.pow(2)) - logvar.exp()))) / y_hat.shape[0])
return (recon_loss + (kld_prefactor * KLD)) |
def assert_close(actual: Any, expected: Any, *, allow_subclasses: bool=True, rtol: Optional[float]=None, atol: Optional[float]=None, equal_nan: bool=False, check_device: bool=True, check_dtype: bool=True, check_stride: bool=False, check_is_coalesced: bool=True, msg: Optional[Union[(str, Callable[([Tensor, Tensor, Diagn... |
class StructField(object):
def __init__(self, parent, member, type_map, args):
self.args = args
self.parent = parent
self.struct = parent.struct
self.member = member
self.lcm_name = member.name
self.proto_name = member.name.lower()
self.repeated = isinstance(m... |
class MapDatasetBase(object):
def __init__(self, data_types=None):
self.data_types = (data_types or {})
def __len__(self):
raise NotImplementedError
def __getitem__(self, seq_idx):
raise NotImplementedError
def get_seq_len(self, seq_idx):
raise OptionalNotImplementedError... |
def test_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': 'object', 'pro... |
def valid(args, model, data_loader):
criterion = torch.nn.CrossEntropyLoss()
metric_logger = misc.MetricLogger(delimiter=' ')
header = 'Test:'
model.eval()
print('++++++ Running Validation ++++++')
for batch in metric_logger.log_every(data_loader, 10, header):
images = batch[0]
... |
def ref_max_pooling_3d(x, kernel, stride, ignore_border, pad):
y = []
for xx in x.reshape((((- 1),) + x.shape[(- 4):])):
if (xx.ndim == 3):
xx = xx[np.newaxis]
y += [refs.pooling_3d(xx, 'max', kernel, stride, pad, ignore_border)[np.newaxis]]
y = np.vstack(y)
if (x.ndim == 3):... |
def U_6(params, wires):
qml.RX(params[0], wires=wires[0])
qml.RX(params[1], wires=wires[1])
qml.RZ(params[2], wires=wires[0])
qml.RZ(params[3], wires=wires[1])
qml.CRX(params[4], wires=[wires[1], wires[0]])
qml.CRX(params[5], wires=[wires[0], wires[1]])
qml.RX(params[6], wires=wires[0])
... |
def init_net(net, net_file):
if net_file:
net.load_state_dict(torch.load(net_file))
else:
net.apply(weights_init) |
def test_StaticDataset_utf8():
s = 'wer'
print('some unicode str:', s, 'repr:', repr(s), 'type:', type(s), 'len:', len(s))
assert (len(s) == 3)
if PY3:
assert isinstance(s, str)
s_byte_list = list(s.encode('utf8'))
else:
assert isinstance(s, unicode)
s_byte_list = lis... |
_builder('violin_entailment_instruct')
class ViolinEntailmentInstructBuilder(BaseDatasetBuilder):
train_dataset_cls = ViolinVideoEntailmentInstructDataset
eval_dataset_cls = ViolinVideoEntailmentInstructDataset
DATASET_CONFIG_DICT = {'default': 'configs/datasets/violin/defaults_entail_instruct.yaml'} |
class Cache():
def __init__(self, enabled=True, gpu=False):
self.cache = {}
self._mutex = Lock()
self.enabled = enabled
self.gpu = gpu
def get(self, fun, args):
if (not self.enabled):
return fun(*args)
self._mutex.acquire(blocking=True)
result ... |
class Categorical(D.Categorical, Likelihood):
def __prior__(cls):
return E.Dirichlet
def from_model_params(cls, x):
return cls(x.softmax((- 1)))
def mean(self):
return self.logits.argmax((- 1))
def sufficient_statistic_mean(self):
return self.probs
def to(self, *args,... |
class Conv2DTransposeBNFoldingTest(BaseBatchNormalizationFolding):
def __init__(self, unit_test):
super().__init__(unit_test, linear_layer=layers.Conv2DTranspose)
def create_networks(self):
inputs = layers.Input(shape=self.get_input_shapes()[0][1:])
x = self.linear_layer(2, 3, padding='s... |
class TestParameterCounter(unittest.TestCase):
def representative_dataset(self, in_shape=(1, 8, 8, 3)):
for _ in range(1):
(yield [np.random.randn(*in_shape)])
def test_conv_layer(self):
out_channels = 2
in_channels = 1
kernel_size = 3
use_bias = True
... |
def plot_flows(fdf, map_f=None, min_flow=0, tiles='cartodbpositron', zoom=6, flow_color='red', opacity=0.5, flow_weight=5, flow_exp=0.5, style_function=flow_style_function, flow_popup=False, num_od_popup=5, tile_popup=True, radius_origin_point=5, color_origin_point='#3186cc', control_scale=True):
if (map_f is None)... |
class Pool2DBlock(nn.Module):
def __init__(self, pool_size):
super(Pool2DBlock, self).__init__()
self.pool_size = pool_size
def forward(self, x):
return F.max_pool2d(x, kernel_size=self.pool_size, stride=self.pool_size) |
def seed(seed=0):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
dgl.random.seed(seed) |
def load_checkpoint(checkpoint_path, model, optimizer):
assert os.path.isfile(checkpoint_path)
print("Loading checkpoint '{}'".format(checkpoint_path))
checkpoint_dict = torch.load(checkpoint_path, map_location='cpu')
model.load_state_dict(checkpoint_dict['state_dict'])
optimizer.load_state_dict(che... |
def barrier(group=group.WORLD):
assert (torch.distributed.deprecated._initialized == _INITIALIZED_PG), 'collective only supported in process-group mode'
return torch._C._dist_barrier(group) |
def check_requirements(cargs):
lcov = which('lcov')
gcov = which('gcov')
genhtml = which('genhtml')
timeout = which('timeout')
if (timeout == None):
timeout = which(cargs.timeout_path)
if (lcov == None):
lcov = which(cargs.lcov_path)
if (genhtml == None):
genhtml = wh... |
def match_file(dir_name: str, cache_dir: Path) -> str:
files = os.listdir(cache_dir)
matched_filenames = []
for file_name in files:
if (re.match((dir_name + '$'), file_name) or re.match((dir_name + '\\..*'), file_name)):
matched_filenames.append(file_name)
if (len(matched_filenames) ... |
class OptunaTuner(ParamsTuner):
_name: str = 'OptunaTuner'
study: optuna.study.Study = None
estimated_n_trials: int = None
mean_trial_time: Optional[int] = None
def __init__(self, timeout: Optional[int]=1000, n_trials: Optional[int]=100, direction: Optional[str]='maximize', fit_on_holdout: bool=True... |
def compute_influences_parallel(device_ids: List[int], train_dataset: GlueDataset, batch_size: int, model: torch.nn.Module, test_inputs: Dict[(str, torch.Tensor)], params_filter: Optional[List[str]]=None, weight_decay: Optional[float]=None, weight_decay_ignores: Optional[List[str]]=None, s_test_damp: float=3e-05, s_tes... |
def run_jacobi_1d(device_type: dace.dtypes.DeviceType):
(TSTEPS, N) = sizes['small']
(A, B) = initialize(N)
A_ref = np.copy(A)
B_ref = np.copy(B)
if (device_type in {dace.dtypes.DeviceType.CPU, dace.dtypes.DeviceType.GPU}):
sdfg = jacobi_1d_kernel.to_sdfg()
sdfg = auto_optimize(sdfg,... |
class IMBALANCECIFAR10(torchvision.datasets.CIFAR10):
cls_num = 10
def __init__(self, root, imb_type='exp', imb_factor=0.01, rand_number=0, train=True, transform=None, target_transform=None, download=False):
super(IMBALANCECIFAR10, self).__init__(root, train, transform, target_transform, download)
... |
def test_ByteMaskedArray_NumpyArray():
v2a = ak.contents.bytemaskedarray.ByteMaskedArray(ak.index.Index(np.array([1, 0, 1, 0, 1], np.int8)), ak.contents.numpyarray.NumpyArray(np.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6])), valid_when=True)
_cuda.jit(extensions=[ak.numba.cuda])
def f(out, obj):
out[0] = l... |
.parametrize('csr_container', (CSR_CONTAINERS + [None]))
def test_dtype_preserved(csr_container, global_dtype):
rng = np.random.RandomState(0)
X = rng.rand(10, 2).astype(global_dtype, copy=False)
if (csr_container is not None):
X[(X < 0.8)] = 0
X = csr_container(X)
km = BisectingKMeans(n... |
def test_set_last_execution_result(test_case_chromosome):
result = MagicMock(ExecutionResult)
test_case_chromosome.set_last_execution_result(result)
assert (test_case_chromosome.get_last_execution_result() == result) |
class PythonComponent(Component):
def __init__(self, name, libz3Component):
assert isinstance(libz3Component, DLLComponent)
global PYTHON_ENABLED
Component.__init__(self, name, None, [])
self.libz3Component = libz3Component
def main_component(self):
return False
def m... |
def move_cache(cache_dir=None, new_cache_dir=None, token=None):
if (new_cache_dir is None):
new_cache_dir = TRANSFORMERS_CACHE
if (cache_dir is None):
old_cache = (Path(TRANSFORMERS_CACHE).parent / 'transformers')
if os.path.isdir(str(old_cache)):
cache_dir = str(old_cache)
... |
def barrier_if_distributed() -> None:
if (dist.is_available() and dist.is_initialized()):
dist.barrier() |
def test_case133():
url = (brokerIp + '/ngsi-ld/v1/subscriptions/')
headers = {'Content-Type': 'application/json', 'Accept': 'application/ld+json', 'Link': '<{{link}}>; rel=" type="application/ld+json"'}
r = requests.post(url, data=json.dumps(ld_data.subdata132), headers=headers)
print(r.content)
pr... |
def _log_factor_(self, base=None, locals=None):
log_factor = self._log_factor_(base=base, locals=locals)
for (g, c) in log_factor:
if (hasattr(g, 'parent') and isinstance(g.parent(), GenericGrowthGroup)):
continue
from .misc import log_string
raise ArithmeticError(('Cannot bu... |
def _tags_to_preslots(tags, tokens, is_start_of_slot, is_end_of_slot):
slots = []
current_slot_start = 0
for (i, tag) in enumerate(tags):
if is_start_of_slot(tags, i):
current_slot_start = i
if is_end_of_slot(tags, i):
slots.append({RANGE: {START: tokens[current_slot_... |
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial) |
def simplify_mesh(mesh, f_target=10000, agressiveness=7.0):
vertices = mesh.vertices
faces = mesh.faces
(vertices, faces) = mesh_simplify(vertices, faces, f_target, agressiveness)
mesh_simplified = trimesh.Trimesh(vertices, faces, process=False)
return mesh_simplified |
def get_sgd_weight_predictor(sgd_type: str, pred_mem: str, pred_type: str, optimizer, scheduler=None, nag_with_predictor=False, true_weights_storage=None) -> WeightPredictor:
has_weight_decay = any([(pg['weight_decay'] != 0) for pg in optimizer.param_groups])
if has_weight_decay:
if (pred_type == 'msnag... |
def register_types(module):
root_module = module.get_root()
module.add_class('Address', import_from_module='ns.network')
module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address'], import_from_module='ns.network')
module.add_class('AsciiTraceHelper', import_from_module='ns.networ... |
class JointTrainAgent(iql.IQLAgent):
network: TrainState = None
def pretrain_update(agent, pretrain_batch, seed=None, value_update=True, actor_update=True, high_actor_update=True):
def loss_fn(network_params):
info = {}
if value_update:
(value_loss, value_info) = ... |
class CallStack():
def __init__(self, frames):
self.frames = frames
def from_here(project_root, start_from=1):
stack = inspect.stack()
context = []
try:
for frame_info in stack[start_from:]:
if (not frame_info.filename.startswith(project_root)):
... |
def get_embedding(text, model='text-embedding-ada-002'):
text = text.replace('\n', ' ')
if (len(text) > 50):
text = ' '.join(text.split(' ')[:50])
for _ in range(5):
try:
return openai.Embedding.create(input=[text], model=model)['data'][0]['embedding']
except:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.