code stringlengths 101 5.91M |
|---|
class VariableCreatingStatement(Statement, metaclass=abc.ABCMeta):
def __init__(self, test_case: tc.TestCase, ret_val: vr.VariableReference):
super().__init__(test_case)
self.ret_val: vr.VariableReference = ret_val |
class TriangularModuleMorphismFromFunction(ModuleMorphismFromFunction, TriangularModuleMorphism):
def __init__(self, domain, function, codomain=None, category=None, **keywords):
ModuleMorphismFromFunction.__init__(self, function=function, domain=domain, codomain=codomain, category=category)
Triangul... |
def prepro(args):
source_dir = args.source_dir
target_dir = args.target_dir
lang = args.lang
task = args.task
is_large = args.large
dev_ratio = args.dev_ratio
all_tasks = list(map(str, range(1, 21)))
tasks = (all_tasks if (task == 'all') else task.split(','))
for task in tasks:
... |
def remove_risky_req(prompt):
prompt = removed_submodules(prompt, ['risky_outcome', 'risky_actions', 'real_req_risky_outcome', 'potential_risk_requirement', 'benign_requirement', 'diversity_risky_outcome', 'feasible_underspec_task_info', 'toolkits_risks', 'brainstorm_case_scenarios_risks', 'brainstorm_task_risks', ... |
_builder('vatex_caption')
class VATEXCapBuilder(MultiModalDatasetBuilder):
train_dataset_cls = VATEXCaptionDataset
eval_dataset_cls = VATEXCaptionEvalDataset
DATASET_CONFIG_DICT = {'default': 'configs/datasets/vatex/defaults_cap.yaml'} |
class TarInfo(object):
__slots__ = ('name', 'mode', 'uid', 'gid', 'size', 'mtime', 'chksum', 'type', 'linkname', 'uname', 'gname', 'devmajor', 'devminor', 'offset', 'offset_data', 'pax_headers', 'sparse', 'tarfile', '_sparse_structs', '_link_target')
def __init__(self, name=''):
self.name = name
... |
class Table(object):
def __init__(self, results: List[common.Measurement], colorize: bool, trim_significant_figures: bool, highlight_warnings: bool):
assert (len(set((r.label for r in results))) == 1)
self.results = results
self._colorize = colorize
self._trim_significant_figures = t... |
def get_parser():
parser = argparse.ArgumentParser()
parser.add_argument('--n-epochs', default=1, type=int, help='number of epochs')
parser.add_argument('--batch-size-train', default=64, type=int, help='training batch size')
parser.add_argument('--batch-size-test', default=1000, type=int, help='test bat... |
def range_serialize(range_instance: range) -> 'IOData':
import scqubits.io_utils.fileio as io
attributes = {'start': range_instance.start, 'stop': range_instance.stop, 'step': range_instance.step}
ndarrays: Dict[(str, ndarray)] = {}
objects: Dict[(str, object)] = {}
typename = type(range_instance)._... |
def add_pipeline_model_mapping(test_class, overwrite=False):
if (getattr(test_class, 'pipeline_model_mapping', None) is not None):
if (not overwrite):
return ('', (- 1))
line_to_add = get_pipeline_model_mapping_string(test_class)
if (len(line_to_add) == 0):
return ('', (- 1))
... |
def concatenate(args, lines):
for line in lines:
infile = line.split()[0]
outfile = line.split()[1]
md5gt = line.split()[2]
out = subprocess.call(('cat %s/%s > %s/%s' % (args.save_path, infile, args.save_path, outfile)), shell=True)
md5ck = md5(('%s/%s' % (args.save_path, out... |
def LF_left_punct(span):
cspan = get_containing_span(span)
left = get_left_span(cspan, span.sentence, window=1)
if (left.text == '+'):
return NON_NEGATED
return ABSTAIN |
def main(argv=None):
parser = argparse.ArgumentParser(description='Takes one or more file paths and reports their detected encodings')
parser.add_argument('input', help='File whose encoding we would like to determine. (default: stdin)', type=argparse.FileType('... |
def _sympysage_ynm(self):
from sage.functions.special import spherical_harmonic
return spherical_harmonic(self.args[0]._sage_(), self.args[1]._sage_(), self.args[2]._sage_(), self.args[3]._sage_()) |
def get_plugin_v3(module_name, sources, headers=None, source_dir=None, **build_kwargs):
assert (verbosity in ['none', 'brief', 'full'])
if (headers is None):
headers = []
if (source_dir is not None):
sources = [os.path.join(source_dir, fname) for fname in sources]
headers = [os.path.... |
def get_que_token(task, specific=False):
if specific:
return f'[que_{task}]'
else:
return '[que]' |
class DistanceMetric(Metric):
def evaluate_generation(self, adapter_spec: AdapterSpec, request_state: RequestState, metric_service: MetricService, eval_cache_path: str) -> List[Stat]:
references = request_state.instance.references
(_, rel_str, relation_type) = map((lambda _: _.output.text), referenc... |
class TestReporter(Reporter):
__test__ = False
def __init__(self, test_case):
super(TestReporter, self).__init__()
self._test_case = test_case
def run_failed(self, _run_id, _cmdline, _return_code, _output):
self._test_case.fail()
def run_completed(self, run_id, statistics, cmdlin... |
def tf_mobilenetv3_small_minimal_100(pretrained=False, **kwargs):
kwargs['bn_eps'] = BN_EPS_TF_DEFAULT
kwargs['pad_type'] = 'same'
model = _gen_mobilenet_v3('tf_mobilenetv3_small_minimal_100', 1.0, pretrained=pretrained, **kwargs)
return model |
def build_sam_vit_b(checkpoint=None):
return _build_sam(encoder_embed_dim=768, encoder_depth=12, encoder_num_heads=12, encoder_global_attn_indexes=[2, 5, 8, 11], checkpoint=checkpoint) |
def eval(model, criterion, data, vocab_size):
total_loss = 0
total_words = 0
total_num_correct = 0
model.eval()
for i in range(len(data)):
batch = data[i]
with torch.no_grad():
outputs = model(batch)
targets = batch[(- 1)]
(loss, _, num_correct) = memo... |
class SEmodule(torch.nn.Module):
def __init__(self, input_shape, inner_dim, activation=torch.nn.Sigmoid, norm=BatchNorm1d):
super().__init__()
self.inner_dim = inner_dim
self.norm = norm
self.activation = activation
(bz, t, chn) = input_shape
self.conv = Sequential(in... |
class SuffixPerturbation(TextPerturbation):
(frozen=True)
class Description(PerturbationDescription):
suffix: str = ''
name: str = 'style'
def __init__(self, suffix: str):
self._suffix: str = suffix
def description(self) -> PerturbationDescription:
return SuffixPerturbation.D... |
def DM_273_17_1():
M = orthogonal_array(17, 17)
M = [R for R in M if any(((x != R[0]) for x in R))]
B = (1, 2, 4, 8, 16, 32, 64, 91, 117, 128, 137, 182, 195, 205, 234, 239, 256)
M = [[B[x] for x in R] for R in M]
M.append(([0] * 17))
from sage.rings.finite_rings.integer_mod_ring import IntegerMo... |
.parametrize('implementation, dtype, size, shape, overwrite, getri', [pytest.param('MKL', np.float32, 4, [[4, 4], [4, 4], [0, 0], [0, 0], [0, 1], [0, 1]], False, True, marks=pytest.mark.mkl), pytest.param('MKL', np.float64, 4, [[4, 4], [4, 4], [0, 0], [0, 0], [0, 1], [0, 1]], False, True, marks=pytest.mark.mkl), pytest... |
class TokenGroup(object):
def __init__(self, tu, memory, count):
self._tu = tu
self._memory = memory
self._count = count
def __del__(self):
conf.lib.clang_disposeTokens(self._tu, self._memory, self._count)
def get_tokens(tu, extent):
tokens_memory = POINTER(Token)()
... |
class BaseTextDetTargets():
def __init__(self):
pass
def point2line(self, xs, ys, point_1, point_2):
a_square = (np.square((xs - point_1[0])) + np.square((ys - point_1[1])))
b_square = (np.square((xs - point_2[0])) + np.square((ys - point_2[1])))
c_square = (np.square((point_1[0]... |
_SEG_HEADS_REGISTRY.register()
class DeepLabV3Head(nn.Module):
def __init__(self, cfg, input_shape: Dict[(str, ShapeSpec)]):
super().__init__()
self.in_features = cfg.MODEL.SEM_SEG_HEAD.IN_FEATURES
in_channels = [input_shape[f].channels for f in self.in_features]
aspp_channels = cfg.... |
class LayerDecayValueAssigner(object):
def __init__(self, values):
self.values = values
def get_scale(self, layer_id):
return self.values[layer_id]
def get_layer_id(self, var_name):
return get_num_layer_for_convnext(var_name) |
(reuse_venv=True)
def coverage(session):
session.install('--upgrade', 'pip')
session.install('--upgrade', 'coverage[toml]')
session.run('coverage', 'report')
session.run('coverage', 'xml')
htmlcov_path = (DIR / 'htmlcov')
if htmlcov_path.exists():
session.log(f'rm -r {htmlcov_path}')
... |
def stochastic_centers_matching(graph: Graph, node_weight_function: NodeWeightFunction, edge_weight_function: EdgeWeightFunction, L, P, uf: UnionFind, verbose=False, record_history=False, special_blocks=None, sb_names=None):
print('stochastic_centers_matching')
prev_graph = Graph.from_other(graph)
uf2 = Uni... |
def test_win_check():
board = jnp.int32([(- 1), (- 1), (- 1), (- 1), (- 1), (- 1), (- 1), (- 1), (- 1)])
turn = jnp.int32(1)
assert (not _win_check(board, turn))
board = jnp.int32([1, (- 1), (- 1), (- 1), 1, (- 1), 0, (- 1), 0])
turn = jnp.int32(1)
assert (not _win_check(board, turn))
board ... |
class CdfNormalizationCallback(Callback):
def __init__(self) -> None:
self.image_dist: (LogNormal | None) = None
self.pixel_dist: (LogNormal | None) = None
def setup(self, trainer: pl.Trainer, pl_module: AnomalyModule, stage: (str | None)=None) -> None:
del trainer, stage
if (not... |
class CALayer(nn.Module):
def __init__(self, channel, reduction=16):
super(CALayer, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.conv_du = nn.Sequential(nn.Conv2d(channel, (channel // reduction), 1, padding=0, bias=True), nn.ReLU(inplace=True), nn.Conv2d((channel // reductio... |
_model_architecture('transformer_lm', 'transformer_lm_gbw')
_model_architecture('transformer_lm', 'transformer_lm_baevski_gbw')
def transformer_lm_baevski_gbw(args):
args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 512)
args.dropout = getattr(args, 'dropout', 0.1)
args.attention_dropout = getattr... |
class Runtime():
def __init__(self):
pass
def aggregator(self):
raise NotImplementedError
def aggregator(self, aggregator: Aggregator):
raise NotImplementedError
def collaborators(self):
raise NotImplementedError
def collaborators(self, collaborators: List[Collaborato... |
def etl_starr_omop_program() -> None:
parser = argparse.ArgumentParser(description='An extraction tool for STARR-OMOP v5 sources')
parser.add_argument('omop_source', type=str, help='Path of the folder to the omop source')
parser.add_argument('target_location', type=str, help='The place to store the extract'... |
class SawyerDoorUnlockEnv(SawyerXYZEnv):
def __init__(self):
hand_low = ((- 0.5), 0.4, (- 0.15))
hand_high = (0.5, 1, 0.5)
obj_low = ((- 0.1), 0.8, 0.1)
obj_high = (0.1, 0.85, 0.1)
goal_low = ((- 0.1), 0.76, 0.1699)
goal_high = (0.2, 0.81, 0.1701)
super().__in... |
class KitModel(nn.Module):
def __init__(self, weight_file):
super(KitModel, self).__init__()
global __weights_dict
__weights_dict = load_weights(weight_file)
self.conv_conv1 = self.__conv(2, name='conv_conv1', in_channels=3, out_channels=96, kernel_size=(7, 7), stride=(2, 2), groups=... |
def prep_type_tokens(tokenlist, token_format=token_format):
return [TypeToken(tok[0], token_format.format(tok[0]), tok[1]) for tok in tokenlist] |
def conv_block_bn(x, filters):
x = Conv2D(filters=filters, kernel_size=(3, 3), padding='same', use_bias=False)(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
return x |
def detect_loader(schema_or_location: (str | dict[(str, Any)]), app: Any, is_openapi: bool) -> Callable:
if isinstance(schema_or_location, str):
if file_exists(schema_or_location):
return (oas_loaders.from_path if is_openapi else gql_loaders.from_path)
if ((app is not None) and (not urlp... |
class EsmForSequenceClassification(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def load_videos_tag(mat_path='./data/ute_query/Tags.mat'):
mat = scipy.io.loadmat(mat_path)
videos_tag = process_mat(mat)
return videos_tag |
def convert_to_timedelta(column):
nan_mask = pd.isna(column)
column[nan_mask] = 0
column = pd.to_timedelta(column)
column[nan_mask] = pd.NaT
return column |
class MinimizationProblem():
def __call__(self, x: TensorList) -> TensorList:
raise NotImplementedError
def ip_input(self, a, b):
return sum((a.view((- 1)) b.view((- 1))))
def M1(self, x):
return x
def M2(self, x):
return x |
def _getmp(self):
try:
data = self.info['mp']
except KeyError:
return None
file_contents = io.BytesIO(data)
head = file_contents.read(8)
endianness = ('>' if (head[:4] == b'MM\x00*') else '<')
try:
info = TiffImagePlugin.ImageFileDirectory_v2(head)
file_contents.s... |
def preprocess_lm_data(data_dir):
preprocess_parser = preprocess.get_parser()
preprocess_args = preprocess_parser.parse_args(['--only-source', '--trainpref', os.path.join(data_dir, 'train.out'), '--validpref', os.path.join(data_dir, 'valid.out'), '--testpref', os.path.join(data_dir, 'test.out'), '--destdir', da... |
_module()
class VideoDataset(BaseDataset):
def __init__(self, ann_file, pipeline, start_index=0, **kwargs):
super().__init__(ann_file, pipeline, start_index=start_index, **kwargs)
def load_annotations(self):
if self.ann_file.endswith('.json'):
return self.load_json_annotations()
... |
def assert_is_tensor(x, ndim):
if (x.ndim != ndim):
raise ValueError(f'Expected {ndim}-tensor but got {x.ndim}-tensor') |
def kaiming_init(m):
if isinstance(m, (nn.Linear, nn.Conv2d)):
init.kaiming_normal(m.weight)
if (m.bias is not None):
m.bias.data.fill_(0)
elif isinstance(m, (nn.BatchNorm1d, nn.BatchNorm2d)):
m.weight.data.fill_(1)
if (m.bias is not None):
m.bias.data.fil... |
def test_knorau():
(pool_classifiers, X_dsel, y_dsel, X_test, y_test) = setup_classifiers()
knorau = KNORAU(pool_classifiers, DFP=True, with_IH=True, IH_rate=0.1)
knorau.fit(X_dsel, y_dsel)
assert np.isclose(knorau.score(X_test, y_test), 0.) |
def DistributedOptimizer(optimizer, named_parameters=None, compression=Compression.none, backward_passes_per_step=1, op=Average):
if ((op != Adasum) or (size() == 1)):
cls = type(optimizer.__class__.__name__, (optimizer.__class__,), dict(_DistributedOptimizer.__dict__))
return cls(optimizer.param_gr... |
def add_column(B, H_B, a, proof):
verbose('starting add_column')
if (B.rank() < B.nrows()):
return add_column_fallback(B, a, proof)
else:
z = solve_system_with_difficult_last_row(B, a)
(zd, d) = z._clear_denom()
x = (H_B * zd)
if (d != 1):
for i in range(x.nrows()):
... |
class ConvNet(nn.Module):
def __init__(self):
super(ConvNet, self).__init__()
self.conv1 = nn.Conv2d(1, 20, 5, 1)
self.conv2 = nn.Conv2d(20, 50, 5, 1)
self.fc1 = nn.Linear(((4 * 4) * 50), 500)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, 2, ... |
_sentencepiece
_tokenizers
class GPTSw3TokenizationTest(TokenizerTesterMixin, unittest.TestCase):
tokenizer_class = GPTSw3Tokenizer
test_rust_tokenizer = False
test_sentencepiece = True
test_sentencepiece_ignore_case = False
def setUp(self):
super().setUp()
tokenizer = GPTSw3Tokenize... |
def split_sentence(sentence, class_name):
if ('.txt' in sentence):
sentence = sentence[(len(class_name) + 4):]
elif ('.md' in sentence):
sentence = sentence[(len(class_name) + 3):]
else:
sentence = sentence[len(class_name):]
tagged_sent = pos_tag(sentence.lower().split())
if ... |
def build_prior(task: Task, model: elfi.ElfiModel):
log = logging.getLogger(__name__)
log.warn('Will discard any correlations in prior')
bounds = {}
prior_cls = str(task.prior_dist)
if (prior_cls == 'Independent()'):
prior_cls = str(task.prior_dist.base_dist)
prior_params = {}
if ('M... |
class LeNet(nn.Module):
def __init__(self, num_classes=1000):
super(LeNet, self).__init__()
self.conv1 = nn.Conv2d(3, 6, kernel_size=5)
self.conv2 = nn.Conv2d(6, 16, kernel_size=5)
self.fc1 = nn.Linear(((16 * 5) * 5), 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.L... |
def pretty_print_templates(templates, verbosity=1):
print(('-' * 70))
for ii in templates:
print(('[Name: %s] [Type: %s]' % (ii['name'], ii['type'])))
print(('-' * 70))
print(('Total of %s templates..' % len(templates)))
print(('-' * 70)) |
def run_analysis(sample, graph, config: AnalysisPipelineConfig, n_iter, recomputation=True, bw_GBps=12, verbose=True, async_pipeline=False, add_comm_times_to_balance=True, sequential_model=None, stages_on_same_gpu: Optional[List[Set[int]]]=None, PRINT_THEORETICAL=False, PRINT_MIN_MAX_BALANCE=False, PRINT_VAR_STD=False,... |
def F(state_m, adjoint_m, u, v, geometry):
(y_m, z_m) = split(state_m)
(p_m, q_m) = split(adjoint_m)
return ((((((inner(grad(y_m), grad(p_m)) * geometry.dx) + ((z_m * p_m) * geometry.dx)) - ((u * p_m) * geometry.dx)) + (inner(grad(z_m), grad(q_m)) * geometry.dx)) + ((y_m * q_m) * geometry.dx)) - ((v * q_m) ... |
class Conv1_1_Block(nn.Module):
def __init__(self, in_chs, block_ch):
super(Conv1_1_Block, self).__init__()
self.conv1_1_branches = nn.ModuleList()
for in_ch in in_chs:
self.conv1_1_branches.append(Conv1_1_Branch(in_ch, block_ch))
def forward(self, inputs, betas, block_sub_ob... |
def resample_subdir(data_dir, data_subdir, out_dir, target_sr):
print(f'resampling {data_subdir}')
tfm = sox.Transformer()
tfm.set_output_format(rate=target_sr)
out_sub_dir = os.path.join(out_dir, data_subdir)
if (not os.path.isdir(out_sub_dir)):
os.makedirs(out_sub_dir)
for file in os.l... |
.run_in_serial
_utils.test(arch=supported_archs_taichi_ndarray)
def test_ndarray_in_python_func():
def test():
z = ti.ndarray(float, (8192, 8192))
for i in range(300):
test() |
_flax
class FlaxViTModelTest(FlaxModelTesterMixin, unittest.TestCase):
all_model_classes = ((FlaxViTModel, FlaxViTForImageClassification) if is_flax_available() else ())
def setUp(self) -> None:
self.model_tester = FlaxViTModelTester(self)
self.config_tester = ConfigTester(self, config_class=ViT... |
def error(s, *args, **kwargs):
print('\r\x1b[K', end='', file=sys.stderr)
print(s.format(*args, **kwargs), file=sys.stderr)
if kwargs.get('flush'):
sys.stderr.flush() |
def get_args():
parser = argparse.ArgumentParser(description='This script converts a segments and labels file\n to a NIST RTTM file. It handles overlapping segments (e.g. the\n output of a sliding-window diarization system).')
parser.add_argument('segments', type=str, help='Input segments file')
parse... |
def generate_analogy_questions(analogy_questions_file):
print('\tPrinting analogy questions to file ', analogy_questions_file)
tot_analogies = 0
f = open(analogy_questions_file, 'w')
f.close()
descr = 'Integer binary operations (type semantic analogy)'
print('\tGenerating:', descr)
num_anlgy... |
def CreateMultiBoxHead(net, data_layer='data', num_classes=[], from_layers=[], use_objectness=False, normalizations=[], use_batchnorm=True, lr_mult=1, use_scale=True, min_sizes=[], max_sizes=[], prior_variance=[0.1], aspect_ratios=[], steps=[], img_height=0, img_width=0, share_location=True, flip=True, clip=True, offse... |
def draw_net(config: object, genome: object, view: object=False, filename: object=None, node_names: object=None, show_disabled: object=True, prune_unused: object=False, node_colors: object=None, fmt: object='svg') -> object:
if (graphviz is None):
warnings.warn('This display is not available due to a missin... |
_registry.register('google_qa_answer_helpful')
class GoogleQuestQALabelHelpful(GoogleQuestQALabel):
def label_columns(self):
return ['answer_helpful']
def label_types(self):
return [_NUMERICAL] |
.parametrize('input_meters, expected_kilometers', [(1000, 1), (10000, 10)])
def test__meters_to_kilometers(h3_tess, input_meters, expected_kilometers):
assert (h3_tess._meters_to_kilometers(input_meters) == expected_kilometers) |
class ImageLabelParse():
def __init__(self, image, labels):
self.image = image
self.labels = labels
def get_labeled_image(self, **kwargs):
image = cv2.cvtColor(self.image, cv2.COLOR_GRAY2BGR)
for label in self.labels.values():
draw_label(image, label, **kwargs)
... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--data-root', '-d', required=True, type=str, help='data root with sub-folders for each language <root>/<src_lang>')
(parser.add_argument('--vocab-type', default='unigram', required=True, type=str, choices=['bpe', 'unigram', 'char']),)
p... |
class ObserverBase(ABC, nn.Module):
def __init__(self, dtype):
super(ObserverBase, self).__init__()
self.dtype = dtype
def forward(self, x):
pass
def calculate_qparams(self, **kwargs):
pass
with_args = classmethod(_with_args) |
def register_Ns3UeCapabilities_s_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::UeCapabilities_s const &', 'arg0')])
cls.add_instance_attribute('m_halfDuplex', 'bool', is_const=False)
cls.add_instance_attribute('m_intraSfHopping', 'bool', is_const=False)
cls.add_... |
def drop_pai_model(datasource, model_name):
(user, passwd, address, database) = MaxComputeConnection.get_uri_parts(datasource)
cmd = ('drop offlinemodel if exists %s' % model_name)
subprocess.run(['odpscmd', '-u', user, '-p', passwd, '--project', database, '--endpoint', address, '-e', cmd], check=True) |
def _resnet(arch, block, layers, **kwargs):
model = ResNet(block, layers, **kwargs)
return model |
class Generator(object):
def __init__(self, name, is_train, norm='batch', activation='relu', batch_size=64, output_height=64, output_width=128, input_dim=64, output_dim=3, use_resnet=False):
print(' [*] Init Generator %s', name)
self.name = name
self._is_train = is_train
self._norm =... |
def get_ner_charlm_package(lang, package):
return get_charlm_package(lang, package, ner_charlms, default_charlms) |
def remove_global_identifiers(G, to_track):
found_track = False
for e in G.edges(data=True):
if (e[2]['stmt'] == to_track):
print('Found ', to_track)
found_track = True
e[2]['stmt'] = re.sub(rgx.global_id, '<>', e[2]['stmt'])
if found_track:
if (e[2]['... |
def _get_cell(lines):
line1 = [x for x in lines[0].split()]
if _is_exist_symbols(line1):
symbols = line1
else:
symbols = None
scale = float(lines[1])
lattice = []
for i in range(2, 5):
lattice.append([float(x) for x in lines[i].split()[:3]])
lattice = (np.array(lattic... |
def retrieve_field(cls):
import os
(downloaded, cls) = check_downloaded(cls)
file_path = os.path.join(cls.path_raw, cls.filename)
if (cls.stream == 'moda'):
file_path_raw = file_path
else:
file_path_raw = file_path.replace('daily', 'oper')
if (downloaded == True):
print('... |
def get_by_name(container, name, name_field='name'):
names = [getattr(x, name_field) for x in container]
inds = [i for (i, e) in enumerate(names) if (e == name)]
if (len(inds) > 1):
raise Exception('Found multiple get_by_name matches, undefined behavior')
elif (len(inds) == 0):
return No... |
_LAYERS.register_module()
class TwoIdentity(BaseModule):
def __init__(self, *args, **kwargs):
super(TwoIdentity, self).__init__()
def forward(self, x1, x2):
return (x1, x2) |
def show_status():
if (status_dev in ['net', 'all']):
show_device_status(network_devices, 'Network', if_field=True) |
def make_landmark_head(fpn_num=3, inchannels=64, anchor_num=2):
landmarkhead = nn.ModuleList()
for i in range(fpn_num):
landmarkhead.append(LandmarkHead(inchannels, anchor_num))
return landmarkhead |
def UnitaryDualPolarGraph(m, q):
from sage.libs.gap.libgap import libgap
G = _polar_graph(m, (q ** 2), libgap.GeneralUnitaryGroup(m, q), intersection_size=int((((q ** (2 * ((m // 2) - 1))) - 1) / ((q ** 2) - 1))))
G.relabel()
G.name(('Unitary Dual Polar Graph DU' + str((m, q))))
if (m == 4):
... |
class FlaxRegNetModel(metaclass=DummyObject):
_backends = ['flax']
def __init__(self, *args, **kwargs):
requires_backends(self, ['flax']) |
(params=['univariate', 'multivariate'])
def arange_graph(request):
shape = ((3, 7, 11) if (request.param == 'multivariate') else (3, 7))
total_elems = np.product(shape)
nodes = IndexedArray((np.arange(total_elems).reshape(shape) / total_elems), index=['a', 'b', 'c'])
edges = pd.DataFrame({'source': ['a'... |
def von_mises_cdf_series(k, x, p):
x = float(x)
s = np.sin(x)
c = np.cos(x)
sn = np.sin((p * x))
cn = np.cos((p * x))
R = 0
V = 0
for n in range((p - 1), 0, (- 1)):
(sn, cn) = (((sn * c) - (cn * s)), ((cn * c) + (sn * s)))
R = (1.0 / (((2 * n) / k) + R))
V = (R * ... |
def _vggface2_topk_frontal_nonmates(wb, topk):
np.random.seed(42)
n_minibatch = 2
vggface2 = VGGFace2('/proj/janus6/vggface2')
imlist = vipy.util.chunklistbysize([im for im in vggface2.frontalset(n_frontal=n_minibatch)], n_minibatch)
imlist_preprocessed = [torch.cat([wb.net.preprocess(f_detection(im... |
class ResNetV2(nn.Module):
def __init__(self, block_units, width_factor, head_size=21843, zero_head=False):
super().__init__()
wf = width_factor
self.wf = wf
self.root = nn.Sequential(OrderedDict([('conv', StdConv2d(3, (64 * wf), kernel_size=7, stride=2, padding=3, bias=False)), ('pa... |
class HalfCheetahDirEnv(HalfCheetahEnvMetaBase):
def __init__(self, task=None):
task = (task or {'direction': 1.0})
self._task = task
self._goal_dir = task['direction']
super().__init__()
def step(self, action):
xposbefore = self.sim.data.qpos[0]
self.do_simulatio... |
def my_evaluate(ground_truth_file, prediction_file):
(F1, EM, TOTAL, SKIP) = evaluate(ground_truth_file, prediction_file)
AVG = ((EM + F1) * 0.5)
return (F1, EM, AVG) |
def load_tf_weights_in_big_bird(*args, **kwargs):
requires_backends(load_tf_weights_in_big_bird, ['torch']) |
class Put_Ingredient_Everywhere(BaseScriptPeriod):
def __init__(self, random_put=True, random_ingredient=True, obj=['onion', 'tomato']):
super().__init__(period_name='Put_Ingredient_Everywhere')
self.random_put = random_put
self.random_ingredient = random_ingredient
self.target_obj =... |
class FBLinkedRelationCache(FBCacheBase):
FILENAME = 'LinkedRelation.bin'
def query_in_out_relation(self, entity):
if (not self.ready):
self.load()
if (entity in self.data):
return self.data[entity]
(in_r, out_r) = get_adjacent_relations(entity)
(in_r, out... |
def count_work_reduce(node, symbols, state):
result = 0
if (node.wcr is not None):
result += count_arithmetic_ops_code(node.wcr)
in_memlet = None
in_edges = state.in_edges(node)
if ((in_edges is not None) and (len(in_edges) == 1)):
in_memlet = in_edges[0]
if ((in_memlet is not No... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.