code stringlengths 101 5.91M |
|---|
def register_Ns3CallbackImpl__Void_Const_ns3Ipv6Header___amp___Ns3Ptr__lt__const_ns3Packet__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ipv6Header const &, ns3::Ptr< ns3::Pack... |
def inception_v2_base(inputs, final_endpoint='Mixed_5c', min_depth=16, depth_multiplier=1.0, use_separable_conv=True, data_format='NHWC', scope=None):
end_points = {}
if (depth_multiplier <= 0):
raise ValueError('depth_multiplier is not greater than zero.')
depth = (lambda d: max(int((d * depth_mult... |
_dispatch
def idst(x, type=2, n=None, axis=(- 1), norm=None, overwrite_x=False, workers=None):
return (Dispatchable(x, np.ndarray),) |
class Sentence(object):
def __init__(self, sent):
self.tokens = {}
self.num_tokens = 0
self.sent = sent
self.tree = None
def set_tokens(self, tokens):
for (i, (t, p)) in enumerate(tokens):
if (t == ''):
t = '='
self.tokens[i] = Toke... |
class MPNetForQuestionAnswering():
def __init__(self, *args, **kwargs):
requires_pytorch(self)
def from_pretrained(self, *args, **kwargs):
requires_pytorch(self) |
def align(input_file, en_output_file, tg_output_file):
for line in input_file:
fields = line.rstrip().split('\t')
en_chars = ' '.join((str(c) for c in fields[0]))
en_output_file.write((en_chars + '\n'))
tg_output_file.write((fields[1] + '\n')) |
class AdaActiveLearningNodeRegressor(ActiveLearningNodePerceptron, AdaNode):
def __init__(self, initial_stats=None, parent_node=None, random_state=None):
super().__init__(initial_stats, parent_node, random_state)
self._adwin = ADWIN()
self._error_change = False
self._n = 0
def n_... |
def evaluate(gold_ud, system_ud):
class Score():
def __init__(self, gold_total, system_total, correct, aligned_total=None):
self.correct = correct
self.gold_total = gold_total
self.system_total = system_total
self.aligned_total = aligned_total
self... |
def _individual_mobility_network_individual(traj, self_loops=False):
loc2loc2weight = defaultdict((lambda : defaultdict((lambda : 0))))
traj = traj.sort_values(by=constants.DATETIME)
lats_lngs = traj[[constants.LATITUDE, constants.LONGITUDE]].values
i = 1
for (lat, lng) in lats_lngs[1:]:
pre... |
def save_img_uint8(img, pth):
with open_file(pth, 'wb') as f:
Image.fromarray((np.clip(np.nan_to_num(img), 0.0, 1.0) * 255.0).astype(jnp.uint8)).save(f, 'PNG') |
def double_moments(x, y):
(batch_size, x_dim) = x.size()
(_, y_dim) = x.size()
x = torch.cat((x, Variable(torch.ones(batch_size, 1))), dim=1)
y = torch.cat((y, Variable(torch.ones(batch_size, 1))), dim=1)
x_dim += 1
y_dim += 1
x = x.unsqueeze(2)
y = y.unsqueeze(1)
outer_prod = (x.exp... |
def test_synthetic_slate_obtain_batch_bandit_feedback_using_uniform_random_behavior_policy_largescale():
n_unique_action = 100
len_list = 10
dim_context = 2
reward_type = 'binary'
random_state = 12345
n_rounds = 10000
dataset = SyntheticSlateBanditDataset(n_unique_action=n_unique_action, len... |
class GCSDataset(GCDataset):
way_steps: int = None
high_p_randomgoal: float = 0.0
def get_default_config():
return ml_collections.ConfigDict({'p_randomgoal': 0.3, 'p_trajgoal': 0.5, 'p_currgoal': 0.2, 'geom_sample': 0, 'reward_scale': 1.0, 'reward_shift': 0.0, 'terminal': False})
def sample(self... |
def _flip(arr, axes=None):
if (axes is None):
reverse = ([slice(None, None, (- 1))] * arr.ndim)
else:
reverse = ([slice(None, None, None)] * arr.ndim)
for axis in axes:
reverse[axis] = slice(None, None, (- 1))
return arr[tuple(reverse)] |
def make_context_embedder(opt, embeddings, embed_type='utterance'):
if (opt.context_embedder_type == 'mean'):
return MeanEncoder(opt.enc_layers, embeddings, embed_type)
else:
bidirectional = (True if (opt.context_embedder_type == 'brnn') else False)
return StdRNNEncoder(opt.rnn_type, bid... |
def convert_k8s_suffix(k8s_value: str) -> float:
try:
return float(k8s_value)
except ValueError:
pass
suffixes = [('Ki', 2, 10), ('Mi', 2, 20), ('Gi', 2, 30), ('Ti', 2, 40), ('Pi', 2, 50), ('Ei', 2, 60), ('n', 10, (- 9)), ('u', 10, (- 6)), ('m', 10, (- 3)), ('k', 10, 3), ('M', 10, 6), ('G', ... |
class CityScapesVideo(data.Dataset):
def __init__(self, transform=None):
self.imgs = make_dataset_video()
if (len(self.imgs) == 0):
raise RuntimeError('Found 0 images, please check the data set')
self.transform = transform
def __getitem__(self, index):
img_path = self... |
_resource
def load_bianque_v1_model():
bianque_v2_model = T5ForConditionalGeneration.from_pretrained(bianque_v1_model_name_or_path)
bianque_v2_model.to(device)
print('bianque_v1 model Load done!')
return bianque_v2_model |
class KerasActivationExtractor(ActivationExtractor):
def __init__(self, model: tf.keras.Model, layer_types_to_extract_inputs: List, image_granularity: ImageGranularity, image_input_manipulation: Callable, linear_layers: Tuple=(Dense, Conv2D)):
self.model = model
self.image_input_manipulation = image... |
def test_unknowntype_categorical():
with pytest.raises(TypeError):
UnknownType(parameters={'__categorical__': True}) |
class MicroStructureProblem(Problem):
def __init__(self):
super().__init__()
self._width = 64
self._height = 64
self._prob = {'empty': 0.5, 'solid': 0.5}
self._border_tile = 'solid'
self._random_probs = True
self._reward_weights = {'tortuosity': 1}
sel... |
_module()
class DepthwiseSeparableFCNHead(FCNHead):
def __init__(self, dw_act_cfg=None, **kwargs):
super(DepthwiseSeparableFCNHead, self).__init__(**kwargs)
self.convs[0] = DepthwiseSeparableConvModule(self.in_channels, self.channels, kernel_size=self.kernel_size, padding=(self.kernel_size // 2), no... |
class IntGELU(nn.Module):
def __init__(self, quant_mode=True, force_dequant='none'):
super().__init__()
self.quant_mode = quant_mode
if (force_dequant in ['nonlinear', 'gelu']):
logger.info('Force dequantize gelu')
self.quant_mode = False
if (not self.quant_mo... |
_module()
class ResnetGenerator(nn.Module):
def __init__(self, in_channels, out_channels, base_channels=64, norm_cfg=dict(type='IN'), use_dropout=False, num_blocks=9, padding_mode='reflect', init_cfg=dict(type='normal', gain=0.02)):
super().__init__()
assert (num_blocks >= 0), f'Number of residual b... |
class ExperimentalFeatureConfigNode(TreeConfigNode):
def init2(self, node_name):
self.props['experimental_feature'] = node_name
def child_constructor(self):
experimental_feature = self.find_prop('experimental_feature')
next_nodes = {'asan': AsanConfigNode, 'xla': XlaConfigNode, 'vulkan':... |
def get_grid_search_configs(config, excluded_keys=[]):
def bool_to_string(x: Union[(List[bool], bool)]) -> Union[(List[str], str)]:
if isinstance(x, bool):
return [str(x)]
for (i, j) in enumerate(x):
x[i] = str(j)
return x
flattened_config_dict = flatten(config, r... |
def test_len():
array = ak.highlevel.Array([1.1, 2.2, 3.3, 4.4, 5.5])
def f1(x):
return len(x)
assert (f1(array) == 5) |
class CircleLoss(GenericPairLoss):
def __init__(self, m=0.4, gamma=80, **kwargs):
super().__init__(mat_based_loss=True, **kwargs)
c_f.assert_distance_type(self, CosineSimilarity)
self.m = m
self.gamma = gamma
self.soft_plus = torch.nn.Softplus(beta=1)
self.op = (1 + s... |
def register_Ns3QueueDiscContainer_methods(root_module, cls):
cls.add_constructor([param('ns3::QueueDiscContainer const &', 'arg0')])
cls.add_constructor([])
cls.add_constructor([param('ns3::Ptr< ns3::QueueDisc >', 'qDisc')])
cls.add_method('Add', 'void', [param('ns3::QueueDiscContainer', 'other')])
... |
class Compose_Joint(object):
def __init__(self, transforms):
self.transforms = transforms
def __call__(self, img, target):
for t in self.transforms:
(img, target) = t(img, target)
return (img, target)
def __repr__(self):
format_string = (self.__class__.__name__ + ... |
def mlir_tasklet_recursion(A: dace.int32[2], B: dace.int32[1]):
('MLIR')
def fib():
(a << A[0])
(b >> B[0]) |
def assert_strict_weak_order(a, b, c, cmp_func):
from sage.matrix.constructor import matrix
from sage.combinat.permutation import Permutations
x = (a, b, c)
cmp_M = matrix(3, 3)
for i in range(3):
for j in range(3):
cmp_M[(i, j)] = (cmp_func(x[i], x[j]) == 1)
msg = 'the binar... |
def main(cfg):
if (cfg.SEED_VALUE >= 0):
print(f'Seed value for the experiment {cfg.SEED_VALUE}')
os.environ['PYTHONHASHSEED'] = str(cfg.SEED_VALUE)
random.seed(cfg.SEED_VALUE)
torch.manual_seed(cfg.SEED_VALUE)
np.random.seed(cfg.SEED_VALUE)
torch.cuda.manual_seed(cfg... |
.parametrize('dtype', [ti.i32, ti.i64])
_utils.test(arch=supported_archs_taichi_ndarray)
def test_default_ip_ndarray(dtype):
arch = ti.lang.impl.current_cfg().arch
ti.reset()
ti.init(arch=arch, default_ip=dtype)
x = ti.Vector.ndarray(2, int, ())
assert (x.dtype == impl.get_runtime().default_ip) |
def bbox(img):
rows = np.any(img, axis=1)
cols = np.any(img, axis=0)
(rmin, rmax) = np.where(rows)[0][[0, (- 1)]]
(cmin, cmax) = np.where(cols)[0][[0, (- 1)]]
return (rmin, rmax, cmin, cmax) |
def test_clean_custom(df_text: pd.DataFrame) -> None:
pipeline: List[Dict[(str, Any)]] = [{'operator': 'lowercase'}, {'operator': 'remove_html'}, {'operator': 'replace_bracketed', 'parameters': {'brackets': 'square', 'value': '**spoilers**'}}, {'operator': 'replace_bracketed', 'parameters': {'brackets': 'curly', 'v... |
def test_superb_sd():
with tempfile.TemporaryDirectory() as tempdir:
secs = [10, 2, 1, 8, 5]
with pseudo_audio(secs) as (wav_paths, num_samples):
class TestSD(SuperbSD):
def default_config(self) -> dict:
config = super().default_config()
... |
class RMSNorm(nn.Module):
def __init__(self, dim: int, eps: float=1e-08) -> None:
super().__init__()
(self.scale, self.eps) = ((dim ** (- 0.5)), eps)
self.g = nn.Parameter(torch.ones(dim))
def forward(self, x: torch.Tensor) -> torch.Tensor:
norm = (torch.norm(x, dim=(- 1), keepdi... |
def render_dt_cat(itmdt: Intermediate, cfg: Config) -> Dict[(str, Any)]:
plot_width = (cfg.plot.width if (cfg.plot.width is not None) else 972)
plot_height = (cfg.plot.height if (cfg.plot.height is not None) else 400)
tabs: List[Panel] = []
if cfg.line.enable:
(data, grp_cnt_stats, timeunit) = i... |
def _fix_order():
os.environ['CUDA_DEVICE_ORDER'] = os.environ.get('CUDA_DEVICE_ORDER', 'PCI_BUS_ID') |
class TestLogParserConfig():
def test_from_dict(self):
config_dict = {'parsing_algorithm': 'drain', 'parsing_algo_params': None}
config = LogParserConfig.from_dict(config_dict)
print(config)
assert (config.parsing_algorithm == 'drain'), 'Algorithm is not the target one'
asser... |
class GradientPTQBaseTest(BaseKerasFeatureNetworkTest):
def __init__(self, unit_test, quant_method=QuantizationMethod.SYMMETRIC, rounding_type=RoundingType.STE, per_channel=True, input_shape=(1, 16, 16, 3), hessian_weights=True, log_norm_weights=True, scaled_log_norm=False, quantization_parameter_learning=True):
... |
def exec_file(program_name, args=()):
runcmd(([os.path.abspath(program_name)] + list(args)), shell=False) |
def _raise_for_params(params, owner, method):
caller = (f'{owner.__class__.__name__}.{method}' if method else owner.__class__.__name__)
if ((not _routing_enabled()) and params):
raise ValueError(f'Passing extra keyword arguments to {caller} is only supported if enable_metadata_routing=True, which you ca... |
def complex_init(in_features, out_features, kernel_size=None, criterion='glorot'):
if (kernel_size is not None):
receptive_field = np.prod(kernel_size)
fan_out = (out_features * receptive_field)
fan_in = (in_features * receptive_field)
else:
fan_out = out_features
fan_in ... |
class BertLayer(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def probe_description(name, ctx=None):
ctx = _get_ctx(ctx)
return Z3_probe_get_descr(ctx.ref(), name) |
class SDECData():
def __init__(self, last_interaction_type, last_line_interaction_in_id, last_line_interaction_out_id, last_line_interaction_in_nu, lines_df, packet_nus, packet_energies, r_inner, spectrum_delta_frequency, spectrum_frequency_bins, spectrum_luminosity_density_lambda, spectrum_wavelength, t_inner, tim... |
def select_device(device='', batch_size=None):
s = f'YOLOR {(git_describe() or date_modified())} torch {torch.__version__} '
cpu = (device.lower() == 'cpu')
if cpu:
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
elif device:
os.environ['CUDA_VISIBLE_DEVICES'] = device
assert torch.cu... |
def setup_warn_with_traceback():
import warnings
from returnn.util.better_exchook import print_tb
def warn_with_traceback(message, category, filename, lineno, file=None, line=None):
log = (file if hasattr(file, 'write') else sys.stderr)
log.write(warnings.formatwarning(message, category, fil... |
def _make_explanation(a, b):
return (['--- actual / +++ expected'] + [line.strip('\n') for line in difflib.ndiff(a, b)]) |
class BgpLookingGlassService(Service):
__emulator: Emulator
def __init__(self):
super().__init__()
self.addDependency('Routing', False, False)
def _createServer(self) -> Server:
return BgpLookingGlassServer()
def _doConfigure(self, node: Node, server: BgpLookingGlassServer):
... |
class CatModel(torch.nn.Module):
def __init__(self):
super(CatModel, self).__init__()
def forward(self, x):
return torch.cat([x, x]) |
class BaseANN(object):
def done(self):
pass
def get_memory_usage(self):
return (psutil.Process().memory_info().rss / 1024)
def fit(self, X):
pass
def query(self, q, n):
return []
def batch_query(self, X, n):
pool = ThreadPool()
self.res = pool.map((lam... |
def get_prediction_json_path(prediction_dir: str) -> str:
files_in_dir = os.listdir(prediction_dir)
files_in_dir = [f for f in files_in_dir if f.endswith('.json')]
assert (len(files_in_dir) == 1), 'Error: The submission .zip file must contain exactly one .json file.'
prediction_json_path = os.path.join(... |
def register_Ns3UanMacRcGw_methods(root_module, cls):
cls.add_constructor([param('ns3::UanMacRcGw const &', 'arg0')])
cls.add_constructor([])
cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')], is_virtual=True)
cls.add_method('AttachPhy', 'void', [param('ns3::Ptr< ns3::UanPhy >', 'p... |
def do_generate_api(targets, sources):
header_file = targets[0]
c_file = targets[1]
doc_file = targets[2]
global_vars = sources[0]
scalar_bool_values = sources[1]
types_api = sources[2]
multiarray_funcs = sources[3]
multiarray_api = sources[:]
module_list = []
extension_list = []... |
def expand_input_by_factor(n, divisible_by=8):
return (lambda num_inputs, **_: _make_divisible((num_inputs * n), divisible_by)) |
def test_get_aggregated_tensor_privileged_function(tensor_db):
collaborator_weight_dict = {'col1': 0.1, 'col2': 0.9}
class PrivilegedSum(AggregationFunction):
def __init__(self):
super().__init__()
self._privileged = True
def call(self, local_tensors, *_):
ten... |
def hook_linear(m, x, y):
flops_per_ele = m.in_features
if (m.bias is not None):
flops_per_ele += 1
flops = (flops_per_ele * y.numel())
return int(flops) |
def _draw_cross(img, pt, color, size=4, thickness=2):
p0 = ((pt[0] - size), (pt[1] - size))
p1 = ((pt[0] + size), (pt[1] + size))
p2 = ((pt[0] + size), (pt[1] - size))
p3 = ((pt[0] - size), (pt[1] + size))
_draw_line(img, p0, p1, color, thickness)
_draw_line(img, p2, p3, color, thickness) |
class AgentBoxesWithFadedHistory(AgentRepresentation):
def __init__(self, helper: PredictHelper, seconds_of_history: float=2, frequency_in_hz: float=2, resolution: float=0.1, meters_ahead: float=40, meters_behind: float=10, meters_left: float=25, meters_right: float=25, color_mapping: Callable[([str], Tuple[(int, i... |
class TruncatedNormal(pyd.Normal):
def __init__(self, loc, scale, low=(- 1.0), high=1.0, eps=1e-06):
super().__init__(loc, scale, validate_args=False)
self.low = low
self.high = high
self.eps = eps
def _clamp(self, x):
clamped_x = torch.clamp(x, (self.low + self.eps), (se... |
_model_architecture('transformer_lm', 'transformer_lm_gpt')
def transformer_lm_gpt(args):
args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 768)
args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', 3072)
args.decoder_layers = getattr(args, 'decoder_layers', 12)
args.decoder_atte... |
class RunMode(Enum):
TPU_STATIC = 0
TPU_DYNAMIC = 1
CPU = 2
LOOP = 3
SWITCH = 4
MERGE = 5
UNKNOWN = 9 |
def register_Ns3UanTransducerHd_methods(root_module, cls):
cls.add_constructor([param('ns3::UanTransducerHd const &', 'arg0')])
cls.add_constructor([])
cls.add_method('AddPhy', 'void', [param('ns3::Ptr< ns3::UanPhy >', 'arg0')], is_virtual=True)
cls.add_method('ApplyRxGainDb', 'double', [param('double',... |
class ProjectiveConic_number_field(ProjectiveConic_field):
def __init__(self, A, f):
ProjectiveConic_field.__init__(self, A, f)
self._local_obstruction = None
self._finite_obstructions = None
self._infinite_obstructions = None
def has_rational_point(self, point=False, obstruction... |
class TestNormalizeOp(hu.HypothesisTestCase):
(X=hu.tensor(min_dim=1, max_dim=5, elements=hu.floats(min_value=0.5, max_value=1.0)), **hu.gcs)
(max_examples=10, deadline=None)
def test_normalize(self, X, gc, dc):
def ref_normalize(X, axis):
x_normed = (X / np.maximum(np.sqrt((X ** 2).sum(... |
def _add_category_id_to_contiguous_id_maps_to_metadata(dataset_names: Iterable[str]):
merged_categories = {}
for dataset_name in dataset_names:
meta = MetadataCatalog.get(dataset_name)
for (cat_id, cat_name) in meta.categories.items():
if (cat_id not in merged_categories):
... |
_start_docstrings(AutoModelForMaskedLM.__doc__)
def modelForMaskedLM(*args, **kwargs):
return AutoModelForMaskedLM.from_pretrained(*args, **kwargs) |
def zeros(shape, dtype=None, order='C'):
a = ndarray.__new__(matrix, shape, dtype, order=order)
a.fill(0)
return a |
class Euclidean(Module):
def __init__(self, inputSize, outputSize):
super(Euclidean, self).__init__()
self.weight = torch.Tensor(inputSize, outputSize)
self.gradWeight = torch.Tensor(inputSize, outputSize)
self.gradInput.resize_(inputSize)
self.output.resize_(outputSize)
... |
def get_female_dominant_sources(topicsDF, delta=1):
femaleSourcesDF = topicsDF.drop('topicDistribution').filter('sourcesFemaleCount - sourcesMaleCount >= {}'.format(delta))
return femaleSourcesDF |
def VI_Block(X, S1, S2, config):
k = config.k
ch_i = config.ch_i
ch_h = config.ch_h
ch_q = config.ch_q
state_batch_size = config.statebatchsize
bias = tf.Variable((np.random.randn(1, 1, 1, ch_h) * 0.01), dtype=tf.float32)
w0 = tf.Variable((np.random.randn(3, 3, ch_i, ch_h) * 0.01), dtype=tf.... |
class Noisy_Agent(RandomScriptAgent):
def __init__(self, onion_ratio, soup_ratio, noise_ratio):
super().__init__({'pickup_onion_and_place_in_pot': dict(prob=(onion_ratio * (1.0 - noise_ratio)), args=dict()), 'pickup_onion_and_place_random': dict(prob=(onion_ratio * noise_ratio), args=dict()), 'pickup_soup_a... |
class PoincareParticles(MutableMapping):
def __init__(self, poincare):
self.poincare = poincare
def __getitem__(self, i):
if (i == 0):
return PoincareParticle(G=np.nan, m=np.nan, Mstar=np.nan, l=np.nan, eta=np.nan, rho=np.nan, Lambda=np.nan, kappa=np.nan, sigma=np.nan)
p = se... |
def test_flux_nu(spectrum):
if (getattr(spectrum, 'distance', None) is not None):
with pytest.warns(DeprecationWarning):
test_helper.assert_quantity_allclose(spectrum.flux_nu, spectrum.luminosity_to_flux(spectrum.luminosity_density_nu, spectrum.distance))
else:
with pytest.raises(Att... |
def str2list(s, out_type=None):
s = s.replace('[', '').replace(']', '')
s = s.replace("'", '')
s = s.split(', ')
if (out_type is not None):
s = [out_type(ss) for ss in s]
return s |
def build_transformer(args):
return Transformer(d_model=args['NN']['hidden_dim'], dropout=args['NN']['dropout'], nhead=args['NN']['nheads'], dim_feedforward=args['NN']['dim_feedforward'], num_encoder_layers=args['NN']['enc_layers'], num_decoder_layers=args['NN']['dec_layers'], normalize_before=args['NN']['pre_norm'... |
def main():
img_embs = np.load('../data/img_embstrain.npy')
cap_embs = np.load('../data/cap_embstrain.npy')
print(np.shape(img_embs), np.shape(cap_embs))
img_embs = torch.from_numpy(img_embs).half().cuda()
cap_embs = torch.from_numpy(cap_embs).half().cuda()
t2ihn = np.zeros((len(cap_embs), total... |
def test_arraytype_9():
text = str(ak.Array([(1, 1.1), (2, 2.2), (3, 3.3)]).type)
parsedtype = ak.types.from_datashape(text, highlevel=False)
assert (str(parsedtype) == text) |
def bert2vit_ckpt_rename(state_dict, layerCount=8):
out_Order_dict = OrderedDict({})
for layer in range(0, layerCount):
bert_q_weight_key = (('bert.encoder.layer.' + str(layer)) + '.attention.self.query.weight')
bert_q_bias_key = (('bert.encoder.layer.' + str(layer)) + '.attention.self.query.bia... |
def remove_index_types(G, to_track, to_reverse_track):
found_track = False
for e in G.edges(data=True):
if (e[2]['stmt'] == to_track):
print('Found ', to_track)
found_track = True
if ((re.match('<%ID> = extractelement', e[2]['stmt']) is not None) or (re.match('<%ID> = in... |
class TFMultipleChoiceModelOutput(ModelOutput):
loss: Optional[tf.Tensor] = None
logits: tf.Tensor = None
hidden_states: Optional[Tuple[tf.Tensor]] = None
attentions: Optional[Tuple[tf.Tensor]] = None |
class Hypothesis():
def __init__(self, trgt_sentence, total_score, score_breakdown=[], base_score=0.0, statistics=None):
self.trgt_sentence = trgt_sentence
self.total_score = total_score
self.score_breakdown = score_breakdown
self.base_score = base_score
self.statistics = sta... |
def clean_no_orgnr(df: Union[(pd.DataFrame, dd.DataFrame)], column: str, output_format: str='standard', inplace: bool=False, errors: str='coerce', progress: bool=True) -> pd.DataFrame:
if (output_format not in {'compact', 'standard'}):
raise ValueError(f'output_format {output_format} is invalid. It needs to... |
def mkdirs(config, trial_idx):
evals_dir = 'evals'
logs_dir = 'logs'
saves_dir = 'saves'
if (not os.path.exists(evals_dir)):
os.mkdir(evals_dir)
if (not os.path.exists(logs_dir)):
os.mkdir(logs_dir)
if (not os.path.exists(saves_dir)):
os.mkdir(saves_dir)
model_name = ... |
def test_arit3():
x = Symbol('x')
y = Symbol('y')
raises(TypeError, (lambda : ('x' * x))) |
def register_types(module):
root_module = module.get_root()
module.add_enum('QueueSizeUnit', ['PACKETS', 'BYTES'], import_from_module='ns.network')
module.add_enum('LogLevel', ['LOG_NONE', 'LOG_ERROR', 'LOG_LEVEL_ERROR', 'LOG_WARN', 'LOG_LEVEL_WARN', 'LOG_DEBUG', 'LOG_LEVEL_DEBUG', 'LOG_INFO', 'LOG_LEVEL_IN... |
def run_job(logger, opt, output_dir, output_dir_ckpt, train):
device_id = allocate_device()
opt_override = {'device': device_id}
def merge(a, b):
d = {}
d.update(a)
d.update(b)
return d
opt = merge(opt, opt_override)
logger.info('new job: job_id={}, device_id={}'.form... |
class TestSolveLyapunov():
cases = [(np.array([[1, 2], [3, 4]]), np.array([[9, 10], [11, 12]])), (np.array([[(1.0 + 1j), 2.0], [(3.0 - 4j), 5.0]]), np.array([[(2.0 - 2j), (2.0 + 2j)], [((- 1.0) - 1j), 2.0]])), (np.array([[1.0, 2.0], [3.0, 5.0]]), np.array([[(2.0 - 2j), (2.0 + 2j)], [((- 1.0) - 1j), 2.0]])), (np.arr... |
class DeformConv(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, deformable_groups=1, bias=False):
super(DeformConv, self).__init__()
assert (not bias)
assert ((in_channels % groups) == 0), 'in_channels {} cannot be divisible ... |
class SlopeTrigger(MetricTrigger, StatefulTriggerMixin):
def __init__(self, range, window_size=10):
self.range = range
self.window_size = window_size
self.vals = deque(maxlen=window_size)
def __call__(self, new_value):
self.vals.append(new_value)
if (len(self.vals) < self... |
def conv2d_transpose(inputs, num_output_channels, kernel_size, scope, stride=[1, 1], padding='SAME', use_xavier=True, stddev=0.001, weight_decay=0.0, activation_fn=tf.nn.relu, bn=False, bn_decay=None, is_training=None, is_dist=False):
with tf.variable_scope(scope) as sc:
(kernel_h, kernel_w) = kernel_size
... |
class E(nn.Module):
def __init__(self, num_features=64, activation=F.relu):
super(E, self).__init__()
self.num_features = num_features
self.activation = activation
self.block1 = OptimizedBlock(6, num_features)
self.block2 = Block(num_features, (num_features * 2), activation=a... |
class MLPDuelingModel(Model):
def __init__(self, output_dim, name=None, hidden_sizes=(32, 32), hidden_nonlinearity=tf.nn.relu, hidden_w_init=tf.contrib.layers.xavier_initializer, hidden_b_init=tf.zeros_initializer, output_nonlinearity=None, output_w_init=tf.contrib.layers.xavier_initializer, output_b_init=tf.zeros_... |
_builder('modelnet40_cls')
class ModelNetClassificationBuilder(MultiModalDatasetBuilder):
train_dataset_cls = ModelNetClassificationDataset
eval_dataset_cls = ModelNetClassificationDataset
DATASET_CONFIG_DICT = {'default': 'configs/datasets/modelnet40/defaults_cls.yaml'} |
class Concatenate(Job):
def __init__(self, inputs):
assert inputs
if isinstance(inputs, set):
inputs = list(inputs)
inputs.sort(key=(lambda x: str(x)))
assert isinstance(inputs, list)
if (len(inputs) == 1):
self.out = inputs.pop()
else:
... |
def compose_system_compile_flags(is_posix: bool) -> list:
if (not is_posix):
return []
(cflags, configure_cppflags, configure_cflags) = sysconfig.get_config_vars('CFLAGS', 'CONFIGURE_CPPFLAGS', 'CONFIGURE_CFLAGS')
return ((((cflags + ' ') + configure_cppflags) + ' ') + configure_cflags).split() |
def habitat_to_mp3d(pt_habitat: np.ndarray) -> np.ndarray:
return quat_rotate_vector(quat_from_two_vectors(np.array([0.0, 1.0, 0.0]), np.array([0.0, 0.0, 1.0])), pt_habitat) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.