code stringlengths 281 23.7M |
|---|
class _FunctionChangers():
def __init__(self, pyfunction, definition_info, changers=None):
self.pyfunction = pyfunction
self.definition_info = definition_info
self.changers = changers
self.changed_definition_infos = self._get_changed_definition_infos()
def _get_changed_definition... |
def quote_type_string(type_string: str) -> str:
no_quote_regex = '^<(tuple|union): \\d+ items>$'
if ((type_string in ['Module', 'overloaded function', 'Never', '<deleted>']) or type_string.startswith('Module ') or (re.match(no_quote_regex, type_string) is not None) or type_string.endswith('?')):
return ... |
.parametrize('ovr_levels', [[2], [3], [2, 4, 8]])
_gdal33
def test_ignore_overviews(data, ovr_levels):
inputfile = str(data.join('RGB.byte.tif'))
with rasterio.open(inputfile, 'r+') as src:
src.build_overviews(ovr_levels, resampling=Resampling.nearest)
with rasterio.open(inputfile, OVERVIEW_LEVEL=(-... |
class FC3_TestCase(CommandTest):
command = 'vnc'
def runTest(self):
obj = self.assert_parse('vnc', 'vnc\n')
obj.enabled = False
self.assertEqual(str(obj), '')
self.assert_parse('vnc --connect=HOSTNAME', 'vnc --connect=HOSTNAME\n')
self.assert_parse('vnc --connect=HOSTNAME... |
def test_model_before_dream(trained_data_prop, computed_data_prop, directory, prop_name='logP'):
plt.figure()
plt.scatter(trained_data_prop, computed_data_prop)
plt.xlabel(('Modelled ' + prop_name))
plt.ylabel(('Computed ' + prop_name))
name = (directory + '/test_model_before_dreaming')
plt.save... |
def register_model_architecture(model_name, arch_name):
def arch_override_from_yaml(args, arch):
root_dir = os.path.dirname(os.path.dirname(fairseq.__file__))
yaml_path = os.path.join(root_dir, 'config/model/{}.yaml'.format(arch))
if (not os.path.exists(yaml_path)):
raise Runtime... |
class QCBasisSet(_QCBase):
center_data: Mapping[(str, QCCenterData)]
atom_map: Sequence[str]
name: str
schema_version: (int | None) = None
schema_name: (str | None) = None
description: (str | None) = None
def from_dict(cls, data: dict[(str, Any)]) -> QCBasisSet:
center_data = {k: QCC... |
def _set_ie_mode():
import winreg
def get_ie_mode():
ie_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, 'Software\\Microsoft\\Internet Explorer')
try:
(version, type) = winreg.QueryValueEx(ie_key, 'svcVersion')
except:
(version, type) = winreg.QueryValueEx(ie_key,... |
def write_shell_script(dir: str, name: str, content: List[str]) -> str:
script_path = os.path.join(dir, name)
with open(script_path, 'w') as f:
f.write('#! /bin/bash\n')
for line in content:
f.write(f'''{line}
''')
f.write('\n')
os.chmod(script_path, 493)
return scrip... |
class InfLineLabel(TextItem):
def __init__(self, line, text='', movable=False, position=0.5, anchors=None, **kwds):
self.line = line
self.movable = movable
self.moving = False
self.orthoPos = position
self.format = text
self.line.sigPositionChanged.connect(self.valueC... |
(constants.InterfaceType.pxi, 'INSTR')
class PXIInstrument(PXICommon):
manufacturer_name: Attribute[str] = attributes.AttrVI_ATTR_MANF_NAME()
manufacturer_id: Attribute[int] = attributes.AttrVI_ATTR_MANF_ID()
model_name: Attribute[str] = attributes.AttrVI_ATTR_MODEL_NAME()
model_code: Attribute[int] = a... |
class TestWordInformationPreserved(MetricClassTester):
def test_word_information_preserved_with_valid_input(self) -> None:
self.run_class_implementation_tests(metric=WordInformationPreserved(), state_names={'correct_total', 'input_total', 'target_total'}, update_kwargs={'input': [['hello world', 'welcome to... |
def unwrap_assert_methods() -> None:
for patcher in _mock_module_patches:
try:
patcher.stop()
except RuntimeError as e:
if (str(e) == 'stop called on unstarted patcher'):
pass
else:
raise
_mock_module_patches[:] = []
_mock_m... |
def runUsernameLikePassword(args):
status = True
usernameLikePassword = UsernameLikePassword(args)
status = usernameLikePassword.connect(stopIfError=True)
if (args['run'] != None):
args['print'].title('MSSQL users have not the password identical to the username ?')
usernameLikePassword.t... |
(name='get_reviewers_vote_details')
def get_reviewers_vote_details(proposal, user):
v_detail = collections.namedtuple('v_detail', 'voter_nick vote_value vote_comment')
reviewers = ProposalSectionReviewer.objects.filter(proposal_section=proposal.proposal_section, conference_reviewer__conference=proposal.conferen... |
class S_VGG11(nn.Module):
def __init__(self, num_classes: int=10, T: int=3) -> None:
super(S_VGG11, self).__init__()
self.layer1 = Spiking(nn.Sequential(first_conv(3, 64, 3, stride=1, padding=1), nn.BatchNorm2d(64), IF()), T)
self.layer2 = Spiking(nn.Sequential(QuantConv2d(64, 128, 3, stride... |
def get_system_metadata(repo_root):
import git
return {'helsinki_git_sha': git.Repo(path=repo_root, search_parent_directories=True).head.object.hexsha, 'transformers_git_sha': git.Repo(path='.', search_parent_directories=True).head.object.hexsha, 'port_machine': socket.gethostname(), 'port_time': time.strftime(... |
class Test_average_gate_fidelity():
def test_identity(self, dimension):
id = qeye(dimension)
assert (average_gate_fidelity(id) == pytest.approx(1, abs=1e-12))
.parametrize('dimension', [2, 5, 10, 20])
def test_bounded(self, dimension):
tol = 1e-07
channel = rand_super_bcsz(di... |
def downloadSample(tmp_path_factory: pytest.TempPathFactory, sample: Dict[(str, str)]):
folder = os.path.splitext(os.path.basename(__file__))[0]
folder = tmp_path_factory.mktemp(folder)
SAMPLE_PATH_14d9f = (folder / sample['fileName'])
response = requests.get(sample['sourceUrl'], allow_redirects=True)
... |
class Registry(object):
def __init__(self, name):
self._name = name
self._obj_map = {}
def _do_register(self, name, obj):
assert (name not in self._obj_map), "An object named '{}' was already registered in '{}' registry!".format(name, self._name)
self._obj_map[name] = obj
def... |
def main_worker(gpu, ngpus_per_node, args):
global return_acc
args.gpu = gpu
if (args.gpu is not None):
print('Use GPU: {} for training'.format(args.gpu))
if args.distributed:
if ((args.dist_url == 'env://') and (args.rank == (- 1))):
args.rank = int(os.environ['RANK'])
... |
def test_zip():
a = Stream()
b = Stream()
c = sz.zip(a, b)
L = c.sink_to_list()
a.emit(1)
b.emit('a')
a.emit(2)
b.emit('b')
assert (L == [(1, 'a'), (2, 'b')])
d = Stream()
e = a.zip(b, d)
L2 = e.sink_to_list()
a.emit(1)
b.emit(2)
d.emit(3)
assert (L2 == [(... |
def test_license_by_id() -> None:
license = license_by_id('MIT')
assert (license.id == 'MIT')
assert (license.name == 'MIT License')
assert license.is_osi_approved
assert (not license.is_deprecated)
license = license_by_id('LGPL-3.0-or-later')
assert (license.id == 'LGPL-3.0-or-later')
a... |
def test_info_no_setup_pkg_info_no_deps(fixture_dir: FixtureDirGetter) -> None:
info = PackageInfo.from_directory((fixture_dir('inspection') / 'demo_no_setup_pkg_info_no_deps'), disable_build=True)
assert (info.name == 'demo')
assert (info.version == '0.1.0')
assert (info.requires_dist is None) |
def read_test_dataset(model_name):
model_path = ((TransphoneConfig.data_path / 'model') / model_name)
grapheme_vocab = Vocab.read((model_path / 'grapheme.vocab'))
phoneme_vocab = Vocab.read((model_path / 'phoneme.vocab'))
test_phoneme_lst = []
test_grapheme_lst = []
lang_lst = []
for lang_id... |
def get_logger(task, model_dir):
logger = logging.getLogger(task)
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(message)s')
fh = logging.FileHandler((((model_dir + '/') + task) + '.log'))
fh.setLevel(logging.INFO)
fh.setFormatter(formatter)
logger.addHandler(fh)
ch = lo... |
def test_ellipsis_replacing_str_key():
layouts = make_layouts(TestField('a_'), TestField('b'), name_mapping(name_style=NameStyle.UPPER, map=[('.*', ('data', ...))]), DEFAULT_NAME_MAPPING)
assert (layouts == Layouts(InputNameLayout(crown=InpDictCrown(map={'data': InpDictCrown(map={'A': InpFieldCrown('a_'), 'B': ... |
class OneFormerConfig(PretrainedConfig):
model_type = 'oneformer'
attribute_map = {'hidden_size': 'hidden_dim'}
def __init__(self, backbone_config: Optional[Dict]=None, ignore_value: int=255, num_queries: int=150, no_object_weight: int=0.1, class_weight: float=2.0, mask_weight: float=5.0, dice_weight: float... |
def main(argv):
parser = argparse.ArgumentParser(description='Submit jobs')
parser.add_argument('--job_type', type=str, default='S', help='Run single (S) or multiple (M) jobs in one experiment: S, M')
args = parser.parse_args()
sbatch_cfg = {'account': 'rrg-ashique', 'job-name': 'MERL_mc_dqn', 'time': '... |
def test_solver_direct_origin_dependency_with_extras_requested_by_other_package(solver: Solver, repo: Repository, package: ProjectPackage, fixture_dir: FixtureDirGetter) -> None:
pendulum = get_package('pendulum', '2.0.3')
cleo = get_package('cleo', '1.0.0')
demo_foo = get_package('demo-foo', '1.2.3')
d... |
def parse_repository_name(include_tag=False, ns_kwarg_name='namespace_name', repo_kwarg_name='repo_name', tag_kwarg_name='tag_name', incoming_repo_kwarg='repository'):
def inner(func):
(func)
def wrapper(*args, **kwargs):
try:
repo_name_components = parse_namespace_reposi... |
class FlowchartWidget(dockarea.DockArea):
def __init__(self, chart, ctrl):
dockarea.DockArea.__init__(self)
self.chart = chart
self.ctrl = ctrl
self.hoverItem = None
self.view = FlowchartGraphicsView.FlowchartGraphicsView(self)
self.viewDock = dockarea.Dock('view', si... |
class ClusterUtilization():
def __init__(self, cluster_resources: Dict[(str, Any)], available_resources: Dict[(str, Any)]):
used_resources = {}
for key in cluster_resources:
if ((isinstance(cluster_resources[key], float) or isinstance(cluster_resources[key], int)) and (key in available_r... |
class TestMatrixTransport(MatrixTransport):
__test__ = False
def __init__(self, config: MatrixTransportConfig, environment: Environment) -> None:
super().__init__(config, environment)
self.broadcast_messages: DefaultDict[(str, List[Message])] = defaultdict(list)
self.send_messages: Defau... |
class RandomAugmentation(nn.Module):
def __init__(self, augmentation: nn.Module, p: float=0.5, same_on_batch: bool=False):
super().__init__()
self.prob = p
self.augmentation = augmentation
self.same_on_batch = same_on_batch
def forward(self, images: Tensor) -> Tensor:
is_... |
def dwsconv3x3_block(in_channels, out_channels, stride=1, padding=1, dilation=1, bias=False, bn_eps=1e-05, activation=(lambda : nn.ReLU(inplace=True))):
return DwsConvBlock(in_channels=in_channels, out_channels=out_channels, kernel_size=3, stride=stride, padding=padding, dilation=dilation, bias=bias, bn_eps=bn_eps,... |
class TestFmtCols(object):
def setup_method(self):
self.in_str = np.arange(0, 40, 1).astype(str)
self.in_kwargs = {'ncols': 5, 'max_num': 40, 'lpad': None}
self.out_str = None
self.filler_row = (- 1)
self.ncols = None
self.nrows = None
self.lpad = (len(self.in... |
class ApplicationsTab(QWidget):
def __init__(self, fileInfo, parent=None):
super(ApplicationsTab, self).__init__(parent)
topLabel = QLabel('Open with:')
applicationsListBox = QListWidget()
applications = []
for i in range(1, 31):
applications.append(('Application ... |
def parse_hitran_file(fname, columns, count=(- 1), output='pandas'):
data = _read_hitran_file(fname, columns, count=1, linereturnformat='a2')
linereturnformat = _get_linereturnformat(data, columns, fname)
data = _read_hitran_file(fname, columns, count, linereturnformat)
df = _ndarray2df(data, columns, l... |
def ql_syscall_socket(ql: Qiling, domain: int, socktype: int, protocol: int):
idx = next((i for i in range(NR_OPEN) if (ql.os.fd[i] is None)), (- 1))
if (idx != (- 1)):
vsock_type = socktype
hsock_type = __host_socket_type(vsock_type, ql.arch.type)
ql.log.debug(f'Converted emulated socke... |
def masked_mae_loss(scaler, null_val):
def loss(preds, labels):
if scaler:
preds = scaler.inverse_transform(preds)
labels = scaler.inverse_transform(labels)
mae = masked_mae_torch(preds=preds, labels=labels, null_val=null_val)
return mae
return loss |
def simus(matrix, objectives, b=None, rank_by=1, solver='pulp'):
transposed_matrix = matrix.T
b = np.asarray(b)
if (None in b):
mins = np.min(transposed_matrix, axis=1)
maxs = np.max(transposed_matrix, axis=1)
auto_b = np.where((objectives == Objective.MIN.value), mins, maxs)
... |
def setup_optimizer(rc_explainer, pro_flag=False):
params = list(rc_explainer.edge_action_rep_generator.parameters())
if pro_flag:
for i_explainer in rc_explainer.edge_action_prob_generator:
params += list(i_explainer.parameters())
else:
params += list(rc_explainer.edge_action_pr... |
def plot_waveform_to_numpy(waveform):
(fig, ax) = plt.subplots(figsize=(12, 3))
ax.plot()
ax.plot(range(len(waveform)), waveform, linewidth=0.1, alpha=0.7, color='blue')
plt.xlabel('Samples')
plt.ylabel('Amplitude')
plt.ylim((- 1), 1)
plt.tight_layout()
fig.canvas.draw()
data = save_... |
class SSLCertificate(object):
def __init__(self, openssl_cert):
self.openssl_cert = openssl_cert
def validate_private_key(self, private_key_path):
context = OpenSSL.SSL.Context(OpenSSL.SSL.TLSv1_METHOD)
context.use_certificate(self.openssl_cert)
try:
context.use_priva... |
class TruncatingMemoryHandler(logging.handlers.MemoryHandler):
target: Optional['logging.Handler']
def __init__(self):
logging.handlers.MemoryHandler.__init__(self, capacity=1, flushLevel=logging.DEBUG)
self.max_size = 100
self.num_messages_seen = 0
self.__never_dumped = True
... |
def _get_test_content_areadef():
data = {}
proj = 'data/mtg_geos_projection'
attrs = {'sweep_angle_axis': 'y', 'perspective_point_height': '.0', 'semi_major_axis': '6378137.0', 'longitude_of_projection_origin': '0.0', 'inverse_flattening': '298.', 'units': 'm'}
data[proj] = xr.DataArray(0, dims=(), attr... |
class AttModule(nn.Module):
def __init__(self, N):
super(AttModule, self).__init__()
self.forw_att = AttentionBlock(N)
self.back_att = AttentionBlock(N)
def forward(self, x, rev=False):
if (not rev):
return self.forw_att(x)
else:
return self.back_a... |
def download_voc(path, overwrite=False):
_DOWNLOAD_URLS = [(' '34ed68851bce2a36e2a223fa52c661d592c66b3c'), (' '41a8d6e12baa5ab18ee7f8f8029b9e11805b4ef1'), (' '4e443f8a2eca6b1dac8a6c57641b67dd40621a49')]
makedirs(path)
for (url, checksum) in _DOWNLOAD_URLS:
filename = download(url, path=path, overwri... |
def test_switch_last():
with pytest.raises(Call) as err:
switch(context=Context({'list': 'sg1', 'case1': False, 'case2': True, 'fg': 'fgv', 'switch': [{'case': '{case1}', 'call': '{list}'}, {'case': '{case2}', 'call': 'sg2'}]}), name='blah')
cof = err.value
assert isinstance(cof, Call)
assert (c... |
class DMA_CR(IntEnum):
EN = (1 << 0)
TCIE = (1 << 1)
HTIE = (1 << 2)
TEIE = (1 << 3)
DIR = (1 << 4)
CIRC = (1 << 5)
PINC = (1 << 6)
MINC = (1 << 7)
PSIZE_0 = (1 << 8)
PSIZE_1 = (2 << 8)
PSIZE = (3 << 8)
MSIZE_0 = (1 << 10)
MSIZE_1 = (2 << 10)
MSIZE = (3 << 10)
... |
class LatexyzPreviewMath(sublime_plugin.EventListener):
def on_activated_async(self, view):
self.set_template_preamble(view)
def on_post_save_async(self, view):
self.set_template_preamble(view)
def set_template_preamble(self, view):
try:
pt = view.sel()[0].end()
e... |
def get_agent_from_batch(features, device, vocab):
(agent_input_ids, agent_output_ids, agent_lens) = features[3]
agent_padding_mask = agent_input_ids.ne(vocab.token2idx('<PAD>')).float()
max_agent_len = max(agent_lens)
agent_input_ids = agent_input_ids.to(device)
agent_padding_mask = agent_padding_m... |
class FetcherTestCase(WithResponses, WithMakeAlgo, ZiplineTestCase):
START_DATE = pd.Timestamp('2006-01-03', tz='utc')
END_DATE = pd.Timestamp('2006-12-29', tz='utc')
SIM_PARAMS_DATA_FREQUENCY = 'daily'
DATA_PORTAL_USE_MINUTE_DATA = False
BENCHMARK_SID = None
def make_equity_info(cls):
r... |
class RatingBox(Gtk.VBox):
def __init__(self):
super().__init__(self)
self.thumb_ups = 1
self.thumb_downs = 1
self.title = Gtk.Label('')
self.title.set_line_wrap(True)
self.title.set_lines(2)
hbox = Gtk.HBox()
self.upvote = ToggleButton('')
sel... |
def get_val_transformations(p):
if (p['val_db_name'] == 'VOCSegmentation'):
import data.dataloaders.fblib_transforms as fblib_tr
return transforms.Compose([fblib_tr.FixedResize(resolutions={'image': tuple((512, 512)), 'semseg': tuple((512, 512))}, flagvals={'image': cv2.INTER_CUBIC, 'semseg': cv2.IN... |
def xml_parse(father, page_tree, flag=1):
if flag:
for child in father:
try:
tag_attr = child.attrib['xpath']
except:
tag_attr = ''
if ((child.text is None) or ('\n' in child.text)):
tag_text = ''
else:
... |
class DicomLocation(db.Model):
__tablename__ = 'DicomLocation'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(128))
host = db.Column(db.String(128), nullable=False)
port = db.Column(db.Integer, nullable=False)
ae_title = db.Column(db.String(128))
owner_key = db.Colum... |
class Effect446(BaseEffect):
type = 'passive'
def handler(fit, container, context, projectionRange, **kwargs):
level = (container.level if ('skill' in context) else 1)
fit.ship.boostItemAttr('shieldCapacity', (container.getModifiedItemAttr('shieldCapacityBonus') * level), **kwargs) |
def _print_panoptic_results(pq_res):
headers = ['', 'PQ', 'SQ', 'RQ', '#categories']
data = []
for name in ['All', 'Things', 'Stuff']:
row = (([name] + [(pq_res[name][k] * 100) for k in ['pq', 'sq', 'rq']]) + [pq_res[name]['n']])
data.append(row)
table = tabulate(data, headers=headers, t... |
def datatype(name, static_fields):
_ordering
class DataType(object):
__name__ = name
def __init__(self, **kwargs):
self._db_id = kwargs.pop('db_id', None)
self._inputs = kwargs.pop('inputs', None)
self._fields = kwargs
for name in static_fields:
... |
.filterwarnings('ignore:The input coordinates to pcolor:UserWarning')
.parametrize('color, args', [('sequential', {}), ('diverging', {}), ('sequential', {'projection': '3d'}), ('sequential', {'colorbar': True})])
def test_plot_spin_distribution(color, args):
j = 5
psi = qutip.spin_coherent(j, (np.random.rand() ... |
class Decoder(nn.Module):
def __init__(self, state_embed_size, hidden_size):
super().__init__()
self.state_embed_size = state_embed_size
self.hidden_size = hidden_size
self.decoder_lins = nn.Sequential(nn.Linear(state_embed_size, self.hidden_size), nn.ReLU(True), nn.Linear(self.hidde... |
def get_doc(project, source_code, offset, resource=None, maxfixes=1):
fixer = fixsyntax.FixSyntax(project, source_code, resource, maxfixes)
pyname = fixer.pyname_at(offset)
if (pyname is None):
return None
pyobject = pyname.get_object()
return PyDocExtractor().get_doc(pyobject) |
class RerankingEvaluator(SentenceEvaluator):
def __init__(self, samples, mrr_at_k: int=10, name: str='', write_csv: bool=True, similarity_fct=cos_sim):
self.samples = samples
self.name = name
self.mrr_at_k = mrr_at_k
self.similarity_fct = cos_sim
if isinstance(self.samples, d... |
class TuckER(Virtue_Triple):
def __init__(self, num_ps, num_qs, num_rs, embedding_dim, reg):
super(TuckER, self).__init__(num_ps, num_qs, num_rs, embedding_dim, reg)
w = torch.empty(embedding_dim, embedding_dim, embedding_dim)
nn.init.xavier_uniform_(w)
self._W = torch.nn.Parameter(t... |
def get_features(commit_hash, return_dict=False):
(title, body, files_changed) = (commit_title(commit_hash), commit_body(commit_hash), commit_files_changed(commit_hash))
pr_number = parse_pr_number(body, commit_hash, title)
labels = []
if (pr_number is not None):
labels = gh_labels(pr_number)
... |
class CRLNumber(ExtensionType):
oid = ExtensionOID.CRL_NUMBER
def __init__(self, crl_number: int) -> None:
if (not isinstance(crl_number, int)):
raise TypeError('crl_number must be an integer')
self._crl_number = crl_number
def __eq__(self, other: object) -> bool:
if (not... |
def test_default(hatch, helpers, temp_dir, config_file):
config_file.model.template.plugins['default']['src-layout'] = False
config_file.save()
project_name = 'My.App'
with temp_dir.as_cwd():
result = hatch('new', project_name)
assert (result.exit_code == 0), result.output
project_path =... |
.xfail(reason="doesn't match, since pivot implicitly sorts")
def test_pivot_wide_long_wide():
df = pd.DataFrame({'name': ['Wilbur', 'Petunia', 'Gregory'], 'a': [67, 80, 64], 'b': [56, 90, 50]})
result = df.pivot_longer(column_names=['a', 'b'], names_to='drug', values_to='heartrate')
result = result.pivot_wi... |
class TRECEval(object):
def __init__(self, task_path, seed=1111):
logging.info('***** Transfer task : TREC *****\n\n')
self.seed = seed
self.train = self.loadFile(os.path.join(task_path, 'train_5500.label'))
self.test = self.loadFile(os.path.join(task_path, 'TREC_10.label'))
def ... |
def convert_t5x_checkpoint_to_flax(t5x_checkpoint_path, config_name, flax_dump_folder_path):
config = AutoConfig.from_pretrained(config_name)
flax_model = FlaxAutoModelForSeq2SeqLM.from_config(config=config)
t5x_model = checkpoints.load_t5x_checkpoint(t5x_checkpoint_path)
split_mlp_wi = ('wi_0' in t5x_m... |
class TestGlobalVariablesChecker(pylint.testutils.CheckerTestCase):
CHECKER_CLASS = GlobalVariablesChecker
def test_no_message_global_type_alias_assignment_builtin(self):
src = '\n MyType = list[list[list[int]]]\n '
mod = astroid.parse(src)
with self.assertNoMessages():
... |
def add_spectra(s1, s2, var=None, force=False):
if (var is None):
try:
var = _get_unique_var(s2, var, inplace=False)
except KeyError:
var = _get_unique_var(s1, var, inplace=False)
if (var not in s1.get_vars()):
raise KeyError('Variable {0} not in Spectrum {1}'.for... |
def test_assert_child_key_has_value_raises_no_child():
context = Context({'parent': {'child': 1}})
with pytest.raises(KeyNotInContextError) as err:
context.assert_child_key_has_value('parent', 'XchildX', 'arb')
assert (str(err.value) == "context['parent']['XchildX'] doesn't exist. It must exist for ... |
class TestPredictionInterpolation():
.parametrize(('obs_time', 'expected'), [((- 1), np.nan), (1.5, 2.5), (5, np.nan)])
def test_interpolate_continuous(self, obs_time, expected):
prediction_times = np.array([0, 1, 2, 3])
predicted_values = np.array([1, 2, 3, 4])
res = nav.interpolate_con... |
class ClassNameFieldTest(StringTestMixin, BaseFieldTestMixin, FieldTestCase):
field_class = fields.ClassName
def test_simple_string_field(self):
field = fields.ClassName()
assert (not field.required)
assert (not field.discriminator)
assert (field.__schema__ == {'type': 'string'})... |
class Time2DistanceGetter(SmoothPointGetter):
def _getCommonData(self, miscParams, src, tgt):
return {'maxSpeed': src.getMaxVelocity(), 'mass': src.item.ship.getModifiedItemAttr('mass'), 'agility': src.item.ship.getModifiedItemAttr('agility')}
def _calculatePoint(self, x, miscParams, src, tgt, commonDat... |
_optimizer('adamax')
class FairseqAdamax(LegacyFairseqOptimizer):
def __init__(self, args, params):
super().__init__(args)
self._optimizer = Adamax(params, **self.optimizer_config)
def add_args(parser):
parser.add_argument('--adamax-betas', default='(0.9, 0.999)', metavar='B', help='beta... |
def driver_kwargs(request, capabilities, chrome_options, chrome_service, driver_args, driver_class, driver_log, driver_path, firefox_options, firefox_service, ie_options, ie_service, edge_options, edge_service, safari_options, safari_service, remote_options, pytestconfig):
kwargs = {}
driver = getattr(drivers, ... |
class MobileNetV3Features(nn.Module):
def __init__(self, block_args, out_indices=(0, 1, 2, 3, 4), feature_location='bottleneck', in_chans=3, stem_size=16, fix_stem=False, output_stride=32, pad_type='', round_chs_fn=round_channels, se_from_exp=True, act_layer=None, norm_layer=None, se_layer=None, drop_rate=0.0, drop... |
(HAS_TV_TUPLE)
.parametrize('tpl', [tuple, Tuple])
def test_type_var_tuple_generic_post(tpl):
from typing import TypeVarTuple, Unpack
ShapeT = TypeVarTuple('ShapeT')
DType = TypeVar('DType')
class PostArray(Generic[(Unpack[ShapeT], DType)]):
pass
assert_normalize(PostArray, PostArray, [norma... |
def preformat_MalNetTiny(dataset_dir, feature_set):
if (feature_set in ['none', 'Constant']):
tf = T.Constant()
elif (feature_set == 'OneHotDegree'):
tf = T.OneHotDegree()
elif (feature_set == 'LocalDegreeProfile'):
tf = T.LocalDegreeProfile()
else:
raise ValueError(f'Une... |
((pty is None), 'pty module not supported on platform')
class Test_Pty_Serial_Open(unittest.TestCase):
def setUp(self):
(self.master, self.slave) = pty.openpty()
def test_pty_serial_open_slave(self):
with serial.Serial(os.ttyname(self.slave), timeout=1) as slave:
pass
def test_pt... |
class TestOutermorphismMatrix():
def test_invariants(self, g2):
(e1, e2) = g2.basis_vectors_lst
matrix = np.array([[0, 1], [(- 1), 0]])
f = transformations.OutermorphismMatrix(matrix, g2)
assert (f(e1) == (- e2))
assert (f(e2) == e1)
assert (f((e1 ^ e2)) == (f(e1) ^ f... |
class AutoConfigTest(unittest.TestCase):
def test_module_spec(self):
self.assertIsNotNone(transformers.models.auto.__spec__)
self.assertIsNotNone(importlib.util.find_spec('transformers.models.auto'))
def test_config_from_model_shortcut(self):
config = AutoConfig.from_pretrained('bert-bas... |
def create_db(filename: str, create_file: bool=True) -> True:
def create(filename: str, data: str) -> None:
with open(filename, 'w') as db_file:
db_file.write(data)
if filename.endswith('.json'):
if (create_file and (not os.path.exists(filename))):
create(filename, json.d... |
def test_nested_process_search_unsupported_field(cortex_product: CortexXDR):
criteria = {'foo': 'bar'}
cortex_product._queries = {}
cortex_product.log = logging.getLogger('pytest_surveyor')
cortex_product.nested_process_search(Tag('unsupported_field'), criteria, {})
assert (len(cortex_product._queri... |
class VersionTest(unittest.TestCase):
def test_can_get_version(self) -> None:
import torchx.pipelines.kfp
self.assertIsNotNone(torchx.pipelines.kfp.__version__)
def test_kfp_1x(self) -> None:
import torchx.pipelines.kfp
with patch('kfp.__version__', '2.0.1'):
with sel... |
def parse(experiment_path, run, max_steps):
(run_rl_objective, run_cost_objective, run_sum_costs, run_timesteps) = ([], [], [], [])
files = list(Path(experiment_path).glob(os.path.join(run, 'events.out.tfevents.*')))
last_time = (- 1)
all_sum_costs = 0
for file in sorted(files, key=numerical_sort):
... |
class QRangeSlider(QtWidgets.QWidget, Ui_Form):
endValueChanged = QtCore.pyqtSignal(int)
maxValueChanged = QtCore.pyqtSignal(int)
minValueChanged = QtCore.pyqtSignal(int)
startValueChanged = QtCore.pyqtSignal(int)
_SPLIT_START = 1
_SPLIT_END = 2
minValueChanged = QtCore.pyqtSignal(int)
m... |
.parametrize('args', [['dir1', 'dir2', '-v'], ['dir1', '-v', 'dir2'], ['dir2', '-v', 'dir1'], ['-v', 'dir2', 'dir1']])
def test_consider_args_after_options_for_rootdir(pytester: Pytester, args: List[str]) -> None:
root = pytester.mkdir('myroot')
d1 = root.joinpath('dir1')
d1.mkdir()
d2 = root.joinpath('... |
class TouchKeyboard(object):
YELLOW = const(65504)
GREEN = const(2016)
KEYS = ((('q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'), ('a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'), ('\t', 'z', 'x', 'c', 'v', 'b', 'n', 'm', '\x08', '\x08'), ('\n', ' ', '\r')), (('Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P'... |
.skipif((not HAVE_DEPS_FOR_RESOURCE_ESTIMATES), reason='pyscf and/or jax not installed.')
.slow
def test_kpoint_thc_reg_gamma():
cell = gto.Cell()
cell.atom = '\n C 0. 0. 0.\n C 1. 1. 1.\n '
cell.basis = 'gth-szv'
cell.pseudo = 'gth-hf-rev'
cell.a = '\n 0., 3., 3.\n 3., 0., 3.... |
class TestData(unittest.TestCase):
(generatePackageSpecifiers)
def test_using_valid_specifier_sets(self, pkg, spec):
message = f'Bad specifier for {pkg}: {spec!r}'
try:
specifier_set = SpecifierSet(spec)
except InvalidSpecifier:
specifier_set = None
self.f... |
def work_block(args):
try:
(cls, store_dir, step, iblock, shared, force) = args
if ((store_dir, step) not in g_builders):
g_builders[(store_dir, step)] = cls(store_dir, step, shared, force=force)
builder = g_builders[(store_dir, step)]
builder.work_block(iblock)
excep... |
class Seq_User_Act(Seq_User):
def __init__(self, nlg_sample, nlg_template):
super().__init__(nlg_sample=nlg_sample, nlg_template=nlg_template)
self._set_initial_state()
self._set_initial_goal_dic()
cfg.init_handler('tsdf-usr_act')
cfg.dataset = 'usr_act'
if cfg.cuda:
... |
def normalize(x):
if (not isinstance(x, str)):
x = x.decode('utf8', errors='ignore')
x = ''.join((c for c in unicodedata.normalize('NFKD', x) if (unicodedata.category(c) != 'Mn')))
x = re.sub('[ `]', "'", x)
x = re.sub('[]', '"', x)
x = re.sub('[]', '-', x)
while True:
old_x = x
... |
def fund_node(token_result: Callable[([], Contract)], proxy_manager: ProxyManager, to_address: Address, amount: TokenAmount) -> None:
token_contract = token_result()
token_proxy = proxy_manager.token(TokenAddress(to_canonical_address(token_contract.address)), BLOCK_ID_LATEST)
token_proxy.transfer(to_address... |
def bind_texture(texture):
if (not getattr(texture, 'image', None)):
texture.image = load_image(texture.find())
glEnable(texture.image.target)
glBindTexture(texture.image.target, texture.image.id)
if (texture.options.clamp == 'on'):
glTexParameterf(texture.image.target, GL_TEXTURE_WRAP_S... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.