code stringlengths 281 23.7M |
|---|
_plugin.register_validator(AscIntSequence)
def validate_ascending_seq(data: list, level):
if (data == [2021, 8, 24]):
raise KeyError
prev = float('-inf')
for number in data:
if (not (number > prev)):
raise ValidationError(('%s is not greater than %s' % (number, prev))) |
_test
def test_batchnorm_correctness():
model = Sequential()
norm = normalization.BatchNormalization(input_shape=(10,), momentum=0.8)
model.add(norm)
model.compile(loss='mse', optimizer='sgd')
x = np.random.normal(loc=5.0, scale=10.0, size=(1000, 10))
model.fit(x, x, epochs=4, verbose=0)
out... |
def usage():
printerr('Usage is: export-to-sqlite.py <database name> [<columns>] [<calls>] [<callchains>] [<pyside-version-1>]')
printerr("where: columns 'all' or 'branches'")
printerr(" calls 'calls' => create calls and call_paths table")
printerr(" callchains ... |
def add_metaopt_configvars():
config.add('metaopt__verbose', '0 for silent, 1 for only warnings, 2 for full output withtimings and selected implementation', IntParam(0), in_c_key=False)
config.add('metaopt__optimizer_excluding', "exclude optimizers with these tags. Separate tags with ':'.", StrParam(''), in_c_k... |
def transform_records(log_records: Iterable[Optional[Record]], replacements: Dict[(str, Any)]) -> Generator[(Record, None, None)]:
def replace(value: Any) -> Any:
if (isinstance(value, tuple) and hasattr(value, '_fields')):
return type(value)(*[replace(inner) for inner in value])
if isin... |
def test_measurable_elemwise():
with pytest.raises(TypeError, match=re.escape('scalar_op exp is not valid')):
MeasurableElemwise(exp)
class TestMeasurableElemwise(MeasurableElemwise):
valid_scalar_types = (Exp,)
measurable_exp_op = TestMeasurableElemwise(scalar_op=exp)
measurable_exp = m... |
class AnnouncementMonth(AnnouncementMixin, MonthArchiveView):
template_name = 'dictionary/announcements/month.html'
date_list_period = 'month'
context_object_name = 'latest'
def get_date_list(self, queryset, **kwargs):
return super().get_date_list(queryset=self.model.objects.all(), ordering='DES... |
class DuplicateDialog(Gtk.Window):
def __quit(self, widget=None, response=None):
if ((response == Gtk.ResponseType.OK) or (response == Gtk.ResponseType.CLOSE)):
print_d('Exiting plugin on user request...')
self.finished = True
self.destroy()
return
def __songs_popup_m... |
class MaxPressureAgent(Agent):
def __init__(self, dic_agent_conf, dic_traffic_env_conf, dic_path, cnt_round, intersection_id):
super(MaxPressureAgent, self).__init__(dic_agent_conf, dic_traffic_env_conf, dic_path, intersection_id)
self.current_phase_time = 0
self.phase_length = len(self.dic_... |
class RegistrationForm(form.Form):
login = fields.StringField(render_kw={'placeholder': 'Username'})
password = fields.PasswordField(render_kw={'placeholder': 'Password'})
def validate_login(self, field):
if User.objects(login=self.login.data):
raise validators.ValidationError('Duplicate... |
def get_resnetd(blocks, conv1_stride=True, width_scale=1.0, model_name=None, pretrained=False, root=os.path.join('~', '.torch', 'models'), **kwargs):
if (blocks == 10):
layers = [1, 1, 1, 1]
elif (blocks == 12):
layers = [2, 1, 1, 1]
elif (blocks == 14):
layers = [2, 2, 1, 1]
eli... |
def url_name(request):
try:
match = resolve(request.path)
except Resolver404:
return {}
else:
(namespace, url_name_) = (match.namespace, match.url_name)
if namespace:
url_name_ = f'{namespace}:{url_name_}'
return {'URL_NAMESPACE': namespace, 'URL_NAME': ur... |
def user_details(strategy, details, backend, user=None, *args, **kwargs):
if (not user):
return
changed = False
if (strategy.setting('NO_DEFAULT_PROTECTED_USER_FIELDS') is True):
protected = ()
else:
protected = ('username', 'id', 'pk', 'email', 'password', 'is_active', 'is_staff... |
def expect_element(__funcname=_qualified_name, **named):
def _expect_element(collection):
if isinstance(collection, (set, frozenset)):
collection_for_error_message = tuple(sorted(collection))
else:
collection_for_error_message = collection
template = "%(funcname)s() e... |
def cov_maxGrad_off_maxHess(value_at_max, sigma, l):
d = len(value_at_max)
num_hessian_combo = int(((d * (d - 1)) / 2))
cov_matrix = np.zeros((d, num_hessian_combo))
for i in range(d):
index = 0
for j in range(d):
for k in range((j + 1), d):
cov_matrix[(i, ind... |
class Effect7211(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Medium Precursor Weapon')), 'damageMultiplierBonusMax', ship.getModifiedItemAttr('eliteBonusHeavyGunship1'), skill='Heavy Assault ... |
class All2Cross(nn.Module):
def __init__(self, config, img_size=224, in_chans=3, embed_dim=(96, 384), norm_layer=nn.LayerNorm):
super().__init__()
self.cross_pos_embed = config.cross_pos_embed
self.pyramid = PyramidFeatures(config=config, img_size=img_size, in_channels=in_chans)
n_p1... |
def test_dual_map(page: Page):
page.get_by_role('link', name='misc examples').click()
page.get_by_role('link', name='misc examples').click()
expect(page).to_have_title('streamlit-folium documentation: Misc Examples')
page.locator('label').filter(has_text='Dual map').click()
page.locator('label').fil... |
def add_eval_sample_opts(parser):
parser.add_argument('--sample_method', type=str, default='greedy', help='greedy; sample; gumbel; top<int>, top<0-1>')
parser.add_argument('--beam_size', type=int, default=1, help='used when sample_method = greedy, indicates number of beams in beam search. Usually 2 or 3 works w... |
def determine_num_input_channels(plans_manager: PlansManager, configuration_or_config_manager: Union[(str, ConfigurationManager)], dataset_json: dict) -> int:
if isinstance(configuration_or_config_manager, str):
config_manager = plans_manager.get_configuration(configuration_or_config_manager)
else:
... |
class ISNetGTEncoder(nn.Module):
def __init__(self, in_ch=1, out_ch=1):
super(ISNetGTEncoder, self).__init__()
self.conv_in = myrebnconv(in_ch, 16, 3, stride=2, padding=1)
self.stage1 = RSU7(16, 16, 64)
self.pool12 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
self.stage2 = RSU... |
class PlayClickWindow(Packet):
id = 9
to = 0
def __init__(self, window_id: int, slot_number: int, button: int, action_number: int, mode: int, slot: dict) -> None:
super().__init__()
self.window_id = window_id
self.slot_number = slot_number
self.button = button
self.ac... |
class FC3_TestCase(CommandTest):
command = 'lilocheck'
def runTest(self):
self.assert_parse('lilocheck', 'lilocheck\n')
self.assert_parse_error('lilocheck foo')
self.assert_parse_error('lilocheck --whatever')
cmd = self.handler().commands[self.command]
cmd.check = False
... |
def test_system_exit_in_setuppy(monkeypatch, tmp_path):
monkeypatch.chdir(tmp_path)
setuppy = "import sys; sys.exit('some error')"
(tmp_path / 'setup.py').write_text(setuppy, encoding='utf-8')
with pytest.raises(SystemExit, match='some error'):
backend = BuildBackend(backend_name='setuptools.bui... |
def main():
log_file = 'train.log'
logger = create_logger(log_file)
assert os.path.exists(args.config)
cfg = yaml.load(open(args.config, 'r'), Loader=yaml.Loader)
set_random_seed(cfg['random_seed'])
dataset_helper = Kitti_Config()
if args.evaluation:
cfg['dataset']['train']['enable']... |
def comments_and_tags_of_parameters_of(*, function_name, args, no_extraction=False):
if (len(args) == 0):
return ([], [], [], [])
comments1 = ([''] * len(args))
comments2 = [[''] for _ in args]
tags1 = ([''] * len(args))
tags2 = [[''] for _ in args]
if (no_extraction or options.sober):
... |
class TestLayerSelector(unittest.TestCase):
def test_select_all_conv_layers(self):
mock_output_shape = (1, 1, 1, 1)
layer1 = Layer(Conv2d(10, 20, 5), '', mock_output_shape)
layer2 = Layer(Conv2d(10, 20, 5), '', mock_output_shape)
layer3 = Layer(Conv2d(10, 10, 5, groups=10), '', mock_... |
class RequiredTextAssetConfiguration(AssetConfigurationMixin, BaseRequiredTextAsset, BenefitFeatureConfiguration):
class Meta(BaseRequiredTextAsset.Meta, BenefitFeatureConfiguration.Meta):
verbose_name = 'Require Text Configuration'
verbose_name_plural = 'Require Text Configurations'
constra... |
class MixerBlock(nn.Module):
def __init__(self, tokens_mlp_dim=16, channels_mlp_dim=1024, tokens_hidden_dim=32, channels_hidden_dim=1024):
super().__init__()
self.ln = nn.LayerNorm(channels_mlp_dim)
self.tokens_mlp_block = MlpBlock(tokens_mlp_dim, mlp_dim=tokens_hidden_dim)
self.chan... |
.parametrize('regex,doc', [(signature.SPHINX, ' :param test: parameter docstring'), (signature.EPYDOC, ' test: parameter docstring'), (signature.GOOGLE, ' test (str): parameter docstring')])
def test_docstring_params(regex, doc):
m = regex.match(doc)
assert (m.group('param') == 'test')
assert (m.g... |
class WhoamiCommand(BaseUserCommand):
def run(self):
token = HfFolder.get_token()
if (token is None):
print('Not logged in')
exit()
try:
user = self._api.whoami(token)
print(user)
except HTTPError as e:
print(e) |
class MachPortManager():
def __init__(self, ql, my_port):
self.ql = ql
self.host_port = MachPort(771)
self.clock_port = MachPort(2051)
self.semaphore_port = MachPort(2307)
self.special_port = MachPort(1799)
self.my_port = my_port
def deal_with_msg(self, msg, addr)... |
class BaseTrainer(nn.Module):
def __init__(self, experiment_name=None, warm_start=False, verbose=False, num_averaged_checkpoints=1, keep_checkpoints=None, **extra_attrs):
super().__init__()
self.keep_checkpoints = (keep_checkpoints or num_averaged_checkpoints)
self.num_averaged_checkpoints =... |
_tokenizers
class RetriBertTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
tokenizer_class = RetriBertTokenizer
test_slow_tokenizer = True
rust_tokenizer_class = RetriBertTokenizerFast
test_rust_tokenizer = True
space_between_special_tokens = True
from_pretrained_filter = filter_non_e... |
def convert_database_command_logic(args):
from randovania.game_description import data_reader, data_writer
data = decode_data_file(args)
if args.decode_to_game_description:
data = data_writer.write_game_description(data_reader.decode_data(data))
output_binary: (Path | None) = args.output_binary
... |
def check_all_python_exist(*, platform_configs: Iterable[PythonConfiguration], container: OCIContainer) -> None:
exist = True
has_manylinux_interpreters = True
messages = []
try:
container.call(['manylinux-interpreters', '--help'], capture_output=True)
except subprocess.CalledProcessError:
... |
class SubCommand(Protocol):
editable_mode: bool = False
build_lib: str
def initialize_options(self):
def finalize_options(self):
def run(self):
def get_source_files(self) -> List[str]:
def get_outputs(self) -> List[str]:
def get_output_mapping(self) -> Dict[(str, str)]: |
def date_key(datestr):
default = [0, 1, 1]
parts = datestr.split('-')
parts += default[len(parts):]
value = 0
for (d, p, m) in zip(default, parts, (10000, 100, 1), strict=False):
try:
value += (int(p) * m)
except ValueError:
value += (d * m)
return value |
class TestSetSelectionOwner(EndianTest):
def setUp(self):
self.req_args_0 = {'selection': , 'time': , 'window': }
self.req_bin_0 = b'\x16\x00\x00\\x144\xafa\x88\xfa7\x16\xdf\x10\x9a'
def testPackRequest0(self):
bin = request.SetSelectionOwner._request.to_binary(*(), **self.req_args_0)
... |
class CmdApproach(Command):
key = 'approach'
help_category = 'combat'
def func(self):
if (not is_in_combat(self.caller)):
self.caller.msg('You can only do that in combat. (see: help fight)')
return
if (not is_turn(self.caller)):
self.caller.msg('You can on... |
class BloombergFutureTicker(FutureTicker, BloombergTicker):
def __init__(self, name: str, family_id: str, N: int, days_before_exp_date: int, point_value: int=1, designated_contracts: str='FGHJKMNQUVXZ', security_type: SecurityType=SecurityType.FUTURE):
if (not (len(designated_contracts) > 0)):
r... |
def ChaCha20_round(H):
for (a, b, c, d) in ORDERS_CHACHA20:
H[a] += H[b]
H[d] = ROL((H[d] ^ H[a]), 16)
H[c] += H[d]
H[b] = ROL((H[b] ^ H[c]), 12)
H[a] += H[b]
H[d] = ROL((H[d] ^ H[a]), 8)
H[c] += H[d]
H[b] = ROL((H[b] ^ H[c]), 7)
return H |
class PerlinNoiseFactory():
def __init__(self, dimension: int, octaves: int=1, tile: tuple[(int, ...)]=(), unbias: bool=False):
self.dimension = dimension
self.octaves = octaves
self.tile = (tile + ((0,) * dimension))
self.unbias = unbias
self.scale_factor = (2 * (dimension *... |
def get_train_batch(b):
begin = (b * _batch_size)
end = min(len(_data_generator.pos_list), (begin + _batch_size))
(u_batch, po_batch, plen_batch, no_batch, nlen_batch) = ([], [], [], [], [])
for p in range(begin, end):
(u, pos_o) = _data_generator.pos_list[p]
neg_o = pos_o
while ... |
def test_const_connect_nested_struct_signal_to_struct():
class SomeMsg1():
a: Bits8
b: Bits32
class SomeMsg2():
a: SomeMsg1
b: Bits32
class Top(ComponentLevel3):
def construct(s):
s.out = OutPort(SomeMsg2)
connect(s.out, SomeMsg2(SomeMsg1(1, 2)... |
class TwoLayerBidirectionalLSTMModel(nn.Module):
def __init__(self):
super(TwoLayerBidirectionalLSTMModel, self).__init__()
self.recurrent = torch.nn.LSTM(input_size=3, hidden_size=5, num_layers=2, bidirectional=True)
def forward(self, x, hx=None):
return self.recurrent(x, hx) |
def test_replace():
class SomethingElse():
def foo(self, n, y=None):
assert None, 'This should never be reached in this test'
s = SomethingElse()
def replacement(n, y=None):
return y
original_method = s.foo.__func__
with replaced(s.foo, replacement):
assert (s.foo... |
def caesarCipher(s, k):
encr_string = ''
for letter in s:
if letter.isalpha():
uni = ord(letter)
base = (97 if letter.islower() else 65)
balance = (((uni + k) - base) % 26)
encr_string += chr((balance + base))
else:
encr_string += lette... |
('(float32, float32, float32[:])', device=True, inline=True)
def point_in_quadrilateral(pt_x, pt_y, corners):
ab0 = (corners[2] - corners[0])
ab1 = (corners[3] - corners[1])
ad0 = (corners[6] - corners[0])
ad1 = (corners[7] - corners[1])
ap0 = (pt_x - corners[0])
ap1 = (pt_y - corners[1])
ab... |
class QuantAnalyzer():
def __init__(self, model: tf.keras.Model, forward_pass_callback: CallbackFunc, eval_callback: CallbackFunc):
if (not isinstance(forward_pass_callback, CallbackFunc)):
raise ValueError('forward_pass_callback and its argument(s) are not encapsulated by CallbackFunc class.')
... |
.cli
.network
_CLI_ENDPONTS
def test_sync__area_of_use__list(input_command, tmpdir):
with tmp_chdir(str(tmpdir)):
output = subprocess.check_output((input_command + ['sync', '--area-of-use', 'France', '--list-files', '--include-already-downloaded']), stderr=subprocess.STDOUT).decode('utf-8')
lines = outp... |
class Effect5500(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredChargeBoost((lambda mod: mod.charge.requiresSkill('Heavy Missiles')), 'aoeCloudSize', ship.getModifiedItemAttr('eliteBonusCommandShips2'), skill='Command Ships', **kwargs) |
.parametrize(('tag', 'node_date', 'expected'), [pytest.param('20.03.03', date(2020, 3, 4), '20.03.04.0', id='next day'), pytest.param('20.03.03', date(2020, 3, 3), '20.03.03.1', id='same day'), pytest.param('20.03.03.2', date(2020, 3, 3), '20.03.03.3', id='same day with patch'), pytest.param('v20.03.03', date(2020, 3, ... |
.parametrize('strategy, level', ([PropagateCastOpsStrategy.NONE, PropagateCastLevel.NOT_USED], [PropagateCastOpsStrategy.INSERT_AND_REDUCE, PropagateCastLevel.FASTER_KEEP_PRECISION], [PropagateCastOpsStrategy.FLOOD_FILL, PropagateCastLevel.FASTER_KEEP_PRECISION]))
def test_set_propagate_cast(strategy, level):
(D_in... |
def test_version_increments_are_correct():
(versions, _) = zip(*get_releases())
for (prev, current) in zip(versions[1:], versions):
assert (prev < current)
assert (current in (prev._replace(patch=(prev.patch + 1)), prev._replace(minor=(prev.minor + 1), patch=0), prev._replace(major=(prev.major +... |
class TestLayerOutputUtil():
def test_generate_layer_outputs(self):
(quantsim, starting_ops, output_ops, output_names, dummy_input) = get_quantsim_artifacts()
(dummy_dataset, data_count, first_input) = get_dataset_artifacts()
temp_dir_path = os.path.dirname(os.path.abspath(__file__))
... |
def pytest_generate_tests(metafunc):
if ('host' in metafunc.fixturenames):
for marker in getattr(metafunc.function, 'pytestmark', []):
if (marker.name == 'testinfra_hosts'):
hosts = marker.args
break
else:
hosts = ['docker://debian_bookworm']
... |
('pypyr.retries.random.uniform', return_value=999)
def test_retries_jitter_list_jrc_up_max(mock_random):
j = pypyr.retries.jitter(sleep=[100, 200, 300], jrc=2, max_sleep=200)
assert (j(0) == 999)
assert (j(1) == 999)
assert (j(2) == 999)
assert (j(1) == 999)
assert (mock_random.mock_calls == [ca... |
class Distribution(_Distribution):
def __init__(self, attrs=None):
_Distribution.__init__(self, attrs)
if (not self.ext_modules):
return
for idx in range((len(self.ext_modules) - 1), (- 1), (- 1)):
ext = self.ext_modules[idx]
if (not isinstance(ext, Extens... |
def draw_words(transcribed_data, midi_notes):
if (transcribed_data is not None):
for (i, data) in enumerate(transcribed_data):
note_frequency = librosa.note_to_hz(midi_notes[i])
frequency_range = get_frequency_range(midi_notes[i])
half_frequency_range = (frequency_range /... |
def _iter_sections(lines):
lines = (line.split('#')[0].strip() for line in lines)
name = None
section = None
for line in lines:
if (not line):
continue
if (line.startswith('[') and line.endswith(']')):
if name:
(yield (name, section))
n... |
class OrderCriterion(Criterion):
def __init__(self, term, direction):
super(OrderCriterion, self).__init__()
self.term = term
self.direction = direction
def get_query(self, **kwargs):
term = self.term.get_query(**kwargs)
if ((self.direction == Order.asc) or (isinstance(se... |
class DefaultArgumentHandler(ArgumentHandler):
def __call__(self, *args, **kwargs):
if ('X' in kwargs):
return kwargs['X']
elif ('data' in kwargs):
return kwargs['data']
elif (len(args) == 1):
if isinstance(args[0], list):
return args[0]
... |
class CNOT(Bloq):
_property
def signature(self) -> 'Signature':
return Signature.build(ctrl=1, target=1)
def decompose_bloq(self) -> 'CompositeBloq':
raise DecomposeTypeError(f'{self} is atomic')
def add_my_tensors(self, tn: qtn.TensorNetwork, tag: Any, *, incoming: Dict[(str, SoquetT)],... |
def alt(*parsers: Parser) -> Parser:
if (not parsers):
return fail('<empty alt>')
def alt_parser(stream, index):
result = None
for parser in parsers:
result = parser(stream, index).aggregate(result)
if result.status:
return result
return re... |
_args
class PrepareLiterals(Transformer_InPlace):
def literal(self, literal):
return ST('pattern', [_literal_to_pattern(literal)])
def range(self, start, end):
assert (start.type == end.type == 'STRING')
start = start.value[1:(- 1)]
end = end.value[1:(- 1)]
assert (len(ev... |
class ROIAlign(nn.Module):
def __init__(self, output_size, spatial_scale, sampling_ratio, aligned=True):
super().__init__()
self.output_size = output_size
self.spatial_scale = spatial_scale
self.sampling_ratio = sampling_ratio
self.aligned = aligned
from torchvision i... |
('/json/update_accounts', methods=['POST'], endpoint='update_accounts')
_required('ACCOUNTS')
def update_accounts():
deleted = []
updated = {}
api = flask.current_app.config['PYLOAD_API']
for (name, value) in flask.request.form.items():
value = value.strip()
if (not value):
c... |
def convert_pandas_data_frame_to_bokeh_data_table(data):
data['index'] = data.index
data = data[(['index'] + data.columns[:(- 1)].tolist())]
data.columns.map(str)
source = ColumnDataSource(data=data)
columns = [TableColumn(field=column_str, title=column_str) for column_str in data.columns]
data_... |
def test_L1_const_index():
a = CaseConnectConstToOutComp.DUT()
a.elaborate()
a.apply(StructuralRTLIRGenL1Pass(gen_connections(a)))
connections = a.get_metadata(StructuralRTLIRGenL1Pass.connections)
comp = sexp.CurComp(a, 's')
assert (connections == [(sexp.ConstInstance(Bits32(a.const_[2]), 42), ... |
class LinearFeatureBaseline(Baseline):
def __init__(self, env_spec, reg_coeff=1e-05):
self._coeffs = None
self._reg_coeff = reg_coeff
def get_param_values(self, **tags):
return self._coeffs
def set_param_values(self, val, **tags):
self._coeffs = val
def _features(self, pa... |
def _lambert_conformal_conic(cf_params):
(first_parallel, second_parallel) = _get_standard_parallels(cf_params['standard_parallel'])
if (second_parallel is not None):
return LambertConformalConic2SPConversion(latitude_first_parallel=first_parallel, latitude_second_parallel=second_parallel, latitude_fals... |
def resize_min_side(im, size, method):
(h, w) = im.shape[(- 2):]
min_side = min(h, w)
ratio = (size / min_side)
if (method == 'bilinear'):
return F.interpolate(im, scale_factor=ratio, mode=method, align_corners=False)
else:
return F.interpolate(im, scale_factor=ratio, mode=method) |
def simu_subtomo(op, packing_op, output, save_tomo=0, save_target=1, save_tomo_slice=0):
import datetime
starttime = datetime.datetime.now()
v = op['v']
import packing_single_sphere.simulate as SI
target_name = packing_op['target']
packing_result = SI.packing_with_target(packing_op)
protein_... |
def _do_test_3D_models(recognizer, target_layer_name, input_shape, num_classes=400):
(blended_imgs_target_shape, preds_target_shape) = _get_target_shapes(input_shape, num_classes=num_classes, model_type='3D')
demo_inputs = generate_gradcam_inputs(input_shape, '3D')
if (torch.__version__ == 'parrots'):
... |
class BSplineFamily(BasisFamily):
def __init__(self, breakpoints, degree, smoothness=None, vars=None):
breakpoints = np.array(breakpoints, dtype=float)
if (breakpoints.ndim == 2):
raise NotImplementedError('breakpoints for each spline variable not yet supported')
elif (breakpoint... |
class ToTensor(object):
def __init__(self, is_test=False):
self.is_test = is_test
def __call__(self, sample):
(image, depth) = (sample['image'], sample['depth'])
image = self.to_tensor(image)
if self.is_test:
depth = (self.to_tensor(depth).float() / 1000)
else... |
class F8_RepoData(FC6_RepoData):
removedKeywords = FC6_RepoData.removedKeywords
removedAttrs = FC6_RepoData.removedAttrs
def __init__(self, *args, **kwargs):
FC6_RepoData.__init__(self, *args, **kwargs)
self.cost = kwargs.get('cost', None)
self.includepkgs = kwargs.get('includepkgs',... |
def test_django_assert_num_queries_output(django_pytester: DjangoPytester) -> None:
django_pytester.create_test_module('\n from django.contrib.contenttypes.models import ContentType\n import pytest\n\n .django_db\n def test_queries(django_assert_num_queries):\n with django_ass... |
class UT_HAR_BiLSTM(nn.Module):
def __init__(self, hidden_dim=64):
super(UT_HAR_BiLSTM, self).__init__()
self.lstm = nn.LSTM(90, hidden_dim, num_layers=1, bidirectional=True)
self.fc = nn.Linear(hidden_dim, 7)
def forward(self, x):
x = x.view((- 1), 250, 90)
x = x.permute... |
def test_const_connect_nested_struct_signal_to_struct():
class SomeMsg1():
a: Bits8
b: Bits32
class SomeMsg2():
a: SomeMsg1
b: Bits32
class Top(Component):
def construct(s):
s.out = OutPort(SomeMsg2)
connect(s.out, SomeMsg2(SomeMsg1(1, 2), 3))
... |
def main(_):
assert FLAGS.checkpoint_dir, '--checkpoint_dir is required'
if (not os.path.isfile(FLAGS.index_file)):
print('index pickle file {} does not exist'.format(FLAGS.index_file))
return
if (not os.path.isfile(FLAGS.bshape_base_file)):
print(' bshape base file {} does not exist... |
_fixtures(WebFixture, FileUploadInputFixture)
def test_prevent_duplicate_upload_js(web_fixture, file_upload_input_fixture):
fixture = file_upload_input_fixture
web_fixture.reahl_server.set_app(fixture.new_wsgi_app(enable_js=True))
browser = web_fixture.driver_browser
error_locator = XPath.span().includi... |
def test_multiple_timers(minimal_conf_noscreen, manager_nospawn):
config = minimal_conf_noscreen
config.screens = [libqtile.config.Screen(top=libqtile.bar.Bar([TimerWidget(10)], 10))]
manager_nospawn.start(config)
assert (manager_nospawn.c.widget['timerwidget'].get_active_timers() == 0)
manager_nosp... |
def get_preprocess_fn(data_args: argparse.Namespace, processor: Union[(PangoCairoTextRenderer, PreTrainedTokenizerFast)], modality: Modality, split: Split, column_names: List[str]):
question_column_name = ('question' if ('question' in column_names) else column_names[0])
context_column_name = ('context' if ('con... |
def test_keys_args_parses_to_dict():
out = pypyr.parser.keys.get_parsed_context(['value 1', 'value 2', 'value3'])
assert out['value 1'], 'value 1 should be True'
assert out['value 2'], 'value 2 should be True'
assert out['value3'], 'value 3 should be True'
assert (len(out) == 3), '3 items expected' |
def test_connect_wr_x_conn_As_rd_y_conn_A_mark_writer():
class Top(ComponentLevel3):
def construct(s):
s.x = Wire(Bits24)
s.A = Wire(Bits32)
s.y = Wire(Bits32)
connect(s.A[8:32], s.x)
connect(s.A, s.y)
def up_wr_x():
s.x... |
class TestShadowRoot(PyScriptTest):
.skip('NEXT: Element interface is gone. Replace with PyDom')
def test_reachable_shadow_root(self):
self.pyscript_run('\n <script>\n // reason to wait for py-script is that it\'s the entry point for\n // all patches and the Muta... |
def create_parquet_in_tempdir(filename: str, num_rows: int, num_features: int, num_classes: int=2, num_partitions: int=1) -> Tuple[(str, str)]:
temp_dir = tempfile.mkdtemp()
path = os.path.join(temp_dir, filename)
create_parquet(path, num_rows=num_rows, num_features=num_features, num_classes=num_classes, nu... |
class WafToApiGatewayConstruct(Construct):
def __init__(self, scope: Construct, id: str, api: apigateway.RestApi, **kwargs) -> None:
super().__init__(scope, id, **kwargs)
web_acl = waf.CfnWebACL(self, 'ProductApiGatewayWebAcl', scope='REGIONAL', default_action=waf.CfnWebACL.DefaultActionProperty(all... |
class MakeKeysStrTests(unittest.TestCase):
def test_bytes(self):
expected_string = 'key_1,key_2'
keys = [b'key_1', b'key_2']
self.assertEqual(expected_string, make_keys_str(keys))
def test_str(self):
expected_string = 'key_1,key_2'
keys = ['key_1', 'key_2']
self.a... |
class TypeguardTest(TestCase):
def test_trivial_fail(self):
with self.assertRaises(Exception):
fun(42)
def test_success(self):
fun(np.random.randn(2, 2))
def test_fail_shape(self):
with self.assertRaises(Exception):
fun(np.random.randn(3, 2))
def test_fail... |
.parametrize('prefer_grpc', [False, True])
def test_points_crud(prefer_grpc):
client = QdrantClient(prefer_grpc=prefer_grpc, timeout=TIMEOUT)
client.recreate_collection(collection_name=COLLECTION_NAME, vectors_config=VectorParams(size=DIM, distance=Distance.DOT), timeout=TIMEOUT)
client.upsert(collection_na... |
def test_wild_extra_targets(debug_ctx, debug_trail, acc_schema):
dumper_getter = make_dumper_getter(shape=shape(TestField('a', acc_schema.accessor_maker('a', is_required=True))), name_layout=OutputNameLayout(crown=OutDictCrown({'a': OutFieldCrown('a')}, sieves={}), extra_move=ExtraTargets(('b',))), debug_trail=debu... |
_model
def randformer_s36(pretrained=False, **kwargs):
model = MetaFormer(depths=[6, 6, 18, 6], dims=[64, 128, 320, 512], token_mixers=[nn.Identity, nn.Identity, RandomMixing, partial(RandomMixing, num_tokens=49)], norm_layers=partial(LayerNormGeneral, normalized_dim=(1, 2, 3), eps=1e-06, bias=False), **kwargs)
... |
class TestIgnoreWorkbookCorruption(TestCase):
def test_not_corrupted(self):
with self.assertRaises(Exception) as context:
xlrd.open_workbook(from_sample('corrupted_error.xls'))
self.assertTrue(('Workbook corruption' in str(context.exception)))
xlrd.open_workbook(from_sample('corr... |
class RejectSponsorshipApplicationUseCaseTests(TestCase):
def setUp(self):
self.notifications = [Mock(), Mock()]
self.use_case = use_cases.RejectSponsorshipApplicationUseCase(self.notifications)
self.user = baker.make(settings.AUTH_USER_MODEL)
self.sponsorship = baker.make(Sponsorshi... |
class GAN_decoder_AE(nn.Module):
def __init__(self, params):
super(GAN_decoder_AE, self).__init__()
input_dim_b = params['input_dim_b']
ch = params['ch']
n_gen_res_blk = params['n_gen_res_blk']
n_gen_front_blk = params['n_gen_front_blk']
if ('res_dropout_ratio' in par... |
class SpectralAudioParser():
def __init__(self, input_audio, offset, frames_per_second, filters):
if (len(filters) < 1):
raise RuntimeError('When using input_audio, at least 1 filter must be specified')
pipe = subprocess.Popen(['ffmpeg', '-i', input_audio, '-f', 's16le', '-acodec', 'pcm_... |
def setup_checkpoint_config(args):
save_checkpoints_config = {}
save_checkpoints_config['model_state_dict'] = (True if args.checkpoint_save_model else False)
save_checkpoints_config['optimizer_state_dict'] = (True if args.checkpoint_save_optim else False)
save_checkpoints_config['train_metric_info'] = (... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.