code stringlengths 101 5.91M |
|---|
def gradients(ys, xs, grad_ys=None, checkpoints='collection', **kwargs):
if (not isinstance(ys, list)):
ys = [ys]
if (not isinstance(xs, list)):
xs = [xs]
bwd_ops = ge.get_backward_walk_ops([y.op for y in ys], inclusive=True)
debug_print('bwd_ops: %s', bwd_ops)
fwd_ops = ge.get_forwa... |
_module()
class TINLrUpdaterHook(LrUpdaterHook):
def __init__(self, min_lr, **kwargs):
self.min_lr = min_lr
super().__init__(**kwargs)
def get_warmup_lr(self, cur_iters):
if (self.warmup == 'linear'):
k = (((cur_iters / self.warmup_iters) * (1 - self.warmup_ratio)) + self.war... |
class ElasticCache(Elastic):
def __init__(self, index_name):
super(ElasticCache, self).__init__(index_name)
self.__num_docs = None
self.__num_fields = None
self.__doc_count = {}
self.__coll_length = {}
self.__avg_len = {}
self.__doc_length = {}
self.__... |
def test_scimodel_optimizer_exceptions(variable_x, variable_y, functional_fx, functional_gx):
xs = [variable_x, variable_y]
ys = [functional_fx, functional_gx]
with pytest.raises(ValueError):
assert isinstance(sn.SciModel(xs, ys, 'mse', 'to_fail'), sn.SciModel) |
def valid(model, iterator, criterion_onset_A, criterion_offset_A, criterion_mpe_A, criterion_velocity_A, criterion_onset_B, criterion_offset_B, criterion_mpe_B, criterion_velocity_B, weight_A, weight_B, device):
model.eval()
epoch_loss = 0
with torch.no_grad():
for (i, (input_spec, label_onset, labe... |
def load_yaml(path):
with open(path, 'r') as f:
model_config = yaml.load(f, Loader=yaml.FullLoader)
return model_config |
class SpecificSpanSparseRelClsDecoder(DecoderBase, ChunkPairsDecoderMixin):
def __init__(self, config: SpecificSpanSparseRelClsDecoderConfig):
super().__init__()
self.max_span_size = config.max_span_size
self.max_size_id = config.max_size_id
self.neg_sampling_rate = config.neg_sampli... |
class Attacker():
def __init__(self, args, model_tgt, tokenizer_tgt, model_mlm, tokenizer_mlm, use_bpe, threshold_pred_score) -> None:
self.args = args
self.model_tgt = model_tgt
self.tokenizer_tgt = tokenizer_tgt
self.model_mlm = model_mlm
self.tokenizer_mlm = tokenizer_mlm
... |
class BaseMultilayerPerceptron(BaseEstimator, metaclass=ABCMeta):
_parameter_constraints: dict = {'hidden_layer_sizes': ['array-like', Interval(Integral, 1, None, closed='left')], 'activation': [StrOptions({'identity', 'logistic', 'tanh', 'relu'})], 'solver': [StrOptions({'lbfgs', 'sgd', 'adam'})], 'alpha': [Interv... |
def build_from_cfg(cfg, registry, default_args=None):
assert (isinstance(cfg, dict) and ('type' in cfg))
assert (isinstance(default_args, dict) or (default_args is None))
args = cfg.copy()
obj_type = args.pop('type')
if mmcv.is_str(obj_type):
obj_cls = registry.get(obj_type)
if (obj_... |
def Function(name, *sig):
sig = _get_args(sig)
if z3_debug():
_z3_assert((len(sig) > 0), 'At least two arguments expected')
arity = (len(sig) - 1)
rng = sig[arity]
if z3_debug():
_z3_assert(is_sort(rng), 'Z3 sort expected')
dom = (Sort * arity)()
for i in range(arity):
... |
_if_win32()
class RendezvousEnvTest(TestCase):
_on_connect_failures
_nccl()
def test_common_errors(self):
if (torch.cuda.device_count() == 0):
raise unittest.SkipTest('No GPUs available, skipping test')
vars = {'WORLD_SIZE': '1', 'RANK': '0', 'MASTER_ADDR': '127.0.0.1', 'MASTER_P... |
def initialize(config):
random.seed(config.random_seed)
population_pickle = os.path.join(os.path.dirname(__file__), 'population.pkl.gz')
popu = pickle.load(gzip.open(population_pickle, 'rb'))
alive = []
for (num, person) in popu.items():
person['num'] = num
person['months_in_prison']... |
class Cluster():
def __init__(self, cloud_config, cluster_config, no_start=False, no_delete=False, containers=None):
self._cloud_config = cloud_config
self._cluster_config = cluster_config
self._cluster_cmd = 'gcloud beta container --project {} clusters --zone {}'.format(self._cloud_config.p... |
class docInternalTypeSub(supermod.docInternalType):
def __init__(self, para=None, sect1=None, mixedclass_=None, content_=None):
supermod.docInternalType.__init__(self, mixedclass_, content_) |
def custom(tensors_in: list, shape_func, op_name: str, out_dtypes: list, out_names: list=None, params: dict=None):
out_shapes = shape_func(tensors_in)
tensors_out = []
for (i, out_dtype) in enumerate(out_dtypes):
tensor_out = Tensor(out_shapes[i], dtype=out_dtype, name=(out_names[i] if out_names els... |
def add_frame(img_in: np.ndarray, color: Tuple[(int, int, int)]) -> np.ndarray:
img = img_in.copy()
w = int(np.round((0.01 * img.shape[1])))
pad_lr = np.tile(np.uint8(color).reshape(1, 1, 3), (img.shape[0], w, 1))
img = np.concatenate([pad_lr, img, pad_lr], axis=1)
pad_tb = np.tile(np.uint8(color).r... |
def transform():
return torchvision.transforms.Compose([_convert_image_to_rgb, torchvision.transforms.ToTensor(), torchvision.transforms.Normalize((0., 0.4578275, 0.), (0., 0., 0.))]) |
def cudnn_LSTM(model, input_blob, initial_states, dim_in, dim_out, scope, recurrent_params=None, input_params=None, num_layers=1, return_params=False):
with core.NameScope(scope):
weight_params = GetLSTMParamNames()['weights']
bias_params = GetLSTMParamNames()['biases']
input_weight_size = (... |
def LF_negex_definite_negation_left(c):
possible_terms = [x['term'].split(' ') for x in negex.dictionary['definite'] if (x['direction'] == 'forward')]
longest = len(max(possible_terms, key=len))
left_window_length = (longest + 2)
v = negex.is_negated(c, 'definite', 'left', left_window_length)
return... |
def secondsToStr(elapsed=None):
if (elapsed is None):
return strftime('%Y-%m-%d %H:%M:%S', localtime())
else:
return str(timedelta(seconds=elapsed)) |
class Sdma(Dma):
def __init__(self, core_id, writer, sheet_name):
super().__init__(core_id, writer)
self.sheet_name = ((sheet_name + '_') + str(core_id))
def load(self, reg_info_file, sdma_layer_map):
super().load(reg_info_file, sdma_layer_map)
new_reg_list = []
for reg_d... |
def GenerateSM80_TensorOp_1688_trmm(manifest, cuda_version):
if (not CudaToolkitVersionSatisfies(cuda_version, 11, 0)):
return
layouts = [(LayoutType.ColumnMajor, LayoutType.ColumnMajor, LayoutType.ColumnMajor), (LayoutType.RowMajor, LayoutType.ColumnMajor, LayoutType.ColumnMajor)]
side_modes = [Sid... |
class PySAGClassifier(BaseClassifier):
def _get_loss(self, loss):
losses = {'modified_huber': ModifiedHuber(), 'smooth_hinge': SmoothHinge(self.gamma), 'squared_hinge': SquaredHinge(1.0), 'log': Log(), 'squared': SquaredLoss()}
return losses[loss]
def _get_penalty(self, penalty):
if isin... |
def load_dataset():
global train_data, dev_data, test_data, trfreq
trace('load train')
for line in open(args.train_file):
(h, r, t) = parse_line(line)
train_data.append((h, r, t))
trfreq[r] += 1
train_data = list(train_data)
for r in trfreq:
trfreq[r] = (args.train_si... |
class Mlp(nn.Module):
def __init__(self, input_size=784, hidden_sizes=None, n_classes=10, bias=True, dropout=False):
super().__init__()
if (hidden_sizes is None):
hidden_sizes = [512, 256]
self.dropout = dropout
self.input_size = input_size
self.hidden_layers = nn... |
class MobileConfigurationPath(ConfigurationPath):
def __init__(self, mobile: MobileBase, path_points: List[List[float]]):
self._mobile = mobile
self._path_points = path_points
self._drawing_handle = None
self._path_done = False
self.i_path = (- 1)
self.inter_done = Tr... |
.parametrize('outside_of,expected_types', [(('tests.fixtures.types.outside.Foo',), ('builtins.int', 'builtins.str', 'builtins.bool', 'builtins.float', 'builtins.bytes', 'builtins.complex', 'builtins.list', 'builtins.set', 'builtins.dict', 'builtins.tuple', 'builtins.object')), (('tests.fixtures.types.outside.Bar',), ('... |
def main():
fusiongraph = FusionGraphModel(graph, gpu_id, config['graph'], config['data'], config['train']['M'], config['train']['d'], config['train']['bn_decay'])
lightning_data = LightningData(train_set, val_set, test_set)
lightning_model = LightningModel(scaler, fusiongraph)
trainer = Trainer(logger=... |
def array_ufunc(ufunc, method: str, inputs, kwargs: dict[(str, Any)]):
if ((method != '__call__') or (len(inputs) == 0) or ('out' in kwargs)):
return NotImplemented
behavior = behavior_of(*inputs)
attrs = attrs_of(*inputs)
backend = backend_of(*inputs, coerce_to_common=True)
inputs = _array_... |
class InsertUsbInComputer(Task):
def init_task(self) -> None:
success_sensor = ProximitySensor('success')
usb = Shape('usb')
usb_tip = Shape('tip')
self.register_graspable_objects([usb])
self.register_success_conditions([DetectedCondition(usb_tip, success_sensor)])
def in... |
class LogitTransform(nn.Module):
def __init__(self, alpha=_DEFAULT_ALPHA):
nn.Module.__init__(self)
self.alpha = alpha
def forward(self, x, logpx=None, reverse=False):
if reverse:
return _sigmoid(x, logpx, self.alpha)
else:
return _logit(x, logpx, self.alp... |
def color_weisfeiler_lehman(adjacency: Union[(sparse.csr_matrix, np.ndarray)], max_iter: int=(- 1)) -> np.ndarray:
adjacency = check_format(adjacency, allow_empty=True)
check_square(adjacency)
n_nodes = adjacency.shape[0]
if ((max_iter < 0) or (max_iter > n_nodes)):
max_iter = n_nodes
labels... |
class Leon(Benchmark):
def __init__(self, dimensions=2):
Benchmark.__init__(self, dimensions)
self._bounds = list(zip(([(- 1.2)] * self.N), ([1.2] * self.N)))
self.global_optimum = [[1 for _ in range(self.N)]]
self.fglob = 0.0
def fun(self, x, *args):
self.nfev += 1
... |
class _OSA_module(nn.Module):
def __init__(self, in_ch, stage_ch, concat_ch, layer_per_block, module_name, SE=False, identity=False, depthwise=False, dcn_config={}):
super(_OSA_module, self).__init__()
self.identity = identity
self.depthwise = depthwise
self.isReduced = False
... |
def finalize_compiler_options(cmd):
dist = cmd.distribution
defaults = {'fcompiler': 'gnu95', 'f2py': default_f2py(), 'compiler': None, 'f77exec': None, 'f90exec': None}
for option in defaults:
if (getattr(cmd, option) == None):
for c in dist.commands:
other_cmd = dist.ge... |
.operations('success')
.openapi_version('3.0')
def test_server_timeout(cli, schema_url, service, mocker):
mocker.patch('schemathesis.cli.output.default.wait_for_report_handler', return_value=events.Timeout())
result = cli.run(schema_url, 'my-api', f'--schemathesis-io-token={service.token}', f'--schemathesis-io-... |
class Agent():
def __init__(self, world_size):
self.ob_rrefs = []
self.agent_rref = RRef(self)
self.rewards = {}
self.saved_log_probs = {}
self.policy = Policy()
self.optimizer = optim.Adam(self.policy.parameters(), lr=0.01)
self.eps = np.finfo(np.float32).eps... |
def compute_scores(Y, Yhat):
Y = Y.drop(Y.index[0:60])
Yhat = Yhat.drop(Yhat.index[0:60])
return [accuracy_score(Y, Yhat), f1_score(Y, Yhat), precision_score(Y, Yhat), recall_score(Y, Yhat)] |
def test_ResourceReservationProtocol_schedule():
tl = Timeline()
n1 = FakeNode('n1', tl)
for _ in range(1000):
s_time = random.randint(1000)
memo_size = (random.randint(25) + 1)
reservation = Reservation('', '', s_time, ((s_time + 1) + random.randint(200)), memo_size, 0.9)
if... |
def compute_files(user1, user2, file_list, dir_pre, start_num):
match_total = 0
test_total = 0
gold_total = 0
for fi in file_list:
file1 = ((((dir_pre + user1) + '/') + fi) + '.txt')
file2 = ((((dir_pre + user2) + '/') + fi) + '.txt')
if (not os.path.exists(file1)):
p... |
def radixpass(a, b, r, s, n, k):
c = array('i', ([0] * (k + 1)))
for i in range(n):
c[r[(a[i] + s)]] += 1
somme = 0
for i in range((k + 1)):
(freq, c[i]) = (c[i], somme)
somme += freq
for i in range(n):
b[c[r[(a[i] + s)]]] = a[i]
c[r[(a[i] + s)]] += 1 |
class XLMTokenizer(PreTrainedTokenizer):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
def __init__(self, vocab_file, merges_fi... |
class RandomAgent(Expert):
def __init__(self, action_scale=0.1, action_space_dim=2):
self.action_scale = action_scale
self.action_space_dim = action_space_dim
self.counter = 0
def get_action(self, obs):
action = (np.random.uniform((- 1), 1, self.action_space_dim) * self.action_sc... |
class LPDictionary(LPAbstractDictionary):
def __init__(self, A, b, c, objective_value, basic_variables, nonbasic_variables, objective_name):
super().__init__()
A = copy(A)
b = copy(b)
c = copy(c)
B = vector(basic_variables)
N = vector(nonbasic_variables)
self.... |
def test_detect_first():
faces = RetinaFace.extract_faces(img_path='tests/dataset/img11.jpg')
num_black_pixels = np.sum(np.all((faces[0] == 0), axis=2))
assert (num_black_pixels > THRESHOLD)
logger.info(' Disabled align_first test for single face photo done') |
class TestL2XText(unittest.TestCase):
def setUp(self) -> None:
categories = ['alt.atheism', 'soc.religion.christian']
newsgroups_train = fetch_20newsgroups(subset='train', categories=categories)
newsgroups_test = fetch_20newsgroups(subset='test', categories=categories)
self.newsgroup... |
def valid_aggregation(state: Dict) -> bool:
aggr1 = json.loads(state['aggr1'])
aggr2 = json.loads(state['aggr2'])
current = json.loads(state['current'])
if ((set(aggr1.keys()) | set(aggr2.keys())) != set(current.keys())):
return False
for country in current.keys():
aggr1_freq = (aggr... |
def default_loader(filename):
if filename.endswith('.npy'):
return numpy.load(filename).view(ndarray)
elif filename.endswith('.npz'):
return numpy.load(filename)
else:
return tv_default_loader(filename) |
class MixtureSameFamily(Distribution):
arg_constraints = {}
has_rsample = False
def __init__(self, mixture_distribution, component_distribution, validate_args=None):
self._mixture_distribution = mixture_distribution
self._component_distribution = component_distribution
if (not isinst... |
class Mish_ResNet(nn.Module):
def __init__(self, block, num_blocks, num_classes=100):
super(Mish_ResNet, 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_l... |
def pre_caption(caption, max_words=50):
caption = re.sub('([.!\\"()*#:;~])', ' ', caption.lower())
caption = re.sub('\\s{2,}', ' ', caption)
caption = caption.rstrip('\n')
caption = caption.strip(' ')
caption_words = caption.split(' ')
if (len(caption_words) > max_words):
caption = ' '.j... |
class GapAware(GapAwareBase):
def __init__(self, optimizer, big_gamma=0.999, epsilon=1e-08, from_grad=True):
super().__init__(optimizer)
self.big_gamma = big_gamma
self.running_avg_step = init_running_avg_step(optimizer)
self.epsilon = epsilon
for pg in self.optimizer.param_g... |
def skyline_input_provider(batch_size=64):
vocab_size = 32000
src_len = 25
tgt_len = 25
device = torch.device('cuda')
src = torch.randint(low=0, high=vocab_size, size=(src_len, batch_size), dtype=torch.int64, device=device)
tgt = torch.randint(low=0, high=vocab_size, size=(tgt_len, batch_size), ... |
def _convert_config(config):
config_list = []
for (k, v) in config.items():
if (v.lower() == 'true'):
config_list.append(('--' + k))
elif (v.lower() != 'false'):
config_list.extend(([('--' + k)] + v.split(' ')))
return config_list |
class TSStr(object):
thisown = _swig_property((lambda x: x.this.own()), (lambda x, v: x.this.own(v)), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
_snap.TSStr_swiginit(self, _snap.new_TSStr(*args))
__swig_destroy__ = _snap.delete_TSStr
def CStr(self, *args):
... |
_model
def tf_efficientnet_b8_ap(pretrained=False, **kwargs):
kwargs['bn_eps'] = BN_EPS_TF_DEFAULT
kwargs['pad_type'] = 'same'
model = _gen_efficientnet('tf_efficientnet_b8_ap', channel_multiplier=2.2, depth_multiplier=3.6, pretrained=pretrained, **kwargs)
return model |
def roi_sampling(x, bbx, idx, roi_size, interpolation='bilinear', padding='border', valid_mask=False):
return ROISampling.apply(x, bbx, idx, roi_size, interpolation, padding, valid_mask) |
def test_combine(tmp_path):
SHARDS = ('train', 'dev', 'test')
for (s_num, shard) in enumerate(SHARDS):
t1_json = (tmp_path / ('en_t1.%s.json' % shard))
write_temp_file(t1_json, '\n\n'.join(([EN_TRAIN_BIO] * (s_num + 1))))
t2_json = (tmp_path / ('en_t2.%s.json' % shard))
write_tem... |
class bmodel_inference(common_inference):
def __init__(self, args):
super().__init__(args)
self.args = args
pyruntime = 'pyruntime_'
self.first = False
self.is_cv18xx = False
if self.args.model_file.endswith('.bmodel'):
pyruntime = (pyruntime + 'bm')
... |
class Partition2(nn.Module):
LAYER_SCOPES = ['T5ForConditionalGeneration/T5Stack[encoder]/ModuleList[block]/T5Block[6]', 'T5ForConditionalGeneration/T5Stack[encoder]/ModuleList[block]/T5Block[7]', 'T5ForConditionalGeneration/T5Stack[encoder]/ModuleList[block]/T5Block[8]']
TENSORS = []
def __init__(self, lay... |
class ResNetBottleneckBlock(nn.Module):
n_hidden: int
strides: Tuple[(int, int)] = (1, 1)
expansion: int = 4
groups: int = 1
base_width: int = 64
activation: Callable = nn.relu
conv_block_cls: ModuleDef = ConvBlock
skip_cls: ModuleDef = ResNetSkipConnection
def __call__(self, x):
... |
class SkewNormal(ReferenceDistribution):
def __init__(self, *, a):
super().__init__(a=a)
def _support(self, a):
return ((- mp.inf), mp.inf)
def _pdf(self, x, a):
return ((2 * mp.npdf(x)) * mp.ncdf((a * x))) |
def SimpleConv3x3lBlock(a, b, c, s):
return nn.Sequential(nn.Conv2d(a, c, 3, padding=1, bias=False), nn.BatchNorm2d(c), nn.ReLU(inplace=True), nn.Conv2d(c, c, 3, padding=1, stride=s, bias=False), nn.BatchNorm2d(c), nn.ReLU(inplace=True)) |
class PlayerState(object):
def __init__(self, position, orientation, held_object=None):
self.position = tuple(position)
self.orientation = tuple(orientation)
self.held_object = held_object
assert (self.orientation in Direction.ALL_DIRECTIONS)
if (self.held_object is not None)... |
def load_data(seq_path, struct_path, alphabet, baselines=False):
pdb_index = {}
for path in struct_path:
pid = os.path.basename(path)[:7]
pdb_index[pid] = path
with open(seq_path, 'rb') as f:
(names, sequences) = fasta.parse(f)
names = [name.split()[0].decode('utf-8') for name in... |
def _self_bleu(completions: List[Sequence]) -> float:
completion_sequences: List[str] = [completion.text.strip() for completion in completions if completion.text.strip()]
if (len(completion_sequences) <= 1):
return 0
scores = []
for i in range(len(completion_sequences)):
hypothesis = com... |
def test_datetime64():
array = ak.Array([[np.datetime64(1, 'D'), np.datetime64(10, 'D')]])
assert ((array == np.datetime64(10, 'D')).to_list() == [[False, True]]) |
def remove_short_notes(notes: List[Note], label: Label, min_char_count: int=0, **kwargs) -> List[Note]:
new_notes: List[Note] = []
for note in notes:
text: str = str(note.event.value)
if (len(text) >= min_char_count):
new_notes.append(note)
return new_notes |
def loop(model, cond_blob, external_blobs, loop_model, cond_model=None):
add_while_op(model.net, cond_blob, external_blobs, loop_model.net, (cond_model.net if cond_model else None)) |
class PythonParameter(message.Message):
__metaclass__ = reflection.GeneratedProtocolMessageType
DESCRIPTOR = _PYTHONPARAMETER |
def run_train_distributed(args: typing.Optional[argparse.Namespace]=None) -> None:
if (args is None):
base_parser = create_base_parser()
distributed_parser = create_distributed_parser(base_parser)
distributed_train_parser = create_train_parser(distributed_parser)
args = distributed_t... |
class EmitSparseGemmInstance():
def __init__(self, operation_suffix=''):
self.operation_suffix = operation_suffix
self.includes = []
self.gemm_template = '\n // Gemm operator ${operation_name}\n using Operation_${operation_name} = cutlass::gemm::device::SparseGemm<\n ${element_a}, ${lay... |
class _MemberSpec(object):
def __init__(self, name='', data_type='', container=0):
self.name = name
self.data_type = data_type
self.container = container
def set_name(self, name):
self.name = name
def get_name(self):
return self.name
def set_data_type(self, data_t... |
def test_compare_ne():
a_raw = torch.tensor([2.0, 2.0, 2.0])
b_raw = torch.tensor([1.0, 2.0, 3.0])
feature_dim = Dim(3)
a = Tensor(name='a', raw_tensor=a_raw, dims=[feature_dim], dtype='float32')
b = Tensor(name='b', raw_tensor=b_raw, dims=[feature_dim], dtype='float32')
result = (a != b)
re... |
def roman_to_int(roman_string):
NUMERALS_SET = set(list(zip(*NUMERAL_MAP))[1])
roman_string = roman_string.upper()
if (len((set(list(roman_string.upper())) - NUMERALS_SET)) != 0):
raise ValueError(f'{roman_string} does not seem to be a roman numeral')
i = result = 0
for (integer, numeral) in... |
def main(in_directory, out_directory, short_name):
phrases = get_tokenized_phrases(in_directory)
process_utils.write_list(os.path.join(out_directory, ('%s.train.json' % short_name)), phrases) |
def test_std():
assert (ak.std(array, axis=None) == pytest.approx(3.))
assert ak.almost_equal(ak.std(array, axis=None, keepdims=True, mask_identity=False), ak.to_regular([[3.]]))
assert ak.almost_equal(ak.std(array, axis=None, keepdims=True, mask_identity=True), ak.to_regular(ak.Array([[3.]]).mask[[[True]]]... |
def register_quantized_custom_module_mapping(float_custom_module_class, quantized_custom_module_class):
assert hasattr(quantized_custom_module_class, 'from_observed'), ('from_observed' + ' must be defined in quantized custom module class')
QUANTIZED_CUSTOM_MODULE_CLASS_MAPPINGS[float_custom_module_class] = quan... |
class SubArray(np.ndarray):
def __new__(cls, arr, info={}):
x = np.asanyarray(arr).view(cls)
x.info = info.copy()
return x
def __array_finalize__(self, obj):
if callable(getattr(super(SubArray, self), '__array_finalize__', None)):
super(SubArray, self).__array_finaliz... |
class Stochastic(Benchmark):
def __init__(self, dimensions=2):
Benchmark.__init__(self, dimensions)
self._bounds = list(zip(([(- 5.0)] * self.N), ([5.0] * self.N)))
self.global_optimum = [[(1.0 / _) for _ in range(1, (self.N + 1))]]
self.fglob = 0.0
self.change_dimensionality... |
def got() -> operations.GraphOfOperations:
operations_graph = operations.GraphOfOperations()
plans = operations.Generate(1, 1)
operations_graph.append_operation(plans)
solved_subsets = []
for i in range(1, 5):
list_id = f'List {i}'
sub_list = operations.Selector((lambda thoughts, lis... |
def enumerate_subgraph(G, k=3, progress_bar=False, node_anchored=False):
ps = (np.arange(1.0, 0.0, ((- 1.0) / (k + 1))) ** 1.5)
motif_counts = defaultdict(list)
for node in (tqdm(G.nodes) if progress_bar else G.nodes):
sg = set()
sg.add(node)
v_ext = set()
neighbors = [nbr fo... |
def setup_ddp() -> None:
if (('RANK' in os.environ) and ('WORLD_SIZE' in os.environ)):
rank = int(os.environ['RANK'])
world_size = int(os.environ['WORLD_SIZE'])
gpu = int(os.environ(['LOCAL_RANK']))
torch.cuda.set_device(gpu)
dist.init_process_group('nccl', init_method='env:/... |
def random_word_no_prob(text, label, label_map, tokenizer):
text = text.replace('\n', '').split(' ')
orig_to_map_label = []
orig_to_map_token = []
assert (len(text) == len(label_map))
for i in range(0, len(text)):
orig_token = text[i]
orig_label_map = label_map[i]
tokens = to... |
def fixDelex(filename, data, data2, idx, idx_acts):
try:
turn = data2[filename.strip('.json')][str(idx_acts)]
except:
return data
if ((not isinstance(turn, bytes)) and (not isinstance(turn, str))):
for (k, act) in turn.items():
if ('Attraction' in k):
if (... |
def main():
args = parse_args()
args.out_dir.mkdir(exist_ok=True)
logging.basicConfig(stream=sys.stdout, level=(logging.ERROR if args.quiet else logging.INFO), format='%(levelname)-8s %(message)s')
logging.info(f'''Using arguments:
{pprint.pformat(vars(args))}''')
logging.info('Loading names...')
... |
class FasterRCNN(nn.Module):
def __init__(self, extractor, rpn, head, loc_normalize_mean=(0.0, 0.0, 0.0, 0.0), loc_normalize_std=(0.1, 0.1, 0.1, 0.1)):
super(FasterRCNN, self).__init__()
self.extractor = extractor
self.rpn = rpn
self.head = head
self.loc_normalize_mean = loc_... |
def get_files_list(base_dataset_dir, images_folder_name, annotations_folder_name, filename):
images_dir = os.path.join(base_dataset_dir, images_folder_name)
annotations_dir = os.path.join(base_dataset_dir, annotations_folder_name)
file = open(filename, 'r')
images_filename_list = [line for line in file]... |
def test_tags():
labels = ['Siren', 'Laughter', 'Engine']
confidence = np.array([1.0, 0.0, 1.0])
tags = annotations.Tags(labels, 'open', confidence)
assert (tags.labels == labels)
assert np.allclose(tags.confidence, confidence)
bad_labels = ['Siren', 'Laughter', 5]
pytest.raises(TypeError, a... |
def generate_train_validation_list(data_path, train_size=0.8):
file_list = glob.glob((data_path + '*.wav'))
file_list = np.array(file_list)
(train, validation) = train_test_split(filenames, train_size=train_size) |
def process_k(func):
def wrap(self, recs: SparkDataFrame, k: IntOrList, *args):
if isinstance(k, int):
k_list = [k]
else:
k_list = k
res = func(self, recs, k_list, *args)
if isinstance(k, int):
return res[k]
return res
return wrap |
def infer_abbr(class_type):
if (not inspect.isclass(class_type)):
raise TypeError(f'class_type must be a type, but got {type(class_type)}')
if hasattr(class_type, '_abbr_'):
return class_type._abbr_
if issubclass(class_type, _InstanceNorm):
return 'in'
elif issubclass(class_type,... |
def check_time(timer_id):
if (timer_id not in _g_timers):
_g_timers[timer_id] = Timer()
return 0
else:
return _g_timers[timer_id].since_last_check() |
def generate_onion_service_keys(tor_cmd, n):
with tempfile.TemporaryDirectory(prefix='tornettools-hs-keygen-') as dir_name:
config = {'DisableNetwork': '1', 'DataDirectory': dir_name, 'ControlPort': '9030'}
tor_process = stem.process.launch_tor_with_config(config, tor_cmd=tor_cmd, init_msg_handler=l... |
class PoolingEncoderTest(tf.test.TestCase):
def setUp(self):
super(PoolingEncoderTest, self).setUp()
self.batch_size = 4
self.sequence_length = 16
self.input_depth = 10
self.mode = tf.contrib.learn.ModeKeys.TRAIN
def _test_with_params(self, params):
inputs = tf.ra... |
def check_compatibility(version, name):
if (version[0] > VERSION_COMPATIBLE[0]):
raise UnsupportedWheel("{}'s Wheel-Version ({}) is not compatible with this version of pip".format(name, '.'.join(map(str, version))))
elif (version > VERSION_COMPATIBLE):
logger.warning('Installing from a newer Whe... |
def store_token_address(token_dict, outname, topk=1000):
sorted_tokens = {k: v for (k, v) in sorted(token_dict.items(), key=(lambda item: item[1]), reverse=True)}
ctr = 0
with open(outname, 'w') as csv_file:
csv_writer = csv.writer(csv_file, delimiter=',')
csv_writer.writerow(['token_address... |
def veri_test_parser(line):
label = int(line.split(' ')[0])
enroll_filename = line.split(' ')[1]
test_filename = line.split(' ')[2].replace('\n', '')
return (label, enroll_filename, test_filename) |
def read_decode_depth(depth_dir):
depth = tf.py_function(func=read_depth_png_tf, inp=[depth_dir], Tout=tf.float32)
return depth |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.