code stringlengths 281 23.7M |
|---|
def cal_train_time(log_dicts, args):
for (i, log_dict) in enumerate(log_dicts):
print('{}Analyze train time of {}{}'.format(('-' * 5), args.json_logs[i], ('-' * 5)))
all_times = []
for epoch in log_dict.keys():
if args.include_outliers:
all_times.append(log_dict[e... |
def check_any_dt(loader):
raises_exc(TypeLoadError(str, None), (lambda : loader(None)))
raises_exc(TypeLoadError(str, 10), (lambda : loader(10)))
raises_exc(TypeLoadError(str, datetime(2011, 11, 4, 0, 0)), (lambda : loader(datetime(2011, 11, 4, 0, 0))))
raises_exc(TypeLoadError(str, date(2019, 12, 4)), ... |
def test(arg=None):
if (arg == '-v'):
def say(*x):
print(*x)
else:
def say(*x):
pass
say('Start Pool testing')
get_tid = (lambda : threading.current_thread().ident)
def return42():
return 42
def f(x):
return (x * x)
def work(mseconds):
... |
class NordStyle(Style):
name = 'nord'
line_number_color = '#D8DEE9'
line_number_background_color = '#242933'
line_number_special_color = '#242933'
line_number_special_background_color = '#D8DEE9'
background_color = '#2E3440'
highlight_color = '#3B4252'
styles = {Token: '#d8dee9', Whitesp... |
.parametrize('type', ['Error', 'Failure'])
def test_testcase_custom_exception_info(pytester: Pytester, type: str) -> None:
pytester.makepyfile(('\n from typing import Generic, TypeVar\n from unittest import TestCase\n import pytest, _pytest._code\n\n class MyTestCase(TestCase):\n ... |
class DeterministicMLPRegressor(LayersPowered, Serializable):
def __init__(self, name, input_shape, output_dim, network=None, hidden_sizes=(32, 32), hidden_nonlinearity=tf.nn.tanh, output_nonlinearity=None, optimizer=None, normalize_inputs=True):
Serializable.quick_init(self, locals())
with tf.varia... |
_module()
class TridentResNet(ResNet):
def __init__(self, depth, num_branch, test_branch_idx, trident_dilations, **kwargs):
assert (num_branch == len(trident_dilations))
assert (depth in (50, 101, 152))
super(TridentResNet, self).__init__(depth, **kwargs)
assert (self.num_stages == 3... |
class TestSetContent(BaseTestCase):
expectedOutput = '<html><head></head><body><div>hello</div></body></html>'
async def test_set_content(self):
(await self.page.setContent('<div>hello</div>'))
result = (await self.page.content())
self.assertEqual(result, self.expectedOutput)
async d... |
class IncSubtensor(COp):
check_input = False
__props__ = ('idx_list', 'inplace', 'set_instead_of_inc')
def __init__(self, idx_list, inplace=False, set_instead_of_inc=False, destroyhandler_tolerate_aliased=None):
if (destroyhandler_tolerate_aliased is None):
destroyhandler_tolerate_aliase... |
class UsersViewsTestCase(TestCase):
def setUp(self):
self.user = UserFactory(username='username', password='password', email='', search_visibility=User.SEARCH_PUBLIC, membership=None)
self.user2 = UserFactory(username='spameggs', password='password', search_visibility=User.SEARCH_PRIVATE, email_priv... |
def filter_by_aspect(dataset, aspect_filter, use_attribute=False):
for example in dataset:
example = copy(example)
aspect_sentiment = defaultdict(list)
for (a, b) in example['aspect_sentiment']:
if ((aspect_filter is not None) and (a not in aspect_filter)):
contin... |
class Dilation2d(nn.Layer):
def __init__(self, m=1):
super(Dilation2d, self).__init__()
self.m = m
self.pad = [m, m, m, m]
def forward(self, x):
(batch_size, c, h, w) = x.shape
x_pad = F.pad(x, pad=self.pad, mode='constant', value=(- .0))
channel = nn.functional.u... |
class LNChannelVerifier(NetworkJobOnDefaultServer):
def __init__(self, network: 'Network', channel_db: 'ChannelDB'):
self.channel_db = channel_db
self.lock = threading.Lock()
self.unverified_channel_info = {}
self.blacklist = set()
NetworkJobOnDefaultServer.__init__(self, net... |
class HerbertTokenizer(XLMTokenizer):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
def __init__(self, vocab_file, merges_file,... |
class Effect7076(BaseEffect):
type = 'passive'
def handler(fit, container, context, projectionRange, **kwargs):
level = (container.level if ('skill' in context) else 1)
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Large Disintegrator Specialization')), 'damageMultiplier', (... |
class RankSubmission(models.Model):
rank_request = models.ForeignKey(RankRequest, on_delete=models.CASCADE, verbose_name=_('rank request'), related_name='rank_submissions')
tag = models.ForeignKey('submissions.SubmissionTag', on_delete=models.CASCADE, verbose_name=_('tag'), null=True)
total_submissions_per_... |
class VGGMultiLayerEncoder(ModelMultiLayerEncoder):
def __init__(self, arch: str, **kwargs: Any) -> None:
_parse_arch(arch)
self.arch = arch
super().__init__(**kwargs)
def state_dict_url(self, framework: str) -> str:
return select_url(self.arch, framework)
def collect_modules... |
def batching_list_instances(config: Config, insts: List[Instance]):
train_num = len(insts)
batch_size = config.batch_size
total_batch = (((train_num // batch_size) + 1) if ((train_num % batch_size) != 0) else (train_num // batch_size))
batched_data = []
for batch_id in range(total_batch):
on... |
class TwoStepParameters5(TwoStepParametersCommon):
zka_id = DataElementField(type='an', max_length=32, _d='ZKA TAN-Verfahren')
zka_version = DataElementField(type='an', max_length=10, _d='Version ZKA TAN-Verfahren')
name = DataElementField(type='an', max_length=30, _d='Name des Zwei-Schritt-Verfahrens')
... |
def create_quant_sim_model(sess: tf.Session, start_op_names: List[str], output_op_names: List[str], use_cuda: bool, evaluator: Callable[([tf.Session, Any], None)], logdir: str) -> QuantizationSimModel:
copied_sess = save_and_load_graph(sess=sess, meta_path=logdir)
quant_scheme = QuantScheme.training_range_learn... |
class Bool(BaseType):
def __init__(self, *, none_ok: bool=False, completions: _Completions=None) -> None:
super().__init__(none_ok=none_ok, completions=completions)
self.valid_values = ValidValues('true', 'false', generate_docs=False)
def to_py(self, value: Union[(bool, str, None)]) -> Optional[... |
class PWGOptimizer():
def __init__(self, model: ParallelWaveGAN, generator_optimizer_params={'lr': 0.0001, 'eps': 1e-06}, generator_scheduler_params={'step_size': 200000, 'gamma': 0.5}, discriminator_optimizer_params={'lr': 5e-05, 'eps': 1e-06}, discriminator_scheduler_params={'step_size': 200000, 'gamma': 0.5}):
... |
def test_location_pool_row_actions(pickup_node, skip_qtbot):
widget = LocationPoolRowWidget(pickup_node, 'Fancy name for a pickup')
skip_qtbot.addWidget(widget)
signal_received = False
def edit_closure():
nonlocal signal_received
signal_received = True
widget.changed.connect(edit_clo... |
class FC4_TestCase(FC3_TestCase):
def runTest(self):
FC3_TestCase.runTest(self)
self.assert_parse(('raid / --device=md0 --fstype="ext3" --level=6 --fsoptions "these=are,options"%s raid.01 raid.02' % self.bytesPerInode), ('raid / --device=0 --fstype="ext3" --level=RAID6 --fsoptions="these=are,options... |
class ELF32_Rela(ELF_Rela):
Rela_SIZE = (4 * 3)
def __init__(self, buf, endian=0, ptr=None):
if (len(buf) != self.Rela_SIZE):
raise
self.ptr = ptr
self.fmt = ('<IIi' if (endian == 0) else '>IIi')
(r_offset, r_info, r_addend) = struct.unpack(self.fmt, buf)
supe... |
class Config():
output_dir = 'outputs'
model_dir = os.path.join(output_dir, 'model_dump')
eval_dir = os.path.join(output_dir, 'eval_dump')
init_weights = '/data/model/resnet50_fbaug.pth'
image_mean = np.array([103.53, 116.28, 123.675])
image_std = np.array([57.375, 57.12, 58.395])
train_imag... |
class Agent(object):
def __init__(self, *args, **kwargs):
pass
def init_states(self, *args, **kwargs):
raise NotImplementedError
def update_states(self, states, new_state):
raise NotImplementedError
def finish_eval(self, states, new_state):
raise NotImplementedError
d... |
class TestQuantizationSimTransformers(unittest.TestCase):
def test_gelu_static_quantization(self):
model = ConvGeLUNet()
model.eval()
input_shapes = (1, 3, 32, 32)
inp_tensor_list = create_rand_tensors_given_shapes(input_shapes, utils.get_device(model))
def forward_pass(model... |
def main():
if (len(sys.argv) < 2):
print((('usage: ' + sys.argv[0]) + ' [image]'))
sys.exit(1)
image = Image.open(sys.argv[1]).convert('RGBA')
lines = find_lines(image, 110, 35, 0)
for line in lines:
print(line)
draw(image, lines, 'test.png')
print(('lines: %d' % len(lin... |
class Effect8154(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.drones.filteredItemBoost((lambda drone: drone.item.requiresSkill('Drones')), 'maxRange', ship.getModifiedItemAttr('eliteBonusBlackOps2'), skill='Black Ops', **kwargs)
fit.drones.filtere... |
class Migration(migrations.Migration):
dependencies = [('adserver', '0002_image-upload')]
operations = [migrations.CreateModel(name='AdType', fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('pub_date', models.DateTimeField(auto_now_add=True, verbose_na... |
class LightningTxDialog(WindowModalDialog):
def __init__(self, parent: 'ElectrumWindow', tx_item: dict):
WindowModalDialog.__init__(self, parent, _('Lightning Payment'))
self.parent = parent
self.is_sent = bool((tx_item['direction'] == 'sent'))
self.label = tx_item['label']
s... |
def _save_sample_stats(sample_settings, sample_stats, chains, trace: MultiTrace, return_inferencedata: bool, _t_sampling, idata_kwargs, model: Model) -> Tuple[(Optional[Any], Optional[InferenceData])]:
sample_settings_dict = sample_settings[0]
sample_settings_dict['_t_sampling'] = _t_sampling
sample_stats_d... |
def test_different_data_types():
a = np.zeros((10, 3), np.float16)
b = gfx.Buffer(a)
assert (b.format == '3xf2')
a = memoryview(np.zeros((10, 2), np.int16))
b = gfx.Buffer(a)
assert (b.format == '2xi2')
a = b''
b = gfx.Buffer(a)
assert (b.format == 'u1')
b = gfx.Buffer(a, format=... |
def CustomWindowProvider(cls):
if (not isinstance(cls, type)):
raise PyUnityException('Provided window provider is not a class')
if (not issubclass(cls, ABCWindow)):
raise PyUnityException('Provided window provider does not subclass Window.ABCWindow')
Logger.LogLine(Logger.DEBUG, 'Using wind... |
class DenseNetBlock(nn.Module):
def __init__(self, in_channels=128, ks=3, padding=1, stride=1):
super(DenseNetBlock, self).__init__()
self.conv1 = nn.Sequential(nn.Conv2d(in_channels=in_channels, out_channels=16, kernel_size=3, stride=1, padding=1), nn.ReLU(inplace=True))
self.conv2 = nn.Seq... |
class TfExampleDecoder(data_decoder.DataDecoder):
def __init__(self):
self.keys_to_features = {'image/encoded': tf.FixedLenFeature((), tf.string, default_value=''), 'image/format': tf.FixedLenFeature((), tf.string, default_value='jpeg'), 'image/filename': tf.FixedLenFeature((), tf.string, default_value=''),... |
def load_SQuAD1(detectLLM):
f = pd.read_csv('datasets/SQuAD1_LLMs.csv')
q = f['Question'].tolist()
a_human = [eval(_)['text'][0] for _ in f['answers'].tolist()]
a_chat = f[f'{detectLLM}_answer'].fillna('').tolist()
res = []
for i in range(len(q)):
if ((len(a_human[i].split()) > 1) and (l... |
def _format_object_to_py(obj):
if (isinstance(obj, dict) and (obj.get('isObject') is True)):
object_type = obj.get('objectType')
available_subclasses = {cls.__name__: cls for cls in PymiereBaseObject.__subclasses__()}
available_subclasses.update({cls.__name__: cls for cls in PymiereBaseColle... |
def _migrate_v44(preset: dict) -> dict:
def add_node_name(location):
node_name = migration_data.get_node_name_for_area(preset['game'], location['world_name'], location['area_name'])
location['node_name'] = node_name
for loc in preset['configuration']['starting_location']:
add_node_name(l... |
class MarginLoss(nn.Module):
def __init__(self, num_classes=10, margin=0.995, use_gpu=True):
super(MarginLoss, self).__init__()
self.margin = margin
self.num_classes = num_classes
self.use_gpu = use_gpu
def forward(self, x, labels):
batch_size = x.size(0)
classes ... |
.filterwarnings('ignore:Trie.has_keys_with_prefix is deprecated')
def test_has_keys_with_prefix():
fruit_trie = marisa_trie.BytesTrie([('apple', b'foo'), ('pear', b'bar'), ('peach', b'baz')])
assert fruit_trie.has_keys_with_prefix('')
assert fruit_trie.has_keys_with_prefix('a')
assert fruit_trie.has_key... |
class SelectionInfo():
wrapper: Optional[str] = None
outcomes: Dict[(str, str)] = dataclasses.field(default_factory=dict)
reason: SelectionReason = SelectionReason.unknown
def set_module_error(self, name: str, error: Exception) -> None:
self.outcomes[name] = f'{type(error).__name__}: {error}'
... |
def get_input(caller, prompt, callback, session=None, *args, **kwargs):
if (not callable(callback)):
raise RuntimeError('get_input: input callback is not callable.')
caller.ndb._getinput = _Prompt()
caller.ndb._getinput._callback = callback
caller.ndb._getinput._prompt = prompt
caller.ndb._g... |
class TlbLexer(RegexLexer):
name = 'Tl-b'
aliases = ['tlb']
filenames = ['*.tlb']
url = '
version_added = ''
tokens = {'root': [('\\s+', Whitespace), include('comments'), ('[0-9]+', Number), (words(('+', '-', '*', '=', '?', '~', '.', '^', '==', '<', '>', '<=', '>=', '!=')), Operator), (words(('#... |
class WordEmbedding(nn.Module):
def __init__(self, args, vocab_size):
super(WordEmbedding, self).__init__()
self.dropout = nn.Dropout(args.dropout)
self.word_embedding = nn.Embedding(vocab_size, args.emb_size)
self.layer_norm = LayerNorm(args.emb_size)
def forward(self, src, _):
... |
class ppc(QlCommonBaseCC):
_retreg = UC_PPC_REG_3
_argregs = ((UC_PPC_REG_3, UC_PPC_REG_4, UC_PPC_REG_5, UC_PPC_REG_6, UC_PPC_REG_7, UC_PPC_REG_8) + ((None,) * 10))
def getNumSlots(argbits: int):
return 1
def setReturnAddress(self, addr: int):
self.arch.regs.lr = addr |
def job_fssdJ1q_imq_optv(p, data_source, tr, te, r, J=1, b=(- 0.5), null_sim=None):
if (null_sim is None):
null_sim = gof.FSSDH0SimCovObs(n_simulate=2000, seed=r)
Xtr = tr.data()
with util.ContextTimer() as t:
c = 1.0
V0 = util.fit_gaussian_draw(Xtr, J, seed=(r + 1), reg=1e-06)
... |
def main():
read_cfg(args.cfg)
cfg.memonger = args.memonger
pprint.pprint(cfg)
aogs = []
for i in range(len(cfg.AOG.dims)):
aog = get_aog(dim=cfg.AOG.dims[i], min_size=1, tnode_max_size=cfg.AOG.dims[i], turn_off_unit_or_node=cfg.AOG.TURN_OFF_UNIT_OR_NODE)
aogs.append(aog)
symbol ... |
def test_fixture_arg_ordering(pytester: Pytester) -> None:
p1 = pytester.makepyfile('\n import pytest\n\n suffixes = []\n\n \n def fix_1(): suffixes.append("fix_1")\n \n def fix_2(): suffixes.append("fix_2")\n \n def fix_3(): suffixes.append("fix_3")\n ... |
class JsonToCsv():
def flattenjson(self, mp, delim='_'):
ret = []
if isinstance(mp, dict):
for k in mp.keys():
csvs = self.flattenjson(mp[k], delim)
for csv in csvs:
ret.append(((k + delim) + str(csv)))
elif isinstance(mp, list)... |
_cache(maxsize=2)
def compute_gaussian(tile_size: Union[(Tuple[(int, ...)], List[int])], sigma_scale: float=(1.0 / 8), value_scaling_factor: float=1, dtype=torch.float16, device=torch.device('cuda', 0)) -> torch.Tensor:
tmp = np.zeros(tile_size)
center_coords = [(i // 2) for i in tile_size]
sigmas = [(i * s... |
class DefaultGuest(DefaultAccount):
def create(cls, **kwargs):
return cls.authenticate(**kwargs)
def authenticate(cls, **kwargs):
errors = []
account = None
username = None
ip = kwargs.get('ip', '').strip()
zone = kwargs.get('zone', '').strip()
if (not set... |
.parametrize('n', [*range(2, 5)])
.parametrize('val', [3, 4, 5, 7, 8, 9])
def test_less_than_consistent_protocols(n: int, val: int):
g = LessThanConstant(n, val)
assert_decompose_is_consistent_with_t_complexity(g)
u = cirq.unitary(g)
np.testing.assert_allclose((u u), np.eye((2 ** (n + 1))))
assert_... |
def is_private_netaddress(host: str) -> bool:
if (str(host) in ('localhost', 'localhost.')):
return True
if ((host[0] == '[') and (host[(- 1)] == ']')):
host = host[1:(- 1)]
try:
ip_addr = ipaddress.ip_address(host)
return ip_addr.is_private
except ValueError:
pas... |
class MultiItr(object):
def __init__(self, itr):
self.itr = itr
self._counts = [0 for x in itr]
def __len__(self):
return sum((len(itr) for itr in self.itr))
def __iter__(self):
return self
def __next__(self):
ratios = [(count / len(itr)) for (count, itr) in zip(s... |
def test_update_matrix_world():
root = WorldObject()
root.local.position = ((- 5), 8, 0)
root.local.rotation = la.quat_from_euler(((pi / 4), 0, 0))
child1 = WorldObject()
child1.local.position = (0, 0, 5)
root.add(child1)
child2 = WorldObject()
child2.local.rotation = la.quat_from_euler(... |
class ExtraDiscordTokenSettings(BaseModel):
pings_for_bot_description: ClassVar[str] = 'A sequence. Who should be pinged if the token found belongs to a bot.'
pings_for_user_description: ClassVar[str] = 'A sequence. Who should be pinged if the token found belongs to a user.'
pings_for_bot: set[str] = Field(... |
def test(oracle_file):
symexec = SimpleSymExec(ARCH.X86_64)
symexec.initialize_register('rip', RIP_ADDR)
symexec.initialize_register('rsp', RSP_ADDR)
symexec.execute_blob(blob, RIP_ADDR)
rax = symexec.get_register_ast('rax')
ltm = InputOutputOracleLevelDB.load(oracle_file)
synthesizer = TopD... |
class Constant(BaseModel):
def get_fundamental_variables(self):
eps_dict = {}
depsdt_dict = {}
for domain in self.options.whole_cell_domains:
eps_dict[domain] = self.param.domain_params[domain.split()[0]].epsilon_init
depsdt_dict[domain] = pybamm.FullBroadcast(0, doma... |
class CurrentUserEmailManager(RetrieveMixin, CreateMixin, DeleteMixin, RESTManager):
_path = '/user/emails'
_obj_cls = CurrentUserEmail
_create_attrs = RequiredOptional(required=('email',))
def get(self, id: Union[(str, int)], lazy: bool=False, **kwargs: Any) -> CurrentUserEmail:
return cast(Cur... |
class EncodedFastaDataset(FastaDataset):
def __init__(self, path, dictionary):
super().__init__(path, cache_indices=True)
self.dictionary = dictionary
def __getitem__(self, idx):
(desc, seq) = super().__getitem__(idx)
return self.dictionary.encode_line(seq, line_tokenizer=list).l... |
class ModelArguments():
model_name_or_path: str = field(default=None, metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'})
config_name: Optional[str] = field(default=None, metadata={'help': 'Pretrained config name or path if not the same as model_name'})
tokenizer_na... |
class SockTourney(BaseModel):
id: Optional[int] = None
guild_id: int
name: str = 'Quotient-Tourney'
registration_channel_id: int
confirm_channel_id: int
role_id: int
required_mentions: int = 4
total_slots: int
banned_users: List[int]
host_id: int
multiregister: bool = False
... |
def test_fileformatyaml_pass_with_encoding_ut32(fs):
in_path = './tests/testfiles/testsubst.yaml'
fs.create_file(in_path, contents='key: "{k1}value1 !$%# *"\n"key2{k2}": blah\n# there is a comment here\nkey3:\n- l1\n # and another\n- \'!$% * {k3}\'\n- l2\n- - l31{k4}\n - l32:\n - l321\n - l322{k5}\n', e... |
def _super_impl(ctx: CallContext) -> Value:
typ = ctx.vars['type']
obj = ctx.vars['obj']
if (typ is _NO_ARG_SENTINEL):
if ctx.visitor.in_comprehension_body:
ctx.show_error('Zero-argument super() does not work inside a comprehension', ErrorCode.bad_super_call)
elif ctx.visitor.sco... |
class Config(StoredObject):
payment_basepoint = attr.ib(type=OnlyPubkeyKeypair, converter=json_to_keypair)
multisig_key = attr.ib(type=OnlyPubkeyKeypair, converter=json_to_keypair)
htlc_basepoint = attr.ib(type=OnlyPubkeyKeypair, converter=json_to_keypair)
delayed_basepoint = attr.ib(type=OnlyPubkeyKeyp... |
class ClassificationCollator(Collator):
def __init__(self, conf, label_size):
super(ClassificationCollator, self).__init__(conf.device)
self.classification_type = conf.task_info.label_type
min_seq = 1
if (conf.model_name == 'TextCNN'):
min_seq = conf.TextCNN.top_k_max_poo... |
('the image is {px_height_str} pixels high')
def then_image_is_cx_pixels_high(context, px_height_str):
expected_px_height = int(px_height_str)
px_height = context.image.px_height
assert (px_height == expected_px_height), ('expected pixel height %d, got %d' % (expected_px_height, px_height)) |
.parametrize('untied', [True, False])
def test_RanksComparator_r2_score(untied):
rank0 = agg.RankResult('test', ['a', 'b'], [1, 1], {})
rank1 = agg.RankResult('test', ['a', 'b'], [1, 1], {})
r2 = ranks_cmp.mkrank_cmp(rank0, rank1).r2_score(untied=untied)
expected = pd.DataFrame.from_dict({'test_1': {'te... |
class SPPLayer(nn.Module):
def __init__(self, pool_size, pool=nn.MaxPool2d):
super(SPPLayer, self).__init__()
self.pool_size = pool_size
self.pool = pool
self.out_length = np.sum((np.array(self.pool_size) ** 2))
def forward(self, x):
(B, C, H, W) = x.size()
for i ... |
def get_model(n_frames, n_mels, n_conditions, lr):
sub_model = MobileNetV2(input_shape=(n_frames, n_mels, 3), alpha=0.5, weights=None, classes=n_conditions)
x = Input(shape=(n_frames, n_mels, 1))
h = x
h = Concatenate()([h, h, h])
h = sub_model(h)
model = Model(x, h)
model.compile(optimizer=... |
class TestStreamsClosedByEndStream(object):
example_request_headers = [(':authority', 'example.com'), (':path', '/'), (':scheme', ' (':method', 'GET')]
example_response_headers = [(':status', '200'), ('server', 'fake-serv/0.1.0')]
server_config = h2.config.H2Configuration(client_side=False)
.parametrize... |
class SentryBaseplateObserver(BaseplateObserver):
def on_server_span_created(self, context: RequestContext, server_span: Span) -> None:
sentry_hub = sentry_sdk.Hub.current
observer = _SentryServerSpanObserver(sentry_hub, server_span)
server_span.register(observer)
context.sentry = se... |
def values(m, *, sol=(- 1)):
if isinstance(m, Variable):
return value(m, sol=sol)
if isinstance(m, (list, tuple, set, frozenset, types.GeneratorType)):
g = [values(v, sol=sol) for v in m]
return (ListInt(g) if ((len(g) > 0) and (isinstance(g[0], (int, ListInt)) or (g[0] == ANY))) else g) |
class ArrayField(Field, list):
def __init__(self, field: Field, **kwargs) -> None:
super().__init__(**kwargs)
self.sub_field = field
self.SQL_TYPE = ('%s[]' % field.SQL_TYPE)
def to_python_value(self, value: Any) -> Any:
return list(map(self.sub_field.to_python_value, value))
... |
.requires_internet
def test_scripts_no_environment(hatch, helpers, temp_dir, config_file):
config_file.model.template.plugins['default']['tests'] = False
config_file.save()
project_name = 'My.App'
with temp_dir.as_cwd():
result = hatch('new', project_name)
assert (result.exit_code == 0), res... |
class CssSmartyLexer(DelegatingLexer):
name = 'CSS+Smarty'
aliases = ['css+smarty']
version_added = ''
alias_filenames = ['*.css', '*.tpl']
mimetypes = ['text/css+smarty']
url = '
def __init__(self, **options):
super().__init__(CssLexer, SmartyLexer, **options)
def analyse_text(t... |
def test_dir_level1(fixture_path, capsys):
result = fixture_path.runpytest('-v', '--order-scope-level=1')
result.assert_outcomes(passed=12, failed=0)
result.stdout.fnmatch_lines(['feature0/test_b.py::test_one PASSED', 'feature0/test_b.py::test_two PASSED', 'feature0/test_a.py::test_three PASSED', 'feature0/... |
def binarize(databin_dir, direction, spm_vocab=SPM_VOCAB, prefix='', splits=['train', 'test', 'valid'], pairs_per_shard=None):
def move_databin_files(from_folder, to_folder):
for bin_file in ((glob.glob(f'{from_folder}/*.bin') + glob.glob(f'{from_folder}/*.idx')) + glob.glob(f'{from_folder}/dict*')):
... |
('pypyr.retries.random.uniform', return_value=999)
def test_retries_linearjitter_jrc_down(mock_random):
lj = pypyr.retries.linearjitter(sleep=3, jrc=0.5)
assert (lj(1) == 999)
assert (lj(2) == 999)
assert (lj(3) == 999)
assert (lj(1) == 999)
assert (mock_random.mock_calls == [call(1.5, 3), call(... |
def test_fixture_disallow_marks_on_fixtures():
with pytest.warns(pytest.PytestRemovedIn9Warning, match='Marks applied to fixtures have no effect') as record:
.parametrize('example', ['hello'])
.usefixtures('tmp_path')
def foo():
raise NotImplementedError()
assert (len(record)... |
def attempt_load(weights, map_location=None, inplace=True, fuse=True):
from models.yolo import Detect, Model
model = Ensemble()
for w in (weights if isinstance(weights, list) else [weights]):
ckpt = torch.load(attempt_download(w), map_location=map_location)
if fuse:
model.append(... |
class NetworkTests(util.TestCase):
signed_cla = 'brettcannon'
not_signed_cla = 'the-knights-who-say-ni'
def setUp(self):
self.bpo = bpo.Host(util.FakeServerHost())
self.loop = asyncio.get_event_loop()
self.session = SessionOnDemand(self.loop)
def test_signed(self):
result... |
def get_stars(repository_ids):
if (not repository_ids):
return {}
tuples = Star.select(Star.repository, fn.Count(Star.id)).where((Star.repository << repository_ids)).group_by(Star.repository).tuples()
star_map = {}
for record in tuples:
star_map[record[0]] = record[1]
return star_map |
('/api/conversations/register_conversation', methods=['POST'])
def register_conversation() -> Response:
request_json = request.get_json()
user_id = request_json.pop('user_id', DEFAULT_USER_ID)
conversation = request_json.get('conversation', None)
if conversation:
try:
db = get_user_c... |
def download_cached_file(url, check_hash=True, progress=False):
if isinstance(url, (list, tuple)):
(url, filename) = url
else:
parts = urlparse(url)
filename = os.path.basename(parts.path)
cached_file = os.path.join(get_cache_dir(), filename)
if (not os.path.exists(cached_file)):... |
class VibrationalOp(SparseLabelOp):
_OPERATION_REGEX = re.compile('([\\+\\-]_\\d+_\\d+\\s)*[\\+\\-]_\\d+_\\d+(?!\\s)')
def __init__(self, data: Mapping[(str, _TCoeff)], num_modals: (Sequence[int] | None)=None, *, copy: bool=True, validate: bool=True) -> None:
self.num_modals = num_modals
super()... |
def test_dumping(retort, debug_trail):
retort = retort.replace(debug_trail=debug_trail).extend(recipe=[dumper(int, int_dumper)])
first_dumper = retort.get_dumper(Tuple[(str, str)])
assert (first_dumper(['a', 'b']) == ('a', 'b'))
assert (first_dumper({'a': 1, 'b': 2}) == ('a', 'b'))
assert (first_dum... |
.arg(4)
def hash_iter_ref(ht, n, env, cont, returns):
from pycket.interpreter import return_value, return_multi_vals
try:
(w_key, w_val) = ht.get_item(n)
if (returns == _KEY):
return return_value(w_key, env, cont)
if (returns == _VALUE):
return return_value(w_val,... |
def _gui() -> game.GameGui:
from randovania.games.common.prime_family.gui.prime_trilogy_teleporter_details_tab import PrimeTrilogyTeleporterDetailsTab
from randovania.games.prime2 import gui
from randovania.games.prime2.pickup_database import progressive_items
return game.GameGui(tab_provider=gui.prime2... |
def contingency_matrix(ref_labels, sys_labels):
if (ref_labels.ndim != sys_labels.ndim):
raise ValueError(('ref_labels and sys_labels should either both be 1D arrays of labels or both be 2D arrays of one-hot encoded labels: shapes are %r, %r' % (ref_labels.shape, sys_labels.shape)))
if (ref_labels.shape... |
class TestInternAtom(EndianTest):
def setUp(self):
self.req_args_0 = {'name': 'fuzzy_prop', 'only_if_exists': 0}
self.req_bin_0 = b'\x10\x00\x00\x05\x00\n\x00\x00fuzzy_prop\x00\x00'
self.reply_args_0 = {'atom': , 'sequence_number': 45122}
self.reply_bin_0 = b'\x01\x00\xb0B\x00\x00\x0... |
def load_nist_vectors(vector_data):
test_data = {}
data = []
for line in vector_data:
line = line.strip()
if ((not line) or line.startswith('#') or (line.startswith('[') and line.endswith(']'))):
continue
if (line.strip() == 'FAIL'):
test_data['fail'] = True
... |
def test_avro_schema():
mock_avro_schema_str = '\n {\n "type": "record",\n "name": "User",\n "fields": [\n {"name": "name", "type": "string"},\n {"name": "age", "type": "int"}\n ]\n }\n '
client = FilesystemClient(scheme='file')
with patch.object(client, '_read_fil... |
.object(QuickCheck, '_socket_send', autospec=True)
class TestQcMethods(TestCase):
def test_connect(self, _socket_send):
qc = QuickCheck('127.0.0.1')
_socket_send.side_effect = mock_socket_send
qc.connect()
self.assertTrue(qc.connected)
self.assertEqual('SER;1000', qc.data)
... |
class Network(nn.Module):
def __init__(self, C, num_classes, layers, auxiliary, genotype):
super(Network, self).__init__()
self._layers = layers
self._auxiliary = auxiliary
stem_multiplier = 3
C_curr = (stem_multiplier * C)
self.stem = nn.Sequential(nn.Conv2d(3, C_cur... |
class TestTerminal():
def test_default(self):
config = RootConfig({})
assert (config.terminal.styles.info == config.terminal.styles.info == 'bold')
assert (config.terminal.styles.success == config.terminal.styles.success == 'bold cyan')
assert (config.terminal.styles.error == config.... |
class ConvNormActAa(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=1, stride=1, padding='', dilation=1, groups=1, bias=False, apply_act=True, norm_layer=nn.BatchNorm2d, act_layer=nn.ReLU, aa_layer=None, drop_layer=None):
super(ConvNormActAa, self).__init__()
use_aa = ((aa_laye... |
class executor_age(Executor):
def __init__(self, conf, model=None, comet_exp=None):
super(executor_age, self).__init__(conf, model, comet_exp)
def init_train_data(self):
loader = data_loader(self.conf)
(img_yng_tr, age_yng_tr, _, _, _, _, img_old_tr, age_old_tr, _, _, _, _) = loader.load... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.