code stringlengths 281 23.7M |
|---|
class TestIssubclassBrain():
def test_type_type(self) -> None:
assert (_get_result('issubclass(type, type)') == 'True')
def test_object_type(self) -> None:
assert (_get_result('issubclass(object, type)') == 'False')
def test_type_object(self) -> None:
assert (_get_result('issubclass(... |
class Effect8021(BaseEffect):
runTime = 'early'
type = 'passive'
def handler(fit, implant, context, projectionRange, **kwargs):
for attr in ('hydraDroneTrackingBonus', 'hydraDroneRangeBonus', 'hydraMissileFlightTimeBonus', 'hydraMissileExplosionVelocityBonus'):
fit.appliedImplants.filter... |
def _eval_update(i, epochs, min_epochs, model, optimizer, batch_dim, eval_batch):
mols = samples(data, model, session, model.sample_z(n_samples), sample=True)
(m0, m1) = all_scores(mols, data, norm=True)
m0 = {k: np.array(v)[np.nonzero(v)].mean() for (k, v) in m0.items()}
m0.update(m1)
return m0 |
def test_output():
with Simulation(MODEL_WEIR_SETTING_PATH) as sim:
for step in sim:
pass
out = Output(MODEL_WEIR_SETTING_PATH.replace('inp', 'out'))
out.open()
assert (len(out.subcatchments) == 3)
assert (len(out.nodes) == 5)
assert (len(out.links) == 4)
assert (len(out.... |
class OnnxModel(object):
def __init__(self, model_path):
sess_options = onnxruntime.SessionOptions()
onnx_gpu = (onnxruntime.get_device() == 'GPU')
providers = (['CUDAExecutionProvider', 'CPUExecutionProvider'] if onnx_gpu else ['CPUExecutionProvider'])
self.sess = onnxruntime.Infere... |
class WeightedIOULocalizationLossTest(tf.test.TestCase):
def testReturnsCorrectLoss(self):
prediction_tensor = tf.constant([[[1.5, 0, 2.4, 1], [0, 0, 1, 1], [0, 0, 0.5, 0.25]]])
target_tensor = tf.constant([[[1.5, 0, 2.4, 1], [0, 0, 1, 1], [50, 50, 500.5, 100.25]]])
weights = [[1.0, 0.5, 2.0... |
class SocketTests(unittest.TestCase):
def setUp(self):
self.server = object()
self.client = Client(self.server)
self.orgsocket = socket.socket
socket.socket = MockSocket
def tearDown(self):
socket.socket = self.orgsocket
def testReopen(self):
self.client._Sock... |
def _test_cache(fn, protocol: SerializationProtocolBase=None, assert_equal_fn: Callable=None):
if (not assert_equal_fn):
assert_equal_fn = _assert_equal_default
cache_dir = '/tmp/test_dir'
if os.path.exists(cache_dir):
shutil.rmtree(cache_dir)
try:
cache = Cache()
call_co... |
def broadcast_shape_iter(arrays: Iterable[Union[(TensorVariable, tuple[(TensorVariable, ...)])]], arrays_are_shapes: bool=False, allow_runtime_broadcast: bool=False) -> tuple[(ps.ScalarVariable, ...)]:
one = pytensor.scalar.ScalarConstant(pytensor.scalar.int64, 1)
if arrays_are_shapes:
max_dims = max((l... |
_module()
class FastSCNN(nn.Module):
def __init__(self, in_channels=3, downsample_dw_channels=(32, 48), global_in_channels=64, global_block_channels=(64, 96, 128), global_block_strides=(2, 2, 1), global_out_channels=128, higher_in_channels=64, lower_in_channels=128, fusion_out_channels=128, out_indices=(0, 1, 2), c... |
class Layer(object):
def __init__(self, **kwargs):
allowed_kwargs = {'name', 'logging'}
for kwarg in kwargs.keys():
assert (kwarg in allowed_kwargs), ('Invalid keyword argument: ' + kwarg)
name = kwargs.get('name')
if (not name):
layer = self.__class__.__name_... |
class FairseqCriterion(_Loss):
def __init__(self, task):
super().__init__()
self.task = task
if hasattr(task, 'target_dictionary'):
tgt_dict = task.target_dictionary
self.padding_idx = (tgt_dict.pad() if (tgt_dict is not None) else (- 100))
def add_args(cls, parse... |
(field_fixture=FieldFixture)
class ChoiceFixture(Fixture):
def new_field(self, field_class=None):
field_class = (field_class or ChoiceField)
field = field_class(self.choices)
field.bind('choice_value', self.model_object)
return field
def new_model_object(self):
return Emp... |
class Effect4088(BaseEffect):
runTime = 'early'
type = ('projected', 'passive')
def handler(fit, module, context, projectionRange, **kwargs):
fit.modules.filteredItemMultiply((lambda mod: (mod.item.requiresSkill('Remote Armor Repair Systems') or mod.item.requiresSkill('Capital Remote Armor Repair Sy... |
class TestRBUtils(unittest.TestCase):
def test_coherence_limit(self):
t1 = 100.0
t2 = 100.0
gate2Q = 0.5
gate1Q = 0.1
twoq_coherence_err = rb.rb_utils.coherence_limit(2, [t1, t1], [t2, t2], gate2Q)
oneq_coherence_err = rb.rb_utils.coherence_limit(1, [t1], [t2], gate1Q... |
def upsample(data, weight):
n_data = len(data)
assert (weight >= 1)
integral = (list(range(n_data)) * int(math.floor(weight)))
residual = list(range(n_data))
shuffle(residual)
residual = residual[:int((n_data * (weight - int(math.floor(weight)))))]
return [deepcopy(data[idx]) for idx in (int... |
class SpecialTagDirective():
def __init__(self, value):
self.value = value
def __bool__(self):
return bool(self.value)
def __str__(self):
return str(self.value)
def __repr__(self):
return f'{self.__class__.__name__}({self.value!r})'
def __eq__(self, other):
re... |
def _format_protfuncs():
out = []
sorted_funcs = [(key, func) for (key, func) in sorted(protlib.PROT_FUNCS.items(), key=(lambda tup: tup[0]))]
for (protfunc_name, protfunc) in sorted_funcs:
out.append('- |c${name}|n - |W{docs}'.format(name=protfunc_name, docs=utils.justify(protfunc.__doc__.strip(), ... |
def preprocess_blizzard(args):
in_dir = os.path.join(args.base_dir, 'Blizzard2012')
out_dir = os.path.join(args.base_dir, args.output)
os.makedirs(out_dir, exist_ok=True)
metadata = blizzard.build_from_path(in_dir, out_dir, args.num_workers, tqdm=tqdm)
write_metadata(metadata, out_dir) |
def test_solver_should_use_the_python_constraint_from_the_environment_if_available(solver: Solver, repo: Repository, package: ProjectPackage) -> None:
set_package_python_versions(solver.provider, '~2.7 || ^3.5')
package.add_dependency(Factory.create_dependency('A', '^1.0'))
a = get_package('A', '1.0.0')
... |
_uncanonicalize
_rewriter([neg])
def local_max_to_min(fgraph, node):
if ((node.op == neg) and node.inputs[0].owner):
max = node.inputs[0]
if (max.owner and isinstance(max.owner.op, CAReduce) and (max.owner.op.scalar_op == ps.scalar_maximum)):
neg_node = max.owner.inputs[0]
if... |
class ResponseHHDUC(DataElementGroup):
atc = DataElementField(type='an', max_length=5, _d='ATC')
ac = DataElementField(type='bin', max_length=256, _d='Application Cryptogram AC')
ef_id_data = DataElementField(type='bin', max_length=256, _d='EF_ID Data')
cvr = DataElementField(type='bin', max_length=256,... |
def update_project_environment(project, name, config):
project_file = (project.root / 'pyproject.toml')
raw_config = load_toml_file(str(project_file))
env_config = raw_config.setdefault('tool', {}).setdefault('hatch', {}).setdefault('envs', {}).setdefault(name, {})
env_config.update(config)
project.... |
class Solution(object):
def levelOrderBottom(self, root):
if (root is None):
return []
stack = [[root]]
res = []
while (len(stack) > 0):
top = stack.pop()
res.insert(0, [t.val for t in top])
temp = []
for node in top:
... |
def test_frequency():
with expected_protocol(TeledyneT3AFG, [('C1:BSWV FRQ,1000', None), ('SYST:ERR?', '-0, No errors'), ('C1:BSWV?', 'C1:BSWV WVTP,SINE,FRQ,0.3HZ,PERI,3.33333S,AMP,0.08V,AMPVRMS,0.02828Vrms,MAX_OUTPUT_AMP,4.6V,OFST,-2V,HLEV,-1.96V,LLEV,-2.04V,PHSE,0')]) as inst:
inst.ch_1.frequency = 1000
... |
class UniCodeHandler(BaseHandler):
async def get(self):
Rtv = {}
try:
content = self.get_argument('content', '')
html_unescape = self.get_argument('html_unescape', 'false')
tmp = bytes(content, 'unicode_escape').decode('utf-8').replace('\\u', '\\\\u').replace('\\\... |
.parametrize('extra_headers', [[], [(b'upgrade', b'h2')]])
def test_handshake_response_broken_upgrade_header(extra_headers: Headers) -> None:
with pytest.raises(RemoteProtocolError) as excinfo:
_make_handshake(101, ([(b'connection', b'Upgrade')] + extra_headers))
assert (str(excinfo.value) == "Missing h... |
class ExchangeDataProvider(BaseDataProvider):
def __init__(self, token: str, tickers: Union[(str, List[str])], stockmarket: StockMarket=StockMarket.LONDON, start: datetime.datetime=datetime.datetime(2016, 1, 1), end: datetime.datetime=datetime.datetime(2016, 1, 30)) -> None:
super().__init__()
if (n... |
class EphemeralBuilderManager(BuildStateInterface):
PHASES_NOT_ALLOWED_TO_CANCEL_FROM = (BUILD_PHASE.PUSHING, BUILD_PHASE.COMPLETE, BUILD_PHASE.ERROR, BUILD_PHASE.INTERNAL_ERROR, BUILD_PHASE.CANCELLED)
ARCHIVABLE_BUILD_PHASES = (BUILD_PHASE.COMPLETE, BUILD_PHASE.ERROR, BUILD_PHASE.CANCELLED)
COMPLETED_PHASE... |
def extend_parser(parser: argparse.ArgumentParser) -> argparse.ArgumentParser:
subparsers = parser.add_subparsers(title='resource', dest='gitlab_resource', help='The GitLab resource to manipulate.')
subparsers.required = True
classes = set()
for cls in gitlab.v4.objects.__dict__.values():
if (no... |
class RCC_APB2RSTR(IntEnum):
TIM1RST = (1 << 0)
USART1RST = (1 << 4)
USART6RST = (1 << 5)
ADCRST = (1 << 8)
SDIORST = (1 << 11)
SPI1RST = (1 << 12)
SPI4RST = (1 << 13)
SYSCFGRST = (1 << 14)
TIM9RST = (1 << 16)
TIM10RST = (1 << 17)
TIM11RST = (1 << 18)
SPI5RST = (1 << 20) |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--vidLen', type=int, default=32, help='Number of frames in a clip')
parser.add_argument('--batchSize', type=int, default=4, help='Training batch size')
parser.add_argument('--preprocessData', help='whether need to preprocess data ( make... |
class Registry(object):
def __init__(self, name: str) -> None:
self._name: str = name
self._obj_map: Dict[(str, object)] = {}
def _do_register(self, name: str, obj: object) -> None:
assert (name not in self._obj_map), "An object named '{}' was already registered in '{}' registry!".format... |
def test_unstructure_deeply_nested_generics_list(genconverter):
class Inner():
a: int
class Outer(Generic[T]):
inner: List[T]
initial = Outer[Inner]([Inner(1)])
raw = genconverter.unstructure(initial, Outer[Inner])
assert (raw == {'inner': [{'a': 1}]})
raw = genconverter.unstruct... |
class Effect11429(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredChargeBoost((lambda mod: mod.charge.requiresSkill('Torpedoes')), 'aoeVelocity', ship.getModifiedItemAttr('shipBonusMB'), skill='Minmatar Battleship', **kwargs) |
def test(model, tensor_loader, criterion, device):
model.eval()
test_acc = 0
test_loss = 0
for data in tensor_loader:
(inputs, labels) = data
inputs = inputs.to(device)
labels.to(device)
labels = labels.type(torch.LongTensor)
outputs = model(inputs)
output... |
.parametrize('annotation, value', [('int', 42), ('bytes', b'')])
def test_enums_type_annotation_non_str_member(annotation, value) -> None:
node = builder.extract_node(f'''
from enum import Enum
class Veg(Enum):
TOMATO: {annotation} = {value}
Veg.TOMATO.value
''')
inferred_member_value = ... |
class FakeHDF4FileHandlerPolar(FakeHDF4FileHandler):
def get_test_content(self, filename, filename_info, filetype_info):
file_content = {'/attr/platform': 'SNPP', '/attr/sensor': 'VIIRS'}
file_content['longitude'] = xr.DataArray(da.from_array(DEFAULT_LON_DATA, chunks=4096), attrs={'_FillValue': np.n... |
def get_proj_incdirs(proj_dir: Path) -> list[str]:
proj_incdir = os.environ.get('PROJ_INCDIR')
incdirs = []
if (proj_incdir is None):
if (proj_dir / 'include').exists():
incdirs.append(str((proj_dir / 'include')))
else:
raise SystemExit('ERROR: PROJ_INCDIR dir not fou... |
class ST_UniversalMeasure(BaseSimpleType):
def convert_from_xml(cls, str_value: str) -> Emu:
(float_part, units_part) = (str_value[:(- 2)], str_value[(- 2):])
quantity = float(float_part)
multiplier = {'mm': 36000, 'cm': 360000, 'in': 914400, 'pt': 12700, 'pc': 152400, 'pi': 152400}[units_pa... |
class QCSchema(QCSchemaInput):
provenance: QCProvenance
return_result: (float | Sequence[float])
success: bool
properties: QCProperties
error: (QCError | None) = None
wavefunction: (QCWavefunction | None) = None
def from_dict(cls, data: dict[(str, Any)]) -> QCSchema:
error: (QCError ... |
def post_process_sql(sql_str, df, table_title=None, process_program_with_fuzzy_match_on_db=True, verbose=False):
def basic_fix(sql_str, all_headers, table_title=None):
def finditer(sub_str: str, mother_str: str):
result = []
start_index = 0
while True:
sta... |
def deepsize(obj, max_depth=4):
def _recurse(o, dct, depth):
if (0 <= max_depth < depth):
return
for ref in gc.get_referents(o):
idr = id(ref)
if (idr not in dct):
dct[idr] = (ref, sys.getsizeof(ref, default=0))
_recurse(ref, dct, (... |
def train():
for epoch_idx in range(start_epoch, args.epochs):
adjust_learning_rate(optimizer, epoch_idx, args.lr, args.lrepochs)
for (batch_idx, sample) in enumerate(TrainImgLoader):
global_step = ((len(TrainImgLoader) * epoch_idx) + batch_idx)
start_time = time.time()
... |
class MonomerWidget(gtk.DrawingArea):
def __init__(self, monomer):
gtk.DrawingArea.__init__(self)
self.connect('expose_event', self.expose)
self.set_size_request(100, (sites_y_pos + (sites_y_spacing * len(monomer.sites))))
self.monomer = monomer
def expose(self, widget, event):
... |
def node_prototype_desc(caller):
text = "\n The |cPrototype-Description|n briefly describes the prototype when it's viewed in listings.\n\n {current}\n ".format(current=_get_current_value(caller, 'prototype_desc'))
helptext = '\n Giving a brief description helps you and others to loc... |
class LegacyGRUCell(tf.nn.rnn_cell.RNNCell):
def __init__(self, num_units, reuse=None):
super(LegacyGRUCell, self).__init__(_reuse=reuse)
self._num_units = num_units
def __call__(self, inputs, state, scope=None):
with tf.variable_scope(scope, default_name='gru_cell', values=[inputs, stat... |
def list_check(head):
nb = 0
if (head.type == list_head.get_type().pointer()):
head = head.dereference()
elif (head.type != list_head.get_type()):
raise gdb.GdbError('argument must be of type (struct list_head [*])')
c = head
try:
gdb.write('Starting with: {}\n'.format(c))
... |
class Pctsp(object):
def __init__(self):
self.prize = []
self.penal = []
self.cost = []
self.prize_min = 0
def load(self, file_name, prize_min):
f = open(file_name, 'r')
for (i, line) in enumerate(f):
if (i is 5):
break
if (... |
def calculate_distance(lat1, lon1, lat2, lon2):
lat1 = math.radians(lat1)
lon1 = math.radians(lon1)
lat2 = math.radians(lat2)
lon2 = math.radians(lon2)
dlat = (lat2 - lat1)
dlon = (lon2 - lon1)
a = ((math.sin((dlat / 2)) ** 2) + ((math.cos(lat1) * math.cos(lat2)) * (math.sin((dlon / 2)) ** 2... |
def test_create_right_lane_split_first_lane():
lanedef = xodr.LaneDef(10, 20, 1, 2, 1)
lanes = xodr.create_lanes_merge_split([lanedef], 0, 30, xodr.std_roadmark_solid_solid(), 3, 3)
assert (len(lanes.lanesections) == 3)
assert (lanes.lanesections[0].s == 0)
assert (lanes.lanesections[1].s == 10)
... |
def classification_error(model: nn.Module, X_test, y_test, batch_size=1024, device=None):
device = (device or infer_model_device(model))
with torch.no_grad(), training_mode(model, is_train=False):
val_logits = process_in_chunks(model, torch.as_tensor(X_test, device=device), batch_size=batch_size)
... |
class Retriever():
def __init__(self, config):
with open(config.DB_dir, 'r') as f:
self.businessDB_dict = json.load(f)
with open(config.value_nl_dict_dir, 'r') as f:
self.value_nl_dict = json.load(f)
self.value2nl_dict = {}
for facet in self.value_nl_dict.keys... |
class DescribeBlock(pytest.Module):
def from_parent(cls, parent, obj):
name = getattr(obj, '_mangled_name', obj.__name__)
nodeid = ((parent.nodeid + '::') + name)
if PYTEST_GTE_7_0:
self = super().from_parent(parent=parent, path=parent.path, nodeid=nodeid)
elif PYTEST_GTE... |
def fancy_time_ax_format(inc):
l0_fmt_brief = ''
l2_fmt = ''
l2_trig = 0
if (inc < 1e-06):
l0_fmt = '.%n'
l0_center = False
l1_fmt = '%H:%M:%S'
l1_trig = 6
l2_fmt = '%b %d, %Y'
l2_trig = 3
elif (inc < 0.001):
l0_fmt = '.%u'
l0_center = ... |
.parametrize(('use_swaths', 'copy_dst_swath'), [(False, None), (True, None), (True, 'dask'), (True, 'swath_def')])
def test_base_resampler_does_nothing_when_src_and_dst_areas_are_equal(_geos_area, use_swaths, copy_dst_swath):
src_geom = (_geos_area if (not use_swaths) else _xarray_swath_def_from_area(_geos_area))
... |
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, in_planes, planes, stride=1):
super(Bottleneck, self).__init__()
self.conv1 = P4MConvP4M(in_planes, planes, kernel_size=1, bias=False, batch_norm=True)
self.conv2 = P4MConvP4M(planes, planes, kernel_size=3, stride=stride, padd... |
def load_txt_info(gt_file, img_info):
with open(gt_file, 'r', encoding='latin1') as f:
anno_info = []
for line in f:
line = line.strip('\n')
if ((line[0] == '[') or (line[0] == 'x')):
continue
ann = line.split(',')
bbox = ann[0:4]
... |
def read_resource_database(game: RandovaniaGame, data: dict) -> ResourceDatabase:
reader = ResourceReader()
item = read_dict(data['items'], reader.read_item_resource_info)
db = ResourceDatabase(game_enum=game, item=item, event=reader.read_resource_info_array(data['events'], ResourceType.EVENT), trick=read_d... |
def coherence_limit(nQ=2, T1_list=None, T2_list=None, gatelen=0.1):
T1 = np.array(T1_list)
if (T2_list is None):
T2 = (2 * T1)
else:
T2 = np.array(T2_list)
if ((len(T1) != nQ) or (len(T2) != nQ)):
raise ValueError('T1 and/or T2 not the right length')
coherence_limit_err = 0
... |
def convert_path(pathname):
if (os.sep == '/'):
return pathname
if (not pathname):
return pathname
if (pathname[0] == '/'):
raise ValueError(("path '%s' cannot be absolute" % pathname))
if (pathname[(- 1)] == '/'):
raise ValueError(("path '%s' cannot end with '/'" % pathn... |
class CMakeBuild(build_ext):
def run(self):
try:
subprocess.check_output(['cmake', '--version'])
except OSError:
raise RuntimeError('CMake is not available.')
super().run()
def build_extension(self, ext):
extdir = os.path.abspath(os.path.dirname(self.get_e... |
class TerminusDeleteWordCommand(sublime_plugin.TextCommand):
def run(self, edit, forward=False):
view = self.view
terminal = Terminal.from_id(view.id())
if (not terminal):
return
if ((len(view.sel()) != 1) or (not view.sel()[0].empty())):
return
if for... |
class LiterateCryptolLexer(LiterateLexer):
name = 'Literate Cryptol'
aliases = ['literate-cryptol', 'lcryptol', 'lcry']
filenames = ['*.lcry']
mimetypes = ['text/x-literate-cryptol']
url = '
version_added = '2.0'
def __init__(self, **options):
crylexer = CryptolLexer(**options)
... |
class ProjectSavingContext():
def __init__(self, asset, gameObject, project, filename=''):
if (not isinstance(asset, Asset)):
raise ProjectParseException(f'{type(asset).__name__} does not subclass Asset')
if (not isinstance(project, Project)):
raise ProjectParseException(f'{p... |
class Scaling():
def setup(self):
self.n = 1000
lat = np.array((9.99, 10, 10.01))
lon = np.array((4.99, 5, 5.01))
self.coordinates = np.array([(lati, loni) for (lati, loni) in zip(lat, lon)])
self.times = pd.date_range('2019-01-01', freq='1T', periods=self.n)
self.pos... |
class ResnetCompleteNetworkTest(tf.test.TestCase):
def _resnet_small(self, inputs, num_classes=None, is_training=True, global_pool=True, output_stride=None, include_root_block=True, reuse=None, scope='resnet_v2_small'):
block = resnet_v2.resnet_v2_block
blocks = [block('block1', base_depth=1, num_un... |
def test_background_check_order(pytester):
pytester.makefile('.feature', background=textwrap.dedent(FEATURE))
pytester.makeconftest(textwrap.dedent(STEPS))
pytester.makepyfile(textwrap.dedent(' from pytest_bdd import scenario\n\n ("background.feature", "Background steps are executed first")\n ... |
def scrapping_empresas():
file = urlopen(EMPRESAS_FILE)
file = file.read().decode(encoding='utf-8')
region = state = city = ''
empresas = []
for line in file.split('\n'):
if line.startswith('## '):
region = line[2:].strip()
elif line.startswith('### '):
state ... |
class Solution(object):
def maximumProduct(self, nums):
min1 = min2 = float('inf')
max1 = max2 = max3 = float('-inf')
for num in nums:
if (num <= min1):
min2 = min1
min1 = num
elif (num <= min2):
min2 = num
i... |
class SeparableConv2d(nn.Module):
def __init__(self, inplanes, planes, kernel_size=3, stride=1, dilation=1, bias=False, norm_layer=None):
super(SeparableConv2d, self).__init__()
self.kernel_size = kernel_size
self.dilation = dilation
padding = get_padding(kernel_size, stride, dilatio... |
class IDAUp(nn.Module):
def __init__(self, in_channels, out_channel, up_f, norm_func):
super(IDAUp, self).__init__()
for i in range(1, len(in_channels)):
in_channel = in_channels[i]
f = int(up_f[i])
proj = DeformConv(in_channel, out_channel, norm_func)
... |
class ShieldTimeColumn(GraphColumn):
name = 'ShieldTime'
def __init__(self, fittingView, params):
super().__init__(fittingView, 1392, (3, 0, 0))
def _getValue(self, fit):
return ((fit.ship.getModifiedItemAttr('shieldRechargeRate') / 1000), 's')
def _getFitTooltip(self):
return 'T... |
def bind_table(bindtable, row_site, col_site, kf=None):
s_rows = [row[0] for row in bindtable[1:]]
s_cols = bindtable[0]
kmatrix = [row[1:] for row in bindtable[1:]]
kiter = itertools.chain.from_iterable(kmatrix)
if (any((isinstance(x, numbers.Real) for x in kiter)) and (kf is None)):
raise ... |
.parametrize('cfg_file', ['../configs/textrecog/sar/sar_r31_parallel_decoder_academic.py'])
def test_model_batch_inference_raises_exception_error_aug_test_recog(cfg_file):
tmp_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
config_file = os.path.join(tmp_dir, cfg_file)
model = build_model(... |
class UNext(nn.Module):
def __init__(self, num_classes, input_channels=3, deep_supervision=False, img_size=224, patch_size=16, in_chans=3, embed_dims=[128, 160, 256], num_heads=[1, 2, 4, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=False, qk_scale=None, drop_rate=0.0, attn_drop_rate=0.0, drop_path_rate=0.0, norm_layer=nn.... |
def eval_loss():
raise NotImplementedError('not finished yet')
model.eval()
from utils.viz_utils import show_pred_and_gt
with torch.no_grad():
accum_loss = 0.0
for (sample_id, data) in enumerate(train_loader):
data = data.to(device)
gt = data.y.view((- 1), out_cha... |
.parametrize('tsys_zmore', [dict(sysname='typem1', K=2.0, atol=0.0015, result=(float('Inf'), (- 120.0007), float('NaN'), 0.5774)), dict(sysname='type0', K=0.8, atol=0.0015, result=(10.0014, float('inf'), 1.7322, float('nan'))), dict(sysname='type0', K=2.0, atol=0.01, result=(4.0, 67.6058, 1.7322, 0.7663)), dict(sysname... |
_specialize
_rewriter([mul, true_div])
def local_mul_pow_to_pow_add(fgraph, node):
pow_nodes = defaultdict(list)
rest = []
for n in node.inputs:
if (n.owner and hasattr(n.owner.op, 'scalar_op') and isinstance(n.owner.op.scalar_op, ps.Pow)):
base_node = n.owner.inputs[0]
pow_n... |
class StreamingEpochBatchIterator(EpochBatchIterating):
def __init__(self, dataset, epoch=0, num_shards=1, shard_id=0):
assert isinstance(dataset, torch.utils.data.IterableDataset)
self.dataset = dataset
self.epoch = epoch
self._current_epoch_iterator = None
self.num_shards =... |
_operation
def mtimes_real_complex(a: torch.Tensor, b: torch.Tensor, conj_b=False):
if is_real(b):
raise ValueError('Incorrect dimensions.')
if (not conj_b):
return complex(torch.matmul(a, b[(..., 0)]), torch.matmul(a, b[(..., 1)]))
if conj_b:
return complex(torch.matmul(a, b[(..., 0... |
class Balancer(Amm):
def __init__(self, reserves: list[int], weights: list[float]):
super().__init__(reserves, weights)
def conservation_function(self):
C = 1
for (i, qty) in enumerate(self.reserves):
C *= (qty ** self.weights[i])
return C
def spot_price(self, ass... |
class GCNLayer(nn.Module):
def __init__(self, in_features, out_features, bias=False, batch_norm=False):
super(GCNLayer, self).__init__()
self.weight = torch.Tensor(in_features, out_features)
self.weight = nn.Parameter(nn.init.xavier_uniform_(self.weight))
if bias:
self.bi... |
def callback_graph(weights, obj_func_eval):
clear_output(wait=True)
objective_func_vals.append(obj_func_eval)
plt.title('Objective function value against iteration')
plt.xlabel('Iteration')
plt.ylabel('Objective function value')
plt.plot(range(len(objective_func_vals)), objective_func_vals)
... |
class AverageAttention(nn.Module):
def __init__(self, model_dim, dropout=0.1, aan_useffn=False):
self.model_dim = model_dim
self.aan_useffn = aan_useffn
super(AverageAttention, self).__init__()
if aan_useffn:
self.average_layer = PositionwiseFeedForward(model_dim, model_d... |
def test_invalid_directjson(tmpdir):
wflowjson = yadage.workflow_loader.workflow('workflow.yml', 'tests/testspecs/local-helloworld')
with pytest.raises(jsonschema.exceptions.ValidationError):
ys = YadageSteering.create(dataarg=('local:' + os.path.join(str(tmpdir), 'workdir')), workflow_json={'invalid': ... |
class TestEstCommonCoord(object):
def setup_method(self):
self.res = 1.0
self.long_coord = np.arange(0, 360, self.res)
self.short_coord = np.arange(10, 350, (10.0 * self.res))
return
def teardown_method(self):
del self.long_coord, self.short_coord, self.res
return... |
class Jacobian():
def __init__(self, known_jacs=None, clear_domain=True):
self._known_jacs = (known_jacs or {})
self._clear_domain = clear_domain
def jac(self, symbol, variable):
try:
return self._known_jacs[symbol]
except KeyError:
jac = self._jac(symbol,... |
class CassandraDatabaseCreation(BaseDatabaseCreation):
def create_test_db(self, verbosity=1, autoclobber=False, **kwargs):
from django.conf import settings
from django.core.management import call_command
self.connection.connect()
default_alias = get_default_cassandra_connection()[0]
... |
def constant_fold_binary_op_extended(op: str, left: ConstantValue, right: ConstantValue) -> (ConstantValue | None):
if ((not isinstance(left, bytes)) and (not isinstance(right, bytes))):
return constant_fold_binary_op(op, left, right)
if ((op == '+') and isinstance(left, bytes) and isinstance(right, byt... |
def create_bases(model, kws=None, gpu=True):
kws = ([] if (kws is None) else kws)
ws0 = copy.deepcopy(model.state_dict())
bases = [rand_basis(ws0, gpu) for _ in range(2)]
bases = [normalize_filter(bs, ws0) for bs in bases]
bases = [ignore_bn(bs) for bs in bases]
bases = [ignore_kw(bs, kws) for b... |
class AuxiliaryHead(nn.Module):
def __init__(self, C, num_classes):
super(AuxiliaryHead, self).__init__()
self.features = nn.Sequential(nn.ReLU(inplace=True), nn.AvgPool2d(5, stride=3, padding=0, count_include_pad=False), nn.Conv2d(C, 128, 1, bias=False), nn.BatchNorm2d(128), nn.ReLU(inplace=True), ... |
class TrainDataset(Dataset):
def __init__(self, args, raw_datasets, cache_root):
self.raw_datasets = raw_datasets
cache_path = os.path.join(cache_root, 'compwebq_train.cache')
if (os.path.exists(cache_path) and args.dataset.use_cache):
self.data = torch.load(cache_path)
e... |
def get_files(**kwargs):
return [File(Path('LICENSES', 'Apache-2.0.txt'), Apache_2_0), File(Path('LICENSES', 'MIT.txt'), MIT.replace('<year>', f"{kwargs['year']}-present", 1).replace('<copyright holders>', f"{kwargs['author']} <{kwargs['email']}>", 1)), File(Path('src', kwargs['package_name'], '__init__.py'), f'''#... |
def convert_clap_checkpoint(checkpoint_path, pytorch_dump_folder_path, config_path, enable_fusion=False):
(clap_model, clap_model_cfg) = init_clap(checkpoint_path, enable_fusion=enable_fusion)
clap_model.eval()
state_dict = clap_model.state_dict()
state_dict = rename_state_dict(state_dict)
transform... |
def configure_environment(config_filename, environment):
factory = environment.factory
if (not os.path.exists(config_filename)):
raise PysmtIOError(("File '%s' does not exists." % config_filename))
config = cp.RawConfigParser()
config.read(config_filename)
new_solvers_sections = [s for s in ... |
def refers_to_fullname(node: Expression, fullnames: (str | tuple[(str, ...)])) -> bool:
if (not isinstance(fullnames, tuple)):
fullnames = (fullnames,)
if (not isinstance(node, RefExpr)):
return False
if (node.fullname in fullnames):
return True
if isinstance(node.node, TypeAlias... |
def test_unknown(hatch, helpers, path_append, mocker):
install = mocker.patch('hatch.python.core.PythonManager.install')
result = hatch('python', 'install', 'foo', 'bar')
assert (result.exit_code == 1), result.output
assert (result.output == helpers.dedent('\n Unknown distributions: foo, bar\n ... |
def get_resnet_v1_d_base(input_x, freeze_norm, scope='resnet50_v1d', 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 Effect1049(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Shield Emission Systems')), 'maxRange', src.getModifiedItemAttr('shipBonusMC2'), skill='Minmatar Cruiser', **kwargs) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.