code stringlengths 281 23.7M |
|---|
class WebEngineInspectorView(QWebEngineView):
def createWindow(self, wintype: QWebEnginePage.WebWindowType) -> QWebEngineView:
our_page = self.page()
assert (our_page is not None)
inspected_page = our_page.inspectedPage()
assert (inspected_page is not None)
if machinery.IS_QT... |
class VertexDomain():
_initial_count = 16
def __init__(self, program, attribute_meta):
self.program = program
self.attribute_meta = attribute_meta
self.allocator = allocation.Allocator(self._initial_count)
self.attribute_names = {}
self.buffer_attributes = []
self... |
class Permute(Layer):
def __init__(self, dims, **kwargs):
super(Permute, self).__init__(**kwargs)
self.dims = tuple(dims)
self.input_spec = InputSpec(ndim=(len(self.dims) + 1))
def compute_output_shape(self, input_shape):
input_shape = list(input_shape)
output_shape = cop... |
def make_retinanet_loss_evaluator(cfg, box_coder):
matcher = Matcher(cfg.MODEL.RETINANET.FG_IOU_THRESHOLD, cfg.MODEL.RETINANET.BG_IOU_THRESHOLD, allow_low_quality_matches=True)
sigmoid_focal_loss = SigmoidFocalLoss(cfg.MODEL.RETINANET.LOSS_GAMMA, cfg.MODEL.RETINANET.LOSS_ALPHA)
loss_evaluator = RetinaNetLos... |
def modified_main(dataset_path, k_list_to_check, ranker_path=None, normalize_ranker=False, num_workers=1, tokenizer='corenlp', docdb_path=None, out=None):
dataset = load_dataset(dataset_path)
ranker = TfidfDocRanker(tfidf_path=ranker_path, normalize_vectors=normalize_ranker, tokenizer=tokenizer)
docdb = Doc... |
class TestGurobiTranslator(QiskitOptimizationTestCase):
((not _optionals.HAS_GUROBIPY), 'Gurobi not available.')
def test_from_and_to(self):
q_p = QuadraticProgram('test')
q_p.binary_var(name='x')
q_p.integer_var(name='y', lowerbound=(- 2), upperbound=4)
q_p.continuous_var(name='... |
class Migration(migrations.Migration):
dependencies = [('views', '0014_data_migration')]
operations = [migrations.AlterField(model_name='view', name='comment', field=models.TextField(blank=True, help_text='Additional internal information about this view.', verbose_name='Comment')), migrations.AlterField(model_n... |
class Conditional_LDSR(Conditional_Unfolding_Loss):
def __init__(self, window_length, hop_length, **kwargs):
super().__init__(window_length, hop_length)
def criterion(self, target_signal_hat, target_signal):
s_target = ((((target_signal_hat * target_signal).sum((- 1), keepdims=True) + 1e-08) / (... |
def run(gl: gitlab.Gitlab, gitlab_resource: str, resource_action: str, args: Dict[(str, Any)], verbose: bool, output: str, fields: List[str]) -> None:
g_cli = GitlabCLI(gl=gl, gitlab_resource=gitlab_resource, resource_action=resource_action, args=args)
data = g_cli.run()
printer: Union[(JSONPrinter, LegacyP... |
class unsubscribe_repos_Handler(BaseHandler):
.authenticated
async def get(self, userid):
try:
user = self.current_user
if ((user['id'] == int(userid)) and (user['role'] == u'admin')):
(await self.render('pubtpl_unsubscribe.html', user=user))
else:
... |
def count_matches(pred_texts, gt_texts):
match_res = {'gt_char_num': 0, 'pred_char_num': 0, 'true_positive_char_num': 0, 'gt_word_num': 0, 'match_word_num': 0, 'match_word_ignore_case': 0, 'match_word_ignore_case_symbol': 0}
comp = re.compile('[^A-Z^a-z^0-9^-]')
norm_ed_sum = 0.0
for (pred_text, gt_text... |
def test_order_ab():
FooAB = namedtuple('FooAB', 'a b')
assert (get_named_tuple_shape(FooAB) == Shape(input=InputShape(constructor=FooAB, kwargs=None, fields=(InputField(type=Any, id='a', default=NoDefault(), is_required=True, metadata=MappingProxyType({}), original=ANY), InputField(type=Any, id='b', default=No... |
_grad()
def convert_wav2vec2_checkpoint(checkpoint_path, pytorch_dump_folder_path, dict_path, encoder_config_path, decoder_config_path, vocab_size, num_decoder_layers):
encoder_config = Wav2Vec2Config.from_pretrained(encoder_config_path)
decoder_config = Speech2Text2Config.from_pretrained(decoder_config_path, v... |
def _validate_template(target: Path, template: (str | None)) -> str:
if (template == ''):
warnings.warn(f'template={template!r} looks like a error, using default instead')
template = None
if (template is None):
template = TEMPLATES.get(target.suffix)
if (template is None):
ra... |
class TestIPMW():
def mdata(self):
df = pd.DataFrame()
df['A'] = [1, 1, 1, 1, 1, 0, 0, 0, 0, 0]
df['L'] = [1, 1, 0, 0, 0, 1, 1, 1, 1, 0]
df['M'] = [1, np.nan, 1, 0, np.nan, 0, 1, np.nan, np.nan, 1]
return df
def test_error_for_non_nan(self, mdata):
with pytest.rai... |
def deconv2d_args_preprocessor(args, kwargs):
converted = []
if (len(args) == 5):
if isinstance(args[4], tuple):
args = args[:(- 1)]
converted.append(('output_shape', None))
if ('output_shape' in kwargs):
kwargs.pop('output_shape')
converted.append(('output_sh... |
class PaymentRequest():
def __init__(self, data, *, error=None):
self.raw = data
self.error = error
self.parse(data)
self.requestor = None
self.tx = None
def __str__(self):
return str(self.raw)
def parse(self, r):
self.outputs = []
if self.erro... |
def test_require_gdal_version_chaining():
version = '.0'
_gdal_version(version, param='foo', values=['bar'])
_gdal_version(version, param='something', values=['else'])
def a(foo=None, something=None):
return (foo, something)
assert (a(foo='ok', something='not else') == ('ok', 'not else'))
... |
class Deadline():
def __init__(self, timeout: Optional[float]) -> None:
self.deadline: Optional[float]
if (timeout is None):
self.deadline = None
else:
self.deadline = (time.monotonic() + timeout)
def timeout(self, *, raise_if_elapsed: bool=True) -> Optional[float... |
def get_color(name):
if ('unord' in name):
return colors[0]
if ('rfwr' in name):
return colors[1]
if ('reinforce_bl' in name):
return colors[2]
if ('reinforce' in name):
return colors[6]
if ('sasbl' in name):
return colors[3]
if ('sas' in name):
re... |
class FFTDF(lib.StreamObject):
_keys = {'cell', 'kpts', 'grids', 'mesh', 'blockdim', 'exxdiv'}
def __init__(self, cell, kpts=numpy.zeros((1, 3))):
from pyscf.pbc.dft import gen_grid
from pyscf.pbc.dft import numint
self.cell = cell
self.stdout = cell.stdout
self.verbose =... |
.script
def _compute(sum_squared_obs: torch.Tensor, sum_obs: torch.Tensor, rss: torch.Tensor, num_obs: torch.Tensor, multioutput: str, num_regressors: int) -> torch.Tensor:
tss = (sum_squared_obs - (torch.square(sum_obs) / num_obs))
r_squared = (1 - (rss / tss))
if (multioutput == 'uniform_average'):
... |
def torch_matmul(input, other, *, out=None):
d1 = input.dim()
d2 = other.dim()
shape = None
if ((d1 == 1) and (d2 == 1)):
shape = None
elif ((d1 == 2) and (d2 == 2)):
shape = (input.size(0), other.size(1))
elif ((d1 == 1) and (d2 == 2)):
shape = (other.size(1),)
elif ... |
def test_random_2_1_wedge_1_1():
dim = 3
n_tensor = numpy.random.random((dim, dim, dim))
m_tensor = numpy.random.random((dim, dim))
true_tensor = numpy.zeros(tuple(([dim] * 5)))
for (a, b, c, d, e) in product(range(dim), repeat=5):
for (u_perm, u_phase) in generate_parity_permutations([a, b,... |
def _assert_values_changed_and_not_hardcoded(test_file_path, pseudonymised_file_path):
ds_input = pydicom.dcmread(test_file_path, force=True)
ds_pseudo = pydicom.dcmread(pseudonymised_file_path, force=True)
assert (ds_input['PatientID'].value != ds_pseudo['PatientID'].value)
assert (ds_pseudo['PatientID... |
class ExposureSettings():
def __init__(self, data_provider: DataProvider, sector_exposure_tickers: List[Ticker], factor_exposure_tickers: List[Ticker]):
self._data_provider = data_provider
self._sector_exposure_tickers = sector_exposure_tickers
self._factor_exposure_tickers = factor_exposure... |
class LatticeDecoder(TopologicalDecoder[TQubit], metaclass=ABCMeta):
def syndrome_graph_keys(self) -> List[str]:
def __init__(self, params: Dict) -> None:
super().__init__(params)
self._params_validation()
for syndrome_graph_key in self.syndrome_graph_keys:
self.S[syndrome_gr... |
class WikiTableQuestion(datasets.GeneratorBasedBuilder):
def _info(self):
return datasets.DatasetInfo(description=_DESCRIPTION, features=datasets.Features({'id': datasets.Value('string'), 'question': datasets.Value('string'), 'table_id': datasets.Value('string'), 'table': {'page_title': datasets.Value('stri... |
class WaveRNN(nn.Module):
def __init__(self, hidden_size=384, quantization=256):
super(WaveRNN, self).__init__()
self.hidden_size = hidden_size
self.split_size = (hidden_size // 2)
self.R = nn.Linear(self.hidden_size, (3 * self.hidden_size), bias=False)
self.O1 = nn.Linear(se... |
class TwitchOpenIdConnect(OpenIdConnectAuth):
name = 'twitch'
USERNAME_KEY = 'preferred_username'
OIDC_ENDPOINT = '
DEFAULT_SCOPE = ['openid', 'user:read:email']
TWITCH_CLAIMS = '{"id_token":{"email": null,"email_verified":null,"preferred_username":null}}'
def auth_params(self, state=None):
... |
def test_initilization_info_logger():
import torch.nn as nn
from mmcv.utils.logging import get_logger
import os
class OverloadInitConv(nn.Conv2d, BaseModule):
def init_weights(self):
for p in self.parameters():
with torch.no_grad():
p.fill_(1)
... |
def test_api_groups():
group_ret = {'groups': [{'membership': [{'real_name': 'Bugzilla User', 'can_login': 1, 'name': '', 'login_denied_text': '', 'id': 85, 'email_enabled': 1, 'email': ''}, {'real_name': 'Bugzilla User2', 'can_login': 0, 'name': '', 'login_denied_text': '', 'id': 77, 'email_enabled': 0, 'email': '... |
def remove_markers(img, left, right, output):
pixels = img.load()
count = len(left)
for i in range(0, count):
header = left[i]
right_header = right[i]
x = int(header[0])
y = int(header[1])
rx = int(right_header[0])
ry = int(right_header[1])
for row in ... |
class TestMetadataColumnConstructionAndProperties(unittest.TestCase):
def test_single_id(self):
index = pd.Index(['id1'], name='id')
series = pd.Series([42], name='col1', index=index)
mdc = DummyMetadataColumn(series)
self.assertEqual(mdc.id_count, 1)
self.assertEqual(mdc.id_... |
_config
def test_stack_commands(manager):
assert (manager.c.layout.info()['current_stack'] == 0)
manager.test_window('one')
assert (_stacks(manager) == [['one'], []])
assert (manager.c.layout.info()['current_stack'] == 0)
manager.test_window('two')
assert (_stacks(manager) == [['one'], ['two']])... |
def generate_module(xsd_path: str) -> None:
module = run_generate_ds(xsd_path)
module = remove_python_version(module)
module = remove_six_import(module)
module = disable_code_analyzers(module)
module = format_with_black(module)
existing_path = xsd_path.replace('.xsd', '.py')
with open(existi... |
def ensureMarkerTable(dbHandle=None):
if (dbHandle is None):
dbHandle = ops.db.Database(db=ops.db.TARGET_DB, isolation_level=None)
curs = dbHandle.connection.cursor()
else:
curs = dbHandle.cursor()
try:
curs.execute('CREATE TABLE marker (name, last_date, extra)')
except:... |
(scope='session')
def run_kodi_pod(build_plugin):
podman('pod', 'rm', '-f', 'kodipod')
podman('pod', 'create', '--publish=8080:8080', '--publish=1080:1080', '--publish=5999:5999', '--name=kodipod')
podman('run', '--detach', '--pod=kodipod', '--name=kodi', '--umask=0002', '--env=KINO_PUB_TEST=1', f'--volume=... |
def _upload(training_dir, algorithm_id=None, writeup=None, benchmark_run_id=None, api_key=None, ignore_open_monitors=False):
if (not ignore_open_monitors):
open_monitors = monitoring._open_monitors()
if (len(open_monitors) > 0):
envs = [(m.env.spec.id if m.env.spec else '(unknown)') for ... |
class AsyncObject(object):
cls_value = 0
def __init__(self):
self.value = 0
_per_instance()
()
def get_value(self, index):
self.value += 1
return self.value
_per_instance()
()
def with_kwargs(self, x=1, y=2, z=3):
self.value += ((x + y) + z)
return... |
class TestGameBase():
title = 'Python-telegram-bot Test Game'
description = 'description'
photo = [PhotoSize('Blah', 'ElseBlah', 640, 360, file_size=0)]
text = b'\\U0001f469\\u200d\\U0001f469\\u200d\\U0001f467\\u200d\\U0001f467\\U0001f431
text_entities = [MessageEntity(13, 17, MessageEntity.URL)]
... |
class DiscordNotifier(Notifier):
__name__ = 'DiscordNotifier'
__type__ = 'addon'
__version__ = '0.11'
__status__ = 'testing'
__config__ = [('enabled', 'bool', 'Activated', False), ('webhookurl', 'string', 'The URL of the webhook', ''), ('captcha', 'bool', 'Notify captcha request', True), ('reconnect... |
def put(id: int) -> dict:
if connexion.request.is_json:
data = connexion.request.get_json()
film = Film.query.filter_by(id=id).first()
film.name = data['name']
film.pub_date = datetime.strptime(data['pubDate'], '%Y-%m-%d').date()
FilmCast.query.filter_by(film=film).delete()
... |
class TestReportsAPI(ReportsAPITestCase):
.parametrize('report_type', ['_GET_FLAT_FILE_OPEN_LISTINGS_DATA_', Reports.ReportType.INVENTORY.value, Reports.ReportType.INVENTORY])
.parametrize('marketplace_id', ['ATVPDKIKX0DER', Marketplaces.US.marketplace_id, Marketplaces.US.value, Marketplaces.US])
def test_r... |
def test_disconnect_one_invalid(timer):
func1 = mock.Mock()
func2 = mock.Mock()
timer.timeout.connect(func1)
with pytest.raises(TypeError):
timer.timeout.disconnect(func2)
func1.assert_not_called()
func2.assert_not_called()
timer.timeout.emit()
func1.assert_called_once_with() |
class CT_Override(BaseOxmlElement):
def content_type(self):
return self.get('ContentType')
def new(partname, content_type):
xml = ('<Override xmlns="%s"/>' % nsmap['ct'])
override = parse_xml(xml)
override.set('PartName', partname)
override.set('ContentType', content_type... |
class Batch(Pipelineable):
dense_features: torch.Tensor
sparse_features: KeyedJaggedTensor
labels: torch.Tensor
def to(self, device: torch.device, non_blocking: bool=False) -> 'Batch':
return Batch(dense_features=self.dense_features.to(device=device, non_blocking=non_blocking), sparse_features=s... |
def make_soft_link():
destination = '/home/xiaoxiao/disk2/ScanNet/rawData/scans/'
source = '/home/xiaoxiao/disk6/ScanNet/'
i = 0
for dir in os.listdir(destination):
if (i == 0):
i += 1
continue
else:
i += 1
print(((((destination + dir) + '/') +... |
def test_two_child_crashes() -> None:
async def crasher(etype: type[Exception]) -> NoReturn:
raise etype
async def main() -> None:
async with _core.open_nursery() as nursery:
nursery.start_soon(crasher, KeyError)
nursery.start_soon(crasher, ValueError)
with pytest.rai... |
class ResNet(MetaModule):
def __init__(self, block, num_blocks, num_classes=10):
super(ResNet, self).__init__()
self.in_planes = 64
self.conv1 = conv3x3(3, 64)
self.bn1 = MetaBatchNorm2d(64)
self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1)
self.layer... |
def generate_area_def_rst_list(area_file: str) -> str:
area_list: List[str] = []
template = '{area_name}\n{n:^>{header_title_length}}\n\n.. raw:: html\n\n{content}\n\n <hr>\n\n'
for (aname, params) in _read_yaml_area_file_content(area_file).items():
area = _create_area_def_from_dict(aname, param... |
def sample_minicorpus(name, factor, topk=30, maxdev=3000):
random.seed(12345)
collection = Collection(path='/dfs/scratch0/okhattab/OpenQA/collection.tsv')
qas_train = Queries(path='/dfs/scratch0/okhattab/OpenQA/NQ/train/qas.json').qas()
qas_dev = Queries(path='/dfs/scratch0/okhattab/OpenQA/NQ/dev/qas.js... |
class Old_Packages_TestCase(ParserTest):
def __init__(self, *args, **kwargs):
ParserTest.__init__(self, *args, **kwargs)
self.version = F7
self.ks = '\n%packages\nbash\n'
def runTest(self):
with warnings.catch_warnings(record=True):
warnings.simplefilter('always')
... |
class Network(Escpos):
def is_usable() -> bool:
return is_usable()
def __init__(self, host: str='', port: int=9100, timeout: Union[(int, float)]=60, *args, **kwargs):
Escpos.__init__(self, *args, **kwargs)
self.host = host
self.port = port
self.timeout = timeout
s... |
def test_ec_private_numbers_hash():
numbers1 = ec.EllipticCurvePrivateNumbers(1, ec.EllipticCurvePublicNumbers(2, 3, DummyCurve()))
numbers2 = ec.EllipticCurvePrivateNumbers(1, ec.EllipticCurvePublicNumbers(2, 3, DummyCurve()))
numbers3 = ec.EllipticCurvePrivateNumbers(2, ec.EllipticCurvePublicNumbers(2, 3,... |
def test_each_combination_works():
nrep = 10
nproc = 1
gsl = 'none'
failed_combos = list()
for clf_name in cfg.regressor_choices:
for fs_name in cfg.all_dim_red_methods:
if fs_name.startswith('lle'):
continue
remove_neuropredict_results(out_dir)
... |
class Drinkable(BaseConsumable):
consume_flag = 'drink'
def at_focus_drink(self, caller, **kwargs):
super().handle_consume(caller, 'drink', **kwargs)
def at_focus_sip(self, caller, **kwargs):
super().handle_consume(caller, 'sip', **kwargs)
def at_consume(self, caller, action):
se... |
class NamedTupleAnalyzer():
def __init__(self, options: Options, api: SemanticAnalyzerInterface, msg: MessageBuilder) -> None:
self.options = options
self.api = api
self.msg = msg
def analyze_namedtuple_classdef(self, defn: ClassDef, is_stub_file: bool, is_func_scope: bool) -> tuple[(boo... |
class BoundFileCollection(BoundFile):
def __init__(self, unbound_file_collection, directory_format, path_maker):
super().__init__(unbound_file_collection, directory_format)
self._path_maker = path_maker
def view(self, view_type):
raise NotImplementedError('Use `iter_views` instead.')
... |
class DummySumMetric(Metric[torch.Tensor]):
def __init__(self: TDummySumMetric, *, device: Optional[torch.device]=None) -> None:
super().__init__(device=device)
self._add_state('sum', torch.tensor(0.0, device=self.device))
_mode()
def update(self: TDummySumMetric, x: torch.Tensor) -> TDummyS... |
(frozen=True, slots=True)
class TeleporterNetworkNode(ResourceNode):
is_unlocked: Requirement
network: str
requirement_to_activate: Requirement
def requirement_to_leave(self, context: NodeContext) -> Requirement:
return RequirementAnd([self.is_unlocked, ResourceRequirement.simple(self.resource(c... |
class Model(nn.Module):
def __init__(self, config):
super(Model, self).__init__()
if (config.embedding_pretrained is not None):
self.embedding = nn.Embedding.from_pretrained(config.embedding_pretrained, freeze=False)
else:
self.embedding = nn.Embedding(config.n_vocab,... |
class InvoiceDialog(Factory.Popup):
def __init__(self, title, data, key):
self.status = PR_UNKNOWN
Factory.Popup.__init__(self)
self.app = App.get_running_app()
self.title = title
self.data = data
self.key = key
invoice = self.app.wallet.get_invoice(key)
... |
class ProxyCompletionHeadSparse(nn.Module):
def __init__(self, channel_in: int, channel_out: int, truncation: int) -> None:
super().__init__()
self.truncation = truncation
self.network = nn.Sequential(Me.MinkowskiInstanceNorm(channel_in), Me.MinkowskiReLU(), Me.MinkowskiLinear(channel_in, ch... |
class CoreProperties():
def __init__(self, element):
self._element = element
def author(self):
return self._element.author_text
def author(self, value):
self._element.author_text = value
def category(self):
return self._element.category_text
def category(self, value):... |
def get_ghz_po_para(n: int) -> Tuple[(QuantumCircuit, List[Parameter])]:
q = QuantumRegister(n, 'q')
delta = Parameter('t')
deltaneg = Parameter('-t')
circ = get_ghz_simple(n, measure=False)
circ.barrier()
circ.append(U2Gate(delta, deltaneg), [q])
meas = get_measurement_circ(n, 'q', 'c', Tru... |
def test_initialize_auth(hatch, devpi, temp_dir_cache, helpers, published_project_name, config_file):
config_file.model.publish['index']['ca-cert'] = devpi.ca_cert
config_file.model.publish['index']['repo'] = 'dev'
config_file.model.publish['index']['repos'] = {'dev': devpi.repo}
config_file.save()
... |
(max_runs=3)
def test_tell_many():
def f(x, offset=0.123214):
a = 0.01
return ((((np.sin((x ** 2)) + np.sin((x ** 5))) + ((a ** 2) / ((a ** 2) + ((x - offset) ** 2)))) + (x ** 2)) + (1e-05 * (x ** 3)))
def f_vec(x, offset=0.123214):
a = 0.01
y = (x + ((a ** 2) / ((a ** 2) + ((x -... |
def rotate_iou_gpu_eval(boxes, query_boxes, criterion=(- 1), device_id=0):
boxes = boxes.astype(np.float32)
query_boxes = query_boxes.astype(np.float32)
N = boxes.shape[0]
K = query_boxes.shape[0]
iou = np.zeros((N, K), dtype=np.float32)
if ((N == 0) or (K == 0)):
return iou
threadsP... |
class UserPlan(models.Model):
plan_status = ((0, ''), (1, ''))
user = models.ForeignKey('UserProfile', related_name='self_user', on_delete=models.CASCADE, verbose_name='')
attention = models.ManyToManyField('UserProfile', related_name='attention_user', blank=True, verbose_name='')
title = models.CharFie... |
class Selector(Layer):
def __init__(self, select, **kwargs):
super(Selector, self).__init__(**kwargs)
self.select = select
self.select_neuron = K.constant(value=self.select)
def build(self, input_shape):
super(Selector, self).build(input_shape)
def call(self, x):
retu... |
class Appr(Inc_Learning_Appr):
def __init__(self, model, device, nepochs=160, lr=0.1, lr_min=0.0001, lr_factor=10, lr_patience=8, clipgrad=10000, momentum=0.9, wd=0.0005, multi_softmax=False, wu_nepochs=0, wu_lr_factor=1, fix_bn=False, eval_on_train=False, logger=None, exemplars_dataset=None, lamb=5.0, pod_flat_fac... |
def test_bloch_redfield_tensor_spectral_callable():
N = 5
H = qutip.num(N)
a = qutip.destroy(N)
A_op = (a + a.dag())
spectra = (lambda w: ((w > 0) * 0.5))
(R_eigs, evecs) = bloch_redfield_tensor(H=H, a_ops=[(A_op, spectra)], c_ops=[(a ** 2)], fock_basis=False)
assert isinstance(R_eigs, qutip... |
class IRFFTOp(Op):
__props__ = ()
def output_type(self, inp):
return TensorType(inp.dtype, shape=((None,) * (inp.type.ndim - 1)))
def make_node(self, a, s=None):
a = as_tensor_variable(a)
if (a.ndim < 3):
raise TypeError((f'{self.__class__.__name__}: input must have dimen... |
def load_word_vector_file(vec_path: str, vocab: Optional[Iterable[str]]=None):
if (vocab is not None):
vocab = set((x.lower() for x in vocab))
if vec_path.endswith('.pkl'):
with open(vec_path, 'rb') as f:
return pickle.load(f)
elif vec_path.endswith('.txt.gz'):
handle = (... |
def get_args_parser():
parser = argparse.ArgumentParser('GFNet evaluation script', add_help=False)
parser.add_argument('--batch-size', default=128, type=int)
parser.add_argument('--arch', default='deit_small', type=str, help='Name of model to train')
parser.add_argument('--input-size', default=224, type... |
class Gen_Video():
def __init__(self):
pass
def Gen_Video(self, beat_times, mp3path, uuid):
FONT_URL = '../font/heimi.TTF'
with open((uuid + '.txt'), 'r', encoding='utf-8') as f:
text_str = f.read()
word_list = text_str.split('\n')
clips = []
for (inde... |
def fix_database_car_1(sqlite_file):
print('Editing database', sqlite_file)
conn = sqlite3.connect(sqlite_file)
conn.text_factory = (lambda b: b.decode(errors='ignore'))
c = conn.cursor()
query_get_all_tables = "SELECT name FROM sqlite_master WHERE type='table'"
c.execute(query_get_all_tables)
... |
class CommandTest(EvenniaTest):
def call(self, cmdobj, args, msg=None, cmdset=None, noansi=True, caller=None, receiver=None, cmdstring=None, obj=None, inputs=None, raw_string=None):
caller = (caller if caller else self.char1)
receiver = (receiver if receiver else caller)
cmdobj.caller = call... |
def test_env_via_toml_bad(testdir: pytest.Testdir) -> None:
toml_file = (Path(str(testdir.tmpdir)) / 'pyproject.toml')
toml_file.write_text('bad toml', encoding='utf-8')
result = testdir.runpytest()
assert (result.ret == 4)
assert (result.errlines == [f"ERROR: {toml_file}: Expected '=' after a key i... |
class WordpieceTokenizer(object):
def __init__(self, vocab, unk_token='[UNK]', max_input_chars_per_word=100):
self.vocab = vocab
self.unk_token = unk_token
self.max_input_chars_per_word = max_input_chars_per_word
def tokenize(self, text):
output_tokens = []
for token in w... |
class RGBTo01Normalization(ImageNormalization):
leaves_pixels_outside_mask_at_zero_if_use_mask_for_norm_is_true = False
def run(self, image: np.ndarray, seg: np.ndarray=None) -> np.ndarray:
assert (image.min() >= 0), 'RGB images are uint 8, for whatever reason I found pixel values smaller than 0. Your i... |
def __CompareString(ql: Qiling, address: int, params) -> int:
lpString1 = params['lpString1']
lpString2 = params['lpString2']
cchCount1 = params['cchCount1']
cchCount2 = params['cchCount2']
if (cchCount1 > 0):
lpString1 = lpString1[:cchCount1]
if (cchCount2 > 0):
lpString2 = lpSt... |
def get_defining_class(meth: Callable[(..., Any)]) -> Optional[Type[Any]]:
if isinstance(meth, functools.partial):
return get_defining_class(meth.func)
if (inspect.ismethod(meth) or (inspect.isbuiltin(meth) and (getattr(meth, '__self__') is not None) and getattr(meth.__self__, '__class__'))):
fo... |
def create_test_data_loader(args):
kwargs = {'num_workers': args.num_workers, 'pin_memory': True}
if (args.dataset == 'mvtec'):
test_dataset = MVTecDataset(args, is_train=False)
elif (args.dataset == 'btad'):
test_dataset = BTADDataset(args, is_train=False)
else:
raise NotImpleme... |
def test_simdiag_orthonormal_eigenvectors():
a = np.array([[1, 0, 1, (- 1), 0], [0, 4, 0, 0, 1], [1, 0, 4, 1, 0], [(- 1), 0, 1, 4, 0], [0, 1, 0, 0, 4]])
(_, evecs) = qutip.simdiag([qutip.Qobj(a), qutip.qeye(5)])
evecs = np.array([evec.full() for evec in evecs]).squeeze()
np.testing.assert_allclose((evec... |
.parametrize('angles', [[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], [[3, 4, 5], [10, 11, 12]]])
.parametrize('kappa', [*range(1, 12)])
.parametrize('constructor', [construct_custom_prga, construct_prga_with_phase, construct_prga_with_identity])
def test_programmable_rotation_gate_array(angles, kappa, constructor):
... |
def tokenize_item(sample, tokenizer):
doc_tokens = []
char_to_word_offset = []
prev_is_whitespace = True
for c in sample['context']:
if _is_whitespace(c):
prev_is_whitespace = True
else:
if prev_is_whitespace:
doc_tokens.append(c)
else:... |
()
def _check_alazy_constant_no_ttl():
global constant_call_count
constant_call_count = 0
_constant()
()
def constant():
global constant_call_count
constant_call_count += 1
return constant_call_count
assert_eq(1, (yield constant.asynq()))
assert_eq(1, (yield constant.... |
class StyleSDFConfig(BaseConfig):
name = 'stylesdf'
hint = 'Train a StyleSDF model.'
info = '\nTo train a StyleSDF model, the recommended settings are as follows:\n\n\x08\n- batch_size: 4 (for FF-HQ dataset, 8 GPU)\n- val_batch_size: 16 (for FF-HQ dataset, 8 GPU)\n- data_repeat: 200 (for FF-HQ dataset)\n- t... |
class ObjParser(Parser):
material_parser_cls = MaterialParser
cache_loader_cls = CacheLoader
cache_writer_cls = CacheWriter
def __init__(self, wavefront, file_name, strict=False, encoding='utf-8', create_materials=False, collect_faces=False, parse=True, cache=False):
super(ObjParser, self).__ini... |
def remove_bpe_dict(pred_dict, bpe_symbol):
new_dict = {}
for i in pred_dict:
if (type(pred_dict[i]) == list):
new_list = [remove_bpe(elem, bpe_symbol) for elem in pred_dict[i]]
new_dict[i] = new_list
else:
new_dict[i] = remove_bpe(pred_dict[i], bpe_symbol)
... |
def test_to_smiles_isomeric():
mol = Ligand.from_file(file_name=get_data('bace0.sdf'))
smiles = mol.to_smiles(isomeric=True, explicit_hydrogens=False, mapped=False)
assert ('' in smiles)
smiles = mol.to_smiles(isomeric=False, explicit_hydrogens=False, mapped=False)
assert ('' not in smiles) |
def cli_run():
print('\nAnatomical MRI module')
from visualqc.utils import run_common_utils_before_starting
run_common_utils_before_starting()
wf = make_workflow_from_user_options()
if (wf.vis_type is not None):
wf.run()
else:
raise ValueError('Invalid state for visualQC!\n\t Ens... |
class Resnet18(nn.Module):
def __init__(self, embedding_size, pretrained=True, is_norm=True, bn_freeze=True):
super(Resnet18, self).__init__()
self.model = resnet18(pretrained)
self.is_norm = is_norm
self.embedding_size = embedding_size
self.num_ftrs = self.model.fc.in_featur... |
_module()
class RawframeDataset(BaseDataset):
def __init__(self, ann_file, pipeline, data_prefix=None, test_mode=False, filename_tmpl='img_{:05}.jpg', with_offset=False, multi_class=False, num_classes=None, start_index=1, modality='RGB', sample_by_class=False, power=0.0, dynamic_length=False):
self.filename... |
def merge_event_handlers(event_handlers: Sequence[EventHandlerType]) -> EventHandlerType:
if (not event_handlers):
msg = 'No event handlers to merge'
raise ValueError(msg)
elif (len(event_handlers) == 1):
return event_handlers[0]
first_handler = event_handlers[0]
stop_propagation... |
def get_dataloader(txtdir, dataset, domain, phase, batch_size, num_workers=8):
assert (phase in ['train', 'val', 'test'])
(names, labels) = _dataset_info(join(txtdir, dataset, ('%s_%s.txt' % (domain, phase))))
if (phase == 'train'):
img_tr = get_train_transformer()
else:
img_tr = get_val... |
.integration
def test_fem_import(long_project):
current_fem = long_project.export_instrument_event_mappings()
instrument_event_mappings = [{'arm_num': '1', 'unique_event_name': 'enrollment_arm_1', 'form': 'demographics'}]
response = long_project.import_instrument_event_mappings(instrument_event_mappings)
... |
.end_to_end()
.xfail(strict=True, reason='pytask cannot capture during collection.')
def test_collect_capturing(tmp_path, runner):
source = '\n import sys\n print("collect %s failure" % 13)\n sys.stderr.write("collect %s_stderr failure" % 13)\n import xyz42123\n '
tmp_path.joinpath('task_module.p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.