code stringlengths 101 5.91M |
|---|
class docXRefSectType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, id=None, xreftitle=None, xrefdescription=None):
self.id = id
if (xreftitle is None):
self.xreftitle = []
else:
self.xreftitle = xreftitle
self.xrefdescription ... |
def preactresnet18(num_classes=10, dropout=False, stride=1):
return PreActResNet(PreActBlock, [2, 2, 2, 2], 64, num_classes, stride=stride) |
def adjacent_tmp_file(path, **kwargs):
with NamedTemporaryFile(delete=False, dir=os.path.dirname(path), prefix=os.path.basename(path), suffix='.tmp', **kwargs) as f:
result = cast('NamedTemporaryFileResult', f)
try:
(yield result)
finally:
result.file.flush()
... |
def eval(config):
np.random.seed(2019)
tf.random.set_seed(2019)
if config['data.cuda']:
cuda_num = config['data.gpu']
device_name = f'GPU:{cuda_num}'
else:
device_name = 'CPU:0'
data_dir = config['data.dataset_path']
ret = load(data_dir, config, ['test'])
test_loader ... |
class LinearClassifier(nn.Module):
def __init__(self, features):
super(LinearClassifier, self).__init__()
self.features = features
self.classifier = nn.Conv2d(features.latent_dim, 1, 1)
def width(self):
return self.features.width
def latent_dim(self):
return self.feat... |
def conv(model, blob_in, blob_out, dim_in, dim_out, kernel, weight_init=None, bias_init=None, WeightInitializer=None, BiasInitializer=None, group=1, transform_inputs=None, **kwargs):
return _ConvBase(model, False, blob_in, blob_out, dim_in, dim_out, kernel, weight_init, bias_init, WeightInitializer, BiasInitializer... |
class DriverNmslibIndexBuilder(IndexBuilder):
def produce_inferer(self, filter_seen_items: bool) -> IndexInferer:
if filter_seen_items:
return NmslibFilterIndexInferer(self.index_params, self.index_store)
else:
return NmslibIndexInferer(self.index_params, self.index_store)
... |
class UtteranceItem():
def __init__(self, interaction, index):
self.interaction = interaction
self.utterance_index = index
def __str__(self):
return str(self.interaction.utterances[self.utterance_index])
def histories(self, maximum):
if (maximum > 0):
history_seqs... |
class Function_arctanh(GinacFunction):
def __init__(self):
GinacFunction.__init__(self, 'arctanh', latex_name='\\operatorname{artanh}', conversions=dict(maxima='atanh', sympy='atanh', fricas='atanh', giac='atanh', mathematica='ArcTanh')) |
def __parse_free_rusage(args):
free_filepath = f'{args.prefix}/free.log'
if (not os.path.exists(free_filepath)):
free_filepath += '.xz'
if (not os.path.exists(free_filepath)):
logging.warning(f'Unable to find memory usage data at {free_filepath}')
return False
rusage = {}
las... |
def get_mangle_prefix(name: str) -> str:
return (name.partition('.')[0] if is_mangled(name) else name) |
class TGCR():
def __init__(self):
self.regs = dict(T5=0, T6=0, T32=0, T33=0, T127=0)
def setter(self, index, value):
self.regs[('T' + str(index))] = value
def getter(self, index):
return int(self.regs[('T' + str(index))]) |
def main():
parser = argparse.ArgumentParser(description='OGBN-Products (SIGN)')
parser.add_argument('--device', type=int, default=0)
parser.add_argument('--log_steps', type=int, default=1)
parser.add_argument('--num_layers', type=int, default=3)
parser.add_argument('--hidden_channels', type=int, de... |
class BackboneMixin():
def out_feature_channels(self):
return {stage: self.num_features[i] for (i, stage) in enumerate(self.stage_names)}
def channels(self):
return [self.out_feature_channels[name] for name in self.out_features]
def forward_with_filtered_kwargs(self, *args, **kwargs):
... |
def _griffin_lim(S, hparams):
angles = np.exp(((2j * np.pi) * np.random.rand(*S.shape)))
S_complex = np.abs(S).astype(np.complex)
y = _istft((S_complex * angles), hparams)
for i in range(hparams.griffin_lim_iters):
angles = np.exp((1j * np.angle(_stft(y, hparams))))
y = _istft((S_complex... |
def iou_t_tf(gtrs, pred, threshold=0.5):
gtrs = tf.cast(tf.reshape((gtrs > threshold), [gtrs.get_shape()[0], ((32 * 32) * 32)]), tf.bool)
pred = tf.cast(tf.reshape((pred > threshold), [pred.get_shape()[0], ((32 * 32) * 32)]), tf.bool)
union = tf.cast(tf.reduce_sum(tf.cast(tf.logical_or(gtrs, pred), tf.int64... |
class MobileNetV3(nn.Module):
def __init__(self, width_mult=1.0):
super(MobileNetV3, self).__init__()
cfgs = [[3, 1, 16, 0, 0, 1], [3, 4, 24, 0, 0, 2], [3, 3, 24, 0, 0, 1], [5, 3, 40, 1, 0, 2], [5, 3, 40, 1, 0, 1], [5, 3, 40, 1, 0, 1], [3, 6, 80, 0, 1, 2], [3, 2.5, 80, 0, 1, 1], [3, 2.3, 80, 0, 1, 1... |
def main(args, store=None):
data_path = os.path.expandvars(args.data)
dataset = DATASETS[args.dataset](data_path)
(train_loader, val_loader) = dataset.make_loaders(args.workers, args.batch_size, data_aug=bool(args.data_aug))
train_loader = helpers.DataPrefetcher(train_loader)
val_loader = helpers.Da... |
class PretrainConfig():
defaults: List[Any] = field(default_factory=(lambda : DEFAULTS))
hydra: Dict[(str, Any)] = field(default_factory=(lambda : {'run': {'dir': './runs/train/${model.identifier}+dataset-${dataset.name}'}}))
run_id: Optional[str] = None
seed: int = 21
resume: bool = True
resume... |
def set_global_backend(backend):
backend = _backend_from_arg(backend)
ua.set_global_backend(backend) |
class BloomForTokenClassification(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def filter_state_dict(state_dict, remove_name='fc'):
new_state_dict = {}
for key in state_dict:
if (remove_name in key):
continue
new_state_dict[key] = state_dict[key]
return new_state_dict |
def create_header_embedding(data_dir, header_vocab, origin_embed, is_bert=False):
with open(os.path.join(data_dir, ('header_embedding_312_bert.pkl' if is_bert else 'header_embedding_312.pkl')), 'rb') as f:
header_embed = pickle.load(f)
for header_id in header_vocab:
origin_embed[header_id] = hea... |
def load_pretrained_weights(model, pretrained_weights, checkpoint_key, model_name, patch_size):
if os.path.isfile(pretrained_weights):
state_dict = torch.load(pretrained_weights, map_location='cpu')
if ((checkpoint_key is not None) and (checkpoint_key in state_dict)):
print(f'Take key {c... |
class HRNet(nn.Module):
def __init__(self, aligned=False, use_se=False, use_global=False, avg_down=False, base_width=32, norm='bn', stage_with_conv=('normal', 'normal', 'normal', 'normal'), num_classes=1000):
super(HRNet, self).__init__()
block_1 = (AlignedBottleneck if aligned else Bottleneck)
... |
class StepVisitor(StepVisitor):
def __init__(self, nodes, flow):
super().__init__(nodes, flow)
def visit_FunctionDef(self, node):
func = getattr(self.flow, node.name)
if hasattr(func, 'is_step'):
self.nodes[node.name] = DAGnode(node, func.decorators, func.__doc__) |
def mse_array(array_x, array_y, size):
rescale_x = array_x
rescale_y = array_y
se = tf.reduce_sum(tf.squared_difference(rescale_x, rescale_y), 1)
inv_size = tf.to_float((1 / size))
return tf.scalar_mul(inv_size, se) |
def get_link(id, entity='paper'):
api = '
webpage = '
for base in [api, webpage]:
link = base.format(entity, id)
txt = f'<a href="{link}">{link}</a>'
ipd.display(ipd.HTML(txt)) |
def custom_tokenizers(test_case):
if (not _run_custom_tokenizers):
test_case = unittest.skip('test of custom tokenizers')(test_case)
return test_case |
def calculate_val(thresholds_val, distances, labels, far_target=0.001, num_folds=10):
num_pairs = min(len(labels), len(distances))
num_thresholds = len(thresholds_val)
k_fold = KFold(n_splits=num_folds, shuffle=False)
tar = np.zeros(num_folds)
far = np.zeros(num_folds)
indices = np.arange(num_pa... |
class SLeNet300(nn.Module):
def __init__(self, input_dim, output_dim, Q_l):
super(SLeNet300, self).__init__()
self.Q_l = Q_l
self.qlevels = Q_l.size(0)
self.input_dim = input_dim
self.output_dim = output_dim
self.w1 = sl.SLinear(input_dim, 300, Q_l)
self.bn1 =... |
class TriFingerAction(object):
def __init__(self, action_mode='joint_positions', normalize_actions=True):
self.normalize_actions = normalize_actions
self.max_motor_torque = 0.36
self.low = None
self.high = None
num_fingers = 3
self.action_mode = action_mode
se... |
class InputExample(object):
def __init__(self, tokens, segment_ids, masked_lm_positions, masked_lm_labels, is_random_next):
self.tokens = tokens
self.segment_ids = segment_ids
self.masked_lm_positions = masked_lm_positions
self.masked_lm_labels = masked_lm_labels
self.is_rand... |
def get_train_loaders(dataset_train, args, batch_size=None, drop_last=True):
batch_size = (batch_size or args.batch_size)
sampler_train = samplers.get_train_sampler(dataset_train, args)
loader_train = torch.utils.data.DataLoader(dataset_train, sampler=sampler_train, batch_size=batch_size, num_workers=args.n... |
def register_Ns3SimpleRefCount__Ns3FdReader_Ns3Empty_Ns3DefaultDeleter__lt__ns3FdReader__gt___methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::SimpleRefCount< ns3::FdReader, ns3::empty, ns3::DefaultDeleter< ns3::FdReader > > const &', 'o')])
return |
def noisy_hartmann_6(x: TensorType) -> TensorType:
return (hartmann_6(x) + tf.random.normal([len(x), 1], 0, 1, tf.float64)) |
def on_key_press(k, modifiers):
if (k == key.SPACE):
action[0][2] = 1
else:
action[0][2] = 0 |
class TestDeriavtives(TestCase):
def setUp(self):
self.model = pin.buildSampleModelHumanoidRandom()
self.data = self.model.createData()
qmax = np.full((self.model.nq, 1), np.pi)
self.q = pin.randomConfiguration(self.model, (- qmax), qmax)
self.v = np.random.rand(self.model.nv... |
class RingDerivationWithoutTwist_zero(RingDerivationWithoutTwist):
def __init__(self, parent, arg=None):
if (isinstance(arg, list) and (len(arg) == 1) and isinstance(arg[0], RingDerivation)):
arg = arg[0]
if (arg and (not (isinstance(arg, RingDerivation) and arg.is_zero()))):
... |
(frozen=True)
class ContaminationPoint():
models: List[str]
groups: List[str]
level: str
description: str |
class ConcatTable(nn.Module):
def __init__(self, module_list=None):
super(ConcatTable, self).__init__()
self.modules_list = nn.ModuleList(module_list)
def forward(self, x: Variable):
y = []
for i in range(len(self.modules_list)):
y.append(self.modules_list[i](x))
... |
class M2M100Tokenizer(metaclass=DummyObject):
_backends = ['sentencepiece']
def __init__(self, *args, **kwargs):
requires_backends(self, ['sentencepiece']) |
class Mlp3Layer128Unit(Mlp3LayerTemplate):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.n_hidden = 128 |
class MCLogTabWidget(QtWidgets.QTabWidget):
def __init__(self, parent=None):
super(MCLogTabWidget, self).__init__(parent)
self.setTabBar(MCLogTabBar(self)) |
def get_block_stats(G, node_labels, n_blocks=None):
if (n_blocks is None):
n_blocks = (max(node_labels) + 1)
seen_nodes = set()
block_ns = np.zeros(n_blocks, dtype=int)
block_ms = np.zeros((n_blocks, n_blocks), dtype=np.int64)
for (i, j) in G.edges():
i_block = node_labels[i]
... |
class CloneExample(object):
def __init__(self, code1, code2, label, url1, url2):
self.source = code1
self.target = code2
self.label = label
self.url1 = url1
self.url2 = url2 |
def save_log(logs, columns, filename):
df = pd.DataFrame(logs)
df.columns = columns
df.to_csv(filename)
return |
class FeatureSet(object):
def extract(self, data):
return NotImplementedError('Method needs to be overwritten by subclass') |
def clip_long_spans(spans, maxspanlen):
faultyspans = []
for i in range(len(spans)):
span = spans[i]
spanlen = ((span[1] - span[0]) + 1)
if (spanlen <= maxspanlen):
continue
faultyspans.append(span)
if (len(faultyspans) == 0):
return spans
for span in ... |
def circle_thin(N=5000):
phi = np.random.randn(N)
x = [[np.sin(phi0), np.cos(phi0)] for phi0 in phi]
x = np.array(x)
x = (x + (0.05 * np.random.randn(N, 2)))
return x |
class Vocabulary(object):
def __init__(self, *args, **kwargs):
self.sos_id = None
self.eos_id = None
self.pad_id = None
self.blank_id = None
def label_to_string(self, labels):
raise NotImplementedError |
class LRScheduler(TrainHook):
def __init__(self, optimizer, scheduler):
self.optimizer = optimizer
self.scheduler = scheduler
largest_group = max((len(g['params']) for g in optimizer.param_groups))
if (largest_group == 1):
lr_count = Counter([g['lr'] for g in optimizer.pa... |
def test_predict_proba_with_ds_hard(create_pool_classifiers):
expected = np.array([0.666, 0.333])
DFP_mask = np.ones((1, 6))
predictions = np.array([[0, 1, 0, 0, 1, 0]])
probabilities = np.array([[[0.5, 0.5], [1, 0], [0.33, 0.67], [0.5, 0.5], [1, 0], [0.33, 0.67]]])
pool_classifiers = (create_pool_c... |
def _create_dummy_line_json_file(ann_file):
ann_info1 = {'filename': 'sample1.jpg', 'text': 'hello'}
ann_info2 = {'filename': 'sample2.jpg', 'text': 'world'}
with open(ann_file, 'w') as fw:
for ann_info in [ann_info1, ann_info2]:
fw.write((json.dumps(ann_info) + '\n')) |
class CompileTimeScope(object):
def __init__(self, outer=None):
self.entries = {}
self.outer = outer
def declare(self, name, value):
self.entries[name] = value
def update(self, other):
self.entries.update(other)
def lookup_here(self, name):
return self.entries[nam... |
def _get_graph(explainer):
_import_tf()
if (not tf.executing_eagerly()):
return explainer.session.graph
else:
from tensorflow.python.keras import backend
graph = backend.get_graph()
return graph |
def register_Ns3TypeId_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('<')
cls.add_constructor([param('char const *', 'name')])
cls.add_constructor([])
cls.add_co... |
()
def common_kwargs(tmp_path):
outputnb = tmp_path.joinpath('output.ipynb')
return {'output_path': str(outputnb), 'kernel_name': f'python{sys.version_info.major}', 'progress_bar': False} |
def _remove_bracketed(text: Any, brackets: Union[(str, Set[str])], inclusive: bool=True) -> Any:
if pd.isna(text):
return text
text = str(text)
value = ('' if inclusive else '\\g<1>\\g<2>')
if isinstance(brackets, set):
for bracket in brackets:
text = re.sub(REGEX_BRACKETS[br... |
def layout():
df = convert_date_to_pandas(get_time_series_from_db())
df = df.replace({'name': get_aliases()})
names = df.name.unique()
children_list = [html.Div([html.H2('Monthly trends: People quoted'), dcc.Markdown("\n In this section, we visualize historical trends related to the top w... |
class CalibratorBase():
def __init__(self, image_generator, cache_file_path):
self._logger = trt.Logger(trt.Logger.INFO)
self._logger.min_severity = trt.Logger.Severity.VERBOSE
self._image_generator = image_generator
self._cache_file_path = cache_file_path
input_spec = image_... |
def packed_sequence_gather(seqs, target_device):
out = seqs[0].cuda(target_device)
for i in range(1, len(seqs)):
out += seqs[i].cuda(target_device)
return out |
def test_knorae_subspaces():
rng = np.random.RandomState(123456)
(X_dsel, X_test, X_train, y_dsel, y_test, y_train) = load_dataset(None, rng)
pool = BaggingClassifier(LogisticRegression(), max_features=0.5, random_state=rng).fit(X_train, y_train)
knorae = KNORAE(pool)
knorae.fit(X_dsel, y_dsel)
... |
class test_segmentation(VOCSegmentation):
def __init__(self, base_dir=Path.db_root_dir('pascal'), split='train', transform=None, flip=True):
super(test_segmentation, self).__init__(base_dir=base_dir, split=split, transform=transform)
self._flip_flag = flip
def __getitem__(self, index):
(... |
def load_parameters(yml: str) -> DictConfig:
cfg = OmegaConf.load(yml)
return cfg['best_params'] |
_utils.test()
def test_atomic_add_with_if_simplify():
x = ti.field(ti.i32)
step = 42
ti.root.dense(ti.i, n).place(x)
boundary = (n / 2)
def func():
for i in range(n):
if (i > boundary):
s = i
j = ti.atomic_add(s, s)
k = (j + s)
... |
def draw_black_img(img_height: int, img_width: int, blank_path: str) -> None:
blank_image = np.zeros((img_height, img_width, 3), np.uint8)
cv2.imwrite(blank_path, blank_image) |
class AnyConverter(BaseConverter):
def __init__(self, map, *items):
BaseConverter.__init__(self, map)
self.regex = ('(?:%s)' % '|'.join([re.escape(x) for x in items])) |
def main():
all_data_file = os.path.join(DATA_DIR, 'reviews_Electronics01_5.csv')
format_5core(in_json=os.path.join(RAW_DATA, 'reviews_Electronics_5.json'), out_csv=all_data_file, label01=True)
dataset_name = '5Electronics01-1-5'
leave_out_by_time_csv(all_data_file, dataset_name, leave_n=1, warm_n=5)
... |
def get_drives(dir):
folders = []
while 1:
(dir, folder) = os.path.split(dir)
if ((folder != '') and (folder != '.')):
folders.append(folder)
else:
break
folders.reverse()
return folders |
class Classifier():
def __init__(self, label_list, ren, norm_fn, device):
self._label_list = label_list
self._ren = ren
self._device = device
self._tokenizer = BertTokenizer.from_pretrained(BERT_MODEL, do_lower_case=True)
self._model = BertForSequenceClassification.from_pretr... |
def _sort_helper(g, input, dim, decending=True, out=None):
if (out is not None):
_unimplemented('Sort', 'Out parameter is not supported')
shape_ = g.op('Shape', input)
dim_size_ = g.op('Gather', shape_, g.op('Constant', value_t=torch.tensor([dim], dtype=torch.int64)))
if (_export_onnx_opset_vers... |
def tonal_dist(chroma1, chroma2, tonal_matrix=None):
if (tonal_matrix is None):
tonal_matrix = get_tonal_matrix()
warnings.warn('`tonal matrix` not specified. Use default tonal matrix', RuntimeWarning)
chroma1 = (chroma1 / np.sum(chroma1))
result1 = np.matmul(tonal_matrix, chroma1)
chrom... |
def get_count(data, tag, level):
assert (level in [1, 2, 3])
count = 0
if (level == 1):
assert (tag in get_list_tag_level_1())
for fam in llvm_IR_stmt_families:
if (fam[0] == tag):
for (key, value) in data.items():
if re.match(fam[3], key):
... |
class BlockPairDataset(FairseqDataset):
def __init__(self, dataset, dictionary, sizes, block_size, break_mode='doc', short_seq_prob=0.1, doc_break_size=1):
super().__init__()
self.dataset = dataset
self.pad = dictionary.pad()
self.eos = dictionary.eos()
self.cls = dictionary.... |
def execute(chunk: np.ndarray):
if np.issubdtype(chunk.dtype, np.uint8):
chunk = (255 - chunk)
elif (np.issubdtype(chunk.dtype, np.float32) and (chunk.max() <= 1) and (chunk.min() >= 0)):
chunk = (1.0 - chunk)
else:
raise TypeError('unsupported chunk data type.')
return [chunk] |
def _remove_urls(text: Any) -> Any:
return (re.sub(REGEX_URL, '', str(text)) if pd.notna(text) else text) |
def objective(points, sleep=True):
if (points.shape[1] != 2):
raise ValueError(f'Incorrect input shape, expected (*, 2), got {points.shape}')
observations = []
for point in points:
observation = ScaledBranin.objective(point).numpy()
if sleep:
delay = (3 * np.sum(point))
... |
class calculateDistExp():
def __init__(self, waypts='assets/data/Trials/Trial1/odom.csv', wifi='assets/data/Trials/Trial1/wifi.csv'):
self.wFile = waypts
self.dim = 2
self.TX = wifi
self.maxZ = 2.4
self.TXName = None
self.numPts = None
self.numAPs = None
... |
def _evalWrapper(eval_id: int, fn: Callable, *args, **kwargs) -> Tuple[(int, float, Any, Any)]:
start_time = timer()
exc = None
fitness = None
features = None
res = None
try:
res = fn(*args, **kwargs)
except Exception as e:
print(f'Exception during evaluation: {e}')
t... |
def propagate_memlets_scope(sdfg, state, scopes, propagate_entry=True, propagate_exit=True):
from dace.sdfg.scope import ScopeTree
if isinstance(scopes, ScopeTree):
scopes_to_process = [scopes]
else:
scopes_to_process = scopes
next_scopes = set()
while (len(scopes_to_process) > 0):
... |
def kde_viz_figure(hist: List[Tuple[(np.ndarray, np.ndarray)]], kde: np.ndarray, col: str, plot_width: int, plot_height: int, cfg: Config) -> Figure:
fig = Figure(plot_width=plot_width, plot_height=plot_height, title=col, toolbar_location=None, y_axis_type=cfg.kde.yscale)
for (i, (data, kde2)) in enumerate(zip(... |
.parametrize('function_name', get_all_functions_names())
def test_function_docstring(function_name, request):
if (function_name in FUNCTION_DOCSTRING_IGNORE_LIST):
request.applymarker(pytest.mark.xfail(run=False, reason='TODO pass numpydoc validation'))
res = numpydoc_validation.validate(function_name)
... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--input', type=str, default='.\\inputs', help='Input image or folder')
parser.add_argument('--model_path', type=str, default='experiments/pretrained_models/A_ESRGAN_Single.pth', help='Path to the pre-trained model')
parser.add_argument(... |
class OptionFillable(Fillable):
def __init__(self, offsets, content):
assert isinstance(offsets, list)
assert isinstance(content, Fillable)
self.offsets = offsets
self.content = content
def fromnulls(cls, nullcount, content):
return cls(([(- 1)] * nullcount), content)
... |
def _get_native_lib_filename():
global _native_lib_filename
if _native_lib_filename:
return _native_lib_filename
native = NativeCodeCompiler(base_name='pytopickle', code_version=1, code=open(_native_cpp_filename).read(), is_cpp=True, c_macro_defines={'LIB': 1})
_native_lib_filename = native.get_... |
def xydata_from_point_list(points):
import numbers
zero = float(0)
xdata = []
ydata = []
for xy in points:
if isinstance(xy, Expression):
xy = xy.n()
if isinstance(xy, numbers.Real):
xdata.append(float(xy))
ydata.append(zero)
elif isinstanc... |
def test_get_data_for_tensorkey_from_db(collaborator_mock, tensor_key):
expected_nparray = 'some_data'
collaborator_mock.tensor_db.get_tensor_from_cache = mock.Mock(return_value='some_data')
nparray = collaborator_mock.get_data_for_tensorkey(tensor_key)
assert (nparray == expected_nparray) |
class DCProblemTestsCC_storeJ(unittest.TestCase):
def setUp(self):
aSpacing = 2.5
nElecs = 5
surveySize = ((nElecs * aSpacing) - aSpacing)
cs = ((surveySize / nElecs) / 4)
mesh = discretize.TensorMesh([[(cs, 10, (- 1.3)), (cs, (surveySize / cs)), (cs, 10, 1.3)], [(cs, 3, (- 1... |
def set_global_config(config):
_get_or_set_config_via_tf_default_graph(config)
global _global_config
_global_config = config |
class GANloss(_Loss):
def __init__(self):
super(GANloss, self).__init__()
def forward(self, pred, label_type):
MSE = nn.MSELoss()
loss = 0
for i in range(0, len(pred)):
if label_type:
labels = torch.ones(pred[i][0].shape)
else:
... |
class TanhConcatAttention(Attention):
def __init__(self, query_size, key_size, dropout=0):
super(TanhConcatAttention, self).__init__(dropout)
self.query_weights = nn.Parameter(torch.Tensor(query_size, 1))
self.key_weights = nn.Parameter(torch.Tensor(key_size, 1))
init.xavier_uniform_... |
class LocationAwareAttention(nn.Module):
def __init__(self, decoder_dim: int=1024, attn_dim: int=1024, smoothing: bool=False) -> None:
super(LocationAwareAttention, self).__init__()
self.decoder_dim = decoder_dim
self.attn_dim = attn_dim
self.location_conv = nn.Conv1d(in_channels=1, ... |
(scope='module')
def os_custom_keys_norm():
return TriFingerObservations(observation_mode='structured', normalize_observations=True, observation_keys=['end_effector_positions', 'action_joint_positions']) |
def NN(inputs, weights, sigma, output_activation=None):
r = as_vector(inputs)
depth = len(weights)
for (i, weight) in enumerate(weights):
term = (weight['weight'] * r)
if ('bias' in weight):
term += weight['bias']
if ((i + 1) >= depth):
r = term
else:
... |
_ARCH_REGISTRY.register()
class ProposalNetwork(nn.Module):
def __init__(self, cfg):
super().__init__()
self.device = torch.device(cfg.MODEL.DEVICE)
self.backbone = build_backbone(cfg)
self.proposal_generator = build_proposal_generator(cfg, self.backbone.output_shape())
pixel... |
def GaussianClippingSimulation(Alpha, sigma, bitWidth):
highPrecision = np.random.normal(0, sigma, size=100000)
simulations = []
for alpha in Alpha:
s = np.copy(highPrecision)
Q = ((2 * alpha) / (2 ** bitWidth))
s[(s > alpha)] = alpha
s[(s < (- alpha))] = (- alpha)
s ... |
def calc_mean_std(feat, eps=1e-05):
size = feat.size()
assert (len(size) == 4)
(N, C) = size[:2]
feat_var = (feat.view(N, C, (- 1)).var(dim=2) + eps)
feat_std = feat_var.sqrt().view(N, C, 1, 1)
feat_mean = feat.view(N, C, (- 1)).mean(dim=2).view(N, C, 1, 1)
return (feat_mean, feat_std) |
_function
def parse_dependencies(source_filename):
with Utils.open_source_file(source_filename, error_handling='ignore') as fh:
source = fh.read()
distutils_info = DistutilsInfo(source)
(source, literals) = strip_string_literals(source)
source = source.replace('\\\n', ' ').replace('\t', ' ')
... |
def can_access(schedule: ScheduleType, storage: StorageType):
if (storage == StorageType.Register):
return True
if (schedule in [ScheduleType.GPU_Device, ScheduleType.GPU_Persistent, ScheduleType.GPU_ThreadBlock, ScheduleType.GPU_ThreadBlock_Dynamic, ScheduleType.GPU_Default]):
return (storage i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.