code stringlengths 281 23.7M |
|---|
def _next_cfg(stride_mode='dw', pool_type='avg2', conv_norm_layer='layernorm2d', conv_norm_layer_cl='layernorm', transformer_norm_layer='layernorm2d', transformer_norm_layer_cl='layernorm', window_size=None, init_values=1e-06, rel_pos_type='mlp', rel_pos_dim=512):
init_values = to_2tuple(init_values)
return dic... |
def define_and_solve_sims(model, experiments, parameter_values):
sims = {}
for (C_rate, experiment) in experiments.items():
sim = pybamm.Simulation(model, experiment=experiment, parameter_values=parameter_values)
sim.solve(calc_esoh=False)
sims[C_rate] = sim
return sims |
class TokenizerUtilsTest(unittest.TestCase):
def check_tokenizer_from_pretrained(self, tokenizer_class):
s3_models = list(tokenizer_class.max_model_input_sizes.keys())
for model_name in s3_models[:1]:
tokenizer = tokenizer_class.from_pretrained(model_name)
self.assertIsNotNon... |
def build_language_model(opt, dicts):
opt = backward_compatible(opt)
onmt.constants.layer_norm = opt.layer_norm
onmt.constants.weight_norm = opt.weight_norm
onmt.constants.activation_layer = opt.activation_layer
onmt.constants.version = 1.0
onmt.constants.attention_out = opt.attention_out
on... |
class SqueezeboxPlaylistPlugin(PlaylistPlugin, SqueezeboxPluginMixin):
PLUGIN_ID = 'Export to Squeezebox Playlist'
PLUGIN_NAME = _('Export to Squeezebox')
PLUGIN_DESC_MARKUP = ((_('Dynamically exports a playlist to Logitech Squeezebox playlist, provided both share a directory structure.') + '\n') + (_('Shar... |
class ResNet(nn.Module):
def __init__(self, block: Type[Union[(BasicBlock, Bottleneck)]], layers: List[int], num_classes: int=1000, zero_init_residual: bool=False, groups: int=1, width_per_group: int=64, replace_stride_with_dilation: Optional[List[bool]]=None, norm_layer: Optional[Callable[(..., nn.Module)]]=None) ... |
def test_structure_flattening(debug_ctx, debug_trail, trail_select):
loader_getter = make_loader_getter(shape=COMPLEX_STRUCTURE_SHAPE, name_layout=InputNameLayout(crown=COMPLEX_STRUCTURE_CROWN, extra_move=ExtraTargets(('extra',))), debug_trail=debug_trail, debug_ctx=debug_ctx)
loader = loader_getter()
asser... |
class ActionScriptLexer(RegexLexer):
name = 'ActionScript'
aliases = ['actionscript', 'as']
filenames = ['*.as']
mimetypes = ['application/x-actionscript', 'text/x-actionscript', 'text/actionscript']
url = '
version_added = '0.9'
flags = re.DOTALL
tokens = {'root': [('\\s+', Whitespace),... |
class LdjsonWriterTest(Ldjson, WriterTest, TestCase):
()
def test_fields(self, context):
context.set_input_fields(['foo', 'bar'])
context.write_sync(('a', 'b'), ('c', 'd'))
context.stop()
assert (self.readlines() == ('{"foo": "a", "bar": "b"}', '{"foo": "c", "bar": "d"}'))
()... |
def test_no_argument_provided(runner):
arguments = ['--deffile', '--profile', '--prefix', '--output', '--defdir', '--iocfile', '--ioctype', '--query', '--hostname', '--days', '--minutes', '--username', '--limit']
for arg in arguments:
result = runner.invoke(cli, [arg])
assert (f"Option '{arg}' r... |
class ISDALoss(nn.Module):
def __init__(self, feature_num, class_num):
super(ISDALoss, self).__init__()
self.estimator = EstimatorCV(feature_num, class_num)
self.class_num = class_num
self.cross_entropy = nn.CrossEntropyLoss()
def isda_aug(self, fc, features, y, labels, cv_matrix... |
def main(args):
if (not os.path.exists(args.res_dir)):
os.mkdir(args.res_dir)
if (not os.path.exists(os.path.join(args.res_dir, args.trainsite))):
os.mkdir(os.path.join(args.res_dir, args.trainsite))
if (not os.path.exists(args.model_dir)):
os.mkdir(args.model_dir)
torch.manual_s... |
def count_conv2d(m, x, y):
x = x[0]
cin = (m.in_channels // m.groups)
cout = (m.out_channels // m.groups)
(kh, kw) = m.kernel_size
batch_size = x.size()[0]
kernel_mul = ((kh * kw) * cin)
kernel_add = (((kh * kw) * cin) - 1)
bias_ops = (1 if (m.bias is not None) else 0)
ops = ((kernel... |
def upsample_flops_counter_hook(module: nn.Module, input: tuple, output: torch.Tensor) -> None:
output_size = output[0]
batch_size = output_size.shape[0]
output_elements_count = batch_size
for val in output_size.shape[1:]:
output_elements_count *= val
module.__flops__ += int(output_elements_... |
class Configurable():
def _override_defaults(self, params):
params = copy.copy(params)
if ('identical_default_ok' in params):
identical_default_ok = True
params.pop('identical_default_ok')
else:
identical_default_ok = False
for (name, value) in par... |
class StsbProcessor(DataProcessor):
def __init__(self, task_name):
self.task_name = task_name
def get_example_from_tensor_dict(self, tensor_dict):
return InputExample(tensor_dict['idx'].numpy(), tensor_dict['sentence1'].numpy().decode('utf-8'), tensor_dict['sentence2'].numpy().decode('utf-8'), s... |
_macro(shortcut='Ctrl+Alt+Q')
def optimize2():
xl = xl_app()
in_values = xl.Range('C11:C12').Value
X = np.array([x[0] for x in in_values])
orig_calc_mode = xl.Calculation
try:
xl.Calculation = constants.xlManual
xl.ScreenUpdating = False
minimize(obj_func, X, method='nelder-m... |
def count_commits_on_date(dt: datetime.datetime) -> int:
dt = dt.combine((dt - datetime.timedelta(days=1)), dt.max.time(), dt.tzinfo)
args = ['git', 'log', '--oneline', '--after', str(dt.timestamp())]
stdout = subprocess.check_output(args, text=True)
return (stdout.strip().count('\n') + 1) |
def get_room(df_objects, df_receptacles, debug=False):
rooms = get_list(df_receptacles, 'room', remove_none_dup=True, insert_spaces=True, append_list=living_room_syns)
objects = get_list(df_objects, 'entity')
target_rooms = get_list(df_objects, 'room')
object_room_scores = []
for (obj, tar) in tqdm(... |
def setUpModule():
global mol, mf
mol = gto.Mole()
mol.atom = '\n N 0. 0. 0.\n N 0. 0. 1.\n '
mol.basis = 'sto-3g'
mol.symmetry = 'D2h'
mol.charge = 0
mol.spin = 0
mol.verbose = 0
mol.build(0, 0)
mf = mol.RHF(chkfile=tempfile.NamedTemporaryFile().nam... |
.parametrize('position', [OSC.WorldPosition(), OSC.RelativeWorldPosition('target', 0, 1, 0), OSC.RelativeObjectPosition('target', 1, 1), OSC.RoadPosition(10, 20, 0, orientation=OSC.Orientation(1, 1, 1, OSC.ReferenceContext.absolute)), OSC.RelativeRoadPosition(10, 0, 'ego', orientation=OSC.Orientation(1, 1, 1, OSC.Refer... |
class TestInclude():
.parametrize(('incl', 'value'), [((int,), 42), ((str,), 'hello'), ((str, fields(C).a), 42), ((str, fields(C).b), 'hello'), (('a',), 42), (('a',), 'hello'), (('a', str), 42), (('a', fields(C).b), 'hello')])
def test_allow(self, incl, value):
i = include(*incl)
assert (i(field... |
def get_eval_loaders(opt):
(train_trans, test_trans) = transforms_options[opt.transform]
if (opt.dataset == 'miniImageNet'):
assert (opt.transform == 'A')
meta_testloader = DataLoader(MetaImageNet(args=opt, partition='test', train_transform=train_trans, test_transform=test_trans, fix_seed=False)... |
class ScenarioReport():
def __init__(self, scenario: Scenario) -> None:
self.scenario: Scenario = scenario
self.step_reports: list[StepReport] = []
def current_step_report(self) -> StepReport:
return self.step_reports[(- 1)]
def add_step_report(self, step_report: StepReport) -> None:... |
def seg_from_api(data):
try:
datas = {'text': data}
headers = {'Content-Type': 'application/json'}
res = requests.post(SEGURL, data=json.dumps(datas), headers=headers)
text = res.text
text_dict = json.loads(text)
return text_dict
except:
print('dfdfdf') |
def test_only_target(local_client, grpc_client):
def f(client: QdrantBase, **kwargs: Dict[(str, Any)]) -> List[models.ScoredPoint]:
return client.discover(collection_name=COLLECTION_NAME, target=10, with_payload=True, limit=10, using='image')
compare_client_results(grpc_client, f)
compare_client_r... |
def test_connect_rd_x_conn_A_b_wr_A_mark_writer():
class Top(ComponentLevel3):
def construct(s):
s.x = Wire(Bits32)
s.A = Wire(SomeMsg)
connect(s.A.b, s.x)
def up_wr_A():
s.A = SomeMsg(12, 123)
def up_rd_x():
z = s.x... |
class BenefitFeatureConfiguration(PolymorphicModel):
objects = BenefitFeatureQuerySet.as_manager()
benefit = models.ForeignKey('sponsors.SponsorshipBenefit', on_delete=models.CASCADE)
non_polymorphic = models.Manager()
class Meta():
verbose_name = 'Benefit Feature Configuration'
verbose_... |
class LocalConnectionTest(unittest.TestCase):
lc = Globals.local_connection
def testGetAttrs(self):
self.assertIsInstance(self.lc.LocalConnection, type)
try:
self.lc.asotnuhaoseu
except (NameError, KeyError):
pass
else:
unittest.fail('NameError... |
class Normalize():
def __init__(self, mean, std):
super().__init__()
self.mean = torch.tensor(mean)
self.std = torch.tensor(std)
def __call__(self, x):
mean = self.mean.reshape((1, 3, 1, 1))
std = self.std.reshape((1, 3, 1, 1))
x = ((x - mean) / std)
retur... |
class Calendar(ContentManageable):
url = models.URLField('URL iCal', blank=True, null=True)
rss = models.URLField('RSS Feed', blank=True, null=True)
embed = models.URLField('URL embed', blank=True, null=True)
twitter = models.URLField('Twitter feed', blank=True, null=True)
name = models.CharField(ma... |
def sentence_bleu(hypothesis, reference):
bleu = _corpus_bleu(hypothesis, reference)
for i in range(1, 4):
bleu.counts[i] += 1
bleu.totals[i] += 1
bleu = compute_bleu(bleu.counts, bleu.totals, bleu.sys_len, bleu.ref_len, smooth='exp', smooth_floor=0.0)
return bleu.score |
class LastFMSyncCache():
registered = 0
lastupdated = None
def __init__(self, username):
self.username = username
self.charts = {}
self.songs = {}
def update_charts(self, progress=None):
def prog(msg, frac):
if progress:
if (not progress(msg, f... |
class BackendTestCases(unittest.TestCase):
def setUp(self):
backend.activate('win32')
def test_register(self):
self.assertRaises(TypeError, backend.register, 'dummy', object, HwndWrapper)
self.assertRaises(TypeError, backend.register, 'dummy', HwndElementInfo, object)
def test_backen... |
class chamferFunction(Function):
def forward(ctx, xyz1, xyz2):
(batchsize, n, _) = xyz1.size()
(_, m, _) = xyz2.size()
dist1 = torch.zeros(batchsize, n)
dist2 = torch.zeros(batchsize, m)
idx1 = torch.zeros(batchsize, n).type(torch.IntTensor)
idx2 = torch.zeros(batchsi... |
class PresetPrimeChaos(PresetTab, Ui_PresetPrimeChaos):
def __init__(self, editor: PresetEditor, game_description: GameDescription, window_manager: WindowManager):
super().__init__(editor, game_description, window_manager)
self.setupUi(self)
self.chaos_label.setText(self.chaos_label.text().r... |
def get_backbone_cfg(backbone):
for i in [1, 2, 3, 4, 5]:
if (backbone == f'mitb{i}'):
return dict(type=f'mit_b{i}')
if (backbone == f'mitb{i}-del'):
return dict(_delete_=True, type=f'mit_b{i}')
return {'r50v1c': {'depth': 50}, 'r101v1c': {'depth': 101}, 'x50-32': {'type'... |
def _gen_mixnet_s(variant, channel_multiplier=1.0, pretrained=False, **kwargs):
arch_def = [['ds_r1_k3_s1_e1_c16'], ['ir_r1_k3_a1.1_p1.1_s2_e6_c24', 'ir_r1_k3_a1.1_p1.1_s1_e3_c24'], ['ir_r1_k3.5.7_s2_e6_c40_se0.5_nsw', 'ir_r3_k3.5_a1.1_p1.1_s1_e6_c40_se0.5_nsw'], ['ir_r1_k3.5.7_p1.1_s2_e6_c80_se0.25_nsw', 'ir_r2_k3... |
def test_cf_rotated_latlon():
crs = CRS.from_cf(dict(grid_mapping_name='rotated_latitude_longitude', grid_north_pole_latitude=32.5, grid_north_pole_longitude=170.0))
expected_cf = {'semi_major_axis': 6378137.0, 'semi_minor_axis': crs.ellipsoid.semi_minor_metre, 'inverse_flattening': crs.ellipsoid.inverse_flatte... |
def restoreSplitter(w, s):
if (type(s) is list):
w.setSizes(s)
elif (type(s) is str):
w.restoreState(QtCore.QByteArray.fromPercentEncoding(s.encode()))
else:
print("Can't configure QSplitter using object of type", type(s))
if (w.count() > 0):
for i in w.sizes():
... |
class TestSplitValueFunc(unittest.TestCase):
def test_with_default_args(self):
line = " key = 'value here' "
r = misc.split_key_value(line)
expected = ('key', "'value here'")
self.assertEqual(expected, r)
def test_with_whitespace_stripping_disabled(self):
line = " key = '... |
('pypyr.cache.loadercache.Loader.get_pipeline')
('pypyr.cache.stepcache.step_cache.get_step')
def test_stop_all_for(mock_step_cache, mock_get_pipe):
nothing_mock = DeepCopyMagicMock()
mock312 = DeepCopyMagicMock()
def step31(context):
mock312(context)
if (context['i'] == 'two'):
... |
def _symlink_package_resource(dest_dir: Path, path: Path, *, force: bool, suffix: str='', executable: bool=False) -> None:
name_suffixed = add_suffix(path.name, suffix)
symlink_path = Path((dest_dir / name_suffixed))
if (not symlink_path.parent.is_dir()):
mkdir(symlink_path.parent)
if force:
... |
class TrackCurrentModel(ObjectStore):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__iter = None
last_current: (Any | None) = None
def set(self, songs: Sequence[Any]):
print_d(('Filling view model with %d songs.' % len(songs)))
self.clear()
... |
def get_available_reporting_integrations():
integrations = []
if is_azureml_available():
integrations.append('azure_ml')
if is_comet_available():
integrations.append('comet_ml')
if is_mlflow_available():
integrations.append('mlflow')
if is_tensorboard_available():
int... |
class SelectiveKernelBottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, cardinality=1, base_width=64, sk_kwargs=None, reduce_first=1, dilation=1, first_dilation=None, act_layer=nn.ReLU, norm_layer=nn.BatchNorm2d, attn_layer=None, aa_layer=None, drop_block=None, ... |
class Test_isdiag():
.parametrize('shape', [(10, 1), (2, 5), (5, 2), (5, 5)])
def test_isdiag(self, shape, datatype):
mat = np.zeros(shape)
data = _data.to(datatype, _data.Dense(mat))
assert _data.isdiag(data)
mat[(0, 0)] = 1
data = _data.to(datatype, _data.Dense(mat))
... |
def main():
(left_column, right_column) = st.columns(2)
with left_column:
st.write('## Upload DICOM RT Dose files')
files: Sequence[BinaryIO] = st.file_uploader("Upload at least two DICOM RT Dose files whose doses you'd like to add together. The first file uploaded will be used as a template for... |
class TestStatsMetadata():
def test_infer_warn_stats_info(self):
with pytest.warns(DeprecationWarning, match='to specify'):
(old, new) = infer_warn_stats_info([{'a': int, 'b': object}], {}, 'bla')
assert isinstance(old, list)
assert (len(old) == 1)
assert (old[0] == {'a':... |
class GDBWatch(GDBBreakpoint):
def __init__(self, exp):
self.exp = exp
super(GDBWatch, self).__init__(None, (- 1))
def insert(self):
out = run_cmd(('-break-watch %s' % self.exp), True)
res = parse_result_line(out)
if (get_result(out) == 'error'):
return
... |
def enrich_ctypes_redefined_types():
c_class_to_type = (('c_byte', 'int', 'b'), ('c_char', 'bytes', 'c'), ('c_double', 'float', 'd'), ('c_float', 'float', 'f'), ('c_int', 'int', 'i'), ('c_int16', 'int', 'h'), ('c_int32', 'int', 'i'), ('c_int64', 'int', 'l'), ('c_int8', 'int', 'b'), ('c_long', 'int', 'l'), ('c_longd... |
class AdaroundParameters():
def __init__(self, data_set: tf.data.Dataset, num_batches: int, default_num_iterations: int=10000, default_reg_param: float=0.01, default_beta_range: Tuple=(20, 2), default_warm_start: float=0.2):
self.data_set = data_set
self.num_batches = num_batches
self.num_it... |
(python=USE_PYTHON_VERSIONS)
('command_a', install_commands)
('command_b', install_commands)
def session_cross_pep420_pkgutil(session, command_a, command_b):
session.install('--upgrade', 'setuptools', 'pip')
install_packages(session, 'native/pkg_a', 'pkgutil/pkg_b', command_a, command_b)
session.run('python... |
class AttnSkipUpBlock2D(nn.Module):
def __init__(self, in_channels: int, prev_output_channel: int, out_channels: int, temb_channels: int, dropout: float=0.0, num_layers: int=1, resnet_eps: float=1e-06, resnet_time_scale_shift: str='default', resnet_act_fn: str='swish', resnet_pre_norm: bool=True, attn_num_head_chan... |
.skipif((PY2 or (not LINUX) or (not CI)), reason='tested on linux and python 3 only')
def test_jedi_completion_environment(workspace):
doc_content = 'import logh\n'
doc = Document(DOC_URI, workspace, doc_content)
com_position = {'line': 0, 'character': 11}
assert os.path.isdir('/tmp/pyenv/')
setting... |
.xfail(reason='causing issues in CI, to be fixed later')
.spark_functions
def test_update_where_column_dne(dataframe, spark_dataframe):
assert_frame_equal(spark_dataframe.update_where(conditions="\n `decorated-elephant` = 1 AND `#$%^` = 'rabbit'\n ", target_column_name='c', target_val=10).toPa... |
class Solution(object):
def letterCombinations(self, digits):
result = []
ls = len(digits)
if (ls == 0):
return result
current = digits[0]
posfix = self.letterCombinations(digits[1:])
for t in dmap[current]:
if (len(posfix) > 0):
... |
def _format_cycles(dag: nx.DiGraph, cycles: list[tuple[(str, ...)]]) -> str:
chain = [x for (i, x) in enumerate(itertools.chain.from_iterable(cycles)) if ((i % 2) == 0)]
chain += [cycles[(- 1)][1]]
lines: list[str] = []
for x in chain:
node = (dag.nodes[x].get('task') or dag.nodes[x].get('node')... |
class ConstrainedVar(Var):
__slots__ = ('constraint',)
def __new__(cls, constraint, token=None, prefix=''):
if (token is None):
token = f'{prefix}_{Var._id}'
Var._id += 1
key = (token, constraint)
obj = cls._refs.get(key, None)
if (obj is None):
... |
def test_issue_594_random_parametrize(pytester: pytest.Pytester) -> None:
p1 = pytester.makepyfile("\n import pytest\n import random\n\n xs = list(range(10))\n random.shuffle(xs)\n .parametrize('x', xs)\n def test_foo(x):\n assert 1\n ")
result = pytester.... |
((not _optionals.HAS_PYSCF), 'pyscf not available.')
class TestElectronicDipoleMoment(PropertyTest):
def setUp(self):
super().setUp()
driver = PySCFDriver()
self.prop = driver.run().properties.electronic_dipole_moment
(('XDipole', {}), ('YDipole', {}), ('ZDipole', {'+_0 -_0': 0., '+_0 -_... |
def test_n_steps_type_error():
x0 = float64('x0')
const = float64('const')
x = (x0 + const)
op = ScalarLoop(init=[x0], constant=[const], update=[x])
with pytest.raises(TypeError, match=re.escape('(n_steps) must be of integer type. Got float64')):
op(float64('n_steps'), x0, const) |
(suppress_health_check=[HealthCheck.function_scoped_fixture], deadline=None)
(args=arglists(anything_pickleable_and_hashable()), kwargs=map_reduce_kwargs_iterators())
.filterwarnings('ignore:.*:pytest.PytestUnraisableExceptionWarning')
def test_map_with_iterators(ray_context, func, args, kwargs):
(iterables1, itera... |
class SurveyMonkeyOAuth2(BaseOAuth2):
name = 'surveymonkey'
AUTHORIZATION_URL = '
ACCESS_TOKEN_URL = '
ACCESS_TOKEN_METHOD = 'POST'
USER_DATA_URL = '/v3/users/me'
STATE_PARAMETER = False
REDIRECT_STATE = False
EXTRA_DATA = [('access_url', 'access_url')]
def get_user_details(self, res... |
.route('/')
def index() -> None:
if (not plugin.settings.access_token):
li = plugin.list_item(name=localize(32018), iconImage=plugin.routing.build_icon_path('activate'))
xbmcplugin.addDirectoryItem(plugin.handle, plugin.routing.build_url('login/'), li, False)
else:
for menu_item in plugi... |
def _compute_cross_entropy_norm(mean_label: torch.Tensor, pos_labels: torch.Tensor, neg_labels: torch.Tensor, eta: float) -> torch.Tensor:
mean_label = mean_label.double()
mean_label.clamp_(min=eta, max=(1 - eta))
return (((- pos_labels) * torch.log2(mean_label)) - (neg_labels * torch.log2((1.0 - mean_label... |
class BaseModel(nn.Module):
def __init__(self, name, config):
super(BaseModel, self).__init__()
self.name = name
self.config = config
self.exp = config.exp
self.epoch = (- 1)
self.iteration = 0
self.eva_res = 0
self.best_suffix = '_best.pth'
se... |
def _get_health_state_cache(filename):
last_error_file = ('cache/last-error-state_' + os.path.basename(filename).rstrip('.yaml'))
if os.path.exists(last_error_file):
with open(last_error_file, 'rb') as f:
last_error_state_cache = pickle.load(f)
return last_error_state_cache |
def test_bloch_redfield_tensor_spectral_string():
N = 5
H = qutip.num(N)
a = qutip.destroy(N)
A_op = (a + a.dag())
spectra = '(w>0) * 0.5'
(R_eigs, evecs) = bloch_redfield_tensor(H=H, a_ops=[(A_op, spectra)], c_ops=[(a ** 2)], fock_basis=False)
assert isinstance(R_eigs, qutip.Qobj)
asser... |
def close_db_filter(_):
if ((db.obj is not None) and (not db.is_closed())):
logger.debug('Disconnecting from database.')
db.close()
if (read_only_config.obj is not None):
for read_replica in read_only_config.obj.read_replicas:
if (not read_replica.is_closed()):
... |
class BasePersistence(Generic[(UD, CD, BD)], ABC):
__slots__ = ('bot', 'store_data', '_update_interval')
def __init__(self, store_data: Optional[PersistenceInput]=None, update_interval: float=60):
self.store_data: PersistenceInput = (store_data or PersistenceInput())
self._update_interval: float... |
def test_cache_classifier():
cache_helper.clear_cache()
for (Wrapper, Model) in [(CacheClassifier, LogisticRegression), (CacheRegressor, LinearRegression)]:
(X, y, weights) = generate_classification_data(n_classes=2)
clf = Wrapper('first', Model()).fit(X, y)
assert (clf._used_cache == Fa... |
def get_job_status(batch_cli, name, namespace='default'):
try:
return batch_cli.read_namespaced_job_status(name=name, namespace=namespace)
except Exception as e:
logging.error(('Exception when calling BatchV1Api->read_namespaced_job_status: %s' % e))
raise |
def test_validate_without_strict_fails_only_non_strict() -> None:
project_failing_strict_validation = ((fixtures_dir / 'project_failing_strict_validation') / 'pyproject.toml')
with project_failing_strict_validation.open('rb') as f:
doc = tomllib.load(f)
content = doc['tool']['poetry']
assert (Fa... |
def tune_test(path, num_trials, num_workers, num_boost_rounds, num_files=0, regression=False, use_gpu=False, fake_data=False, smoke_test=False):
ray_params = RayParams(elastic_training=False, max_actor_restarts=0, num_actors=num_workers, cpus_per_actor=1, gpus_per_actor=(0 if (not use_gpu) else 1))
def local_tr... |
class TestClassyTestCase(unittest.TestCase):
def test_assert_torch_all_close(self):
test_fixture = ClassyTestCase()
data = [1.1, 2.2]
tensor_1 = torch.Tensor(data)
tensor_2 = tensor_1
test_fixture.assertTorchAllClose(tensor_1, tensor_2)
tensor_2 = (tensor_1 / 2)
... |
def custom_debugger_hook():
called = []
class _CustomDebugger():
def __init__(self, *args, **kwargs):
called.append('init')
def reset(self):
called.append('reset')
def interaction(self, *args):
called.append('interaction')
def set_trace(self, f... |
def get_config():
config = get_default_configs()
training = config.training
training.sde = 'vpsde'
training.continuous = True
training.reduce_mean = True
sampling = config.sampling
sampling.method = 'ode'
sampling.smallest_time = 0.001
data = config.data
data.centered = True
... |
def render_policy(policy, log_dir, total_timesteps, eval_episodes=5):
frames = []
for episode in range(eval_episodes):
obs = env.reset()
policy.reset()
frames.append(env.render(mode='rgb_array'))
done = False
while (not done):
action = policy.select_action(np.... |
class BaseImageHeader():
def __init__(self, px_width, px_height, horz_dpi, vert_dpi):
self._px_width = px_width
self._px_height = px_height
self._horz_dpi = horz_dpi
self._vert_dpi = vert_dpi
def content_type(self):
msg = 'content_type property must be implemented by all ... |
def save_weights(G, D, E1, A1, state_dict, weights_root, experiment_name, name_suffix=None, G_ema=None, copy=False):
if copy:
root = '/'.join([weights_root, experiment_name, str(state_dict['itr'])])
else:
root = '/'.join([weights_root, experiment_name])
if (not os.path.exists(root)):
... |
def _get_gdal_info():
import rasterio
blob = [('rasterio', rasterio.__version__), ('GDAL', rasterio.__gdal_version__), ('PROJ', rasterio.__proj_version__), ('GEOS', rasterio.__geos_version__), ('PROJ DATA', os.pathsep.join(rasterio._env.get_proj_data_search_paths())), ('GDAL DATA', rasterio._env.get_gdal_data()... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--game', default='StreetFighterIISpecialChampionEdition-Genesis')
parser.add_argument('--state', default=retro.State.DEFAULT)
parser.add_argument('--scenario', default='scenario')
args = parser.parse_args()
ia = RetroInteractive... |
class Effect7173(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: (mod.item.group.name == 'Mutadaptive Remote Armor Repairer')), 'armorDamageAmount', src.getModifiedItemAttr('eliteBonusLogistics2'), skill='Logistics Cruis... |
class ReportMgr(ReportMgrBase):
def __init__(self, report_every, start_time=(- 1.0), tensorboard_writer=None):
super(ReportMgr, self).__init__(report_every, start_time)
self.tensorboard_writer = tensorboard_writer
def maybe_log_tensorboard(self, stats, prefix, learning_rate, step):
if (s... |
class TagHint(BaseEntry):
def __init__(self, tag: str, message: str, description: str, default_query: str=None, inline_keyboard: InlineKeyboardMarkup=None, group_command: bool=False):
self.tag = tag
self._message = message
self._default_query = default_query
self._description = descr... |
def obj_func_cell_cycle(trajectory):
timestep = tspan[:(- 1)]
y = (trajectory[:(- 1)] - trajectory[1:])
freq = 0
local_times = []
prev = y[0]
for n in range(1, len(y)):
if (y[n] > 0 > prev):
local_times.append(timestep[n])
freq += 1
prev = y[n]
local_t... |
def test_ineichen_series_perez_enhancement():
times = pd.date_range(start='2014-06-24', end='2014-06-25', freq='3h', tz='America/Phoenix')
apparent_zenith = pd.Series(np.array([, 113., 82., 46.0467599, 10., 34., 72., 105., 124.]), index=times)
am = pd.Series(np.array([nan, nan, 6., 1., 0., 1., 3., nan, nan]... |
def test_mercator_a_operation__defaults():
aeaop = MercatorAConversion()
assert (aeaop.name == 'unknown')
assert (aeaop.method_name == 'Mercator (variant A)')
assert (_to_dict(aeaop) == {'Latitude of natural origin': 0.0, 'Longitude of natural origin': 0.0, 'False easting': 0.0, 'False northing': 0.0, '... |
def parse_input():
description = 'This script allows you to evaluate the ActivityNet untrimmed video classification task which is intended to evaluate the ability of algorithms to predict activities in untrimmed video sequences.'
p = argparse.ArgumentParser(description=description)
p.add_argument('ground_tr... |
class DistcheckCmd(sdist):
description = 'run tests on a fresh sdist'
def _check_manifest(self):
assert self.get_archive_files()
if (subprocess.call(['git', 'status'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0):
included_files = self.filelist.files
assert inclu... |
_torch
class SplinterModelIntegrationTest(unittest.TestCase):
def test_splinter_question_answering(self):
model = SplinterForQuestionAnswering.from_pretrained('tau/splinter-base-qass')
input_ids = torch.tensor([[101, 7796, 1108, 1255, 1107, 104, 119, 1124, 1608, 1106, 1103, 1244, 2325, 1224, 119, 10... |
class CustomObjectProperty(bpy.types.PropertyGroup, SizeOffsetGetSet, ArrayGetSet):
array: PointerProperty(type=ArrayProperty)
size_offset: PointerProperty(type=SizeOffsetProperty)
def init(self, wall_dimensions):
self['wall_dimensions'] = wall_dimensions
self.size_offset.init(((self['wall_d... |
def meet_similar_callables(t: CallableType, s: CallableType) -> CallableType:
from mypy.join import safe_join
arg_types: list[Type] = []
for i in range(len(t.arg_types)):
arg_types.append(safe_join(t.arg_types[i], s.arg_types[i]))
if (t.fallback.type.fullname != 'builtins.function'):
fal... |
.parametrize('learned_grid', [False, True])
def test_qc_rnn_learned_grid_mode(tmp_path, learned_grid):
torch.manual_seed(0)
model = GruModel()
input_shape = (4, 3, 4)
dummy_input = (torch.rand(input_shape, requires_grad=True).to('cpu'), torch.rand((1, 3, 4), requires_grad=True).to('cpu'))
quant_sche... |
def pca(mat):
if (mat.shape[0] >= mat.shape[1]):
(eig_vals, eig_vecs) = np.linalg.eig(np.cov(mat.T))
eig_pairs = zip(np.abs(eig_vals), eig_vecs.T)
eig_pairs.sort(reverse=True)
(eig_vals, eig_vecs) = zip(*eig_pairs)
eig_vals = np.asarray(eig_vals)
eig_vecs = np.asarray... |
class NNPolicy(Policy, Serializable):
def __init__(self, env_spec, observation_ph, actions, scope_name=None):
Serializable.quick_init(self, locals())
self._observations_ph = observation_ph
self._actions = actions
self._scope_name = (tf.get_variable_scope().name if (not scope_name) el... |
class AdvertiserFlightReportView(AdvertiserAccessMixin, BaseReportView):
export_view = 'flight_report_export'
template_name = 'adserver/reports/advertiser-flight.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
advertiser_slug = kwargs.get('advertiser_... |
def unlock_view(ModelAdmin, request, pk):
sponsorship = get_object_or_404(ModelAdmin.get_queryset(request), pk=pk)
if ((request.method.upper() == 'POST') and (request.POST.get('confirm') == 'yes')):
try:
sponsorship.locked = False
sponsorship.save(update_fields=['locked'])
... |
class WaitLoadBar(WaitLoadBase, Gtk.HBox):
def __init__(self):
super().__init__()
self._label.set_alignment(0.0, 0.5)
self._label.set_ellipsize(Pango.EllipsizeMode.END)
self._cancel_button.remove(self._cancel_button.get_child())
self._cancel_button.add(Gtk.Image.new_from_icon... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.