code stringlengths 101 5.91M |
|---|
class TextClassificationDecoder(DecoderBase, TextClassificationDecoderMixin):
def __init__(self, config: TextClassificationDecoderConfig):
super().__init__()
self.idx2label = config.idx2label
self.dropout = CombinedDropout(*config.in_drop_rates)
self.hid2logit = torch.nn.Linear(confi... |
class QuerySetSelectField(fields.SelectFieldBase):
widget = widgets.Select()
def __init__(self, label=None, validators=None, queryset=None, get_label=None, allow_blank=False, blank_text='', **kwargs):
super(QuerySetSelectField, self).__init__(label, validators, **kwargs)
self.allow_blank = allow... |
def _cluster_intersections(intersections, radius_threshold):
if (len(intersections) == 0):
return []
n = 1
while True:
km = KMeans(n)
assignments = km.fit_predict(intersections)
centers = [instantiators['point'](*p) for p in km.cluster_centers_]
radii = []
for... |
class FilterableRequestsAuth(Protocol):
def apply_to(self, func: (MatcherFunc | None)=None, *, name: (FilterValue | None)=None, name_regex: (str | None)=None, method: (FilterValue | None)=None, method_regex: (str | None)=None, path: (FilterValue | None)=None, path_regex: (str | None)=None) -> FilterableRequestsAuth... |
class SmoothedValue():
def __init__(self, window_size=20):
self.window_size = window_size
self.reset()
def reset(self):
self.deque = deque(maxlen=self.window_size)
self.averaged_value_deque = deque(maxlen=self.window_size)
self.batch_sizes = deque(maxlen=self.window_size)... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--txt_file', type=str, help='Input plaintext file')
parser.add_argument('--label_file', type=str, default=None, help='Character-level label file')
parser.add_argument('--json_file', type=str, default=None, help='JSON file with pre... |
def dosig(node):
if (node is None):
return 'self'
else:
non_keyword_args = (node.args.posonlyargs + node.args.args)
argnames = [x.arg for x in (non_keyword_args + node.args.kwonlyargs)]
defaults = [('=' + tostr(x)) for x in (node.args.defaults + node.args.kw_defaults) if (x is no... |
class WikiExtractor(object):
def __init__(self, lowercase=True, min_paragraph_len=20):
self._lowercase = lowercase
self._min_paragraph_len = min_paragraph_len
self._tokenizer = RegexpTokenizer()
def extract_paragraphs(self, page):
paragraphs = []
cur_text = []
cur... |
class LargestNConnectedComponents(pymia_fltr.Filter):
def __init__(self, number_of_components: int=1, consecutive_component_labels: bool=False):
super().__init__()
if (not (number_of_components >= 1)):
raise ValueError('number_of_components must be larger or equal to 1')
self.num... |
def ngb_matrix(U, N):
user = load_users(U)
server = load_servers(N)
neighbourhood = np.zeros([U, N])
for u in range(0, U):
for n in range(0, N):
if server.iloc[n].geometry.contains(user.iloc[u].geometry):
neighbourhood[(u, n)] = 1
else:
nei... |
class PreFilter():
def filter(d: pd.DataFrame, ns: SimpleNamespace) -> pd.DataFrame:
if (not hasattr(ns, 'prefiltering')):
return d
ns = ns.prefiltering
dataframe = d.copy()
for strategy in ns:
dataframe = PreFilter.single_filter(dataframe, strategy)
r... |
class ConcatSampler(Sampler):
def __init__(self, concat_dataset: ConcatDataset, samples_per_dataset: int):
assert isinstance(concat_dataset, ConcatDataset)
self.concat_dataset = concat_dataset
self.nb_datasets = len(concat_dataset.datasets)
self.samples_per_dataset = samples_per_data... |
def block_inception_c(inputs, scope=None, reuse=None):
with slim.arg_scope([slim.conv2d, slim.avg_pool2d, slim.max_pool2d], stride=1, padding='SAME'):
with tf.variable_scope(scope, 'BlockInceptionC', [inputs], reuse=reuse):
with tf.variable_scope('Branch_0'):
branch_0 = slim.conv... |
def get_local_rank() -> int:
if (not dist.is_available()):
return 0
if (not dist.is_initialized()):
return 0
assert (_LOCAL_PROCESS_GROUP is not None)
return dist.get_rank(group=_LOCAL_PROCESS_GROUP) |
def result_info(tool_id, finding):
fname = finding['name']
info_finding = sb.tools.info_finding(tool_id, fname)
result_dict = {'ruleId': rule_id(tool_id, fname), 'locations': [{'physicalLocation': {'artifactLocation': {'uri': finding['filename']}}}]}
v = result_message(finding, info_finding)
if v:
... |
.pure
def test_onnx_return_scalars(gpu, sdfg_name):
X = helper.make_tensor_value_info('X', TensorProto.FLOAT, [5])
Y = helper.make_tensor_value_info('Y', TensorProto.FLOAT, [])
node_def = helper.make_node('ReduceSum', ['X'], ['Y'], keepdims=0)
graph_def = helper.make_graph([node_def], 'test-scalar-retur... |
class Pipeline(BaseSKMObject):
_estimator_type = 'pipeline'
def __init__(self, steps):
super().__init__()
self.steps = tosequence(steps)
self.active = False
self.__configure()
def __configure(self):
self._validate_steps()
def predict(self, X):
Xt = X
... |
def line_search_wolfe1(f, fprime, xk, pk, gfk=None, old_fval=None, old_old_fval=None, args=(), c1=0.0001, c2=0.9, amax=50, amin=1e-08, xtol=1e-14):
if (gfk is None):
gfk = fprime(xk, *args)
gval = [gfk]
gc = [0]
fc = [0]
def phi(s):
fc[0] += 1
return f((xk + (s * pk)), *args)... |
def BuildAdj(vtoi, deps):
itov = {v: k for (k, v) in vtoi.items()}
adjs = {}
conn_adjs = {}
for (k, v) in itov.items():
(adjs[k], conn_adjs[k]) = ({}, {})
src = itov[k]
for tup in deps:
if (tup[0] == src):
(tgt_k, arc) = (vtoi[tup[1]], tup[(- 1)])
... |
.parametrize('forward_output', (True, False))
.parametrize('backend', ('hdf5', 'netcdf4'))
.parametrize('as_scalar', (True, False))
def test_mixed_3D(backend, forward_output, as_scalar):
if (((backend == 'netcdf4') and (forward_output is True)) or skip[backend]):
return
K0 = FunctionSpace(N[0], 'F', dty... |
class AttentionPool(nn.Module):
def __init__(self, inputdim, outputdim=10, pooldim=1, **kwargs):
super().__init__()
self.inputdim = inputdim
self.outputdim = outputdim
self.pooldim = pooldim
self.transform = nn.Linear(inputdim, outputdim)
self.activ = nn.Softmax(dim=p... |
class SingleProcessRamTensorStorage(SingleProcessTensorStorage):
def __init__(self, data_schema: Dict[(str, SizeData)], buf: io.BytesIO):
super().__init__(data_schema, buf) |
class config(old_config):
old_config.user_options += [('fcompiler=', None, 'specify the Fortran compiler type')]
def initialize_options(self):
self.fcompiler = None
old_config.initialize_options(self)
def _check_compiler(self):
old_config._check_compiler(self)
from numpy.dist... |
def test_branch_coverage_half_branch(subject_properties_mock, trace_mock):
subject_properties_mock.existing_predicates[0] = MagicMock(PredicateMetaData)
trace_mock.true_distances[0] = 0.0
assert (ff.compute_branch_coverage(trace_mock, subject_properties_mock) == 0.5) |
class WifiLinkMonitor(object):
def __init__(self, dummy_viz):
self.access_points = {}
self.stations = []
def scan_nodes(self, viz):
for (sta_netdevice, viz_node, wifi_link) in self.stations:
wifi_link.destroy()
self.access_points = {}
self.stations = []
... |
(frozen=True)
class RunConfiguration(HalfFrozenObject):
experiment_name: str = attr.ib(default=None)
eval_experiment_name: str = attr.ib(default=None)
experiment_directory: str = attr.ib(default=None)
eval_mode: str = attr.ib(default=None, validator=(lambda i, a, v: (v in ('default', 'dropout', 'ensembl... |
def register_Ns3Ping6Helper_methods(root_module, cls):
cls.add_constructor([param('ns3::Ping6Helper const &', 'arg0')])
cls.add_constructor([])
cls.add_method('Install', 'ns3::ApplicationContainer', [param('ns3::NodeContainer', 'c')])
cls.add_method('SetAttribute', 'void', [param('std::string', 'name'),... |
class tqdm_notebook(tqdm):
def status_printer(_, total=None, desc=None):
if total:
pbar = IntProgress(min=0, max=total)
else:
pbar = IntProgress(min=0, max=1)
pbar.value = 1
pbar.bar_style = 'info'
if desc:
pbar.description = desc
... |
def adapt_time_step(ts, status, adt, problem, verbose=False):
if (ts.time > 0.5):
ts.set_time_step(0.1)
return True |
_node_type()
class Overlap(optplan.Function):
type = schema_utils.polymorphic_model_type('function.overlap')
simulation = optplan.ReferenceType(optplan.Function)
overlap = optplan.ReferenceType(optplan.EmOverlap) |
.parametrize('module_creator', [ModuleCreator(TSTPureConv(), [(4, 3, 32, 32)])])
.parametrize('another_input_shape', [(1, 3, 64, 64), (1, 3, 80, 80)])
def test_another_shape_input(module_creator, another_input_shape):
module = module_creator.module
proto_variable_inputs = [nn.ProtoVariable(shape) for shape in m... |
def efficient_pwdist_gauss(M1, S1, M2=None, S2=None, sqrtS1=None, sqrtS2=None, symmetric=False, diagonal_cov=False, commute=False, sqrt_method='spectral', sqrt_niters=20, sqrt_pref=0, device='cpu', nworkers=1, cost_function='euclidean', return_dmeans=False, return_sqrts=False):
if (M2 is None):
symmetric = ... |
def largest_available_k(n, t=2):
from .block_design import projective_plane
if (n < 0):
raise ValueError('n(={}) was expected to be >=0'.format(n))
if (t < 0):
raise ValueError('t(={}) was expected to be >=0'.format(t))
if ((n == 0) or (n == 1)):
from sage.rings.infinity import I... |
class Differential(UniqueRepresentation, Morphism, metaclass=InheritComparisonClasscallMetaclass):
def __classcall__(cls, A, im_gens):
if isinstance(im_gens, (list, tuple)):
im_gens = {A.gen(i): A(x) for (i, x) in enumerate(im_gens)}
else:
im_gens = {A(a): A(im_gens[a]) for a... |
class ShearX(DauphinTransform):
value_range = (0.0, 0.3)
def __init__(self, name=None, prob=1.0, level=0):
super().__init__(name, prob, level)
def transform(self, pil_img, label, **kwargs):
degree = categorize_value(self.level, self.value_range, 'float')
if (random.random() > 0.5):
... |
def write_output_files(output_file_name, primal_res, dual_res=None, psf_res=None, output_format='npy'):
if (output_format == 'fits'):
write_to_fits((output_file_name + '_primal.fits'), primal_res)
if (not isinstance(dual_res, type(None))):
write_to_fits((output_file_name + '_dual.fits'),... |
()
def schema(fastapi_app):
return from_asgi('/openapi.json', fastapi_app, force_schema_version='30') |
def get_completion_adapter_spec(instructions: str='', input_prefix: str='', output_prefix: str='', output_suffix: str='', max_train_instances: int=0, temperature: float=0.0, num_outputs: int=1, max_tokens: int=100, stop_sequences: Optional[List]=None, **kwargs) -> AdapterSpec:
if (stop_sequences is None):
s... |
class TAPEVisualizer(ABC):
def __init__(self, log_dir: typing.Union[(str, Path)], exp_name: str, debug: bool=False):
raise NotImplementedError
def log_config(self, config: typing.Dict[(str, typing.Any)]) -> None:
raise NotImplementedError
def watch(self, model: nn.Module) -> None:
ra... |
class TestIterators(unittest.TestCase):
def test_counting_iterator(self):
x = list(range(10))
itr = iterators.CountingIterator(x)
self.assertTrue(itr.has_next())
self.assertEqual(next(itr), 0)
self.assertEqual(next(itr), 1)
itr.skip(3)
self.assertEqual(next(it... |
_criterion('cross_entropy')
class CrossEntropyCriterion(FairseqCriterion):
def __init__(self, args, task):
super().__init__(args, task)
def forward(self, model, sample, reduce=True):
net_output = model(**sample['net_input'])
(loss, _) = self.compute_loss(model, net_output, sample, reduce... |
class DistributedBackend():
BACKEND_MODULE_NAME = None
BACKEND_NAME = None
ROOT_RANK = 0
backend_module = None
is_initialized = False
def __init__(self):
if (self.BACKEND_MODULE_NAME is None):
raise NotImplementedError('BACKEND_MODULE_NAME is not set')
if (self.BACKEN... |
def test_load_tags():
default_clipid = 'airport-lisbon-1000-40000-0-a'
dataset = tau2022uas_mobile.Dataset(TEST_DATA_HOME)
clip = dataset.clip(default_clipid)
assert (len(clip.tags.labels) == 1)
assert (clip.tags.labels[0] == 'airport')
assert np.allclose([1.0], clip.tags.confidence)
eval_de... |
class UCF101Dataset(BaseDataset):
def __init__(self, *args, split='', **kwargs):
assert (split in ['train', 'val', 'test'])
self.split = split
self.metadata = None
self.ans_lab_dict = dict()
if (split == 'train'):
names = ['ucf101_train']
elif (split == 'v... |
def test_power_two_range_stmt_non_interactive():
group_pair = BilinearGroupPair()
group = group_pair.G1
value = Secret(value=Bn(10))
randomizer = Secret(value=group.order().random())
(g, h) = make_generators(2, group)
limit = 20
com = ((value * g) + (randomizer * h))
p1 = PowerTwoRangeSt... |
.operations('upload_file')
def test_cli_binary_body(cli, schema_url, hypothesis_max_examples):
result = cli.run(schema_url, '--hypothesis-suppress-health-check=filter_too_much', f'--hypothesis-max-examples={(hypothesis_max_examples or 1)}')
assert (result.exit_code == ExitCode.OK), result.stdout
assert (' H... |
class BaseCalculator(HypotestsObject):
def __init__(self, input, minimizer):
super().__init__(input, minimizer)
self._obs_nll = {}
self._parameters = {}
for m in self.model:
for d in m.get_params():
self._parameters[d.name] = d
def obs_nll(self, pois: ... |
class LALR_WithLexer(WithLexer):
def __init__(self, lexer_conf, parser_conf, options=None):
debug = (options.debug if options else False)
self.parser = LALR_Parser(parser_conf, debug=debug)
WithLexer.__init__(self, lexer_conf, parser_conf, options)
self.init_lexer()
def init_lexe... |
def trieste_keras_ensemble_model(example_data: Dataset, ensemble_size: int, independent_normal: bool=False) -> KerasEnsemble:
(input_tensor_spec, output_tensor_spec) = get_tensor_spec_from_data(example_data)
networks = [GaussianNetwork(input_tensor_spec, output_tensor_spec, hidden_layer_args=[{'units': 32, 'act... |
class VolumetricConvolution(Module):
def __init__(self, nInputPlane, nOutputPlane, kT, kW, kH, dT=1, dW=1, dH=1, padT=0, padW=None, padH=None):
super(VolumetricConvolution, self).__init__()
self.nInputPlane = nInputPlane
self.nOutputPlane = nOutputPlane
self.kT = kT
self.kW =... |
class TestNumericStyleTypecodes(_DeprecationTestCase):
def test_all_dtypes(self):
deprecated_types = ['Bool', 'Complex32', 'Complex64', 'Float16', 'Float32', 'Float64', 'Int8', 'Int16', 'Int32', 'Int64', 'Object0', 'Timedelta64', 'UInt8', 'UInt16', 'UInt32', 'UInt64', 'Void0']
if (sys.version_info[0... |
def shuffle_in_unison(a, b):
assert (len(a) == len(b))
shuffled_a = np.empty(a.shape, dtype=a.dtype)
shuffled_b = np.empty(b.shape, dtype=b.dtype)
permutation = np.random.permutation(len(a))
for (old_index, new_index) in enumerate(permutation):
shuffled_a[new_index] = a[old_index]
sh... |
class OllamaLocal(LM):
def __init__(self, model: str='llama2', model_type: Literal[('chat', 'text')]=None, **kwargs):
super().__init__(model)
self.provider = 'ollama'
self.base_url = '
default_model_type = 'text'
self.model_type = (model_type if model_type else default_model_... |
def csv_sniffer_has_bug_last_field():
has_bug = getattr(csv_sniffer_has_bug_last_field, 'has_bug', None)
if (has_bug is None):
dialect = csv.Sniffer().sniff("3, 'a'")
csv_sniffer_has_bug_last_field.has_bug = (dialect.quotechar != "'")
has_bug = csv_sniffer_has_bug_last_field.has_bug
... |
class TrivialMapInitEliminationTest(unittest.TestCase):
def test_can_be_applied(self):
graph = trivial_map_init_sdfg()
count = graph.apply_transformations(TrivialMapElimination, validate=False, validate_all=False)
graph.validate()
self.assertGreater(count, 0)
def test_removes_map... |
def _allgather_then_aggregate_hook(process_group: object, bucket: dist._GradBucket) -> torch.futures.Future:
group_to_use = (process_group if (process_group is not None) else dist.group.WORLD)
rank = (process_group.rank() if (process_group is not None) else dist.get_rank())
world_size = (process_group.size(... |
class Postgres(object):
def __init__(self, db_name, schema_name, user, password=None, host=None, port=None, verbose=False, debug=False):
self.db_name = db_name
self.user = user
self.verbose = verbose
self.debug = debug
self.cursors_opened = 0
self._table_columns = {}
... |
def _moments_raw_to_central_fast(moments_raw):
ndim = moments_raw.ndim
order = (moments_raw.shape[0] - 1)
float_dtype = moments_raw.dtype
moments_raw = moments_raw.astype(np.float64, copy=False)
moments_central = np.zeros_like(moments_raw)
if ((order >= 4) or (ndim not in [2, 3])):
raise... |
def MOLS_table(start, stop=None, compare=False, width=None):
from .orthogonal_arrays import largest_available_k
if (stop is None):
(start, stop) = (0, start)
start = (start - (start % 20))
stop = (stop - 1)
stop = (stop + (20 - (stop % 20)))
assert (((start % 20) == 0) and ((stop % 20) =... |
class RNNCell(RNNCellBase):
__constants__ = ['input_size', 'hidden_size', 'bias', 'nonlinearity']
def __init__(self, input_size, hidden_size, bias=True, nonlinearity='tanh', dtype=torch.qint8):
super(RNNCell, self).__init__(input_size, hidden_size, bias, num_chunks=1, dtype=dtype)
self.nonlinear... |
def get_entity_from_task_config(task_dict: dict):
entity_dict = dict()
entity_dict['Entity'] = dict()
for task in list(task_dict.keys()):
if ('entities' in task_dict[task]):
for entity in task_dict[task]['entities']:
if (entity not in entity_dict['Entity']):
... |
class ConvModBlock(nn.Module):
def __init__(self, dim, mlp_ratio=4.0, drop_path=0.0):
super().__init__()
self.attn = ConvMod(dim)
self.mlp = MLP(dim, mlp_ratio)
layer_scale_init_value = 1e-06
self.layer_scale_1 = nn.Parameter((layer_scale_init_value * torch.ones(dim)), requir... |
def DenseNet121(nclass):
return DenseNet(Bottleneck, [6, 12, 24, 16], growth_rate=32, num_classes=nclass) |
class TestFirls(object):
def test_bad_args(self):
assert_raises(ValueError, firls, 10, [0.1, 0.2], [0, 0])
assert_raises(ValueError, firls, 11, [0.1, 0.2, 0.4], [0, 0, 0])
assert_raises(ValueError, firls, 11, [0.1, 0.2, 0.3, 0.4], [0, 0, 0])
assert_raises(ValueError, firls, 11, [0.2,... |
.parametrize('ctx, func_name', ctxs)
.parametrize('seed', [313])
.parametrize('p', [None, 1.0, 1.3, 3.0])
.parametrize('shape, axis', [((2, 3, 5, 7), (0, 2)), ((13,), 0), ((7, 3, 1), None), ((2, 1, 4, 5), (0, 2))])
.parametrize('eps', [1e-12])
def test_norm_normalization_forward_backward(eps, axis, p, shape, seed, ctx,... |
def point_maze(maze_str):
maze_arr = parse_maze(maze_str)
mjcmodel = MJCModel('point_maze')
mjcmodel.root.compiler(inertiafromgeom='true', angle='radian', coordinate='local')
mjcmodel.root.option(timestep='0.01', gravity='0 0 0', iterations='20', integrator='Euler')
default = mjcmodel.root.default()... |
class BloclLocalStorage(BenchmarkItem):
name = 'bls'
def __init__(self):
self._items = {'bls_on': True, 'bls_off': False} |
def edge_accurate(pred, target):
true_labels = retrieve_adjacency_matrix(target)
predictions = retrieve_adjacency_matrix(pred, (target.nodes() if isinstance(target, nx.DiGraph) else None))
total_edges = true_labels.sum()
tp = ((predictions == 1) & (predictions == true_labels)).sum()
tn = ((predictio... |
def test_case124():
url = (brokerIp + '/ngsi-ld/v1/subscriptions/')
headers = {'Content-Type': 'application/json', 'Accept': 'application/ld+json', 'Link': '<{{link}}>; rel=" type="application/ld+json"'}
r = requests.post(url, data=json.dumps(ld_data.subdata123), headers=headers)
print(r.content)
pr... |
def get_concat_h(im1, im2):
dst = PIL.Image.new('RGB', ((im1.width + im2.width), im1.height))
dst.paste(im1, (0, 0))
dst.paste(im2, (im1.width, 0))
return dst |
def parse(exit_code, log, output):
(findings, infos) = ([], set())
(errors, fails) = sb.parse_utils.errors_fails(exit_code, log)
errors.discard('EXIT_CODE_1')
for f in list(fails):
if f.startswith('exception (teether.evm.exceptions.'):
fails.remove(f)
elif (f.startswith('exce... |
class UNet(nn.Module):
def l2n(self, x):
return torch.nn.functional.normalize(x, p=2.0, dim=1)
def __init__(self, n_channels, n_classes, bilinear=False):
super(UNet, self).__init__()
self.IN = nn.InstanceNorm2d(1)
self.n_channels = n_channels
self.n_classes = n_classes
... |
class BinnedDataset(Dataset):
def __init__(self, df, data_dir, num_bins, graph_featurizer, num_workers=0, upper_limit=1500, form_dir_name: str='subform_20', use_ray=False, **kwargs):
self.df = df
self.num_bins = num_bins
self.num_workers = num_workers
self.upper_limit = upper_limit
... |
def load_data(path, flag='train'):
data_npz = np.load(os.path.join(path, 'data_{}.npz'.format(flag)))
with open(os.path.join(path, 'data_feature_output.pkl'), 'rb') as f:
data_feature_outputs = pickle.load(f)
with open(os.path.join(path, 'data_attribute_output.pkl'), 'rb') as f:
data_attribu... |
class TransferModule(nn.Module):
def forward(self, node_attn, edge_attn):
new_attn = torch.matmul(node_attn, edge_attn.float())
return new_attn |
def _preprocess_dataset_for_language_modeling(dataset: Sequence, sep_token: Optional[int]=None, conditional: bool=True):
decision_to_str = {'REJECTED': 0, 'ACCEPTED': 1, 'PENDING': 2, 'CONT-REJECTED': 3, 'CONT-ACCEPTED': 4, 'CONT-PENDING': 5}
indices_of_cont_patents = {v for (k, v) in decision_to_str.items() if... |
class BeatsEncoder(BaseEncoder):
def __init__(self, checkpoint_path=ckp_path):
super().__init__()
if is_url(checkpoint_path):
cached_file = download_cached_file(checkpoint_path, check_hash=False, progress=True)
checkpoint = torch.load(cached_file)
elif os.path.isfile(... |
def get_sequence_mask(sequence_len):
batch_size = sequence_len.size()[0]
max_len = torch.max(sequence_len)
tmp = torch.arange(max_len, device=sequence_len.device).expand(batch_size, max_len)
return (tmp < sequence_len.unsqueeze(1)) |
class GroupViTTextConfig(PretrainedConfig):
model_type = 'groupvit_text_model'
def __init__(self, vocab_size=49408, hidden_size=256, intermediate_size=1024, num_hidden_layers=12, num_attention_heads=4, max_position_embeddings=77, hidden_act='quick_gelu', layer_norm_eps=1e-05, dropout=0.0, attention_dropout=0.0,... |
def save_results(input_img, gt_data, density_map, output_dir, fname='results.png'):
density_map[(density_map < 0)] = 0
input_img = input_img[0][0].astype(np.uint8)
gt_data = ((255 * gt_data) / np.max(gt_data))
density_map = ((255 * density_map) / np.max(density_map))
gt_data = gt_data[0][0]
dens... |
def test_same_predict() -> None:
mapie_cal = MapieCalibrator(method='top_label')
mapie_cal.fit(X=X_, y=y_, random_state=random_state)
y_pred_calib_set = mapie_cal.single_estimator_.predict(X=X_test)
y_pred_calib_set_through_predict = mapie_cal.predict(X=X_test)
y_pred_calibrated_test_set = np.nanarg... |
class MixConv2d(nn.Module):
def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True):
super().__init__()
groups = len(k)
if equal_ch:
i = torch.linspace(0, (groups - 1e-06), c2).floor()
c_ = [(i == g).sum() for g in range(groups)]
else:
b = ([c2] +... |
def test_is_datetime_type_with_mixed_array():
data = [pd.to_datetime('2020-01-01'), '1890-03-05', pd.Timestamp('01-01-01'), datetime(2020, 1, 1), np.nan]
is_datetime = is_datetime_type(data)
assert is_datetime |
def arrowed_spines(fig, ax):
(xmin, xmax) = ax.get_xlim()
(ymin, ymax) = ax.get_ylim()
for side in ['bottom', 'right', 'top', 'left']:
ax.spines[side].set_visible(False)
plt.xticks([])
plt.yticks([])
ax.xaxis.set_ticks_position('none')
ax.yaxis.set_ticks_position('none')
dps = fi... |
_LAYERS.register_module(name='Clip')
_LAYERS.register_module()
class Clamp(nn.Module):
def __init__(self, min=(- 1.0), max=1.0):
super(Clamp, self).__init__()
self.min = min
self.max = max
def forward(self, x):
return torch.clamp(x, min=self.min, max=self.max) |
class DDIMSampler(object):
def __init__(self, model, schedule='linear', **kwargs):
super().__init__()
self.model = model
self.ddpm_num_timesteps = model.num_timesteps
self.schedule = schedule
def register_buffer(self, name, attr):
if (type(attr) == torch.Tensor):
... |
def update(G, B, h):
R = h.parent()
LCM = R.monomial_lcm
def lt_divides(x, y):
return (R.monomial_divides(LM(h), LM(g)) and LC(h).divides(LC(g)))
def lt_pairwise_prime(x, y):
return (R.monomial_pairwise_prime(LM(x), LM(y)) and (gcd(LC(x), LC(y)) == 1))
def lcm_divides(f, g1, h):
... |
def QDM_57_9_1_1_8():
from sage.rings.finite_rings.integer_mod_ring import IntegerModRing as G
B = [None, 1, 6, 7, 9, 19, 38, 42, 49]
OA = orthogonal_array(9, 9, 2)
M = [R for R in OA if any(((R[0] != x) for x in R))]
M = [[B[x] for x in R] for R in M]
M.append(([0] * 9))
return (G(57), M) |
.parametrize('observation_shape', [(4,), ((4,), (8,))])
.parametrize('length', [100])
.parametrize('pad_size', [5])
def test_batch_pad_observations(observation_shape: Shape, length: int, pad_size: int) -> None:
observations = create_observations(observation_shape, length)
padded_observations = batch_pad_observa... |
def preprocess_with_artifacts(net_preproc_fn, jpeg_quality_range, scale_factor_range, jitter=True):
preproc_fn = prepare_image_fn(jitter=jitter)
artifact_fn = generate_induce_artifacts(jpeg_quality_range, scale_factor_range)
return transforms.Compose((preproc_fn, artifact_fn, transforms.Lambda(net_preproc_f... |
class SequenceNode(ExprNode):
subexprs = ['args', 'mult_factor']
is_sequence_constructor = 1
unpacked_items = None
mult_factor = None
slow = False
def compile_time_value_list(self, denv):
return [arg.compile_time_value(denv) for arg in self.args]
def replace_starred_target_node(self)... |
def seed(seed=None):
if (isinstance(seed, str) and (seed == 'default')):
backend.id_srando()
elif hasattr(seed, '__len__'):
state = np.asfortranarray(seed, dtype=float)
if (state.shape != (55,)):
raise ValueError('invalid input size')
elif ((state.min() < 0) or (state... |
(scope='module')
def simulation_one_loop(atomic_data_fname, config, tardis_ref_data, generate_reference):
config.atom_data = atomic_data_fname
config.montecarlo.iterations = 2
config.montecarlo.no_of_packets = int(40000.0)
config.montecarlo.last_no_of_packets = int(40000.0)
simulation = Simulation.f... |
def is_FunctionField(x):
if isinstance(x, FunctionField):
return True
return (x in FunctionFields()) |
class DataPrefetcher():
def __init__(self, loader, device, init=False):
self.loader = loader
self.iter = None
self.stream = torch.cuda.Stream()
if init:
self.iter = self.loader
self.preload()
def __len__(self):
return len(self.loader)
def prelo... |
def WloopIN_Y(X1, X2, S, E):
Data = np.append(X1, X2, axis=1)
(row, col) = Data.shape
ab = np.ones(row)
ab.shape = (1, row)
Data = np.insert(Data, 1, (S * ab), axis=1)
Data = np.insert(Data, 3, X1.T, axis=1)
Data = np.insert(Data, 4, (E * ab), axis=1)
Data = np.insert(Data, 5, X2.T, axis... |
class BaseLoader(Reader, Scanner, Parser, Composer, BaseConstructor, BaseResolver):
def __init__(self, stream):
Reader.__init__(self, stream)
Scanner.__init__(self)
Parser.__init__(self)
Composer.__init__(self)
BaseConstructor.__init__(self)
BaseResolver.__init__(self... |
_module()
class DRIVEDataset(CustomDataset):
CLASSES = ('background', 'vessel')
PALETTE = [[120, 120, 120], [6, 230, 230]]
def __init__(self, **kwargs):
super(DRIVEDataset, self).__init__(img_suffix='.png', seg_map_suffix='_manual1.png', reduce_zero_label=False, **kwargs)
assert self.file_cl... |
def test_augment_ratio():
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
should_augment = (lambda x: (x >= 3))
can_augment = (lambda x: (x >= 4))
assert (get_augment_ratio(data, should_augment, can_augment, desired_ratio=0.1) == 0.0)
with pytest.raises(AssertionError):
get_augment_ratio(data, can_au... |
class FreeAlgebraQuotientElement(AlgebraElement):
def __init__(self, A, x):
AlgebraElement.__init__(self, A)
Q = self.parent()
if (isinstance(x, FreeAlgebraQuotientElement) and (x.parent() == Q)):
self.__vector = Q.module()(x.vector())
return
if isinstance(x, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.