code stringlengths 101 5.91M |
|---|
def test_numerical_columns_gets_pii():
data = pd.DataFrame(data={'id': [0, 1, 2, 3, 4], 'city': [0, 0, 0, 0, 0], 'numerical': [21, 22, 23, 24, 25]})
metadata = SingleTableMetadata.load_from_dict({'primary_key': 'id', 'columns': {'id': {'sdtype': 'id'}, 'city': {'sdtype': 'city'}, 'numerical': {'sdtype': 'numeri... |
class _PyAccess32_3(PyAccess):
def _post_init(self, *args, **kwargs):
self.pixels = ffi.cast('struct Pixel_RGBA **', self.image32)
def get_pixel(self, x, y):
pixel = self.pixels[y][x]
return (pixel.r, pixel.g, pixel.b)
def set_pixel(self, x, y, color):
pixel = self.pixels[y][... |
class TestDSModifierMultyModification():
def test_modifier_multiple_initialization(self):
ds_modifier = DSModifier(DSModifier())
composed_names = '{}#{}'.format(modifier_name, modifier_name)
assert (ds_modifier.name == modifier_name)
assert (ds_modifier._get_name() == composed_names)... |
class ConstantPadNd(Function):
def symbolic(g, input, pad, value=0):
paddings = prepare_onnx_paddings(len(input.type().sizes()), pad)
return g.op('Pad', input, pads_i=paddings, mode_s='constant', value_f=value)
def forward(ctx, input, pad, value=0):
ctx.pad = pad
ctx.value = valu... |
def eval_distinct2(hyps_resp):
if (len(hyps_resp) == 0):
print('ERROR, eval_distinct get empty input')
return
if (type(hyps_resp[0]) != list):
print("ERROR, eval_distinct takes in a list of <class 'list'>, get a list of {} instead".format(type(hyps_resp[0])))
return
hyps_resp... |
class DRODataset(Dataset):
def __init__(self, dataset, process_item_fn, n_groups, n_classes, group_str_fn):
self.dataset = dataset
self.process_item = process_item_fn
self.n_groups = n_groups
self.n_classes = n_classes
self.group_str = group_str_fn
group_array = []
... |
class lazydict(object):
def __init__(self, **kwargs):
self._lazy_dict = kwargs
self._dict = {}
def __getitem__(self, key):
if (key not in self._dict):
self._dict[key] = self._lazy_dict[key]()
return self._dict[key]
def __setitem__(self, i, y):
self.set(i, ... |
class ResNet(nn.Module):
def __init__(self, block, layers, num_classes, criterion):
self.inplanes = 128
super(ResNet, self).__init__()
self.conv1 = conv3x3(3, 64, stride=2)
self.bn1 = BatchNorm2d(64)
self.relu1 = nn.ReLU(inplace=False)
self.conv2 = conv3x3(64, 64)
... |
def nonl(x, cfg, inplace=False):
_s = get_parameter_or_create('Asize', (), ConstantInitializer(np.prod(x.shape[1:])), need_grad=False)
delta = cfg.a_stepsize
xmax = (delta * ((2.0 ** cfg.a_bitwidth) - 1))
if ((cfg.a_quantize is not None) and ('pow2' in cfg.a_quantize)):
xmax = (2.0 ** np.round(n... |
class GELU_VGG(nn.Module):
def __init__(self, vgg_name):
super(GELU_VGG, self).__init__()
self.features = self._make_layers(cfg[vgg_name])
self.classifier = nn.Linear(512, 100)
def forward(self, x):
out = self.features(x)
out = out.view(out.size(0), (- 1))
out = s... |
def thread_wrapper(program, parent_tid, *args, **kwargs):
dsp_settings.initialize_for_thread(parent_tid)
return program(*args, **kwargs) |
def init_array(A):
n = N.get()
for i in range(n):
for j in range(n):
A[(i, j)] = (datatype(((i * (j + 2)) + 2)) / n) |
def _clean_loop_body(body: str) -> str:
if body.endswith('continue;\n'):
body = body[:(- len('continue;\n'))]
return body |
def register_Ns3TcpOptionNOP_methods(root_module, cls):
cls.add_constructor([param('ns3::TcpOptionNOP const &', 'arg0')])
cls.add_constructor([])
cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True)
cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], i... |
def skipIfUnsupportedMaxOpsetVersion(min_opset_version):
def skip_dec(func):
def wrapper(self):
if (self.opset_version > min_opset_version):
raise unittest.SkipTest('Skip verify test for unsupported opset_version')
return func(self)
return wrapper
return s... |
_model
def mpvit_xsmall(**kwargs):
model = MPViT(img_size=224, num_stages=4, num_path=[2, 3, 3, 3], num_layers=[1, 2, 4, 1], embed_dims=[64, 128, 192, 256], mlp_ratios=[4, 4, 4, 4], num_heads=[8, 8, 8, 8], **kwargs)
model.default_cfg = _cfg_mpvit()
return model |
class HerReplayBuffer(ReplayBuffer):
def __init__(self, replay_k, reward_fun, env_spec, size_in_transitions, time_horizon):
self._sample_transitions = make_her_sample(replay_k, reward_fun)
self._replay_k = replay_k
self._reward_fun = reward_fun
super().__init__(env_spec, size_in_tran... |
class Knots(Singleton, Parent):
def __init__(self):
Parent.__init__(self, category=Monoids().Infinite())
def _repr_(self):
return 'Knots'
def one(self):
return self.element_class([])
def an_element(self):
return self.element_class([[1, 5, 2, 4], [5, 3, 6, 2], [3, 1, 4, 6]... |
def test_channel_first_with_2_dim_obs() -> None:
env = DummyAtari(squeeze=True)
assert env.observation_space.shape
(width, height) = env.observation_space.shape
wrapper = ChannelFirst(env)
(observation, _) = wrapper.reset()
assert (observation.shape == (1, width, height))
(observation, _, _,... |
def create_test_input(batch_size, height, width, channels):
if (None in [batch_size, height, width, channels]):
return tf.placeholder(tf.float32, (batch_size, height, width, channels))
else:
return tf.to_float(np.tile(np.reshape((np.reshape(np.arange(height), [height, 1]) + np.reshape(np.arange(... |
def all_saved_variables(derivatives, key):
seen = set()
saved = []
for d in derivatives:
for saved_arg in d[key]:
if (saved_arg['name'] in seen):
continue
seen.add(saved_arg['name'])
saved.append(saved_arg)
return saved |
def main(data, split_num, year):
train_index_path = glob.glob('../data/controversy/raw_data/split/*trainSet_Twitter{}_{}*'.format(year, split_num))[0]
test_index_path = glob.glob('../data/controversy/raw_data/split/*testSet_Twitter{}_{}*'.format(year, split_num))[0]
train_data_output_path = '../data/controv... |
class AE(nn.Module):
def __init__(self, in_channels, out_channels, latent_channels, spiral_indices, down_transform, up_transform):
super(AE, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.latent_channels = latent_channels
self.latent_cha... |
def create_decoder():
try:
decoder = decoding.DECODER_REGISTRY[args.decoder](args)
except Exception as e:
logging.fatal(('An %s has occurred while initializing the decoder: %s Stack trace: %s' % (sys.exc_info()[0], e, traceback.format_exc())))
sys.exit('Could not initialize decoder.')
... |
def is_type(type_, types):
for attr in types:
if getattr(type_, attr, False):
return True
return False |
class ModelLM(object):
def __init__(self, model_name_or_path=None, model_type=None, device=None, gpu_batch_size=None, gpu_id=0):
self.gpu_batch_size = gpu_batch_size
if (model_type is None):
self.model = None
elif (model_type == 'gpt2'):
self.model = GPT2LM(model_name... |
def eval_all_metrics(ref_texts, hypo_texts, label):
os.makedirs('eval_logs/ms_jaccard', exist_ok=True)
msj_results = evaluate_ms_jaccard(hypo_texts=hypo_texts, ref_texts=ref_texts)
pickle.dump(msj_results, open(f'eval_logs/ms_jaccard/{label}.pickle', 'wb'))
os.makedirs('eval_logs/tfidf_distance', exist_... |
def test_initialize_background_knowledge_1():
_bk = Background()
assert (_bk.modes is None)
assert (not _bk.line_search)
assert (not _bk.recursion) |
class RobertaLongSelfAttention(LongformerSelfAttention):
def forward(self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, output_attentions=False):
return super().forward(hidden_states, attention_mask=attention_mask, output_attentions=output_atte... |
def tmpt5_base_tied_lmheads_512_4_4p_bw12_squad1_mpipe():
return dict(model_type='new_t5_stateless', model_name_or_path='t5-base', do_lower_case=False, output_past=False, output_attentions=False, output_hidden_states=False, do_resize_token_embedding=True, explicitly_set_dict={'return_dict': False, 'use_cache': Fals... |
class Convolution2DArchitectureBase(ModelArchitecture):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def preprocess_data(self, x_train, x_val, x_test, y_train, y_val, y_test):
data = (x_train[(..., None)], x_val[(..., None)], x_test[(..., None)], y_train, y_val, y_test)... |
def write_conlltag_with_dict(tag_list, root_path, tag_file, dictfn1, dictfn2, dictfn3, dictfn4=None):
per_dict = []
org_dict = []
loc_dict = []
gpe_dict = []
with open(dictfn1) as dict_f:
for line in dict_f:
dict1.append(line.strip())
with open(dictfn2) as dict_f:
for... |
def compute_lm_ppl(hyp_uid_to_tra, score_fn):
lm_score = 0.0
w_cnt = 0
for hyp in hyp_uid_to_tra.values():
cur_score = score_fn(hyp)
cur_cnt = (len(hyp.split()) + 1)
lm_score += cur_score
w_cnt += cur_cnt
logger.debug(f'''
score sum/avg = {cur_score:.2f}/{(cur_score /... |
def test_disambiguate_int(ambiguous_node_int):
ground_truth = np.array([['1', '1::HiClass::Separator::2'], ['2', '2::HiClass::Separator::3']])
ambiguous_node_int._disambiguate()
assert_array_equal(ground_truth, ambiguous_node_int.y_) |
class HighwayEntrySample():
def __init__(self):
curvature_range = [(- 0.03), 0.03]
self.c1 = world.world.rng_road_network.uniform(low=(- 0.01), high=0.01)
self.c2 = world.world.rng_road_network.uniform(low=(- 0.005), high=0.005)
self.c3 = world.world.rng_road_network.uniform(low=curv... |
def probability_that_2_overtakes_1(i):
return (lambda x: (x[i].drop_top2_probs > x[i].drop_top1_probs).float().mean(dim=0).view((- 1))) |
def log_softmax_to_probabilities(log_softmax, epsilon=1e-05):
softmax = np.exp(log_softmax)
probabilities = (softmax / np.sum(softmax))
assert ((np.sum(probabilities) >= (1.0 - epsilon)) and (np.sum(probabilities) <= (1.0 + epsilon)))
return probabilities |
def loss_plot(epochs_adam_sa, epochs_lbfgs_sa, adam_loss, lbfgs_loss, title=None, dpi=150, figsize=(10, 8)):
x_adam = range(0, (epochs_adam_sa + 250), 250)
x_lbfgs = range((x_adam[(- 1)] + 5), ((epochs_adam_sa + epochs_lbfgs_sa) + 5), 5)
plt.figure(dpi=dpi, figsize=figsize)
plt.vlines(x_adam[(- 1)], lbf... |
def register_Ns3InfrastructureWifiMac_methods(root_module, cls):
cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True)
cls.add_constructor([])
cls.add_method('Enqueue', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'to')], is_pure_virtual=True, is_virtual=Tru... |
def FloatDouble(ctx=None):
ctx = _get_ctx(ctx)
return FPSortRef(Z3_mk_fpa_sort_double(ctx.ref()), ctx) |
def read_wav(filepath: str, target_sr: int=44100, duration: Optional[float]=None) -> Tuple[(np.ndarray, int)]:
print(f'reading audio from {filepath}')
if filepath.startswith('gs://'):
gcs = storage.Client(project=GOOGLE_CLOUD_PROJECT)
(bucket, file_name) = filepath.replace('gs://', '').split('/'... |
def build_srm_rom_feat(cfg):
srm_rom_feat = SRMROMFeat(in_channel=cfg['MODEL']['BACKBONE']['CHANNELS'][(- 1)], box_channels=cfg['MODEL']['FEAT']['BOX_CHANNELS'], dis_channels=cfg['MODEL']['FEAT']['DIS_CHANNELS'], cls_channels=cfg['MODEL']['FEAT']['CLS_CHANNELS'], rom_channels=cfg['MODEL']['FEAT']['ROM_CHANNELS'])
... |
def _write_ninja_file_and_compile_objects(sources: List[str], objects, cflags, post_cflags, cuda_cflags, cuda_post_cflags, build_directory: str, verbose: bool, with_cuda: Optional[bool]) -> None:
verify_ninja_availability()
if IS_WINDOWS:
compiler = os.environ.get('CXX', 'cl')
else:
compiler... |
class MHALayerNetTest(MHABaseTest):
def create_feature_network(self, input_shape):
return MHANet(embed_dim=self.embed_dim, num_heads=self.num_heads, kdim=self.kdim, vdim=self.vdim, bias=self.bias, add_bias_kv=self.add_bias_kv, add_zero_attn=self.add_zero_attn, batch_first=self.batch_first) |
def reporthook(*args, **kwargs):
kwargs2 = dict(unit_scale=True, miniters=1)
kwargs2.update(kwargs)
bar = __call__(None, *args, **kwargs2)
class ReportHook(object):
def __init__(self, t):
self.t = t
def __call__(self, b=1, bsize=1, tsize=None):
if hasattr(self.t, ... |
def copy_from_predicted(mode, train_attention_to_copy, eval_attention_to_copy):
attention_to_copy = (train_attention_to_copy if (mode == tf.estimator.ModeKeys.TRAIN) else eval_attention_to_copy)
if (len(attention_to_copy.get_shape()) < 3):
attention_to_copy = tf.one_hot(attention_to_copy, tf.shape(atten... |
def create_model(config_path):
config = OmegaConf.load(config_path)
model = instantiate_from_config(config.model).cpu()
print(f'Loaded model config from [{config_path}]')
return model |
def move_file(file, dst_dir, overwrite=True):
basename = os.path.basename(file)
(head, tail) = os.path.splitext(basename)
dst_file = os.path.join(dst_dir, basename)
if overwrite:
count = 0
while os.path.exists(dst_file):
count += 1
dst_file = os.path.join(dst_dir,... |
def test_add_panel():
def f14(growablebuffer):
growablebuffer._add_panel()
growablebuffer = GrowableBuffer(np.float32, initial=10, resize=2.0)
growablebuffer._pos = 5
assert (len(growablebuffer._panels) == 1)
assert (len(growablebuffer._panels[0]) == 10)
assert (growablebuffer._pos == 5)... |
def validate_tl_line(line, LTRB=True, withTranscription=True, withConfidence=True, imWidth=0, imHeight=0):
get_tl_line_values(line, LTRB, withTranscription, withConfidence, imWidth, imHeight) |
def test_multilingual_entity_vocab(multilingual_entity_vocab):
assert (len(multilingual_entity_vocab) == 6)
assert (len(list(multilingual_entity_vocab)) == 9)
assert multilingual_entity_vocab.contains('', 'ja')
assert (multilingual_entity_vocab.get_id('[MASK]', 'ja') == 2)
assert (multilingual_entit... |
_task('translation_from_pretrained_xlm', dataclass=TranslationFromPretrainedXLMConfig)
class TranslationFromPretrainedXLMTask(TranslationTask):
def load_dictionary(cls, filename):
return MaskedLMDictionary.load(filename) |
def lift_uniformiser_odd(p, u, n):
g = lift_gen_to_gamma1((p ** u), n)
return [(p * g[0]), g[1], (p * g[2]), g[3]] |
def getResource(request):
username = request.session['username']
date = str(request.session['date'])
date = ((date[0:4] + date[4:6]) + date[6:8])
path = ((username + '/') + date)
file = request.FILES['file']
filename = ((path + '/') + file.name)
file.save(filename)
return HttpResponse('f... |
class Attention(nn.Module):
def __init__(self, dim, num_heads=8, qkv_bias=False, attn_drop=0.0, proj_drop=0.0):
super().__init__()
self.num_heads = num_heads
head_dim = (dim // num_heads)
self.scale = (head_dim ** (- 0.5))
self.qkv = nn.Linear(dim, (dim * 3), bias=qkv_bias)
... |
def prepare_training_data(src1, src2, tgt, output_folder, training_frac):
assert (training_frac < 1.0)
if (not os.path.exists(output_folder)):
os.makedirs(output_folder)
src1_paths = sorted(glob.glob((src1 + '/*')))
if src2:
check = True
src2_paths = sorted(glob.glob((src2 + '/*'... |
class RandomScaleCrop(object):
def __init__(self, base_size, crop_size, fill=0):
self.base_size = base_size
self.crop_size = crop_size
self.fill = fill
def __call__(self, img, mask):
short_size = random.randint(int((self.base_size * 0.8)), int((self.base_size * 1.2)))
(w,... |
def is_in_notebook():
try:
get_ipython = sys.modules['IPython'].get_ipython
if ('IPKernelApp' not in get_ipython().config):
raise ImportError('console')
if ('VSCODE_PID' in os.environ):
raise ImportError('vscode')
if (('DATABRICKS_RUNTIME_VERSION' in os.enviro... |
class R1_mAP_reranking(Metric):
def __init__(self, num_query, max_rank=50, feat_norm='yes'):
super(R1_mAP_reranking, self).__init__()
self.num_query = num_query
self.max_rank = max_rank
self.feat_norm = feat_norm
def reset(self):
self.feats = []
self.pids = []
... |
def subset_refuter(df: pd.DataFrame, treatment: str, fraction: float=0.8):
df = df.groupby(treatment, group_keys=False).apply((lambda x: x.sample(frac=fraction)))
validate = 1
return (df, validate) |
def get_detection_scores(detection_results_file, rgb_fns, obj_id, score_thr):
with open(detection_results_file) as jsonFile:
detections = json.load(jsonFile)
jsonFile.close()
scores = [(- 1) for x in range(len(rgb_fns))]
for (counter, rgb_fn) in enumerate(rgb_fns):
rgb_fn = rgb_fn.sp... |
class _ReferenceConvBnNd(torch.nn.Conv2d, torch.nn.modules.conv._ConvNd):
def __init__(self, in_channels, out_channels, kernel_size, stride, padding, dilation, transposed, output_padding, groups, bias, padding_mode, eps=1e-05, momentum=0.1, freeze_bn=False, qconfig=None):
nn.modules.conv._ConvNd.__init__(se... |
def test_arraytype_3():
text = str(ak.with_parameter(ak.Array([[1, 2, 3], [], [4, 5]]), 'wonky', {'other': 'JSON'}).type)
parsedtype = ak.types.from_datashape(text, highlevel=False)
assert (str(parsedtype) == text) |
def Evaluate(num_epochs):
since = time.time()
for haha in range(1):
model = SVC(C=10)
for epoch in range(1):
for phase in ['test', 'train', 'val']:
running_loss = 0.0
running_corrects = 0.0
total = 0
embedding.train(Fals... |
_module()
class pvt_v2_b2(PyramidVisionTransformerV2Original):
def __init__(self, **kwargs):
super(pvt_v2_b2, self).__init__(patch_sizes=(7, 3, 3, 3), strides=(4, 2, 2, 2), embed_dims=(64, 128, 320, 512), num_heads=(1, 2, 5, 8), mlp_ratios=(8, 8, 4, 4), qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e... |
def deprecated(func):
(func)
def wrapper(*args, **kwargs):
warnings.warn('This function is deprecated.', DeprecationWarning)
return func(*args, **kwargs)
return wrapper |
def gen_env(render='drgb'):
HORIZON = 750
FLOW_RATE = 2000
RL_PENETRATION = 0.1
NUM_RL = 5
additional_net_params = deepcopy(ADDITIONAL_NET_PARAMS)
additional_net_params['merge_lanes'] = 1
additional_net_params['highway_lanes'] = 1
additional_net_params['pre_merge_length'] = 500
vehic... |
class TBTimeFunctionTests(unittest.TestCase):
def setUp(self):
super(TBTimeFunctionTests, self).setUp()
dt1 = datetime.datetime(2000, 11, 12)
self.dt_a = [(dt1 + datetime.timedelta(hours=val)) for val in range(100)]
self.dt_b = [(dt1 + datetime.timedelta(hours=val)) for val in range(... |
class dts_ConvAI2(object):
def __init__(self, path=data_path):
self.path = path
def _txt_to_json(self, txt_path, mode, cands):
def pop_one_sample(lines):
self_persona = []
other_persona = []
dialog = []
candidates = []
started = False
... |
def register_Ns3SimpleRefCount__Ns3ChannelCoordinationListener_Ns3Empty_Ns3DefaultDeleter__lt__ns3ChannelCoordinationListener__gt___methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::SimpleRefCount< ns3::ChannelCoordinationListener, ns3::empty, ns3::DefaultDeleter< ns3::ChannelC... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--data_folder', type=Path, required=True)
parser.add_argument('--grid_resolution', type=int, required=True)
parser.add_argument('--camera_coverage_threshold', type=int, required=True)
args = parser.parse_args()
generate_occupanc... |
def register_Ns3RlcListElement_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::RlcListElement const &', 'arg0')])
cls.add_instance_attribute('m_rlcPduElements', 'std::vector< ns3::RlcPduInfo >', is_const=False)
return |
def load(data_dir, subset='train'):
maybe_download_and_extract(data_dir)
if (subset == 'train'):
train_data = [unpickle(os.path.join(data_dir, 'cifar-10-batches-py', ('data_batch_' + str(i)))) for i in range(1, 6)]
trainx = np.concatenate([d['x'] for d in train_data], axis=0)
trainy = np... |
def Curve(F, A=None):
if (A is None):
if (is_AmbientSpace(F) and (F.dimension() == 1)):
return Curve(F.coordinate_ring().zero(), F)
if is_AlgebraicScheme(F):
return Curve(F.defining_polynomials(), F.ambient_space())
if isinstance(F, (list, tuple)):
P = Seq... |
class Logger(nn.Module):
def __init__(self):
super(Logger, self).__init__()
self.stats = {}
def forward(self, x):
pass |
def load_config_from_json(filepath):
with open(filepath, 'rb') as f:
data = json.load(f)
dot_list = []
for key in data.keys():
dot_list.append(f"{key}={data[key]['value']}")
return OmegaConf.from_dotlist(dot_list) |
def test_generator(multiple_databases) -> TestGenerator:
return TestGenerator(databases=multiple_databases) |
def save_scripts(path, scripts_to_save=None):
if (not os.path.exists(os.path.join(path, 'scripts'))):
os.makedirs(os.path.join(path, 'scripts'))
if (scripts_to_save is not None):
for script in scripts_to_save:
dst_path = os.path.join(path, 'scripts', script)
try:
... |
class BinanceWithdraw(VirtualFunctionTool):
name = 'BinanceWithdraw'
summary = "Withdraw a specified amount of cryptocurrency or fiat money to a specified destination address or bank account from user's account. The bank account id must be retrieved using the RetrieveAccounts tool."
parameters: List[ArgPara... |
class VGG16(nn.Module):
def __init__(self, n_inputs=12, numCls=17):
super().__init__()
vgg = models.vgg16(pretrained=False)
self.encoder = nn.Sequential(nn.Conv2d(n_inputs, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)), *vgg.features[1:])
self.classifier = nn.Sequential(nn.L... |
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None, last=False):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.BatchNorm2d(planes)
self.relu = nn.ReLU(inplace=True)
se... |
def new(mode, size, color=0):
_check_size(size)
if (color is None):
return Image()._new(core.new(mode, size))
if isinstance(color, str):
from . import ImageColor
color = ImageColor.getcolor(color, mode)
im = Image()
if ((mode == 'P') and isinstance(color, (list, tuple)) and (... |
def embedded_cnn(x):
emdded = get_emdedding_layer()(x)
conv_layers = []
for (n_gram, hidden_units) in zip(KERNEL_SIZE, NUMBER_OF_FILTERS):
conv_layer = Conv1D(filters=hidden_units, kernel_size=n_gram, padding='valid', activation='relu')(emdded)
conv_layer = GlobalMaxPooling1D()(conv_layer)
... |
def root_mean_square_error(y_true, y_pred):
(y_true, y_pred) = (np.array(y_true), np.array(y_pred))
score = np.sqrt(np.mean(((y_pred - y_true) ** 2)))
return score |
class Function_tanh(GinacFunction):
def __init__(self):
GinacFunction.__init__(self, 'tanh', latex_name='\\tanh') |
class Rubiks(JoinFeature):
def __init__(self):
JoinFeature.__init__(self, 'rubiks', [cu2(), size222(), optimal(), mcube(), dikcube(), cubex()], spkg='rubiks') |
class GradientRegistry(object):
gradient_registry_ = {}
def RegisterGradient(cls, op_type):
def Wrapper(func):
cls.gradient_registry_[op_type] = func
return func
return Wrapper
def _GetGradientForOpCC(cls, op_def, g_output):
def from_untyped(grad):
... |
class ColaProcessor(DataProcessor):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
warnings.warn(DEPRECATION_WARNING.format('processor'), FutureWarning)
def get_example_from_tensor_dict(self, tensor_dict):
return InputExample(tensor_dict['idx'].numpy(), tensor_dic... |
class SimpleAEWithLinear(BaseAE):
def __init__(self, input_shape: Tuple[int], latent_dim: int, visualisation_channels):
super().__init__(visualisation_channels)
self.latent_dim = latent_dim
channels = input_shape[0]
self.encoder = nn.Sequential(nn.Conv2d(channels, 64, 3, stride=2, pa... |
def _timestamp_to_seconds(timestamp: str):
parts = timestamp.split(':')
seconds = float(parts[(- 1)])
seconds += (float(parts[(- 2)]) * 60)
seconds += ((float(parts[(- 3)]) * 60) * 60)
return seconds |
def get_optimizer(args, net):
base_params = []
for (name, param) in net.named_parameters():
base_params.append(param)
if args.sgd:
optimizer = optim.SGD(base_params, lr=args.lr, weight_decay=args.weight_decay, momentum=args.momentum, nesterov=False)
else:
raise ValueError('Not a ... |
def prior(rng=None):
if (rng is None):
rng = np.random.default_rng()
beta = rng.normal(0, 2)
f = rng.multivariate_normal(np.zeros(9), Cov)
return np.append(beta, f) |
def evaluate(model, dataloader, logger, device):
score = 0
number = 0
model.eval()
with torch.no_grad():
for (i, row) in enumerate(dataloader):
(image_data, question, target, answer_type, question_type, phrase_type, answer_target) = row
(question, answer_target) = (questi... |
def _warn_keyword_parameter(func_name, kwargs):
if (not kwargs):
return False
elif ((len(kwargs) > 1) or ('warn' not in kwargs)):
kwargs.pop('warn', None)
arg = next(iter(kwargs.keys()))
raise TypeError('{}() got an unexpected keyword argument {!r}'.format(func_name, arg))
re... |
class ComparableMixin():
def __eq__(self, other):
if ((self is None) and (other is not None)):
return False
elif ((self is not None) and (other is None)):
return False
else:
return ((not (self < other)) and (not (other < self)))
def __ne__(self, other)... |
def option():
parser = argparse.ArgumentParser()
parser.add_argument('--epochs', default=200, type=int, metavar='N', help='number of total epochs to run')
parser.add_argument('-b', '--batch-size', default=16, type=int, metavar='N')
parser.add_argument('--lr', '--learning-rate', default=0.0005, type=floa... |
def test_aliasing():
c = 1
A_ub = [[1]]
b_ub = [1]
A_eq = [[1]]
b_eq = [1]
bounds = ((- np.inf), np.inf)
c_copy = deepcopy(c)
A_ub_copy = deepcopy(A_ub)
b_ub_copy = deepcopy(b_ub)
A_eq_copy = deepcopy(A_eq)
b_eq_copy = deepcopy(b_eq)
bounds_copy = deepcopy(bounds)
_cl... |
class Reshape(LoopEntryTransform):
def __init__(self, shapes: dict) -> None:
super().__init__(loop_axis=None, entries=tuple(shapes.keys()))
self.shapes = shapes
def transform_entry(self, np_entry, entry, loop_i=None) -> np.ndarray:
return np.reshape(np_entry, self.shapes[entry]) |
def init_gans(target):
for m in target.modules():
if isinstance(m, nn.modules.conv._ConvNd):
m.weight.data.normal_(0.0, 0.02)
if (hasattr(m, 'bias') and (m.bias is not None)):
m.bias.data.zero_()
if isinstance(m, nn.Linear):
m.weight.data.normal_(0... |
def prepare_ctrl_input(args, _, tokenizer, prompt_text):
if (args.temperature > 0.7):
logger.info('CTRL typically works better with lower temperatures (and lower top_k).')
encoded_prompt = tokenizer.encode(prompt_text, add_special_tokens=False)
if (not any(((encoded_prompt[0] == x) for x in tokenize... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.