code stringlengths 281 23.7M |
|---|
class ConfigTest(unittest.TestCase):
def setUp(self):
os.environ['DESTALINATOR_STRING_VARIABLE'] = 'test'
os.environ['DESTALINATOR_LIST_VARIABLE'] = 'test,'
def test_environment_variable_configs(self):
self.assertEqual(get_config().string_variable, 'test')
self.assertListEqual(ge... |
.parametrize(['ops', 'state'], [pytest.param(PZ, basis(2, 0), id='PZ_ket1'), pytest.param(PZ, basis(2, 1), id='PZ_ket2'), pytest.param(PZ, ket2dm(basis(2, 0)), id='PZ_dm1'), pytest.param(PZ, ket2dm(basis(2, 1)), id='PZ_dm2'), pytest.param(PZ_ket, basis(2, 0), id='PZket_ket1'), pytest.param(PZ_ket, basis(2, 1), id='PZke... |
class SEResNetBottleneck(Bottleneck):
expansion = 4
def __init__(self, inplanes, planes, groups, reduction, stride=1, downsample=None):
super(SEResNetBottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False, stride=stride)
self.bn1 = nn.BatchNorm2d(... |
def get_seq_without_gaps_at_index(seq, position):
start_idx = bisect.bisect_left(seq, position)
forward_gap = get_index_of_gap_in_sorted_integer_seq_forward(seq, start_idx)
reverse_gap = get_index_of_gap_in_sorted_integer_seq_reverse(seq, start_idx)
if (forward_gap is not None):
seq[:] = seq[:fo... |
def test_tsm_optimizer_constructor():
model = ExampleModel()
optimizer_cfg = dict(type='SGD', lr=base_lr, weight_decay=base_wd, momentum=momentum)
paramwise_cfg = dict(fc_lr5=True)
optim_constructor_cfg = dict(type='TSMOptimizerConstructor', optimizer_cfg=optimizer_cfg, paramwise_cfg=paramwise_cfg)
... |
def test_rotate_bounds_bottomright(view, item):
item.SELECT_RESIZE_SIZE = 10
item.SELECT_ROTATE_SIZE = 10
path = item.get_rotate_bounds(QtCore.QPointF(100, 80))
assert (path.boundingRect().topLeft().x() == 95)
assert (path.boundingRect().topLeft().y() == 75)
assert (path.boundingRect().bottomRig... |
class ProxiesOnDevice(Proxies):
def __init__(self) -> None:
super().__init__()
self.proxy_id_to_dev_mems: Dict[(int, Set[DeviceMemoryId])] = {}
self.dev_mem_to_proxy_ids: DefaultDict[(DeviceMemoryId, Set[int])] = defaultdict(set)
def mem_usage_add(self, proxy: ProxyObject) -> None:
... |
def canonicalized_query_string(params):
description_items = []
encoded_params = clean_params_dict(params, urlencode=True)
for item in sorted(encoded_params.keys()):
encoded_val = encoded_params[item]
description_items.append(f'{item}={encoded_val}')
return '&'.join(description_items) |
def train(model, training_data, validation_data, optimizer, scheduler, pred_loss_func, opt):
valid_event_losses = []
valid_pred_losses = []
valid_rmse = []
best_event_ll = (- 999999)
for epoch_i in range(opt.epoch):
epoch = (epoch_i + 1)
log_path = opt.log_path
with open(os.p... |
def unevaluatedProperties_draft2019(validator, uP, instance, schema):
if (not validator.is_type(instance, 'object')):
return
evaluated_keys = find_evaluated_property_keys_by_schema(validator, instance, schema)
unevaluated_keys = []
for property in instance:
if (property not in evaluated_... |
class TestAssert_reprcompare_namedtuple():
def test_namedtuple(self) -> None:
NT = collections.namedtuple('NT', ['a', 'b'])
left = NT(1, 'b')
right = NT(1, 'c')
lines = callequal(left, right)
assert (lines == ["NT(a=1, b='b') == NT(a=1, b='c')", '', 'Omitting 1 identical item... |
def check_repo_quality():
print('Checking all models are included.')
check_model_list()
print('Checking all models are public.')
check_models_are_in_init()
print('Checking all models are properly tested.')
check_all_decorator_order()
check_all_models_are_tested()
print('Checking all obje... |
class CallableObject(object):
__slots__ = ['_ob', '_func']
def __init__(self, c):
if (not hasattr(c, '__call__')):
raise ValueError('Error: given callback is not callable.')
if hasattr(c, '__self__'):
self._ob = weakref.ref(c.__self__)
self._func = c.__func__.... |
class BoxHead(object):
def __init__(self, cfgs):
self.cfgs = cfgs
def fpn_fc_head(self, roi_extractor, rois_list, feature_pyramid, img_shape, is_training, mode=0):
with tf.variable_scope('Fast-RCNN'):
with tf.variable_scope('rois_pooling'):
roi_features_list = []
... |
def CheckIncludeLine(filename, clean_lines, linenum, include_state, error):
fileinfo = FileInfo(filename)
line = clean_lines.lines[linenum]
if _RE_PATTERN_INCLUDE_NEW_STYLE.search(line):
error(filename, linenum, 'build/include_dir', 4, 'Include the directory when naming .h files')
match = _RE_PA... |
class ResSPP(nn.Module):
def __init__(self, c1=1024, c2=384, n=3, act='swish', k=(5, 9, 13)):
super(ResSPP, self).__init__()
c_ = c2
if (c2 == 1024):
c_ = (c2 // 2)
self.conv1 = ConvBNLayer(c1, c_, 1, act=act)
self.basicBlock_spp1 = BasicBlock(c_, c_, shortcut=Fal... |
def bin_xml_escape(arg: object) -> str:
def repl(matchobj: Match[str]) -> str:
i = ord(matchobj.group())
if (i <= 255):
return ('#x%02X' % i)
else:
return ('#x%04X' % i)
illegal_xml_re = '[^\t\n\r -~\x80-\ud7ff\ue000-0-FF]'
return re.sub(illegal_xml_re, repl, ... |
def clip_frames(unclipped: np.ndarray, clipped_num_frames: int) -> np.ndarray:
unclipped_num_frames = unclipped.shape[0]
if (unclipped_num_frames == clipped_num_frames):
return unclipped
assert (clipped_num_frames == (unclipped_num_frames - 1))
return unclipped[:clipped_num_frames] |
.parametrize('new_path,original_dictionary,output', [('/a', {}, {'/a': ['/']}), ('b', {'/a': ['some_path', 'another_path']}, {'/a': ['some_path', 'another_path'], '/b': ['/']}), ('/a/b/c/d', {'/e': ['some_path', 'another_path']}, {'/e': ['some_path', 'another_path'], '/a/b/c/d': ['/', '/a', '/a/b', '/a/b/c']})])
def te... |
('/v1/superuser/users/<namespace>/quota/<quota_id>', '/v1/superuser/organization/<namespace>/quota/<quota_id>')
_if(features.SUPER_USERS)
_if(features.QUOTA_MANAGEMENT)
class SuperUserUserQuota(ApiResource):
schemas = {'UpdateNamespaceQuota': {'type': 'object', 'description': 'Description of a new organization quot... |
def parse_args(argv: List[str]) -> argparse.Namespace:
parser = argparse.ArgumentParser(description='example TorchX captum app')
parser.add_argument('--load_path', type=str, help='checkpoint path to load model weights from', required=True)
parser.add_argument('--data_path', type=str, help='path to load the ... |
def create_channel_from_models(our_model, partner_model, partner_pkey):
channel_state = create(NettingChannelStateProperties(reveal_timeout=10, settle_timeout=100, our_state=NettingChannelEndStateProperties(address=our_model.participant_address, balance=our_model.balance, pending_locks=PendingLocksState(our_model.p... |
def test_lazy_gettext_defaultdomain():
app = flask.Flask(__name__)
babel.Babel(app, default_locale='de_DE', default_domain='test')
first = lazy_gettext('first')
with app.test_request_context():
assert (str(first) == 'erste')
get_babel(app).default_locale = 'en_US'
with app.test_request_c... |
def add_parse_opts(parser) -> None:
parser.add_argument('--raw_output', help="If set don't format output from kernel. If set to --raw_output=kunit, filters to just KUnit output.", type=str, nargs='?', const='all', default=None)
parser.add_argument('--json', nargs='?', help='Stores test results in a JSON, and ei... |
class Bleu():
def __init__(self, n=4):
self._n = n
self._hypo_for_image = {}
self.ref_for_image = {}
def compute_score(self, gts, res, verbose=1):
assert (gts.keys() == res.keys())
imgIds = gts.keys()
bleu_scorer = BleuScorer(n=self._n)
for id in imgIds:
... |
_grad()
def contrastive_evaluate(val_loader, model, memory_bank):
top1 = AverageMeter('', ':6.2f')
model.eval()
for batch in val_loader:
images = batch['image'].cuda(non_blocking=True)
target = batch['target'].cuda(non_blocking=True)
output = model(images)
output = memory_ban... |
def load_document_topics(opt, recover_topic_peaks, max_m=None):
filepaths1 = []
filepaths2 = []
topic_model_folder = get_topic_pred_folder(opt)
task = opt.get('tasks')[0]
subsets = opt.get('subsets')
for s in subsets:
filepaths1.append(os.path.join(topic_model_folder, (((task + '_') + s)... |
class TestMisc():
.trio
async def test_close_no_stop(self):
async with trio_asyncio.open_loop() as loop:
triggered = trio.Event()
def close_no_stop():
with pytest.raises(RuntimeError):
loop.close()
triggered.set()
lo... |
def test_sqliteio_write_inserts_new_pixmap_item_jpg(tmpfile, view):
item = BeePixmapItem(QtGui.QImage(), filename='bee.jpg')
view.scene.addItem(item)
item.pixmap_to_bytes = MagicMock(return_value=(b'abc', 'jpg'))
io = SQLiteIO(tmpfile, view.scene, create_new=True)
io.write()
assert (item.save_id... |
def _iload_all_spickle_internal(stream, offset=None):
if (offset is not None):
stream.seek(offset, 0)
else:
header = stream.read(512)
if (not header.startswith(b'SPICKLE')):
raise ValueError('Not a SPICKLE file.')
while True:
try:
(yield _load_one_spic... |
class AddressSpace(enum.IntEnum):
a16 = VI_A16_SPACE
a24 = VI_A24_SPACE
a32 = VI_A32_SPACE
a64 = VI_A64_SPACE
pxi_config = VI_PXI_CFG_SPACE
pxi_bar0 = VI_PXI_BAR0_SPACE
pxi_bar1 = VI_PXI_BAR1_SPACE
pxi_bar2 = VI_PXI_BAR2_SPACE
pxi_bar3 = VI_PXI_BAR3_SPACE
pxi_bar4 = VI_PXI_BAR4_S... |
class MatIO(fileio.FileIO):
FORMATS = ['mat']
MODES = ['r', 'w']
def __init__(self, *args, **kwargs):
self._varName = 'Unknown'
fileio.FileIO.__init__(self, *args, **kwargs)
self.file = open(self.dataPath, (self.mode + 'b'))
def _set_varName(self, val):
if issubclass(type... |
class Effect7046(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
fit.ship.boostItemAttr('explosiveDamageResonance', src.getModifiedItemAttr('eliteBonusFlagCruisers1'), skill='Flag Cruisers', **kwargs)
fit.ship.boostItemAttr('shieldKineticDamageResonance',... |
(params=['message', 'inline'])
def callback_query(bot, request):
cbq = CallbackQuery(TestCallbackQueryBase.id_, TestCallbackQueryBase.from_user, TestCallbackQueryBase.chat_instance, data=TestCallbackQueryBase.data, game_short_name=TestCallbackQueryBase.game_short_name)
cbq.set_bot(bot)
cbq._unfreeze()
i... |
class RobustLoss(torch.nn.Module):
def __init__(self, size, reg, geometry, tol=0.0001, max_iter=1000, debugging=False):
super().__init__()
self.size = size
self.reg = reg
self.geometry = geometry
self.tol = tol
self.max_iter = max_iter
self.debugging = debuggi... |
class FuzzyTestCase(unittest.TestCase):
test_dict = OrderedDict([(u'Hiya', 1), (u'hiya', 2), (u'test3', 3), (1, 324)])
def test_creation_empty(self):
fd = FuzzyDict()
self.assertEqual(fd, {})
def test_creation_dict(self):
fd = FuzzyDict(self.test_dict)
self.assertEqual(fd, se... |
def accuracy(pred, target, topk=1, thresh=None):
assert isinstance(topk, (int, tuple))
if isinstance(topk, int):
topk = (topk,)
return_single = True
else:
return_single = False
maxk = max(topk)
if (pred.size(0) == 0):
accu = [pred.new_tensor(0.0) for i in range(len(to... |
_model
def caformer_b36(pretrained=False, **kwargs):
model = MetaFormer(depths=[3, 12, 18, 3], dims=[128, 256, 512, 768], token_mixers=[SepConv, SepConv, Attention, Attention], head_fn=MlpHead, **kwargs)
model.default_cfg = default_cfgs['caformer_b36']
if pretrained:
state_dict = torch.hub.load_stat... |
.fast
def test_ignore_cached_files():
sf = SpectrumFactory(wavenum_min=2000, wavenum_max=3000, pressure=1)
file_dir = getTestFile('cdsd_hitemp_09_fragment.txt')
test_file = (file_dir[:(- 8)] + '*')
sf.load_databank(path=test_file, format='cdsd-hitemp', parfuncfmt='hapi')
try:
sf.load_databan... |
class Transaction():
def __init__(self, transaction_fill_time: datetime, ticker: Ticker, quantity: float, price: float, commission: float, trade_id=None, account=None, strategy=None, broker=None, currency=None):
assert (commission >= 0.0)
self.transaction_fill_time = transaction_fill_time
se... |
def test_create(monkeypatch):
created = {}
def spy(path, *_1, **_2):
created.update({path: True})
monkeypatch.setattr('pyscaffold.file_system.create_file', spy)
for contents in ('contents', ''):
path = uniqpath()
create(path, contents, {})
assert created[path]
path = ... |
def compose_transforms(meta, center_crop=True, new_imageSize=None, override_meta_imsize=False):
normalize = transforms.Normalize(mean=meta['mean'], std=meta['std'])
im_size = meta['imageSize']
if override_meta_imsize:
im_size = new_imageSize
assert (im_size[0] == im_size[1]), 'expected square im... |
class MESolver(SESolver):
name = 'mesolve'
_avail_integrators = {}
solver_options = {'progress_bar': '', 'progress_kwargs': {'chunk_size': 10}, 'store_final_state': False, 'store_states': None, 'normalize_output': True, 'method': 'adams'}
def __init__(self, H, c_ops=None, *, options=None):
_time... |
class Migration(migrations.Migration):
dependencies = [('tasks', '0019_meta')]
operations = [migrations.AddField(model_name='task', name='text_lang3', field=models.TextField(blank=True, help_text='The text for this task in the tertiary language.', null=True, verbose_name='Text (tertiary)')), migrations.AddField... |
def loadData(root_path):
dir_name = 'MULTIWOZ2.1'
shutil.copy(os.path.join(root_path, dir_name, 'data.json'), root_path)
shutil.copy(os.path.join(root_path, dir_name, 'ontology.json'), root_path)
shutil.copy(os.path.join(root_path, dir_name, 'valListFile.json'), root_path)
shutil.copy(os.path.join(r... |
class GCNModelSiemens(GCNModelVAE):
def __init__(self, placeholders, num_features, num_nodes, features_nonzero, **kwargs):
super(GCNModelSiemens, self).__init__(placeholders, num_features, num_nodes, features_nonzero, **kwargs)
def make_decoder(self):
self.l0 = Dense(input_dim=self.input_dim, ou... |
class MetaConv2d(MetaModule):
def __init__(self, *args, **kwargs):
super().__init__()
ignore = nn.Conv2d(*args, **kwargs)
self.in_channels = ignore.in_channels
self.out_channels = ignore.out_channels
self.stride = ignore.stride
self.padding = ignore.padding
se... |
class Bottleneck(nn.Module):
expansion = 4
__constants__ = ['downsample']
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=64, dilation=1, norm_layer=None):
super(Bottleneck, self).__init__()
if (norm_layer is None):
norm_layer = nn.BatchNorm2d... |
def status_change(names=PROPERTY_NAMES, values=PROPERTY_VALUES):
devices = st.sampled_from(['DA898B', 'F0D1BC', '94103EA2B277BD6E', '94103EA2B27751AB', ''])
capabilities = st.sampled_from(['10006', '10008', '30008', '30009', '3000A', '10300', '30301'])
device_id = st.sampled_from(['DeviceID', ElementWithAtt... |
class _FontStyleRunsRangeIterator():
def __init__(self, font_names, font_sizes, bolds, italics, stretch, dpi):
self.zip_iter = runlist.ZipRunIterator((font_names, font_sizes, bolds, italics, stretch))
self.dpi = dpi
def ranges(self, start, end):
from pyglet import font
for (start... |
class KnownValues(unittest.TestCase):
def test_gwac_pade(self):
nocc = (mol.nelectron // 2)
gw_obj = gw.GW(mf, freq_int='ac', frozen=0)
gw_obj.linearized = False
gw_obj.ac = 'pade'
gw_obj.kernel(orbs=range((nocc - 3), (nocc + 3)))
self.assertAlmostEqual(gw_obj.mo_ener... |
def checksum(filename, chkname, buffering=None):
res = None
buf = (buffering or blksize(filename))
if (chkname in ('adler32', 'crc32')):
res = _crcsum(filename, chkname, buf)
elif (chkname in hashlib.algorithms_available):
res = _hashsum(filename, chkname, buf)
return res |
class TID3Header(TestCase):
silence = os.path.join(DATA_DIR, 'silence-44-s.mp3')
empty = os.path.join(DATA_DIR, 'emptyfile.mp3')
def test_header_empty(self):
with open(self.empty, 'rb') as fileobj:
self.assertRaises(ID3Error, ID3Header, fileobj)
def test_header_silence(self):
... |
class OutputEvent(OutputView):
placeholder = None
label = None
event_connector = None
def __init__(self, name, event_connector, *args, **kwargs):
self.event_connector = event_connector
gui.SvgSubcontainer.__init__(self, 0, 0, 0, 0, *args, **kwargs)
self.placeholder = gui.SvgRecta... |
def test_run_pyscript_with_exception(base_app, request):
test_dir = os.path.dirname(request.module.__file__)
python_script = os.path.join(test_dir, 'pyscript', 'raises_exception.py')
(out, err) = run_cmd(base_app, 'run_pyscript {}'.format(python_script))
assert err[0].startswith('Traceback')
assert ... |
def patch_model_repository_get_repository(monkeypatch, get_repository):
if (get_repository is not None):
def mock_get_repository(base_namespace, base_repository):
vis_mock = Mock()
vis_mock.name = get_repository
get_repo_mock = Mock(visibility=vis_mock)
return... |
class LazilyParsedConfig():
def __init__(self, config: dict, steps: tuple=()):
self.raw_data = config
self.steps = steps
def parse_fields(self):
for attribute in self.__dict__:
(_, prefix, name) = attribute.partition('_field_')
if prefix:
parse_con... |
class SeznamOAuth2Test(OAuth2Test):
backend_path = 'social_core.backends.seznam.SeznamOAuth2'
user_data_url = '
expected_username = 'krasty'
access_token_body = json.dumps({'access_token': 'foo', 'account_name': '', 'expires_in': , 'oauth_user_id': '0123abcd', 'refresh_token': 'bar', 'scopes': ['identit... |
def test_schemafile_and_instancefile(runner, mock_parse_result, in_tmp_dir, tmp_path):
touch_files(tmp_path, 'foo.json')
runner.invoke(cli_main, ['--schemafile', 'schema.json', 'foo.json'])
assert (mock_parse_result.schema_mode == SchemaLoadingMode.filepath)
assert (mock_parse_result.schema_path == 'sch... |
def test_detect_clearsky_components(detect_clearsky_data):
(expected, cs) = detect_clearsky_data
(clear_samples, components, alpha) = clearsky.detect_clearsky(expected['GHI'], cs['ghi'], times=cs.index, window_length=10, return_components=True)
assert_series_equal(expected['Clear or not'], clear_samples, ch... |
def test_sudo_fail_from_root(host):
assert (host.user().name == 'root')
with pytest.raises(AssertionError) as exc:
with host.sudo('unprivileged'):
assert (host.user().name == 'unprivileged')
host.check_output('ls /root/invalid')
assert str(exc.value).startswith('Unexpected ex... |
def ql_syscall_bind(ql: Qiling, sockfd: int, addr: int, addrlen: int):
if (sockfd not in range(NR_OPEN)):
return (- 1)
sock: Optional[ql_socket] = ql.os.fd[sockfd]
if (sock is None):
return (- 1)
data = ql.mem.read(addr, addrlen)
abits = ql.arch.bits
endian = ql.arch.endian
s... |
def paginate(start_id_kwarg_name='start_id', limit_kwarg_name='limit', callback_kwarg_name='pagination_callback'):
def wrapper(func):
(func)
def wrapped(*args, **kwargs):
try:
requested_limit = int(request.args.get('n', _MAX_RESULTS_PER_PAGE))
except ValueErro... |
class CheckpointDataLoader(DataLoader):
def __init__(self, dataset, checkpoint=None, batch_size=1, shuffle=False, num_workers=0, pin_memory=False, drop_last=True, timeout=0, worker_init_fn=None):
if shuffle:
sampler = RandomSampler(dataset, checkpoint)
else:
sampler = Sequent... |
class Solution(object):
def insertionSortList(self, head):
if (head is None):
return None
helper = ListNode((- 1000))
(pre, curr) = (helper, head)
while (curr is not None):
next_step = curr.next
while (pre.next and (pre.next.val < curr.val)):
... |
def est_dof_support(coef, intercept=None, transform=None, zero_tol=1e-06):
coef = np.array(coef)
if (transform is None):
n_nonzero_coef = count_support(coef, zero_tol=zero_tol)
else:
n_nonzero_coef = count_support(transform(coef), zero_tol=zero_tol)
if (intercept is not None):
n_... |
class _WebEngineScripts(QObject):
_widget: webview.WebEngineView
def __init__(self, tab, parent=None):
super().__init__(parent)
self._tab = tab
self._widget = cast(webview.WebEngineView, None)
self._greasemonkey = greasemonkey.gm_manager
def connect_signals(self):
con... |
class SwishJitAutoFn(torch.autograd.Function):
def symbolic(g, x):
return g.op('Mul', x, g.op('Sigmoid', x))
def forward(ctx, x):
ctx.save_for_backward(x)
return swish_jit_fwd(x)
def backward(ctx, grad_output):
x = ctx.saved_tensors[0]
return swish_jit_bwd(x, grad_out... |
def get_purpose_features(repo_path, branch):
repo = Repository(repo_path)
head = repo.references.get(branch)
commits = list(repo.walk(head.target, (GIT_SORT_TOPOLOGICAL | GIT_SORT_REVERSE)))
features = []
for (_, commit) in enumerate(tqdm(commits)):
message = commit.message
fix = (1.... |
class HierarchicalConcurrent(nn.Sequential):
def __init__(self, axis=1):
super(HierarchicalConcurrent, self).__init__()
self.axis = axis
def forward(self, x):
out = []
y_prev = None
for module in self._modules.values():
y = module(x)
if (y_prev is ... |
def check_changelog_urls(_args: argparse.Namespace=None) -> bool:
ok = True
all_requirements = set()
for name in recompile_requirements.get_all_names():
outfile = recompile_requirements.get_outfile(name)
missing = set()
with open(outfile, 'r', encoding='utf-8') as f:
for ... |
def _worker_rollout_policy(G, args):
sample_std = args['sample_std'].flatten()
cur_mean = args['cur_mean'].flatten()
K = len(cur_mean)
params = ((np.random.standard_normal(K) * sample_std) + cur_mean)
G.policy.set_param_values(params)
path = rollout(G.env, G.policy, args['max_path_length'])
... |
class Lingeling(object):
def __init__(self, bootstrap_with=None, use_timer=False, incr=False, with_proof=False, warm_start=False):
if incr:
raise NotImplementedError('Incremental mode is not supported by Lingeling.')
if warm_start:
raise NotImplementedError('Warm-start mode i... |
def test_apply_patcher_file_newer_version(tmp_path):
patcher_data = {}
randomizer_data = {}
progress_update = MagicMock()
game_root = tmp_path.joinpath('game_root')
game_root.mkdir()
claris_randomizer._patch_version_file(game_root).write_text(str(10000))
with pytest.raises(UnableToExportErro... |
def construct_outgoing_unicast_answers(answers: _AnswerWithAdditionalsType, ucast_source: bool, questions: List[DNSQuestion], id_: int_) -> DNSOutgoing:
out = DNSOutgoing(_FLAGS_QR_RESPONSE_AA, False, id_)
if ucast_source:
for question in questions:
out.add_question(question)
_add_answer... |
class TestCustomBuildPy():
FILES = {**TestOverallBehaviour.EXAMPLES['flat-layout'], 'setup.py': dedent(' import pathlib\n from setuptools import setup\n from setuptools.command.build_py import build_py as orig\n\n class my_build_py(orig):\n def run(self):\n... |
def convert_xlm_roberta_xl_checkpoint_to_pytorch(roberta_checkpoint_path: str, pytorch_dump_folder_path: str, classification_head: bool):
roberta = FairseqRobertaModel.from_pretrained(roberta_checkpoint_path)
roberta.eval()
roberta_sent_encoder = roberta.model.encoder.sentence_encoder
config = XLMRobert... |
.parametrize('username,password', users)
.parametrize('snapshot_id', snapshots)
def test_list_snapshot(db, client, username, password, snapshot_id):
client.login(username=username, password=password)
url = (reverse(urlnames['list']) + f'?snapshot={snapshot_id}')
response = client.get(url)
if password:
... |
.parametrize(('pyproject_toml', 'parse_output'), [({'build-system': {'requires': ['foo']}}, {'requires': ['foo'], 'build-backend': 'setuptools.build_meta:__legacy__'}), ({'build-system': {'requires': ['foo'], 'build-backend': 'bar'}}, {'requires': ['foo'], 'build-backend': 'bar'}), ({'build-system': {'requires': ['foo'... |
def import_tf():
warnings.filterwarnings('ignore', category=FutureWarning)
try:
import tensorflow as tf
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
module = tf
except ImportError:
module = None
warnings.filterwarnings('default', category=FutureWarning)
... |
class ImageValidator(ContentTypeValidator):
def __init__(self, minimum: Dimension=None, maximum: Dimension=None, content_types=None, min_aspect_ratio: float=None, max_aspect_ratio: float=None):
(self.min_width, self.min_height) = (minimum if minimum else (0, 0))
(self.max_width, self.max_height) = (... |
def create_shared(name, initial_value, dtype='floatX', strict=False, allow_downcast=True):
if (dtype == 'floatX'):
dtype = theano.config.floatX
initial_value = np.ascontiguousarray(initial_value, dtype=dtype)
variable = theano.shared(initial_value, name=name, strict=strict, allow_downcast=allow_down... |
def test_history_expanded(base_app):
cmds = ['alias create s shortcuts', 's']
for cmd in cmds:
run_cmd(base_app, cmd)
(out, err) = run_cmd(base_app, 'history -x')
expected = [' 1 alias create s shortcuts', ' 2 shortcuts']
assert (out == expected)
verify_hi_last_result(base_app, 2... |
(eq=False, hash=False, slots=True, repr=False)
class RunVar(Generic[T]):
_name: str = attr.ib()
_default: (T | type[_NoValue]) = attr.ib(default=_NoValue)
def get(self, default: (T | type[_NoValue])=_NoValue) -> T:
try:
return cast(T, _run.GLOBAL_RUN_CONTEXT.runner._locals[self])
... |
def main() -> None:
application = Application.builder().token('TOKEN').build()
application.add_handler(CommandHandler('start', start))
application.add_handler(CommandHandler('bad_command', bad_command))
application.add_error_handler(error_handler)
application.run_polling(allowed_updates=Update.ALL_T... |
def NMC_electrolyte_exchange_current_density_PeymanMPM(c_e, c_s_surf, c_s_max, T):
m_ref = (4.824 * (10 ** (- 6)))
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 instantiate_generator_class(builder: IRBuilder) -> Value:
fitem = builder.fn_info.fitem
generator_reg = builder.add(Call(builder.fn_info.generator_class.ir.ctor, [], fitem.line))
if builder.fn_info.is_nested:
curr_env_reg = builder.fn_info.callable_class.curr_env_reg
else:
curr_env_r... |
class CPD_VGG(nn.Module):
def __init__(self, channel=32):
super(CPD_VGG, self).__init__()
self.vgg = B2_VGG()
self.rfb3_1 = RFB(256, channel)
self.rfb4_1 = RFB(512, channel)
self.rfb5_1 = RFB(512, channel)
self.agg1 = aggregation(channel)
self.rfb3_2 = RFB(256... |
def start_server_in_current_thread_session():
websocket_conn_opened = threading.Event()
thread = threading.current_thread()
class SingleSessionWSHandler(_webio_handler(cdn=False)):
session: ScriptModeSession = None
instance: typing.ClassVar = None
closed = False
def send_msg_... |
class NgramCounts():
def __init__(self, ngram_order, bos_symbol='<s>', eos_symbol='</s>'):
assert (ngram_order >= 2)
self.ngram_order = ngram_order
self.bos_symbol = bos_symbol
self.eos_symbol = eos_symbol
self.counts = []
for n in range(ngram_order):
self... |
class InvalidHeader(InvalidHandshake):
def __init__(self, name: str, value: Optional[str]=None) -> None:
self.name = name
self.value = value
def __str__(self) -> str:
if (self.value is None):
return f'missing {self.name} header'
elif (self.value == ''):
re... |
class TestChangeActivePointerGrab(EndianTest):
def setUp(self):
self.req_args_0 = {'cursor': , 'event_mask': 36287, 'time': }
self.req_bin_0 = b'\x1e\x00\x04\x00\x8f\r\xd7<fV3y\xbf\x8d\x00\x00'
def testPackRequest0(self):
bin = request.ChangeActivePointerGrab._request.to_binary(*(), **se... |
def train_ram_plus(model, data_loader, optimizer, epoch, device, config, model_clip):
model.train()
metric_logger = utils.MetricLogger(delimiter=' ')
metric_logger.add_meter('lr', utils.SmoothedValue(window_size=50, fmt='{value:.6f}'))
metric_logger.add_meter('loss_tag', utils.SmoothedValue(window_size... |
_model_architecture('masked_lm', 'bert_large')
def bert_large_architecture(args):
args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 1024)
args.encoder_layers = getattr(args, 'encoder_layers', 24)
args.encoder_attention_heads = getattr(args, 'encoder_attention_heads', 16)
args.encoder_ffn_embed... |
class TestCounter(TestCase):
def test_dump_counter(self):
c = Counter('A counter is something that counts!')
dumped = jsons.dump(c)
expected = {'A': 1, ' ': 5, 'c': 2, 'o': 3, 'u': 2, 'n': 3, 't': 5, 'e': 2, 'r': 1, 'i': 2, 's': 3, 'm': 1, 'h': 2, 'g': 1, 'a': 1, '!': 1}
self.assertD... |
def test_main_reads_config_values(mirror_mock: mock.MagicMock, tmpdir: Path) -> None:
base_config_path = (Path(bandersnatch.__file__).parent / 'unittest.conf')
diff_file = (Path(tempfile.gettempdir()) / 'srv/pypi/mirrored-files')
config_lines = [(f'''diff-file = {diff_file.as_posix()}
''' if line.startswith... |
class TPadding(TestCase):
def setUp(self):
self.b = Padding((b'\x00' * 100))
def test_padding(self):
self.failUnlessEqual(self.b.write(), (b'\x00' * 100))
def test_blank(self):
self.failIf(Padding().write())
def test_empty(self):
self.failIf(Padding(b'').write())
def ... |
class SponsorshipsBenefitsFormTests(TestCase):
def setUp(self):
self.current_year = SponsorshipCurrentYear.get_year()
self.psf = baker.make('sponsors.SponsorshipProgram', name='PSF')
self.wk = baker.make('sponsors.SponsorshipProgram', name='Working Group')
self.program_1_benefits = b... |
class Mlp(nn.Module):
def __init__(self, dim, mlp_ratio=4, out_features=None, act_layer=StarReLU, drop=0.0, bias=False, **kwargs):
super().__init__()
in_features = dim
out_features = (out_features or in_features)
hidden_features = int((mlp_ratio * in_features))
drop_probs = t... |
class ModuleHelper(object):
def BNReLU(num_features, norm_type=None, **kwargs):
if (norm_type == 'batchnorm'):
return nn.Sequential(nn.BatchNorm2d(num_features, **kwargs), nn.ReLU())
elif (norm_type == 'encsync_batchnorm'):
from encoding.nn import BatchNorm2d
retu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.