code stringlengths 101 5.91M |
|---|
def _resolve_handlers(l):
if (not isinstance(l, ConvertingList)):
return l
return [l[i] for i in range(len(l))] |
_experiment(snapshot_mode='none')
def sac_half_cheetah_batch(ctxt=None, seed=1):
deterministic.set_seed(seed)
runner = LocalRunner(snapshot_config=ctxt)
env = GarageEnv(normalize(gym.make('HalfCheetah-v2')))
policy = TanhGaussianMLPPolicy(env_spec=env.spec, hidden_sizes=[256, 256], hidden_nonlinearity=n... |
class Resnet152Triplet(nn.Module):
def __init__(self, embedding_dimension=512, pretrained=False):
super(Resnet152Triplet, self).__init__()
self.model = resnet152(pretrained=pretrained)
input_features_fc_layer = self.model.fc.in_features
self.model.fc = nn.Linear(input_features_fc_lay... |
class MpiAdam(object):
def __init__(self, var_list, *, beta1=0.9, beta2=0.999, epsilon=1e-08, scale_grad_by_procs=True, comm=None):
self.var_list = var_list
self.beta1 = beta1
self.beta2 = beta2
self.epsilon = epsilon
self.scale_grad_by_procs = scale_grad_by_procs
siz... |
.parametrize('print_changed_only', [True, False])
def test_one_estimator_print_change_only(print_changed_only):
pca = PCA(n_components=10)
with config_context(print_changed_only=print_changed_only):
pca_repr = html.escape(str(pca))
html_output = estimator_html_repr(pca)
assert (pca_repr ... |
def masked_l2(preds, actuals, mask):
loss = tf.nn.l2(preds, actuals)
mask = tf.cast(mask, dtype=tf.float32)
mask /= tf.reduce_mean(mask)
loss *= mask
return tf.reduce_mean(loss) |
def plot_all_task_group_box_plots(df_results: pd.DataFrame, score: str, path_to_output_dir: str, model_heads: Optional[List[Tuple[(str, str)]]]=None):
(fig, axes) = plt.subplots(2, 2, figsize=(12, 12))
task_groups: List[str] = list(TASK_GROUP_2_LABELING_FUNCTION.keys())
for (idx, task_group) in tqdm(enumera... |
class Germany(Domain):
def __init__(self):
Domain.__init__(self)
try:
import fiona
import shapely.geometry
except ModuleNotFoundError:
raise ModuleNotFoundError('The Germany domain requires fiona and shapely. Please install fiona and shapely, e.g., using p... |
class LaheyFCompiler(FCompiler):
compiler_type = 'lahey'
description = 'Lahey/Fujitsu Fortran 95 Compiler'
version_pattern = 'Lahey/Fujitsu Fortran 95 Compiler Release (?P<version>[^\\s*]*)'
executables = {'version_cmd': ['<F90>', '--version'], 'compiler_f77': ['lf95', '--fix'], 'compiler_fix': ['lf95',... |
def inject_inferable_lora(model, lora_path='', unet_replace_modules=['UNet3DConditionModel'], text_encoder_replace_modules=['CLIPEncoderLayer'], is_extended=False, r=16):
from transformers.models.clip import CLIPTextModel
from diffusers import UNet3DConditionModel
def is_text_model(f):
return (('tex... |
def calc_body_body_forces_torques_python_new(bodies, r_vectors, *args, **kwargs):
Nbodies = len(bodies)
force_torque_bodies = np.zeros(((2 * len(bodies)), 3))
torque = kwargs.get('omega_one_roller')
constant_torque_counter = 0
for i in range(Nbodies):
if (bodies[i].ID == 'bacteria_constant_t... |
class GcnHIVNet(HIVNet):
def make_graph_layer(self, hidden_dim, layer_idx):
return GCNConv(hidden_dim, hidden_dim) |
def update_namespace_defs(old_defs: List[List[str]], new_defs: List[List[str]]) -> List[List[str]]:
next_insert_pos = 0
for new_def in new_defs:
if (not new_def):
continue
type_and_name = get_def_type_and_name(new_def)
if (type_and_name is None):
raise Exception('... |
def test_shuffle():
movieLensDataHandler = AEDataHandler('MovieLensSmall', train_data_path, validation_input_data_path, validation_output_data_path, test_input_data_path, test_output_data_path)
train_dataloader = movieLensDataHandler.get_train_dataloader(shuffle=False)
first = True
first_batch = None
... |
def _check_assert(user_ids, item_ids, user_answer, item_answer):
for (idx, item_id) in enumerate(item_ids):
assert (sorted(item_id) == sorted(item_answer[idx]))
assert (sorted(user_ids[idx]) == sorted(user_answer[idx])) |
def covariate_observer(run, intervention):
prev_state = run[max((intervention.time - 1), 0)].values()
curr_state = run[intervention.time].values()
return np.concatenate([prev_state, curr_state]) |
def MinMaxScaler(data):
numerator = (data - np.min(data, 0))
denominator = (np.max(data, 0) - np.min(data, 0))
norm_data = (numerator / (denominator + 1e-07))
return norm_data |
.skipif((environ.get('DB_URL', '') == ''), reason='Skip tests that requires database setup and sql query specified')
def test_read_sql() -> None:
db_url = environ['DB_URL']
sql = os.path.join(os.getcwd(), 'dependency_example')
lx = lineagex(sql, 'mimiciii_derived', db_url, 'mimiciii_clinical, public')
p... |
def evaluate_weight(dpr_dict, bm25_dict, qrels, mode, weight_dpr, weight_bm25, measurements={'recall_1', 'recall_2', 'recall_3', 'recall_4', 'recall_5', 'recall_6', 'recall_7', 'recall_8', 'recall_9', 'recall_10', 'P_1', 'P_2', 'P_3', 'P_4', 'P_5', 'P_6', 'P_7', 'P_8', 'P_9', 'P_10'}):
output_dir2 = '/mnt/c/Users/s... |
def get_recall(sess):
goal_item = get_goal_item(sess)
retri_items = get_session_items(sess)
if (goal_item in retri_items):
return 1
else:
return 0 |
def random_frame_sampling(cfg: Dict, total_video_len: int, use_fractional_t: bool=False) -> np.ndarray:
min_time_diff = (cfg['num_frames_per_video'] - 1)
max_time_diff = min((total_video_len - 1), cfg.get('max_dist', float('inf')))
if (type(cfg.get('total_dists')) in (list, tuple)):
time_diff_range ... |
def fast_hash(obj):
_hash_state.update(obj)
result = _hash_state.intdigest()
_hash_state.reset()
return result |
class SeparableConv2d_same(nn.Module):
def __init__(self, inplanes, planes, kernel_size=3, stride=1, dilation=1, bias=False, padding=0):
super(SeparableConv2d_same, self).__init__()
self.depthwise = nn.Conv2d(inplanes, inplanes, kernel_size, stride, padding, dilation, groups=inplanes, bias=bias)
... |
def add_indent_lines(prefix, s):
if (not s):
return prefix
prefix_len = str_visible_len(prefix)
lines = s.splitlines(True)
return ''.join(([(prefix + lines[0])] + [((' ' * prefix_len) + line) for line in lines[1:]])) |
def clean(opts):
logs = glob.glob(os.path.join(opts.ckpt_dir, '*checkpoint*'))
print(logs)
for log in logs:
with open(log, 'r') as log_f:
log_ = json.load(log_f)
for fname in log_['latest']:
fpath = os.path.join(opts.ckpt_dir, ('weights_' + fname))
... |
def my_glob(folder):
for p in [f'{folder}/*', f'{folder}/*/*', f'{folder}/*/*/*']:
for f in glob.glob(p):
(yield f) |
def test_sparray_norm():
row = np.array([0, 0, 1, 1])
col = np.array([0, 1, 2, 3])
data = np.array([4, 5, 7, 9])
test_arr = scipy.sparse.coo_array((data, (row, col)), shape=(2, 4))
test_mat = scipy.sparse.coo_matrix((data, (row, col)), shape=(2, 4))
assert_equal(spnorm(test_arr, ord=1, axis=0), ... |
(frozen=True)
class GeneralInfo():
version: str
example_queries: List[Query]
all_models: List[ModelMetadata] |
class UbuntuDataUtils(object):
def __init__(self, txt_path, bert_pretrained_dir):
self.txt_path = txt_path
self._bert_tokenizer_init(bert_pretrained_dir)
def _bert_tokenizer_init(self, bert_pretrained_dir, bert_pretrained='bert-base-uncased'):
self._bert_tokenizer = tokenization_bert.Ber... |
def get_ap_offset(expr: Expression) -> Optional[int]:
reg_and_offset = get_reg_offset(expr)
if (reg_and_offset is None):
return None
(reg, offset) = reg_and_offset
return (None if (reg != Register.AP) else offset) |
class Adadelta(Optimizer):
def __init__(self, params, lr=1.0, rho=0.9, eps=1e-06, weight_decay=0):
if (not (0.0 <= lr)):
raise ValueError('Invalid learning rate: {}'.format(lr))
if (not (0.0 <= rho <= 1.0)):
raise ValueError('Invalid rho value: {}'.format(rho))
if (no... |
def make_builder(out_file, impl, vocab_size=None):
if (impl == 'mmap'):
return MMapIndexedDatasetBuilder(out_file, dtype=best_fitting_int_dtype(vocab_size))
elif (impl == 'fasta'):
raise NotImplementedError
else:
return IndexedDatasetBuilder(out_file) |
def _pairwise_distances(embeddings, squared=False):
dot_product = torch.matmul(embeddings, embeddings.t())
square_norm = torch.diag(dot_product)
distances = ((square_norm.unsqueeze(0) - (2.0 * dot_product)) + square_norm.unsqueeze(1))
distances[(distances < 0)] = 0
if (not squared):
mask = d... |
def train_epoch_with_utterances(batches, model, randomize=True):
if randomize:
random.shuffle(batches)
progbar = get_progressbar('train ', len(batches))
progbar.start()
loss_sum = 0.0
for (i, batch) in enumerate(batches):
batch_loss = model.train_step(batch)
loss_sum += b... |
def beat_seq(ts):
beatCount = ts.numerator
beatDuration = (4 / ts.denominator)
beat_sequence = (([0] * beatCount) * int((beatDuration / 0.25)))
beat_sequence[0] += 1
medium = 0
if ((ts.numerator % 3) == 0):
medium = 3
elif ((ts.numerator % 2) == 0):
medium = 2
for idx in ... |
def fuzzy_parse_action(text):
text = text.strip(' ').strip('.')
pattern = '^(\\w+)\\[(.+)\\]'
match = re.match(pattern, text)
if match:
action_type = match.group(1)
argument = match.group(2)
return (action_type, argument)
else:
return (text, '') |
def get_last_window_attn_mask(window_size, max_seq_length=800):
assert (window_size > 0)
counter = 0
causal_mask = torch.tril(torch.ones(max_seq_length, max_seq_length))
for i in range(max_seq_length):
for j in range((i + 1)):
if ((i - j) <= window_size):
causal_mask[... |
def get_model(model_name, config, is_training=True, inference_only=False, num_pass=1, num_node=1, inp=None, label=None, batch_size=None):
config_dict = dict(config.__dict__)
config_copy = json.loads(json.dumps(config_dict), object_hook=(lambda d: namedtuple('X', d.keys())(*d.values())))
key = model_name
... |
def _get_epoch_timings():
times_itrs = gt.get_times().stamps.itrs
times = OrderedDict()
epoch_time = 0
for key in sorted(times_itrs):
time = times_itrs[key][(- 1)]
epoch_time += time
times['time/{} (s)'.format(key)] = time
times['time/epoch (s)'] = epoch_time
times['time/... |
def process_config(args):
if (args.config_file is not None):
with open(args.config_file) as file:
raw_config = yaml.load(file, Loader=yaml.Loader)
os.makedirs(args.save_path, exist_ok=True)
shutil.copy(args.config_file, os.path.join(args.save_path, 'config.yaml'))
else:
... |
def test_list_array():
array = ak.highlevel.Array(np.arange(((3 * 5) * 2)).reshape(3, 5, 2).tolist())
assert (ak.operations.num(array, axis=0) == 3)
assert (ak.operations.num(array, axis=1).to_list() == [5, 5, 5])
assert (ak.operations.num(array, axis=2).to_list() == [[2, 2, 2, 2, 2], [2, 2, 2, 2, 2], [... |
_module()
class MaskRCNN(TwoStageDetector):
'Implementation of `Mask R-CNN <
def __init__(self, backbone, rpn_head, roi_head, train_cfg, test_cfg, neck=None, pretrained=None):
super(MaskRCNN, self).__init__(backbone=backbone, neck=neck, rpn_head=rpn_head, roi_head=roi_head, train_cfg=train_cfg, test_cfg... |
def _test_ndarray_2d():
n = 4
m = 7
def run(x: ti.types.ndarray(), y: ti.types.ndarray()):
for i in range(n):
for j in range(m):
x[(i, j)] += ((i + j) + y[(i, j)])
a = ti.ndarray(ti.i32, shape=(n, m))
for i in range(n):
for j in range(m):
a[(i,... |
def sitk_resample_to_image(image, reference_image, default_value=0.0, interpolator=sitk.sitkLinear, transform=None, output_pixel_type=None):
if (transform is None):
transform = sitk.Transform()
transform.SetIdentity()
if (output_pixel_type is None):
output_pixel_type = image.GetPixelID()... |
class ConvLinSeq(nn.Module):
def __init__(self, input_dims, linear_hidden_dims, conv_hidden_dims, output_dim, kernel_dim, k_lipschitz, p_drop):
super().__init__()
if (k_lipschitz is not None):
k_lipschitz = (k_lipschitz ** (1.0 / 2.0))
self.convolutions = convolution_sequential(i... |
class EncoderBlock(nn.Module):
def __init__(self, n_heads, n_dims, total_ex, total_cat, seq_len, time_width):
super(EncoderBlock, self).__init__()
self.seq_len = seq_len
self.exercise_embed = nn.Embedding(total_ex, n_dims)
self.category_embed = nn.Embedding(total_cat, n_dims)
... |
def check_string(context, obj, stacklevel=3):
if (type(obj) is not str):
warn(("'%s' requires strings, got '%s'" % (context, type(obj).__name__)), WSGIWarning) |
def trainModel(model, trainData, validData, dataset, optim):
sys.stdout.flush()
model.train()
criterion = NMTCriterion(opt.num_classes)
vocab_size = dataset['dicts']['src'].size()
start_time = time.time()
def trainEpoch(epoch):
if (opt.extra_shuffle and (epoch > opt.curriculum)):
... |
class SPN(nn.Module):
def __init__(self, nf=32, spn=1):
super(SPN, self).__init__()
self.mask_conv = nn.Conv2d(3, nf, 3, 1, 1)
self.encoder = VGG(nf)
self.decoder = Decoder(nf, spn)
self.left_right = spn_block(True, False)
self.right_left = spn_block(True, True)
... |
def keep_t_if_possible_handler(info, t):
if (info.graph is info.graph_):
return t
else:
return replace_t_with_placeholder_handler(info, t) |
def bias_variable(shape):
initial = tf.random_normal(shape, mean=0.0, stddev=0.01)
return tf.Variable(initial) |
class BuiltinScope(Scope):
is_builtin_scope = True
def __init__(self):
if (Options.pre_import is None):
Scope.__init__(self, '__builtin__', None, None)
else:
Scope.__init__(self, '__builtin__', PreImportScope(), None)
self.type_names = {}
for (name, defini... |
def make_compute(sdfg, state):
A_pipe_in = state.add_read('A_pipe')
A_pipe_out = state.add_write('A_pipe')
B_pipe_in = state.add_read('B_pipe')
B_pipe_out = state.add_write('B_pipe')
C_pipe_in = state.add_read('C_pipe')
C_pipe_out = state.add_write('C_pipe')
(entry_n0, exit_n0) = state.add_m... |
class DeepSVDDConf(DetectorConfig):
_default_transform = MeanVarNormalize()
def __init__(self, net_name='merlion', xp_path='./results/deepsvdd', load_model='./results/deepsvdd/deepsvdd.pkl', objective='one-class', nu=0.1, device='cpu', seed=(- 1), optimizer_name='adam', lr=0.001, n_epochs=300, lr_milestone=None... |
def main(in_directory, out_directory, short_name):
phrases = get_tokenized_phrases(in_directory)
os.makedirs(out_directory, exist_ok=True)
out_filename = os.path.join(out_directory, ('%s.train.json' % short_name))
process_utils.write_list(out_filename, phrases) |
class ATSDmat(SpectralMatrix):
def assemble(self, method):
(test, trial) = (self.testfunction, self.trialfunction)
assert isinstance(test[0], T)
assert isinstance(trial[0], SD)
N = test[0].N
k = np.arange(N, dtype=float)
self._keyscale = 1
def _getkey(j):
... |
class EvalConfig():
config = attr.ib()
config_args = attr.ib()
logdir = attr.ib()
section = attr.ib()
inferred = attr.ib()
output = attr.ib() |
def random_uniform(dims: Sequence[Dim], *, dtype: Optional[str]=None, device: Optional[str]=None, sparse_dim: Optional[Dim]=None, feature_dim: Optional[Dim]=None, minval: Union[(int, float, Tensor)]=0, maxval: Union[(int, float, Tensor)]=1, seed: Optional[Union[(int, Sequence[int], numpy.ndarray)]]=None, algorithm: Opt... |
.parametrize('name', sorted(PARAMETERS))
.filterwarnings('ignore:.*method is good for exploring strategies.*')
def test_get_examples(name, swagger_20):
if (name == 'body'):
example = expected = {'name': 'John'}
media_type = 'application/json'
cls = PayloadAlternatives
else:
examp... |
def extract_features(number, audio_features, targets, path):
global max_len, min_len
if (not os.path.exists(os.path.join(prefix, '{1}/{0}/positive_out.wav'.format(number, path)))):
return
positive_file = wave.open(os.path.join(prefix, '{1}/{0}/positive_out.wav'.format(number, path)))
sr1 = posit... |
def hardness_metric(batch, num_classes):
if (('train' not in batch) and ('support' not in batch)):
raise ValueError('The tasks do not contain any training/support set. Make sure the tasks contain either the "train" or the "support" key.')
if (('test' not in batch) and ('query' not in batch)):
ra... |
def main(args):
env = gym.make('LunarLander-v2', render_mode='rgb_array')
env = gym.wrappers.RecordVideo(env, args.video_folder)
env.reset()
for _ in range(MAX_STEPS):
img = env.render()
random.shuffle(LUNAR_LANDER_OPTIONS)
options_str = ', '.join(LUNAR_LANDER_OPTIONS)
im... |
class TestBuildCommand():
def setup(self):
self.test_subclasses = [BuildCommandTestImpl]
self.build_command_subclasses_orig = BuildCommand.__subclasses__
BuildCommand._get_implementations = (lambda *_: self.test_subclasses)
self.logger = logging.getLogger('test')
def teardown(sel... |
def _is_fromfile_compatible(stream):
if (sys.version_info[0] < 3):
return True
bad_cls = []
try:
import gzip
bad_cls.append(gzip.GzipFile)
except ImportError:
pass
try:
import bz2
bad_cls.append(bz2.BZ2File)
except ImportError:
pass
bad... |
def test_clobber():
for func_input_type in img_funcs:
for func_output_type in img_funcs:
img = np.random.rand(5, 5)
img_in = func_input_type(img)
img_in_before = img_in.copy()
func_output_type(img_in)
assert_equal(img_in, img_in_before) |
def check_type(obj, expected_type, logger):
if (not isinstance(obj, expected_type)):
exception = TypeError(f'Expected type {type(obj)}, got type {str(expected_type)}')
logger.exception(repr(exception))
raise exception |
def noelse(A: dace.float32[1]):
if (A[0] > 0):
def mytask():
(o >> A[0])
o = 5 |
_module()
class DRIVEDataset(CustomDataset):
CLASSES = ('background', 'vessel')
PALETTE = [[120, 120, 120], [6, 230, 230]]
def __init__(self, **kwargs):
super(DRIVEDataset, self).__init__(img_suffix='.png', seg_map_suffix='_manual1.png', reduce_zero_label=False, **kwargs)
assert osp.exists(s... |
class TBVisualizer(object):
def __init__(self, opt):
self._opt = opt
self._save_path = os.path.join(opt.checkpoints_dir, opt.name)
self._log_path = os.path.join(self._save_path, 'loss_log2.txt')
self._tb_path = os.path.join(self._save_path, 'summary.json')
self._writer = Summ... |
.parametrize('n, user_answer, item_answer', [(5, [[], [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3]], [[], [1, 2, 3, 4, 5, 1, 2, 3, 9, 10, 1, 5, 3, 1, 2]])])
.parametrize('dataset_type', [pytest.param('spark_dataframe_test', marks=pytest.mark.spark), pytest.param('pandas_dataframe_test', marks=pytest.mark.core)])
def t... |
class MarkupLMTokenizerFast(PreTrainedTokenizerFast):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
slow_tokenizer_class = MarkupLMTokenizer
def __init__(self, vocab_file, merges_file, tags... |
class DistributedSampler(_DistributedSampler):
def __init__(self, dataset: Dataset, num_replicas: Optional[int]=None, rank: Optional[int]=None, shuffle: bool=True, seed=0) -> None:
super().__init__(dataset, num_replicas=num_replicas, rank=rank, shuffle=shuffle)
device = get_device()
self.see... |
def _call_method(method, rref, *args, **kwargs):
return method(rref.local_value(), *args, **kwargs) |
class Checkpoint(object):
SAVE_PATH = 'outputs'
LOAD_PATH = '../../../outputs'
TRAINER_STATE_NAME = 'trainer_states.pt'
MODEL_NAME = 'model.pt'
def __init__(self, model: nn.Module=None, optimizer: Optimizer=None, trainset_list: list=None, validset: SpectrogramDataset=None, epoch: int=None) -> None:
... |
def model(inputs, is_training=True):
batch_norm_params = {'is_training': is_training, 'decay': 0.9, 'updates_collections': None}
with slim.arg_scope([slim.conv2d, slim.fully_connected], normalizer_fn=slim.batch_norm, normalizer_params=batch_norm_params):
x = tf.reshape(inputs, [(- 1), 28, 28, 1])
... |
def get_version():
version_file = 'mmhuman3d/version.py'
with open(version_file, 'r', encoding='utf-8') as f:
exec(compile(f.read(), version_file, 'exec'))
return locals()['__version__'] |
def rename_keys(s_dict):
keys = list(s_dict.keys())
for key in keys:
if ('transformer_layers' in key):
s_dict[key.replace('transformer_layers', 'layers')] = s_dict.pop(key)
elif ('subsample' in key):
s_dict[key.replace('subsample', 'conv')] = s_dict.pop(key) |
def test_cases():
for (values, method, expected) in _cases:
r = rankdata(values, method=method)
assert_array_equal(r, expected) |
def convert_pytorch_state_dict_to_flax(pt_state_dict, flax_model):
pt_state_dict = {k: v.numpy() for (k, v) in pt_state_dict.items()}
model_prefix = flax_model.base_model_prefix
random_flax_state_dict = flatten_dict(flax_model.params)
flax_state_dict = {}
load_model_with_head_into_base_model = ((mod... |
def find_last_entry(entries, time_point, start_time):
if (time_point is None):
return (entries[(- 1)], (- 1))
s = utils.time_to_seconds(time_point)
last = None
last_elasp = None
for entry in entries:
timestamp = entry['timestamp']
elasp = (timestamp - start_time)
if (... |
def _mk_fp_unary_pred(f, a, ctx):
ctx = _get_ctx(ctx)
[a] = _coerce_fp_expr_list([a], ctx)
if z3_debug():
_z3_assert(is_fp(a), 'First argument must be a Z3 floating-point expression')
return BoolRef(f(ctx.ref(), a.as_ast()), ctx) |
def _is_long(x):
if hasattr(x, 'data'):
x = x.data
return (isinstance(x, torch.LongTensor) or isinstance(x, torch.cuda.LongTensor)) |
class MyBashProcess(BashProcess):
def _run(self, command: str) -> Tuple[(str, int)]:
try:
output = subprocess.run(command, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).stdout.decode().strip()
except subprocess.CalledProcessError as error:
if self.... |
def _gen_dir_name():
now_str = datetime.now().strftime('%m-%d-%y_%H.%M.%S')
rand_str = ''.join(random.choices(string.ascii_lowercase, k=4))
return f'{now_str}_{rand_str}' |
def test_update():
def fake_condition(memo_info, manager, args):
if ((memo_info.state == 'ENTANGLED') and (memo_info.fidelity > 0.8)):
return [memo_info]
else:
return []
def fake_action(memories, args):
return (FakeProtocol('protocol'), [None], [None], [{}])
t... |
def make(env_id: EnvId):
if (env_id == '2048'):
from pgx.play2048 import Play2048
return Play2048()
elif (env_id == 'animal_shogi'):
from pgx.animal_shogi import AnimalShogi
return AnimalShogi()
elif (env_id == 'backgammon'):
from pgx.backgammon import Backgammon
... |
def NormalFan(polytope, lattice=None):
dimension_error = ValueError('the normal fan is only defined for full-dimensional polytopes')
from sage.geometry.lattice_polytope import is_LatticePolytope
if is_LatticePolytope(polytope):
if (polytope.dim() != polytope.lattice_dim()):
raise dimensi... |
def test_not_complete_and_not_homogeneous_labeling():
(h, c, v) = homogeneity_completeness_v_measure([0, 0, 0, 1, 1, 1], [0, 1, 0, 1, 2, 2])
assert_almost_equal(h, 0.67, 2)
assert_almost_equal(c, 0.42, 2)
assert_almost_equal(v, 0.52, 2) |
class MaxPoolBlock(nn.Module):
expansion = 1
def __init__(self, in_filters, out_filters, shortcut=False, bias=False):
super().__init__()
self.shortcut = shortcut
self.increasing = (out_filters > in_filters)
if self.increasing:
self.max_pool = nn.MaxPool1d(3, stride=2,... |
class ExperimentContext():
def __init__(self, *, snapshot_dir, snapshot_mode, snapshot_gap):
self.snapshot_dir = snapshot_dir
self.snapshot_mode = snapshot_mode
self.snapshot_gap = snapshot_gap |
def test_case47():
url = (brokerIp + '/ngsi-ld/v1/subscriptions/')
headers = {'Content-Type': 'application/json', 'Link': '<{{link}}>; rel=" type="application/ld+json"'}
r = requests.post(url, data=json.dumps(ld_data.subdata36), headers=headers)
print(r.content)
print(r.status_code)
url = (disco... |
class ArchGradientFunction(torch.autograd.Function):
def forward(ctx, x, binary_gates, run_func, backward_func):
ctx.run_func = run_func
ctx.backward_func = backward_func
detached_x = detach_variable(x)
with torch.enable_grad():
output = run_func(detached_x)
ctx.s... |
def visualize_kernel(tensor, ind):
vis = tf.gather_nd(tensor, ind)
(H, W) = vis.get_shape().as_list()
vis = tf.expand_dims(vis, 0)
vis = tf.expand_dims(vis, 3)
vis = tf.image.resize_nearest_neighbor(vis, [(10 * H), (10 * W)])
return vis |
class XLNetForQuestionAnswering():
def __init__(self, *args, **kwargs):
requires_pytorch(self)
def from_pretrained(self, *args, **kwargs):
requires_pytorch(self) |
def _seg_36():
return [(42626, 'M', u''), (42627, 'V'), (42628, 'M', u''), (42629, 'V'), (42630, 'M', u''), (42631, 'V'), (42632, 'M', u''), (42633, 'V'), (42634, 'M', u''), (42635, 'V'), (42636, 'M', u''), (42637, 'V'), (42638, 'M', u''), (42639, 'V'), (42640, 'M', u''), (42641, 'V'), (42642, 'M', u''), (42643, 'V... |
class Logger(object):
def __init__(self, outfile):
self.terminal = sys.stdout
self.log = open(outfile, 'w')
sys.stdout = self
def write(self, message):
self.terminal.write(message)
self.log.write(message)
def flush(self):
self.terminal.flush() |
def install_import_hook(module_to_instrument: str, tracer: ExecutionTracer, coverage_metrics: (set[config.CoverageMetric] | None)=None, dynamic_constant_provider: (DynamicConstantProvider | None)=None) -> ImportHookContextManager:
if (dynamic_constant_provider is None):
dynamic_constant_provider = DynamicCo... |
class Caffe2BenchmarkBase(object):
tensor_index = 0
test_index = 0
def __init__(self):
self.args = {}
self.user_provided_name = None
self._num_inputs_require_grads = 0
self._pass_count = 0
def _set_backward_test(self, is_backward):
pass
def _device_option(self... |
class ShowCategory(Enum):
SUBNET = 5
HOST_CPU = 4
TPU_LAYER = 3
NODE_OP = 2
TPU_GDMA = 1
TPU_BD = 0 |
class Downsampler(nn.Module):
def __init__(self, n_planes, factor, kernel_type, phase=0, kernel_width=None, support=None, sigma=None, preserve_size=False):
super(Downsampler, self).__init__()
assert (phase in [0, 0.5]), 'phase should be 0 or 0.5'
if (kernel_type == 'lanczos2'):
s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.