code stringlengths 281 23.7M |
|---|
class Option(Generic[_O]):
def __init__(self, name: str, default: _O=UNDEFINED, mutable: bool=True, parent: (Option[_O] | None)=None, validator: Callable[([Any], _O)]=(lambda x: cast(_O, x))) -> None:
self._name = name
self._mutable = mutable
self._validator = validator
self._subscri... |
class PyOggVorbisSource(PyOggSource):
def _load_source(self):
if self.file:
self._stream = MemoryVorbisFileStream(self.filename, self.file)
else:
self._stream = UnclosedVorbisFileStream(self.filename)
self._duration = pyogg.vorbis.libvorbisfile.ov_time_total(byref(sel... |
class Describe_Marker():
def it_can_construct_from_a_stream_and_offset(self, from_stream_fixture):
(stream, marker_code, offset, _Marker__init_, length) = from_stream_fixture
marker = _Marker.from_stream(stream, marker_code, offset)
_Marker__init_.assert_called_once_with(ANY, marker_code, of... |
class VerticalLabel(QtWidgets.QLabel):
def __init__(self, text, orientation='vertical', forceWidth=True):
QtWidgets.QLabel.__init__(self, text)
self.forceWidth = forceWidth
self.orientation = None
self.setOrientation(orientation)
def setOrientation(self, o):
if (self.orie... |
class TestBroadcastObject(DistributedTest):
def test_str(self):
spawn_and_init(functools.partial(TestBroadcastObject._test_broadcast_object, 'hello world'), world_size=2)
def test_tensor(self):
spawn_and_init(functools.partial(TestBroadcastObject._test_broadcast_object, torch.rand(5)), world_siz... |
def write_metric(summary_writer, train_metrics, eval_metrics, train_time, step):
summary_writer.scalar('train_time', train_time, step)
train_metrics = get_metrics(train_metrics)
for (key, vals) in train_metrics.items():
tag = f'train_{key}'
for (i, val) in enumerate(vals):
summar... |
def _classify_peps(peps: list[PEP]) -> tuple[(list[PEP], ...)]:
meta = []
info = []
provisional = []
accepted = []
open_ = []
finished = []
historical = []
deferred = []
dead = []
for pep in peps:
if (pep.status == STATUS_DRAFT):
open_.append(pep)
elif... |
class Ui_KEY2(object):
def setupUi(self, KEY2):
KEY2.setObjectName('KEY2')
KEY2.resize(419, 106)
self.gridLayout = QtWidgets.QGridLayout(KEY2)
self.gridLayout.setObjectName('gridLayout')
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectNa... |
def assert_show_output(manylinux_ctr, wheel, expected_tag, strict):
output = docker_exec(manylinux_ctr, f'auditwheel show /io/{wheel}')
output = output.replace('\n', ' ')
match = SHOW_RE.match(output)
assert match
assert (match['wheel'] == wheel)
if (strict or ('musllinux' in expected_tag)):
... |
class SimulSTEvaluationService(object):
DEFAULT_HOSTNAME = 'localhost'
DEFAULT_PORT = 12321
def __init__(self, hostname=DEFAULT_HOSTNAME, port=DEFAULT_PORT):
self.hostname = hostname
self.port = port
self.base_url = f'
def __enter__(self):
self.new_session()
def __exi... |
def test_reflection_using_prepare_consistent_protocols_and_controlled():
prepare_gate = StatePreparationAliasSampling.from_lcu_probs([1, 2, 3, 4], probability_epsilon=0.1)
gate = ReflectionUsingPrepare(prepare_gate, control_val=None)
op = gate.on_registers(**get_named_qubits(gate.signature))
equals_test... |
def clone_get_equiv(inputs: Sequence[Variable], outputs: Sequence[Variable], copy_inputs: bool=True, copy_orphans: bool=True, memo: Optional[dict[(Union[(Apply, Variable, 'Op')], Union[(Apply, Variable, 'Op')])]]=None, clone_inner_graphs: bool=False, **kwargs) -> dict[(Union[(Apply, Variable, 'Op')], Union[(Apply, Vari... |
class SAMLIdentityProvider():
def __init__(self, name, **kwargs):
self.name = name
assert ((':' not in self.name) and (' ' not in self.name)), 'IdP "name" should be a slug (short, no spaces)'
self.conf = kwargs
def get_user_permanent_id(self, attributes):
uid = attributes[self.co... |
def main():
found = False
dcName = ''
domainName = ''
try:
myCommand = ops.cmd.getDszCommand('domaincontroller -primary')
cmdRes = myCommand.execute()
dcName = cmdRes.domaincontroller[0].dcname
domainName = cmdRes.domaincontroller[0].domainname
ops.info(('The dc i... |
class WavpackFile(APEv2File):
format = 'WavPack'
mimes = ['audio/x-wavpack']
def __init__(self, filename):
with translate_errors():
audio = WavPack(filename)
super().__init__(filename, audio)
self['~#length'] = audio.info.length
self['~#channels'] = audio.info.cha... |
class GymObject(dict):
def __init__(self, id=None, api_key=None, **params):
super(GymObject, self).__init__()
self._unsaved_values = set()
self._transient_values = set()
self._retrieve_params = params
self._previous = None
object.__setattr__(self, 'api_key', api_key)
... |
class MappedRecognizer(Recognizer):
def __init__(self, transition_model, decoder, symbols=None, allow_partial=True, acoustic_scale=0.1):
self.transition_model = transition_model
self.decoder = decoder
self.symbols = symbols
self.allow_partial = allow_partial
self.acoustic_sca... |
class Evaluator():
def __init__(self, references, candidates):
self.references = references
self.candidates = candidates
self.eval = {}
self.imgToEval = {}
def evaluate(self):
scorers = [(Rouge(), 'ROUGE_L')]
for (scorer, method) in scorers:
(score, sc... |
def waymo_data_prep(root_path, info_prefix, version, out_dir, workers, max_sweeps=5):
from tools.data_converter import waymo_converter as waymo
splits = ['training', 'validation', 'testing']
for (i, split) in enumerate(splits):
load_dir = osp.join(root_path, 'waymo_format', split)
if (split ... |
class Migration(migrations.Migration):
dependencies = [('conditions', '0005_empty_relation')]
operations = [migrations.AlterField(model_name='condition', name='source', field=models.ForeignKey(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='domain.... |
def run_restored_tensor(tensornames, left, right, sess=None, label=None, w_tl=None, w_tr=None, d_tl=None, d_tr=None, t_l=None, t_r=None):
graph = tf.get_default_graph()
XL = graph.get_tensor_by_name('XL:0')
XR = graph.get_tensor_by_name('XR:0')
feed_dict = {XL: left, XR: right}
if (not (label is Non... |
def prepare_folder_structure(abs_origin_path, config: Config=None, foldertype: str='result', window_roll: int=0):
folder_path = abs_origin_path
if config:
folder_list = dict(inspect.getmembers(config))
folder_list['seed'] = ('seed_' + str(config.seed))
folder_levels = settings.FOLDER_LEV... |
class Layouts(object):
theme = Layout_Aesthetics.layout_theme
def max(self, name=None):
if (name is None):
return Max(**self.theme)
return Max(name=name, **self.theme)
def zoomy(self, name=None):
if (name is None):
return Zoomy(**self.theme)
return Zoo... |
class TestCase(unittest.TestCase):
def run_awaitable(self, coroutine, *, loop=None):
if (loop is None):
loop = asyncio.new_event_loop()
self.addCleanup(loop.close)
return loop.run_until_complete(coroutine)
def noException(self, coroutine):
return self.run_awaitabl... |
class IASIL2CDRNC(NetCDF4FsspecFileHandler):
def get_dataset(self, data_id, ds_info):
ds = self[data_id['name']]
if ('scan_lines' in ds.dims):
ds = ds.rename(scan_lines='y')
if ('pixels' in ds.dims):
ds = ds.rename(pixels='x')
if (('_FillValue' in ds.attrs) an... |
class MlpMixer(nn.Module):
def __init__(self, num_classes=1000, img_size=224, in_chans=3, patch_size=16, num_blocks=8, embed_dim=512, mlp_ratio=(0.5, 4.0), block_layer=MixerBlock, mlp_layer=Mlp, norm_layer=partial(nn.LayerNorm, eps=1e-06), act_layer=nn.GELU, drop_rate=0.0, drop_path_rate=0.0, nlhb=False, stem_norm=... |
def print_report(samples, losses, wer, cer, dataset_name):
mean_loss = np.mean(losses)
print(('Test on %s - WER: %f, CER: %f, loss: %f' % (dataset_name, wer, cer, mean_loss)))
print(('-' * 80))
best_samples = samples[:FLAGS.report_count]
worst_samples = samples[(- FLAGS.report_count):]
median_in... |
def main():
(args, cfg) = parse_config()
if (args.launcher == 'none'):
dist_train = False
total_gpus = 1
else:
(total_gpus, cfg.LOCAL_RANK) = getattr(common_utils, ('init_dist_%s' % args.launcher))(args.tcp_port, args.local_rank, backend='nccl')
dist_train = True
if (args... |
def test_hover_flip_event_top_edge(view, item):
view.scene.addItem(item)
item.setSelected(True)
event = MagicMock()
event.pos.return_value = QtCore.QPointF(50, 0)
with patch.object(item, 'bounding_rect_unselected', return_value=QtCore.QRectF(0, 0, 100, 80)):
item.hoverMoveEvent(event)
... |
def copy_layers(src_layers: nn.ModuleList, dest_layers: nn.ModuleList, layers_to_copy: List[int]) -> None:
layers_to_copy = nn.ModuleList([src_layers[i] for i in layers_to_copy])
assert (len(dest_layers) == len(layers_to_copy)), f'{len(dest_layers)} != {len(layers_to_copy)}'
dest_layers.load_state_dict(laye... |
class SetACL(namedtuple('SetACL', 'path acls version')):
type = 7
def serialize(self):
b = bytearray()
b.extend(write_string(self.path))
b.extend(int_struct.pack(len(self.acls)))
for acl in self.acls:
b.extend(((int_struct.pack(acl.perms) + write_string(acl.id.scheme)... |
def peek(dat, folder, force=False):
g = Globals()
outf = g.default_repo_dir
mkdir((outf + 'peek'))
mkdir(((outf + 'peek/') + dat))
print(((('\nPeeking ' + folder) + ' for ') + dat))
dir = ((((outf + 'samples/') + dat) + '/') + folder)
print('dir', dir)
if ((not force) and os.path.exists(... |
class BertTokenizer(object):
def __init__(self, vocab_file, do_lower_case=True, max_len=None, never_split=('[UNK]', '[SEP]', '[PAD]', '[CLS]', '[MASK]', '[unused98]', '[unused99]', '[unused1]', '[unused2]', '[unused3]', '[unused4]', '[unused5]', '[unused6]')):
if (not os.path.isfile(vocab_file)):
... |
def exchange_from_config(app_config: config.RawConfig, prefix: str, **kwargs: Any) -> Exchange:
assert prefix.endswith('.')
parser = config.SpecParser({'exchange_name': config.Optional(config.String), 'exchange_type': config.String})
options = parser.parse(prefix[:(- 1)], app_config)
return Exchange(nam... |
def test_make_package_pre_signed_dist(upload_settings, caplog):
filename = helpers.WHEEL_FIXTURE
expected_size = '15.4 KB'
signed_filename = (helpers.WHEEL_FIXTURE + '.asc')
signatures = {os.path.basename(signed_filename): signed_filename}
upload_settings.sign = True
upload_settings.verbose = Tr... |
class Subscription():
scheduler_event: (sched.Event | None) = None
scheduler_active: bool = True
expiration_time: float = 0.0
event_received: bool = False
subscription_id: (str | None) = None
default_timeout_seconds: int = 300
device: Device
callback_port: int
service_name: str
p... |
.dict(os.environ, {'A_FAKE_OPTION': '1'})
def test_option_validator():
opt = Option('A_FAKE_OPTION', False, validator=(lambda x: bool(int(x))))
assert (opt.current is True)
opt.current = '0'
assert (opt.current is False)
with pytest.raises(ValueError, match='Invalid value'):
opt.current = 'n... |
class InstructionPromptProcessor(PromptBaseProcessor):
def __init__(self, data_args: DataTrainingArguments, task_name: str, sentence1_key: str, sentence2_key: str, template: List[Optional[dict]], label_words_mapping: dict, instruction: Optional[dict]=None, tokenizer: Optional[AutoTokenizer]=None) -> None:
s... |
def test_dirty_workspace(tmpfolder):
project = 'my_project'
struct = {'dummyfile': 'NO CONTENT'}
structure.create_structure(struct, dict(project_path=project))
repo.init_commit_repo(project, struct)
path = (tmpfolder / project)
assert info.is_git_workspace_clean(path)
with open(str((path / '... |
def _compare_pvgis_tmy_csv(expected, month_year_expected, inputs_expected, meta_expected, csv_meta, pvgis_data):
(data, months_selected, inputs, meta) = pvgis_data
for outvar in meta_expected['outputs']['tmy_hourly']['variables'].keys():
assert np.allclose(data[outvar], expected[outvar])
assert np.a... |
class TaggedMetricsLocalSpanObserver(SpanObserver):
def __init__(self, batch: metrics.Batch, span: Span, allowlist: Set[str], sample_rate: float=1.0):
self.batch = batch
self.span = span
self.tags: Dict[(str, Any)] = {}
self.base_name = 'baseplate.local'
self.timer = batch.ti... |
class ReplayDataset(Dataset):
def __init__(self, max_size=1000000.0):
self.storage = []
self.max_size = max_size
def add(self, data):
if (len(self.storage) == self.max_size):
self.storage.pop(0)
self.storage.append((data[0].astype('float32'), data[1].astype('float32')... |
class Solution():
def middleNode(self, head: ListNode) -> ListNode:
count = 0
head_ref = head
while (head != None):
count += 1
head = head.next
count = (int((count / 2)) + 1)
while (count > 1):
head_ref = head_ref.next
count -= ... |
def top1gating(logits: torch.Tensor, capacity_factor: float, fp16_mode: bool=False, nonpadding: torch.Tensor=None, random_token_drop: bool=False) -> Tuple[(Tensor, Tensor, Tensor, float)]:
if (fp16_mode is True):
logits = logits.to(torch.float32)
gates = F.softmax(logits, dim=1)
num_tokens = gates.s... |
class BaseTokenizer():
def __init__(self, folder: str, urls: List[str]):
super(BaseTokenizer, self).__init__()
self._folder = folder
self._urls = urls
self._to_ids = {}
self._to_tokens = []
self._load()
assert all([(sptoken in self._to_ids.keys()) for sptoken ... |
def row_wise(sizes_placement: Optional[Tuple[(List[int], str)]]=None) -> ParameterShardingGenerator:
def _parameter_sharding_generator(param: nn.Parameter, local_size: int, world_size: int, device_type: str, sharder: ModuleSharder[nn.Module]) -> ParameterSharding:
if (sizes_placement is None):
s... |
.unit()
def test_importmode_importlib_with_dataclass(tmp_path: Path) -> None:
fn = tmp_path.joinpath('_src/project/task_dataclass.py')
fn.parent.mkdir(parents=True)
fn.write_text(textwrap.dedent('\n from dataclasses import dataclass\n\n \n class Data:\n value:... |
def ECE(conf, pred, true, bin_size=0.1):
upper_bounds = np.arange(bin_size, (1 + bin_size), bin_size)
n = len(conf)
ece = 0
for conf_thresh in upper_bounds:
(acc, avg_conf, len_bin) = compute_acc_bin((conf_thresh - bin_size), conf_thresh, conf, pred, true)
ece += ((np.abs((acc - avg_conf... |
def main():
program_name = sys.argv[0]
argv = sys.argv[1:]
description = '\n Visualize h2 state machines as graphs.\n '
epilog = '\n You must have the graphviz tool suite installed. Please visit\n for more information.\n '
argument_parser = argparse.ArgumentParser(prog=program_name,... |
def softmax_backward_data(parent, grad_output, output, dim, self):
from torch import _softmax_backward_data
if is_torch_less_than_1_11:
return _softmax_backward_data(grad_output, output, parent.dim, self)
else:
return _softmax_backward_data(grad_output, output, parent.dim, self.dtype) |
def train(train_loader, train_meta_loader, model, vnet, optimizer_model, optimizer_vnet, epoch, meta_lr, flag):
print(('\nEpoch: %d' % epoch))
train_loss = 0
meta_loss = 0
train_total = 0
train_correct = 0
prec_meta = 0.0
train_meta_loader_iter = iter(train_meta_loader)
for (batch_idx, (... |
class PEPError(Exception):
def __init__(self, error: str, pep_file: Path, pep_number: (int | None)=None):
super().__init__(error)
self.filename = pep_file
self.number = pep_number
def __str__(self):
error_msg = super(PEPError, self).__str__()
error_msg = f'({self.filename... |
def egg2wheel(egg_path: str, dest_dir: str) -> None:
filename = os.path.basename(egg_path)
match = egg_info_re.match(filename)
if (not match):
raise WheelError(f'Invalid egg file name: {filename}')
egg_info = match.groupdict()
dir = tempfile.mkdtemp(suffix='_e2w')
if os.path.isfile(egg_p... |
class TestCOUTA(unittest.TestCase):
def setUp(self):
train_file = 'data/omi-1/omi-1_train.csv'
test_file = 'data/omi-1/omi-1_test.csv'
train_df = pd.read_csv(train_file, sep=',', index_col=0)
test_df = pd.read_csv(test_file, index_col=0)
y = test_df['label'].values
(t... |
class RemoteFunctionDefTransformer(FunctionDefTransformer):
def __init__(self, keep_sync: Optional[List[str]]=None, exclude_methods: Optional[List[str]]=None, async_methods: Optional[List[str]]=None):
super().__init__(keep_sync=keep_sync)
self.exclude_methods = (exclude_methods if (exclude_methods i... |
(trylast=True)
def pytask_execute_task_log_end(session: Session, report: ExecutionReport) -> None:
url_style = create_url_style_for_task(report.task.function, session.config['editor_url_scheme'])
console.print(report.outcome.symbol, style=unify_styles(report.outcome.style, url_style), end='') |
def cmd_venv_recreate(options, root, python, benchmarks):
from . import _venv, _utils
from .venv import Requirements, VenvForBenchmarks
requirements = Requirements.from_benchmarks(benchmarks)
if _venv.venv_exists(root):
venv_python = _venv.resolve_venv_python(root)
if (venv_python == sys... |
_fixtures(WebFixture, AccountsWebFixture)
def test_register(web_fixture, accounts_web_fixture):
fixture = accounts_web_fixture
verification_requests = Session.query(VerifyEmailRequest)
fixture.browser.open('/a_ui/register')
fixture.browser.type(XPath.input_labelled('Email'), '')
fixture.browser.type... |
def _parse_peps(path: Path) -> list[parser.PEP]:
peps: list[parser.PEP] = []
for file_path in path.iterdir():
if (not file_path.is_file()):
continue
if file_path.match('pep-0000*'):
continue
if file_path.match('pep-????.rst'):
pep = parser.PEP(path.joi... |
_existing_mirrors
('util.repomirror.skopeomirror.SkopeoMirror.run_skopeo')
def test_mirror_config_server_hostname(run_skopeo_mock, initialized_db, app, monkeypatch):
(mirror, repo) = create_mirror_repo_robot(['latest', '7.1'])
skopeo_calls = [{'args': ['/usr/bin/skopeo', '--debug', 'list-tags', '--tls-verify=Tr... |
class sender(asyncore.dispatcher):
'\n\tFrom
def __init__(self, receiver, args):
self.args = args
asyncore.dispatcher.__init__(self)
self.receiver = receiver
receiver.sender = self
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.connect((self.args['se... |
class Performer(MultiHeadAttention):
def __init__(self, *args, **kwargs):
self.attention_method = kwargs.pop('attention_method', 'quadratic')
self.scaling = kwargs.pop('scaling', 0)
self.supports = kwargs.pop('supports', None)
self._check_attention_method_is_valid()
if (self.... |
class Effect2812(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: (mod.item.group.name == 'Burst Jammer')), 'ecmBurstRange', ship.getModifiedItemAttr('shipBonusCB3'), skill='Caldari Battleship', **kwargs) |
class DyMFAgent(RLModel):
def __init__(self, player: Literal[(1, 2)]):
super().__init__()
self.position = player
self.model_path = './MovementForecasting/model/DyMF_2__150'
self.args = load_args_file(self.model_path)
self.args['sample_num'] = self.args['max_length']
n... |
class CSMatrixType(types.Type):
name: str
def instance_class(data, indices, indptr, shape):
raise NotImplementedError()
def __init__(self, dtype):
self.dtype = dtype
self.data = types.Array(dtype, 1, 'A')
self.indices = types.Array(types.int32, 1, 'A')
self.indptr = t... |
def test_dh_public_numbers_equality():
params = dh.DHParameterNumbers(P_1536, 2)
public = dh.DHPublicNumbers(1, params)
assert (public == dh.DHPublicNumbers(1, params))
assert (public != dh.DHPublicNumbers(0, params))
assert (public != dh.DHPublicNumbers(1, dh.DHParameterNumbers(P_1536, 5)))
ass... |
class Plotter():
def __init__(self, plotting_frequency=1, time_window=15, window_title='States'):
self.time_window = time_window
self.time = 0
self.prev_time = 0
self.plotting_frequency = plotting_frequency
self.freq_counter = 0
self.x_grid_on = False
self.y_g... |
def det(m):
((m00, m01, m02, m03), (m10, m11, m12, m13), (m20, m21, m22, m23), (m30, m31, m32, m33)) = m
a = (m00 * mat3.det(((m11, m12, m13), (m21, m22, m23), (m31, m32, m33))))
b = (m10 * mat3.det(((m01, m02, m03), (m21, m22, m23), (m31, m32, m33))))
c = (m20 * mat3.det(((m01, m02, m03), (m11, m12, m1... |
def test_deep_prop():
root = MyRootTrackable()
tree1 = MyTrackable()
tree1.sub1 = MyTrackable()
tree1.sub1.sub1 = t1 = MyTrackable()
tree2 = MyTrackable()
tree2.sub1 = MyTrackable()
tree2.sub1.sub1 = t2 = MyTrackable()
root.sub1 = tree1
with root.track_usage('x'):
root.sub1.s... |
def test_random_geometric():
rng = shared(np.random.RandomState(123))
p = np.array([0.3, 0.7])
g = pt.random.geometric(p, size=(10000, 2), rng=rng)
g_fn = random_function([], g, mode=jax_mode)
samples = g_fn()
np.testing.assert_allclose(samples.mean(axis=0), (1 / p), rtol=0.1)
np.testing.ass... |
class TestTerminalWriter():
(params=['path', 'stringio'])
def tw(self, request, tmp_path: Path) -> Generator[(terminalwriter.TerminalWriter, None, None)]:
if (request.param == 'path'):
p = tmp_path.joinpath('tmpfile')
f = open(str(p), 'w+', encoding='utf8')
tw = termi... |
def test_select_ctrl_c(outsim_app, monkeypatch):
read_input_mock = mock.MagicMock(name='read_input', side_effect=KeyboardInterrupt)
monkeypatch.setattr('cmd2.Cmd.read_input', read_input_mock)
with pytest.raises(KeyboardInterrupt):
outsim_app.select([('Guitar', 'Electric Guitar'), ('Drums',)], 'Instr... |
def import_userscript(name):
repo_root = pathlib.Path(__file__).resolve().parents[2]
script_path = (((repo_root / 'misc') / 'userscripts') / name)
module_name = name.replace('-', '_')
loader = importlib.machinery.SourceFileLoader(module_name, str(script_path))
spec = importlib.util.spec_from_loader(... |
def type_convert(results):
java_dtype = str(results.getType())
if (java_dtype == 'Boolean'):
results = results.getResultAsBoolean()
if (results == 1):
return True
else:
return False
elif (java_dtype == 'String'):
return results.getResultAsString()
... |
class TestCheckpointer(unittest.TestCase):
def create_model(self):
return nn.Sequential(nn.Linear(2, 3), nn.Linear(3, 1))
def create_complex_model(self):
m = nn.Module()
m.block1 = nn.Module()
m.block1.layer1 = nn.Linear(2, 3)
m.layer2 = nn.Linear(3, 2)
m.res = nn... |
def test_device_wrong_manufacturer():
args = {**DEVICE_PROPERTIES, 'manufacturer': 'pywemo'}
xsd_device = device_parser.DeviceType(**args)
root = device_parser.root(device=xsd_device)
with mock.patch(DEVICE_PARSER) as mock_parser, pytest.raises(InvalidSchemaError):
mock_parser.parseString.return... |
class ModelArguments():
model_name_or_path: str = field(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_name: Optional[s... |
def test_MinMaxScaler_matrix(decision_matrix):
dm = decision_matrix(seed=42, min_alternatives=10, max_alternatives=10, min_criteria=20, max_criteria=20, min_objectives_proportion=0.5)
mtx = dm.matrix.to_numpy()
mtx_min = np.min(mtx, axis=0, keepdims=True)
mtx_max = np.max(mtx, axis=0, keepdims=True)
... |
class DribbbleOAuth2Test(OAuth2Test):
backend_path = 'social_core.backends.dribbble.DribbbleOAuth2'
user_data_url = '
expected_username = 'foobar'
access_token_body = json.dumps({'access_token': 'foobar', 'token_type': 'bearer'})
user_data_body = json.dumps({'id': 'foobar', 'username': 'foobar', 'na... |
def preprocess_and_save(json_path='./unprocessed.json', text_key='abstract', save_dir='./data', streamlit=False, component=None):
if (not json_path.endswith('.json')):
raise ValueError('Selected `json_path` should end with `.json`.')
if (streamlit and (component is None)):
raise ValueError('`com... |
def test_create_user_policy(initialized_db, app):
with client_with_identity('freshuser', app) as cl:
response = conduct_api_call(cl, UserAutoPrunePolicies, 'POST', {'orgname': 'freshuser'}, {'method': 'creation_date', 'value': '2w'}, 201).json
assert (response['uuid'] is not None)
assert (mo... |
def _connect_reddit():
if (_config is None):
error("Can't connect to reddit without a config")
return None
return praw.Reddit(client_id=_config.r_oauth_key, client_secret=_config.r_oauth_secret, username=_config.r_username, password=_config.r_password, user_agent=_config.useragent, check_for_upd... |
class TFCvtSelfAttentionConvProjection(tf.keras.layers.Layer):
def __init__(self, config: CvtConfig, embed_dim: int, kernel_size: int, stride: int, padding: int, **kwargs):
super().__init__(**kwargs)
self.padding = tf.keras.layers.ZeroPadding2D(padding=padding)
self.convolution = tf.keras.la... |
def test_transformer__get_last_used_operation():
transformer = Transformer.from_crs('EPSG:4326', 'EPSG:3857')
if PROJ_GTE_91:
with pytest.raises(ProjError, match='Last used operation not found\\. This is likely due to not initiating a transform\\.'):
transformer.get_last_used_operation()
... |
()
def django_pytester(request: pytest.FixtureRequest, pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch) -> DjangoPytester:
from pytest_django_test.db_helpers import DB_NAME, SECOND_DB_NAME, SECOND_TEST_DB_NAME, TEST_DB_NAME
marker = request.node.get_closest_marker('django_project')
options = _mar... |
def scalar_elemwise(*symbol, nfunc=None, nin=None, nout=None, symbolname=None):
import pytensor.scalar as scalar
def construct(symbol):
nonlocal symbolname
symbolname = (symbolname or symbol.__name__)
if symbolname.endswith('_inplace'):
base_symbol_name = symbolname[:(- len('... |
def _shufflenetv2(arch, pretrained, progress, quantize, *args, **kwargs):
model = QuantizableShuffleNetV2(*args, **kwargs)
_replace_relu(model)
if quantize:
backend = 'fbgemm'
quantize_model(model, backend)
else:
assert (pretrained in [True, False])
if pretrained:
if ... |
def _get_rank_to_manifest(metadata: SnapshotMetadata) -> List[Dict[(str, Entry)]]:
rank_to_manifest: List[Dict[(str, Entry)]] = [{} for _ in range(metadata.world_size)]
for (path, entry) in metadata.manifest.items():
tokens = path.split('/')
rnk = int(tokens.pop(0))
logical_path = '/'.jo... |
class Model(TrainableModel):
def __init__(self, pretrained_name: str='paraphrase-multilingual-MiniLM-L12-v2', num_groups: int=27, lr: float=3e-05):
self._pretrained_name = pretrained_name
self._num_groups = num_groups
self._lr = lr
super().__init__()
def configure_encoders(self) ... |
.parametrize(argnames=['value'], argvalues=[['X'], [5]])
def test_union(module: DataclassModule, value: t.List[object], assert_dump_load: AssertLoadDumpProtocol) -> None:
class A():
x: t.Union[(int, str)]
schema = desert.schema_class(A)()
dumped = {'x': value}
loaded = A(value)
assert_dump_l... |
class UnityEnvironment(BaseEnvironment):
def __init__(self, num_agents=2, max_episode_length=200, observation_types=None, use_editor=False, base_port=8080, port_id=0, executable_args={}, recording_options={'recording': False, 'output_folder': None, 'file_name_prefix': None, 'cameras': 'PERSON_FROM_BACK', 'modality'... |
class BatchTests(unittest.TestCase):
def test_v2(self):
batch = event_publisher.V2Batch(max_size=50)
batch.add(None)
batch.add(b'a')
batch.add(b'b')
result = batch.serialize()
self.assertEqual(result.item_count, 2)
self.assertEqual(result.serialized, b'{"1":{"... |
class TestFindFlags():
.parametrize('case_sensitive, backward, expected', [(True, True, (QWebEnginePage.FindFlag.FindCaseSensitively | QWebEnginePage.FindFlag.FindBackward)), (True, False, QWebEnginePage.FindFlag.FindCaseSensitively), (False, True, QWebEnginePage.FindFlag.FindBackward), (False, False, QWebEnginePag... |
def insertSamples(count, insert_records):
recs = [((- 3), 123, , decimal.Decimal('.40031'), decimal.Decimal('432.40031'), 'some_oa_thing', 'varying', '', datetime.datetime(1982, 5, 18, 12, 0, 0, 100232)) for x in range(count)]
gen = time.time()
insert_records.load_rows(recs)
fin = time.time()
xactti... |
class XpDirectory(Mssql):
OUTPUT_FORMAT_XP_DIRTREE = '{0} ({1})\n'
REQ_XP_DIRTREE = "EXEC master..xp_dirtree '{0}',1,1;"
REQ_XP_FILEEXIST = "EXEC MASTER.DBO.XP_FILEEXIST '{0}';"
REQ_XP_FIXEDDRIVES = 'EXEC master.sys.xp_fixeddrives'
REQ_XP_AVAILABLEMEDIA = 'EXEC master.sys.xp_availablemedia'
REQ_... |
def get_resnet_v1_b_base(input_x, freeze_norm, scope='resnet50_v1b', bottleneck_nums=[3, 4, 6, 3], base_channels=[64, 128, 256, 512], freeze=[True, False, False, False, False], is_training=True):
assert (len(bottleneck_nums) == len(base_channels)), 'bottleneck num should same as base_channels size'
assert (len(... |
class DistributedStorage(StoragePaths):
def __init__(self, storages, preferred_locations=None, default_locations=None, proxy=None, readonly_mode=False, validate_endtoend=False):
self._storages = dict(storages)
self.preferred_locations = list((preferred_locations or []))
self.default_location... |
def thread_fn(receive_from_trio, send_to_trio):
while True:
try:
request = trio.from_thread.run(receive_from_trio.receive)
except trio.EndOfChannel:
trio.from_thread.run(send_to_trio.aclose)
return
else:
response = (request + 1)
tri... |
def test_format_interval_invalid_skeleton():
t1 = TEST_DATE
t2 = (TEST_DATE + datetime.timedelta(days=1))
assert (dates.format_interval(t1, t2, 'mumumu', fuzzy=False, locale='fi') == '8.1.20169.1.2016')
assert (dates.format_interval(t1, t2, fuzzy=False, locale='fi') == '8.1.20169.1.2016') |
class FlavaProcessor(ProcessorMixin):
attributes = ['image_processor', 'tokenizer']
image_processor_class = 'FlavaImageProcessor'
tokenizer_class = ('BertTokenizer', 'BertTokenizerFast')
def __init__(self, image_processor=None, tokenizer=None, **kwargs):
if ('feature_extractor' in kwargs):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.