code stringlengths 281 23.7M |
|---|
def pwre(id, raw_buf):
data = struct.unpack_from('<IQ', raw_buf)
payload = data[1]
hw = ((payload >> 7) & 1)
cstate = ((payload >> 12) & 15)
subcstate = ((payload >> 8) & 15)
value = struct.pack('!hiqiiiiiB', 4, 8, id, 4, cstate, 4, subcstate, 1, hw)
pwre_file.write(value) |
class HRModule(nn.Module):
def __init__(self, num_branches, blocks, num_blocks, in_channels, num_channels, multiscale_output=True, with_cp=False, conv_cfg=None, norm_cfg=dict(type='BN', requires_grad=True)):
super(HRModule, self).__init__()
self._check_branches(num_branches, num_blocks, in_channels,... |
def test_pass_extra_reporting(pytester: Pytester) -> None:
pytester.makepyfile('def test_this(): assert 1')
result = pytester.runpytest()
result.stdout.no_fnmatch_line('*short test summary*')
result = pytester.runpytest('-rp')
result.stdout.fnmatch_lines(['*test summary*', 'PASS*test_pass_extra_repo... |
class MBConvBlock(nn.Module):
def __init__(self, block_args, global_params, image_size=None):
super().__init__()
self._block_args = block_args
self._bn_mom = (1 - global_params.batch_norm_momentum)
self._bn_eps = global_params.batch_norm_epsilon
self.has_se = ((self._block_ar... |
class Solution():
def removeElement(self, nums: List[int], val: int) -> int:
i = 0
x = len(nums)
if (x == 1):
if (nums[0] == val):
nums.remove(val)
return len(nums)
while (i < x):
if (nums[i] == val):
nums.remove... |
class TypedDictTests(BaseTestCase):
def assert_typeddict_deprecated(self):
with self.assertWarnsRegex(DeprecationWarning, 'mypy_extensions.TypedDict is deprecated'):
(yield)
def test_basics_iterable_syntax(self):
with self.assert_typeddict_deprecated():
Emp = TypedDict('E... |
def save_command(command):
url = (BH_URL + '/api/v1/command')
try:
r = requests.post(url, data=command.to_JSON(), headers=json_auth_headers())
except ConnectionError as error:
print("Sorry, looks like there's a connection error")
pass
except Exception as error:
if (r.stat... |
class SourceConverter(commands.Converter):
async def convert(ctx: commands.Context, argument: str) -> SourceType:
cog = ctx.bot.get_cog(argument)
if cog:
return cog
cmd = ctx.bot.get_command(argument)
if cmd:
return cmd
raise commands.BadArgument(f'Una... |
class Window(operator):
def __init__(self, var, tumbling, only, binding_seq, s_when, e_when, vars):
self.var = var
self.tumbling = tumbling
self.only = only
self.binding_seq = binding_seq
self.s_when = s_when
self.e_when = e_when
self.vars = vars
def defin... |
def test_add_opening_quote_delimited_text_is_common_prefix(cmd2_app):
text = '/home/user/file'
line = 'test_delimited {}'.format(text)
endidx = len(line)
begidx = (endidx - len(text))
expected_common_prefix = '"/home/user/file'
expected_display = sorted(['file.txt', 'file space.txt'], key=cmd2_a... |
def test_threadpolltext_force_update(minimal_conf_noscreen, manager_nospawn):
config = minimal_conf_noscreen
tpoll = PollingWidget('Not polled')
config.screens = [libqtile.config.Screen(top=libqtile.bar.Bar([tpoll], 10))]
manager_nospawn.start(config)
widget = manager_nospawn.c.widget['pollingwidget... |
class TestVmap():
.skipif((not _has_functorch), reason=f'functorch not found: err={FUNCTORCH_ERR}')
.parametrize('moduletype,batch_params', [['linear', False], ['bn1', True], ['linear', True]])
def test_vmap_patch(self, moduletype, batch_params):
if (moduletype == 'linear'):
module = nn.... |
class SSData(BaseDbModel):
class Meta():
table = 'ss_data'
id = fields.IntField(pk=True)
author_id = fields.BigIntField()
channel_id = fields.BigIntField()
message_id = fields.BigIntField()
dhash = fields.CharField(max_length=1024, null=True)
phash = fields.CharField(max_length=1024,... |
def random_integer_and_continuously_increasing_data(janela, trend, limit):
random_series = [(i + randrange(10)) for i in range(1, 101)]
random_series = pd.DataFrame(random_series)
random_series.index = sorted(pd.to_datetime(np.random.randint(1, 101, size=100), unit='d').tolist())
random_series.columns =... |
def test_loading_extension_which_raises_exceptions_init(extensionregistry, mocker):
class SimpleExtension(object):
LOAD_IF = staticmethod((lambda config: True))
def __init__(self):
raise AssertionError('some error')
with pytest.raises(AssertionError) as exc:
extensionregistry... |
class CloudGuruCourseDownload(object):
def __init__(self):
self._id = None
self._title = None
self._course = None
def __repr__(self):
course = '{title}'.format(title=self.title)
return course
def id(self):
return self._id
def title(self):
return se... |
class TestInputFileWithRequest():
async def test_send_bytes(self, bot, chat_id):
message = (await bot.send_document(chat_id, data_file('text_file.txt').read_bytes()))
out = BytesIO()
(await (await message.document.get_file()).download_to_memory(out=out))
out.seek(0)
assert (o... |
class SaveScrim(ScrimsButton):
def __init__(self, ctx: Context):
super().__init__(style=discord.ButtonStyle.green, label='Save Scrim', disabled=True)
self.ctx = ctx
async def callback(self, interaction: Interaction):
(await interaction.response.defer())
self.ctx.bot.loop.create_t... |
def smart_repr(x):
if isinstance(x, tuple):
if (len(x) == 0):
return 'tuple()'
elif (len(x) == 1):
return ('(%s,)' % smart_repr(x[0]))
else:
return (('(' + ','.join(map(smart_repr, x))) + ')')
elif hasattr(x, '__call__'):
return ("__import__('p... |
def _lines_to_gdf(net, points, node_id):
(starts, ends, edge_data) = zip(*net.edges(data=True), strict=True)
gdf_edges = gpd.GeoDataFrame(list(edge_data))
if (points is True):
gdf_edges['node_start'] = [net.nodes[s][node_id] for s in starts]
gdf_edges['node_end'] = [net.nodes[e][node_id] for... |
class SMPLMarket(Dataset):
def __init__(self, data_dir, train_flag=True, random_pick=True):
super().__init__()
self.data_dir = data_dir
self.random_pick = random_pick
paths_pkl_path = osp.join(data_dir, 'train_test_img_paths_pid.pkl')
with open(paths_pkl_path, 'rb') as f:
... |
class GlyphTextureAtlas(image.atlas.TextureAtlas):
texture_class = GlyphTexture
def __init__(self, width=2048, height=2048, fmt=GL_RGBA, min_filter=GL_LINEAR, mag_filter=GL_LINEAR):
self.texture = self.texture_class.create(width, height, GL_TEXTURE_2D, fmt, min_filter, mag_filter, fmt=fmt)
self.... |
class Effect2252(BaseEffect):
type = 'passive'
def handler(fit, container, context, projectionRange, **kwargs):
fit.modules.filteredItemForce((lambda mod: mod.item.requiresSkill('Cloaking')), 'moduleReactivationDelay', container.getModifiedItemAttr('covertOpsAndReconOpsCloakModuleDelay'), **kwargs) |
def calculate_image_aggregate_size(ancestors_str, image_size, parent_image):
ancestors = ancestors_str.split('/')[1:(- 1)]
if (not ancestors):
return image_size
if (parent_image is None):
raise DataModelException('Could not load parent image')
ancestor_size = parent_image.aggregate_size
... |
class DepthwiseConv2D(layers.DepthwiseConv2D):
__doc__ += layers.DepthwiseConv2D.__doc__
def call(self, inputs, params=None):
if (params[(self.name + '/depthwise_kernel:0')] is None):
return super(layers.DepthwiseConv2D, self).call(inputs)
else:
depthwise_kernel = params.... |
class MultiChoiceBatchTransform(Transform):
def transform(x: List[Dict], y: List[Dict]=None, **kwargs: Any) -> str:
if ((not isinstance(x[0], Dict)) or (y and (not isinstance(y[0], Dict)))):
raise TypeError('x and y should be dict in multi-choice task.')
transformed = ''
for (idx... |
class ConfigDict(Dict):
def __missing__(self, name):
raise KeyError(name)
def __getattr__(self, name):
try:
value = super(ConfigDict, self).__getattr__(name)
except KeyError:
ex = AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'")
... |
class TextEditBox(Gtk.HBox):
def __init__(self, default=''):
super().__init__(spacing=6)
sw = Gtk.ScrolledWindow()
sw.set_shadow_type(Gtk.ShadowType.IN)
sw.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
sw.add(TextView(buffer=TextBuffer()))
self.pack_s... |
class UnitTest(unittest.TestCase):
def test_initialization_and_get_next_batch(self) -> None:
unit = TestUnit()
self.assertIsNotNone(unit.train_progress)
self.assertIsNotNone(unit.eval_progress)
self.assertIsNotNone(unit.predict_progress)
tensor_1 = torch.ones(1)
tenso... |
class Rotation(CGAThing):
def __init__(self, cga, *args) -> None:
super().__init__(cga)
if (len(args) == 0):
U = self.layout.randomMV()(2)
U = self.cga.I_base.project(U)
self.mv = (e ** U)
elif (len(args) == 1):
arg = args[0]
if isi... |
class Transformer(Classifier):
def __init__(self, dataset, config):
super(Transformer, self).__init__(dataset, config)
self.pad = dataset.token_map[dataset.VOCAB_PADDING]
if (config.feature.feature_names[0] == 'token'):
seq_max_len = config.feature.max_token_len
else:
... |
def handle_transferreroute(payment_state: InitiatorPaymentState, state_change: ActionTransferReroute, channelidentifiers_to_channels: Dict[(ChannelID, NettingChannelState)], addresses_to_channel: Dict[(Tuple[(TokenNetworkAddress, Address)], NettingChannelState)], pseudo_random_generator: random.Random, block_number: Bl... |
class PageTests(TestCase):
_settings(EVENTS_PAGES_PATH=PAGES_PATH)
def test_valid_event_page_reponse_200(self):
pages = (reverse('events:page', args=('my-event',)), reverse('events:page', args=('my-event/subpage',)))
for page in pages:
with self.subTest(page=page):
re... |
class VersionConflict(ResolutionError):
_template = '{self.dist} is installed but {self.req} is required'
def dist(self):
return self.args[0]
def req(self):
return self.args[1]
def report(self):
return self._template.format(**locals())
def with_context(self, required_by):
... |
class _FmtResult(GaPrintable):
def __new__(cls, obj, label: str) -> GaPrintable:
if (label is None):
return obj
self = super().__new__(cls)
self._obj = obj
self._label = label
return self
def _latex(self, printer):
return ((self._label + ' = ') + print... |
class TestRealWorldLocate():
def setup_method(self) -> None:
self.dirpath = os.path.join(os.path.dirname(__file__), './data/')
network_distance = pandas.read_csv((self.dirpath + 'SF_network_distance_candidateStore_16_censusTract_205_new.csv'))
ntw_dist_piv = network_distance.pivot_table(valu... |
def Pulling(Loss_type, embedding, Jm):
if (Loss_type == 'NpairLoss'):
embedding_split = tf.split(embedding, 2, axis=0)
anc = embedding_split[0]
pos = embedding_split[1]
neg = pos
anc_tile = tf.reshape(tf.tile(anc, [1, int((FLAGS.batch_size / 2))]), [(- 1), int(FLAGS.embedding... |
class Vacation():
name: str
accommodations: List[Accommodation]
events: List[str]
def __init__(self):
self.accommodations = []
self.events = []
def setName(self, name: str) -> None:
self.name = name
def setAccommodations(self, accommodations: List[Accommodation]) -> None:... |
class TemplateConfig(LazilyParsedConfig):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._field_name = FIELD_TO_PARSE
self._field_email = FIELD_TO_PARSE
self._field_licenses = FIELD_TO_PARSE
self._field_plugins = FIELD_TO_PARSE
def name(self):... |
def convert_bip32_intpath_to_strpath(path: Sequence[int], *, hardened_char=BIP32_HARDENED_CHAR) -> str:
assert isinstance(hardened_char, str), hardened_char
assert (len(hardened_char) == 1), hardened_char
s = 'm/'
for child_index in path:
if (not isinstance(child_index, int)):
raise ... |
.script
def finalize_hypos_loop_scores(finalized_scores_list: List[Tensor], finalized_idxs, pad_idx: int, finalized_tokens, finalized_scores):
for i in range(finalized_idxs.size(0)):
cutoff = finalized_scores[i].ne(pad_idx)
scores = finalized_scores[i][cutoff]
finalized_scores_list[finalized... |
def fr_ssn(value: str):
if (not value):
return False
matched = re.match(_ssn_pattern(), value)
if (not matched):
return False
groups = list(matched.groups())
control_key = groups[(- 1)]
department = groups[3]
if ((department != '99') and (not fr_department(department))):
... |
class Slice3D_test_norm(torch.utils.data.Dataset):
suitableJobs = ['seg', 'cla']
def __init__(self, image96, classes, job, spacing=None, crop=None, ratio=None, rotate=None, include_slices=None):
assert (job in self.suitableJobs), 'not suitable jobs'
self.job = job
if (job == 'seg'):
... |
class SolveDiscreteARE(pt.Op):
__props__ = ('enforce_Q_symmetric',)
def __init__(self, enforce_Q_symmetric=False):
self.enforce_Q_symmetric = enforce_Q_symmetric
def make_node(self, A, B, Q, R):
A = as_tensor_variable(A)
B = as_tensor_variable(B)
Q = as_tensor_variable(Q)
... |
class MarkingDecorator():
def __init__(self, function):
self.function = function
self.fixture_class = None
def bind_class(self, fixture_class):
self.fixture_class = fixture_class
def __get__(self, instance, owner):
self.bind_class(owner)
if (instance is None):
... |
class DeterminismTest(TestCase):
(IS_WINDOWS, 'Remove when is fixed')
('num_workers', [1, 8])
def test_mprs_determinism(self, num_workers):
data_length = 64
exp = list(range(data_length))
data_source = IterableWrapper(exp)
dp = data_source.shuffle().sharding_filter().map(_ra... |
class QLWinSingleTest():
def __init__(self, test):
self._test = test
def _run_test(self, results):
try:
results['result'] = self._test()
except Exception as e:
tb = traceback.format_exc()
results['exception'] = tb
results['result'] = False
... |
class TWavpackFile(TestCase):
def setUp(self):
self.song = WavpackFile(get_data_path('silence-44-s.wv'))
def test_length(self):
self.assertAlmostEqual(self.song('~#length'), 3.68471, 3)
def test_channels(self):
assert (self.song('~#channels') == 2)
def test_samplerate(self):
... |
class CustomPythonBuild(build_py):
def pin_version(self):
path = os.path.join(self.build_lib, 'mypy')
self.mkpath(path)
with open(os.path.join(path, 'version.py'), 'w') as stream:
stream.write(f'''__version__ = "{version}"
''')
def run(self):
self.execute(self.pin_ver... |
class AvgMeter(object):
def __init__(self, num=40):
self.num = num
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
self.losses = []
def update(self, val, n=1):
self.val = val
self.sum += (val * n)
... |
def get_shot_to_precision(shots, logits, targets):
shot_to_precision = collections.defaultdict(list)
for (episode_num, episode_shots) in enumerate(shots):
episode_logits = logits[episode_num]
episode_targets = targets[episode_num]
for (class_id, class_shot) in enumerate(episode_shots):
... |
def create_dataset(queryset_items, name):
if (not queryset_items):
return
out_filepath = os.path.join(settings.DATASET_FOLDER, name)
data = {'links': [x.get_data4cls(status=True) for x in queryset_items]}
if (not os.path.exists(os.path.dirname(out_filepath))):
os.makedirs(os.path.dirname... |
class FakeFilesystemUnitTest(TestCase):
def setUp(self):
self.filesystem = fake_filesystem.FakeFilesystem(path_separator='/')
self.root_name = self.filesystem.root_dir_name
self.fake_file = fake_filesystem.FakeFile('foobar', filesystem=self.filesystem)
self.fake_child = fake_filesyst... |
class ResponsiveOption():
def __init__(self, allowed_options, prefix=None, xs=None, sm=None, md=None, lg=None, xl=None):
self.prefix = prefix
self.allowed_options = allowed_options
all_options = {'xs': xs, 'sm': sm, 'md': md, 'lg': lg, 'xl': xl}
self.device_options = {DeviceClass(dev... |
class GroupSampler(Sampler):
def __init__(self, dataset, samples_per_gpu=1):
assert hasattr(dataset, 'flag')
self.dataset = dataset
self.samples_per_gpu = samples_per_gpu
self.flag = dataset.flag.astype(np.int64)
self.epoch = 0
self.group_sizes = np.bincount(self.flag... |
def _get_list_output(python_version: str, package_version: str, package_name: str, new_install: bool, exposed_binary_names: List[str], unavailable_binary_names: List[str], exposed_man_pages: List[str], unavailable_man_pages: List[str], injected_packages: Optional[Dict[(str, PackageInfo)]]=None, suffix: str='') -> str:
... |
class PauseTagHandler(EtreeTagHandler):
def validate(self):
return self.__handler(validate=True)
def process(self):
self.__handler()
def __handler(self, validate=False):
msg = self.element.text
if (not validate):
ops.pause(msg)
return True |
def dePem(s, name):
prefix = ('-----BEGIN %s-----' % name)
postfix = ('-----END %s-----' % name)
start = s.find(prefix)
if (start == (- 1)):
raise SyntaxError('Missing PEM prefix')
end = s.find(postfix, (start + len(prefix)))
if (end == (- 1)):
raise SyntaxError('Missing PEM post... |
def matrix_loads(explode: bool, name: str, schema_type: str, location: Mapping[(str, Any)]) -> Any:
if (explode == False):
m = re.match(f'^;{name}=(.*)$', location[f';{name}'])
if (m is None):
raise KeyError(name)
value = m.group(1)
if (schema_type == 'array'):
... |
class Window(ABCWindow, message='Cannot load example window provider'):
def __init__(self, name):
pass
def refresh(self):
pass
def quit(self):
pass
def setResize(self, resize):
pass
def updateFunc(self):
pass
def getMouse(self, mousecode, mousestate):
... |
class TestPassportElementErrorReverseSideWithoutRequest(TestPassportElementErrorReverseSideBase):
def test_slot_behaviour(self, passport_element_error_reverse_side):
inst = passport_element_error_reverse_side
for attr in inst.__slots__:
assert (getattr(inst, attr, 'err') != 'err'), f"got... |
class Migration(migrations.Migration):
dependencies = [migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('successstories', '0009_auto__0352')]
operations = [migrations.AddField(model_name='story', name='submitted_by', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to=... |
class FitCapacitorGraph(FitGraph):
internalName = 'capacitorGraph'
name = _t('Capacitor')
xDefs = [XDef(handle='time', unit='s', label=_t('Time'), mainInput=('time', 's')), XDef(handle='capAmount', unit='GJ', label=_t('Cap amount'), mainInput=('capAmount', '%')), XDef(handle='capAmount', unit='%', label=_t(... |
def test_hidden_false(tmp_path, tmp_env):
text = '\n [[command]]\n name = "my-visible-command"\n hidden = false\n\n [[command.stages]]\n command = "eval"\n params = {code=\'1\'}\n '
(tmp_path / 'config.toml').write_text(text)
result = helpers.run(['--help'], env=tmp_env).decode()
as... |
class TypeVarTupleExpr(TypeVarLikeExpr):
__slots__ = 'tuple_fallback'
tuple_fallback: mypy.types.Instance
__match_args__ = ('name', 'upper_bound', 'default')
def __init__(self, name: str, fullname: str, upper_bound: mypy.types.Type, tuple_fallback: mypy.types.Instance, default: mypy.types.Type, variance... |
def test_get_group_symbol():
assert (numbers.get_group_symbol('en_US') == ',')
assert (numbers.get_group_symbol('en_US', numbering_system='latn') == ',')
assert (numbers.get_group_symbol('en_US', numbering_system='default') == ',')
assert (numbers.get_group_symbol('ar_EG') == ',')
assert (numbers.ge... |
def test(args):
device = torch.device(('cuda' if torch.cuda.is_available() else 'cpu'))
(log_dir, model_name) = os.path.split(args.model_path)
model = torch.load(args.model_path)
model = model.to(device)
writer = SummaryWriter(log_dir=log_dir)
class_names = ['upper_ns', 'middle_ns', 'lower_ns', ... |
class DjangoIntegration(UnmarshallingProcessor[(HttpRequest, HttpResponse)]):
request_cls = DjangoOpenAPIRequest
response_cls = DjangoOpenAPIResponse
def get_openapi_request(self, request: HttpRequest) -> DjangoOpenAPIRequest:
return self.request_cls(request)
def get_openapi_response(self, respo... |
class FCIDumpDriver(FermionicDriver):
def __init__(self, fcidump_input: str, atoms: Optional[List[str]]=None) -> None:
super().__init__()
if (not isinstance(fcidump_input, str)):
raise QiskitChemistryError("The fcidump_input must be str, not '{}'".format(fcidump_input))
self._fci... |
def refresh_suppressed_submodules(module: str, path: (str | None), deps: dict[(str, set[str])], graph: Graph, fscache: FileSystemCache, refresh_file: Callable[([str, str], list[str])]) -> (list[str] | None):
messages = None
if ((path is None) or (not path.endswith(INIT_SUFFIXES))):
return None
pkgdi... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--n_jobs', type=int, default=32)
parser.add_argument('--episode_size', type=int, default=8192)
parser.add_argument('--batch_size', type=int, default=1024)
parser.add_argument('--entropy_weight', type=int, default=1)
parser.add_a... |
def Weir_Goudet_beta(ds: Dataset, *, stat_identity_by_state: Hashable=variables.stat_identity_by_state, merge: bool=True) -> Dataset:
ds = define_variable_if_absent(ds, variables.stat_identity_by_state, stat_identity_by_state, identity_by_state)
variables.validate(ds, {stat_identity_by_state: variables.stat_ide... |
class OptimizationApplication(ABC):
def to_quadratic_program(self) -> QuadraticProgram:
pass
def interpret(self, result: Union[(OptimizationResult, np.ndarray)]):
pass
def _result_to_x(self, result: Union[(OptimizationResult, np.ndarray)]) -> np.ndarray:
if isinstance(result, Optimiz... |
class DE(DE_yabox):
def solve(self, show_progress=False):
best_pop_evo = []
best_fitn_evo = []
mean_fitn_evo = []
if show_progress:
from tqdm import tqdm
iterator = tqdm(self.iterator(), total=self.maxiters, desc='Optimizing ({0})'.format(self.name))
e... |
_funcify.register(CAReduce)
def numba_funcify_CAReduce(op, node, **kwargs):
axes = op.axis
if (axes is None):
axes = list(range(node.inputs[0].ndim))
if (hasattr(op, 'acc_dtype') and (op.acc_dtype is not None)):
acc_dtype = op.acc_dtype
else:
acc_dtype = node.outputs[0].type.dtyp... |
class ProtocolTestCase(FramesTestCase):
def assertFrameSent(self, connection, frame, eof=False):
frames_sent = [(None if (write is SEND_EOF) else self.parse(write, mask=(connection.side is CLIENT), extensions=connection.extensions)) for write in connection.data_to_send()]
frames_expected = ([] if (f... |
class Trainer():
def __init__(self, exp_dir='experiment', score_type='exprsco', batch_size=64, random_seed=42, print_every=100, checkpoint_every=1000, samp_rate=2000, KL_rate=0.9999, free_bits=60):
if (random_seed is not None):
torch.manual_seed(random_seed)
if (not os.path.isabs(exp_dir... |
def driver(request, driver_class, driver_kwargs):
retries = int(request.config.getini('max_driver_init_attempts'))
for retry in Retrying(stop=stop_after_attempt(retries), wait=wait_exponential(), reraise=True):
with retry:
LOGGER.info(f'Driver init, attempt {retry.retry_state.attempt_number}... |
class uvm_nonblocking_transport_port(uvm_port_base):
def __init__(self, name, parent):
super().__init__(name, parent)
def nb_transport(self, put_data):
try:
(success, get_data) = self.export.nb_transport(put_data)
except AttributeError:
raise UVMTLMConnectionError... |
def register(parent):
devices = wp.get_devices()
class TestOperators(parent):
pass
add_kernel_test(TestOperators, test_operators_scalar_float, dim=1, devices=devices)
add_kernel_test(TestOperators, test_operators_scalar_int, dim=1, devices=devices)
add_kernel_test(TestOperators, test_operato... |
class DuckTestDrive():
def main(*args):
duck: Duck = MallardDuck()
turkey: Turkey = WildTurkey()
turkeyAdapter: Duck = TurkeyAdapter(turkey)
print('The Turkey says...')
turkey.gobble()
turkey.fly()
print('\nThe Duck says...')
DuckTestDrive.testDuck(duc... |
class TypeReplaceVisitor(SyntheticTypeVisitor[None]):
def __init__(self, replacements: dict[(SymbolNode, SymbolNode)]) -> None:
self.replacements = replacements
def visit_instance(self, typ: Instance) -> None:
typ.type = self.fixup(typ.type)
for arg in typ.args:
arg.accept(se... |
def test_SKCImputerABC__impute_not_implemented(decision_matrix):
class Foo(impute.SKCImputerABC):
_skcriteria_parameters = []
def _impute(self, **kwargs):
return super()._impute(**kwargs)
transformer = Foo()
dm = decision_matrix(seed=42)
with pytest.raises(NotImplementedError... |
class File(FileSystemObject):
is_file = True
preview_data = None
preview_known = False
preview_loading = False
_firstbytes = None
def firstbytes(self):
if (self._firstbytes is not None):
return self._firstbytes
try:
with open(self.path, 'rb') as fobj:
... |
def collate_fn(batch):
max_len = max([len(f['input_ids']) for f in batch])
input_ids = [(f['input_ids'] + ([0] * (max_len - len(f['input_ids'])))) for f in batch]
input_mask = [(([1.0] * len(f['input_ids'])) + ([0.0] * (max_len - len(f['input_ids'])))) for f in batch]
labels = [f['labels'] for f in batc... |
class RandomHorizontalFlip(object):
def __call__(self, sample):
if (random.random() < 0.5):
sample['image'] = sample['image'].transpose(Image.FLIP_LEFT_RIGHT)
sample['sal'] = sample['sal'].transpose(Image.FLIP_LEFT_RIGHT)
return sample
def __str__(self):
return 'R... |
def test_asyncio_mark_respects_parametrized_loop_policies(pytester: Pytester):
pytester.makepyfile(__init__='', test_parametrization=dedent(' import asyncio\n\n import pytest\n\n pytestmark = pytest.mark.asyncio(scope="package")\n\n (\n scope="package",\n ... |
class SnapshotMetadata():
version: str
world_size: int
manifest: Manifest
def to_yaml(self) -> str:
return json.dumps(asdict(self), sort_keys=False, indent=2)
def from_yaml(cls, yaml_str: str) -> 'SnapshotMetadata':
d = yaml.load(yaml_str, Loader=Loader)
manifest: Manifest = ... |
class Effect7061(BaseEffect):
runTime = 'early'
type = ('projected', 'passive', 'gang')
def handler(fit, beacon, context, projectionRange, **kwargs):
for x in range(1, 3):
if beacon.getModifiedItemAttr('warfareBuff{}ID'.format(x)):
value = beacon.getModifiedItemAttr('warf... |
def get_args_parser():
parser = argparse.ArgumentParser('Holistic edge attention transformer', add_help=False)
parser.add_argument('--data_path', default='', help='path to the data`')
parser.add_argument('--lr', default=0.0002, type=float)
parser.add_argument('--batch_size', default=16, type=int)
pa... |
def parse_gts(gts_list, num_classes):
logger.info('Start parsing gts list......')
index_info = [temp for temp in enumerate(gts_list) if temp[1].startswith('#')]
gts = defaultdict(list)
gts['num'] = np.zeros(num_classes)
for i in range(len(index_info)):
index = index_info[i][0]
img_na... |
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, plan... |
class Log1mexp(UnaryScalarOp):
def static_impl(x):
if (x < np.log(0.5)):
return np.log1p((- np.exp(x)))
else:
return np.log((- np.expm1(x)))
def impl(self, x):
return Log1mexp.static_impl(x)
def grad(self, inp, grads):
(x,) = inp
(gz,) = grads
... |
class MySortModel(QSortFilterProxyModel):
def __init__(self, parent, *, sort_role):
super().__init__(parent)
self._sort_role = sort_role
def lessThan(self, source_left: QModelIndex, source_right: QModelIndex):
item1 = self.sourceModel().itemFromIndex(source_left)
item2 = self.sou... |
.parametrize('value,order', [('bysource', ['Foo', 'decorator_okay', 'Bar']), ('alphabetical', ['Bar', 'Foo', 'decorator_okay']), ('groupwise', ['Bar', 'Foo', 'decorator_okay'])])
def test_order_members(builder, parse, value, order):
confoverrides = {'autoapi_member_order': value, 'exclude_patterns': ['manualapi.rst... |
class Match2Match(nn.Module):
def __init__(self, feat_dims, luse):
super(Match2Match, self).__init__()
input_dim = 16
layer_num = 6
expand_ratio = 4
bottlen = 26
self.to_embedding = nn.Sequential(Rearrange('b c h1 w1 h2 w2 -> b (h1 w1 h2 w2) c'), nn.Linear(bottlen, in... |
class LineCounter():
__slots__ = ('char_pos', 'line', 'column', 'line_start_pos', 'newline_char')
def __init__(self, newline_char):
self.newline_char = newline_char
self.char_pos = 0
self.line = 1
self.column = 1
self.line_start_pos = 0
def __eq__(self, other):
... |
class Logger():
def __init__(self, stdout=sys.stdout, verbose=NOTE):
self.stdout = stdout
self.verbose = verbose
self._t0 = process_clock()
self._w0 = perf_counter()
log = log
error = error
warn = warn
note = note
info = info
debug = debug
debug1 = debug1
... |
class _IHDRChunk(_Chunk):
def __init__(self, chunk_type, px_width, px_height):
super(_IHDRChunk, self).__init__(chunk_type)
self._px_width = px_width
self._px_height = px_height
def from_offset(cls, chunk_type, stream_rdr, offset):
px_width = stream_rdr.read_long(offset)
... |
class TCPClient(RawTCPClient):
def __init__(self, host, prog, vers, open_timeout=5000):
pmap = TCPPortMapperClient(host, open_timeout)
port = pmap.get_port((prog, vers, IPPROTO_TCP, 0))
pmap.close()
if (port == 0):
raise RPCError('program not registered')
RawTCPCl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.