code stringlengths 281 23.7M |
|---|
def setup_args():
args = argparse.Namespace()
args.global_sync_iter = 20
args.block_momentum = 0.875
args.block_lr = 0.5
args.input_size = 5
args.nb_classes = 2
args.batch_size = 1
args.lr = [0.001]
args.momentum = 0
args.weight_decay = 0
args.warmup_iterations = 0
args.u... |
def exception_net_file():
with tempfile.NamedTemporaryFile(mode='w+', delete=False) as f:
f.write("name: 'pythonnet' force_backward: true\n input: 'data' input_shape { dim: 10 dim: 9 dim: 8 }\n layer { type: 'Python' name: 'layer' bottom: 'data' top: 'top'\n python_param { module: 'te... |
def test_importorskip_module_level(pytester: Pytester) -> None:
pytester.makepyfile('\n import pytest\n foobarbaz = pytest.importorskip("foobarbaz")\n\n def test_foo():\n pass\n ')
result = pytester.runpytest()
result.stdout.fnmatch_lines(['*collected 0 items / 1 skipped*'... |
def output_node2vec(g, tmp_node_vec_fname, node_vec_fname, options):
with open(tmp_node_vec_fname, 'r') as f:
with open(node_vec_fname, 'w') as fo:
fo.write(f'''size={options.dim}, alpha={options.alpha}, windows={options.window}, negative={options.neg}, walk_num={options.walk_num}, walk_len={opt... |
class struct_s_pxe_cpb_fill_header_fragmented(ctypes.Structure):
_pack_ = True
_fields_ = [('SrcAddr', (ctypes.c_ubyte * 32)), ('DestAddr', (ctypes.c_ubyte * 32)), ('PacketLen', ctypes.c_uint32), ('Protocol', ctypes.c_uint16), ('MediaHeaderLen', ctypes.c_uint16), ('FragCnt', ctypes.c_uint16), ('reserved', ctype... |
class kNNClassificationEvaluatorPytorch(Evaluator):
def __init__(self, sentences_train, y_train, sentences_test, y_test, k=1, batch_size=32, limit=None, **kwargs):
super().__init__(**kwargs)
if (limit is not None):
sentences_train = sentences_train[:limit]
y_train = y_train[:... |
class FixNumliterals(fixer_base.BaseFix):
_accept_type = token.NUMBER
def match(self, node):
return (node.value.startswith('0') or (node.value[(- 1)] in 'Ll'))
def transform(self, node, results):
val = node.value
if (val[(- 1)] in 'Ll'):
val = val[:(- 1)]
elif (va... |
def dense_stack_tds(td_list: (Sequence[TensorDictBase] | LazyStackedTensorDict), dim: int=None) -> T:
if isinstance(td_list, LazyStackedTensorDict):
dim = td_list.stack_dim
td_list = td_list.tensordicts
elif (dim is None):
raise ValueError('If a list of tensordicts is provided, stack_dim... |
class FeatureExtractorUtilTester(unittest.TestCase):
def test_cached_files_are_used_when_internet_is_down(self):
response_mock = mock.Mock()
response_mock.status_code = 500
response_mock.headers = []
response_mock.raise_for_status.side_effect = HTTPError
_ = Wav2Vec2FeatureEx... |
class ShoppingUI(UserInterface):
def assemble(self):
shopping_cart = ShoppingCart.for_current_session()
home = self.define_view('/', title='Paypal Example')
home.set_slot('main', PurchaseForm.factory(shopping_cart))
order_summary_page = self.define_view('/order_summary', title='Order... |
def change_size_unit(total):
if (total < (1 << 10)):
return '{:.2f} B'.format(total)
elif (total < (1 << 20)):
return '{:.2f} KB'.format((total / (1 << 10)))
elif (total < (1 << 30)):
return '{:.2f} MB'.format((total / (1 << 20)))
else:
return '{:.2f} GB'.format((total / ... |
class TestModuleFinder():
def find(self, path, *args, **kwargs):
return set(ModuleFinder.find(str(path), *args, **kwargs))
EXAMPLES = {'simple_folder': (['file.py', 'other.py'], {}, ['file', 'other']), 'exclude': (['file.py', 'other.py'], {'exclude': ['f*']}, ['other']), 'include': (['file.py', 'fole.py... |
()
def pickle_files_wo_callback_data(user_data, chat_data, bot_data, conversations):
data = {'user_data': user_data, 'chat_data': chat_data, 'bot_data': bot_data, 'conversations': conversations}
with Path('pickletest_user_data').open('wb') as f:
pickle.dump(user_data, f)
with Path('pickletest_chat_d... |
class TestDevNet(unittest.TestCase):
def setUp(self):
self.n_train = 200
self.n_test = 100
self.contamination = 0.1
self.roc_floor = 0.8
(self.X_train, self.X_test, self.y_train, self.y_test) = generate_data(n_train=self.n_train, n_test=self.n_test, n_features=10, contaminati... |
def lattice_to_kws_index(clat, utterance_id, max_silence_frames=50, max_states=(- 1), allow_partial=True, destructive=False):
if destructive:
index = _kws_functions._lattice_to_kws_index_destructive(clat, utterance_id, max_silence_frames, max_states, allow_partial)
else:
index = _kws_functions._... |
def decompress_and_unpickle(key: str, serialized: bytes, flags: int) -> Any:
if (flags & PickleFlags.ZLIB):
serialized = zlib.decompress(serialized)
flags ^= PickleFlags.ZLIB
if (flags == 0):
return serialized
if (flags in (PickleFlags.INTEGER, PickleFlags.LONG)):
return int(... |
def test_SagaException():
try:
raise se.SagaException('SagaException')
except se.SagaException as e:
assert ('SagaException' in e.get_message()), str(e)
assert ('SagaException' in str(e)), str(e)
try:
raise se.SagaException('SagaException')
except se.NotImplemented:
... |
def run_coro_with_timeout(aw: Coroutine, loop: asyncio.AbstractEventLoop, timeout: float) -> Any:
try:
return asyncio.run_coroutine_threadsafe(aw, loop).result((millis_to_seconds(timeout) + _LOADED_SYSTEM_TIMEOUT))
except concurrent.futures.TimeoutError as ex:
raise EventLoopBlocked from ex |
class Conv3d(nn.Module):
def __init__(self, in_channels: int, out_channels: int, kernel_size: Union[(int, Tuple[(int, ...)])]=3, stride: Union[(int, Tuple[(int, ...)])]=1, dilation: int=1, bias: bool=False, transposed: bool=False) -> None:
super().__init__()
self.in_channels = in_channels
se... |
class _PyModule(PyDefinedObject, AbstractModule):
def __init__(self, pycore, ast_node, resource):
self.resource = resource
self.concluded_data = []
AbstractModule.__init__(self)
PyDefinedObject.__init__(self, pycore, ast_node, None)
def absolute_name(self) -> str:
return ... |
def convert_observation_field_params(params: RequestParams) -> RequestParams:
if ('observation_fields' in params):
params['observation_field_values_attributes'] = params.pop('observation_fields')
obs_fields = params.get('observation_field_values_attributes')
if isinstance(obs_fields, dict):
... |
def test_preprocess_input():
x = np.random.uniform(0, 255, (2, 10, 10, 3))
assert (utils.preprocess_input(x).shape == x.shape)
out1 = utils.preprocess_input(x, 'channels_last')
out2 = utils.preprocess_input(np.transpose(x, (0, 3, 1, 2)), 'channels_first')
assert_allclose(out1, out2.transpose(0, 2, 3... |
class TimeDiversityBinning():
param_names = ['binning']
params = [('HeadTailBreaks', 'Quantiles', 'EqualInterval')]
def setup(self, *args):
test_file_path = mm.datasets.get_path('bubenec')
self.df_buildings = gpd.read_file(test_file_path, layer='buildings')
self.df_streets = gpd.read... |
def create_metadata(title, author=None):
if (author is None):
author = 'PyMedPhys Contributors'
metadata = {'metadata': {'title': title, 'upload_type': 'dataset', 'creators': [{'name': author}], 'description': '<p>This is an automated upload from the PyMedPhys library.</p>', 'license': 'Apache-2.0', 'ac... |
def average_distance_auc(reference, query, min_threshold=0, max_threshold=0.01, plot=False):
kdtree = sklearn.neighbors.KDTree(reference)
(distances, _) = kdtree.query(query, k=1)
x = np.linspace(min_threshold, max_threshold)
y = [((distances <= xi).sum() / distances.size) for xi in x]
auc = (sklear... |
def test_unix_temporal_crs__coordinate_system():
crs = CRS('TIMECRS[Unix time,TDATUM[Unix epoch,TIMEORIGIN[1970-01-01T00:00:00Z]],CS[TemporalCount,1],AXIS[Time,future,TIMEUNIT[second]]]')
assert (crs.cs_to_cf() == [{'standard_name': 'time', 'long_name': 'time', 'calendar': 'proleptic_gregorian', 'units': 'secon... |
def test_simulation_9():
with Simulation(MODEL_WEIR_SETTING_PATH) as sim:
J1 = Nodes(sim)['J1']
def init_function():
J1.initial_depth = 15
sim.initial_conditions(init_function)
for (ind, step) in enumerate(sim):
if (ind == 0):
assert (J1.depth ... |
class EvoNorm2dB0(nn.Module):
def __init__(self, num_features, apply_act=True, momentum=0.1, eps=0.001, **_):
super().__init__()
self.apply_act = apply_act
self.momentum = momentum
self.eps = eps
self.weight = nn.Parameter(torch.ones(num_features))
self.bias = nn.Para... |
def open_file_chooser_dialog(title='Choose a file', multiple=False):
dialog = Gtk.FileChooserDialog(title, None, Gtk.FileChooserAction.OPEN, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN, Gtk.ResponseType.OK))
dialog.set_default_response(Gtk.ResponseType.OK)
dialog.set_select_multiple(multiple)... |
def process_data(points_name, dataset='test'):
locs = []
feats = []
point_ids = []
for (idx, i) in enumerate(range(val_reps)):
scan.open_scan(points_name)
label_name = points_name.replace('bin', 'label').replace('velodyne', 'labels')
if (dataset == 'val'):
scan.open_l... |
def register_argparse_argument_parameter(param_name: str, param_type: Optional[Type[Any]]) -> None:
attr_name = f'{_CUSTOM_ATTRIB_PFX}{param_name}'
if ((param_name in CUSTOM_ACTION_ATTRIBS) or hasattr(argparse.Action, attr_name)):
raise KeyError(f'Custom parameter {param_name} already exists')
if (n... |
def test_correctness_voronoi():
(head, tail, weight) = _voronoi(cau_coords)
known_head = np.array([0, 0, 0, 1, 1, 2, 2, 2, 2, 3, 4, 4])
known_tail = np.array([1, 2, 4, 0, 2, 0, 1, 3, 4, 2, 0, 2])
np.testing.assert_array_equal(known_head, head)
np.testing.assert_array_equal(known_tail, tail)
np.t... |
def test_FullMultiplicativeForm_kracka2010ranking():
dm = skcriteria.mkdm(matrix=[[33.95, 23.78, 11.45, 39.97, 29.44, 167.1, 3.852], [38.9, 4.17, 6.32, 0.01, 4.29, 132.52, 25.184], [37.59, 9.36, 8.23, 4.35, 10.22, 136.71, 10.845], [30.44, 37.59, 13.91, 74.08, 45.1, 198.34, 2.186], [36.21, 14.79, 9.17, 17.77, 17.06,... |
def pg_config_dictionary(*pg_config_path, encoding='utf-8', timeout=8):
default_output = get_command_output(pg_config_path, encoding=encoding, timeout=timeout)
if (default_output is not None):
d = {}
for x in default_output.splitlines():
if ((not x) or x.isspace() or (x.find('=') == ... |
(scope='module')
def grpc_port(greeter_pb2, greeter_pb2_grpc):
class Servicer(greeter_pb2_grpc.GreeterServicer):
def SayHello(self, message, context):
metadata = []
for (key, value) in context.invocation_metadata():
metadata.append((key, value))
metadata =... |
def test_atmost():
vp = IDPool()
n = 20
b = 50
assert (n <= b)
lits = [vp.id(v) for v in range(1, (n + 1))]
top = vp.top
G = CardEnc.atmost(lits, b, vpool=vp)
assert (len(G.clauses) == 0)
try:
assert (vp.top >= top)
except AssertionError as e:
print(f'''
vp.top = ... |
class SegmentationNet10a(VGGNet):
cfg = [(64, 1), (128, 1), ('M', None), (256, 1), (256, 1), (512, 2), (512, 2)]
def __init__(self, config):
super(SegmentationNet10a, self).__init__()
self.batchnorm_track = config.batchnorm_track
self.trunk = SegmentationNet10aTrunk(config, cfg=Segmentat... |
def generate_html_response():
html_content = '\n <!doctype html>\n <html>\n <head>\n <title>PyScript Service Worker</title>\n </head>\n <body>\n <h1>PyScript from a service worker </h1>\n <h2>FastAPI demo</h2>\n <ul>\n <li>Test so... |
class FC3_LogVolData(BaseData):
removedKeywords = BaseData.removedKeywords
removedAttrs = BaseData.removedAttrs
def __init__(self, *args, **kwargs):
BaseData.__init__(self, *args, **kwargs)
self.fstype = kwargs.get('fstype', '')
self.grow = kwargs.get('grow', False)
self.maxS... |
def add_dataset_args(parser, train=False, gen=False):
group = parser.add_argument_group('Dataset and data loading')
group.add_argument('--num-workers', default=1, type=int, metavar='N', help='how many subprocesses to use for data loading')
group.add_argument('--skip-invalid-size-inputs-valid-test', action='... |
def _get_wheel_metadata_from_wheel(whl_basename, metadata_directory, config_settings):
from zipfile import ZipFile
with open(os.path.join(metadata_directory, WHEEL_BUILT_MARKER), 'wb'):
pass
whl_file = os.path.join(metadata_directory, whl_basename)
with ZipFile(whl_file) as zipf:
dist_in... |
class CommandTester():
def __init__(self, command: Command) -> None:
self._command = command
self._io = BufferedIO()
self._inputs: list[str] = []
self._status_code: (int | None) = None
def command(self) -> Command:
return self._command
def io(self) -> BufferedIO:
... |
_fixtures(WebFixture)
def test_check_missing_form(web_fixture):
fixture = web_fixture
class ModelObject():
fields = ExposedNames()
fields.name = (lambda i: Field())
class MyPanel(Div):
def __init__(self, view):
super().__init__(view)
model_object = ModelObject... |
class Namer():
def __init__(self, debug_trail: DebugTrail, path_to_suffix: Mapping[(CrownPath, str)], path: CrownPath):
self.debug_trail = debug_trail
self.path_to_suffix = path_to_suffix
self._path = path
def _with_path_suffix(self, basis: str) -> str:
if (not self._path):
... |
class PyzoLogger(QtWidgets.QWidget):
def __init__(self, parent):
QtWidgets.QWidget.__init__(self, parent)
self._logger_shell = PyzoLoggerShell(self)
self.layout = QtWidgets.QVBoxLayout(self)
self.layout.addWidget(self._logger_shell, 1)
self.layout.setSpacing(0)
margin... |
def is_valid_bn_fold(conv_linear: NodeProto, model: ModelProto, fold_backward: bool) -> bool:
valid = True
if (conv_linear.op_type in LinearType):
w = retrieve_constant_input(conv_linear, model, WEIGHT_INDEX)[0]
if (w is None):
valid = False
if (not fold_backward):
if (co... |
class App(ttk.Frame):
def __init__(self, parent):
ttk.Frame.__init__(self, parent)
for index in range(4):
self.columnconfigure(index=index, weight=1)
self.rowconfigure(index=(index + 1), weight=1)
self.result = tk.StringVar(value='')
self.setup_widgets()
d... |
class Effect2054(BaseEffect):
type = 'passive'
def handler(fit, skill, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: (mod.item.group.name == 'Shield Resistance Amplifier')), 'explosiveDamageResistanceBonus', (skill.getModifiedItemAttr('hardeningBonus') * skill.level), *... |
def validate(model, data_loader):
print('validating ... ', flush=True, end='')
val_loss_meter = pyutils.AverageMeter('loss1', 'loss2')
model.eval()
with torch.no_grad():
for pack in data_loader:
img = pack['img']
label = pack['label'].cuda(non_blocking=True)
x... |
def pytest_generate_tests(metafunc):
if getattr(metafunc, 'function', False):
if getattr(metafunc.function, 'pytestmark', False):
marks = metafunc.function.pytestmark
order_marks = [mark for mark in marks if (mark.name == 'order')]
if (len(order_marks) > 1):
... |
def test_ScanArgs_remove_outer_output():
hmm_model_env = create_test_hmm()
scan_args = hmm_model_env['scan_args']
hmm_model_env['scan_op']
Y_t = hmm_model_env['Y_t']
Y_rv = hmm_model_env['Y_rv']
hmm_model_env['sigmas_in']
hmm_model_env['sigmas_t']
Gamma_rv = hmm_model_env['Gamma_rv']
... |
_lr_scheduler('cosine')
class CosineSchedule(FairseqLRScheduler):
def __init__(self, args, optimizer):
super().__init__(args, optimizer)
if (len(args.lr) > 1):
raise ValueError('Cannot use a fixed learning rate schedule with cosine. Consider --lr-scheduler=fixed instead.')
warmup... |
class QuestionAnsweringArgumentHandler(ArgumentHandler):
def normalize(self, item):
if isinstance(item, SquadExample):
return item
elif isinstance(item, dict):
for k in ['question', 'context']:
if (k not in item):
raise KeyError('You need t... |
class GammaIncInv(BinaryScalarOp):
nfunc_spec = ('scipy.special.gammaincinv', 2, 1)
def st_impl(k, x):
return scipy.special.gammaincinv(k, x)
def impl(self, k, x):
return GammaIncInv.st_impl(k, x)
def grad(self, inputs, grads):
(k, x) = inputs
(gz,) = grads
return... |
def set_deployment_placement_options(deployment_config: dict, scaling_config: ScalingConfig):
scaling_config = scaling_config.as_air_scaling_config()
deployment_config.setdefault('ray_actor_options', {})
replica_actor_resources = {'CPU': deployment_config['ray_actor_options'].get('num_cpus', 1), 'GPU': depl... |
.parametrize('output_is_path', [True, False])
.filterwarnings('ignore::sgkit.io.vcfzarr_reader.DimensionNameForFixedFormatFieldWarning')
def test_zarr_to_vcf(shared_datadir, tmp_path, output_is_path):
path = path_for_test(shared_datadir, 'sample.vcf.gz')
intermediate = tmp_path.joinpath('intermediate.vcf.zarr')... |
_fast
def test_long_destroyers_loop():
(x, y, z) = inputs()
e = dot(dot(add_in_place(x, y), add_in_place(y, z)), add(z, x))
g = create_fgraph([x, y, z], [e])
assert g.consistent()
TopoSubstitutionNodeRewriter(add, add_in_place).rewrite(g)
assert g.consistent()
assert (str(g) != 'FunctionGrap... |
class PresetEchoesHints(PresetTab, Ui_PresetEchoesHints):
def __init__(self, editor: PresetEditor, game_description: GameDescription, window_manager: WindowManager):
super().__init__(editor, game_description, window_manager)
self.setupUi(self)
self.hint_layout.setAlignment(QtCore.Qt.Alignmen... |
def get_example_xml(song_path, rating, lastplayed):
song_uri = fsn2uri(song_path)
mount_uri = fsn2uri(find_mount_point(song_path))
return ('<?xml version="1.0" standalone="yes"?>\n<rhythmdb version="1.9">\n <entry type="song">\n <title>Music</title>\n <genre>Unknown</genre>\n <track-number>7</trac... |
def main():
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
if ((len(sys.argv) == 2) and sys.argv[1].endswith('.json')):
(model_args, data_args, training_args) = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
else:
(model_args, data_args,... |
class PHP(CNF, object):
def __init__(self, nof_holes, kval=1, topv=0, verb=False):
super(PHP, self).__init__()
vpool = IDPool(start_from=(topv + 1))
var = (lambda i, j: vpool.id('v_{0}_{1}'.format(i, j)))
for i in range(1, ((kval * nof_holes) + 2)):
self.append([var(i, j)... |
def exportFighters(fighters):
FIGHTER_ORDER = ('Light Fighter', 'Heavy Fighter', 'Support Fighter')
def fighterSorter(fighter):
groupName = Market.getInstance().getGroupByItem(fighter.item).name
return (FIGHTER_ORDER.index(groupName), fighter.item.typeName)
fighterLines = []
for fighter ... |
def test_ff_cannot_write_to_struct_field():
class C():
bar: Bits16
class B():
foo: Bits32
bar: ([([C] * 5)] * 5)
class A(ComponentLevel3):
def construct(s):
s.wire = Wire(B)
_ff
def ffs():
s.wire.bar <<= 1
try:
_... |
class VOC(BaseDataLoader):
def __init__(self, kwargs):
self.MEAN = [0.485, 0.456, 0.406]
self.STD = [0.229, 0.224, 0.225]
self.batch_size = kwargs.pop('batch_size')
kwargs['mean'] = self.MEAN
kwargs['std'] = self.STD
kwargs['ignore_index'] = 255
try:
... |
def main_fn(path_config_file, extra_args={}):
(env_name, env_extra_args, output_file, seed_number, lowU_train_val, highU_train_val, lowU_test_val, highU_test_val, max_episode_length, num_data_train, num_data_test, save_video, disable_substep, control_policy, n_rollout, num_data_colocation, extra_noise_colocation) =... |
def test_bits_to_int():
rs = np.random.RandomState(52)
bitstrings = rs.choice([0, 1], size=(100, 23))
nums = bits_to_ints(bitstrings)
assert (nums.shape == (100,))
for (num, bs) in zip(nums, bitstrings):
ref_num = cirq.big_endian_bits_to_int(bs.tolist())
assert (num == ref_num)
(... |
def init():
cache_path = standarddir.cache()
data_path = standarddir.data()
QWebSettings.setIconDatabasePath(standarddir.cache())
QWebSettings.setOfflineWebApplicationCachePath(os.path.join(cache_path, 'application-cache'))
QWebSettings.globalSettings().setLocalStoragePath(os.path.join(data_path, 'l... |
def recursively_load_weights(fairseq_model, hf_model, is_headless):
unused_weights = []
fairseq_dict = fairseq_model.state_dict()
feature_extractor = hf_model.wav2vec2.feature_extractor
for (name, value) in fairseq_dict.items():
is_used = False
if ('conv_layers' in name):
loa... |
def read_lmv_tofits(fileobj):
from astropy.io import fits
(data, header) = read_lmv(fileobj)
data = data.squeeze()
bad_kws = ['NAXIS4', 'CRVAL4', 'CRPIX4', 'CDELT4', 'CROTA4', 'CUNIT4', 'CTYPE4']
cards = [(fits.header.Card(keyword=k, value=v[0], comment=v[1]) if isinstance(v, tuple) else fits.header... |
class TestRequestsBackend():
.parametrize('test_data,expected', [(False, '0'), (True, '1'), ('12', '12'), (12, '12'), (12.0, '12.0'), (complex((- 2), 7), '(-2+7j)')])
def test_prepare_send_data_non_strings(self, test_data, expected) -> None:
assert isinstance(expected, str)
files = {'file': ('fi... |
def test_cmdstep_cmd_is_dict_default_save_true():
obj = CmdStep('blahname', Context({'cmd': {'run': 'blah', 'save': True}}), is_shell=False)
assert (not obj.is_shell)
assert (obj.logger.name == 'blahname')
assert (obj.context == Context({'cmd': {'run': 'blah', 'save': True}}))
assert (obj.commands =... |
class Effect11943(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredChargeBoost((lambda mod: mod.charge.requiresSkill('Missile Launcher Operation')), 'thermalDamage', ship.getModifiedItemAttr('shipBonusGD1'), skill='Gallente Destroyer', **kwarg... |
class BertDataLoader(DataLoader):
def __iter__(self):
while True:
while self._empty():
self._fill_buf()
if ((self.start + self.batch_size) >= self.end):
instances = self.buffer[self.start:]
else:
instances = self.buffer[self... |
class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000, zero_init_residual=False, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None):
super(ResNet, self).__init__()
if (norm_layer is None):
norm_layer = nn.BatchNorm2d
self._norm... |
def convert_tf_checkpoint_to_pytorch(tf_checkpoint_path, pytorch_dump_path):
config = CanineConfig()
model = CanineModel(config)
model.eval()
print(f'Building PyTorch model from configuration: {config}')
load_tf_weights_in_canine(model, config, tf_checkpoint_path)
print(f'Save PyTorch model to {... |
.parametrize('matrix_server_count', [2])
.parametrize('number_of_transports', [2])
def test_matrix_message_sync(matrix_transports):
(transport0, transport1) = matrix_transports
transport0_messages = set()
transport1_messages = set()
transport0_message_handler = MessageHandler(transport0_messages)
tr... |
(id='vmware-node-reboot', name='Reboot VMware VM', description='Reboot the node(s) by starting the VMware VM on which the node is configured', outputs={'success': NodeScenarioSuccessOutput, 'error': NodeScenarioErrorOutput})
def node_reboot(cfg: NodeScenarioConfig) -> typing.Tuple[(str, typing.Union[(NodeScenarioSucces... |
def hinge_d_loss_with_exemplar_weights(logits_real, logits_fake, weights):
assert (weights.shape[0] == logits_real.shape[0] == logits_fake.shape[0])
loss_real = torch.mean(F.relu((1.0 - logits_real)), dim=[1, 2, 3])
loss_fake = torch.mean(F.relu((1.0 + logits_fake)), dim=[1, 2, 3])
loss_real = ((weights... |
def download_and_unzip_post(config, rootpath, hot_run=True, disable_progress=False):
resource = config['category']
destination = os.path.relpath(config['destination'])
postdata = config['urls']['post']
url = postdata.pop('url')
file_path = os.path.join(destination, os.path.basename(url))
if hot_... |
class Object(object):
def __init__(self, tagname, inamevals):
self._tagname = tagname
self._data = []
for kv in inamevals:
self._data.append(list(kv))
def inamevals_to_save(self):
for (k, v) in self._data:
(yield (k, to_xstr(v)))
def inamevals(self):
... |
def squad_convert_example_to_features(example, max_seq_length, doc_stride, max_query_length, is_training):
features = []
if (is_training and (not example.is_impossible)):
start_position = example.start_position
end_position = example.end_position
actual_text = ' '.join(example.doc_tokens... |
def write_metadata(metadata, out_dir):
with open(os.path.join(out_dir, 'train.txt'), 'w', encoding='utf-8') as f:
for m in metadata:
f.write(('|'.join([str(x) for x in m]) + '\n'))
frames = sum([m[2] for m in metadata])
hours = ((frames * hparams.frame_shift_ms) / (3600 * 1000))
prin... |
class PlaylistModel(TrackCurrentModel):
order: Order
sourced = False
def __init__(self, order_cls: type[Order]=OrderInOrder):
super().__init__(object)
self.order = order_cls()
def next(self):
iter_ = self.current_iter
print_d(('Using %s.next_explicit() to get next song' %... |
def test_tags_disabled_namespace(v2_protocol, basic_images, liveserver_session, app_reloader, liveserver, registry_server_executor):
credentials = ('devtable', 'password')
registry_server_executor.on(liveserver).disable_namespace('buynlarge')
v2_protocol.tags(liveserver_session, credentials=credentials, nam... |
class AsmCmdGotoLinked(AsmCmdBase):
_id = 20
_menuText = QT_TRANSLATE_NOOP('asm3', 'Select linked object')
_tooltip = QT_TRANSLATE_NOOP('asm3', 'Select the linked object')
_accel = 'A, G'
_toolbarName = ''
def getIconName(cls):
return 'LinkSelect'
def Activated(cls):
from .as... |
def trans_mat_all_days(animal_day_transmats, animal_id, dpi=200, figsize=(8, 4)):
day_transmats = animal_day_transmats[animal_id]
ncol = len(day_transmats)
(fig, ax) = plt.subplots(1, ncol, dpi=dpi, figsize=figsize)
ax = ax.ravel()
for (ind, (day, trans_mat_tup)) in enumerate(day_transmats.items()):... |
def find_span(sentence, search_text, start=0):
search_text = search_text.lower()
for tok in sentence[start:]:
remainder = sentence[tok.i:].text.lower()
if remainder.startswith(search_text):
len_to_consume = len(search_text)
start_idx = tok.idx
for next_tok in ... |
def main(args):
cfg = setup(args)
if args.eval_only:
model = Trainer.build_model(cfg)
DetectionCheckpointer(model, save_dir=cfg.OUTPUT_DIR).resume_or_load(cfg.MODEL.WEIGHTS, resume=args.resume)
res = Trainer.test(cfg, model)
return res
trainer = Trainer(cfg)
trainer.resum... |
class ProfilerTracer(torch.fx.Tracer):
def trace(self, root, concrete_args=None):
orig_record_function_enter = torch.autograd.profiler.record_function.__enter__
orig_record_function_exit = torch.autograd.profiler.record_function.__exit__
def fake_profiler_enter(_self):
nonlocal s... |
_optimizer('rmsprop_tf')
class RMSPropTF(ClassyOptimizer):
def __init__(self, lr: float=0.1, momentum: float=0, weight_decay: float=0, alpha: float=0.99, eps: float=1e-08, centered: bool=False) -> None:
super().__init__()
self._lr = lr
self._momentum = momentum
self._weight_decay = w... |
def test_raises_if_no_generic_params_supplied(converter: Union[(Converter, BaseConverter)]):
data = TClass(1, 'a')
with pytest.raises(StructureHandlerNotFoundError, match='Unsupported type: ~T. Register a structure hook for it.|Missing type for generic argument T, specify it when structuring.') as exc:
... |
def load_runtime_vs_ns(fname, xlabel='Sample size $n$', show_legend=True, xscale='linear', yscale='linear'):
func_xvalues = (lambda agg_results: agg_results['ns'])
ex = 1
def func_title(agg_results):
(repeats, _, n_methods) = agg_results['job_results'].shape
alpha = agg_results['alpha']
... |
(bp, '/testTree', methods=['GET'])
def test_tree():
res = ResMsg()
data = [{'id': 1, 'father_id': None, 'name': '01'}, {'id': 2, 'father_id': 1, 'name': '0101'}, {'id': 3, 'father_id': 1, 'name': '0102'}, {'id': 4, 'father_id': 1, 'name': '0103'}, {'id': 5, 'father_id': 2, 'name': '010101'}, {'id': 6, 'father_i... |
def _test():
import torch
pretrained = False
models = [condensenet74_c4_g4, condensenet74_c8_g8]
for model in models:
net = model(pretrained=pretrained)
net.eval()
weight_count = _calc_width(net)
print('m={}, {}'.format(model.__name__, weight_count))
assert ((mode... |
class BTOOLS_OT_add_balcony(bpy.types.Operator):
bl_idname = 'btools.add_balcony'
bl_label = 'Add Balcony'
bl_options = {'REGISTER', 'UNDO', 'PRESET'}
props: bpy.props.PointerProperty(type=BalconyProperty)
def poll(cls, context):
return ((context.object is not None) and (context.mode == 'EDI... |
def resamp(x, type, shift, extmod):
if (shift is None):
shift = 1
if (extmod is None):
extmod = 'per'
if ((type == 0) or (type == 1)):
y = resampc(x, type, shift, extmod)
elif ((type == 2) or (type == 3)):
y = resampc(x.T, (type - 2), shift, extmod).T
else:
pr... |
def test_envunset_doesnt_exist():
try:
del os.environ['ARB_DELETE_SNARK']
except KeyError:
pass
context = Context({'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'env': {'unset': ['ARB_DELETE_SNARK']}})
assert pypyr.steps.env.env_unset(context)
assert ('ARB_DELETE_SNARK' not i... |
class MultiCorpusSampledDataset(FairseqDataset):
def __init__(self, datasets: Dict[(str, FairseqDataset)], sampling_func: Callable[([List], int)]=None):
super().__init__()
assert isinstance(datasets, OrderedDict)
self.datasets = datasets
if (sampling_func is None):
sampli... |
def main():
args = parse_args()
cfg_path = args.config
cfg = Config.fromfile(cfg_path)
(_, fullname) = os.path.split(cfg_path)
(fname, ext) = os.path.splitext(fullname)
root_workdir = cfg.pop('root_workdir')
workdir = os.path.join(root_workdir, fname)
os.makedirs(workdir, exist_ok=True)
... |
def test_event_filter_for_payments():
secret = factories.make_secret()
identifier = PaymentID(1)
target = TargetAddress(factories.make_address())
event1 = EventPaymentSentSuccess(token_network_registry_address=UNIT_TOKEN_NETWORK_REGISTRY_ADDRESS, token_network_address=UNIT_TOKEN_NETWORK_ADDRESS, identif... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.