code stringlengths 281 23.7M |
|---|
def test_none_attr_custom_init():
assert (get_attrs_shape(NoneAttrCustomInit) == Shape(input=InputShape(constructor=NoneAttrCustomInit, kwargs=None, fields=(InputField(type=Any, id='a', default=NoDefault(), is_required=True, metadata=MappingProxyType({}), original=ANY),), params=(Param(field_id='a', name='a', kind=... |
def get_locked_package(dependency: Dependency, packages_by_name: dict[(str, list[Package])], decided: (dict[(Package, Dependency)] | None)=None) -> (Package | None):
decided = (decided or {})
candidates = packages_by_name.get(dependency.name, [])
overlapping_candidates = set()
for package in candidates:... |
class ChannelUsability(Enum):
USABLE = True
NOT_OPENED = 'channel is not open'
INVALID_SETTLE_TIMEOUT = 'channel settle timeout is too low'
CHANNEL_REACHED_PENDING_LIMIT = 'channel reached limit of pending transfers'
CHANNEL_DOESNT_HAVE_ENOUGH_DISTRIBUTABLE = "channel doesn't have enough distributab... |
class d_lka_former_trainer_synapse(Trainer_synapse):
def __init__(self, plans_file, fold, output_folder=None, dataset_directory=None, batch_dice=True, stage=None, unpack_data=True, deterministic=True, fp16=False, trans_block=None, depths=[3, 3, 3, 3], skip_connections=[True, True, True, True], seed=12345):
... |
def collect_citations(dag: ProvDAG, deduplicate: bool=True) -> bp.bibdatabase.BibDatabase:
bdb = bp.bibdatabase.BibDatabase()
citations = []
for node_uuid in dag:
node = dag.get_node_data(node_uuid)
if (node is not None):
node_citations = list(node.citations.values())
... |
def handle_refundtransfer(received_transfer: LockedTransferUnsignedState, channel_state: NettingChannelState, refund: ReceiveTransferRefund) -> EventsOrError:
events: List[Event]
(is_valid, msg, pending_locks) = is_valid_refund(refund=refund, channel_state=channel_state, sender_state=channel_state.partner_state... |
def test_makereport_getsource(pytester: Pytester) -> None:
pytester.makepyfile('\n def test_foo():\n if False: pass\n else: assert False\n ')
result = pytester.runpytest()
result.stdout.no_fnmatch_line('*INTERNALERROR*')
result.stdout.fnmatch_lines(['*else: assert False*'... |
def test_specific_location(hatch, helpers, temp_dir_data, path_append, dist_name, mocker):
install_dir = (((temp_dir_data / 'foo') / 'bar') / 'baz')
dist_dir = (install_dir / dist_name)
python_path = (dist_dir / get_distribution(dist_name).python_path)
install = mocker.patch('hatch.python.core.PythonMan... |
def test_qubit_vs_toffoli_original_strategy():
lam = 307.68
dE = 0.001
eps = (dE / (10 * lam))
n = 108
chi = 10
beta = 16
M = 350
ref_tof = np.asarray([95, 89, 2852, 10, 18, 10, 54, 402, 1512, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,... |
def pytask_execute_task_setup(session: Session, task: PTask) -> None:
is_unchanged = (has_mark(task, 'skip_unchanged') and (not has_mark(task, 'would_be_executed')))
if (is_unchanged and (not session.config['force'])):
raise SkippedUnchanged
is_skipped = has_mark(task, 'skip')
if is_skipped:
... |
def test_async_cmd_maximal_not_save():
context = Context({'cmds': {'run': ['A', 'B'], 'cwd': '/cwd', 'stdout': '/stdout', 'stderr': '/stderr', 'encoding': 'enc', 'bytes': True, 'append': True}})
step = AsyncCmdStep('blah', context)
assert (len(step.commands) == 1)
cmd1 = step.commands[0]
assert (cmd... |
class FlowNetSD(nn.Module):
def __init__(self, args, batchNorm=True):
super(FlowNetSD, self).__init__()
self.batchNorm = batchNorm
self.conv0 = conv(self.batchNorm, 6, 64)
self.conv1 = conv(self.batchNorm, 64, 64, stride=2)
self.conv1_1 = conv(self.batchNorm, 64, 128)
... |
class HuffmanLength(object):
def __init__(self, code, bits=0):
self.code = code
self.bits = bits
self.symbol = None
self.reverse_symbol = None
def __repr__(self):
return repr((self.code, self.bits, self.symbol, self.reverse_symbol))
def _sort_func(obj):
return... |
def parse_select(toks, start_idx, tables_with_alias, schema, default_tables=None):
idx = start_idx
len_ = len(toks)
assert (toks[idx] == 'select'), "'select' not found"
idx += 1
isDistinct = False
if ((idx < len_) and (toks[idx] == 'distinct')):
idx += 1
isDistinct = True
val... |
class RHEL4_Network(FC3_Network):
removedKeywords = FC3_Network.removedKeywords
removedAttrs = FC3_Network.removedAttrs
def _getParser(self):
op = FC3_Network._getParser(self)
op.add_argument('--notksdevice', action='store_true', default=False, version=RHEL4, help='This network device is not... |
def test_unstructure_deeply_nested_generics(genconverter):
class Inner():
a: int
class Outer(Generic[T]):
inner: T
initial = Outer[Inner](Inner(1))
raw = genconverter.unstructure(initial, Outer[Inner])
assert (raw == {'inner': {'a': 1}})
raw = genconverter.unstructure(initial)
... |
def test_scalar_overlay_visualisation(nifti_data):
patient_path = nifti_data.joinpath('LCTSC-Test-S1-201')
ct_path = next(patient_path.glob('IMAGES/*.nii.gz'))
structures = {struct.name.split('.nii.gz')[0].split('RTSTRUCT_')[(- 1)]: sitk.ReadImage(str(struct)) for struct in patient_path.glob('STRUCTURES/*.n... |
_required
def version_delete(request, package_name, version):
plugin = get_object_or_404(Plugin, package_name=package_name)
version = get_object_or_404(PluginVersion, plugin=plugin, version=version)
if (not check_plugin_access(request.user, plugin)):
return render(request, 'plugins/version_permissio... |
class StsbProcessor(DataProcessor):
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'), str(tensor_dict['label'].numpy()))
def get_train_examples(self, dat... |
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, radix=1, cardinality=1, bottleneck_width=64, avd=False, avd_first=False, dilation=1, is_first=False, rectified_conv=False, rectify_avg=False, norm_layer=None, dropblock_prob=0.0, last_gamma=False, number=1... |
def torch_expm(A):
n_A = A.shape[0]
A_fro = torch.sqrt(A.abs().pow(2).sum(dim=(1, 2), keepdim=True))
maxnorm = torch.tensor([5.], dtype=A.dtype, device=A.device)
zero = torch.tensor([0.0], dtype=A.dtype, device=A.device)
n_squarings = torch.max(zero, torch.ceil(torch_log2((A_fro / maxnorm))))
A_... |
def test_stl_caster_vs_stl_bind(msg):
import pybind11_cross_module_tests as cm
v1 = cm.VectorInt([1, 2, 3])
assert (m.load_vector_via_caster(v1) == 6)
assert (cm.load_vector_via_binding(v1) == 6)
v2 = [1, 2, 3]
assert (m.load_vector_via_caster(v2) == 6)
with pytest.raises(TypeError) as excin... |
def test_format_response():
response = CachedResponse(status_code=200, expires=datetime(2021, 1, 1), headers={'Age': '0'})
response_str = format_response(response)
assert ('cached; expires in ' in response_str)
assert ('Age: 0' in response_str)
response.expires = None
assert ('never expires' in ... |
.parametrize('untied', [True, False])
def test_RanksComparatorPlotter_reg_unexpected_keyword_argument_color(untied):
rank0 = agg.RankResult('test', ['a', 'b'], [1, 1], {})
rank1 = agg.RankResult('test', ['a', 'b'], [1, 1], {})
rcmp = ranks_cmp.mkrank_cmp(rank0, rank1)
with pytest.raises(TypeError):
... |
def yaml_load(f: Union[(str, IO[str])]) -> Any:
start = datetime.datetime.now()
with log.py_warning_filter(category=DeprecationWarning, message="Using or importing the ABCs from 'collections' instead of from 'collections\\.abc' is deprecated.*"):
try:
data = yaml.load(f, Loader=YamlLoader)
... |
def test_magic():
mgc = magic.Magic(mime=True)
with GeneratorFile(mimed_html_generator()) as f:
buffered = BufferedReader(f)
file_header_bytes = buffered.peek(1024)
assert (mgc.from_buffer(file_header_bytes) == 'text/html')
with GeneratorFile(sample_generator()) as f:
buffere... |
class SlotSelector(discord.ui.Select):
view: BaseSelector
def __init__(self, bot, records):
_options = []
for record in records[:25]:
reg_channel = bot.get_channel(record['registration_channel_id'])
_options.append(discord.SelectOption(label=f"Slot {record['num']} #{geta... |
def build_detector(cfg, train_cfg=None, test_cfg=None):
if ((train_cfg is not None) or (test_cfg is not None)):
warnings.warn('train_cfg and test_cfg is deprecated, please specify them in model', UserWarning)
assert ((cfg.get('train_cfg') is None) or (train_cfg is None)), 'train_cfg specified in both ou... |
class ForecastDisplay(Observer, DisplayElement):
__currentPressure: float = 29.92
__lastPressure: float
__weatherData: WeatherData
def __init__(self, weatherData: WeatherData):
self.__weatherData = weatherData
weatherData.registerObserver(self)
def update(self, temp: float, humidity:... |
def runningInNotebook():
try:
shell = get_ipython().__class__.__name__
if (shell == 'ZMQInteractiveShell'):
return True
elif (shell == 'TerminalInteractiveShell'):
return False
else:
return False
except NameError:
return False |
('beeref.actions.mixin.menu_structure')
('beeref.actions.mixin.actions')
def test_build_menu_and_actions_with_submenu(actions_mock, menu_mock, qapp):
widget = FooWidget()
actions_mock.__iter__.return_value = [{'id': 'foo', 'text': '&Foo', 'callback': 'on_foo', 'group': 'bar'}]
menu_mock.__iter__.return_valu... |
class Effect11423(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
for dmgType in ('em', 'kinetic', 'explosive', 'thermal'):
fit.modules.filteredChargeBoost((lambda mod: mod.charge.requiresSkill('Heavy Missiles')), f'{dmgType}Damage', ship.getModified... |
.parametrize('tensor', [torch.rand(2, 3, 4, 5), torch.rand(2, 3, 4, 5, 6)])
.parametrize('idx', range(3))
.parametrize('ndim', range(1, 4))
.parametrize('slice_leading_dims', [True, False])
def test_getitem_batch_size_mask(tensor, idx, ndim, slice_leading_dims):
if ((idx + ndim) > 4):
pytest.skip('Not enoug... |
class TestReadBytes():
()
def adapterR(self, adapter):
adapter.write('*IDN?')
(yield adapter)
def test_read_bytes(self, adapterR):
assert (adapterR.read_bytes(22) == b'SCPI,MOCK,VERSION_1.0\n')
def test_read_all_bytes(self, adapterR):
assert (adapterR.read_bytes((- 1)) ==... |
.parametrize('ndarray_type', ['numpy', 'cupy'])
def test_regenie__glow_comparison(ndarray_type: str, datadir: Path) -> None:
xp = pytest.importorskip(ndarray_type)
with open((datadir / 'config.yml')) as fd:
config = yaml.load(fd, Loader=yaml.FullLoader)
for run in config['runs']:
check_simul... |
def test_column_lateral_ref_within_subquery():
sql = '\n insert into public.tgt_tbl1\n select\n sq.name\n from\n (\n select\n id || name as alias1,\n alias1 || email as name\n from\n public.src_tbl1\n ) as sq\n '
... |
class UnetConv3(nn.Module):
def __init__(self, in_size, out_size, is_batchnorm, kernel_size=(3, 3, 1), padding_size=(1, 1, 0), init_stride=(1, 1, 1)):
super(UnetConv3, self).__init__()
if is_batchnorm:
self.conv1 = nn.Sequential(nn.Conv3d(in_size, out_size, kernel_size, init_stride, padd... |
def ebic(log_lik, n_samples, n_features, n_support, gamma='default', fit_intercept=True):
if fit_intercept:
n_features = (n_features + 1)
n_support = (n_support + 1)
if (gamma == 'default'):
gamma = (1 - (0.5 * (np.log(n_samples) / np.log(n_features))))
gamma = np.clip(gamma, a_m... |
_doc(np.cross)
def cross(a, b, axisa=(- 1), axisb=(- 1), axisc=(- 1), axis=None):
if (not (isinstance(a, Quantity) and isinstance(b, Quantity))):
return np.cross(a, b, axisa, axisb, axisc, axis)
if (not isinstance(a, Quantity)):
a = Quantity(a, dimensionless, copy=False)
if (not isinstance(b... |
class QuadraticProgramToQubo(QuadraticProgramConverter):
def __init__(self, penalty: Optional[float]=None) -> None:
from ..converters.integer_to_binary import IntegerToBinary
from ..converters.inequality_to_equality import InequalityToEquality
from ..converters.linear_equality_to_penalty imp... |
def create_experiment(config, resume=None):
if (resume is not None):
print(('\n==> Restoring experiment from directory:\n' + resume))
logdir = resume
else:
name = 'TR_MC_nusc'
logdir = os.path.join(os.path.expandvars(config.logdir), name)
print(('\n==> Creating new experi... |
class Effect6153(BaseEffect):
type = 'passive'
def handler(fit, module, context, projectionRange, **kwargs):
fit.modules.filteredItemMultiply((lambda mod: mod.item.requiresSkill('High Speed Maneuvering')), 'capacitorNeed', (1 / module.getModifiedItemAttr('modeMWDCapPostDiv')), **kwargs) |
def run_random_search(max_time_budget=5000000.0):
nasbench.reset_budget_counters()
(times, best_valids, best_tests) = ([0.0], [0.0], [0.0])
while True:
spec = random_spec()
data = nasbench.query(spec)
if (data['validation_accuracy'] > best_valids[(- 1)]):
best_valids.appe... |
class SizeEstimator(object):
def __init__(self, model, input_size=(1, 1, 32, 32), bits=32):
self.model = model
self.input_size = input_size
self.bits = 32
return
def get_parameter_sizes(self):
mods = list(self.model.modules())
sizes = []
for i in range(1, ... |
def test_trustme_cli_identities(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.chdir(tmp_path)
main(argv=['-i', 'example.org', 'www.example.org'])
assert tmp_path.joinpath('server.key').exists()
assert tmp_path.joinpath('server.pem').exists()
assert tmp_path.joinpath('client.p... |
def _parse_HITRAN_class6(df, verbose=True, dataframe_type='pandas'):
if (dataframe_type == 'pandas'):
dgu = df['globu'].astype(str).str.extract('[ ]{9}(?P<v1u>[\\-\\d ]{2})(?P<v2u>[\\-\\d ]{2})(?P<v3u>[\\-\\d ]{2})', expand=True)
dgl = df['globl'].astype(str).str.extract('[ ]{9}(?P<v1l>[\\-\\d ]{2})... |
class BehavioralRTLIRTypeEnforcerL1(bir.BehavioralRTLIRNodeVisitor):
def __init__(s, component):
s.component = component
def enter(s, blk, context, node):
s.blk = blk
s.stack = deque([])
with s.register_context(context):
s.visit(node)
def register_context(s, conte... |
class CircularBuffer():
def __init__(self, size):
self.max_size = size
self.data = np.zeros(self.max_size)
self.size = 0
self.pointer = (- 1)
def add(self, element):
self.size = min((self.size + 1), self.max_size)
self.pointer = ((self.pointer + 1) % self.max_size... |
def main():
with open(FLAGS.cluster_spec_file) as fp:
cluster_spec = json.load(fp)
workers = cluster_spec['worker']
master = workers[0]
number_of_ps = len(cluster_spec['ps'])
ps_job = '/job:ps/'
train_ops = []
for (dev_id, _) in enumerate(workers):
device = '/job:worker/task:... |
def pack(v_short, v_post):
dest_dir = (DataDir / ExtPlats.sourcebuild)
dest_dir.mkdir(parents=True, exist_ok=True)
libname = LibnameForSystem[Host.system]
shutil.copy((PDFiumBuildDir / libname), (dest_dir / libname))
write_pdfium_info(dest_dir, v_short, origin='sourcebuild', **v_post)
run_ctypes... |
class BusinessLogicTests(object):
def setUp(self):
self.store = self.get_store()
self.logic = BusinessLogic(self.store, '')
def tearDown(self):
signal.alarm(0)
signal.signal(signal.SIGALRM, signal.SIG_DFL)
self.free_store()
def test_noop(self):
pass
def te... |
def objective(objective, objective_config: str, **kwargs) -> Type[Objective]:
if (objective == 'docking'):
from molpal.objectives.docking import DockingObjective
return DockingObjective(objective_config, **kwargs)
if (objective == 'lookup'):
from molpal.objectives.lookup import LookupObj... |
class TestHandler(BufferingHandler):
def __init__(self, only_warnings=False):
self.only_warnings = only_warnings
BufferingHandler.__init__(self, 0)
def shouldFlush(self, record):
return False
def emit(self, record):
if (self.only_warnings and (record.level != logging.WARNING)... |
class WriteFailedError(ErrorMessage):
def __init__(self, parent, song):
title = _('Unable to save song')
fn_format = util.bold(fsn2text(song('~basename')))
description = (_('Saving %(file-name)s failed.The file may be read-only, corrupted, or you do not have permission to edit it.') % {'file... |
class SawyerBasketballEnv(SawyerXYZEnv):
def __init__(self):
liftThresh = 0.3
goal_low = ((- 0.1), 0.85, 0.15)
goal_high = (0.1, (0.9 + 1e-07), 0.15)
hand_low = ((- 0.5), 0.4, 0.05)
hand_high = (0.5, 1, 0.5)
obj_low = ((- 0.1), 0.6, 0.03)
obj_high = (0.1, 0.7,... |
_grad()
def _get_stats_multilabel(output: torch.LongTensor, target: torch.LongTensor) -> Tuple[(torch.LongTensor, torch.LongTensor, torch.LongTensor, torch.LongTensor)]:
(batch_size, num_classes, *dims) = target.shape
output = output.view(batch_size, num_classes, (- 1))
target = target.view(batch_size, num_... |
def parse_args():
parser = argparse.ArgumentParser(description='Finetune a transformers model on a text classification task')
parser.add_argument('--task_name', type=str, default=None, help='The name of the glue task to train on.', choices=list(task_to_keys.keys()))
parser.add_argument('--train_file', type=... |
class OSTreeContainer_TestCase(unittest.TestCase):
def runTest(self):
cmd = F38_OSTreeContainer()
self.assertEqual(cmd.noSignatureVerification, False)
op = cmd._getParser()
for action in op._actions:
if ('--url' in action.option_strings):
self.assertEqual(... |
def test_dns_record_hashablity_does_not_consider_ttl():
record1 = r.DNSAddress('irrelevant', const._TYPE_A, const._CLASS_IN, const._DNS_OTHER_TTL, b'same')
record2 = r.DNSAddress('irrelevant', const._TYPE_A, const._CLASS_IN, const._DNS_HOST_TTL, b'same')
record_set = {record1, record2}
assert (len(recor... |
class W_StructPropertyAccessor(values.W_Procedure):
errorname = 'struct-property-accessor'
_attrs_ = _immutable_fields_ = ['property']
import_from_mixin(SingleResultMixin)
def __init__(self, prop):
self.property = prop
def get_arity(self, promote=False):
return Arity.ONE
_call_me... |
.requires_internet
def test_install_project_no_dev_mode(hatch, helpers, temp_dir, platform, config_file, extract_installed_requirements):
config_file.model.template.plugins['default']['tests'] = False
config_file.save()
project_name = 'My.App'
with temp_dir.as_cwd():
result = hatch('new', projec... |
def _get_pointwise_all_likefism_data(dataset, num_negatives, train_dict):
(user_input, num_idx, item_input, labels) = ([], [], [], [])
num_users = dataset.num_users
num_items = dataset.num_items
for u in range(num_users):
items_by_user = train_dict[u].copy()
items_set = set(items_by_user... |
def main():
parser = argparse.ArgumentParser(description='Identify bugfixes. Use this script together with a\n gitlog.json and a path with issues. The gitlog.json\n is created using the git_log_to_array.py script a... |
def build_data_instance_training(row, correct_lang_feedback: str, include_input=False, cur_df_path=None, add_reference=False):
success = row['execution_result']['success']
problem = row['prompt']
generated_solution = row['generation']
reference = row['reference']
if (not success):
if ('trace... |
def train_mlm(args, gpu_id, rank, loader, model, optimizer, scheduler):
model.train()
start_time = time.time()
(total_loss, total_loss_mlm, total_loss_nsp) = (0.0, 0.0, 0.0)
(total_correct, total_denominator) = (0.0, 0.0)
total_instances = (0.0, 0.0)
steps = 1
total_steps = args.total_steps
... |
def test_known_answer_supression_service_type_enumeration_query():
zc = Zeroconf(interfaces=['127.0.0.1'])
type_ = '_otherknown._tcp.local.'
name = 'knownname'
registration_name = f'{name}.{type_}'
desc = {'path': '/~paulsm/'}
server_name = 'ash-2.local.'
info = ServiceInfo(type_, registrati... |
def read_tmy2(filename):
string = '%2d%2d%2d%2d%4d%4d%4d%1s%1d%4d%1s%1d%4d%1s%1d%4d%1s%1d%4d%1s%1d%4d%1s%1d%4d%1s%1d%2d%1s%1d%2d%1s%1d%4d%1s%1d%4d%1s%1d%3d%1s%1d%4d%1s%1d%3d%1s%1d%3d%1s%1d%4d%1s%1d%5d%1s%1d%10d%3d%1s%1d%3d%1s%1d%3d%1s%1d%2d%1s%1d'
columns = 'year,month,day,hour,ETR,ETRN,GHI,GHISource,GHIUncerta... |
def sample_mesh_brute(tri_points: wp.array(dtype=wp.vec3), tri_indices: wp.array(dtype=int), tri_count: int, query_points: wp.array(dtype=wp.vec3), query_faces: wp.array(dtype=int), query_signs: wp.array(dtype=float), query_dist: wp.array(dtype=float)):
tid = wp.tid()
min_face = int(0)
min_dist = float(1000... |
def simpleDialog(item, action, question, options, defaultOption):
if isinstance(item, FileItem):
filename = item.id
else:
filename = item.id()
mb = QtWidgets.QMessageBox
M = {'ok': mb.Ok, 'open': mb.Open, 'save': mb.Save, 'cancel': mb.Cancel, 'close': mb.Close, 'discard': mb.Discard, 'ap... |
class Effect5333(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Medium Energy Turret')), 'damageMultiplier', ship.getModifiedItemAttr('shipBonusABC2'), skill='Amarr Battlecruiser', **kwargs) |
class IterationBatchSampler(object):
def __init__(self, data_source, batch_size, num_samples, shuffle=False, indices=None):
self.batch_size = batch_size
self.num_samples = num_samples
self.shuffle = shuffle
self.data_source = data_source
self.index_queue = list(range(len(self... |
class TradingDayOfWeekRule(six.with_metaclass(ABCMeta, StatelessRule)):
(n=lossless_float_to_int('TradingDayOfWeekRule'))
def __init__(self, n, invert):
if (not (0 <= n < MAX_WEEK_RANGE)):
raise _out_of_range_error(MAX_WEEK_RANGE)
self.td_delta = (((- n) - 1) if invert else n)
de... |
(('Python' not in caffe.layer_type_list()), 'Caffe built without Python layer support')
class TestPythonLayer(unittest.TestCase):
def setUp(self):
net_file = python_net_file()
self.net = caffe.Net(net_file, caffe.TRAIN)
os.remove(net_file)
def test_forward(self):
x = 8
se... |
def memory_subplot(output, data_list):
import matplotlib.pyplot as plt
from matplotlib import dates
number_plots = len(data_list)
(fig, all_memory_axes) = plt.subplots(1, number_plots, sharey='row')
if (number_plots == 1):
all_memory_axes = [all_memory_axes]
memory_max = 0.0
for line... |
class TestSharedData():
def test_default(self, isolation):
builder = WheelBuilder(str(isolation))
assert (builder.config.shared_data == builder.config.shared_data == {})
def test_invalid_type(self, isolation):
config = {'tool': {'hatch': {'build': {'targets': {'wheel': {'shared-data': 42... |
_flax
class FlaxViTBertModelTest(VisionTextDualEncoderMixin, unittest.TestCase):
def get_pretrained_model_and_inputs(self):
model = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained('hf-internal-testing/tiny-random-vit', 'hf-internal-testing/tiny-bert', vision_from_pt=True, text_from_pt=True)
... |
def main(root):
generate_default_image_optim_loop_asset(root)
generate_default_image_optim_loop_processing_asset(root)
generate_default_image_pyramid_optim_loop_asset(root)
generate_default_image_pyramid_optim_loop__processing_asset(root)
generate_default_transformer_optim_loop_asset(root)
gener... |
def test_hierarchical_logp():
with pm.Model() as m:
x = pm.Uniform('x', lower=0, upper=1)
y = pm.Uniform('y', lower=0, upper=x)
logp_ancestors = list(ancestors([m.logp()]))
ops = {a.owner.op for a in logp_ancestors if a.owner}
assert (len(ops) > 0)
assert (not any((isinstance(o, Rand... |
_start_docstrings('Bert Based model to embed queries or document for document retrieval.', RETRIBERT_START_DOCSTRING)
class RetriBertModel(RetriBertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.projection_dim = config.projection_dim
self.bert_query = BertModel(c... |
def animate(message: str, do_animation: bool, *, delay: float=0) -> Generator[(None, None, None)]:
if ((not do_animation) or (not _env_supports_animation())):
sys.stderr.write(f'''{message}...
''')
(yield)
return
event = Event()
if EMOJI_SUPPORT:
animate_at_beginning_of_line ... |
class TransformerDecoder(nn.Module):
def __init__(self, decoder_layer: nn.Module, num_layers: int, norm: Optional[nn.Module]=None, return_intermediate: Optional[bool]=False) -> None:
super().__init__()
self.layers = _get_clones(decoder_layer, num_layers)
self.num_layers = num_layers
... |
def abs_relative(depth_pred, depth_gt):
assert np.all((((np.isfinite(depth_pred) & np.isfinite(depth_gt)) & (depth_pred >= 0)) & (depth_gt >= 0)))
diff = (depth_pred - depth_gt)
num_pixels = float(diff.size)
if (num_pixels == 0):
return np.nan
else:
return (np.sum((np.absolute(diff) ... |
def import_all_modules(root: str, base_module: str) -> None:
for file in os.listdir(root):
if (file.endswith(('.py', '.pyc')) and (not file.startswith('_'))):
module = file[:file.find('.py')]
if (module not in sys.modules):
module_name = '.'.join([base_module, module]... |
def validate_uint64(value: int, title: str='Value') -> None:
if ((not isinstance(value, int)) or isinstance(value, bool)):
raise ValidationError(f'{title} must be an integer: Got: {type(value)}')
if (value < 0):
raise ValidationError(f'{title} cannot be negative: Got: {value}')
if (value > U... |
def test_specify_elements_with_labels(standard):
network = Network(standard.tpm.tpm, node_labels=('A', 'B', 'C'))
subsystem = Subsystem(network, (0, 0, 0), ('B', 'C'))
assert (subsystem.node_indices == (1, 2))
assert (tuple((node.label for node in subsystem.nodes)) == ('B', 'C'))
assert (str(subsyst... |
def test_caplog_captures_for_all_stages(caplog: pytest.LogCaptureFixture, logging_during_setup_and_teardown: None) -> None:
assert (not caplog.records)
assert (not caplog.get_records('call'))
logger.info('a_call_log')
assert ([x.message for x in caplog.get_records('call')] == ['a_call_log'])
assert ... |
def decode_opcreate_script(script: bytes) -> Optional[list]:
try:
decoded = [x for x in script_GetOp(script)]
except MalformedBitcoinScript:
return None
if ((len(decoded) == 5) and (decoded[0] == (1, b'\x04', 2)) and (decoded[(- 1)][0] == opcodes.OP_CREATE)):
return decoded
retur... |
def pytest_cmdline_main(config: Config) -> Optional[Union[(int, ExitCode)]]:
if (config.option.version > 0):
showversion(config)
return 0
elif config.option.help:
config._do_configure()
showhelp(config)
config._ensure_unconfigure()
return 0
return None |
def _bpx_to_param_dict(bpx: BPX) -> dict:
pybamm_dict = {}
pybamm_dict = _bpx_to_domain_param_dict(bpx.parameterisation.cell, pybamm_dict, cell)
pybamm_dict = _bpx_to_domain_param_dict(bpx.parameterisation.negative_electrode, pybamm_dict, negative_electrode)
pybamm_dict = _bpx_to_domain_param_dict(bpx.p... |
class AverageMeter():
def __init__(self, ema=False):
self.ema = ema
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
if isinstance(val, torch.Tensor):
val = val.item()
s... |
class TestModisL2():
def test_available_reader(self):
assert ('modis_l2' in available_readers())
def test_scene_available_datasets(self, modis_l2_nasa_mod35_file):
scene = Scene(reader='modis_l2', filenames=modis_l2_nasa_mod35_file)
available_datasets = scene.all_dataset_names()
... |
class OnnxExportTestCaseV2(TestCase):
def _onnx_export(self, test_name, name, model_name, feature, onnx_config_class_constructor):
from transformers.onnx import export
model_class = FeaturesManager.get_model_class_for_feature(feature)
config = AutoConfig.from_pretrained(model_name)
m... |
def test_guard_against_duplicate_packets():
zc = Zeroconf(interfaces=['127.0.0.1'])
zc.registry.async_add(ServiceInfo('_ 'Test._ server='Test._ port=4))
zc.question_history = QuestionHistoryWithoutSuppression()
class SubListener(_listener.AsyncListener):
def handle_query_or_defer(self, msg: DNSI... |
def Transformer(input_vocab_size: int, target_vocab_size: int, encoder_input_size: int=None, decoder_input_size: int=None, num_layers: int=6, d_model: int=512, num_heads: int=8, dff: int=2048, dropout_rate: float=0.1) -> tf.keras.Model:
inputs = [tf.keras.layers.Input(shape=(encoder_input_size,), dtype=tf.int64), t... |
class Effect6316(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
for attrName in ('buffDuration', 'warfareBuff1Value', 'warfareBuff2Value', 'warfareBuff3Value', 'warfareBuff4Value'):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('S... |
class DST_Optimizer(BaseOptimizer):
def __init__(self, args=None):
super().__init__(args)
self.model_name = 'dst'
def _optimize(self, oracle, config):
self.oracle.assign_evaluator(oracle)
gnn = GCN(nfeat=50, nhid=100, n_out=1, num_layer=2)
gnn = gnn.to(device)
gnn... |
class TRPaned():
Kind = None
def test_ctr(self):
self.Kind().destroy()
def test_pre_alloc(self):
p = self.Kind()
p.set_relative(0.25)
self.assertEqual(p.get_relative(), 0.25)
self.assertRaises(ValueError, p.set_relative, 2.0)
self.assertRaises(ValueError, p.se... |
_test
def test_avgpooling3d_legacy_interface():
old_layer = keras.layers.AveragePooling3D(pool_size=(2, 2, 2), border_mode='valid', name='avgpooling3d')
new_layer = keras.layers.AvgPool3D(pool_size=(2, 2, 2), padding='valid', name='avgpooling3d')
assert (json.dumps(old_layer.get_config()) == json.dumps(new_... |
def test_venv_creator_from_mapping_maximal_no_pip():
d = {'path': '/arb', 'system_site_packages': True, 'clear': False, 'symlinks': True, 'upgrade': True, 'with_pip': False, 'prompt': 'arbprompt', 'upgrade_pip': False, 'quiet': True}
context = get_simple_context()
with patch('pypyr.venv.EnvBuilderWithExtraD... |
class TestEgg(TestZip):
def setUp(self):
super().setUp()
self._fixture_on_path('example-21.12-py3.6.egg')
def test_files(self):
for file in files('example'):
path = str(file.dist.locate_file(file))
assert ('.egg/' in path), path
def test_normalized_name(self):... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.