code stringlengths 101 5.91M |
|---|
def get_human_goals(all_products, product_prices):
goals = []
cnt_atts = defaultdict(int)
cnt = 0
for item in all_products:
asin = item['asin']
if ('instructions' not in item):
continue
for product in item['instructions']:
attributes = product['instruction... |
def analyze(model, dataset, sampled_classes=50, examples_per_class=50, kappa=0, n_t=300, n_reps=1, max_class=None, projection=True, projection_dimension=5000, layer_nums=None, layer_types=None, verbose=True, cuda=True, seed=0):
device = torch.device(('cuda' if (torch.cuda.is_available() and cuda) else 'cpu'))
m... |
def gen_data_from_full_jsons(game, input_dir, min_frames_per_video):
all_data = []
for rl_agent_name in tqdm(os.listdir(input_dir)):
for level_json in tqdm(os.listdir(os.path.join(input_dir, rl_agent_name, 'json_metadata'))):
json_file = os.path.join(input_dir, rl_agent_name, 'json_metadata'... |
def test_smplify():
smplify_config = dict(mmcv.Config.fromfile('configs/smplify/smplify.py'))
device = (torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu'))
smplify_config['body_model'] = dict(type='SMPL', gender='neutral', num_betas=10, keypoint_src='smpl_45', keypoint_dst='smpl_45',... |
.async_execution
def async_add_chained(to, x, y, z):
return rpc.rpc_async(to, torch.add, args=(x, y)).then((lambda fut: (fut.wait() + z))) |
def main(args):
print(args)
problem_list = sorted(get_valid_problems(args.source))
print(f'number of problems = {len(problem_list)}')
prob_index = args.number
print(f'problem is {problem_list[prob_index]}')
assert (prob_index < len(problem_list))
if ((args.data == 'q') or (args.data == 'ques... |
def test_semgrex(corenlp_client):
pattern = '{word:wrote} >nsubj {}=subject >dobj {}=object'
matches = corenlp_client.semgrex(TEXT, pattern, to_words=True)
assert (matches == [{'text': 'wrote', 'begin': 1, 'end': 2, '$subject': {'text': 'Chris', 'begin': 0, 'end': 1}, '$object': {'text': 'sentence', 'begin'... |
def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__const_ns3Packet__gt___Const_ns3Address___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ptr< ns3::Packet const >, ns3::Address const &... |
class MNIST_L5_DRP05(nn.Module):
def __init__(self, dropout=0.3):
super(MNIST_L5_DRP05, self).__init__()
self.block = nn.Sequential(nn.Conv2d(1, 32, 2), nn.MaxPool2d(2), nn.ReLU(), nn.Conv2d(32, 64, 2), nn.MaxPool2d(2), nn.ReLU(), nn.Conv2d(64, 128, 2), nn.ReLU())
self.fc1 = nn.Linear((128 *... |
def default_steering_mind(boid):
acceleration = vec3()
for behavior in boid.behaviors:
acceleration += behavior.calculate(boid)
return acceleration |
class AST_translator():
def __init__(self, ast: ast_components.InternalFortranAst, source: str):
self.tables = ast.tables
self.top_level = None
self.globalsdfg = None
self.functions_and_subroutines = ast.functions_and_subroutines
self.name_mapping = ast_utils.NameMap()
... |
class ResNet(Backbone):
def __init__(self, stem, stages, num_classes=None, out_features=None, freeze_at=0):
super().__init__()
self.stem = stem
self.num_classes = num_classes
current_stride = self.stem.stride
self._out_feature_strides = {'stem': current_stride}
self._... |
class LabeledDummyDataProvider(DummyDataProvider):
def __init__(self, data_dim, num_classes=10, num_cases=7):
self.batch_range = [1]
self.batch_meta = {'num_vis': data_dim, 'label_names': [str(x) for x in range(num_classes)], 'data_in_rows': True}
self.num_cases = num_cases
self.num_... |
def register_Ns3VhtCapabilities_methods(root_module, cls):
cls.add_output_stream_operator()
cls.add_constructor([param('ns3::VhtCapabilities const &', 'arg0')])
cls.add_constructor([])
cls.add_method('DeserializeInformationField', 'uint8_t', [param('ns3::Buffer::Iterator', 'start'), param('uint8_t', 'le... |
def concatenate_backward(grad_inputs, inputs, input_shapes, outputs, output_shapes, axis=None):
dy = grad_inputs[0]
axis = (axis if (axis is not None) else (len(dy.shape) - 1))
ctx = nn.get_current_context()
df = ConcatenateDataGrad(ctx, axis=axis)
df.xshapes = input_shapes
dx0 = df(dy)
retu... |
def downsample_avg(in_channels, out_channels, kernel_size, stride=1, dilation=1, first_dilation=None, norm_layer=None):
norm_layer = (norm_layer or nn.BatchNorm2d)
avg_stride = (stride if (dilation == 1) else 1)
if ((stride == 1) and (dilation == 1)):
pool = nn.Identity()
else:
avg_pool_... |
class CLEVADialogueGenerationScenario(CLEVAScenario):
description = 'Dialogue generation task in CLEVA benchmark'
tags = ['dialogue_generation']
def task(self) -> str:
return 'dialogue_generation'
def get_instances(self, output_path: str) -> List[Instance]:
dataset = self.load_dataset(ou... |
class DerivativeOperator():
class DerivativeOperatorWithParameters():
def __init__(self, parameter_set):
self._parameter_set = parameter_set
def __call__(self, function):
return FDerivativeOperator(function, self._parameter_set)
def __repr__(self):
return ... |
class OutputInMiddleTest(BaseKerasFeatureNetworkTest):
def __init__(self, unit_test):
super().__init__(unit_test, experimental_exporter=True)
def create_networks(self):
inputs = layers.Input(shape=self.get_input_shapes()[0][1:])
x = layers.Conv2D(3, 4)(inputs)
x = layers.BatchNor... |
class TestSequenceBatch(object):
def sequences(self):
return [['a', 'b', 'b', 'c'], ['c'], []]
def vocab(self):
return SimpleVocab(['<unk>', 'a', 'b', 'c', '<start>', '<stop>'])
def test_from_sequences(self, sequences, vocab):
seq_batch = SequenceBatch.from_sequences(sequences, vocab... |
def test_multiple_inheritance_python_many_bases():
class MIMany14(m.BaseN1, m.BaseN2, m.BaseN3, m.BaseN4):
def __init__(self):
m.BaseN1.__init__(self, 1)
m.BaseN2.__init__(self, 2)
m.BaseN3.__init__(self, 3)
m.BaseN4.__init__(self, 4)
class MIMany58(m.Base... |
class OptimizerNames(ExplicitEnum):
ADAMW_HF = 'adamw_hf'
ADAMW_TORCH = 'adamw_torch'
ADAMW_APEX_FUSED = 'adamw_apex_fused'
ADAFACTOR = 'adafactor' |
class WideResnetBackbone(nn.Module):
def __init__(self, k=1, n=28, drop_rate=0):
super(WideResnetBackbone, self).__init__()
(self.k, self.n) = (k, n)
assert (((self.n - 4) % 6) == 0)
n_blocks = ((self.n - 4) // 6)
n_layers = ([16] + [((self.k * 16) * (2 ** i)) for i in range(... |
def get_hole_count(full_path):
hole_count = 0
file_lines = open(full_path, encoding='utf8', errors='backslashreplace').readlines()
for line in file_lines:
line = line.strip()
if (line and (not np.any([line.startswith(comment) for comment in comments]))):
hole_count += 1
retur... |
class SVHN(VisionDataset):
split_list = {'train': [' 'train_32x32.mat', 'e26dedcc434d2e4c54c9b2d4a06d8373'], 'val': [' 'train_32x32.mat', 'e26dedcc434d2e4c54c9b2d4a06d8373'], 'test': [' 'test_32x32.mat', 'eb5a983be6af1b164d9cef3'], 'extra': [' 'extra_32x32.mat', 'a93ce644f1a588dc4d68dda5feec44a7']}
def __init__... |
class _AtomicContext():
def __call__(self, bmodel_net: BModel, bmodel_context: BModelContext) -> Any:
self.bmodel_net = bmodel_net
self.bmodel_context = bmodel_context
return self
def __enter__(self):
pass
def __exit__(self, *exc_info):
self.bmodel_net = None
... |
class CCPM(BaseModel):
def __init__(self, linear_feature_columns, dnn_feature_columns, conv_kernel_width=(6, 5), conv_filters=(4, 4), dnn_hidden_units=(256,), l2_reg_linear=1e-05, l2_reg_embedding=1e-05, l2_reg_dnn=0, dnn_dropout=0, init_std=0.0001, seed=1024, task='binary', device='cpu', dnn_use_bn=False, dnn_acti... |
class CTRLPreTrainedModel():
def __init__(self, *args, **kwargs):
requires_pytorch(self)
def from_pretrained(self, *args, **kwargs):
requires_pytorch(self) |
def _create_attention_images_summary(final_context_state):
attention_images = final_context_state.alignment_history.stack()
attention_images = tf.expand_dims(tf.transpose(attention_images, [1, 2, 0]), (- 1))
attention_images *= 255
attention_summary = tf.summary.image('attention_images', attention_image... |
def __plot_validation__(curve, classes, area, area_method, colors, markers):
try:
from matplotlib import pyplot as plt
except Exception:
raise pycmPlotError(MATPLOTLIB_PLOT_LIBRARY_ERROR)
if (classes is None):
classes = curve.classes
if area:
curve.area(method=area_method... |
class RandomDataset(Dataset):
def __init__(self, length: int, sample_fn: Callable, size: Union[(Tuple, List)]):
self.length = length
self.sample_fn = sample_fn
self.size = size
def __len__(self) -> int:
return self.length
def __getitem__(self, idx: int) -> Tensor:
ret... |
class SubNodeFuser(object):
def __call__(self, graph):
nodes = graph.nodes
fused_nodes = []
for node in nodes:
if (len(node.parents) != 1):
continue
parent = node.get_only_parent()
if (len(parent.children) != 1):
continue
... |
def main(data_args: DataArguments, model_args: ModelArguments, training_args: TrainingArguments, outfile: str, ckpt_num: int, max_samples: int=None, prompt: Optional[str]=None, max_new_tokens: int=2048):
prompt_is_provided = (prompt is not None)
assert data_args.is_multimodal
print('loading model and data..... |
def get_hash(x, bucket_size):
if isinstance(x, np.ndarray):
ret = np.ndarray(x.shape, dtype='int64')
for i in range(x.size):
ret.put(i, (hashing(x.take(i)) % bucket_size))
else:
ret = (hashing(x) % bucket_size)
return ret |
def find_head(x):
x_parsed = nlp(x)
for tok in x_parsed:
if (tok.head == tok):
if (tok.lemma_ == u'-PRON-'):
return (tok.text, tok.text.lower())
return (tok.text, tok.lemma_) |
class ItemAutoRecModel(keras.Model):
def __init__(self, data, num_users, num_items, lr, hidden_neuron, l_w, name='ItemAutoRec', **kwargs):
super().__init__(name=name, **kwargs)
tf.random.set_seed(42)
self.data = data
self.num_users = num_users
self.num_items = num_items
... |
class SRS_SENet(nn.Module):
def __init__(self, block, num_blocks, num_classes=100):
super(SRS_SENet, self).__init__()
self.in_planes = 64
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.layer1 = self._make_layer... |
def check_port(port: int) -> None:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind(('127.0.0.1', port))
except socket.error as e:
if (e.errno == errno.EADDRINUSE):
raise ValueError(f'Port {port} is already in use')
else:
raise e |
class DWFormer(nn.Module):
def __init__(self, feadim, n_head, FFNdim, classnum):
super(DWFormer, self).__init__()
self.or1 = vanilla_transformer_block(feadim, n_head, FFNdim)
self.dt1 = DWFormerBlock(feadim, n_head, FFNdim)
self.dt2 = DWFormerBlock(feadim, n_head, FFNdim)
sel... |
.parametrize('n_rounds, n_unique_action, len_list, dim_context, reward_type, reward_structure, click_model, base_reward_function, is_factorizable, evaluation_policy_logit_, description', valid_input_of_calc_ground_truth_policy_value)
def test_calc_ground_truth_policy_value_using_valid_input_data(n_rounds, n_unique_acti... |
class SpecialHyperellipticQuotientRing(UniqueRepresentation, CommutativeAlgebra):
_p = None
def __init__(self, Q, R=None, invert_y=True):
if (R is None):
R = Q.base_ring()
x = PolynomialRing(R, 'xx').gen()
if is_EllipticCurve(Q):
E = Q
if ((E.a1() != 0... |
def __getattr__(name):
return _sub_module_deprecation(sub_package='signal', module='ltisys', private_modules=['_ltisys'], all=__all__, attribute=name) |
def seed_everything(seed=42):
os.environ['PYTHONHASHSEED'] = str(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed)
torch.backends.cudnn.deterministic = True |
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, in_channel, out_channel, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(in_channels=in_channel, out_channels=out_channel, kernel_size=1, stride=1, bias=False)
self.bn1 = nn.BatchNorm2d(nu... |
def init_config(config, default_config, name=None):
if (config is None):
config = default_config
else:
for k in default_config.keys():
if (k not in config.keys()):
config[k] = default_config[k]
if (name and config['PRINT_CONFIG']):
print(('\n%s Config:' % ... |
class DropboxGetItemMetadata(VirtualFunctionTool):
name = 'DropboxGetItemMetadata'
summary = "Get metadata of a file or folder in the user's Dropbox account."
parameters: List[ArgParameter] = [{'name': 'item_path', 'type': 'string', 'description': "The cloud file or folder path in the user's Dropbox account... |
def getFilenames():
result = []
root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..'))
assert os.path.exists(root_dir)
for dirname in ('models', 'examples'):
dirname = os.path.join(root_dir, dirname)
assert os.path.exists(dirname)
for (cwd, _, filen... |
def sig(epoch):
scale = 5
return (1 / (1 + np.exp((- ((epoch / scale) - (EP / (scale * 2))))))) |
class KRTToRCBijectionAbstract():
def __init__(self, tp_krt):
self.tp_krt = tp_krt
self.n = tp_krt.parent().cartan_type().classical().rank()
self.ret_rig_con = tp_krt.parent().rigged_configurations()(partition_list=([[]] * self.n))
self.ret_rig_con._set_mutable()
self.cur_dim... |
def adjust_lr(optimizer, init_lr, epoch, decay_rate=0.1, decay_epoch=30):
decay = (decay_rate ** (epoch // decay_epoch))
for param_group in optimizer.param_groups:
param_group['lr'] = (decay * init_lr)
lr = param_group['lr']
return lr |
class Node():
def __init__(self, bbox, frame_id, next_frame_id=(- 1)):
self.bbox = bbox
self.frame_id = frame_id
self.next_frame_id = next_frame_id |
def validate_context_and_answer_and_hops(example, pred, trace=None):
if (not dspy.evaluate.answer_exact_match(example, pred)):
return False
if (not dspy.evaluate.answer_passage_match(example, pred)):
return False
hops = ([example.question] + [outputs.query for (*_, outputs) in trace if ('que... |
class SysStdLogger(object):
def __init__(self, filename='terminal log.txt', stream=sys.stdout):
self.terminal = stream
self.log = open(filename, 'a')
self.log.write(''.join([time.strftime('%y-%m-%d %H:%M:%S'), '\n\n']))
def write(self, message):
if ('deprecated pixel format used'... |
def process_evaluation_result(outdir, filename):
callback = _get_callback('process_evaluation_result')
if callback:
callback.process_evaluation_result(outdir, filename) |
class MultiPassOptimizerTests(tf.test.TestCase):
def test_basic(self):
for aggregate_method in ['cumsum', 'storage']:
with tf.Graph().as_default(), tf.Session() as sess, log.verbose_level(2):
opt = tf.train.GradientDescentOptimizer(0.1)
mp_opt = MultiPassOptimizer... |
class VertexCube(VertexBase):
def __init__(self, x, nn=None, index=None):
super().__init__(x, nn=nn, index=index)
def connect(self, v):
if ((v is not self) and (v not in self.nn)):
self.nn.add(v)
v.nn.add(self)
def disconnect(self, v):
if (v in self.nn):
... |
def get_char_embed(word, model, device):
char_vec = model.get_char_embeds(word, device)
return char_vec |
def convert_tag_vocab(state_dict):
if state_dict['lower']:
raise AssertionError("Did not expect an NER vocab with 'lower' set to True")
items = state_dict['_id2unit'][len(VOCAB_PREFIX):]
items = [[[[x]]] for x in items]
vocab = CompositeVocab(data=items, lang=state_dict['lang'], idx=0, sep=None)... |
class GaussianTailProbabilityCalibrator(BasePostprocessor):
def __init__(self, running_statistics=True, window_size=6400):
self.running_statistics = running_statistics
self.window_size = window_size
if self.running_statistics:
self.avg_meter = RunningStatistic(AverageMeter, self.... |
def single_wall_mobility_trans_times_force_pycuda(r_vectors, force, eta, a, *args, **kwargs):
number_of_blobs = np.int32(len(r_vectors))
(threads_per_block, num_blocks) = set_number_of_threads_and_blocks(number_of_blobs)
L = kwargs.get('periodic_length', np.array([0.0, 0.0, 0.0]))
x = real(np.reshape(r_... |
def prepare_download():
for file_url in BLOB_NAMES:
for split in SPLIT_LIST:
if (split in file_url):
split_name = split
split_path = os.path.join(COMPRESSED_PATH, split_name)
if (not os.path.exists(split_path)):
os.makedirs(split_path)
if (not ... |
class GatewayObjStoreOperator(GatewayOperator):
def __init__(self, handle: str, region: str, bucket_name: str, bucket_region: str, input_queue: GatewayQueue, output_queue: GatewayQueue, error_event, error_queue: Queue, n_processes: Optional[int]=1, chunk_store: Optional[ChunkStore]=None):
super().__init__(h... |
class DeepAttention(nn.Module):
def __init__(self, dim):
super(DeepAttention, self).__init__()
self.linear_in = nn.Linear(dim, dim, bias=False)
self.linear_v = nn.Linear(dim, 1, bias=False)
self.linear_out = nn.Linear((dim * 2), dim, bias=False)
self.relu = nn.ReLU()
... |
def move_file(src: str, dest: str):
assert os.path.exists(src), f'source file {src} does not exist.'
if dest.startswith('gs://'):
(bucket_dest, filepath_dest) = split_gcs_bucket_and_filepath(dest)
gcs_bucket(bucket_dest).blob(filepath_dest).upload_from_filename(src)
else:
shutil.move... |
def make_plots(statistics_file):
print('\n Make Plots')
with open(statistics_file, 'r') as f:
stats = json.load(f)
output_folder = os.path.split(statistics_file)[0]
statNames = ['SSIM $\\uparrow$', 'LPIPS $\\downarrow$']
statTags = ['ssim', 'lpips']
statAggregation = [max, min]
latex... |
def get_token(doc, doc_id):
token = {'doc_id': [], 'sid': [], 'tid': [], 'token': [], 'token_with_ws': [], 'lemma': [], 'upos': [], 'xpos': [], 'tid_source': [], 'relation': []}
sid = 1
for x in doc.sents:
start_token_i = x[0].i
tid = 1
for word in x:
if (word.dep_ == 'RO... |
def test_axis_none():
record = ak.zip({'x': [1, None], 'y': [2, 3]})
assert (ak.fill_none(record, 0, axis=None).to_list() == [{'x': 1, 'y': 2}, {'x': 0, 'y': 3}]) |
class LinkCollector(object):
def __init__(self, session, search_scope):
self.search_scope = search_scope
self.session = session
def create(cls, session, options, suppress_no_index=False):
index_urls = ([options.index_url] + options.extra_index_urls)
if (options.no_index and (not ... |
def add_joints_to_image(img_demo, joints):
for joint in joints:
[i, j, sure] = joint
cv2.circle(img_demo, (i, j), radius=2, color=(255, 255, 255), thickness=2)
return img_demo |
def get_exact_set_match_metrics(examples, pred_list, verbose=False, vocabs=None, schema_graphs=None, clauses=None):
assert (len(examples) == len(pred_list))
esm = ExactSetMatch(vocabs)
metrics = {'select': 0.0, 'groupBy': 0.0, 'orderBy': 0.0, 'from': 0.0, 'where': 0.0, 'having': 0.0, 'limit': 0.0}
for (... |
_torch
_sentencepiece
_tokenizers
class M2M100TokenizerIntegrationTest(unittest.TestCase):
checkpoint_name = 'facebook/m2m100_418M'
src_text = ['In my opinion, there are two levels of response from the French government.', 'NSA Affair Emphasizes Complete Lack of Debate on Intelligence']
tgt_text = ['Selon m... |
def aggregate_graph(input_matrix: sparse.csr_matrix, labels: Optional[np.ndarray]=None, labels_row: Optional[np.ndarray]=None, labels_col: Optional[np.ndarray]=None) -> sparse.csr_matrix:
if (labels_row is not None):
membership_row = get_membership(labels_row)
else:
membership_row = get_membersh... |
_module
class ConvFCBBoxHead(BBoxHead):
def __init__(self, num_shared_convs=0, num_shared_fcs=0, num_cls_convs=0, num_cls_fcs=0, num_reg_convs=0, num_reg_fcs=0, conv_out_channels=256, fc_out_channels=1024, conv_cfg=None, norm_cfg=None, *args, **kwargs):
super(ConvFCBBoxHead, self).__init__(*args, **kwargs)
... |
def model_form(model, db_session=None, base_class=Form, only=None, exclude=None, field_args=None, converter=None, exclude_pk=True, exclude_fk=True, type_name=None):
if (not hasattr(model, '_sa_class_manager')):
raise TypeError('model must be a sqlalchemy mapped model')
type_name = (type_name or str((mod... |
def check_varenv(env: str='', args: dict=None):
if (args is None):
args = {}
env_val = environ.get(env)
if (env and (env_val is not None)):
args[env] = env_val
return args |
class CTRL(nn.Module):
def __init__(self, cfg):
super(CTRL, self).__init__()
print('ctrl/model/cross_task_relation.py --> class CTRL --> __init__()')
self.get_depth_prob = DepthProb(cfg)
self.prob_to_entropy = Prob2Entropy()
def forward(self, semseg_pred, srh_pred, depth_pred):
... |
class MethodStatement(ParametrizedStatement):
def __init__(self, test_case: tc.TestCase, generic_callable: gao.GenericMethod, callee: vr.VariableReference, args: (dict[(str, vr.VariableReference)] | None)=None):
super().__init__(test_case, generic_callable, args)
self._callee = callee
def access... |
(0.5)
_service.route('/add_more_to_order', methods=['POST'])
def add_more_to_order():
try:
entities = request.json['entities']
oid = int(entities['oid'])
value = int(entities['quantity'])
add_more_res = simple_db.add_more_to_order(oid, value)
if (add_more_res != 'ERROR'):
... |
class MultiStepLR_Restart(_LRScheduler):
def __init__(self, optimizer, milestones, restarts=None, weights=None, gamma=0.1, clear_state=False, last_epoch=(- 1)):
self.milestones = Counter(milestones)
self.gamma = gamma
self.clear_state = clear_state
self.restarts = (restarts if restar... |
def phone2prono(phones, rule_in, rule_out):
for (pattern, replacement) in zip(rule_in, rule_out):
phones = re.sub(pattern, replacement, phones)
prono = phones
return prono |
def test_state_transition_array():
sdfg = dace.SDFG('sta_test')
s0 = sdfg.add_state()
s1 = sdfg.add_state()
s2 = sdfg.add_state()
inp = s0.add_array('inp', [1], dace.float32)
A = s0.add_array('A', [1], dace.float32)
t = s0.add_tasklet('seta', {'a'}, {'b'}, 'b = a')
s0.add_edge(inp, None,... |
class ConcatDataset(data.Dataset):
def cumsum(sequence):
(r, s) = ([], 0)
for e in sequence:
l = len(e)
r.append((l + s))
s += l
return r
def __init__(self, datasets, **kwargs):
super(ConcatDataset, self).__init__()
assert (len(datasets... |
def save_config(cfg, path):
if is_main_process():
with open(path, 'w') as f:
f.write(cfg.dump()) |
def test_balanced_batch_generator_class_no_return_indices(data):
with pytest.raises(ValueError, match='needs to have an attribute'):
BalancedBatchGenerator(*data, sampler=ClusterCentroids(estimator=KMeans(n_init=1)), batch_size=10) |
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, in_planes, planes, stride=1):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, planes, kernel_size... |
_utils.test()
def test_multiple_ib_deeper_non_scalar():
N = 10
x = ti.field(float, shape=N, needs_dual=True)
y = ti.field(float, shape=N, needs_dual=True)
def compute_y():
for j in range(N):
for i in range(j):
y[j] += x[j]
for i in range(3):
... |
def _format(val: Any, output_format: str='standard', split: bool=False, errors: str='coarse') -> Any:
val = str(val)
result: Any = []
if (val in NULL_VALUES):
return [np.nan]
if (not validate_al_nipt(val)):
if (errors == 'raise'):
raise ValueError(f'Unable to parse value {val... |
class FiveCrop(object):
def __init__(self, size):
self.size = size
if isinstance(size, numbers.Number):
self.size = (int(size), int(size))
else:
assert (len(size) == 2), 'Please provide only two dimensions (h, w) for size.'
self.size = size
def __call_... |
def read_via_csv(path):
table = pd.read_csv(path)
table['image_name'] = table['filename'].apply(strip_ext)
table = table.drop('filename', axis=1)
table = table.loc[(table['region_count'] > 0)]
regions = table['region_shape_attributes']
x_coord = np.zeros(len(table), dtype=int)
y_coord = np.z... |
def init_cnn(m):
if (getattr(m, 'bias', None) is not None):
nn.init.constant_(m.bias, 0)
if isinstance(m, (nn.Conv1d, nn.Conv2d, nn.Linear)):
nn.init.kaiming_normal_(m.weight)
for l in m.children():
init_cnn(l) |
class HighResolutionNet(nn.Module):
def __init__(self, config, **kwargs):
extra = config.MODEL.EXTRA
super(HighResolutionNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1, bias=False)
self.bn1 = BatchNorm2d(64, momentum=BN_MOMENTUM)
self.c... |
def get_lable(image_path, is_grayscale=False):
image = imread(image_path, is_grayscale)
return (image / 255.0) |
def default_flist_reader(flist):
imlist = []
with open(flist, 'r') as rf:
for line in rf.readlines():
(impath, imlabel) = line.strip().split()
imlist.append((impath, int(imlabel)))
return imlist |
class Threshold(Module):
__constants__ = ['threshold', 'value', 'inplace']
threshold: float
value: float
inplace: bool
def __init__(self, threshold: float, value: float, inplace: bool=False) -> None:
super(Threshold, self).__init__()
self.threshold = threshold
self.value = va... |
def get_transform(opt):
transform_list = []
if (opt.resize_or_crop == 'resize_and_crop'):
osize = [opt.loadSizeH, opt.loadSizeW]
fsize = [opt.fineSizeH, opt.fineSizeW]
transform_list.append(transforms.Resize(osize, Image.BICUBIC))
transform_list.append(transforms.RandomCrop(fsize... |
def conv(in_channels, out_channels, kernel_size, bias=False, padding=1, stride=1):
return nn.Conv2d(in_channels, out_channels, kernel_size, padding=(kernel_size // 2), bias=bias, stride=stride) |
def set_dict_key(dict, path, value):
if (len(path) == 1):
dict[path[0]] = value
else:
set_dict_key(dict[path[0]], path[1:], value) |
class NoiseModeling(object):
def __init__(self, mean=0.0, var=0.1, pov=0.6):
self.var = var
self.mean = mean
self.pov = pov
def __call__(self, tensor):
sigma = random.uniform(0, (self.var ** self.pov))
noiseModel = ((torch.randn(tensor.size()).uniform_(0, 1.0) * sigma) + ... |
class AgentPair(AgentGroup):
def __init__(self, *agents, allow_duplicate_agents=False):
super().__init__(*agents, allow_duplicate_agents=allow_duplicate_agents)
assert (self.n == 2)
(self.a0, self.a1) = self.agents
if ((type(self.a0) is CoupledPlanningAgent) and (type(self.a1) is Cou... |
class TextEncoderTypes(Enum):
identity = 'identity'
transformer = 'transformer'
embedding = 'embedding' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.