code stringlengths 101 5.91M |
|---|
.parametrize('observer, model, rule', [(_broken_observer, _PseudoTrainableQuadratic(), FixedAcquisitionRule([[0.0]])), (_quadratic_observer, _BrokenModel(), FixedAcquisitionRule([[0.0]])), (_quadratic_observer, _PseudoTrainableQuadratic(), _BrokenRule())])
def test_bayesian_optimizer_optimize_for_failed_step(observer: ... |
class AnalyserGeneratorTests(unittest.TestCase):
generator = Generator()
analyser = Analyser()
def setUp(self):
self.testFile = open(os.path.join(CURR_DIR, 'tests.json'))
self.tests = json.load(self.testFile, object_hook=Struct)
def tearDown(self):
self.testFile.close()
def t... |
def two_choice(input_dict, k, verbose=False, method='means'):
num_inputs = len(input_dict)
num_dimensions = len(list(input_dict.values())[0])
original_dist_means_array = np.zeros(num_dimensions)
original_dist_inputs_by_dim = []
for d in range(num_dimensions):
inputs = [val[d] for val in inpu... |
class TreePredictor():
def __init__(self, nodes, binned_left_cat_bitsets, raw_left_cat_bitsets):
self.nodes = nodes
self.binned_left_cat_bitsets = binned_left_cat_bitsets
self.raw_left_cat_bitsets = raw_left_cat_bitsets
def get_n_leaf_nodes(self):
return int(self.nodes['is_leaf']... |
class DiscreteProbabilitySpace(ProbabilitySpace_generic, DiscreteRandomVariable):
def __init__(self, X, P, codomain=None, check=False):
if (codomain is None):
from sage.rings.real_mpfr import RealField
codomain = RealField()
if ((not isinstance(codomain, sage.rings.abc.RealFi... |
class EggProvider(NullProvider):
def __init__(self, module):
NullProvider.__init__(self, module)
self._setup_prefix()
def _setup_prefix(self):
path = self.module_path
old = None
while (path != old):
if _is_egg_path(path):
self.egg_name = os.pat... |
def sympy_set_to_list(set, vars):
from sage.rings.infinity import UnsignedInfinity
from sympy import FiniteSet, And, Or, Union, Interval, oo, S
from sympy.core.relational import Relational
if (set == S.Reals):
return [(x._sage_() < oo) for x in vars]
elif (set == S.Complexes):
return... |
def construct_optimizer(model, cfg):
bn_params = []
rest_params = []
for (name, p) in model.named_parameters():
if ('bn' in name):
bn_params.append(p)
else:
rest_params.append(p)
optim_params = []
if bn_params:
optim_params.append({'params': bn_params,... |
class COCODataModule(pl.LightningDataModule):
def __init__(self, data_path, train_batch_size=16, val_batch_size=16, test_batch_size=16, use_data_augmentation=False):
super().__init__()
self.data_path = Path(data_path)
self.annotations_path = (self.data_path / 'annotations')
self.trai... |
class SingleDummyVecEnv2(VecEnv):
def __init__(self, env_fns):
self.envs = [fn() for fn in env_fns]
env = self.envs[0]
VecEnv.__init__(self, len(env_fns), env.observation_space, env.action_space)
self.ts = np.zeros(len(self.envs), dtype='int')
self.actions = None
def step... |
def gumbel_softmax_sample(logits, temperature):
y = (logits + sample_gumbel(logits.shape, tens_type=type(logits.data)))
return F.softmax((y / temperature), dim=1) |
def register_Ns3QueueSizeChecker_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::QueueSizeChecker const &', 'arg0')])
return |
def get_tpc():
tp = mct.target_platform
default_config = tp.OpQuantizationConfig(activation_quantization_method=tp.QuantizationMethod.POWER_OF_TWO, weights_quantization_method=tp.QuantizationMethod.POWER_OF_TWO, activation_n_bits=3, weights_n_bits=2, weights_per_channel_threshold=True, enable_weights_quantizati... |
(**njit_dict_no_parallel)
def macro_atom(activation_level_id, current_shell_id, opacity_state):
current_transition_type = 0
while (current_transition_type >= 0):
probability = 0.0
probability_event = np.random.random()
block_start = opacity_state.macro_block_references[activation_level_i... |
def get_camera_meshes(camera_list, radius=0.02):
verts_list = []
faces_list = []
color_list = []
rots = np.array([quaternion.as_rotation_matrix(camera_info['rotation']) for camera_info in camera_list])
lookat = np.array([0, 0, (- 1)])
vertical = np.array([0, 1, 0])
positions = np.array([came... |
def main():
args = parse_args()
cfg = Config.fromfile(args.config)
update_data_root(cfg)
assert (args.eval or args.format_only), 'Please specify at least one operation (eval/format the results) with the argument "--eval", "--format-only"'
if (args.eval and args.format_only):
raise ValueError... |
def spectral_de_normalize_torch(magnitudes):
output = dynamic_range_decompression_torch(magnitudes)
return output |
def random_deletion(words, p):
if (len(words) == 1):
return words
new_words = []
for word in words:
r = random.uniform(0, 1)
if (r > p):
new_words.append(word)
if (len(new_words) == 0):
rand_int = random.randint(0, (len(words) - 1))
return [words[rand_... |
def srwl_uti_write_data_cols(_file_path, _cols, _str_sep, _str_head=None, _i_col_start=0, _i_col_end=(- 1)):
f = open(_file_path, 'w')
if (_str_head is not None):
lenStrHead = len(_str_head)
if (lenStrHead > 0):
strHead = _str_head
if (_str_head[(lenStrHead - 1)] != '\n')... |
def my_load(model, pretrained_dict):
current_dict = model.state_dict()
new_state_dict = OrderedDict()
for key in current_dict.keys():
if (key in pretrained_dict.keys()):
new_state_dict[key] = pretrained_dict[key]
elif ('encoder1' in key):
if (pretrained_dict[key.repla... |
class GenericObject(object):
def __init__(self, v):
self.v = v
def __add__(self, other):
return self
def __radd__(self, other):
return self
dtype = np.dtype('O') |
.skipif((not has_pytorch()), reason='Pytorch not installed.')
_utils.test(arch=[ti.cpu, ti.opengl])
def test_subscript():
a = ti.ndarray(ti.i32, shape=(10, 10))
def ndarray(x: ti.types.ndarray()):
b = x[(3, 1.1)]
with pytest.raises(ti.TaichiTypeError, match='indices must be integers'):
ndarr... |
_criterion('composite_loss')
class CompositeLoss(FairseqCriterion):
def add_args(parser):
parser.add_argument('--underlying-criterion', type=str, metavar='VAL', required=True, help='underlying criterion to use for the composite loss')
def build_underlying_criterion(args, task):
saved_criterion =... |
def _init_dist_pytorch(backend, **kwargs):
torch.cuda.set_device(int(os.environ['LOCAL_RANK']))
dist.init_process_group(backend=backend, **kwargs) |
class CustomAbsoluteJointVelocity(JointVelocity):
def action(self, scene: Scene, action: np.ndarray):
if (np.random.random() > 0.5):
print('Skip action!')
return
super(CustomAbsoluteJointVelocity, self).action(scene, action) |
def convolve_with_waveform(func, waveform, times, fargs=None, fkwargs=None):
try:
t_nodes = waveform.time_nodes
except AttributeError:
raise TypeError(f'Unsupported waveform type of {type(waveform)}')
if (fargs is None):
fargs = []
if (fkwargs is None):
fkwargs = {}
n... |
_processor('multi_sentence_bert_tokenizer')
class MultiSentenceBertTokenizer(BaseProcessor):
def __init__(self, config, *args, **kwargs):
super().__init__(config, *args, **kwargs)
self.fusion_strategy = config.get('fusion', 'concat')
self._probability = config.get('mask_probability', 0)
... |
def descr_to_dtype(descr):
if isinstance(descr, str):
return numpy.dtype(descr)
elif isinstance(descr, tuple):
dt = descr_to_dtype(descr[0])
return numpy.dtype((dt, descr[1]))
fields = []
offset = 0
for field in descr:
if (len(field) == 2):
(name, descr_st... |
class UniformMutation(Mutation):
def __init__(self, tokenizer=None, mlm_obj=None, safe_mut=False):
self.tokenizer = tokenizer
self.mlm_obj = mlm_obj
self.safe_mut = safe_mut
def _do(self, problem, x, **kwargs):
query_batches = problem.x_to_query_batches(x)
(batch_shape, n... |
def get_extensions():
this_dir = os.path.dirname(os.path.abspath(__file__))
extensions_dir = os.path.join(this_dir, 'src')
main_file = glob.glob(os.path.join(extensions_dir, '*.cpp'))
source_cpu = glob.glob(os.path.join(extensions_dir, 'cpu', '*.cpp'))
source_cuda = glob.glob(os.path.join(extensions... |
def _down_score(level: Array, vul: Array, call_x: Array, call_xx: Array, trick: Array) -> Array:
_DOWN = jnp.array([(- 50), (- 100), (- 150), (- 200), (- 250), (- 300), (- 350), (- 400), (- 450), (- 500), (- 550), (- 600), (- 650)], dtype=jnp.float32)
_DOWN_VUL = jnp.array([(- 100), (- 200), (- 300), (- 400), (... |
def test_range_stmt_non_interactive_wrong_commit(group):
x = Secret(value=14)
randomizer = Secret(value=group.order().random())
(g, h) = make_generators(2, group)
lo = 7
hi = 15
com = ((x * g) + (randomizer * h))
comval = (com.eval() + g)
stmt = RangeStmt(comval, g, h, lo, hi, x, randomi... |
def find_index(input_sequence, tokens):
for i in range(len(input_sequence)):
found = True
j = 0
while (j < len(tokens)):
if (input_sequence[(i + j)] == tokens[j]):
j += 1
else:
found = False
break
if found:
... |
class QuantumMoebiusAlgebra(Parent, UniqueRepresentation):
def __init__(self, L, q=None):
if (not L.is_lattice()):
raise ValueError('L must be a lattice')
if (q is None):
q = LaurentPolynomialRing(ZZ, 'q').gen()
self._q = q
R = q.parent()
cat = Algebra... |
def convert_mesh_to_numpy(mesh_file, npoints=8192):
print('Loading point cloud.')
mesh = trimesh.load_mesh(mesh_file, force='mesh')
mesh = as_mesh(mesh)
vertices = mesh.vertices
num_points = len(vertices)
if (num_points < npoints):
repetitions = int(np.ceil((npoints / num_points)))
... |
def pairwise_distance(query_features, gallery_features, query=None, gallery=None):
if ((query is None) and (gallery is None)):
n = len(features)
x = torch.cat(list(features.values()))
x = x.view(n, (- 1))
dist = (torch.pow(x, 2).sum(1) * 2)
dist = (dist.expand(n, n) - (2 * to... |
class Button():
def __init__(self, name: str, pybullet_server_id=0):
self.pid = pybullet_server_id
self.btn = p.addUserDebugParameter((' %s ' % name), 1, 0, 0, pybullet_server_id)
self.n = 0
def is_click(self) -> bool:
c = p.readUserDebugParameter(self.btn, self.pid)
r = ... |
class Flatten(Module):
def __init__(self):
Module.__init__(self)
self.inputshape = []
def backward(self, DY):
return np.reshape(DY, self.inputshape)
def forward(self, X, *args, **kwargs):
self.inputshape = X.shape
return np.reshape(X, [self.inputshape[0], numpy.prod(s... |
class BaseStream(object):
def __init__(self, mode='w'):
self._i = 0
self._count = (- 1)
if isinstance(mode, int):
self._count = mode
mode = 'r'
elif (mode == 'w'):
self._count = 0
assert (mode in ('r', 'w'))
self._mode = mode
... |
def log_txt_as_img(wh, xc, size=10):
b = len(xc)
txts = list()
for bi in range(b):
txt = Image.new('RGB', wh, color='white')
draw = ImageDraw.Draw(txt)
font = ImageFont.truetype('font/DejaVuSans.ttf', size=size)
nc = int((40 * (wh[0] / 256)))
lines = '\n'.join((xc[bi]... |
class SqueezeBertConfig(PretrainedConfig):
pretrained_config_archive_map = SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP
model_type = 'squeezebert'
def __init__(self, vocab_size=30522, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout_prob=0... |
class values_vec_t(object):
__slots__ = ['x', 'y', 'rot', 'rot_vec', 'scalar_vec', 'list_of_lists']
def __init__(self, x=0.0, y=0.0, rot=None, rot_vec=None, scalar_vec=None, list_of_lists=None, _skip_initialize=False):
if _skip_initialize:
return
self.x = x
self.y = y
... |
def get_KarelDSLSyntax(dsl_type='prob', seed=None):
if (dsl_type == 'prob'):
return KarelDSLProbSyntax(seed=seed)
else:
raise ValueError('Undefined dsl syntax type') |
def get_doctime_class(c, doc_ts, threshold=((24 * 60) * 60)):
if (not doc_ts):
return None
sent_ts = get_sentence_markup(c.get_parent(), 'DATETIME', tagged_sentences)
if (not sent_ts):
return None
sent_ts = [d for d in list(zip(*sent_ts))[(- 1)] if d]
if (not sent_ts):
return... |
def create_GC_metadata(raw_data_path, meta_data_path):
GC_IMAGE_WIDTH = 1920
GC_IMAGE_HEIGHT = 1080
dir_list = sorted(os.listdir(raw_data_path))
p_num = len(dir_list)
p_data_list = [{} for _ in range((p_num + 1))]
max_t = 0
for dir_name in dir_list:
person_trajectory_txt_path = os.pa... |
def parse_overrides(options: list):
config = {}
for position in range(0, len(options), 2):
key: str = options[position]
assert key.startswith('--')
key = key.strip('--')
value_str: str = options[(position + 1)]
(key, value_str) = (key.strip(), value_str.strip())
r... |
def test_integer():
with pytest.raises(ValueError):
ak.operations.from_json(' [ 1 ,2 ,3.0, 4, 5] \n ', schema={'type': 'array', 'items': {'type': 'integer'}})
result = ak.operations.from_json(' [ 1 ,2 ,3, 4, 5] \n ', schema={'type': 'array', 'items': {'type': 'integer'}})
assert (result.to_list(... |
def builder_inited_handler(app):
subprocess.run(['./cp_origin_docs.sh'])
subprocess.run(['./merge_docs.sh'])
subprocess.run(['./stats.py']) |
def augment_many_model_functions_with_bundled_inputs(model: torch.jit.ScriptModule, inputs: Dict[(Callable, Optional[Sequence[Tuple[(Any, ...)]]])], _receive_inflate_expr: Optional[List[str]]=None, info: Optional[Dict[(Callable, List[str])]]=None, skip_size_check=False) -> None:
if (not isinstance(model, torch.jit.... |
class Vertex():
def __init__(self, vid, cid, nodes, k_in=0):
self._vid = vid
self._cid = cid
self._nodes = nodes
self._kin = k_in |
class DemoConfig():
num_inducing = 7
inner_layer_qsqrt_factor = 0.001
between_layer_noise_variance = 0.001
likelihood_noise_variance = 0.01
whiten = True |
def summary(results):
report = {}
for (k, v) in results.items():
if ((k != 'steps') and (k != 'probs')):
boots_series = sns.algorithms.bootstrap(results[k], func=np.mean, n_boot=1000)
report[k] = np.mean(results[k])
report[f'{k}_ci'] = np.max(np.abs((sns.utils.ci(boot... |
.parametrize('seed', [313])
.parametrize('op', ['+', '-', '*', '/', '**'])
.parametrize('x_var, y_var', [(False, False), (False, True), (True, False)])
.parametrize('shape', [(2, 3, 4), (0,)])
def test_ndarray_arithmetic_ops2(seed, op, x_var, y_var, shape):
rng = np.random.RandomState(seed)
vx_data = rng.randn(... |
class DQN(nn.Module):
def __init__(self, c: int, h: int, w: int, action_shape: Sequence[int], device: Union[(str, int, torch.device)]='cpu', features_only: bool=False) -> None:
super().__init__()
self.device = device
self.net = nn.Sequential(nn.Conv2d(c, 32, kernel_size=8, stride=4), nn.ReLU... |
('warnings.warn')
('sdv.iter_entry_points')
def test__find_addons_bad_addon(entry_points_mock, warning_mock):
def entry_point_error():
raise ValueError()
bad_entry_point = Mock()
bad_entry_point.name = 'bad_entry_point'
bad_entry_point.module_name = 'bad_module'
bad_entry_point.load.side_eff... |
class TestComposed(TestCase):
def setUp(self):
self.n = 100
self.n_atoms = np.random.randint(1, high=10, size=self.n)
r = [(5 * np.random.random((na, 3))) for na in self.n_atoms]
self.r = np.array(r, dtype=object)
self.z = np.array([np.random.randint(1, high=3, size=na) for n... |
_method
class PeriodLattice_ell(PeriodLattice):
def __init__(self, E, embedding=None):
self.E = E
K = E.base_field()
if (embedding is None):
embs = K.embeddings(AA)
real = (len(embs) > 0)
if (not real):
embs = K.embeddings(QQbar)
... |
class SawyerSoccerV2Policy(Policy):
_fully_parsed
def _parse_obs(obs):
return {'hand_pos': obs[:3], 'ball_pos': obs[3:6], 'goal_pos': obs[9:], 'unused_info': obs[6:9]}
def get_action(self, obs):
o_d = self._parse_obs(obs)
action = Action({'delta_pos': np.arange(3), 'grab_effort': 3})... |
def create_dataset(dataset, config, min_scale=0.5):
print(config)
normalize = transforms.Normalize((0., 0.4578275, 0.), (0., 0., 0.))
transform_train = transforms.Compose([transforms.RandomResizedCrop(config['image_size'], scale=(min_scale, 1.0)), RandomAugment(2, 5, isPIL=True, augs=['Identity', 'AutoContr... |
def test_recordarray_localindex():
v2_array = ak.contents.regulararray.RegularArray(ak.contents.recordarray.RecordArray([ak.contents.numpyarray.NumpyArray(np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6]))], ['nest']), 3)
assert (to_list(ak._do.local_index(v2_array, 0)) == [0, 1])
assert (ak._do.local_index(v2_... |
def _parquet_schema_to_form(schema):
def lst(path):
return ('lst:' + '.'.join(path))
def col(path):
return ('col:' + '.'.join(path))
def maybe_nullable(field, content):
if field.nullable:
return ak.forms.ByteMaskedForm('i8', content.with_form_key(None), valid_when=True, f... |
def register_all_ctx459(root):
root = os.path.join(root, 'pascal_ctx_d2')
meta = _get_ctx459_meta()
for (name, dirname) in [('train', 'training'), ('val', 'validation')]:
image_dir = os.path.join(root, 'images', dirname)
gt_dir = os.path.join(root, 'annotations_ctx459', dirname)
name... |
_module('numpy')
class ndenumerate(object):
def __init__(self, arr):
self.iter = asarray(arr).flat
def __next__(self):
return (self.iter.coords, next(self.iter))
def __iter__(self):
return self
next = __next__ |
def plot_training(H):
with plt.xkcd():
plt.plot(H.history['loss'], label='train_loss')
plt.plot(H.history['val_loss'], label='val_loss')
plt.plot(H.history['accuracy'], label='train_acc')
plt.plot(H.history['val_accuracy'], label='val_acc')
plt.legend(loc='lower left')
... |
class TransformerEncoder(EncoderBase):
def __init__(self, num_layers, d_model, heads, d_ff, dropout, attention_dropout, embeddings, max_relative_positions):
super(TransformerEncoder, self).__init__()
self.embeddings = embeddings
self.transformer = nn.ModuleList([TransformerEncoderLayer(d_mod... |
def _calc_box(srs: dd.Series, qntls: da.Array, cfg: Config) -> Dict[(str, Any)]:
data = {f'qrtl{(i + 1)}': qntls.loc[qnt].sum() for (i, qnt) in enumerate((0.25, 0.5, 0.75))}
iqr = (data['qrtl3'] - data['qrtl1'])
srs_iqr = srs[srs.between((data['qrtl1'] - (1.5 * iqr)), (data['qrtl3'] + (1.5 * iqr)))]
(da... |
def test_int():
array = ak.Array([[1, 2], [3, 4, 5]])
assert ((array == 2).to_list() == [[False, True], [False, False, False]]) |
class FlaxMBartForConditionalGeneration(metaclass=DummyObject):
_backends = ['flax']
def __init__(self, *args, **kwargs):
requires_backends(self, ['flax']) |
class GNNEdgeHead(nn.Module):
def __init__(self, dim_in, dim_out):
super(GNNEdgeHead, self).__init__()
if (cfg.model.edge_decoding == 'concat'):
self.layer_post_mp = MLP((dim_in * 2), dim_out, num_layers=cfg.gnn.layers_post_mp, bias=True)
self.decode_module = (lambda v1, v2: ... |
def create_csv(data_list, save_path='list_folder/experiment_name', test_split=0.2, val_split=0.1, shuffle=False):
if shuffle:
np.random.shuffle(data_list)
num_files = len(data_list)
num_test_files = int((test_split * num_files))
num_val_files = int(((num_files - num_test_files) * val_split))
... |
class codelineTypeSub(supermod.codelineType):
def __init__(self, external=None, lineno=None, refkind=None, refid=None, highlight=None):
supermod.codelineType.__init__(self, external, lineno, refkind, refid, highlight) |
def setup_env(gpu_s, seed):
os.environ['BITSANDBYTES_NOWELCOME'] = '1'
os.environ['TOKENIZERS_PARALLELISM'] = 'false'
setup_gpu(gpu_s)
setup_seed(seed) |
()
('--seed', default=1)
('--epochs', default=500)
('--batch_size', default=1024)
('--n_worker', default=psutil.cpu_count(logical=False))
_experiment(snapshot_mode='all')
def mttrpo_metaworld_mt50(ctxt, seed, epochs, batch_size, n_worker):
set_seed(seed)
tasks = mwb.MT50.get_train_tasks().all_task_names
env... |
(pin.WITH_HPP_FCL, 'Needs HPP-FCL')
class TestGeometryObjectBindings(unittest.TestCase):
def setUp(self):
self.model = pin.buildSampleModelHumanoid()
self.collision_model = pin.buildSampleGeometryModelHumanoid(self.model)
def test_name_get_set(self):
col = self.collision_model.geometryOb... |
class Flowavenet(nn.Module):
def __init__(self, in_channel, cin_channel, n_block, n_flow, n_layer, affine=True, pretrained=False, block_per_split=8):
super().__init__()
self.block_per_split = block_per_split
self.blocks = nn.ModuleList()
self.n_block = n_block
for i in range(... |
class DialogModel(modules.CudaModule):
def __init__(self, word_dict, item_dict, context_dict, output_length, args, device_id):
super(DialogModel, self).__init__(device_id)
domain = get_domain(args.domain)
self.word_dict = word_dict
self.item_dict = item_dict
self.context_dict... |
.parametrize('slate_id, reward, pscore, position, evaluation_policy_pscore, description_1', valid_input_of_slate_estimators)
.parametrize('alpha, n_bootstrap_samples, random_state, err, description_2', invalid_input_of_estimate_intervals)
def test_estimate_intervals_of_all_estimators_using_invalid_input_data(slate_id, ... |
class EncoderManager(object):
def __init__(self):
self.encoders = []
self.sessions = []
def load_model(self, model_config, vocabulary_file, embedding_matrix_file, checkpoint_path):
tf.logging.info('Reading vocabulary from %s', vocabulary_file)
with tf.gfile.GFile(vocabulary_file,... |
class _data_matrix(_spbase):
def __init__(self):
_spbase.__init__(self)
def dtype(self):
return self.data.dtype
def dtype(self, newtype):
self.data.dtype = newtype
def _deduped_data(self):
if hasattr(self, 'sum_duplicates'):
self.sum_duplicates()
retur... |
def cal_ndcg(predicts, labels, user_ids, k_list):
d = {'user': np.squeeze(user_ids), 'predict': np.squeeze(predicts), 'label': np.squeeze(labels)}
df = pd.DataFrame(d)
user_unique = df.user.unique()
ndcgs = [[] for _ in range(len(k_list))]
for user_id in user_unique:
user_srow = df.loc[(df['... |
def solarize_add(img, add, thresh=128, **__):
lut = []
for i in range(256):
if (i < thresh):
lut.append(min(255, (i + add)))
else:
lut.append(i)
if (img.mode in ('L', 'RGB')):
if ((img.mode == 'RGB') and (len(lut) == 256)):
lut = ((lut + lut) + lut... |
def main(_):
(env, dataset) = make_env_and_dataset(FLAGS.env_name, FLAGS.seed)
kwargs = dict(FLAGS.config)
kwargs['alpha'] = FLAGS.alpha
kwargs['alg'] = FLAGS.alg
agent = Learner(FLAGS.seed, env.observation_space.sample()[np.newaxis], env.action_space.sample()[np.newaxis], max_steps=FLAGS.max_steps,... |
def bool_flag(s):
if (s.lower() in FALSY_STRINGS):
return False
elif (s.lower() in TRUTHY_STRINGS):
return True
else:
raise argparse.ArgumentTypeError('Invalid value for a boolean flag!') |
def _mk_fp_tern(f, rm, a, b, c, ctx):
ctx = _get_ctx(ctx)
[a, b, c] = _coerce_fp_expr_list([a, b, c], ctx)
if z3_debug():
_z3_assert(is_fprm(rm), 'First argument must be a Z3 floating-point rounding mode expression')
_z3_assert((is_fp(a) or is_fp(b) or is_fp(c)), 'Second, third or fourth arg... |
class CpmTokenizerFast(PreTrainedTokenizerFast):
def __init__(self, vocab_file=None, tokenizer_file=None, do_lower_case=False, remove_space=True, keep_accents=False, bos_token='<s>', eos_token='</s>', unk_token='<unk>', sep_token='<sep>', pad_token='<pad>', cls_token='<cls>', mask_token='<mask>', additional_special... |
def paint_profile_in_cube(cube, positions, profile=None, kernel=None):
assert ((profile is not None) or (kernel is not None))
if (kernel is None):
x = np.arange(cube.shape[0])
y = np.arange(cube.shape[1])
z = np.arange(cube.shape[2])
(rx, ry, rz) = np.meshgrid(x, y, z, sparse=Tru... |
class GatewayOperator():
def __init__(self, op_type):
self.op_type = op_type
self.children = []
self.handle = None
def add_children(self, children):
self.children.extend(children)
def add_child(self, child):
self.children.append(child)
def set_handle(self, handle:... |
class SawyerButtonPressTopdownWallV1Policy(Policy):
_fully_parsed
def _parse_obs(obs):
return {'hand_pos': obs[:3], 'button_pos': obs[3:6], 'unused_info': obs[6:]}
def get_action(self, obs):
o_d = self._parse_obs(obs)
action = Action({'delta_pos': np.arange(3), 'grab_effort': 3})
... |
class AdventLoss(torch.nn.Module):
def __init__(self):
super().__init__()
self.crit = nn.BCEWithLogitsLoss()
def forward(self, y_pred, y_true):
loss_stats = {}
y_t = torch.FloatTensor(y_pred.size())
y_t.fill_(y_true)
y_t = y_t.to(y_pred.get_device())
adven... |
def loss_fn(train_rng, state, params, batch, is_training, model, inner_learning_rate, inner_n_steps):
def inner_maml_loss_fn(inner_batch_train, inner_batch_val):
params_upd = inner_step(params=params, model=model, inner_batch=inner_batch_train, inner_learning_rate=inner_learning_rate, inner_n_steps=inner_n_... |
class A001906(RecurrenceSequence2):
def __init__(self):
SloaneSequence.__init__(self, offset=0)
self._params = (0, 1, 3, (- 1))
self._b = []
self._precompute(2)
def _repr_(self):
return 'F(2n) = bisection of Fibonacci sequence: a(n)=3a(n-1)-a(n-2).' |
def generate_table_rounds(velocity):
r = ''
for i in range(0, len(presolver)):
res = ''
if (presolver_to_velocity.get(presolver.get(i)) != velocity):
continue
matches = list(filter((lambda x: (x.calls[i] > 0)), information))
val = list(map((lambda x: x.calls[i]), matc... |
def uttwav_collater(batch):
max_len = 0
for sample in batch:
(wav, uttname) = sample
if (wav.shape[0] > max_len):
max_len = wav.shape[0]
wavs = []
utts = []
lens = []
for sample in batch:
(wav, uttname) = sample
T = wav.shape[0]
P = (max_len - ... |
def pbmc_seurat_v4_cite_seq(save_path: str='data/', apply_filters: bool=True, aggregate_proteins: bool=True, mask_protein_batches: int=0) -> anndata.AnnData:
return _load_pbmc_seurat_v4_cite_seq(save_path=save_path, apply_filters=apply_filters, aggregate_proteins=aggregate_proteins, mask_protein_batches=mask_protei... |
def generate_matrix(size, dtype):
from numpy.random import default_rng
rng = default_rng(42)
A = rng.random((size, size), dtype=dtype)
return ((0.5 * A) A.T).copy() |
class ExactMatchEvaluator(object):
def __init__(self):
pass
def eval(self, pred, golden):
total_mentions = 0.0
pred_error = 0.0
pred_correct = 0.0
for sent_id in golden:
total_mentions += len(golden[sent_id])
if (not (sent_id in pred)):
... |
class MpKpiAggregation(Enum):
SUM = partial(sum_kpi)
MAX = partial(max_kpi)
TOTAL = partial(total_kpi)
def __call__(self, *args):
return self.value(*args) |
def get_gpt_prompt(claim: str, evidence_list: list[str], line_idx: list[int]) -> str:
assert (len(evidence_list) == len(line_idx)), f'{len(evidence_list)} != {len(line_idx)}, {line_idx}'
evidence_string = '\n'.join([f' <sentence_{idx}>{line}</sentence_{idx}>' for (idx, line) in zip(line_idx, evidence_lis... |
def test_keras_ensemble_ensemble_size_attributes(ensemble_size: int) -> None:
example_data = empty_dataset([1], [1])
keras_ensemble = trieste_keras_ensemble_model(example_data, ensemble_size)
assert (keras_ensemble.ensemble_size == ensemble_size) |
def ambiguous_node_str():
classifier = HierarchicalClassifier()
classifier.y_ = np.array([['a', 'b'], ['b', 'c']])
return classifier |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.