code stringlengths 281 23.7M |
|---|
.usefixtures('save_env')
class TestUtil():
def test_get_host_platform(self):
with mock.patch('os.name', 'nt'):
with mock.patch('sys.version', '... [... (ARM64)]'):
assert (get_host_platform() == 'win-arm64')
with mock.patch('sys.version', '... [... (ARM)]'):
... |
def load_dataset_stats(config):
if (config.data.dataset == 'CIFAR10'):
filename = 'assets/stats/cifar10_stats.npz'
elif (config.data.dataset == 'CELEBA'):
filename = 'assets/stats/celeba_stats.npz'
elif (config.data.dataset == 'LSUN'):
filename = f'assets/stats/lsun_{config.data.cate... |
class TestHandlersApp(RapidTest):
def setUp(self):
self.connection = self.create_connection()
def test_init(self):
settings = {'INSTALLED_APPS': ['rapidsms.contrib.echo']}
with override_settings(**settings):
app = HandlersApp(self.router)
self.assertEqual(len(app.... |
class DenseModule(nn.Module):
def __init__(self, in_channels, growth, layers, bottleneck_factor=4, norm_act=ABN, dilation=1):
super(DenseModule, self).__init__()
self.in_channels = in_channels
self.growth = growth
self.layers = layers
self.convs1 = nn.ModuleList()
sel... |
def tencent_trick(model: nn.Module) -> list:
(decay, no_decay) = ([], [])
for (name, param) in model.named_parameters():
if (not param.requires_grad):
continue
elif ((len(param.shape) == 1) or name.endswith('.bias')):
no_decay.append(param)
else:
decay... |
class Match(operator):
def __init__(self, exact, vars, pattern, expr):
self.exact = exact
self.vars = vars
self.pattern = pattern
self.expr = expr
def defined_vars(self):
return set(self.vars)
def execute(self, table, prior_locs, prior_globs):
from pythonql.Ex... |
_module()
class DBHead(HeadMixin, BaseModule):
def __init__(self, in_channels, with_bias=False, downsample_ratio=1.0, loss=dict(type='DBLoss'), postprocessor=dict(type='DBPostprocessor', text_repr_type='quad'), init_cfg=[dict(type='Kaiming', layer='Conv'), dict(type='Constant', layer='BatchNorm', val=1.0, bias=0.00... |
class LxmertConfig(PretrainedConfig):
model_type = 'lxmert'
attribute_map = {}
def __init__(self, vocab_size=30522, hidden_size=768, num_attention_heads=12, num_qa_labels=9500, num_object_labels=1600, num_attr_labels=400, intermediate_size=3072, hidden_act='gelu', hidden_dropout_prob=0.1, attention_probs_dr... |
class PartialPipelineData(unittest.TestCase):
def test_returns_partial_when_uid_and_email_do_match(self):
email = ''
backend = self._backend({'uid': email})
backend.strategy.request_data.return_value = {backend.ID_KEY: email}
(key, val) = ('foo', 'bar')
partial = partial_pipe... |
class NagiosPerfdataCollector(diamond.collector.Collector):
GENERIC_FIELDS = ['DATATYPE', 'HOSTNAME', 'TIMET']
HOST_FIELDS = ['HOSTPERFDATA']
SERVICE_FIELDS = ['SERVICEDESC', 'SERVICEPERFDATA']
TOKENIZER_RE = ("([^\\s]+|'[^']+')=([-.\\d]+)(c|s|ms|us|B|KB|MB|GB|TB|%)?" + '(?:;([-.\\d]+))?(?:;([-.\\d]+))?... |
class ERB(nn.Module):
def __init__(self, in_channels, out_channels):
super(ERB, self).__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0)
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1)
self.relu = nn... |
def _nominal_center_frequency(center, fraction):
def _roundn(x, n):
return round(x, ((- int(np.floor((np.sign(x) * np.log10(abs(x)))))) + n))
b = fraction
x = center
if (b == 1):
n = index_of_frequency(x, b)
if ((- 6) <= n < 5):
return acoustics.standards.iec_61672_1_... |
_deprecated
def simple_evaluate(model, load='', args='', tasks=[], num_fewshot=0, batch_size=None, device=None, no_cache=False, limit=None, bootstrap_iters=100000, description_dict=None, check_integrity=False, decontamination_ngrams_path=None):
random.seed(1234)
np.random.seed(1234)
assert (tasks != []), 'N... |
class TestPredictiveFunctions():
def test_correct_sensitivity(self):
r = sensitivity(25, 50)
assert (r[0] == 0.5)
def test_sensitivity_match_sas_ci(self):
sas_ci = (0., 0.)
r = sensitivity(25, 50, confint='wald')
npt.assert_allclose(r[1:3], sas_ci)
def test_sensitivit... |
class HandlerStates(int, enum.Enum):
END = ConversationHandler.END
STATE_1 = 1
STATE_2 = 2
STATE_3 = 3
STATE_4 = 4
def next(self):
cls = self.__class__
members = list(cls)
index = (members.index(self) + 1)
if (index >= len(members)):
index = 0
... |
class TestEventletSemaphore(test_lock.TestSemaphore):
def setUp(self):
if (not EVENTLET_HANDLER_AVAILABLE):
pytest.skip('eventlet handler not available.')
super(TestEventletSemaphore, self).setUp()
def make_condition():
return threading.Condition()
def make_event():
... |
class CompareAction(actions.BaseAction):
name = 'compare'
security = 'validate'
parent_parsers = [actions.SELECTION_PARSER]
def add_action_subparser(cls, sub_handler):
subparser = super().add_action_subparser(sub_handler)
subparser.add_argument('--method', choices=['meta', 'full', 'hash'... |
def eval(epoch, trainer, dataset_name, testset_loader, test_batch_generator):
trainer.model.eval()
eval_result = {}
cur_sample_idx = 0
for (itr, (inputs, targets, meta_info)) in enumerate(tqdm(test_batch_generator)):
inputs = {k: v.cuda() for (k, v) in inputs.items()}
targets = {k: v.cud... |
class TestMultiSceneGrouping():
()
def scene1(self):
from satpy import Scene
scene = Scene()
dsid1 = make_dataid(name='ds1', resolution=123, wavelength=(1, 2, 3), polarization='H')
scene[dsid1] = _create_test_dataset(name='ds1')
dsid2 = make_dataid(name='ds2', resolution=... |
class CmdSetHandler(object):
def __init__(self, obj, init_true=True):
self.obj = obj
self.key = None
self.current = None
self.cmdset_stack = [_EmptyCmdSet(cmdsetobj=self.obj)]
self.mergetype_stack = ['Union']
self.permanent_paths = ['']
if init_true:
... |
def CreateDataLoader(opt):
(train_dataset, test_dataset) = CreateDataset(opt)
train_dl = torch.utils.data.DataLoader(train_dataset, batch_size=opt.batch_size, sampler=data_sampler(train_dataset, shuffle=True, distributed=opt.distributed), drop_last=True)
test_dl = torch.utils.data.DataLoader(test_dataset, b... |
class Flatc(iw.CustomCommand):
def __init__(self, path, unit):
self._path = path
self._incl_dirs = ['$S', '$B']
def descr(self):
return ('FL', self._path, 'light-green')
def tools(self):
return ['contrib/tools/flatc']
def input(self):
return common.make_tuples([se... |
def get_dataloader(dataset='coco', img_size=128):
if (dataset == 'coco'):
dataset = CocoSceneGraphDataset(image_dir='./datasets/coco/images/val2017/', instances_json='./datasets/coco/annotations/instances_val2017.json', stuff_json='./datasets/coco/annotations/stuff_val2017.json', stuff_only=True, image_size... |
def test_no_matches(keyhint, config_stub):
bindings = {'normal': {'aa': 'message-info cmd-aa', 'ab': 'message-info cmd-ab'}}
config_stub.val.bindings.default = {}
config_stub.val.bindings.commands = bindings
keyhint.update_keyhint(usertypes.KeyMode.normal, 'z')
assert (not keyhint.text())
assert... |
def normalize_path(base, filename):
abs_path = os.path.abspath(base)
joined = os.path.join(abs_path, filename)
normalized = os.path.normpath(joined)
if normalized.startswith(os.path.join(abs_path, '')):
return normalized
raise PathTraversalException('Path Traversal detected') |
class TestReceiver():
def testHasNoIntentFilter(SAMPLE_PATH_13667):
receiver = getReceivers(SAMPLE_PATH_13667)[2]
assert (receiver.hasIntentFilter() is False)
def testHasIntentFilter(SAMPLE_PATH_13667):
receiver = getReceivers(SAMPLE_PATH_13667)[0]
assert (receiver.hasIntentFilte... |
class HAN(nn.Module):
def __init__(self, args, conv=common.default_conv):
super(HAN, self).__init__()
n_resgroups = args.n_resgroups
n_resblocks = args.n_resblocks
n_feats = args.n_feats
kernel_size = 3
reduction = args.reduction
scale = args.scale[0]
... |
def tbwrite_loglikelihoods(step: Union[(int, None)]=None, agent_loglikelihoods: Union[(torch.Tensor, None)]=None, prior_loglikelihoods: Union[(torch.Tensor, None)]=None) -> None:
avg_agent_loglikelihood = torch.mean(agent_loglikelihoods)
avg_prior_loglikelihood = torch.mean(prior_loglikelihoods)
tb_writer.a... |
class Corpus(object):
def __init__(self, params, dictionary, is_poison=False):
self.path = params['data_folder']
authors_no = params['number_of_total_participants']
self.dictionary = dictionary
self.no_tokens = len(self.dictionary)
self.authors_no = authors_no
self.tr... |
def _fitting_dataset(args: SharedArgs, dataset: Dataset, heads: List[TrainerHeadInterface], repetitions: Optional[int], shuffle_videos: bool, chunk_shuffle: float) -> FittingDataset:
video_start_providers = _video_start_providers(args, dataset)
tf_dataset = _tf_dataset(args, dataset, heads, video_start_provider... |
def _reserve_kjt_storage(topology: Topology, batch_size: int, batch_inputs: List[float], input_data_type_size: int, multiplier: int) -> Storage:
kjt_size = (math.ceil((sum(batch_inputs) * float(input_data_type_size))) * multiplier)
kjt_storage = Storage(hbm=(kjt_size if (topology.compute_device == 'cuda') else ... |
def _configure_project_with_groups(poetry: Poetry, installed: Repository) -> None:
poetry.package.add_dependency(Factory.create_dependency('cachy', '^0.1.0'))
poetry.package.add_dependency_group(DependencyGroup(name='time', optional=True))
poetry.package.add_dependency(Factory.create_dependency('pendulum', ... |
def write_human_readable_meta(game: GameDescription, output: TextIO) -> None:
output.write('\nTemplates\n')
for (template_name, template) in game.resource_database.requirement_template.items():
output.write(f'''
* {template_name}:
''')
for (level, text) in pretty_print_requirement(template):
... |
class BatchNormalization(layers.BatchNormalization):
__doc__ += layers.BatchNormalization.__doc__
def call(self, inputs, params=None, training=None):
if (params[(self.name + '/gamma:0')] is None):
return super(layers.BatchNormalization, self).call(inputs)
else:
gamma = pa... |
class Database(Element):
_e_label = 'DATABASE'
def backend_id(self) -> (int, None):
def version_info(self) -> tuple:
def client_address(self) -> (str, None):
def client_port(self) -> (int, None):
def xact(self, isolation=None, mode=None) -> Transaction:
def settings(self) -> Settings:
de... |
def _find_facility_from_conf():
facility_names = logging.handlers.SysLogHandler.facility_names
facility = getattr(logging.handlers.SysLogHandler, CONF.syslog_log_facility, None)
if ((facility is None) and (CONF.syslog_log_facility in facility_names)):
facility = facility_names.get(CONF.syslog_log_fa... |
class QMixer(nn.Module):
def __init__(self, args):
super(QMixer, self).__init__()
self.args = args
self.n_agents = args.n_agents
self.state_dim = int(np.prod(args.state_shape))
self.embed_dim = args.mixing_embed_dim
if (getattr(args, 'hypernet_layers', 1) == 1):
... |
class Editor():
def __init__(self, game: GameDescription):
self.game = game
self.next_node_index = len(game.region_list.all_nodes)
def new_node_index(self) -> NodeIndex:
result = self.next_node_index
self.next_node_index += 1
return result
def edit_connections(self, a... |
def test_get_protocol():
model0 = get_protocol(protocol_name='0')
assert (model0.lj_on_polar_h is True)
assert (model0.free_parameters['X'].r_free == 1.083)
assert (model0.free_parameters['H'].r_free == 1.738)
assert (model0.free_parameters['C'].r_free == 2.008)
assert (model0.free_parameters['N... |
def test_connection_get_item():
conn = Connection(REGION)
table_name = 'Thread'
conn.add_meta_table(MetaTable(DESCRIBE_TABLE_DATA[TABLE_KEY]))
with patch(PATCH_METHOD) as req:
req.return_value = GET_ITEM_DATA
item = conn.get_item(table_name, 'Amazon DynamoDB', 'How do I update multiple i... |
class CaptureManager():
def __init__(self, method: CaptureMethod) -> None:
self._method = method
self._capturing: (MultiCapture[str] | None) = None
def __repr__(self) -> str:
return '<CaptureManager _method={!r} _capturing={!r}>'.format(self._method, self._capturing)
def is_capturing... |
def main(args):
vocab = Tokenizer(args.vocab_path, args.emb_dim, args.vsize)
word2id = vocab.token2idx_dict
(train_batcher, val_batcher) = build_batchers(word2id, args.cuda, args.debug, args.augment)
(net, net_args) = configure_net(len(word2id), args.emb_dim, args.n_hidden, args.bi, args.n_layer)
ne... |
def entangling_power(U):
if (not U.isoper):
raise Exception('U must be an operator.')
if (U.dims != [[2, 2], [2, 2]]):
raise Exception('U must be a two-qubit gate.')
from qutip.core.gates import swap
swap13 = expand_operator(swap(), [2, 2, 2, 2], [1, 3])
a = (((tensor(U, U).dag() * s... |
def init_model(prototxt_file, model_file):
caffe.set_mode_gpu()
caffe.set_device(0)
net = caffe.Net(prototxt_file, model_file, caffe.TEST)
transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})
transformer.set_mean('data', np.array([111, 111, 111]))
transformer.set_transpose(... |
class TestThreading(TestCase):
def test_validation_across_a_second_thread(self):
failed = []
def validate():
try:
validators.validate(instance=37, schema=True)
except:
failed.append(sys.exc_info())
validate()
from threading impo... |
class BottleneckBlock(nn.Module):
def __init__(self, in_chs, out_chs, dilation=1, bottle_ratio=0.25, groups=1, act_layer=nn.ReLU, norm_layer=nn.BatchNorm2d, attn_last=False, attn_layer=None, drop_block=None, drop_path=0.0):
super(BottleneckBlock, self).__init__()
mid_chs = int(round((out_chs * bottl... |
def _find_all_split_bn_in_graph(connected_graph: ConnectedGraph):
def _examine_split_bn(op_subset):
split_bn_pair_list.append(op_subset)
split_bn_pair_list = []
handler = PatternHandler(_examine_split_bn)
_support_split_op = ['Concat']
patterns_with_callbacks = []
for _split_op in _suppo... |
class ScaledDotProductAttention(nn.Module):
def __init__(self, d_model, d_k, d_v, h):
super(ScaledDotProductAttention, self).__init__()
self.fc_q = nn.Linear(d_model, (h * d_k))
self.fc_k = nn.Linear(d_model, (h * d_k))
self.fc_v = nn.Linear(d_model, (h * d_v))
self.fc_o = nn... |
class _Roles(EnvConfig, env_prefix='roles_'):
advent_of_code: int =
announcements: int =
lovefest: int =
pyweek_announcements: int =
revival_of_code: int =
legacy_help_channels_access: int =
contributors: int =
partners: int =
python_community: int =
voice_verified: int ... |
def test_linewidth(use_dask):
mc_hdu = moment_cube()
sc = SpectralCube.read(mc_hdu, use_dask=use_dask)
with warnings.catch_warnings(record=True) as w:
assert_allclose(sc.moment2(), MOMENTS[2][0])
assert (len(w) == 1)
assert (w[0].category == VarianceWarning)
assert (str(w[0].message) == ... |
.command()
('--hostname', default='docker-for-desktop')
('--path', default=None)
def create_state(hostname, path):
pvc_name = 'yadagedata'
sc_name = 'local-storage'
path_base = (path or os.getcwd())
size = '1G'
kubeyaml = 'kind: PersistentVolumeClaim\napiVersion: v1\nmetadata:\n name: {pvc_name}\ns... |
class nonnegative_float(click.ParamType):
name = 'FLT'
def convert(self, value, param, ctx):
msg = 'must be a positive float or zero'
if isinstance(value, str):
try:
value = float(value)
except ValueError:
self.fail(msg, param, ctx)
... |
def cleanup_server_instance(tcp_port):
sock = socket.socket()
sock.connect(('localhost', tcp_port))
try:
for _ in range(10):
sock.sendall(b'exit\n')
sock.recv(1)
time.sleep(0.1)
except (BrokenPipeError, ConnectionAbortedError, ConnectionResetError):
pa... |
class F12Handler(BaseHandler):
version = F12
commandMap = {'auth': commands.authconfig.FC3_Authconfig, 'authconfig': commands.authconfig.FC3_Authconfig, 'autopart': commands.autopart.F12_AutoPart, 'autostep': commands.autostep.FC3_AutoStep, 'bootloader': commands.bootloader.F12_Bootloader, 'cdrom': commands.cdr... |
.parametrize(['alias', 'dtype'], zip(dtype_names, dtype_types), ids=[str(dtype) for dtype in dtype_names])
.parametrize('func', [rand_herm, rand_unitary, rand_dm, rand_ket, rand_stochastic, rand_super, rand_super_bcsz, rand_kraus_map])
def test_random_dtype(func, alias, dtype):
with CoreOptions(default_dtype=alias)... |
class TableSection(Section):
has_data_type_header = True
def read(cls, reader):
if cls.has_data_type_header:
DataType.read(reader)
ts = cls.table_setup
header = get_versioned(ts['header'], reader.version_dialect)
blocks = list(cls.read_table(reader, header, ts['cls'],... |
def test_upload(copy_sample):
responses.add(responses.POST, upload.PYPI, status=200)
td = copy_sample('module1_toml')
with temp_pypirc(pypirc1) as pypirc, patch('flit.upload.get_repository', return_value=repo_settings):
upload.main((td / 'pyproject.toml'), repo_name='pypi', pypirc_path=pypirc)
a... |
def decay_lr(step, boundaries, values, max_steps):
if (FLAGS.decay_lr_type == 'linear'):
decayed_lr = linear_decay_lr(step, boundaries, values, max_steps)
elif (FLAGS.decay_lr_type == 'cosine'):
decayed_lr = cos_decay_lr(step, boundaries, values, max_steps)
elif (FLAGS.decay_lr_type == 'sine... |
_SEG_HEADS_REGISTRY.register()
class SemSegFPNHead(nn.Module):
def __init__(self, input_shape: Dict[(str, ShapeSpec)], *, num_classes: int, conv_dims: int, common_stride: int, loss_weight: float=1.0, norm: Optional[Union[(str, Callable)]]=None, ignore_value: int=(- 1)):
super().__init__()
input_shap... |
def test_items_bounding_rect_given_items(view):
item1 = BeePixmapItem(QtGui.QImage())
view.scene.addItem(item1)
item1.setSelected(True)
item1.setPos(4, (- 6))
item2 = BeePixmapItem(QtGui.QImage())
view.scene.addItem(item2)
item2.setSelected(True)
item2.setPos((- 33), 22)
item3 = BeeP... |
_on_failure
.parametrize('number_of_nodes', [2])
.parametrize('enable_rest_api', [True])
def test_api_payments_with_hash_no_secret(api_server_test_instance, raiden_network: List[RaidenService], token_addresses, pfs_mock):
(_, app1) = raiden_network
token_address = token_addresses[0]
target_address = app1.ad... |
def calculate_sentence_transformer_embedding(text_to_encode, args):
num = len(text_to_encode)
emb_model = SentenceTransformer(args.embedding_model)
embeddings = []
bar = tqdm(range(0, num, 20), desc='calculate embeddings')
for i in range(0, num, 20):
embeddings += emb_model.encode(text_to_en... |
def GetClipboardFormats():
win32clipboard.OpenClipboard()
available_formats = []
current_format = 0
while True:
current_format = win32clipboard.EnumClipboardFormats(current_format)
if (not current_format):
break
available_formats.append(current_format)
win32clipbo... |
def _strategy_dispatch(T, limit):
if isinstance(limit, st.SearchStrategy):
return limit
if isinstance(T, list):
return bitslists(T, limit)
if is_bitstruct_class(T):
return bitstructs(T, limit)
assert issubclass(T, Bits)
if (limit is None):
return bits(T.nbits)
ass... |
_db
def test_query_job_board(rf, graphql_client, job_listing_factory, conference_factory):
listing = job_listing_factory()
job_listing_factory(conference=conference_factory())
request = rf.get('/')
resp = _query_job_board(graphql_client, conference=listing.conference.code)
assert (len(resp['data']['... |
class BoundingBox():
def __init__(self, imageName, classId, x, y, w, h, typeCoordinates=CoordinatesType.Absolute, imgSize=None, bbType=BBType.GroundTruth, classConfidence=None, format=BBFormat.XYWH):
self._imageName = imageName
self._typeCoordinates = typeCoordinates
if ((typeCoordinates == ... |
def _encode_python_objects(obj):
if (isinstance(obj, (list, tuple)) and all([(not isinstance(item, (list, tuple))) for item in obj])):
return [_encode_to_cf(item) for item in obj]
try:
dump = _encode_object(obj)
except ValueError:
decoded = _try_decode_object(obj)
dump = json... |
def test_regex_reversal() -> None:
assert (parse('b').reversed() == parse('b'))
assert (parse('e*').reversed() == parse('e*'))
assert (parse('bear').reversed() == parse('raeb'))
assert (parse('beer').reversed() == parse('reeb'))
assert (parse('abc|def|ghi').reversed() == parse('cba|fed|ihg'))
as... |
def DiffAugment(x, policy=None, channels_first=True):
if (policy is not None):
if (not channels_first):
x = x.permute(0, 3, 1, 2)
for p in policy:
for f in AUGMENT_FNS[p]:
x = f(x)
if (not channels_first):
x = x.permute(0, 2, 3, 1)
... |
_module()
class Body3DH36MDataset(Kpt3dSviewKpt2dDataset):
JOINT_NAMES = ['Root', 'RHip', 'RKnee', 'RFoot', 'LHip', 'LKnee', 'LFoot', 'Spine', 'Thorax', 'NeckBase', 'Head', 'LShoulder', 'LElbow', 'LWrist', 'RShoulder', 'RElbow', 'RWrist']
SUPPORTED_JOINT_2D_SRC = {'gt', 'detection', 'pipeline'}
ALLOWED_METR... |
_ARCH_REGISTRY.register()
class SSRCNN(nn.Module):
def __init__(self, cfg):
super().__init__()
self.device = torch.device(cfg.MODEL.DEVICE)
self.backbone = build_backbone(cfg)
self.proposal_generator = build_proposal_generator(cfg, self.backbone.output_shape())
self.from_conf... |
def prefetch_test(opt):
if (not opt.not_set_cuda_env):
os.environ['CUDA_VISIBLE_DEVICES'] = opt.gpus_str
Dataset = dataset_factory[opt.test_dataset]
opt = opts().update_dataset_info_and_set_heads(opt, Dataset)
print(opt)
Logger(opt)
split = ('val' if (not opt.trainval) else 'test')
d... |
.parametrize('in_memory_ds', [True, False])
.filterwarnings('ignore::sgkit.io.vcfzarr_reader.DimensionNameForFixedFormatFieldWarning')
def test_write_vcf(shared_datadir, tmp_path, in_memory_ds):
path = path_for_test(shared_datadir, 'sample.vcf.gz')
intermediate = tmp_path.joinpath('intermediate.vcf.zarr').as_po... |
class BaseFeaturesCollection():
def __init__(self):
self.compute_base_features_topic = rospy.get_param('~compute_base_features_topic', '/base_features_computation_node/compute_base_features')
self.data_dir = rospy.get_param('~data_dir_path', os.path.join(rospkg.RosPack().get_path('rail_semantic_gras... |
class AttenSepConvLSTM2DCell(DropoutRNNCellMixin, Layer):
def __init__(self, filters, kernel_size, strides=(1, 1), padding='valid', data_format=None, dilation_rate=(1, 1), depth_multiplier=1, activation='tanh', recurrent_activation='hard_sigmoid', use_bias=True, kernel_initializer='glorot_uniform', recurrent_initia... |
class Solution():
def isSubsequence(self, s: str, t: str) -> bool:
for a in s:
if (a in t):
for b in range(0, len(t)):
if (a == t[b]):
t = t[(b + 1):]
break
else:
return False
... |
def test_exact():
constrainer = SomeNotInSetConstraint(set('abc'), n=2, exact=True)
(v1, v2, v3) = variables = [Variable('v1'), Variable('v2'), Variable('v3')]
assignments = {v1: 'a', v2: 'y', v3: 'z'}
assert constrainer(variables, {}, assignments)
assignments = {v1: 'a', v2: 'y'}
assert constra... |
class InvCompress(Cheng2020Anchor):
def __init__(self, N=192, **kwargs):
super().__init__(N=N)
self.g_a = None
self.g_s = None
self.enh = EnhModule(64)
self.inv = InvComp(M=N)
self.attention = AttModule(N)
def g_a_func(self, x):
x = self.enh(x)
x =... |
def resnet152(pretrained=False, root='~/.encoding/models', **kwargs):
model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs)
if pretrained:
from ..models.model_store import get_model_file
model.load_state_dict(torch.load(get_model_file('resnet152', root=root)), strict=False)
return model |
class _ChunkResizer():
def __init__(self, adapter, chunk_size):
self.adapter = adapter
self.old_chunk_size = None
self.new_chunk_size = (int(chunk_size) if chunk_size else 0)
def __enter__(self):
if ((self.adapter.connection is not None) and hasattr(self.adapter.connection, 'chun... |
class HKPRO3(FinTS3Segment):
date_start = DataElementField(type='dat', required=False, _d='Von Datum')
date_end = DataElementField(type='dat', required=False, _d='Bis Datum')
max_number_responses = DataElementField(type='num', max_length=4, required=False, _d='Maximale Anzahl Eintrage')
touchdown_point ... |
def setup(args, modify_exp_name=False):
cfg = get_config()
cfg.merge_from_file(args.config_file)
cfg.merge_from_list(args.opts)
if ((cfg.MODEL.DEVICE != 'cpu') and (not torch.cuda.is_available())):
cfg.MODEL.DEVICE = 'cpu'
if modify_exp_name:
curr_time = datetime.datetime.now().strft... |
def ToStructure(device):
LayersList = []
MatList = []
for i in range(device['numlayers']):
layer = device['layers'][i]
MatList.append(ToSolcoreMaterial(layer['properties']['composition'], device['T']))
LayersList.append(ToLayer(layer['properties']['width'], MatList[i], layer['label']... |
def get_submodules_from_kwargs(kwargs):
backend = kwargs.get('backend', _KERAS_BACKEND)
layers = kwargs.get('layers', _KERAS_LAYERS)
layers.Conv2D = Conv2D
layers.BatchNormalization = BatchNormalization
layers.Dense = Dense
layers.DepthwiseConv2D = DepthwiseConv2D
layers.SeparableConv2D = Se... |
class SeekBar(Gtk.Box):
def __init__(self, player, library):
super().__init__()
self._elapsed_label = TimeLabel()
self._remaining_label = TimeLabel()
scale = Gtk.Scale(orientation=Gtk.Orientation.HORIZONTAL)
scale.set_adjustment(Gtk.Adjustment.new(0, 0, 0, 3, (- 15), 0))
... |
class ItemParams(wx.Panel):
def __init__(self, parent, stuff, item, context=None):
wx.Panel.__init__(self, parent, size=(1000, 1000))
self.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNFACE))
self.mainFrame = gui.mainFrame.MainFrame.getInstance()
mainSizer = wx.Box... |
class Effect4385(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredChargeBoost((lambda mod: mod.charge.requiresSkill('Heavy Assault Missiles')), 'maxVelocity', ship.getModifiedItemAttr('eliteBonusReconShip1'), skill='Recon Ships', **kwargs) |
class CascadedManager(nvCompManager):
def __init__(self, **kwargs):
super().__init__(kwargs)
default_options = {'chunk_size': (1 << 12), 'type': np.int32, 'num_RLEs': 2, 'num_deltas': 1, 'use_bp': True}
for (k, v) in default_options.items():
try:
getattr(self, k)
... |
class CategoricalMLPPolicy(StochasticPolicy, LasagnePowered, Serializable):
def __init__(self, env_spec, hidden_sizes=(32, 32), hidden_nonlinearity=NL.tanh, num_seq_inputs=1, prob_network=None):
Serializable.quick_init(self, locals())
assert isinstance(env_spec.action_space, Discrete)
if (pr... |
('PyQt6.QtWidgets.QGraphicsTextItem.keyPressEvent')
('beeref.items.BeeTextItem.exit_edit_mode')
def test_key_press_event_enter(exit_mock, key_press_mock, view):
item = BeeTextItem('foo bar')
view.scene.addItem(item)
view.scene.edit_item = item
event = MagicMock()
event.key.return_value = Qt.Key.Key_... |
class Visualization(ScreenProgram):
NUM_PARTICLES = 400
FPS_MEASURE_WINDOW = 20.0
def get_variants() -> List[str]:
try:
with open('/proc/device-tree/model', encoding='utf-8') as model_file:
model = model_file.read()
if model.startswith('Raspberry Pi 3'):
... |
class TagViewTests(django.test.TestCase):
def setUp(self):
super().setUp()
self.commit = Commit.objects.create(**TEST_COMMIT_KWARGS)
def test_routing(self):
Tag.objects.create(name='example', last_commit=self.commit)
Tag.objects.create(name='grouped-tag', group='group-name', last... |
def filled_stream(stream, audio_source):
with stream.mainloop.lock:
stream.connect_playback()
assert stream.is_ready
with stream.mainloop.lock:
writable_size = stream.get_writable_size()
assert (writable_size > 0)
nbytes = min(1024, writable_size)
audio_data = audio_source.ge... |
class TestUtils(unittest.TestCase):
def test_line_info_at(self):
text = 'abc\ndef'
self.assertEqual(line_info_at(text, 0), (0, 0))
self.assertEqual(line_info_at(text, 2), (0, 2))
self.assertEqual(line_info_at(text, 3), (0, 3))
self.assertEqual(line_info_at(text, 4), (1, 0))
... |
class RSoftmax(nn.Module):
def __init__(self, radix, groups):
super().__init__()
self.radix = radix
self.groups = groups
def forward(self, x):
batch = x.size(0)
if (self.radix > 1):
x = x.view(batch, self.groups, self.radix, (- 1)).transpose(1, 2)
... |
class Wav2Vec2ProcessorWithLM(ProcessorMixin):
feature_extractor_class = 'Wav2Vec2FeatureExtractor'
tokenizer_class = 'Wav2Vec2CTCTokenizer'
def __init__(self, feature_extractor: 'FeatureExtractionMixin', tokenizer: 'PreTrainedTokenizerBase', decoder: 'BeamSearchDecoderCTC'):
from pyctcdecode import... |
def pytest_addoption(parser: Parser) -> None:
group = parser.getgroup('general')
group._addoption('-k', action='store', dest='keyword', default='', metavar='EXPRESSION', help="Only run tests which match the given substring expression. An expression is a Python evaluatable expression where all names are substrin... |
class Fp16OptimizerHook(OptimizerHook):
def __init__(self, grad_clip=None, coalesce=True, bucket_size_mb=(- 1), loss_scale=512.0, distributed=True):
self.grad_clip = grad_clip
self.coalesce = coalesce
self.bucket_size_mb = bucket_size_mb
self.loss_scale = loss_scale
self.dist... |
def invert(model: torch.nn.Module) -> torch.nn.Module:
fx_model = fx.symbolic_trace(model)
new_graph = fx.Graph()
env = {}
for node in reversed(fx_model.graph.nodes):
if (node.op == 'call_function'):
new_node = new_graph.call_function(invert_mapping[node.target], (env[node.name],))
... |
def test_quantizable_mha_with_value():
B = 5
T = 8
S = 4
q_inputs = keras.Input(shape=(T, 16))
v_inputs = keras.Input(shape=(S, 16))
k_inputs = keras.Input(shape=(S, 16))
model_output = keras.layers.MultiHeadAttention(key_dim=2, num_heads=2)(q_inputs, v_inputs, k_inputs)
unquantized_mode... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.