code stringlengths 281 23.7M |
|---|
class Logger(object):
INFO = 0
DEBUG = 1
WARNING = 2
ERROR = 3
CRITICAL = 4
def config_logger(cls, file_folder='.', level='info', save_log=False, display_source=False):
cls.file_folder = file_folder
cls.file_json = os.path.join(file_folder, 'log-1.json')
cls.file_log = os... |
class JavaScriptLoader(ScriptLoader):
def __init__(self):
super().__init__('js')
self.original_template = gradio.routes.templates.TemplateResponse
self.load_js()
gradio.routes.templates.TemplateResponse = self.template_response
def load_js(self):
js_scripts = ScriptLoader... |
def manager_function(input_queue: Queue, output_queue: Queue, worker_function: Callable) -> None:
logging.getLogger().setLevel(logging.ERROR)
warnings.filterwarnings(action='ignore', category=UserWarning, module=MODULE_ADDONS_INSTALL)
logging.info('MANAGER: initializing')
worker_result_queue = Queue()
... |
class EnumList(EnumType):
def __init__(self, *args, **kwargs):
assert (len(kwargs) in (0, 1, 2)), (type(self).__name__ + ': expected 0 to 2 extra parameters ("ctype", "cname").')
ctype = kwargs.pop('ctype', 'int')
cname = kwargs.pop('cname', None)
for (arg_rank, arg) in enumerate(arg... |
def read_tables(data_dir, bc):
bc.create_table('web_sales', os.path.join(data_dir, 'web_sales/*.parquet'))
bc.create_table('web_returns', os.path.join(data_dir, 'web_returns/*.parquet'))
bc.create_table('date_dim', os.path.join(data_dir, 'date_dim/*.parquet'))
bc.create_table('item', os.path.join(data_d... |
class Robot(namedtuple('Robot', ['name', 'password', 'created', 'last_accessed', 'description', 'unstructured_metadata'])):
def to_dict(self, include_metadata=False, include_token=False):
data = {'name': self.name, 'created': (format_date(self.created) if (self.created is not None) else None), 'last_accesse... |
def set_settings(**new_settings):
def decorator(testcase):
if (type(testcase) is type):
namespace = {'OVERRIDE_SETTINGS': new_settings, 'ORIGINAL_SETTINGS': {}}
wrapper = type(testcase.__name__, (SettingsTestCase, testcase), namespace)
else:
(testcase)
... |
def train(train_loader, model, criterion, optimizer, epoch, cfg, logger, writer):
model.train()
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
num_iter = len(train_loader)
end = time.time()
time1 = time.time()
for (idx, (images, _)) in enumerate(train_load... |
def test_generate_env_name_ignores_case_for_case_insensitive_fs(poetry: Poetry, tmp_path: Path) -> None:
venv_name1 = EnvManager.generate_env_name(poetry.package.name, 'MyDiR')
venv_name2 = EnvManager.generate_env_name(poetry.package.name, 'mYdIr')
if (sys.platform == 'win32'):
assert (venv_name1 ==... |
def test_marker_union_intersect_marker_union() -> None:
m = parse_marker('sys_platform == "darwin" or python_version < "3.4"')
intersection = m.intersect(parse_marker('implementation_name == "cpython" or os_name == "Windows"'))
assert (str(intersection) == 'sys_platform == "darwin" and implementation_name =... |
(m2m_changed, sender=Topic.mirrors.through)
def update_topic_disambiguation(instance, action, pk_set, **kwargs):
appended_topics = Topic.objects.filter(pk__in=pk_set)
current = instance.mirrors.all()
if (action not in ('post_add', 'post_remove')):
return
for topic in appended_topics:
rel... |
class Torus(DynSys):
def _rhs(x, y, z, t, a, n, r):
xdot = (((((- a) * n) * np.sin((n * t))) * np.cos(t)) - ((r + (a * np.cos((n * t)))) * np.sin(t)))
ydot = (((((- a) * n) * np.sin((n * t))) * np.sin(t)) + ((r + (a * np.cos((n * t)))) * np.cos(t)))
zdot = ((a * n) * np.cos((n * t)))
... |
class TestNumeric():
def klass(self):
return configtypes._Numeric
def test_minval_gt_maxval(self, klass):
with pytest.raises(ValueError):
klass(minval=2, maxval=1)
def test_special_bounds(self, klass):
numeric = klass(minval='maxint', maxval='maxint64')
assert (nu... |
def test_walsh_control():
with pytest.raises(ArgumentsValueError):
_ = new_wamf1_control(rabi_rotation=0.3, maximum_rabi_rate=np.pi)
walsh_pi = new_wamf1_control(rabi_rotation=np.pi, azimuthal_angle=(- 0.35), maximum_rabi_rate=(2 * np.pi))
pi_segments = np.vstack((walsh_pi.amplitude_x, walsh_pi.ampl... |
def test_renext_bottleneck():
with pytest.raises(AssertionError):
BottleneckX(64, 64, groups=32, base_width=4, style='tensorflow')
block = BottleneckX(64, 64, groups=32, base_width=4, stride=2, style='pytorch')
assert (block.conv2.stride == (2, 2))
assert (block.conv2.groups == 32)
assert (b... |
def set_client(scheduler=None):
if ((scheduler != config._SCHEDULER) and (config._CLIENT is not None)):
try:
config._CLIENT.shutdown()
config._CLIENT = None
except Exception:
pass
config._SCHEDULER = scheduler
if (scheduler is not None):
config._CL... |
def _get_builtin_metadata():
thing_dataset_id_to_contiguous_id = {x['id']: i for (i, x) in enumerate(sorted(categories, key=(lambda x: x['id'])))}
thing_classes = [x['name'] for x in sorted(categories, key=(lambda x: x['id']))]
return {'thing_dataset_id_to_contiguous_id': thing_dataset_id_to_contiguous_id, ... |
def mnist_generator(data, batch_size, n_labelled, limit=None, selecting_label=None, bias=None, portion=1):
(images, targets) = data
if (bias is not None):
images = images[(targets != bias)]
targets = targets[(targets != bias)]
if (selecting_label is None):
rng_state = numpy.random.ge... |
class BoundaryValue(BoundaryOperator):
def __init__(self, child, side):
super().__init__('boundary value', child, side)
def _unary_new_copy(self, child):
return boundary_value(child, self.side)
def _sympy_operator(self, child):
sympy = have_optional_dependency('sympy')
if ((s... |
def wildcard_file_resolution(glob_search_string):
filepaths = glob(glob_search_string)
if (len(filepaths) < 1):
raise FileNotFoundError('No file found that matches the provided path')
if (len(filepaths) > 1):
raise TypeError('More than one file found that matches the search string')
foun... |
def match(y_true, y_pred):
y_true = y_true.astype(np.int64)
y_pred = y_pred.astype(np.int64)
assert (y_pred.size == y_true.size)
D = (max(y_pred.max(), y_true.max()) + 1)
w = np.zeros((D, D), dtype=np.int64)
for i in range(y_pred.size):
w[(y_pred[i], y_true[i])] += 1
(row_ind, col_in... |
def cv_select_tune_param(cv_results, metric='score', rule='best', prefer_larger_param=True):
if (metric is None):
metric = 'score'
test_key = ('mean_test_' + metric)
if (test_key not in cv_results):
raise ValueError('{} was not found in cv_results'.format(test_key))
if (rule not in ['bes... |
def eval_det(pred_all, gt_all, ovthresh=0.25, use_07_metric=False, get_iou_func=get_iou):
pred = {}
gt = {}
for img_id in pred_all.keys():
for (classname, bbox, score) in pred_all[img_id]:
if (classname not in pred):
pred[classname] = {}
if (img_id not in pred... |
_fixtures(ReahlSystemFixture, PartyAccountFixture)
def test_request_new_password(reahl_system_fixture, party_account_fixture):
fixture = party_account_fixture
system_account = fixture.new_system_account(activated=False)
account_management_interface = fixture.new_account_management_interface(system_account=s... |
class DataloaderAsyncGPUWrapper(DataloaderWrapper):
def __init__(self, dataloader: Iterable) -> None:
assert torch.cuda.is_available(), 'This Dataloader wrapper needs a CUDA setup'
super().__init__(dataloader)
self.cache = None
self.cache_next = None
self.stream = torch.cuda.... |
def amsgrad(func, x, n_iter, learning_rate=0.001, beta1=0.9, beta2=0.999, eps=1e-07):
V = 0.0
S = 0.0
S_hat = 0.0
for i in range((n_iter + 1)):
(_, grad) = func(x)
V = ((beta1 * V) + ((1 - beta1) * grad))
S = ((beta2 * S) + ((1 - beta2) * (grad ** 2)))
S_hat = np.maximum(... |
class Emeter(Usage):
def realtime(self) -> EmeterStatus:
return EmeterStatus(self.data['get_realtime'])
def emeter_today(self) -> Optional[float]:
raw_data = self.daily_data
today = datetime.now().day
data = self._convert_stat_data(raw_data, entry_key='day')
return data.g... |
def ensure_trees_loaded(manager: BuildManager, graph: dict[(str, State)], initial: Sequence[str]) -> None:
to_process = find_unloaded_deps(manager, graph, initial)
if to_process:
if is_verbose(manager):
manager.log_fine_grained('Calling process_fresh_modules on set of size {} ({})'.format(le... |
class CourseraOAuth2Test(OAuth2Test):
backend_path = 'social_core.backends.coursera.CourseraOAuth2'
user_data_url = '
expected_username = '560e7ed2076e0d589e88bd74b6aad4b7'
access_token_body = json.dumps({'access_token': 'foobar', 'token_type': 'Bearer', 'expires_in': 1795})
request_token_body = jso... |
def _unparse_paren(level_lst):
line = level_lst[0][0][0]
for level in level_lst[1:]:
for group in level:
new_string = group[(- 1)]
if ((new_string[:2] == '((') and (new_string[(- 2):] == '))')):
new_string = new_string[1:(- 1)]
line = line.replace(grou... |
class XMLResponse(HttpResponse):
def __init__(self, xml, name=None):
super().__init__(prettify_xml(xml), content_type='application/xml')
if (name and (settings.EXPORT_CONTENT_DISPOSITION == 'attachment')):
self['Content-Disposition'] = 'attachment; filename="{}.xml"'.format(name.replace(... |
def create_context(default_value: _Type) -> Context[_Type]:
def context(*children: Any, value: _Type=default_value, key: (Key | None)=None) -> _ContextProvider[_Type]:
return _ContextProvider(*children, value=value, key=key, type=context)
context.__qualname__ = 'context'
return context |
(frozen=True)
class AndConstraint(AbstractConstraint):
constraints: Tuple[(AbstractConstraint, ...)]
def apply(self) -> Iterable['Constraint']:
for cons in self.constraints:
(yield from cons.apply())
def invert(self) -> 'OrConstraint':
return OrConstraint(tuple((cons.invert() for... |
def LFP_electrolyte_exchange_current_density_kashkooli2017(c_e, c_s_surf, c_s_max, T):
m_ref = (6 * (10 ** (- 7)))
E_r = 39570
arrhenius = np.exp(((E_r / pybamm.constants.R) * ((1 / 298.15) - (1 / T))))
return ((((m_ref * arrhenius) * (c_e ** 0.5)) * (c_s_surf ** 0.5)) * ((c_s_max - c_s_surf) ** 0.5)) |
def scatter(inputs, target_gpus, dim=0, chunk_sizes=None):
def scatter_map(obj):
if isinstance(obj, Variable):
return Scatter.apply(target_gpus, chunk_sizes, dim, obj)
assert (not torch.is_tensor(obj)), 'Tensors not supported in scatter.'
if isinstance(obj, tuple):
re... |
def link_AGL(name, restype, argtypes, requires=None, suggestions=None):
try:
func = getattr(agl_lib, name)
func.restype = restype
func.argtypes = argtypes
decorate_function(func, name)
return func
except AttributeError:
return missing_function(name, requires, sugg... |
def transform_2d(arr, kpts, ki, rmat, label, trans):
ki_ibz = kpts.bz2ibz[ki]
ki_ibz_bz = kpts.ibz2bz[ki_ibz]
if (ki == ki_ibz_bz):
return arr[ki_ibz]
(pi, pj) = label
rmat_i = getattr(rmat, (pi * 2))
rmat_j = getattr(rmat, (pj * 2))
iop = kpts.stars_ops_bz[ki]
rot_i = rmat_i[ki_... |
def test_tdm_fmcw_tx():
print('#### TDM FMCW transmitter ####')
tdm = tdm_fmcw_tx()
print('# TDM FMCW transmitter parameters #')
assert (tdm.waveform_prop['pulse_length'] == 8e-05)
assert (tdm.waveform_prop['bandwidth'] == .0)
assert (tdm.rf_prop['tx_power'] == 20)
assert (tdm.waveform_prop[... |
('requires_bandmat')
def test_linalg_choleskey_inv():
from nnmnkwii.paramgen import build_win_mats
for windows in _get_windows_set():
for T in [5, 10]:
win_mats = build_win_mats(windows, T)
P = _get_banded_test_mat(win_mats, T).full()
L = scipy.linalg.cholesky(P, lowe... |
def L2_PGD(x_in, y_true, net, steps, eps):
if (eps == 0):
return x_in
training = net.training
if training:
net.eval()
x_adv = x_in.clone().requires_grad_()
optimizer = Adam([x_adv], lr=0.01)
eps = torch.tensor(eps).view(1, 1, 1, 1).cuda()
for _ in range(steps):
optimi... |
def add_single_database_parameters(add_in_memory=False):
def add_single_database_parameters_decorator(command):
click.argument('database', metavar='DATABASE')(command)
if add_in_memory:
_in_memory_option(command)
def wrapped_command(**kwargs):
popped_kwargs = {'databa... |
class FrontPage(Element):
def __init__(self, header: str, title: str, subtitle: str, logo: str, grid_proportion: GridProportion=GridProportion.Eight):
super().__init__(grid_proportion)
self.header = header
self.title = title
self.subtitle = subtitle
self.logo = logo
def g... |
def conv3x3(mode, in_planes, out_planes, k_in_mask, k_out_mask, output, stride=1):
if ((mode == 'finetune') or (mode == 'full')):
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
if (mode == 'sparse'):
return SparseConv2d(in_planes, out_planes, kernel_... |
def get_plot(title):
possibles_edit = [(i + 'Edit') for i in possibles]
all_possibles = (possibles + possibles_edit)
try:
title = urllib.parse.unquote(title.replace('_', ' '))
wik = wikipedia.WikipediaPage(title)
except:
wik = np.NaN
plot = None
try:
for j in all_... |
def test_bad_extra(base_object: dict[(str, Any)]) -> None:
bad_extra = 'a{[*+'
base_object['extras'] = {}
base_object['extras']['test'] = [bad_extra]
errors = validate_object(base_object, 'poetry-schema')
assert (len(errors) == 1)
assert (errors[0] == 'data.extras.test[0] must match pattern ^[a-... |
def train_and_validate(args):
set_seed(args.seed)
vocab = Vocab()
vocab.load(args.vocab_path)
args.vocab = vocab
model = build_model(args)
if (args.pretrained_model_path is not None):
model = load_model(model, args.pretrained_model_path)
else:
for (n, p) in list(model.named_p... |
def test_pattern_str() -> None:
assert (str(Pattern(Conc(Mult(Charclass('a'), ONE)), Conc(Mult(Charclass('b'), ONE)))) == 'a|b')
assert (str(Pattern(Conc(Mult(Charclass('a'), ONE)), Conc(Mult(Charclass('a'), ONE)))) == 'a')
assert (str(Pattern(Conc(Mult(Charclass('a'), ONE), Mult(Charclass('b'), ONE), Mult(... |
def test_slicing_basic(do_test):
a = CaseBits32Bits64SlicingBasicComp.DUT()
a._rtlir_test_ref = {'slicing_basic': CombUpblk('slicing_basic', [Assign([Slice(Attribute(Base(a), 'out'), Number(0), Number(16))], Slice(Attribute(Base(a), 'in_'), Number(16), Number(32)), True), Assign([Slice(Attribute(Base(a), 'out')... |
_torch
_vision
class DPTFeatureExtractionTest(FeatureExtractionSavingTestMixin, unittest.TestCase):
feature_extraction_class = (DPTFeatureExtractor if is_vision_available() else None)
def setUp(self):
self.feature_extract_tester = DPTFeatureExtractionTester(self)
def feat_extract_dict(self):
... |
def get_unbalanced(task, pos_pos, pos_neg, neg_pos, neg_neg):
x_train = []
x_test = []
if (('age' in task) or ('mention2' in task)):
lim_1_train = 40000
lim_1_test = 42000
lim_2_train = 10000
lim_2_test = 11000
else:
lim_1_train = 66400
lim_1_test = 70400
... |
def prepare_dataloader(device: torch.device) -> torch.utils.data.DataLoader:
num_samples = (NUM_BATCHES * BATCH_SIZE)
data = torch.randn(num_samples, 128, device=device)
labels = torch.randint(low=0, high=2, size=(num_samples,), device=device)
return torch.utils.data.DataLoader(TensorDataset(data, label... |
def _load_info(root, basename='info'):
info_json = os.path.join(root, (basename + '.json'))
info_yaml = os.path.join(root, (basename + '.yaml'))
err_str = ''
try:
with wds.gopen.gopen(info_json) as f:
info_dict = json.load(f)
return info_dict
except Exception as e:
... |
class Migration(migrations.Migration):
dependencies = [('api', '0071_increase_message_content_4000')]
operations = [migrations.AlterField(model_name='documentationlink', name='base_url', field=models.URLField(blank=True, help_text='The base URL from which documentation will be available for this project. Used t... |
class ShardingPlan():
plan: Dict[(str, ModuleShardingPlan)]
def get_plan_for_module(self, module_path: str) -> Optional[ModuleShardingPlan]:
return self.plan.get(module_path, None)
def __str__(self) -> str:
out = ''
for (i, (module_path, module_plan)) in enumerate(self.plan.items()):... |
class ChannelAttention(nn.Module):
def __init__(self, channel, reduction=16):
super().__init__()
self.maxpool = nn.AdaptiveMaxPool2d(1)
self.avgpool = nn.AdaptiveAvgPool2d(1)
self.se = nn.Sequential(nn.Conv2d(channel, (channel // reduction), 1, bias=False), nn.ReLU(), nn.Conv2d((chan... |
def printFlakeOutput(text):
ret = 0
gotError = False
for line in text.split('\n'):
m = re.match('[^\\:]+\\:\\d+\\:\\d+\\: (\\w+) .*', line)
if (m is None):
print(line)
else:
gotError = True
error = m.group(1)
if (error in FLAKE_MANDATOR... |
def assert_named_modules_identical(actual, desired, equality_sufficient=False):
(actual_names, actual_modules) = zip(*actual)
(desired_names, desired_modules) = zip(*desired)
assert (actual_names == desired_names)
assert_modules_identical(actual_modules, desired_modules, equality_sufficient=equality_suf... |
_config
def test_spiral_left_anticlockwise(manager):
manager.test_window('one')
assert_dimensions(manager, 0, 0, 798, 598)
manager.test_window('two')
assert_dimensions(manager, 400, 0, 398, 598)
manager.test_window('three')
assert_dimensions(manager, 400, 0, 398, 298)
manager.test_window('fo... |
class VisibilityTracing(nn.Module):
def __init__(self, object_bounding_sphere=1.0, sphere_tracing_iters=30, initial_epsilon=0.001):
super().__init__()
self.object_bounding_sphere = object_bounding_sphere
self.sphere_tracing_iters = sphere_tracing_iters
self.start_epsilon = initial_ep... |
def add_flops_counting_methods(net_main_module):
net_main_module.start_flops_count = start_flops_count.__get__(net_main_module)
net_main_module.stop_flops_count = stop_flops_count.__get__(net_main_module)
net_main_module.reset_flops_count = reset_flops_count.__get__(net_main_module)
net_main_module.comp... |
def _report_unserialization_failure(type_name: str, report_class: Type[BaseReport], reportdict) -> NoReturn:
url = '
stream = StringIO()
pprint(('-' * 100), stream=stream)
pprint(('INTERNALERROR: Unknown entry type returned: %s' % type_name), stream=stream)
pprint(('report_name: %s' % report_class),... |
def main(cmdline=None):
parser = make_parser()
args = parser.parse_args(cmdline)
dev = args.dev
if (not dev):
cmd = 'devlink -j dev show'
(stdout, stderr) = run_command(cmd)
assert (stderr == '')
devs = json.loads(stdout)['dev']
if devs:
dev = list(dev... |
class LLaMATokenizer():
def __init__(self, model_path: str):
assert os.path.isfile(model_path), model_path
self.sp_model = SentencePieceProcessor(model_file=model_path)
logger.info(f'Reloaded SentencePiece model from {model_path}')
self.n_words: int = self.sp_model.vocab_size()
... |
class Bert4RecDataloader():
def __init__(self, dataset: Dict[(str, Any)], train_batch_size: int, val_batch_size: int, test_batch_size: int) -> None:
self.train: pd.DataFrame = dataset['train']
self.val: pd.DataFrame = dataset['val']
self.test: pd.DataFrame = dataset['test']
self.trai... |
class _Coefficients():
LUTS: list[np.ndarray] = []
COEFF_INDEX_MAP: dict[(int, dict[(Union[(tuple, str)], int)])] = {}
def __init__(self, wavelength_range, resolution=0):
self._wv_range = wavelength_range
self._resolution = resolution
def __call__(self):
idx = self._find_coeffici... |
def numbered_glob(pattern, last=True, decimal=False, every=False):
repat = '(\\d+(?:\\.\\d*)?)'.join((re.escape(s) for s in pattern.split('*', 1)))
best_fn = None
best_n = None
all_results = []
for c in glob.glob(pattern):
m = re.match(repat, c)
if m:
if decimal:
... |
class MBConvBlockWithoutDepthwise(MBConvBlock):
def _build(self):
filters = (self._block_args.input_filters * self._block_args.expand_ratio)
if (self._block_args.expand_ratio != 1):
self._expand_conv = tf.layers.Conv2D(filters, kernel_size=[3, 3], strides=[1, 1], kernel_initializer=conv_... |
class TestModelValidation(TestCase):
def setUp(self):
super(TestModelValidation, self).setUp()
self.env = get_env()
self.tm = self.env.type_manager
self.fm = self.env.formula_manager
def test_basic(self):
model_source = '(model\n ;; universe for U:\n ;; (as U) (as U... |
def test_filerewriter_files_in_to_out_edit_dir_slash(temp_dir, temp_file_creator):
rewriter = ArbRewriter('formatter')
temp_file_creator()
temp_file_creator()
in_path = temp_dir.joinpath('*')
out = (str(temp_dir) + os.sep)
with patch_logger('pypyr.utils.filesystem', logging.INFO) as mock_logger_... |
def test_date_convert_parity():
path = pymedphys.data_path('negative-metersetmap.trf')
(header, _) = pymedphys.trf.read(path)
utc_date = header['date'][0]
timezone = 'Australia/Sydney'
dateutil_version = identify._date_convert_using_dateutil(utc_date, timezone)
pandas_version = identify.date_con... |
class DNN(Network):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
inp = None
output = None
if (self.shared_network is None):
inp = Input((self.input_dim,))
output = self.get_network_head(inp).output
else:
inp = self... |
def test_custom_dataset():
tmp_dir = tempfile.TemporaryDirectory()
ann_file = osp.join(tmp_dir.name, 'fake_data.txt')
_create_dummy_ann_file(ann_file)
loader = _create_dummy_loader()
for mode in [True, False]:
dataset = BaseDataset(ann_file, loader, pipeline=[], test_mode=mode)
asser... |
def roll(*args, **kwargs):
func = kwargs.pop('function')
window = kwargs.pop('window')
if (len(args) > 2):
raise ValueError('Cannot pass more than 2 return sets')
if (len(args) == 2):
if (not isinstance(args[0], type(args[1]))):
raise ValueError('The two returns arguments are... |
class TVolume(TestCase):
def setUp(self):
self.p = NullPlayer()
self.v = Volume(self.p)
def test_setget(self):
for i in [0.0, 1.2, 0.24, 1.0, 0.9]:
self.v.set_value(i)
self.assertAlmostEqual(self.p.volume, self.v.get_value())
def test_add(self):
self.v... |
def cached_function(inputs, outputs):
import theano
with Message('Hashing theano fn'):
if hasattr(outputs, '__len__'):
hash_content = tuple(map(theano.pp, outputs))
else:
hash_content = theano.pp(outputs)
cache_key = hex((hash(hash_content) & ((2 ** 64) - 1)))[:(- 1)]... |
class Line(entity):
def __init__(self):
self.parent = False
self.children = []
self.feats = {}
self.featpaths = {}
self.finished = False
self.__parses = {}
self.__bestparse = {}
self.__boundParses = {}
def parse(self, meter=None, init=None):
... |
def test_tagulous_in_migrations(apps, schema_editor):
model = apps.get_model('tagulous_tests_migration', 'MigrationTestModel')
assertIsSubclass(model, tagulous.models.TaggedModel)
assertIsInstance(model.singletag, tagulous.models.SingleTagDescriptor)
assertIsSubclass(model.singletag.tag_model, tagulous.... |
class TestInline():
def test_inlonly(self, header_checker):
header_checker.check_ignored('inline')
def test_inlonlyquoted(self, header_checker):
header_checker.check_ignored('"inline"')
def test_inlwithasciifilename(self, header_checker):
header_checker.check_filename('inline; filena... |
class Discriminator(nn.Module):
def __init__(self, num_classes, image_size=224, conv_dim=64, repeat_num=5):
super(Discriminator, self).__init__()
layers = []
layers.append(SpectralNorm(nn.Conv2d(3, conv_dim, kernel_size=4, stride=2, padding=1)))
layers.append(nn.LeakyReLU(0.01))
... |
class BookSettings():
def __init__(self) -> None:
self.order: Order = Order.SHORT_TO_LONG
self.books_string: str = 'Book A\n1. e4 e5\n\nBook B\n1. e4 e5 2. f4'
def order_callback(self, _, order_value):
self.order = Order(order_value)
def books_string_callback(self, _, books_string):
... |
class CDAE(nn.Module):
def __init__(self, NUM_USER, NUM_MOVIE, NUM_BOOK, EMBED_SIZE, dropout, is_sparse=False):
super(CDAE, self).__init__()
self.NUM_MOVIE = NUM_MOVIE
self.NUM_BOOK = NUM_BOOK
self.NUM_USER = NUM_USER
self.emb_size = EMBED_SIZE
self.user_embeddings = ... |
def assert_mirror(original: NettingChannelState, mirror: NettingChannelState) -> None:
original_locked_amount = channel.get_amount_locked(original.our_state)
mirror_locked_amount = channel.get_amount_locked(mirror.partner_state)
assert (original_locked_amount == mirror_locked_amount)
balance0 = channel.... |
def affiliation_recall_distance(Is=[(1, 2), (3, 4), (5, 6)], J=(2, 5.5)):
Is = [I for I in Is if (I is not None)]
if (len(Is) == 0):
return math.inf
E_gt_recall = get_all_E_gt_func(Is, ((- math.inf), math.inf))
Js = affiliation_partition([J], E_gt_recall)
return (sum([integral_interval_dista... |
_callback_query((tools.option_filter('show') & tools.is_admin))
def show_option(bot: AutoPoster, callback_query: CallbackQuery):
data = callback_query.data.split()
bot.reload_config()
if (data[2] == 'send_reposts'):
info = '** :**\n\n'
button_list = [InlineKeyboardButton('', callback_data='... |
def test_transform_matrix():
r = wp.quat_from_axis_angle(wp.vec3(1.0, 0.0, 0.0), 0.5)
t = wp.vec3(0.25, 0.5, (- 0.75))
s = wp.vec3(2.0, 0.5, 0.75)
m = wp.mat44(t, r, s)
p = wp.vec3(1.0, 2.0, 3.0)
r_0 = (wp.quat_rotate(r, wp.cw_mul(s, p)) + t)
r_1 = wp.transform_point(m, p)
r_2 = wp.trans... |
_solaranywhere_credentials
.remote_data
.flaky(reruns=RERUNS, reruns_delay=RERUNS_DELAY)
def test_get_solaranywhere_probability_exceedance_error(solaranywhere_api_key):
with pytest.raises(ValueError, match='start and end time must be null'):
(data, meta) = pvlib.iotools.get_solaranywhere(latitude=44.4675, l... |
.skipif((python_implementation() == 'PyPy'), reason='no orjson on PyPy')
(everythings(min_int=(- ), max_int=, allow_inf=False))
def test_orjson_converter_unstruct_collection_overrides(everything: Everything):
from cattrs.preconf.orjson import make_converter as orjson_make_converter
converter = orjson_make_conve... |
class Solution(object):
def closestValue(self, root, target):
kid = (root.left if (target < root.val) else root.right)
if (not kid):
return root.val
kid_min = self.closestValue(kid, target)
return min((kid_min, root.val), key=(lambda x: abs((target - x)))) |
class TestFlumeCollector(CollectorTestCase):
def setUp(self):
config = get_collector_config('FlumeCollector', {'interval': 10})
self.collector = FlumeCollector(config, None)
def test_import(self):
self.assertTrue(FlumeCollector)
(Collector, 'publish')
(Collector, 'publish_gauge')... |
class CategoricalConditionalBatchNorm2d(ConditionalBatchNorm2d):
def __init__(self, num_classes, num_features, eps=1e-05, momentum=0.1, affine=False, track_running_stats=True):
super(CategoricalConditionalBatchNorm2d, self).__init__(num_features, eps, momentum, affine, track_running_stats)
self.weig... |
class CheckCommand(Command):
name = 'check'
description = 'Validates the content of the <comment>pyproject.toml</> file and its consistency with the poetry.lock file.'
options = [option('lock', None, 'Checks that <comment>poetry.lock</> exists for the current version of <comment>pyproject.toml</>.')]
de... |
class TestAssertIs(TestCase):
def test_you(self):
self.assertIs(abc, 'xxx')
def test_me(self):
self.assertIs(123, (xxx + y))
self.assertIs(456, (aaa and bbb))
self.assertIs(789, (ccc or ddd))
self.assertIs(123, (True if You else False))
def test_everybody(self):
... |
def recall_cap(qrels: Dict[(str, Dict[(str, int)])], results: Dict[(str, Dict[(str, float)])], k_values: List[int]) -> Tuple[Dict[(str, float)]]:
capped_recall = {}
for k in k_values:
capped_recall[f'R_{k}'] = 0.0
k_max = max(k_values)
logging.info('\n')
for (query_id, doc_scores) in results... |
class DecoderSPP(nn.Module):
def __init__(self):
super().__init__()
self.conv = nn.Conv2d(256, 48, 1, bias=False)
self.bn = nn.BatchNorm2d(48)
self.relu = nn.ReLU(inplace=True)
self.sep1 = SeparableConv2d(304, 256, relu_first=False)
self.sep2 = SeparableConv2d(256, 25... |
class Model(nn.Module):
def __init__(self, config):
super(Model, self).__init__()
if (config.embedding_pretrained is not None):
self.embedding = nn.Embedding.from_pretrained(config.embedding_pretrained, freeze=False)
else:
self.embedding = nn.Embedding(config.n_vocab,... |
class CustomCategorical(Categorical):
def __init__(self, *args, **kwargs):
super(CustomCategorical, self).__init__(*args, **kwargs)
def log_prob(self, value):
logits_dim = self.logits.ndim
if (value.ndim == logits_dim):
assert (value.shape[(- 1)] == 1), f'Shape error {value.s... |
class _TAACFileMixin():
def test_basic(self):
self.song['title'] = 'SomeTestValue'
self.song.write()
self.song.reload()
self.assertEqual(self.song('title'), 'SomeTestValue')
def test_write(self):
self.song.write()
def test_can_change(self):
self.assertTrue(sel... |
class _BotUnpickler(pickle.Unpickler):
__slots__ = ('_bot',)
def __init__(self, bot: Bot, *args: Any, **kwargs: Any):
self._bot = bot
super().__init__(*args, **kwargs)
def persistent_load(self, pid: str) -> Optional[Bot]:
if (pid == _REPLACED_KNOWN_BOT):
return self._bot
... |
class PhaseFitEstimator(_VPEEstimator):
def __init__(self, evals: numpy.ndarray, ref_eval: float=0):
self.evals = evals
self.ref_eval = ref_eval
def get_simulation_points(self, safe: bool=True) -> numpy.ndarray:
if safe:
numsteps = (len(self.evals) * 2)
step_size ... |
class TestComment(unittest.TestCase):
def test_ok(self):
test_comment(POEntry(msgid='Hello, I am a test string'))
test_comment(POEntry(msgid='c', comment="TRANSLATORS: 'c' to continue"))
def test_no_comment(self):
self.assertRaises(AssertionError, test_comment, POEntry(msgid='c')) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.