code stringlengths 101 5.91M |
|---|
def _shuffle_and_restrict(examples: List[InputExample], num_examples: int, seed: int=42) -> List[InputExample]:
if (0 < num_examples < len(examples)):
random.Random(seed).shuffle(examples)
examples = examples[:num_examples]
return examples |
class DetectionEvaluator(object):
def __init__(self):
pass
def eval(self, pred, golden):
total_mentions = 0.0
pred_error = 0.0
pred_correct = 0.0
for sent_id in golden:
total_mentions += len(golden[sent_id])
if (not (sent_id in pred)):
... |
def stop_afl(cargs):
rv = True
if (not cargs.afl_fuzzing_dir):
print('[*] Must set --afl-fuzzing-dir')
return False
if (not is_dir(cargs.afl_fuzzing_dir)):
print(("[*] Doesn't look like AFL fuzzing directory '%s' exists." % cargs.afl_fuzzing_dir))
return False
if os.path.... |
def Convolutional_Block(inputs, shortcut, num_filters, name, is_training):
with tf.variable_scope(((('conv_block_' + str(num_filters)) + '_') + name)):
for i in range(2):
with tf.variable_scope(('conv1d_%s' % str(i))):
filter_shape = [3, inputs.get_shape()[2], num_filters]
... |
class EisensteinSubmodule_g1_Q(EisensteinSubmodule_gH_Q):
def _parameters_character(self):
return self.level() |
class MultiAgentActionSpace(list):
def __init__(self, ma_space):
for x in ma_space:
assert isinstance(x, gym.spaces.space.Space)
super(MultiAgentActionSpace, self).__init__(ma_space)
def sample(self):
return [sa_space.sample() for sa_space in self] |
class DebertaForMaskedLM(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def update_learning_rate(optimizer, new_lr, param_group=None):
if (param_group is None):
groups = range(len(optimizer.param_groups))
else:
groups = param_group
for i in groups:
old_lr = optimizer.param_groups[i]['lr']
if (new_lr != old_lr):
optimizer.param_groups[... |
def main():
args = parse_args()
if (args is None):
exit()
with tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) as sess:
gan = GDWCT(sess, args)
gan.build_model()
show_all_variables()
if (args.phase == 'train'):
gan.train()
print(' ... |
def export_2d_annotation(root_path, info_path, version):
warning.warn('DeprecationWarning: 2D annotations are not used on the Lyft dataset. The function export_2d_annotation will be deprecated.')
camera_types = ['CAM_FRONT', 'CAM_FRONT_RIGHT', 'CAM_FRONT_LEFT', 'CAM_BACK', 'CAM_BACK_LEFT', 'CAM_BACK_RIGHT']
... |
def write_metric(node_name, task_name, metric_name, metric, round_number):
get_writer()
writer.add_scalar(f'{node_name}/{task_name}/{metric_name}', metric, round_number) |
def CuspForms(group=1, weight=2, base_ring=None, use_cache=True, prec=defaults.DEFAULT_PRECISION):
return ModularForms(group, weight, base_ring, use_cache=use_cache, prec=prec).cuspidal_submodule() |
class LogCaptureHandler(logging.Handler):
def __init__(self, log_capture):
self.records = log_capture.records
logging.Handler.__init__(self)
def emit(self, record):
self.records.append(record) |
class StateOKDataset(PretrainDataset):
def __init__(self, epoch: int, index_path: Path, img_transform: Compose, lang_dropout: Optional[float]=None, stream: bool=False, prefix: Optional[Path]=None, no_lang: bool=False, is_val: bool=False, do_retry: bool=True, n_retries: int=3) -> None:
super().__init__()
... |
def test_floordiv():
value = 7
proxy = tt.ObjectProxy(value)
assert ((value // 2) == (proxy // 2))
assert (int in tt.UsageTraceNode.from_proxy(proxy).children['__floordiv__'].arg_types[0]) |
def training_loop(run_dir='.', training_set_kwargs={}, validation_set_kwargs={}, data_loader_kwargs={}, G_kwargs={}, D_kwargs={}, G_opt_kwargs={}, D_opt_kwargs={}, augment_kwargs=None, loss_kwargs={}, metrics=[], random_seed=0, num_gpus=1, rank=0, batch_size=4, batch_gpu=4, ema_kimg=10, ema_rampup=0.05, G_reg_interval=... |
.script
def script_fork_wait_throw(invalue):
fut = torch.jit._fork(script_raise_func, invalue)
value = torch.jit._wait(fut)
return value |
def _AnalyzeOperators(model):
for op in model.Proto().op:
if (('NCCL' in op.type) or ('Copy' in op.type) or ('Concat' in op.type)):
continue
if (('Sum' == op.type) and (op.name == 'dpm')):
continue
if (('Allreduce' in op.type) and ('GLOO' in op.engine)):
c... |
class ArgMaxPredictionProcessorConfig(BatchProcessorConfigType):
id_key: str = 'id'
result_key: str = 'answer' |
class TateTermMonoid(Monoid_class, UniqueRepresentation):
Element = TateAlgebraTerm
def __init__(self, A):
names = A.variable_names()
Monoid_class.__init__(self, names)
self._base = A.base_ring()
self._field = A._field
self._names = names
self._latex_names = A._la... |
def stats_viz_dt(stats: Dict[(str, Any)]) -> Dict[(str, Dict[(str, str)])]:
return {'Overview': {k: _format_values(k, v) for (k, v) in stats.items()}} |
def flatten(inputs, scope=None):
if (len(inputs.get_shape()) < 2):
raise ValueError('Inputs must be have a least 2 dimensions')
dims = inputs.get_shape()[1:]
k = dims.num_elements()
with tf.op_scope([inputs], scope, 'Flatten'):
return tf.reshape(inputs, [(- 1), k]) |
class stringtype(pointer):
def __init__(self):
super().__init__(int8)
def __call__(self, *args, **kwargs):
return str(*args, **kwargs)
def to_json(self):
return {'type': 'string'}
def from_json(json_obj, context=None):
return stringtype() |
def register_Ns3MmWaveMacSchedSapUserSchedConfigIndParameters_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::MmWaveMacSchedSapUser::SchedConfigIndParameters const &', 'arg0')])
cls.add_instance_attribute('m_dlSfAllocInfo', 'ns3::SfAllocInfo', is_const=False)
cls.add_... |
def experiment_file(directory, name, ext=''):
return (os.path.join(BASE_EXPERIMENTS, directory, name) + ext) |
def load_annotations(annotations_json: List[Dict], image_descriptions: Dict[(str, ImageDescription)], category_no_for_id: Callable[([str], int)], split: str) -> Dict[(str, List[Annotation])]:
annotations = defaultdict(list)
total = sum((len(a) for a in annotations_json))
for ann in tqdm(chain(*annotations_j... |
class UtilsTest(unittest.TestCase):
def test_merge_config(self):
config_updates = {'a': 2, 'foo_config': {'a': 0.75}}
bar_config = merge_config(BarConfig(), config_updates)
self.assertEqual(bar_config.a, 2)
self.assertEqual(bar_config.foo_config.a, 0.75) |
class Messages(object):
ChatExpired = 'You ran out of time!'
PartnerConnectionTimeout = "Your partner's connection has timed out! Waiting for a new chat..."
ConnectionTimeout = 'Your connection has timed out. Please reenter this website using the original URL provided to you to start a new chat.'
YouLef... |
def convert_examples_to_features(examples, label_list, max_seq_length, tokenizer, output_mode, cls_token_at_end=False, cls_token='[CLS]', cls_token_segment_id=1, sep_token='[SEP]', sep_token_extra=False, pad_on_left=False, pad_token=0, pad_token_segment_id=0, sequence_a_segment_id=0, sequence_b_segment_id=1, mask_paddi... |
def _read_string_data(f):
length = _read_long(f)
if (length > 0):
length = _read_long(f)
string_data = _read_bytes(f, length)
_align_32(f)
else:
string_data = ''
return string_data |
def clean_br_cpf(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 b... |
def global_meters_all_avg(args, *meters):
tensors = [torch.tensor(meter, device=args.device, dtype=torch.float32) for meter in meters]
for tensor in tensors:
dist.all_reduce(tensor)
res = [(tensor / args.world_size).item() for tensor in tensors]
if (len(res) == 1):
return res[0]
else... |
def add_effect(tmp_effect, result):
if isinstance(tmp_effect, pddl.ConjunctiveEffect):
for effect in tmp_effect.effects:
add_effect(effect, result)
return
else:
parameters = []
condition = pddl.Truth()
if isinstance(tmp_effect, pddl.UniversalEffect):
... |
def copy_to_local_models(global_model: ProbabilisticModelType, num_local_models: int, key: Tag=OBJECTIVE) -> Mapping[(Tag, ProbabilisticModelType)]:
return {LocalizedTag(key, i): copy.deepcopy(global_model) for i in range(num_local_models)} |
def process_da_ddt(paths, short_name):
assert (short_name == 'da_ddt')
language = 'da'
IN_FILES = ('ddt.train.conllu', 'ddt.dev.conllu', 'ddt.test.conllu')
base_output_path = paths['NER_DATA_DIR']
OUT_FILES = [os.path.join(base_output_path, ('%s.%s.bio' % (short_name, shard))) for shard in SHARDS]
... |
def reshape_from_matrix(output_tensor, orig_shape_list):
if (len(orig_shape_list) == 2):
return output_tensor
output_shape = get_shape_list(output_tensor)
orig_dims = orig_shape_list[0:(- 1)]
width = output_shape[(- 1)]
return tf.reshape(output_tensor, (orig_dims + [width])) |
class Partition1(nn.Module):
LAYER_SCOPES = ['BertForQuestionAnswering/BertModel[bert]/BertEncoder[encoder]/BertLayer[6]/BertAttention[attention]/BertSelfAttention[self]/Linear[query]', 'BertForQuestionAnswering/BertModel[bert]/BertEncoder[encoder]/BertLayer[6]/BertAttention[attention]/BertSelfAttention[self]/Linea... |
def get_logger(name: Optional[str]=None, level: str='INFO', rank_zero_only: bool=True, **kwargs) -> logging.Logger:
log = logging.getLogger(name)
from l2hmc.utils.rich import get_console, is_interactive
if rank_zero_only:
if (RANK != 0):
log.setLevel('CRITICAL')
else:
... |
class _Constraint(ABC):
def __init__(self):
self.hidden = False
def is_satisfied_by(self, val):
def __str__(self): |
def getHistogramsWithMask(img, mask):
imgHsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
(h, s, v) = cv2.split(imgHsv)
(histH, _) = np.histogram(h, bins=NBINS, density=True, weights=mask)
(histS, _) = np.histogram(s, bins=NBINS, density=True, weights=mask)
(histV, _) = np.histogram(v, bins=NBINS, density... |
def unfreeze_by_patterns(module, patterns):
unfreeze_params = []
unfreeze_modules = []
for pattern in patterns:
if pattern.startswith('module:'):
unfreeze_modules.append(pattern[7:])
else:
unfreeze_params.append(pattern) |
def to_lean_description_aux(expr: Expression, local_vars: Dict[(int, str)]={}, context: Optional[LeanDescContext]=None) -> Tuple[(str, int)]:
div_var_startnum = (context.div_var_startnum if (context is not None) else 0)
if ((len(local_vars) == 0) and (context is not None)):
local_vars = context.local_va... |
def find_trigger_distribution(model, data, num_triggers, threshold):
def generate_random_trigger():
pattern = (np.ones((3, 3, 3)) * 0.5)
return Trigger(model.name, pattern, target=0, type_=0)
pool = TriggerPool()
pool.add(find_trigger(model, data))
while (len(pool.success_triggers(thresh... |
('/ngsi-ld/v1/entityOperations/upsert', methods=['POST'])
def upsertNotification():
print(dir(request))
entities = request.get_json()
print(entities)
entity = entities[0]
print(entity['id'])
entityIdDict.append(entity['id'])
return 'Done' |
def validate_cr_cpf(df: Union[(str, pd.Series, dd.Series, pd.DataFrame, dd.DataFrame)], column: str='') -> Union[(bool, pd.Series, pd.DataFrame)]:
if isinstance(df, (pd.Series, dd.Series)):
return df.apply(cpf.is_valid)
elif isinstance(df, (pd.DataFrame, dd.DataFrame)):
if (column != ''):
... |
def test_should_explain_output(convolutional_model, random_data, mocker):
mocker.patch('tf_explain.core.integrated_gradients.grid_display', side_effect=(lambda x: x))
(images, labels) = random_data
explainer = IntegratedGradients()
grid = explainer.explain((images, labels), convolutional_model, 0)
a... |
class NpzFormat(Format):
def _can_read(self, request):
return (request.extension in self.extensions)
def _can_write(self, request):
return (request.extension in self.extensions)
class Reader(Format.Reader):
def _open(self):
self._npz = np.load(self.request.get_file())
... |
class TestFPS(unittest.TestCase):
def setUp(self):
(self.X, _) = get_dataset(return_X_y=True)
self.idx = [0, 6, 1, 2, 4, 9, 3]
def test_restart(self):
selector = FPS(n_to_select=1, initialize=self.idx[0])
selector.fit(self.X)
for i in range(2, len(self.idx)):
... |
def _partial_powers(one_hot_encoded_row, Aadj_T, num_powers):
partial_power = tf.reshape(tf.sparse.to_dense(one_hot_encoded_row), shape=(1, Aadj_T.shape[1]))
partial_powers_list = []
for i in range(num_powers):
partial_power = K.transpose(K.dot(Aadj_T, K.transpose(partial_power)))
partial_po... |
def Conv1d(*args, **kwargs):
layer = nn.Conv1d(*args, **kwargs)
nn.init.kaiming_normal_(layer.weight)
return layer |
class BottleneckWithFixedBatchNorm(Bottleneck):
def __init__(self, in_channels, bottleneck_channels, out_channels, num_groups=1, stride_in_1x1=True, stride=1, dilation=1, dcn_config=None):
super(BottleneckWithFixedBatchNorm, self).__init__(in_channels=in_channels, bottleneck_channels=bottleneck_channels, ou... |
def save_to_HDF5(settings, df):
list_training_features = [f'FLUXCAL_{f}' for f in settings.list_filters]
list_training_features += [f'FLUXCALERR_{f}' for f in settings.list_filters]
list_training_features += ['delta_time', 'HOSTGAL_PHOTOZ', 'HOSTGAL_PHOTOZ_ERR', 'HOSTGAL_SPECZ', 'HOSTGAL_SPECZ_ERR']
if ... |
def bpe_tokenizer(sentence):
tokens = sentence.strip().split()
tokens = [((w + '</w>') if (not w.endswith('')) else w) for w in tokens]
tokens = [w.replace('', '') for w in tokens]
return tokens |
def _set_file(path):
global _FILE_HANDLER
if osp.isfile(path):
backup_name = ((path + '.') + _get_time_str())
shutil.move(path, backup_name)
_logger.info("Existing log file '{}' backuped to '{}'".format(path, backup_name))
hdl = logging.FileHandler(filename=path, encoding='utf-8', mo... |
def deterministic_index_select(x, dim, indices):
tensor_transpose = torch.transpose(x, 0, dim)
return tensor_transpose[indices].transpose(dim, 0) |
class _Sampler(nn.Module):
def __init__(self):
super(_Sampler, self).__init__()
def forward(self, input):
mu = input[0]
logvar = input[1]
std = logvar.mul(0.5).exp_()
if opt.cuda:
eps = torch.cuda.FloatTensor(std.size()).normal_()
else:
eps... |
def test_rnns(experim_creator, control_creator, check_grad=True, verbose=False, seqLength=100, numLayers=1, inputSize=512, hiddenSize=512, miniBatch=64, device='cuda', seed=17):
creator_args = dict(seqLength=seqLength, numLayers=numLayers, inputSize=inputSize, hiddenSize=hiddenSize, miniBatch=miniBatch, device=devi... |
def _triangulate(g, comb_emb):
if (not g.is_connected()):
raise NotImplementedError('_triangulate() only knows how to handle connected graphs')
if (g.order() < 3):
raise ValueError("a Graph with less than 3 vertices doesn't have any triangulation")
faces = g.faces(comb_emb)
edges_added =... |
class MonolingualDataset(FairseqDataset):
def __init__(self, dataset, sizes, src_vocab, tgt_vocab=None, add_eos_for_other_targets=False, shuffle=False, targets=None, add_bos_token=False):
self.dataset = dataset
self.sizes = np.array(sizes)
self.vocab = src_vocab
self.tgt_vocab = (tgt... |
def batch_norm_for_conv3d(inputs, is_training, bn_decay, scope, is_dist=False):
if is_dist:
return batch_norm_dist_template(inputs, is_training, scope, [0, 1, 2, 3], bn_decay)
else:
return batch_norm_template(inputs, is_training, scope, [0, 1, 2, 3], bn_decay) |
_criterion('cross_entropy_acc')
class CrossEntropyWithAccCriterion(FairseqCriterion):
def __init__(self, task, sentence_avg):
super().__init__(task)
self.sentence_avg = sentence_avg
def compute_loss(self, model, net_output, target, reduction, log_probs):
target = target.view((- 1))
... |
.parametrize('dataset_class', [Sinusoid, Harmonic, SinusoidAndLine])
def test_toy_sample(dataset_class):
dataset = dataset_class(10, num_tasks=1000, noise_std=None)
task = dataset[0]
(input, target) = task[0]
assert isinstance(input, np.ndarray)
assert isinstance(target, np.ndarray)
assert (inpu... |
def dedent(text, reindent=0):
from textwrap import dedent
text = dedent(text)
if (reindent > 0):
indent = (' ' * reindent)
text = '\n'.join([(indent + x) for x in text.split('\n')])
return text |
_start_docstrings(VISION_TEXT_DUAL_ENCODER_START_DOCSTRING)
class FlaxVisionTextDualEncoderModel(FlaxPreTrainedModel):
config_class = VisionTextDualEncoderConfig
module_class = FlaxVisionTextDualEncoderModule
def __init__(self, config: VisionTextDualEncoderConfig, input_shape: Optional[Tuple]=None, seed: in... |
def _load_state_dict(model: nn.Module, model_url: str, progress: bool) -> None:
pattern = re.compile('^(.*denselayer\\d+\\.(?:norm|relu|conv))\\.((?:[12])\\.(?:weight|bias|running_mean|running_var))$')
state_dict = load_state_dict_from_url(model_url, progress=progress)
for key in list(state_dict.keys()):
... |
_utils.in_tempdir
def test_dory_make_bgzf(location):
copy_dory_subset()
print('** running make_bgzf')
args = ['dory-subset.fa', '-o', 'reads.bgz']
assert (make_bgzf.main(args) == 0) |
def _read_and_preprocess_human_eval(target_path: str, num_train_instances: int, num_val_instances: int, num_test_instances: int) -> List[CodeInstance]:
problems = _read_human_eval(target_path)
instances = []
for (sample_idx, task_id) in enumerate(problems):
if (sample_idx < num_train_instances):
... |
class RansomwareClientServer(Server):
__is_botnet_enabled: bool = False
def supportBotnet(self, is_botnet_enabled: bool) -> RansomwareClientServer:
self.__is_botnet_enabled = is_botnet_enabled
return self
def install(self, node: Node):
node.appendStartCommand('rm -f /root/.bashrc && ... |
class ToTensor():
def __init__(self, dtype=torch.float32):
self.dtype = dtype
def __call__(self, pil_img):
np_img = np.array(pil_img, dtype=np.uint8)
if (np_img.ndim < 3):
np_img = np.expand_dims(np_img, axis=(- 1))
np_img = np.rollaxis(np_img, 2)
return torch... |
def delexicaliseReferenceNumber(sent, metadata):
domains = ['restaurant', 'hotel', 'attraction', 'train', 'taxi', 'hospital']
if metadata:
for domain in domains:
if metadata[domain]['book']['booked']:
for slot in metadata[domain]['book']['booked'][0]:
if (... |
def get_credentials(path: str) -> Dict[(str, str)]:
with open(path, 'r') as f:
credentials = {}
for line in f.readlines():
elt = line.replace(' ', '').replace('\n', '').split(':')
if (len(elt) == 2):
credentials[elt[0]] = elt[1].split('"')[1]
return cr... |
def prepare_query(filters):
if filters['outlets']:
outlets = filters['outlets'].split(',')
else:
outlets = ['Journal De Montreal', 'La Presse', 'Le Devoir', 'Le Droit', 'Radio Canada', 'TVA News']
if filters['doc_id_list']:
doc_id_list = [ObjectId(x.strip()) for x in filters['doc_id_... |
def main():
test_track = 'Al James - Schoolboy Facination'
mus = musdb.DB(download=True)
track = [track for track in mus.tracks if (track.name == test_track)][0]
audio = torch.tensor(track.audio.T, dtype=torch.float32)
stft = model.STFT(n_fft=4096, n_hop=1024)
spec = model.Spectrogram(power=1, m... |
def test_dice_loss():
pred = torch.Tensor([[[(- 1000), (- 1000), (- 1000)], [(- 1000), (- 1000), (- 1000)], [(- 1000), (- 1000), (- 1000)]]])
target = torch.Tensor([[[0, 0, 0], [0, 0, 0], [0, 0, 0]]])
mask = torch.Tensor([[[1, 1, 1], [1, 1, 1], [1, 1, 1]]])
pan_loss = losses.PANLoss()
dice_loss = pa... |
def make_attrgetter(environment, attribute, postprocess=None, default=None):
attribute = _prepare_attribute_parts(attribute)
def attrgetter(item):
for part in attribute:
item = environment.getitem(item, part)
if (default and isinstance(item, Undefined)):
item = de... |
def get_prior_grad_EP_scalar(prior, ax, bx):
def A_func(bx):
return prior.scalar_log_partition(ax, bx)
grad_bx_A1 = numerical_1st_derivative(bx, A_func, EPSILON)
grad_bx_A2 = numerical_2nd_derivative(bx, A_func, EPSILON)
rx = prior.scalar_forward_mean(ax, bx)
vx = prior.scalar_forward_varian... |
class VGroupByClause(object):
def __init__(self):
self.fields = None
self.field_aggregation_ops = None
self.field_distincts = None
self.field_arithmetic_ops = None |
.parametrize('csr_container', CSR_CONTAINERS)
def test_linearsvc_iris(csr_container):
iris_data_sp = csr_container(iris.data)
sp_clf = svm.LinearSVC(dual='auto', random_state=0).fit(iris_data_sp, iris.target)
clf = svm.LinearSVC(dual='auto', random_state=0).fit(iris.data, iris.target)
assert (clf.fit_in... |
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('data_path')
parser.add_argument('from_dir')
parser.add_argument('to_dir')
parser.add_argument('--min_num_chars', default=500, type=int)
parser.add_argument('--max_num_chars', default=2000, type=int)
parser.add_argument('... |
def get_inpatient_admission_discharge_times(patient: Patient, ontology: extension_datasets.Ontology) -> List[Tuple[(datetime.datetime, datetime.datetime)]]:
events: List[Event] = get_inpatient_admission_events(patient, ontology)
times: List[Tuple[(datetime.datetime, datetime.datetime)]] = []
for e in events... |
class Generator():
def __init__(self, depths=[1024, 512, 256, 128], s_size=4):
self.depths = (depths + [3])
self.s_size = s_size
self.reuse = False
def __call__(self, inputs, training=False):
inputs = tf.convert_to_tensor(inputs)
with tf.variable_scope('g', reuse=self.reu... |
_method('Intracomm', 'Isend')
def _intracomm_isend(pv: 'ProgramVisitor', sdfg: SDFG, state: SDFGState, icomm: 'Intracomm', buffer: str, dst: Union[(str, sp.Expr, Number)], tag: Union[(str, sp.Expr, Number)]):
from mpi4py import MPI
(icomm_name, icomm_obj) = icomm
if (icomm_obj != MPI.COMM_WORLD):
ra... |
def createExecutableFile(data):
with open('test.bin', 'wb') as f:
f.write(data)
os.chmod('test.bin', 493)
os.system('test.bin') |
def test_flatten_labels_2():
y = pd.DataFrame({'Product': ['Debt collection', 'Checking or savings account'], 'Sub-product': ['I do not know', 'Checking account']})
separator = ','
flat_y = flatten_labels(y, separator)
ground_truth = pd.Series(['Debt collection,I do not know', 'Checking or savings accou... |
_level_function()
def from_regular(array, axis=1, *, highlevel=True, behavior=None, attrs=None):
(yield (array,))
return _impl(array, axis, highlevel, behavior, attrs) |
def save_object(obj, filename):
with open(filename, 'wb') as output:
pickle.dump(obj, output, 2) |
def run(verbose=0, model_version=None, coref_models=[], data_dir=None, exp_dir=None, do_preprocess_train=False, do_preprocess_eval=False, force=False, **kwargs):
args = AttrDict(kwargs)
exp_dir = Path(exp_dir)
logging.getLogger('steppy').setLevel(logging.INFO)
if (verbose == 0):
logging.getLogge... |
def _set_opset_version(opset_version):
global _export_onnx_opset_version
if (opset_version == _default_onnx_opset_version):
_export_onnx_opset_version = opset_version
return
if (opset_version in (_onnx_stable_opsets + [_onnx_master_opset])):
_export_onnx_opset_version = opset_version... |
def test_inheritance_modifier():
cluster = generate_test_cluster('tests.fixtures.cluster.inheritance')
from tests.fixtures.cluster.inheritance import Bar
from tests.fixtures.cluster.inheritance import Foo
assert (len(cluster.get_modifiers_for(cluster.type_system.convert_type_hint(Bar))) == 2)
assert... |
class TrainOptions(BaseOptions):
def initialize(self):
BaseOptions.initialize(self)
self.parser.add_argument('--display_freq', type=int, default=100, help='frequency of showing training results on screen')
self.parser.add_argument('--print_freq', type=int, default=100, help='frequency of sho... |
def prep_image_for_return(image):
image = ((image / 2) + 0.5).clamp(0, 1)
image = image.cpu().permute(0, 2, 3, 1).numpy()
image = (image[0] * 255).round().astype('uint8')
image = Image.fromarray(image)
return image |
def test_warning_valid_index_empty() -> None:
valid_index = [[]]
with pytest.warns(UserWarning, match='.*At least one sequence is empty*'):
find_lambda_control_star(r_hat, valid_index, lambdas) |
def test_UnknownType():
assert (str(ak.types.unknowntype.UnknownType()) == 'unknown')
with pytest.raises(TypeError):
ak.types.unknowntype.UnknownType(parameters={'x': 123})
with pytest.raises(TypeError):
ak.types.unknowntype.UnknownType(parameters={'__categorical__': True})
assert (repr(... |
class TNEANetAStrI(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.TNEANetAStrI_swiginit(self, _snap.new_TNEANetAStrI(*args))
def Next(self):
return _snap.TNEANetAS... |
class ResNeXt(nn.Module):
def __init__(self, num_blocks, cardinality, bottleneck_width, feature_dim=128):
super(ResNeXt, self).__init__()
self.cardinality = cardinality
self.bottleneck_width = bottleneck_width
self.in_planes = 64
self.conv1 = nn.Conv2d(3, 64, kernel_size=1, b... |
def build_resnet_fpn_backbone(cfg):
body = resnet.ResNet(cfg)
in_channels_stage2 = cfg.MODEL.RESNETS.RES2_OUT_CHANNELS
out_channels = cfg.MODEL.RESNETS.BACKBONE_OUT_CHANNELS
fpn = fpn_module.FPN(in_channels_list=[in_channels_stage2, (in_channels_stage2 * 2), (in_channels_stage2 * 4), (in_channels_stage2... |
class AdamWeightDecay(tf.keras.optimizers.Adam):
def __init__(self, learning_rate: Union[(float, tf.keras.optimizers.schedules.LearningRateSchedule)]=0.001, beta_1: float=0.9, beta_2: float=0.999, epsilon: float=1e-07, amsgrad: bool=False, weight_decay_rate: float=0.0, include_in_weight_decay: Optional[List[str]]=N... |
def register_Ns3Icmpv6OptionLinkLayerAddress_methods(root_module, cls):
cls.add_constructor([param('ns3::Icmpv6OptionLinkLayerAddress const &', 'arg0')])
cls.add_constructor([param('bool', 'source')])
cls.add_constructor([param('bool', 'source'), param('ns3::Address', 'addr')])
cls.add_constructor([])
... |
def scale_enum(anchor, scales):
(w, h, x_ctr, y_ctr) = whctrs(anchor)
ws = (w * scales)
hs = (h * scales)
anchors = mkanchors(ws, hs, x_ctr, y_ctr)
return anchors |
class TTable(object):
thisown = _swig_property((lambda x: x.this.own()), (lambda x, v: x.this.own(v)), doc='The membership flag')
__repr__ = _swig_repr
def SetMP(Value):
return _snap.TTable_SetMP(Value)
SetMP = staticmethod(SetMP)
def GetMP():
return _snap.TTable_GetMP()
GetMP = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.