code stringlengths 281 23.7M |
|---|
class UserProfileViewTest(TestCase):
def setUpTestData(cls):
add_default_data()
def test_UserProfileViewOk(self):
response = self.client.get(reverse('user_profile', args=['max']))
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'petition/user_profile... |
class UserShared(TelegramObject):
__slots__ = ('request_id', 'user_id')
def __init__(self, request_id: int, user_id: int, *, api_kwargs: Optional[JSONDict]=None):
super().__init__(api_kwargs=api_kwargs)
self.request_id: int = request_id
self.user_id: int = user_id
self._id_attrs ... |
class MainMenuBar(wx.MenuBar):
def __init__(self, mainFrame):
pyfalog.debug('Initialize MainMenuBar')
self.characterEditorId = wx.NewId()
self.damagePatternEditorId = wx.NewId()
self.targetProfileEditorId = wx.NewId()
self.implantSetEditorId = wx.NewId()
self.graphFra... |
class CfdCommand(object):
def __init__(self):
self.resources = {'Pixmap': 'fem-cfd-analysis', 'MenuText': QtCore.QT_TRANSLATE_NOOP('Cfd_Command', 'Default Cfd Command MenuText'), 'Accel': '', 'ToolTip': QtCore.QT_TRANSLATE_NOOP('Cfd_Command', 'Default Cfd Command ToolTip')}
self.is_active = None
... |
def load(fp: BinaryIO, *, parse_float: ParseFloat=float) -> Dict[(str, Any)]:
s_bytes = fp.read()
try:
s = s_bytes.decode()
except AttributeError:
warnings.warn('Text file object support is deprecated in favor of binary file objects. Use `open("foo.toml", "rb")` to open the file in binary mo... |
(ttl=86400, hash_funcs={pymedphys.mosaiq.Connection: id})
def _get_all_columns(connection, table):
raw_columns = pymedphys.mosaiq.execute(connection, '\n SELECT COLUMN_NAME, DATA_TYPE\n FROM INFORMATION_SCHEMA.COLUMNS\n WHERE TABLE_NAME = %(table)s\n ', {'table': table})
columns = [i... |
class Config():
def __init__(self) -> None:
self.root_path: str = '.'
self.data_set: str = 'sample'
self.batch_size: int = 32
self.if_shuffle: bool = True
self.label_size: Optional[int] = None
self.char_embed: int = 128
self.num_filters: int = 128
self... |
(web_fixture=WebFixture)
class NavbarToggleFixture(Fixture):
def is_expanded(self, locator):
return (self.web_fixture.driver_browser.is_visible(locator) and self.web_fixture.driver_browser.does_element_have_attribute(locator, 'class', value='collapse show'))
def panel_is_visible(self):
return se... |
def test_excluded_subpackage() -> None:
poetry = Factory().create_poetry(project('excluded_subpackage'))
builder = SdistBuilder(poetry)
setup = builder.build_setup()
setup_ast = ast.parse(setup)
setup_ast.body = [n for n in setup_ast.body if isinstance(n, ast.Assign)]
ns: dict[(str, Any)] = {}
... |
def getTrainingData(batch_size=64):
__imagenet_pca = {'eigval': torch.Tensor([0.2175, 0.0188, 0.0045]), 'eigvec': torch.Tensor([[(- 0.5675), 0.7192, 0.4009], [(- 0.5808), (- 0.0045), (- 0.814)], [(- 0.5836), (- 0.6948), 0.4203]])}
__imagenet_stats = {'mean': [0.485, 0.456, 0.406], 'std': [0.229, 0.224, 0.225]}
... |
def test_towgs84_transformation__defaults():
transformation = ToWGS84Transformation(GeographicCRS())
assert (transformation.towgs84 == [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
assert (_to_dict(transformation) == {'Scale difference': 0.0, 'X-axis rotation': 0.0, 'X-axis translation': 0.0, 'Y-axis rotation': 0.0,... |
def test_cannot_order_room_with_random_room_id(graphql_client, hotel_room_factory, user, conference_factory, mocker, bed_layout_factory):
graphql_client.force_login(user)
conference = conference_factory(start=timezone.make_aware(timezone.datetime(2020, 1, 1)), end=timezone.make_aware(timezone.datetime(2020, 1, ... |
class transformer_decoder(nn.Module):
def __init__(self, num_layers):
super(transformer_decoder, self).__init__()
base = MultiHeadAttention(1, 192, 64, 192)
self.q = nn.Parameter(torch.rand(1, 64, 192)).cuda()
self.layer0 = MultiHeadAttention_d0(1, 192, 64, 192)
self.layer1 =... |
def eth_abi_encode(func: dict, args: list) -> str:
if (not func):
return '00'
types = list([inp['type'] for inp in func.get('inputs', [])])
if func.get('name'):
result = (function_abi_to_4byte_selector(func) + encode_abi(types, args))
else:
result = encode_abi(types, args)
re... |
class TestNonce(TestCase):
def test_use(self):
self.assertEqual(Nonce.objects.count(), 0)
self.assertTrue(Nonce.use(server_url='/', timestamp=1, salt='1'))
self.assertFalse(Nonce.use(server_url='/', timestamp=1, salt='1'))
self.assertEqual(Nonce.objects.count(), 1) |
class OpencorporaTag(object):
PARTS_OF_SPEECH = frozenset(['NOUN', 'ADJF', 'ADJS', 'COMP', 'VERB', 'INFN', 'PRTF', 'PRTS', 'GRND', 'NUMR', 'ADVB', 'NPRO', 'PRED', 'PREP', 'CONJ', 'PRCL', 'INTJ'])
ANIMACY = frozenset(['anim', 'inan'])
GENDERS = frozenset(['masc', 'femn', 'neut'])
NUMBERS = frozenset(['si... |
def gat_graph_conv(x, adj, eps, kernel):
v = (eps * tf.diag_part(adj))
mask = tf.diag(tf.ones_like(v))
adj = ((mask * tf.diag(v)) + ((1.0 - mask) * adj))
y1 = K.dot(adj, x)
conv_op_y1 = tf.split(y1, 1, axis=0)
conv_op_y1 = K.concatenate(conv_op_y1, axis=1)
conv_op_y1 = K.dot(conv_op_y1, kern... |
def lazify_imports(registry: dict[(str, str)], package: str, fallback: (Callable | None)=None) -> tuple[(tuple[(str, ...)], Callable, Callable)]:
__all__ = tuple(registry.keys())
def __dir__() -> tuple[(str, ...)]:
return __all__
def __getattr__(name: str) -> Any:
if (name not in registry):
... |
class YOLOv5Darknet(nn.Module):
def __init__(self, depth_multiple, width_multiple, focus, in_channels=3, bottle_depths=[3, 9, 9, 3], out_channels=[128, 256, 512, 1024], spp=[5, 9, 13], shortcut=[True, True, True, False], out_indices=(2, 3, 4), norm_type='BN', num_groups=None):
super(YOLOv5Darknet, self).__i... |
def test_get_vol_files_list():
train_files = get_dataset_files_list(mode='train')
assert np.all([('train' in tf) for tf in train_files])
assert np.all([('valid' not in tf) for tf in train_files])
assert np.all([('test' not in tf) for tf in train_files])
valid_files = get_dataset_files_list(mode='val... |
def apply_specifiers(specifiers, declaration):
for s in specifiers:
if (type(s) == StorageClassSpecifier):
if declaration.storage:
p.parser.cparser.handle_error('Declaration has more than one storage class', '???', p.lineno(1))
return
declaration.stora... |
def Gtest(test_loader, model, criterion=nn.L1Loss(reduction='mean')):
model.eval()
error = 0
correct = 0
with torch.no_grad():
for data in test_loader:
data = data.to(device)
output = model(data.x, data.edge_index, data.edge_attr, data.batch)
error += (criteri... |
class TrainerIntegrationCommon():
def check_saved_checkpoints(self, output_dir, freq, total, is_pretrained=True):
file_list = [WEIGHTS_NAME, 'training_args.bin', 'optimizer.pt', 'scheduler.pt', 'trainer_state.json']
if is_pretrained:
file_list.append('config.json')
for step in ra... |
class MaxPositionSize(TradingControl):
def __init__(self, on_error, asset=None, max_shares=None, max_notional=None):
super(MaxPositionSize, self).__init__(on_error, asset=asset, max_shares=max_shares, max_notional=max_notional)
self.asset = asset
self.max_shares = max_shares
self.max... |
class ELAN(nn.Module):
def __init__(self, c1, c2):
c_ = (c2 // 4)
super(ELAN, self).__init__()
self.conv1 = Conv(c1, c_, 1, 1)
self.conv2 = Conv(c1, c_, 1, 1)
self.conv3 = Conv(c_, c_, 3, 1)
self.conv4 = Conv(c_, c_, 3, 1)
self.conv5 = Conv(c_, c_, 3, 1)
... |
class SOAPHandler(BaseHTTPRequestHandler):
def do_GET(self):
args = self.path[1:].split('?')
if ((self.path != '/') and (args[0] not in self.server.dispatcher.methods.keys())):
self.send_error(404, ('Method not found: %s' % args[0]))
else:
if (self.path == '/'):
... |
def train_net(args, model, train_dl, valid_dl, output_model_path, comment):
if args.viz:
writer = SummaryWriter(log_dir=os.path.join(output_model_path, 'log'), comment=comment)
global_step = 0
optimizer = optim.Adam(model.parameters(), lr=args.lr)
scheduler = optim.lr_scheduler.MultiStepLR(optim... |
_tag
def metabase_question_embed(question_id, **kwargs):
if (not question_id):
return None
if (not settings.METABASE_SECRET_KEY):
log.warning("Metabase Secret Key is not set - Graphs won't render")
return None
payload = {'resource': {'question': question_id}, 'params': serialize_para... |
class MKS937B(Instrument):
ch_1 = Instrument.ChannelCreator(IonGaugeAndPressureChannel, 1)
ch_2 = Instrument.ChannelCreator(PressureChannel, 2)
ch_3 = Instrument.ChannelCreator(IonGaugeAndPressureChannel, 3)
ch_4 = Instrument.ChannelCreator(PressureChannel, 4)
ch_5 = Instrument.ChannelCreator(IonGau... |
def pip_install(path: Path, environment: Env, editable: bool=False, deps: bool=False, upgrade: bool=False) -> str:
is_wheel = (path.suffix == '.whl')
args = ['install', '--disable-pip-version-check', '--isolated', '--no-input', '--prefix', str(environment.path)]
if ((not is_wheel) and (not editable)):
... |
class KnownValues(unittest.TestCase):
def test_kuhf_kernel(self):
self.assertAlmostEqual(kmf.e_tot, (- 4.), 8)
kmf.analyze()
def test_uhf_kernel(self):
self.assertAlmostEqual(mf.e_tot, (- 3.), 8)
mf.analyze()
def test_kuhf_vs_uhf(self):
np.random.seed(1)
k = n... |
class BashhubSetupTest(unittest.TestCase):
.skipif(CI_UNSUPPORTED, reason='uuid for mac address not supported on github actions')
def test_get_mac_addresss(self):
test_mac = bashhub_setup.get_mac_address()
assert (str(uuid.getnode()) == test_mac)
def test_get_mac_addresss_where_uuid_is_rando... |
def get_tb_stats(logdir, desired_tag):
try:
logpath = newest(logdir)
with open(logpath, 'rb') as f:
data = f.read()
except FileNotFoundError:
print('Unable to find log file in ', logdir)
return
(steps, tag_values) = ([], [])
while data:
(data, event_st... |
class TestTwoCNOT(Bloq):
_property
def signature(self) -> Signature:
return Signature.build(q1=1, q2=1)
def build_composite_bloq(self, bb: 'BloqBuilder', q1: 'Soquet', q2: 'Soquet') -> Dict[(str, SoquetT)]:
(q1, q2) = bb.add(CNOT(), ctrl=q1, target=q2)
(q1, q2) = bb.add(CNOT(), ctrl=... |
def parse_args():
parser = argparse.ArgumentParser(description='Run KGAT.')
parser.add_argument('--weights_path', nargs='?', default='', help='Store model path.')
parser.add_argument('--data_path', nargs='?', default='../Data/', help='Input data path.')
parser.add_argument('--proj_path', nargs='?', defa... |
def test_fetchyaml_empty_path_raises():
context = Context({'fetchYaml': {'path': None}})
with pytest.raises(KeyInContextHasNoValueError) as err_info:
filefetcher.run_step(context)
assert (str(err_info.value) == "context['fetchYaml']['path'] must have a value for pypyr.steps.fetchyaml.") |
class FontConfigSearchResult(FontConfigPattern):
def __init__(self, fontconfig, result_pattern):
super(FontConfigSearchResult, self).__init__(fontconfig, result_pattern)
def name(self):
return self._get_string(FC_FAMILY)
def size(self):
return self._get_double(FC_SIZE)
def bold(s... |
def assert_table_lineage_equal(sql: str, source_tables=None, target_tables=None, dialect: str='ansi', test_sqlfluff: bool=True, test_sqlparse: bool=True):
lr = LineageRunner(sql, dialect=SQLPARSE_DIALECT)
lr_sqlfluff = LineageRunner(sql, dialect=dialect)
if test_sqlparse:
_assert_table_lineage(lr, s... |
.parametrize('username,password', users)
def test_project_create_import_post_upload_file_empty(db, client, username, password):
client.login(username=username, password=password)
url = reverse('project_create_import')
response = client.post(url, {'method': 'upload_file'})
if password:
assert (re... |
class ValidMD():
def __init__(self, filename):
self.filename = filename
self.required_user_fields = ['title', 'summary', 'image', 'author', 'tags', 'github-link', 'category']
self.optional_image_fields = ['featured_image_1', 'featured_image_2']
self.valid_tags = valid_tags
se... |
class ExploreModule():
def __init__(self, params, num_envs):
self.params = params
actions = ['STOP', 'MOVE_FORWARD', 'TURN_LEFT', 'TURN_RIGHT', 'LOOK_UP', 'LOOK_DOWN', 'GRAB_RELEASE']
self.action_mapping = {action: idx for (idx, action) in enumerate(actions)}
self.num_envs = num_envs... |
def test_array_array():
from sys import byteorder
e = ('<' if (byteorder == 'little') else '>')
arr = m.create_array_array(3)
assert (str(arr.dtype) == (((("{{'names':['a','b','c','d'], " + "'formats':[('S4', (3,)),('") + e) + "i4', (2,)),('u1', (3,)),('{e}f4', (4, 2))], ") + "'offsets':[0,12,20,24], 'i... |
def logDictionary(f, d, levels, indent=0):
for (key, value) in d.items():
f.write(((((('\t' * indent) + str(levels[indent])) + ': ') + str(key)) + '\n'))
if isinstance(value, dict):
logDictionary(f, value, levels, (indent + 1))
else:
f.write(((((('\t' * (indent + 1)) ... |
class EmbeddingCollectionTest(unittest.TestCase):
def _test_ec(self, tables: List[EmbeddingConfig], features: KeyedJaggedTensor, quant_type: torch.dtype=torch.qint8, output_type: torch.dtype=torch.float, quant_state_dict_split_scale_bias: bool=False) -> None:
ec = EmbeddingCollection(tables=tables)
... |
.parametrize('M, p, size', [(np.array(10, dtype=np.int64), np.array(0.5, dtype=config.floatX), None), (np.array(10, dtype=np.int64), np.array(0.5, dtype=config.floatX), []), (np.array(10, dtype=np.int64), np.array(0.5, dtype=config.floatX), [2, 3]), (np.full((1, 2), 10, dtype=np.int64), np.array(0.5, dtype=config.float... |
def _extraPayloadCheck(params, dir):
if params.has_key('utilityburst'):
try:
f = open(('%s/config.xml' % dir), 'r')
try:
lines = f.readlines()
for line in lines:
if (re.search('PCHEAP_CONFIG_LOADED_WITH_UTILITY_BURST', line) != None... |
class FC3_Url(KickstartCommand):
removedKeywords = KickstartCommand.removedKeywords
removedAttrs = KickstartCommand.removedAttrs
def __init__(self, writePriority=0, *args, **kwargs):
KickstartCommand.__init__(self, writePriority, *args, **kwargs)
self.url = kwargs.get('url', None)
se... |
def get_annot(t) -> dict:
if is_generic(t):
origin = getattr(t, '__origin__', None)
if (origin is not None):
origin_annotations = get_annots(origin)
args = t.__args__
params = origin.__parameters__
param_to_args = dict(zip(params, args))
re... |
def performace_to_table(role_id_prec, role_id_rec, role_id_f, role_prec, role_rec, role_f, role_ner_prec, role_ner_rec, role_ner_f, role_cls_ner_prec, role_cls_ner_rec, role_cls_ner_f):
return pd.DataFrame({'Role Identification': [(role_id_prec * 100.0), (role_id_rec * 100.0), (role_id_f * 100.0)], 'Role Classifica... |
def gen_w(params):
worker_script = f'''#!/bin/bash -ex
exec > >(tee /var/log/user-command.log|logger -t user-data -s 2>/dev/console) 2>&1
sudo yum install tc -y
git clone
cd wondershaper
sudo ./wondershaper -a eth0 -u {(params['up'] * 1024)} -d {(params['down'] * 1024)}
cd ..
git clone {repo_path}
cd DeDLOC
pip in... |
def test_TrafficSignalState():
tss = _TrafficSignalState('ID_1', 'Signal_State')
tss2 = _TrafficSignalState('ID_1', 'Signal_State')
tss3 = _TrafficSignalState('ID_2', 'Signal_State')
prettyprint(tss.get_element())
assert (tss == tss2)
assert (tss != tss3)
tss4 = _TrafficSignalState.parse(tss... |
def test_show_benchmark(benchmark, tabbed_browser, qtbot, mode_manager):
tab = tabbed_browser.widget.tabs[0]
with qtbot.wait_signal(tab.load_finished):
tab.load_url(QUrl('qute://testdata/data/hints/benchmark.html'))
manager = qutebrowser.browser.hints.HintManager(win_id=0)
def bench():
w... |
class ContractNotificationToPSFTests(TestCase):
def setUp(self):
self.notification = notifications.ContractNotificationToPSF()
self.contract = baker.make_recipe('sponsors.tests.awaiting_signature_contract', _fill_optional=['document'], _create_files=True)
self.subject_template = 'sponsors/em... |
class MutationExportData():
def __init__(self):
self.reference = 1
self.mutants = {}
def formatMutants(self):
mutationLines = []
if self.mutants:
for mutantReference in sorted(self.mutants):
mutant = self.mutants[mutantReference]
mutati... |
class PatternLexer(Scanner):
def __init__(self, s):
self.string = s
Scanner.__init__(self, [('([^<>|\\\\]|\\\\.)+', self.text), ('\\|\\||[<>|]', self.table)])
def text(self, scanner, string):
return PatternLexeme(TEXT, re.sub('\\\\([|<>\\\\])', '\\1', string))
def table(self, scanner... |
class TabletCanvas(EventDispatcher):
def __init__(self, window):
self.window = window
def close(self):
raise NotImplementedError('abstract')
if _is_pyglet_doc_run:
def on_enter(self, cursor):
def on_leave(self, cursor):
def on_motion(self, cursor, x, y, pressure, tilt... |
class QKTCallback():
def __init__(self) -> None:
self._data = [[] for i in range(5)]
def callback(self, x0, x1=None, x2=None, x3=None, x4=None):
self._data[0].append(x0)
self._data[1].append(x1)
self._data[2].append(x2)
self._data[3].append(x3)
self._data[4].appen... |
def _retrieval_precision_update_input_check(input: torch.Tensor, target: torch.Tensor, num_tasks: int=1, indexes: Optional[torch.Tensor]=None, num_queries: int=1) -> None:
if (input.shape != target.shape):
raise ValueError(f'input and target must be of the same shape, got input.shape={input.shape} and targe... |
class AxialAttention(nn.Module):
def __init__(self, dim, num_dimensions=2, heads=8, dim_heads=None, dim_index=(- 1), sum_axial_out=True):
assert ((dim % heads) == 0), 'hidden dimension must be divisible by number of heads'
super().__init__()
self.dim = dim
self.total_dimensions = (nu... |
class SideBlock(nn.Module):
def __init__(self, in_c, out_c, conv2d=None, norm_layer=None, kernel_size=3, padding=1, stride=1, non_linear=nn.ReLU):
super(SideBlock, self).__init__()
if (conv2d is None):
conv2d = nn.Conv2d
if (norm_layer is None):
norm_layer = Identity
... |
class Handle():
tip = ''
def __init__(self, window, player):
self.win = window
self.player = player
def hit_test(self, x, y, z):
(dx, dy, dz) = [(a - b) for (a, b) in zip(self.pos(), (x, y, z))]
if ((((dx * dx) + (dy * dy)) + (dz * dz)) < (self.radius * self.radius)):
... |
class CarliniLID():
def __init__(self, sess, model, image_size, num_channels, num_labels, batch_size=100, confidence=L2_CONFIDENCE, targeted=L2_TARGETED, learning_rate=L2_LEARNING_RATE, binary_search_steps=L2_BINARY_SEARCH_STEPS, max_iterations=L2_MAX_ITERATIONS, abort_early=L2_ABORT_EARLY, initial_const=L2_INITIAL... |
def main(args):
checkpoint = args.checkpoint
collection = args.collection
experiment_dir = args.expdir
k = 5
(searcher, index_path) = build_index_and_init_searcher(checkpoint, collection, experiment_dir)
squad = load_dataset('squad')
squad_dev = get_squad_split(squad)
question = squad_de... |
class ZeroconfDevice(object):
def __init__(self, name: str, ip: str, port: int, model: str, id: str) -> None:
self.name = name
self.ip = ip
self.port = port
self.model = model
self.id = id
def __repr__(self) -> str:
return f'{type(self).__name__}({self.__dict__})'... |
def read_traj_images(json_path, image_folder):
root_path = json_path.parents[0]
with open(json_path) as json_file:
json_dict = json.load(json_file)
image_names = ([None] * len(json_dict['plan']['low_actions']))
for (im_idx, im_dict) in enumerate(json_dict['images']):
if (image_names[im_d... |
def get_quantized_dequantized_weight(layer: torch.nn.Module) -> torch.Tensor:
weight_tensor = layer._module_to_wrap.weight
weight_quantizer = layer.param_quantizers['weight']
quant_dequant_weights = weight_quantizer.quantize_dequantize(weight_tensor, weight_quantizer.round_mode)
return quant_dequant_wei... |
def search_plan(sym, ntrial=6, type_dict=None, **kwargs):
history = []
threshold = 0
min_threshold = None
min_cost = None
nbegin = 3
for k in range(nbegin):
info = {}
sym = make_mirror_plan(sym, threshold=threshold, plan_info=info, **kwargs)
cost = get_cost(sym, type_dict... |
class TestPytestPluginManagerBootstrapming():
def test_preparse_args(self, pytestpm: PytestPluginManager) -> None:
pytest.raises(ImportError, (lambda : pytestpm.consider_preparse(['xyz', '-p', 'hello123'])))
with pytest.raises(ImportError) as excinfo:
pytestpm.consider_preparse(['-phello... |
def _simple_conv_model(model_type='functional'):
if (model_type == 'functional'):
inp = layers.Input((32, 32, 3))
x = layers.Conv2D(filters=32, kernel_size=2)(inp)
x = layers.ReLU(max_value=6.0)(x)
x = layers.Conv2D(filters=32, kernel_size=2, activation=tf.nn.relu6)(x)
x = la... |
class TestReplaceNodeTransformer(object):
def test_found(self):
node = ast.parse('a.b(c)')
replacement_node = ast.Name(id='d')
new_node = ReplaceNodeTransformer(node.body[0].value.func, replacement_node).visit(node)
assert (new_node is not node)
assert_code_equal('d(c)\n', de... |
class GeoJsonTooltip(GeoJsonDetail):
_template = Template((('\n {% macro script(this, kwargs) %}\n {{ this._parent.get_name() }}.bindTooltip(' + GeoJsonDetail.base_template) + ',{{ this.tooltip_options | tojson | safe }});\n {% endmacro %}\n '))
def __init__(self, f... |
class Attention(nn.Module):
def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.0, proj_drop=0.0):
super().__init__()
self.num_heads = num_heads
head_dim = (dim // num_heads)
self.scale = (qk_scale or (head_dim ** (- 0.5)))
self.qkv = nn.Linear(dim... |
def test_gitlab_reference_handling_on_bad_data(run_line, tmp_path):
doc = (tmp_path / 'data.yml')
doc.write_text('include:\n - local: setup.yml\n\ntest:\n script:\n # !reference not a list, error\n - !reference .setup\n - echo running my own command\n')
res = run_line(['check-jsonschema', '--buil... |
class FinTS3Segment(Container, SubclassesMixin, metaclass=FinTS3SegmentMeta):
header = DataElementGroupField(type=SegmentHeader, _d='Segmentkopf')
def TYPE(cls):
match = TYPE_VERSION_RE.match(cls.__name__)
if match:
return match.group(1)
def VERSION(cls):
match = TYPE_VER... |
class BasicBlock(nn.Sequential):
def __init__(self, conv, in_channels, out_channels, kernel_size, stride=1, bias=False, bn=True, act=nn.ReLU(True)):
m = [conv(in_channels, out_channels, kernel_size, bias=bias)]
if bn:
m.append(nn.BatchNorm2d(out_channels))
if (act is not None):
... |
def retrieve_available_artifacts():
class Artifact():
def __init__(self, name: str, single_gpu: bool=False, multi_gpu: bool=False):
self.name = name
self.single_gpu = single_gpu
self.multi_gpu = multi_gpu
self.paths = []
def __str__(self):
... |
class TestRegistryProxyModelGetRepoTag():
upstream_registry = 'quay.io'
upstream_repository = 'app-sre/ubi8-ubi'
orgname = 'quayio-cache'
repository = f'{orgname}/{upstream_repository}'
tag = 'latest'
(autouse=True)
def setup(self, app):
self.user = get_user('devtable')
self.... |
class TestUserVersion():
.parametrize('val, major, minor', [(524289, 8, 1), (, 32767, 65535)])
def test_from_int(self, val, major, minor):
version = sql.UserVersion.from_int(val)
assert (version.major == major)
assert (version.minor == minor)
.parametrize('major, minor, val', [(8, 1,... |
def prepare_sccs(sccs: list[set[T]], edges: dict[(T, list[T])]) -> dict[(AbstractSet[T], set[AbstractSet[T]])]:
sccsmap = {v: frozenset(scc) for scc in sccs for v in scc}
data: dict[(AbstractSet[T], set[AbstractSet[T]])] = {}
for scc in sccs:
deps: set[AbstractSet[T]] = set()
for v in scc:
... |
class Packer(object):
def __init__(self, obj: Any):
tensor_lists = _extract_tensors(obj)
memo = {id(t): t for t in tensor_lists}
self._tensor_memo = copy(memo)
self._obj = deepcopy(obj, memo)
self._params_tensor_list: Optional[List[torch.Tensor]] = tensor_lists
self._... |
class GeneratorFunieGAN(nn.Module):
def __init__(self, in_channels=3, out_channels=3):
super(GeneratorFunieGAN, self).__init__()
self.down1 = UNetDown(in_channels, 32, bn=False)
self.down2 = UNetDown(32, 128)
self.down3 = UNetDown(128, 256)
self.down4 = UNetDown(256, 256)
... |
class KnownValues(unittest.TestCase):
def test_parse_pople(self):
self.assertEqual(gto.basis._parse_pople_basis('631g(d)', 'C'), ('pople-basis/6-31G.dat', 'pople-basis/6-31G-polarization-d.dat'))
self.assertEqual(gto.basis._parse_pople_basis('631g**', 'C'), ('pople-basis/6-31Gss.dat',))
self... |
class CallTipObject():
def __init__(self, textCtrl, name, offset):
self.textCtrl = textCtrl
self.name = name
self.bufferName = name
self.offset = offset
def tryUsingBuffer(self):
bufferName = self.textCtrl._callTipBuffer_name
t = (time.time() - self.textCtrl._call... |
def run(train_batch_size, epochs, lr, weight_decay, config, exp_id, log_dir, disable_gpu=False):
if (config['test_ratio'] is not None):
(train_loader, val_loader, test_loader) = get_data_loaders(config, train_batch_size, exp_id)
else:
(train_loader, val_loader) = get_data_loaders(config, train_b... |
def solve():
problem = Problem()
problem.addVariables('abcdxefgh', range(1, 10))
problem.addConstraint((lambda a, b, c, d, x: ((a < b < c < d) and (((((a + b) + c) + d) + x) == 27))), 'abcdx')
problem.addConstraint((lambda e, f, g, h, x: ((e < f < g < h) and (((((e + f) + g) + h) + x) == 27))), 'efghx')... |
class Maximum(BinaryOperator):
def __init__(self, left, right):
super().__init__('maximum', left, right)
def __str__(self):
return f'maximum({self.left!s}, {self.right!s})'
def _diff(self, variable):
(left, right) = self.orphans
return (((left >= right) * left.diff(variable))... |
.skipif((sys.version_info < (3,)), reason='Cannot catch warnings in python 2')
_test
def test_warnings():
a = Input(shape=(3,), name='input_a')
b = Input(shape=(3,), name='input_b')
a_2 = Dense(4, name='dense_1')(a)
dp = Dropout(0.5, name='dropout')
b_2 = dp(b)
model = Model([a, b], [a_2, b_2])
... |
class TRCMTreeView(TestCase):
def setUp(self):
self.c = RCMTreeView()
_fill_view(self.c)
def test_right_click(self):
with visible(self.c):
send_button_click(self.c, Gdk.BUTTON_SECONDARY)
send_button_click(self.c, Gdk.BUTTON_SECONDARY, primary=True)
def test_po... |
def _git_str_subprocess(gitpath: str) -> Optional[str]:
if (not os.path.isdir(os.path.join(gitpath, '.git'))):
return None
try:
commit_hash = _call_git(gitpath, 'describe', '--match=NeVeRmAtCh', '--always', '--dirty')
date = _call_git(gitpath, 'show', '-s', '--format=%ci', 'HEAD')
... |
class FICScorer(object):
def __init__(self):
self.imgToEval = {}
self.eval = {}
print('init COCO-EVAL scorer')
def score(self, GT, RES, IDs):
gts = {}
res = {}
for ID in IDs:
gts[ID] = GT[ID]
res[ID] = RES[ID]
print('tokenization...... |
('/v1/user/robots/<robot_shortname>')
_param('robot_shortname', 'The short name for the robot, without any user or organization prefix')
class UserRobot(ApiResource):
schemas = {'CreateRobot': CREATE_ROBOT_SCHEMA}
_user_admin()
('getUserRobot')
def get(self, robot_shortname):
parent = get_authen... |
def beams_to_bintable(beams):
c1 = Column(name='BMAJ', format='1E', array=[bm.major.to(u.arcsec).value for bm in beams], unit=u.arcsec.to_string('FITS'))
c2 = Column(name='BMIN', format='1E', array=[bm.minor.to(u.arcsec).value for bm in beams], unit=u.arcsec.to_string('FITS'))
c3 = Column(name='BPA', format... |
def _parse_lookaround(source, info, behind, positive):
saved_flags = info.flags
saved_ignore = source.ignore_space
try:
subpattern = _parse_pattern(source, info)
finally:
source.ignore_space = saved_ignore
info.flags = saved_flags
source.expect(u')')
return LookAround(sub... |
def get_config(config_path):
with open(config_path) as config_file:
base_config = json.load(config_file)
if os.path.exists('job_parameters.json'):
with open('job_parameters.json') as param_config_file:
param_config = json.load(param_config_file)
else:
param_config = {}
... |
.needs_connection
def test_calc_spectrum_multiple_molecules_otherinputs(verbose=True, plot=True, warnings=True, *args, **kwargs):
s = calc_spectrum(wavelength_min=4165, wavelength_max=5000, Tgas=1000, path_length=0.1, molecule=['CO2', 'CO'], mole_fraction=1, isotope={'CO2': '1,2', 'CO': '1,2,3'}, verbose=verbose)
... |
def get_espnetv2(width_scale, model_name=None, pretrained=False, root=os.path.join('~', '.torch', 'models'), **kwargs):
assert (width_scale <= 2.0)
branches = 4
layers = [1, 4, 8, 4]
max_dilation_list = [6, 5, 4, 3, 2]
max_dilations = [([max_dilation_list[i]] + ([max_dilation_list[(i + 1)]] * (li - ... |
def test_stream_write(stream, audio_source):
with stream.mainloop.lock:
stream.connect_playback()
assert stream.is_ready
with stream.mainloop.lock:
writable_size = stream.get_writable_size()
assert (writable_size > 0)
nbytes = min(1024, writable_size)
audio_data = audio_sourc... |
class StringEnd(PositionToken):
def __init__(self):
super().__init__()
self.errmsg = 'Expected end of text'
def parseImpl(self, instring, loc, doActions=True):
if (loc < len(instring)):
raise ParseException(instring, loc, self.errmsg, self)
if (loc == len(instring)):
... |
class DHTID(int):
HASH_FUNC = hashlib.sha1
HASH_NBYTES = 20
RANGE = (MIN, MAX) = (0, (2 ** (HASH_NBYTES * 8)))
def __new__(cls, value: int):
assert (cls.MIN <= value < cls.MAX), f'DHTID must be in [{cls.MIN}, {cls.MAX}) but got {value}'
return super().__new__(cls, value)
def generate... |
def main():
args = create_argparser().parse_args()
dist.init()
logger.configure()
torch.set_num_threads(40)
logger.log('creating data loader...')
if (args.batch_size == (- 1)):
batch_size = (args.global_batch_size // dist.get_world_size())
if ((args.global_batch_size % dist.get_w... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.