code stringlengths 281 23.7M |
|---|
(cache_hash=True)
class ReflectionUsingPrepare(GateWithRegisters):
prepare_gate: PrepareOracle
control_val: Optional[int] = None
_property
def control_registers(self) -> Tuple[(Register, ...)]:
return (() if (self.control_val is None) else (Register('control', 1),))
_property
def selecti... |
def _check_const_name(node_type: str, name: str) -> List[str]:
error_msgs = []
if (not _is_in_upper_case_with_underscores(name)):
msg = f'{node_type.capitalize()} name "{name}" should be in UPPER_CASE_WITH_UNDERSCORES format. Constants should be all-uppercase words with each word separated by an undersc... |
.parametrize('width, height, minsize, expected', [(256, 256, 256, 0), (257, 257, 256, 1), (1000, 1000, 128, 3), (1000, 100, 128, 0)])
def test_max_overview(width, height, minsize, expected):
overview_level = get_maximum_overview_level(width, height, minsize)
assert (overview_level == expected) |
class ProjectQuerySet(TreeQuerySet):
def filter_current_site(self):
return self.filter(site=settings.SITE_ID)
def filter_user(self, user):
if user.is_authenticated:
if user.has_perm('projects.view_project'):
return self.all()
elif is_site_manager(user):
... |
def get_target(args):
target = Image.open(args.target)
if (target.mode == 'RGBA'):
new_image = Image.new('RGBA', target.size, 'WHITE')
new_image.paste(target, (0, 0), target)
target = new_image
target = target.convert('RGB')
(masked_im, mask) = utils.get_mask_u2net(args, target)
... |
class EditIntWindow(sd.Dialog):
def __init__(self, parent, configitem, current):
self.parent = parent
self.config_item = configitem
self.current = current
sd.Dialog.__init__(self, parent, 'Edit integer configuration')
def body(self, master):
self.configure(background=GetB... |
.skipif((not _has_h5py), reason='h5py not found.')
class TestH5Serialization():
def worker(cls, cyberbliptronics, q1, q2):
assert isinstance(cyberbliptronics, PersistentTensorDict)
assert cyberbliptronics.file.filename.endswith('groups.hdf5')
q1.put(cyberbliptronics['Base_Group'][('Sub_Group... |
('/json/save_config', methods=['POST'], endpoint='save_config')
_required('SETTINGS')
def save_config():
api = flask.current_app.config['PYLOAD_API']
category = flask.request.args.get('category')
if (category not in ('core', 'plugin')):
return (jsonify(False), 500)
for (key, value) in flask.requ... |
class NominationViewSet(CreateModelMixin, RetrieveModelMixin, ListModelMixin, GenericViewSet):
serializer_class = NominationSerializer
queryset = Nomination.objects.all().prefetch_related('entries')
filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter)
filterset_fields = ('user__id', 'ac... |
def install_minimum(c):
with open('setup.py', 'r') as setup_py:
lines = setup_py.read().splitlines()
versions = []
started = False
for line in lines:
if started:
if (line == ']'):
started = False
continue
line = line.strip()
... |
.skipif((not HAVE_DEPS_FOR_RESOURCE_ESTIMATES), reason='pyscf and/or jax not installed.')
def test_generate_costing_table_df():
mf = make_diamond_113_szv()
thresh = np.array([0.1, 0.01, 1e-14])
table = generate_costing_table(mf, cutoffs=thresh, chi=10, beta=22, dE_for_qpe=0.001)
assert np.allclose(table... |
class QUBEKitHandler(vdWHandler):
hfree = ParameterAttribute((0 * unit.angstroms), unit=unit.angstroms)
xfree = ParameterAttribute((0 * unit.angstroms), unit=unit.angstroms)
cfree = ParameterAttribute((0 * unit.angstroms), unit=unit.angstroms)
nfree = ParameterAttribute((0 * unit.angstroms), unit=unit.a... |
def load_the_parser(parser_module_name):
logger.debug('starting')
parser_module = pypyr.moduleloader.get_module(parser_module_name)
logger.debug('context parser module found: %s', parser_module_name)
try:
get_parsed_context = getattr(parser_module, 'get_parsed_context')
except AttributeError... |
.parametrize('locale', ('ru', 'pl'))
def test_gettext_compilation(locale):
ru_rules = localedata.load(locale)['plural_form'].rules
chars = 'ivwft'
assert any(((f' {ch} ' in rule) for ch in chars for rule in ru_rules.values()))
ru_rules_gettext = plural.to_gettext(ru_rules)
assert (not any(((ch in ru... |
def _migrate_v47(preset: dict) -> dict:
if (preset['game'] == 'prime1'):
preset['configuration'].pop('deterministic_idrone')
preset['configuration'].pop('deterministic_maze')
preset['configuration'].pop('qol_game_breaking')
preset['configuration'].pop('qol_pickup_scans')
pres... |
class SOCKETCALL(IntEnum):
SYS_SOCKET = 1
SYS_BIND = 2
SYS_CONNECT = 3
SYS_LISTEN = 4
SYS_ACCEPT = 5
SYS_GETSOCKNAME = 6
SYS_GETPEERNAME = 7
SYS_SOCKETPAIR = 8
SYS_SEND = 9
SYS_RECV = 10
SYS_SENDTO = 11
SYS_RECVFROM = 12
SYS_SHUTDOWN = 13
SYS_SETSOCKOPT = 14
S... |
def Gen_I(FP, ItemS):
global CanNum
Item = FP[:]
ExpSet = []
for i in range(len(Item)):
for j in range((i + 1), len(Item)):
pre = Item[i]
suf = Item[j]
p = []
p.append(pre[0])
p.append(suf[0])
CanNum += 1
(count,... |
def train_generate_(dataset, batch_size, few, symbol2id, ent2id, e1rel_e2, num_neg=1):
logging.info('LOADING TRAINING DATA')
train_tasks = json.load(open((dataset + '/train_tasks.json')))
logging.info('LOADING CANDIDATES')
rel2candidates = json.load(open((dataset + '/rel2candidates.json')))
task_poo... |
class Test_ChangeAttributes(unittest.TestCase):
def setUp(self):
self.s = serial.serial_for_url(PORT, do_not_open=True)
def tearDown(self):
self.s.close()
def test_PortSetting(self):
self.s.port = PORT
self.assertEqual(self.s.portstr.lower(), PORT.lower())
self.assert... |
class TestAccountOverviewView(TestCase):
def setUp(self):
self.email = ''
self.name = 'Test User'
self.user = get(get_user_model(), name=self.name, email=self.email)
self.url = reverse('account')
self.client.force_login(self.user)
def test_logged_out(self):
self.c... |
class InteractionBroker(object):
def __init__(self, peer1, peer2, poll_interval=1):
self.peers = (peer1, peer2)
self.poll_interval = poll_interval
def interact(self):
directions = (self.peers, tuple(reversed(self.peers)))
while True:
start = time.time()
fo... |
def test_plugin_does_not_interfere_with_doctest_collection(pytester: Pytester):
pytester.makepyfile(dedent(' def any_function():\n """\n >>> 42\n 42\n """\n '))
result = pytester.runpytest('--asyncio-mode=strict', '--doctest-modul... |
class Migration(migrations.Migration):
dependencies = [('comms', '0010_auto__1912')]
operations = [migrations.AlterField(model_name='channeldb', name='db_attributes', field=models.ManyToManyField(help_text='attributes on this object. An attribute can hold any pickle-able python object (see docs for special case... |
(web_fixture=WebFixture)
class AddressAppFixture(Fixture):
def new_browser(self):
return Browser(self.web_fixture.new_wsgi_app(site_root=AddressBookUI))
def new_existing_address(self):
address = Address(name='John Doe', email_address='')
address.save()
return address
def is_o... |
def test_default_sort_key(cmd2_app):
text = ''
line = 'test_sort_key {}'.format(text)
endidx = len(line)
begidx = (endidx - len(text))
cmd2_app.default_sort_key = cmd2.Cmd.ALPHABETICAL_SORT_KEY
expected = ['1', '11', '2']
first_match = complete_tester(text, line, begidx, endidx, cmd2_app)
... |
def get_data(stock_symbol, financial_metrics, source):
template = 'Between >>> and <<< are the content from HTML.\n The website contains company financial information.\n Extract the answer to the question \'{query}\' or say "not found" if the information is not contained\n Make sure to remove commas and in... |
class BasisFamily():
def __init__(self, N):
self.N = N
self.nvars = None
self.coef_offset = [0]
self.coef_length = [N]
def __repr__(self):
return (f'<{self.__class__.__name__}: nvars={self.nvars}, ' + f'N={self.N}>')
def __call__(self, i, t, var=None):
return ... |
class TestInterpolated(BaseTestDistributionRandom):
def interpolated_rng_fn(self, size, mu, sigma, rng):
return st.norm.rvs(loc=mu, scale=sigma, size=size)
pymc_dist = pm.Interpolated
mu = sigma = 1
x_points = pdf_points = np.linspace(1, 100, 100)
pymc_dist_params = {'x_points': x_points, 'p... |
def test_text_formatting_function(capsys: pytest.CaptureFixture[str]) -> None:
def format_text(seconds: float) -> str:
return f'Function: {(seconds + 1):.0f}'
with Timer(text=format_text):
waste_time()
(stdout, stderr) = capsys.readouterr()
assert (stdout.strip() == 'Function: 1')
as... |
class Effect8229(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Gas Cloud Harvesting')), 'duration', ship.getModifiedItemAttr('miningBargeBonusGasHarvestingDuration'), skill='Mining Barge', **kw... |
class Effect5503(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.drones.filteredItemBoost((lambda drone: drone.item.requiresSkill('Drones')), 'trackingSpeed', ship.getModifiedItemAttr('eliteBonusCommandShips2'), skill='Command Ships', **kwargs) |
def set_args():
parser = argparse.ArgumentParser()
parser.add_argument('--model', default='bert', type=str, required=False, help='')
parser.add_argument('--problem_type', default='single_label_classification', type=str, required=False, help='')
parser.add_argument('--dir_name', default='xinwen', type=st... |
class Polygon(ShapeBase):
def __init__(self, *coordinates, color=(255, 255, 255, 255), batch=None, group=None):
self._rotation = 0
self._coordinates = list(coordinates)
(self._x, self._y) = self._coordinates[0]
self._num_verts = ((len(self._coordinates) - 2) * 3)
(r, g, b, *a... |
class TestRole():
def test_creation(self, parent_role):
r = Role(child_roles=[parent_role, parent_role])
assert (r.chat_ids == set())
assert (str(r) == 'Role({})')
assert (r.child_roles == {parent_role})
assert isinstance(r._admin, Role)
assert (str(r._admin) == f'Rol... |
def make_servicer(echo_pb2, echo_grpc):
class Servicer(echo_grpc.EchoServicer):
async def Echo(self, message):
return echo_pb2.EchoReply(data=message.data)
async def EchoTwoTimes(self, message):
(yield echo_pb2.EchoReply(data=message.data))
(yield echo_pb2.EchoRep... |
def create_contour(series_slice: Dataset, contour_data: np.ndarray) -> Dataset:
contour_image = Dataset()
contour_image.ReferencedSOPClassUID = series_slice.SOPClassUID
contour_image.ReferencedSOPInstanceUID = series_slice.SOPInstanceUID
contour_image_sequence = Sequence()
contour_image_sequence.app... |
_cli(name='reduce')
('reduce', cls=cli_tools.DocumentedCommand, section='Traversals', short_help='Reduce a sequence with a function like ``operator.mul``.', help=reduce.__doc__)
_exec_before
('function_name')
def _reduce(function_name, **parameters):
return [{'code': f'toolz.curry({function_name})', 'name': 'reduce... |
class WinnowResNet18Test(unittest.TestCase):
def test_winnowing_multiple_zeroed_resnet34(self):
model = models.resnet34(pretrained=False)
model.eval()
input_shape = [1, 3, 224, 224]
list_of_modules_to_winnow = []
input_channels_to_prune = [5, 9, 14, 18, 23, 27, 32, 36, 41, 45... |
.skipif((not PY_3_8_PLUS), reason='cached_property is 3.8+')
def test_slots_cached_property_called_independent_across_instances():
(slots=True)
class A():
x = attr.ib()
_property
def f(self):
return self.x
obj_1 = A(1)
obj_2 = A(2)
assert (obj_1.f == 1)
assert... |
def _parse_qsl(qs):
r = []
for pair in qs.replace(';', '&').split('&'):
if (not pair):
continue
nv = pair.split('=', 1)
if (len(nv) != 2):
nv.append('')
key = urlunquote(nv[0].replace('+', ' '))
value = urlunquote(nv[1].replace('+', ' '))
r... |
def write_to_tsv(output_file: str, data: Dict[(str, str)]):
with open(output_file, 'w') as fOut:
writer = csv.writer(fOut, delimiter='\t', quoting=csv.QUOTE_MINIMAL)
writer.writerow(['query-id', 'corpus-id', 'score'])
for (query_id, corpus_dict) in data.items():
for (corpus_id, s... |
(bind=True, base=StatsTask)
def ptt_monthly_summary(self, year, month) -> Dict:
logger.info('Get monthly summary: %s-%s', year, month)
daily_summaries = self.sess.query(func.year(PttPost.created_at), func.month(PttPost.created_at), func.day(PttPost.created_at), func.count(PttPost.id)).filter((func.year(PttPost.... |
class FitBert():
def __init__(self, model=None, tokenizer=None, model_name='bert-large-uncased', mask_token='***mask***', disable_gpu=False):
self.mask_token = mask_token
self.delemmatizer = Delemmatizer()
self.device = torch.device(('cuda' if (torch.cuda.is_available() and (not disable_gpu)... |
class TestFCIDumpH2(QiskitNatureTestCase, BaseTestFCIDump):
def setUp(self):
super().setUp()
self.nuclear_repulsion_energy = 0.7199
self.num_molecular_orbitals = 2
self.num_alpha = 1
self.num_beta = 1
self.mo_onee = np.array([[1.2563, 0.0], [0.0, 0.4719]])
sel... |
class AllowedValueRangeType(GeneratedsSuper):
__hash__ = GeneratedsSuper.__hash__
subclass = None
superclass = None
def __init__(self, minimum=None, maximum=None, step=None, gds_collector_=None, **kwargs_):
self.gds_collector_ = gds_collector_
self.gds_elementtree_node_ = None
se... |
_model
def test_multibonds():
Monomer('A', ['a'])
Monomer('B', ['b'])
Parameter('k1', 100)
Parameter('A_0', 200)
Parameter('B_0', 50)
Rule('r1', (((A(a=None) + A(a=None)) + B(b=None)) >> ((A(a=1) % A(a=[1, 2])) % B(b=2))), k1)
Initial(A(a=None), A_0)
Initial(B(b=None), B_0)
generate_... |
class AutoEncoder(nn.Module):
def __init__(self, args):
super(AutoEncoder, self).__init__()
self.args = args
self.input_dim = args.input_dim
self.output_dim = self.input_dim
self.hidden_dims = args.hidden_dims
self.hidden_dims.append(args.latent_dim)
self.dims... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--base_dir', default='.')
parser.add_argument('--output', default='training')
parser.add_argument('--dataset', default='ljspeech', choices=['blizzard', 'ljspeech', 'blizzard2013'])
parser.add_argument('--num_workers', type=int, defa... |
class InlineQueryHandler(BaseHandler[(Update, CCT)]):
__slots__ = ('pattern', 'chat_types')
def __init__(self, callback: HandlerCallback[(Update, CCT, RT)], pattern: Optional[Union[(str, Pattern[str])]]=None, block: DVType[bool]=DEFAULT_TRUE, chat_types: Optional[List[str]]=None):
super().__init__(callb... |
def get_multi_hop_model(rnn_dim, c2c: bool, q2c: bool, res_rnn: bool, res_self_att: bool, post_merge: bool, encoder: str, merge_type: str, num_c2c_hops: int):
recurrent_layer = CudnnGru(rnn_dim, w_init=TruncatedNormal(stddev=0.05))
answer_encoder = BinaryAnswerEncoder()
res_model = get_res_fc_seq_fc(model_r... |
def main(args):
IMAGENET_MEAN = [0.485, 0.456, 0.406]
IMAGENET_STD = [0.229, 0.224, 0.225]
transform = [T.ToTensor()]
transform.append(T.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD))
im_transform = T.Compose(transform)
orig_images = os.listdir(args.orig_image_path)
N = len(orig_images)
... |
class Effect2296(BaseEffect):
type = 'passive'
def handler(fit, booster, context, projectionRange, **kwargs):
for (srcResType, tgtResType) in (('Em', 'Em'), ('Explosive', 'Explosive'), ('Kinetic', 'Kinetic'), ('Thermic', 'Thermal')):
fit.ship.boostItemAttr(f'armor{tgtResType}DamageResonance'... |
class Event(object):
def __init__(self, raw):
self.raw = raw
self.from_user = False
self.from_chat = False
self.from_group = False
self.from_me = False
self.to_me = False
self.attachments = {}
self.message_data = None
self.message_id = None
... |
class GitlabCLI():
def __init__(self, gl: gitlab.Gitlab, gitlab_resource: str, resource_action: str, args: Dict[(str, str)]) -> None:
self.cls: Type[gitlab.base.RESTObject] = cli.gitlab_resource_to_cls(gitlab_resource, namespace=gitlab.v4.objects)
self.cls_name = self.cls.__name__
self.gitla... |
_model
def test_complex_pattern_equivalence_bond_state():
Monomer('A', ['s'], {'s': ['x', 'y', 'z']})
cp0 = (A(s=('x', 1)) % A(s=('y', 1)))
cp1 = (A(s=('y', 1)) % A(s=('x', 1)))
cp2 = (A(s=('z', 1)) % A(s=('y', 1)))
cp3 = (A(s='x') % A(s='y'))
_check_pattern_equivalence((cp0, cp1))
_check_pa... |
def p2g(model: MPMModelStruct, state_in: MPMStateStruct, state_out: MPMStateStruct, gravity: wp.vec3, dt: float):
p = wp.tid()
contact_force = state_in.particle_f[p]
x = state_in.particle_q[p]
x = (x - (wp.vec3(float(state_in.grid_lower[0]), float(state_in.grid_lower[1]), float(state_in.grid_lower[2])) ... |
def main():
Format()
a = Matrix(2, 2, (1, 2, 3, 4))
b = Matrix(2, 1, (5, 6))
c = (a * b)
print(a, b, '=', c)
(x, y) = symbols('x, y')
d = Matrix(1, 2, ((x ** 3), (y ** 3)))
e = Matrix(2, 2, ((x ** 2), ((2 * x) * y), ((2 * x) * y), (y ** 2)))
f = (d * e)
print('%', d, e, '=', f)
... |
def total_processes_number(local_rank):
if is_torch_tpu_available():
import torch_xla.core.xla_model as xm
return xm.xrt_world_size()
elif is_sagemaker_dp_enabled():
import smdistributed.dataparallel.torch.distributed as dist
return dist.get_world_size()
elif ((local_rank != ... |
class ReBrainTest(unittest.TestCase):
def test_regex_flags(self) -> None:
names = [name for name in dir(re) if name.isupper()]
re_ast = MANAGER.ast_from_module_name('re')
for name in names:
self.assertIn(name, re_ast)
self.assertEqual(next(re_ast[name].infer()).value,... |
class CollaborativeAdaptiveOptimizer(CollaborativeOptimizer):
def __init__(self, opt: torch.optim.Optimizer, average_opt_statistics: Sequence[str], **kwargs):
super().__init__(opt, average_opt_statistics=average_opt_statistics, **kwargs)
def _make_averager(self, average_opt_statistics, **kwargs):
... |
class ConvBNLayer(nn.Module):
def __init__(self, ch_in, ch_out, filter_size=3, stride=1, groups=1, padding=0, act='swish'):
super(ConvBNLayer, self).__init__()
self.conv = nn.Conv2d(in_channels=ch_in, out_channels=ch_out, kernel_size=filter_size, stride=stride, padding=padding, groups=groups, bias=F... |
def print_new_wheels(msg: str, output_dir: Path) -> Generator[(None, None, None)]:
start_time = time.time()
existing_contents = set(output_dir.iterdir())
(yield)
final_contents = set(output_dir.iterdir())
new_contents = [FileReport(wheel.name, f'{((wheel.stat().st_size + 1023) // 1024):,d}') for whe... |
class BasicConv(nn.Module):
def __init__(self, in_planes, out_planes, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True):
super(BasicConv, self).__init__()
self.out_channels = out_planes
self.conv = nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padd... |
(frozen=True)
class MinLen(AnnotatedTypesCheck):
value: Any
def predicate(self, value: Any) -> bool:
return (len(value) >= self.value)
def is_compatible_metadata(self, metadata: AnnotatedTypesCheck) -> bool:
if isinstance(metadata, MinLen):
return (metadata.value >= self.value)
... |
def generator_unet(image, out_dim, params=dict(), is_training=True, name='generator'):
feat_ch = int(params.get('feat_ch', 64))
dropout_rate = (0.5 if is_training else 1.0)
with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
e1 = inst_norm(conv2d(image, feat_ch, name='g_e1_conv'))
e2 = inst_n... |
class XTSEExchangeCalendar(TradingCalendar):
regular_early_close = time(13)
name = 'XTSE'
tz = timezone('America/Toronto')
open_times = ((None, time(9, 31)),)
close_times = ((None, time(16)),)
def regular_holidays(self):
return HolidayCalendar([XTSENewYearsDay, FamilyDay, GoodFriday, Vic... |
class GRAFConfig(BaseConfig):
name = 'graf'
hint = 'Train a GRAF model.'
info = '\nTo train a GRAF model, the recommend settings are as follows:\n\n\x08\n- batch_size: 8 (for FF-HQ dataset, 8 GPU)\n- val_batch_size: 8 (for FF-HQ dataset, 8 GPU)\n- data_repeat: 200 (for FF-HQ dataset)\n- total_img: 25_000_00... |
def test_show_fixtures_and_test(pytester: Pytester, dummy_yaml_custom_test: None) -> None:
pytester.makepyfile('\n import pytest\n \n def arg():\n assert False\n def test_arg(arg):\n assert False\n ')
result = pytester.runpytest('--setup-plan')
assert (re... |
class TestHooks():
def test_test_report(self, pytester: Pytester, pytestconfig: Config) -> None:
pytester.makepyfile('\n def test_a(): assert False\n def test_b(): pass\n ')
reprec = pytester.inline_run()
reports = reprec.getreports('pytest_runtest_logreport')
... |
def test_env_global_override_project_platform(tmp_path, platform):
pyproject_toml = (tmp_path / 'pyproject.toml')
pyproject_toml.write_text('\n[tool.cibuildwheel.linux]\nrepair-wheel-command = "repair-project-linux"\n[tool.cibuildwheel.windows]\nrepair-wheel-command = "repair-project-windows"\n[tool.cibuildwhee... |
def create_logger(name, log_file, level=logging.INFO):
logger = logging.getLogger(name)
global logger_id
if (logger_id == 1):
return logger
formatter = logging.Formatter('[%(asctime)s][%(filename)15s][line:%(lineno)4d][%(levelname)8s]%(message)s')
fh = logging.FileHandler(log_file)
fh.se... |
def showSolution(solution):
for i in range(1, 6):
print(('House %d' % i))
print('')
print(('Nationality: %s' % solution[('nationality%d' % i)]))
print(('Color: %s' % solution[('color%d' % i)]))
print(('Drink: %s' % solution[('drink%d' % i)]))
print(('Smoke: %s' % solu... |
class TestFlaskOpenAPIResponse():
def test_type_invalid(self):
with pytest.raises(TypeError):
FlaskOpenAPIResponse(None)
def test_invalid_server(self, response_factory):
data = b'Not Found'
status_code = 404
response = response_factory(data, status_code=status_code)
... |
class CommonAPIRequestTools(object):
CREDENTIAL_ACCESS = 'cred_access'
CREDENTIAL_SECRET = 'cred_secret'
CREDENTIAL_ACCOUNT = 'cred_account'
CREDENTIAL_TOKEN = 'cred_token'
api_class = mws.mws.MWS
def setUp(self):
self.api = self.api_class(self.CREDENTIAL_ACCESS, self.CREDENTIAL_SECRET, ... |
def run_test(case, m):
m.elaborate()
tr = mk_TestStructuralTranslator(StructuralTranslatorL1)(m)
tr.clear(m)
tr.translate_structural(m)
try:
name = tr.structural.component_unique_name[m]
assert (name == case.REF_NAME)
decl_ports = tr.structural.decl_ports[m]
assert (d... |
def generic_test(sdr, test_async=True, test_exceptions=True, use_numpy=True):
print(('Testing %r' % sdr))
sdr.rs = 2048000.0
assert check_close(7, 2048000.0, sdr.rs)
print(('sample_rate: %s' % sdr.rs))
bw = (sdr.rs / 2)
print('setting bandwidth to {}'.format(bw))
sdr.bandwidth = bw
asser... |
def start_env_episode_distance(task, episode, pickup_order):
pathfinder = task._simple_pathfinder
agent_start_pos = episode.start_position
prev_obj_end_pos = agent_start_pos
object_positions = [obj.position for obj in episode.objects]
rec_positions = [rec.position for rec in episode.get_receptacles(... |
def reiddataset_downloader(data_dir, data_name, hdf5=True):
if (not os.path.exists(data_dir)):
os.makedirs(data_dir)
if hdf5:
dataset_dir = os.path.join(data_dir, data_name)
if (not os.path.exists(dataset_dir)):
os.makedirs(dataset_dir)
destination = os.path.join(data... |
def test_log_action(first_model, second_model, combined_model, initialized_db):
day = date(2019, 1, 1)
with freeze_time(day):
combined_model.log_action('push_repo', namespace_name='devtable', repository_name='simple', ip='1.2.3.4')
simple_repo = model.repository.get_repository('devtable', 'simple')
... |
class TestTransforms(unittest.TestCase):
def setUp(self) -> None:
self.transformer = transforms.TransformVisitor()
def parse_transform(self, code: str) -> Module:
module = parse(code, apply_transforms=False)
return self.transformer.visit(module)
def test_function_inlining_transform(s... |
def make_predictions(all_examples, all_features, all_results, n_best_size, max_answer_length, larger_than_cls):
example_id_to_features = collections.defaultdict(list)
for feature in all_features:
example_id_to_features[feature.example_id].append(feature)
example_id_to_results = collections.defaultdi... |
class BufferedIterator(object):
def __init__(self, size, iterable):
self._queue = queue.Queue(size)
self._iterable = iterable
self._consumer = None
self.start_time = time.time()
self.warning_time = None
self.total = len(iterable)
def _create_consumer(self):
... |
class clean(distutils.command.clean.clean):
def initialize_options(self):
self.template_files = None
self.commands = None
super().initialize_options()
def finalize_options(self):
self.set_undefined_options('pre_build_templates', ('template_files', 'template_files'))
self.... |
class RoIAwarePool3dFunction(Function):
def forward(ctx, rois, pts, pts_feature, out_size, max_pts_each_voxel, pool_method):
assert ((rois.shape[1] == 7) and (pts.shape[1] == 3))
if isinstance(out_size, int):
out_x = out_y = out_z = out_size
else:
assert (len(out_size... |
def which_model(input_csv_path: str) -> str:
with open(input_csv_path, 'r') as csv_file:
params_reader = csv.reader(csv_file, delimiter=';')
for (key, value) in params_reader:
if (key == 'model'):
return value
raise ValueError('Model type not specified.') |
class Dataset(object):
def get_epoch(self):
raise NotImplementedError(self.__class__)
def get_batches(self, n_batches):
if (len(self) < n_batches):
raise ValueError()
return itertools.islice(self.get_epoch(), n_batches)
def get_epochs(self, n_epochs: int):
for _ i... |
class FairseqLanguageModel(BaseFairseqModel):
def __init__(self, decoder):
super().__init__()
self.decoder = decoder
assert isinstance(self.decoder, FairseqDecoder)
def forward(self, src_tokens, **kwargs):
return self.decoder(src_tokens, **kwargs)
def extract_features(self, s... |
class ValueEnum(menu):
def __init__(self, name, pypilot_path, pypilot_items_path=None):
super(ValueEnum, self).__init__(name, [])
self.pypilot_path = pypilot_path
self.pypilot_items_path = pypilot_items_path
self.items_val = None
self.selection = (- 1)
def process(self):
... |
class EvaluatedName(PyName):
def __init__(self, callback, module=None, lineno=None):
self.module = module
self.lineno = lineno
self.callback = callback
self.pyobject = _Inferred(callback, _get_concluded_data(module))
def get_object(self):
return self.pyobject.get()
de... |
def main():
args = parse_args()
if (args.world_size > 1):
rank = init_distributed(args)
torch.cuda.set_device(args.local_rank)
else:
rank = 0
set_random_seed((args.seed + rank))
(train_env, val_envs, aug_env) = build_dataset(args, rank=rank, is_test=args.test)
if (not arg... |
class CvtAttention(nn.Module):
def __init__(self, num_heads, embed_dim, kernel_size, padding_q, padding_kv, stride_q, stride_kv, qkv_projection_method, qkv_bias, attention_drop_rate, drop_rate, with_cls_token=True):
super().__init__()
self.attention = CvtSelfAttention(num_heads, embed_dim, kernel_si... |
class EmotionBot(Bot):
class TimeoutException(Exception):
def __init__(self, uuid, status):
self.uuid = uuid
self.status = status
def __init__(self, name=None, need_login=True, timeout_max=15, qr_callback=None, *args, **kwargs):
self.name = name
self.timeout_count... |
def test_require_gdal_version_param_values():
for values in [('bar',), ['bar'], {'bar'}]:
_gdal_version('1.0', param='foo', values=values)
def a(foo=None):
return foo
assert (a() is None)
assert (a('bar') == 'bar')
assert (a(foo='bar') == 'bar') |
_module()
class BottomUpCrowdPoseDataset(BottomUpCocoDataset):
def __init__(self, ann_file, img_prefix, data_cfg, pipeline, dataset_info=None, test_mode=False):
if (dataset_info is None):
warnings.warn('dataset_info is missing. Check for details.', DeprecationWarning)
cfg = Config.f... |
class OptSimilarity_Mestranol(Molecule):
def _reward(self):
scorer = similarity(smiles='COc1ccc2[]3CC[]4(C)[](CC[]4(O)C#C)[]3CCc2c1', name='Mestranol', fp_type='AP', threshold=0.75)
s_fn = scorer.wrapped_objective
molecule = Chem.MolFromSmiles(self._state)
if (molecule is None):
... |
class InlineResponse20016(BaseModel, extra='forbid'):
time: Optional[float] = Field(default=None, description='Time spent to process this request')
status: Optional[str] = Field(default=None, description='')
result: Optional[List[List['ScoredPoint']]] = Field(default=None, description='') |
class _Config():
def __init__(self):
self._init_logging_handler()
self.cuda_device = 6
self.eos_m_token = 'EOS_M'
self.beam_len_bonus = 0.6
self.mode = 'unknown'
self.m = 'TSD'
self.prev_z_method = 'none'
self.dataset = 'unknown'
self.root_dir ... |
class TestCommunication(coroutine_tests.CoroutineTestCase):
server_config = h2.config.H2Configuration(client_side=False)
def test_basic_request_response(self):
request_headers = [(b':method', b'GET'), (b':path', b'/'), (b':authority', b'example.com'), (b':scheme', b' (b'user-agent', b'test-client/0.1.0'... |
(Advertiser)
class AdvertiserAdmin(RemoveDeleteMixin, SimpleHistoryAdmin):
actions = ['action_create_draft_invoice']
inlines = (CampaignInline,)
list_display = ('name', 'report', 'stripe_customer')
list_per_page = 500
prepopulated_fields = {'slug': ('name',)}
raw_id_fields = ('djstripe_customer'... |
def insert_sphere(arr, sp_radius=4, sp_centre=(0, 0, 0)):
arr_copy = arr[:]
(x, y, z) = np.indices(arr.shape)
if (not hasattr(sp_radius, '__iter__')):
sp_radius = ([sp_radius] * 3)
(sp_radius_x, sp_radius_y, sp_radius_z) = sp_radius
arr_copy[((((((x - sp_centre[0]) / sp_radius_x) ** 2.0) + (... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.