code stringlengths 281 23.7M |
|---|
class TestSceneRun():
class TestStartScripts():
class TestAudioListeners(SceneTestCase):
def setUp(self):
super().setUp()
os.environ['PYUNITY_INTERACTIVE'] = '0'
config.audio = True
def testCase1(self):
scene = SceneMana... |
def _get_acis(start, end, params, map_variables, url, **kwargs):
params = {'sdate': pd.to_datetime(start).strftime('%Y-%m-%d'), 'edate': pd.to_datetime(end).strftime('%Y-%m-%d'), 'output': 'json', **params}
response = requests.post(url, json=params, headers={'Content-Type': 'application/json'}, **kwargs)
re... |
def modify_commandline_options(parser, is_train):
(opt, _) = parser.parse_known_args()
netG_cls = find_network_using_name(opt.netG, 'generator')
parser = netG_cls.modify_commandline_options(parser, is_train)
if is_train:
netD_cls = find_network_using_name(opt.netD, 'discriminator')
parse... |
(stability='beta')
class RayXGBRegressor(XGBRegressor, RayXGBMixin):
__init__ = _xgboost_version_warn(XGBRegressor.__init__)
_deprecate_positional_args
def fit(self, X, y, *, sample_weight=None, base_margin=None, eval_set=None, eval_metric=None, early_stopping_rounds=None, verbose=True, xgb_model: Optional[... |
def test_initial_private_browsing(request, quteproc_new):
args = (_base_args(request.config) + ['--temp-basedir', '-s', 'content.private_browsing', 'true'])
quteproc_new.start(args)
quteproc_new.compare_session('\n windows:\n - private: True\n tabs:\n - history:\n... |
class Cursor(object):
rowcount = (- 1)
arraysize = 1
description = None
def __init__(self, C):
self.database = self.connection = C
self.description = ()
self.__portals = []
def _portal():
def fget(self):
if (self.__portals is None):
raise E... |
def main():
parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
parser.add_argument('--batch-size', type=int, default=64, metavar='N', help='input batch size for training (default: 64)')
parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N', help='input batch size fo... |
def copy_presets(old_presets: dict[(str, VersionedPreset)], gd: GameDescription, pickup_db: PickupDatabase):
new_game = gd.game
for (path, preset) in old_presets.items():
config = preset.get_preset().configuration
new_preset = dataclasses.replace(preset.get_preset(), uuid=uuid.uuid4(), game=new_... |
def get_log_info(log_info):
with open('./train_log/DQN-60-MA-SELF_PLAY/log.log', 'r') as file:
content = file.read()
lines = content.splitlines()
front_idx = 0
end_idx = 1
while True:
if ('Start Epoch' in lines[front_idx]):
break
front_... |
def test__irrad_for_celltemp():
total_irrad = pd.DataFrame(index=[0, 1], columns=['poa_global'], data=[10.0, 20.0])
empty = total_irrad.drop('poa_global', axis=1)
effect_irrad = pd.Series(index=total_irrad.index, data=[5.0, 8.0])
poa = modelchain._irrad_for_celltemp(total_irrad, effect_irrad)
assert... |
def cov_devdevX_y(x, y, sigma, l, m, n):
result = 0
if (m == n):
result = (((- covariance(x, y, sigma, l)) / (l[n] ** 2)) - (((x[m] - y[m]) / (l[m] ** 2)) * cov_devX_y(x, y, sigma, l, n)))
else:
result = ((- ((x[m] - y[m]) / (l[m] ** 2))) * cov_devX_y(x, y, sigma, l, n))
return result |
class VecAsRowAndCol(Op):
__props__ = ()
def make_node(self, v):
if (not isinstance(v, Variable)):
v = pt.as_tensor_variable(v)
assert (v.type.ndim == 1)
type_class = type(v.type)
out_r_type = type_class(dtype=v.dtype, shape=(1, None))
out_c_type = type_class(... |
def _param_docs(docstring, param_name):
for line in docstring.splitlines():
for regex in DOC_REGEX:
m = regex.match(line)
if (not m):
continue
if (m.group('param') != param_name):
continue
return (m.group('doc') or '') |
class _TAppDataFileMixin():
PATH = None
def test_filename(self):
self.assertTrue(self.PATH.endswith('.appdata.xml.in'))
def test_validate(self):
try:
subprocess.check_output(['appstreamcli', 'validate', '--no-net', self.PATH], stderr=subprocess.STDOUT)
except subprocess.C... |
def configure(app_config):
logger.debug('Configuring log model')
model_name = app_config.get('LOGS_MODEL', 'database')
model_config = app_config.get('LOGS_MODEL_CONFIG', {})
def should_skip_logging(kind_name, namespace_name, is_free_namespace):
if (namespace_name and (namespace_name in app_confi... |
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('--result', default='/disk/scratch/XingxingZhang/summarization/experiments/extract_baseline_rouge_lbl/base_ms30/run.save.1layer.sh.models/3.test.txt')
parser.add_argument('--article', default='/disk/scratch/XingxingZhang/summarization/da... |
def _introspect_uniforms(program_id: int, have_dsa: bool) -> dict:
uniforms = {}
for index in range(_get_number(program_id, GL_ACTIVE_UNIFORMS)):
(u_name, u_type, u_size) = _query_uniform(program_id, index)
array_count = u_name.count('[0]')
if (array_count > 1):
raise ShaderE... |
class TestDiversity():
def setup_method(self):
test_file_path = mm.datasets.get_path('bubenec')
self.df_buildings = gpd.read_file(test_file_path, layer='buildings')
self.df_streets = gpd.read_file(test_file_path, layer='streets')
self.df_tessellation = gpd.read_file(test_file_path, l... |
class R2Plus1DStem(ResNeXt3DStem):
def __init__(self, temporal_kernel, spatial_kernel, input_planes, stem_planes, maxpool):
super(R2Plus1DStem, self).__init__(temporal_kernel, spatial_kernel, input_planes, stem_planes, maxpool)
def _construct_stem(self, temporal_kernel, spatial_kernel, input_planes, ste... |
def handle_inittarget(state_change: ActionInitTarget, channel_state: NettingChannelState, pseudo_random_generator: random.Random, block_number: BlockNumber) -> TransitionResult[Optional[TargetTransferState]]:
iteration: TransitionResult[Optional[TargetTransferState]]
transfer = state_change.transfer
from_ho... |
class ReversibleBlockFunction(torch.autograd.Function):
def forward(ctx, x, fm, gm, *params):
with torch.no_grad():
(x1, x2) = torch.chunk(x, chunks=2, dim=1)
x1 = x1.contiguous()
x2 = x2.contiguous()
y1 = (x1 + fm(x2))
y2 = (x2 + gm(y1))
... |
class StatViewSettings():
_instance = None
def getInstance(cls):
if (cls._instance is None):
cls._instance = StatViewSettings()
return cls._instance
def __init__(self):
serviceStatViewDefaultSettings = {'resources': 2, 'resistances': 2, 'recharge': 2, 'firepower': 2, 'cap... |
class CmdGive(MuxCommand):
key = 'give'
locks = 'cmd:all()'
arg_regex = '\\s|$'
def func(self):
caller = self.caller
if ((not self.args) or (not self.rhs)):
caller.msg('Usage: give <inventory object> = <target>')
return
to_give = caller.search(self.lhs, lo... |
class ComposeTypesTestCase(ZiplineTestCase):
def test_identity(self):
assert_is(compose_types(C), C, msg='compose_types of a single class should be identity')
def test_compose(self):
composed = compose_types(C, D)
assert_is_subclass(composed, C)
assert_is_subclass(composed, D)
... |
class TstWindow(MainWindow):
def __init__(self, parent=None, show=True, off_screen=True):
MainWindow.__init__(self, parent)
self.frame = QFrame()
vlayout = QVBoxLayout()
self.vtk_widget = QtInteractor(parent=self.frame, off_screen=off_screen, stereo=False)
vlayout.addWidget(s... |
class Vec3():
__slots__ = ('x', 'y', 'z')
def __init__(self, x: float=0.0, y: float=0.0, z: float=0.0) -> None:
self.x = x
self.y = y
self.z = z
def __iter__(self) -> _Iterator[float]:
(yield self.x)
(yield self.y)
(yield self.z)
_typing.overload
def _... |
_register
class ContentDescriptionObject(BaseObject):
GUID = guid2bytes('75B22633-668E-11CF-A6D9-00AA0062CE6C')
NAMES = [u'Title', u'Author', u'Copyright', u'Description', u'Rating']
def parse(self, asf, data):
super(ContentDescriptionObject, self).parse(asf, data)
lengths = struct.unpack('<... |
def build_dataset(cfg):
args = copy.deepcopy(cfg)
transform = build_transform(args.trans_dict)
ds_dict = args.ds_dict
ds_name = ds_dict.pop('type')
ds_dict['transform'] = transform
if hasattr(torchvision.datasets, ds_name):
ds = getattr(torchvision.datasets, ds_name)(**ds_dict)
else:... |
_REGISTRY.register()
class MME(TrainerXU):
def __init__(self, cfg):
super().__init__(cfg)
self.lmda = cfg.TRAINER.MME.LMDA
def build_model(self):
cfg = self.cfg
print('Building F')
self.F = SimpleNet(cfg, cfg.MODEL, 0)
self.F.to(self.device)
print('# param... |
class FC3_SkipX(KickstartCommand):
removedKeywords = KickstartCommand.removedKeywords
removedAttrs = KickstartCommand.removedAttrs
def __init__(self, writePriority=0, *args, **kwargs):
KickstartCommand.__init__(self, writePriority, *args, **kwargs)
self.op = self._getParser()
self.sk... |
class MemoryGraph(_Graph):
orientations = base.ORIENTATION_HORIZONTAL
fixed_upper_bound = True
def __init__(self, **config):
_Graph.__init__(self, **config)
val = self._getvalues()
self.maxvalue = val['MemTotal']
mem = (((val['MemTotal'] - val['MemFree']) - val['Buffers']) - ... |
def orthoFrames2Versor(B, A=None, delta: float=0.001, eps: Optional[float]=None, det=None, remove_scaling: bool=False):
if (A is None):
A = B[0].layout.basis_vectors_lst
A = A[:]
B = B[:]
if (len(A) != len(B)):
raise ValueError('len(A)!=len(B)')
if (eps is None):
eps = global... |
def init_distributed_mode(args):
if (('RANK' in os.environ) and ('WORLD_SIZE' in os.environ)):
args.rank = int(os.environ['RANK'])
args.world_size = int(os.environ['WORLD_SIZE'])
args.gpu = int(os.environ['LOCAL_RANK'])
elif ('SLURM_PROCID' in os.environ):
args.rank = int(os.envi... |
def _migrate_v66(preset: dict) -> dict:
if (preset['game'] == 'cave_story'):
excluded = set(preset['configuration']['available_locations']['excluded_indices'])
excluded = excluded.union((30, 31))
preset['configuration']['available_locations']['excluded_indices'] = sorted(excluded)
return... |
class Effect6510(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Capital Projectile Turret')), 'speed', src.getModifiedItemAttr('shipBonusDreadnoughtM2'), skill='Minmatar Dreadnought', **kwargs) |
class AssetConfigurationMixin():
def create_benefit_feature(self, sponsor_benefit, **kwargs):
if (not self.ASSET_CLASS):
raise NotImplementedError('Subclasses of AssetConfigurationMixin must define an ASSET_CLASS attribute.')
benefit_feature = super().create_benefit_feature(sponsor_benef... |
class ColoredCommand(Command):
def parse_args(self, ctx: Context, args: list[str]) -> list[str]:
if ((not args) and self.no_args_is_help and (not ctx.resilient_parsing)):
click.echo(ctx.get_help(), color=ctx.color)
ctx.exit()
parser = self.make_parser(ctx)
(opts, args... |
def test_use_function_in_current_file(config, workspace, code_action_context):
document = create_document(workspace, 'function.py')
document2 = create_document(workspace, 'method_object.py')
line = 0
pos = (document.lines[line].index('def add') + 4)
selection = Range((line, pos), (line, pos))
re... |
class IsomerScoringFunction(MoleculewiseScoringFunction):
def __init__(self, molecular_formula: str, mean_function='geometric') -> None:
super().__init__()
self.mean_function = self.determine_mean_function(mean_function)
self.scoring_functions = self.determine_scoring_functions(molecular_for... |
class _ClassInitVisitor(_AssignVisitor):
def __init__(self, scope_visitor, self_name):
super().__init__(scope_visitor)
self.self_name = self_name
def _Attribute(self, node):
if (not isinstance(node.ctx, ast.Store)):
return
if (isinstance(node.value, ast.Name) and (nod... |
def partial_pipeline_data(backend, user=None, partial_token=None, *args, **kwargs):
request_data = backend.strategy.request_data()
partial_argument_name = backend.setting('PARTIAL_PIPELINE_TOKEN_NAME', 'partial_token')
partial_token = (partial_token or request_data.get(partial_argument_name) or backend.stra... |
class KnownValues(unittest.TestCase):
def test_ip_adc2(self):
myadc.max_memory = 20
myadc.incore_complete = False
(e, t_amp1, t_amp2) = myadc.kernel_gs()
self.assertAlmostEqual(e, (- 0.), 6)
(e, v, p, x) = myadc.kernel(nroots=3)
self.assertAlmostEqual(e[0], 0., 6)
... |
(persist=eval(os.getenv('PERSISTENT')))
def compute_acc_between_years(keywords, model_path_1, model_path_2, all_model_vectors=False, top_k_acc=200, skip_same_word_pairs=True, skip_duplicates=True):
(kw1, em1, sim_matrix_1) = compute_similarity_matrix_keywords(model_path_1, all_model_vectors=all_model_vectors, keywo... |
def collect_files(img_dir, gt_dir):
assert isinstance(img_dir, str)
assert img_dir
assert isinstance(gt_dir, str)
assert gt_dir
(ann_list, imgs_list) = ([], [])
for gt_file in os.listdir(gt_dir):
ann_list.append(osp.join(gt_dir, gt_file))
imgs_list.append(osp.join(img_dir, gt_fil... |
def sort_verts_by_loops(face):
start_loop = max(face.loops, key=(lambda loop: loop.vert.co.to_tuple()[:2]))
verts = []
current_loop = start_loop
while (len(verts) < len(face.loops)):
verts.append(current_loop.vert)
current_loop = current_loop.link_loop_prev
return verts |
def test_get_update_appearance(gl, resp_application_appearance):
appearance = gl.appearance.get()
assert (appearance.title == title)
assert (appearance.description == description)
appearance.title = new_title
appearance.description = new_description
appearance.save()
assert (appearance.title... |
class Command(BaseCommand):
def help(self):
return _('Creates a generic user')
def add_arguments(self, parser):
parser.add_argument('user-type', type=str, help=_('The type of the user to be created'))
parser.add_argument('password', type=str, help=_('The password of the user to be create... |
class AmazonOAuth2Test(OAuth2Test):
backend_path = 'social_core.backends.amazon.AmazonOAuth2'
user_data_url = '
expected_username = 'FooBar'
access_token_body = json.dumps({'access_token': 'foobar', 'token_type': 'bearer'})
user_data_body = json.dumps({'user_id': 'amzn1.account.ABCDE1234', 'email': ... |
def test_top_level_non_blocking_ifc_in_deep_net():
class Top(Component):
def construct(s):
s.push = CalleeIfcCL()
s.pull = CalleeIfcCL()
s.inner = Top_less_less_inner()
s.inner.push //= s.push
s.inner.pull //= s.pull
def line_trace(s):
... |
def _parse_args(kwargs, excludes=()):
kwargs = {k: v for (k, v) in kwargs.items() if ((v is not None) and (k not in excludes))}
check_dom_name_value(kwargs.get('name', ''), '`name`')
kwargs.update(kwargs.get('other_html_attrs', {}))
kwargs.pop('other_html_attrs', None)
if kwargs.get('validate'):
... |
class ToolTipsTestCases(unittest.TestCase):
def setUp(self):
Timings.fast()
self.texts = [u'', u'New', u'Open', u'Save', u'Cut', u'Copy', u'Paste', u'Print', u'About', u'Help']
app = Application()
app.start(os.path.join(mfc_samples_folder, 'CmnCtrl1.exe'))
self.app = app
... |
class Effect6563(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
lvl = src.level
fit.fighters.filteredItemBoost((lambda mod: mod.item.requiresSkill('Heavy Fighters')), 'fighterAbilityMissilesDamageMultiplier', (src.getModifiedItemAttr('damageMultiplierBon... |
class ChannelLock3(AsyncContextManagerMixin):
def __init__(self) -> None:
(self.s, self.r) = open_memory_channel[None](0)
self.acquired = False
def acquire_nowait(self) -> None:
assert (not self.acquired)
self.acquired = True
async def acquire(self) -> None:
if self.a... |
class FakeHDF5FileHandler2(FakeHDF5FileHandler):
num_scans = 2
num_cols = 2048
def _rows_per_scan(self):
return self.filetype_info.get('rows_per_scan', 10)
def get_test_content(self, filename, filename_info, filetype_info):
global_attrs = {'/attr/Observing Beginning Date': '2019-01-01', ... |
_state_transitions.register
def _handle_receive_withdraw_expired(action: ReceiveWithdrawExpired, channel_state: NettingChannelState, block_number: BlockNumber, **kwargs: Optional[Dict[(Any, Any)]]) -> TransitionResult:
events: List[Event] = []
withdraw_state = channel_state.partner_state.withdraws_pending.get(a... |
def create_task(coro: Coroutine) -> (asyncio.Task | None):
loop = asyncio.get_running_loop()
if (not loop):
return None
def tidy(task: asyncio.Task) -> None:
TASKS.remove(task)
task = asyncio.create_task(coro)
TASKS.append(task)
task.add_done_callback(tidy)
return task |
class AvoidObstaclesBaseEnv(BaseEnv):
DEFAULT_EPISODE_JSON: str
ASSET_UID: str
tcp: sapien.Link
def __init__(self, episode_json=None, **kwargs):
if (episode_json is None):
episode_json = self.DEFAULT_EPISODE_JSON
episode_json = format_path(episode_json)
if (not Path(e... |
def test_pretend_move(tmpfolder):
tmpfolder.join('a-file.txt').write('text')
tmpfolder.join('another-file.txt').write('text')
tmpfolder.join('a-dir').ensure_dir()
fs.move('a-file.txt', target='a-dir')
assert tmpfolder.join('a-dir/a-file.txt').check()
fs.move('another-file.txt', target='a-dir', p... |
def scan_setup_py():
found = set()
setters = False
errors = 0
with open('setup.py', 'r') as f:
for line in f.readlines():
if ('import versioneer' in line):
found.add('import')
if ('versioneer.get_cmdclass()' in line):
found.add('cmdclass')
... |
class BernoulliLikelihood(NewtonOneDimensionalLikelihood):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def forward(self, function_samples, nobs=None, **kwargs):
return base_distributions.Bernoulli(logits=function_samples)
def grad_f(self, f, targets):
exp_f... |
def main(argv):
pycaffe_dir = os.path.dirname(__file__)
parser = argparse.ArgumentParser()
parser.add_argument('input_file', help="Input txt/csv filename. If .txt, must be list of filenames. If .csv, must be comma-separated file with header 'filename, xmin, ymin, xmax, ymax'")
parser.add_a... |
class PyzoSourceStructure(QtWidgets.QWidget):
def __init__(self, parent):
QtWidgets.QWidget.__init__(self, parent)
toolId = self.__class__.__name__.lower()
self._config = pyzo.config.tools[toolId]
if (not hasattr(self._config, 'showTypes')):
self._config.showTypes = ['cla... |
def fillin_tokens4gts(generator_tokens, mlm_tgts):
size = len(generator_tokens)
data_out = []
for lidx in range(size):
tokens = generator_tokens[lidx]
tgts = mlm_tgts[lidx]
if (len(tgts) < 1):
data_out.append(tokens)
continue
(counter, token) = (0, [])... |
class MultiSimilarityLoss(torch.nn.Module):
def __init__(self):
super(MultiSimilarityLoss, self).__init__()
self.thresh = 0.5
self.epsilon = 0.1
self.scale_pos = 2
self.scale_neg = 50
self.miner = miners.MultiSimilarityMiner(epsilon=self.epsilon)
self.loss_fun... |
class _ModelTrainingRound():
class EarlyStopNecessary(Exception):
pass
def __init__(self, model_trainer: SmilesRnnTrainer, training_data, test_data, n_epochs, batch_size, print_every, valid_every, num_workers=0) -> None:
self.model_trainer = model_trainer
self.training_data = training_da... |
def similarity_of_words(qdmr_w, sql_w):
match = SequenceMatcher(None, qdmr_w, sql_w).find_longest_match(0, len(qdmr_w), 0, len(sql_w))
if (match.size > 1):
p = (match.size / len(qdmr_w))
r = (match.size / len(sql_w))
return (((2 * p) * r) / (p + r))
else:
return 0.0 |
class RangeAttribute(IntAttribute):
min_value: int
max_value: int
values: Optional[List[int]] = None
def redoc(cls) -> None:
assert (cls.__doc__ is not None)
super(RangeAttribute, cls).redoc()
cls.__doc__ += ('\n:range: %s <= value <= %s' % (cls.min_value, cls.max_value))
... |
class HeaderDict(MultiDict):
def __init__(self, *a, **ka):
self.dict = {}
if (a or ka):
self.update(*a, **ka)
def __contains__(self, key):
return (_hkey(key) in self.dict)
def __delitem__(self, key):
del self.dict[_hkey(key)]
def __getitem__(self, key):
... |
def test_get_formatted_immutable_mapping():
class ReadOnlyMapping(typing.Mapping):
def __init__(self, *args, **kwargs):
self._data = dict(*args, **kwargs)
def __getitem__(self, key):
return self._data[key]
def __len__(self):
return len(self._data)
... |
def check_importable(dist, attr, value):
try:
ep = metadata.EntryPoint(value=value, name=None, group=None)
assert (not ep.extras)
except (TypeError, ValueError, AttributeError, AssertionError) as e:
raise DistutilsSetupError(("%r must be importable 'module:attrs' string (got %r)" % (attr... |
class SeparableConv2d(nn.Module):
def __init__(self, inplanes, planes, kernel_size=3, stride=1, dilation=1, bias=False, norm_layer=None, norm_kwargs=None):
super(SeparableConv2d, self).__init__()
norm_kwargs = (norm_kwargs if (norm_kwargs is not None) else {})
self.kernel_size = kernel_size
... |
.skipif((not HAVE_DEPS_FOR_RESOURCE_ESTIMATES), reason='pyscf and/or jax not installed.')
.slow
def test_generate_costing_table_thc():
mf = make_diamond_113_szv()
thc_rank_params = np.array([2, 4, 6])
table = generate_costing_table(mf, thc_rank_params=thc_rank_params, chi=10, beta=22, dE_for_qpe=0.001, bfgs... |
class TestChannels(unittest.TestCase):
def test_wav(self):
actual = file_info.channels(INPUT_FILE)
expected = 1
self.assertEqual(expected, actual)
def test_wav_pathlib(self):
actual = file_info.channels(Path(INPUT_FILE))
expected = 1
self.assertEqual(expected, act... |
class TestVisibilityNotify(EndianTest):
def setUp(self):
self.evt_args_0 = {'sequence_number': 38616, 'state': 253, 'type': 174, 'window': }
self.evt_bin_0 = b'\xae\x00\x96\xd87\xcc\x14A\xfd\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
def testPack... |
def _put_config(key: str, value: str, config: Dict[(str, Any)]) -> None:
idx = key.find('.')
if (idx < 0):
config[key] = value
elif (idx == (len(key) - 1)):
raise ValueError(f'Illegal config key `{key}`. Key should not have a `.` suffix')
else:
first_key = key[:idx]
rest_... |
def test_invalid_unicode_2(app):
token = '4JPCOLIVMAY32Q3XGVPHC4CBF8SKII5FWNYMASOFDIVSXTC5I5NBU'.encode('utf-8')
header = ('basic ' + b64encode((b'devtable+somerobot:%s' % token)).decode('ascii'))
result = validate_basic_auth(header)
assert (result == ValidateResult(AuthKind.basic, error_message='Could ... |
def test_load_rsa_nist_pss_verification_vectors():
vector_data = textwrap.dedent('\n # CAVS 11.0\n # "SigVer PKCS#1 RSASSA-PSS" information\n # Mod sizes selected: 1024 1536 2048 3072 4096\n # SHA Algorithm selected:SHA1 SHA224 SHA256 SHA384 SHA512\n # Salt len: 10\n # Generated on Wed Mar 02 00:2... |
class _libusb_device_descriptor(Structure):
_fields_ = [('bLength', c_uint8), ('bDescriptorType', c_uint8), ('bcdUSB', c_uint16), ('bDeviceClass', c_uint8), ('bDeviceSubClass', c_uint8), ('bDeviceProtocol', c_uint8), ('bMaxPacketSize0', c_uint8), ('idVendor', c_uint16), ('idProduct', c_uint16), ('bcdDevice', c_uint... |
_vision
class GitProcessorTest(unittest.TestCase):
def setUp(self):
self.tmpdirname = tempfile.mkdtemp()
image_processor = CLIPImageProcessor()
tokenizer = BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-BertModel', model_input_names=['input_ids', 'attention_mask'])
pr... |
def test_digit_version():
assert (digit_version('0.2.16') == (0, 2, 16, 0, 0, 0))
assert (digit_version('1.2.3') == (1, 2, 3, 0, 0, 0))
assert (digit_version('1.2.3rc0') == (1, 2, 3, 0, (- 1), 0))
assert (digit_version('1.2.3rc1') == (1, 2, 3, 0, (- 1), 1))
assert (digit_version('1.0rc0') == (1, 0, ... |
class Registry():
def __init__(self, name):
self._name = name
self._module_dict = dict()
def __len__(self):
return len(self._module_dict)
def __contains__(self, key):
return (self.get(key) is not None)
def __repr__(self):
format_str = (self.__class__.__name__ + f'... |
def modify(struct: Structure, path: PathLike, modifier: Callable[([AbstractContent, FileOp], ResolvedLeaf)]) -> Structure:
path_parts = Path(path).parts
root = deepcopy(struct)
last_parent: dict = root
name = path_parts[(- 1)]
for parent in path_parts[:(- 1)]:
last_parent = last_parent.setde... |
()
def main() -> None:
tool_versions = parse_pre_commit_config_tool_versions(find_pre_commit_config_file())
project_requirements = parse_requirements_dev(find_requirements_dev_file())
errors = check_pre_commit_tool_versions(tool_versions, project_requirements)
if errors:
click.secho('pre-commit ... |
def NMC_entropic_change_PeymanMPM(sto, c_s_max):
u_eq = (((((4.3452 - (1.6518 * sto)) + (1.6225 * (sto ** 2))) - (2.0843 * (sto ** 3))) + (3.5146 * (sto ** 4))) - ((0.5623 * (10 ** (- 4))) * np.exp(((109.451 * sto) - 100.006))))
du_dT = ((((((- 800) + (779 * u_eq)) - (284 * (u_eq ** 2))) + (46 * (u_eq ** 3))) -... |
class AttnScoreBertSelfAttention(BertSelfAttention):
def forward(self, hidden_states, attention_mask, head_mask=None):
mixed_query_layer = self.query(hidden_states)
mixed_key_layer = self.key(hidden_states)
mixed_value_layer = self.value(hidden_states)
query_layer = self.transpose_fo... |
(frozen=True)
class Endpoint():
id: typing.Union[str]
name: str = dataclasses.field(hash=False)
email: str = dataclasses.field(hash=False)
full_name: str = dataclasses.field(hash=False)
is_staff: bool = dataclasses.field(hash=False)
has_sent_submission_to: typing.List[str] = dataclasses.field(ha... |
def test_storyboard_mangr_input():
egoname = 'Ego'
targetname = 'target'
init = OSC.Init()
step_time = OSC.TransitionDynamics(OSC.DynamicsShapes.step, OSC.DynamicsDimension.time, 1)
egospeed = OSC.AbsoluteSpeedAction(0, step_time)
egostart = OSC.TeleportAction(OSC.LanePosition(25, 0, (- 3), 0))
... |
class Provider():
UNSAFE_PACKAGES: ClassVar[set[str]] = set()
def __init__(self, package: Package, pool: RepositoryPool, io: IO, *, installed: (list[Package] | None)=None, locked: (list[Package] | None)=None) -> None:
self._package = package
self._pool = pool
self._direct_origin = Direct... |
class TestBaseHungarianTracker(unittest.TestCase):
def setUp(self):
self._img_size = np.array([600, 800])
self._prev_boxes = np.array([[101, 101, 200, 200], [301, 301, 450, 450]]).astype(np.float32)
self._prev_scores = np.array([0.9, 0.9])
self._prev_classes = np.array([1, 1])
... |
def test_continue_on_collection_errors_maxfail(pytester: Pytester) -> None:
pytester.makepyfile(**COLLECTION_ERROR_PY_FILES)
res = pytester.runpytest('--continue-on-collection-errors', '--maxfail=3')
assert (res.ret == 1)
res.stdout.fnmatch_lines(['collected 2 items / 2 errors', '*1 failed, 2 errors*']) |
class Convert():
def __init__(self, arguments):
logger.debug('Initializing %s: (args: %s)', self.__class__.__name__, arguments)
self.args = arguments
Utils.set_verbosity(self.args.loglevel)
self.patch_threads = None
self.images = Images(self.args)
self.validate()
... |
class BasicLayer(GenericLayer):
def __init__(self, in_planes, out_planes, stride=1, mid_planes_and_cardinality=None, reduction=1, final_bn_relu=True, use_se=False, se_reduction_ratio=16):
assert (is_pos_int(in_planes) and is_pos_int(out_planes))
assert ((is_pos_int(stride) or is_pos_int_tuple(stride... |
(optionalhook=True)
def pytest_selenium_capture_debug(item, report, extra):
provider = SauceLabs(item.config.getini('saucelabs_data_center'))
if (not provider.uses_driver(item.config.getoption('driver'))):
return
pytest_html = item.config.pluginmanager.getplugin('html')
extra.append(pytest_html.... |
def test_run_with_optional_and_python_restricted_dependencies(installer: Installer, locker: Locker, repo: Repository, package: ProjectPackage) -> None:
package.python_versions = '~2.7 || ^3.4'
package_a = get_package('A', '1.0')
package_b = get_package('B', '1.1')
package_c12 = get_package('C', '1.2')
... |
class RC2(object):
def __init__(self, formula, solver='g3', adapt=False, exhaust=False, incr=False, minz=False, trim=0, verbose=0):
self.verbose = verbose
self.exhaust = exhaust
self.solver = solver
self.adapt = adapt
self.minz = minz
self.trim = trim
(self.se... |
class TestIncidenceRateRatio():
def test_incidence_rate_ratio_reference_equal_to_1(self, time_data):
irr = IncidenceRateRatio()
irr.fit(time_data, exposure='exp', outcome='dis', time='t')
assert (irr.incidence_rate_ratio[0] == 1)
def test_incidence_rate_ratio_equal_to_expected(self, time... |
class VGG16(nn.Module):
def __init__(self, embedding_dim=1024, pretrained=False):
super(VGG16, self).__init__()
seed_model = imagemodels.__dict__['vgg16'](pretrained=pretrained).features
seed_model = nn.Sequential(*list(seed_model.children())[:(- 1)])
last_layer_index = len(list(seed... |
class Effect8053(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Medium Vorton Projector')), 'maxRange', ship.getModifiedItemAttr('shipBonusUC1'), skill='EDENCOM Cruiser', **kwargs) |
class CoordinateConverter(commands.Converter):
async def convert(ctx: commands.Context, coordinate: str) -> tuple[(int, int)]:
if (len(coordinate) not in (2, 3)):
raise commands.BadArgument('Invalid co-ordinate provided.')
coordinate = coordinate.lower()
if coordinate[0].isalpha(... |
class BatchThreader():
def __init__(self, func, args_list, batch_size, prefetch_size=4, processes=12):
self.batch_size = batch_size
self.prefetch_size = prefetch_size
self.pool = ThreadPool(processes=processes)
self.async_result = []
self.func = func
self.left_args_li... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.