code stringlengths 281 23.7M |
|---|
class TestRunnerWrapper():
def __init__(self, runner: DocTestRunner):
self._runner = runner
def __getattr__(self, name: str) -> Any:
return getattr(self._runner, name)
def run(self, test: DocTest, *args: Any, **kwargs: Any) -> Any:
for ex in test.examples:
ex.source = tes... |
def create_rss_feed(doctree_dir: Path, output_dir: Path):
last_build_date = _format_rfc_2822(dt.datetime.now(dt.timezone.utc))
items = '\n'.join(_generate_items(Path(doctree_dir)))
output = f'''<?xml version='1.0' encoding='UTF-8'?>
<rss xmlns:atom=" xmlns:content=" version="2.0">
<channel>
<title>New... |
def test_call_invalid_selector(deploy_client: JSONRPCClient) -> None:
(contract_proxy, _) = deploy_rpc_test_contract(deploy_client, 'RpcTest')
address = contract_proxy.address
assert (len(deploy_client.web3.eth.get_code(address)) > 0)
data = decode_hex(get_transaction_data(deploy_client.web3, contract_p... |
class ExGaussianRV(RandomVariable):
name = 'exgaussian'
ndim_supp = 0
ndims_params = [0, 0, 0]
dtype = 'floatX'
_print_name = ('ExGaussian', '\\operatorname{ExGaussian}')
def rng_fn(cls, rng, mu, sigma, nu, size=None) -> np.ndarray:
return np.asarray((rng.normal(mu, sigma, size=size) + r... |
def get_next_arguments(action, type='input'):
req = []
non_req = []
if (type == 'input'):
for (k, v) in action.signature.inputs.items():
if (not v.has_default()):
req.append([k, v.qiime_type])
else:
non_req.append([('.' + k), v.qiime_type])
... |
class BackboneEncoder(Module):
def __init__(self, num_layers, mode='ir', n_styles=18, opts=None):
super(BackboneEncoder, self).__init__()
assert (num_layers in [50, 100, 152]), 'num_layers should be 50,100, or 152'
assert (mode in ['ir', 'ir_se']), 'mode should be ir or ir_se'
blocks... |
class UseFunctionTest(unittest.TestCase):
def setUp(self):
super().setUp()
self.project = testutils.sample_project()
self.mod1 = testutils.create_module(self.project, 'mod1')
self.mod2 = testutils.create_module(self.project, 'mod2')
def tearDown(self):
testutils.remove_pr... |
class GraphSearchUtils():
def __init__(self, model: tf.Graph, start_op_names: Union[(str, List[str])], output_op_names: Union[(str, List[str])]):
if isinstance(start_op_names, str):
start_op_names = [start_op_names]
if isinstance(output_op_names, str):
output_op_names = [outp... |
class Task(BaseModel):
testcase_name: str
task_mode: str = 'normal'
custom_strategies: List[List[Any]] = []
parallel_workers: int = multiprocessing.cpu_count()
api_addresses: List[str] = []
api_timeout: int = 30000
net_ordering_evaluation_mode: int = 2
droute_end_iter: int = (- 1) |
class BasicLayer(nn.Module):
def __init__(self, dim, out_dim, input_resolution, depth, num_heads, window_size, mlp_ratio=4.0, qkv_bias=True, qk_scale=None, drop=0.0, attn_drop=0.0, drop_path=0.0, norm_layer=nn.LayerNorm, upsample=None):
super().__init__()
self.dim = dim
self.input_resolution... |
.parametrize('proc_name', ['s1', 's2', 's3'])
def test_terminate_no_pid(tcp_port, proc_name, xprocess):
class Starter(ProcessStarter):
pattern = 'started'
args = [sys.executable, server_path, tcp_port]
xprocess.ensure(proc_name, Starter)
info = xprocess.getinfo(proc_name)
(pid, info.pid)... |
class TransformerLayer(nn.Module):
def __init__(self, args):
super(TransformerLayer, self).__init__()
self.self_attn = MultiHeadedAttention(args.hidden_size, args.heads_num, args.dropout)
self.dropout_1 = nn.Dropout(args.dropout)
self.layer_norm_1 = LayerNorm(args.hidden_size)
... |
def make_loader(split, dst_cls=DatasetAllTasks, repeat=None, is_training=True, unlabeled=False, transforms_tr=None, transforms_val=None):
if is_training:
dst = dst_cls(split=split, repeat=repeat, unlabeled=unlabeled, transform=transforms_tr, task=args.task, num_cls=config.num_cls, is_2d=True)
return... |
def test_fixture_order_respects_scope(pytester: Pytester) -> None:
pytester.makepyfile("\n import pytest\n\n data = {}\n\n (scope='module')\n def clean_data():\n data.clear()\n\n (autouse=True)\n def add_data():\n data.update(value=True)\n\n .us... |
def generate_all_rotation_angles(increment):
n = round(((2 * math.pi) / increment))
print(n, 'rotations along each axis')
print('generating template rotations...')
angles = []
phi = 0.0
theta = 0.0
psi = 0.0
for i in range(n):
phi = (i * increment)
for j in range(n):
... |
class TestCommonAncestor():
def test_has_ancestor(self, tmp_path: Path) -> None:
fn1 = (((tmp_path / 'foo') / 'bar') / 'test_1.py')
fn1.parent.mkdir(parents=True)
fn1.touch()
fn2 = (((tmp_path / 'foo') / 'zaz') / 'test_2.py')
fn2.parent.mkdir(parents=True)
fn2.touch()... |
class S3():
def __init__(self, session):
self._session = session
self._s3 = session.client('s3')
def cp(self, target_path, bucket, key):
target_basename = os.path.basename(target_path)
if os.path.isdir(target_path):
tmpdir = tempfile.mkdtemp(prefix='petctl_')
... |
class RotatedDecoder(LatticeDecoder):
encoder_type = XXZZQubit
syndrome_graph_keys = ['X', 'Z']
def _params_validation(self):
super()._params_validation()
if isinstance(self.params['d'], Number):
d = int(self.params['d'])
self.params['d'] = (d, d)
if (len(self... |
class TypeCheckSuite(DataSuite):
files = typecheck_files
def run_case(self, testcase: DataDrivenTestCase) -> None:
if ((lxml is None) and (os.path.basename(testcase.file) == 'check-reports.test')):
pytest.skip('Cannot import lxml. Is it installed?')
incremental = (('incremental' in t... |
def validate_sort_fields(sort_fields):
descending = set()
def sort_order_filter(name):
if name.startswith('-'):
name = name[1:]
descending.add(name)
return name
sort_fields = validate_field_list(sort_fields, name_filter=sort_order_filter)
log.debug(('Sorting order... |
class TestHarness(Component):
def construct(s, Type, q, src_msgs, sink_msgs, src_interval, sink_interval):
s.src = TestSrcCL(Type, src_msgs, interval_delay=src_interval)
s.q = q
s.sink = TestSinkCL(Type, sink_msgs, interval_delay=sink_interval)
connect(s.src.send, s.q.enq)
co... |
def create_dataset(input_folder: str, output_folder: str, target_transform):
dataset = DSprites(root=input_folder, target_transform=target_transform)
mapper = DSpritesMapper(dataset, output_path=output_folder)
loader = DataLoader(mapper, num_workers=8, batch_size=1, collate_fn=(lambda x: x[0]))
with tqd... |
def _add_variable_to_netcdf_file(nc, var_name, var_info):
v = nc.createVariable(var_name, var_info['data'].dtype.str[1:], dimensions=var_info['dim_labels'], fill_value=var_info.get('fill_value'))
v[:] = var_info['data']
for (attr_key, attr_val) in var_info['attrs'].items():
if isinstance(attr_val, (... |
def groups_target(tmp_path):
filenames = ['older.c', 'older.h', 'target.o', 'newer.c', 'newer.h']
paths = [(tmp_path / name) for name in filenames]
for (mtime, path) in enumerate(paths):
path.write_text('', encoding='utf-8')
os.utime(path, (mtime, mtime))
return types.SimpleNamespace(old... |
class Continuation(Model):
project = models.ForeignKey('Project', on_delete=models.CASCADE, related_name='+', verbose_name=_('Project'), help_text=_('The project for this continuation.'))
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='+', verbose_name=_('User'), help_... |
class Tpattern(TestCase):
def test_empty(self):
self.assertEqual(util.pattern(''), '')
def test_basic(self):
self.assertEqual(util.pattern('<title>'), 'Title')
def test_basic_nocap(self):
self.assertEqual(util.pattern('<title>', False), 'title')
def test_internal(self):
s... |
class KnownValues(unittest.TestCase):
def test_orth(self):
numpy.random.seed(10)
n = 100
a = numpy.random.random((n, n))
s = numpy.dot(a.T, a)
c = orth.lowdin(s)
self.assertTrue(numpy.allclose(reduce(numpy.dot, (c.T, s, c)), numpy.eye(n)))
x1 = numpy.dot(a, c)... |
('a paragraph format having {prop_name} set {setting}')
def given_a_paragraph_format_having_prop_set(context, prop_name, setting):
style_name = {'to inherit': 'Normal', 'On': 'Base', 'Off': 'Citation'}[setting]
document = Document(test_docx('sty-known-styles'))
context.paragraph_format = document.styles[sty... |
def syllabify(language, word):
if (type(word) == str):
word = word.split()
syllables = []
internuclei = []
for phoneme in word:
phoneme = phoneme.strip()
if (phoneme == ''):
continue
stress = None
if phoneme[(- 1)].isdigit():
stress = int(p... |
def test_run_with_fill_defaults_adds_required_field(run_line, tmp_path):
schemafile = (tmp_path / 'schema.json')
schemafile.write_text(json.dumps(SCHEMA))
doc = (tmp_path / 'instance.json')
doc.write_text(json.dumps(MISSING_FIELD_DOC))
result_without_fill_defaults = run_line(['check-jsonschema', '--... |
def _update(input: torch.Tensor, target: torch.Tensor, from_logits: bool, weight: Optional[torch.Tensor]=None) -> Tuple[(torch.Tensor, torch.Tensor, torch.Tensor)]:
if from_logits:
cross_entropy = F.binary_cross_entropy_with_logits(input, target, weight, reduction='none').sum(dim=(- 1))
else:
cr... |
class HotpotFullIterativeDataset(QuestionAndParagraphsDataset):
def __init__(self, questions: List[HotpotQuestion], batcher: ListBatcher, bridge_as_comparison=False):
self.questions = questions
self.batcher = batcher
self.bridge_as_comparison = bridge_as_comparison
self.samples = sel... |
class TrainGenerator(Dataset):
def __init__(self, args_config, graph):
self.args_config = args_config
self.graph = graph
self.user_dict = graph.train_user_dict
self.exist_users = list(graph.exist_users)
self.low_item_index = graph.item_range[0]
self.high_item_index = ... |
def capture_regexes():
regexes = []
real_compile = re.compile
real_search = re.search
real_sub = re.sub
def capture_compile(regex, flags=0):
regexes.append((regex, flags))
return real_compile(regex, flags)
def capture_search(regex, target, flags=0):
regexes.append((regex,... |
def treutler_ahlrichs(n, *args, **kwargs):
r = numpy.empty(n)
dr = numpy.empty(n)
step = (numpy.pi / (n + 1))
ln2 = (1 / numpy.log(2))
for i in range(n):
x = numpy.cos(((i + 1) * step))
r[i] = (((- ln2) * ((1 + x) ** 0.6)) * numpy.log(((1 - x) / 2)))
dr[i] = ((((step * numpy.... |
def load_question_set(qs_file_name, append_hat_for_LL=True, convert_svs_pattern=True):
with open(qs_file_name) as f:
lines = f.readlines()
binary_qs_index = 0
continuous_qs_index = 0
binary_dict = {}
numeric_dict = {}
LL = re.compile(re.escape('LL-'))
for line in lines:
line ... |
def test_async_subproc_command_no_stdout_on_save():
with pytest.raises(ContextError) as err:
Command('arb', is_save=True, stdout='in')
assert (str(err.value) == "You can't set `stdout` or `stderr` when `save` is True.")
with pytest.raises(ContextError) as err:
Command('arb', is_save=True, st... |
_constructor
class W_Character(W_Object):
_attrs_ = _immutable_fields_ = ['value']
errorname = 'char'
def __init__(self, val):
assert isinstance(val, unicode)
self.value = val
def tostring(self):
from pypy.objspace.std.bytesobject import string_escape_encode
return ('#\\%... |
class RDP(BaseDeepAD):
def __init__(self, epochs=100, batch_size=64, lr=0.001, rep_dim=128, hidden_dims='100,50', act='LeakyReLU', bias=False, epoch_steps=(- 1), prt_steps=10, device='cuda', verbose=2, random_state=42):
super(RDP, self).__init__(model_name='RDP', epochs=epochs, batch_size=batch_size, lr=lr,... |
class IPS120_10(OxfordInstrumentsBase):
_SWITCH_HEATER_HEATING_DELAY = 20
_SWITCH_HEATER_COOLING_DELAY = 20
_SWITCH_HEATER_SET_VALUES = {False: 0, True: 1, 'Force': 2}
_SWITCH_HEATER_GET_VALUES = {0: False, 1: True, 2: False, 5: 'Heater fault, low heater current', 8: 'No switch fitted'}
def __init__... |
class FC6_Monitor(FC3_Monitor):
removedKeywords = FC3_Monitor.removedKeywords
removedAttrs = FC3_Monitor.removedAttrs
def __init__(self, writePriority=0, *args, **kwargs):
FC3_Monitor.__init__(self, writePriority, *args, **kwargs)
self.probe = kwargs.get('probe', True)
def __str__(self):... |
def _create_isolated_env_virtualenv(path: str) -> tuple[(str, str)]:
import virtualenv
cmd = [str(path), '--no-setuptools', '--no-wheel', '--activators', '']
result = virtualenv.cli_run(cmd, setup_logging=False)
executable = str(result.creator.exe)
script_dir = str(result.creator.script_dir)
ret... |
class BuildInstructions(object):
def __init__(self, build_instr_file=None):
self.instructions = {}
self.metadata = {}
if build_instr_file:
allheaders = get_inp_sections_details(build_instr_file)
instructions = {}
for (section, _) in allheaders.items():
... |
class TestInputContactMessageContentWithoutRequest(TestInputContactMessageContentBase):
def test_slot_behaviour(self, input_contact_message_content):
inst = input_contact_message_content
for attr in inst.__slots__:
assert (getattr(inst, attr, 'err') != 'err'), f"got extra slot '{attr}'"
... |
class LengthColumn(NumericColumn):
def __init__(self):
super().__init__('~#length')
def _get_min_width(self):
return self._cell_width(util.format_time_display(((60 * 82) + 22)))
def _fetch_value(self, model, iter_):
return model.get_value(iter_).get('~#length', 0)
def _apply_valu... |
.pydicom
def test_require_dicom_patient_position():
test_ds_dict = {key: pydicom.dcmread(test_coords.get_data_file(key)) for key in ORIENTATIONS_SUPPORTED}
ds_no_orient = pydicom.dcmread(str(pymedphys.data_path('example_structures.dcm')), force=True)
test_ds_dict['no orient'] = ds_no_orient
test_orienta... |
def get_param_from_h5(sdf_h5_file, cat_id, obj):
h5_f = h5py.File(sdf_h5_file, 'r')
try:
if ('norm_params' in h5_f.keys()):
norm_params = h5_f['norm_params'][:]
else:
raise Exception(cat_id, obj, 'no sdf and sample')
finally:
h5_f.close()
return (norm_para... |
('beeref.widgets.SceneToPixmapExporterDialog.exec', return_value=False)
('beeref.widgets.SceneToPixmapExporterDialog.value')
def test_scene_to_pixmap_exporter_get_user_input_when_canceled(value_mock, exec_mock, view):
exporter = SceneToPixmapExporter(view.scene)
value = exporter.get_user_input(None)
assert ... |
class LossBuilder():
LOSS_DICT = {'edge': EdgeLoss, 'depth': DepthLoss}
def __init__(self, weight_name, weight, name, img, pil_target):
self.weight_name = weight_name
self.weight = weight
self.name = name
self.img = img
self.pil_target = pil_target
def weight_category... |
class PrideFacts(commands.Cog):
def __init__(self, bot: Bot):
self.bot = bot
self.daily_fact_task = self.bot.loop.create_task(self.send_pride_fact_daily())
_task(Month.JUNE)
async def send_pride_fact_daily(self) -> None:
channel = self.bot.get_channel(Channels.sir_lancebot_playground... |
('xarray.open_dataset')
def test_1258(fake_open_dataset):
from satpy import Scene
fake_open_dataset.side_effect = generate_fake_abi_xr_dataset
scene = Scene(abi_file_list, reader='abi_l1b')
scene.load(['true_color_nocorr', 'C04'], calibration='radiance')
resampled_scene = scene.resample(scene.coarse... |
def _get_unit_vector_x(sat_sun_vec, unit_vector_z, angle_between_earth_and_sun):
beta = angle_between_earth_and_sun
sin_beta = np.sin(beta)
cos_beta = np.cos(beta)
cross1 = _get_uz_cross_satsun(unit_vector_z, sat_sun_vec)
cross2 = cross_product(cross1, unit_vector_z)
unit_vector_x = Vector3D(x=(... |
class rpt(SWMMIOFile):
def __init__(self, filePath):
SWMMIOFile.__init__(self, filePath)
meta_data = get_rpt_metadata(filePath)
self.swmm_version = meta_data['swmm_version']
self.simulationStart = meta_data['simulation_start']
self.simulationEnd = meta_data['simulation_end']
... |
def bar(view_tmin, view_tmax, changes, tmin, tmax, sx):
delta = ((view_tmax - view_tmin) / (sx - 2))
out = [ansi_dim]
ic = 0
while ((ic < len(changes)) and (changes[ic][0] < view_tmin)):
ic += 1
if ((0 < ic) and (ic < len(changes))):
count = changes[(ic - 1)][1]
else:
cou... |
class _MemoryStreamCloser(_StreamCloser):
def __init__(self, write, close_on_exit, is_binary):
super().__init__(write, close_on_exit)
io_class = (io.BytesIO if is_binary else io.StringIO)
fp = self._wrap(io_class)()
assert (fp == self.fp)
def close(self, parent_close=None):
... |
def test_parse_empty_string(parser):
line = ''
statement = parser.parse(line)
assert (statement == '')
assert (statement.args == statement)
assert (statement.raw == line)
assert (statement.command == '')
assert (statement.arg_list == [])
assert (statement.multiline_command == '')
ass... |
def make_env(scenario_name, benchmark=False):
from multiagent.environment import MultiAgentEnv
import multiagent.scenarios as scenarios
scenario = scenarios.load((scenario_name + '.py')).Scenario()
world = scenario.make_world()
if benchmark:
env = MultiAgentEnv(world, scenario.reset_world, s... |
def test_h_constraints_offxml(methanol, tmpdir):
with tmpdir.as_cwd():
methanol.to_offxml(file_name='methanol.offxml', h_constraints=True)
methanol_ff = ForceField('methanol.offxml')
off_methanol = Molecule.from_rdkit(methanol.to_rdkit())
system = methanol_ff.create_openmm_system(top... |
class SawyerButtonPressV1Policy(Policy):
def _parse_obs(obs):
return {'hand_pos': obs[:3], 'button_start_pos': obs[3:6], 'unused_info': obs[6:]}
def get_action(self, obs):
o_d = self._parse_obs(obs)
action = Action({'delta_pos': np.arange(3), 'grab_effort': 3})
action['delta_pos'... |
def convert(x, dtype=None):
if isinstance(x, np.ma.MaskedArray):
raise NotImplementedError('MaskedArrays are not supported')
if (dtype is not None):
x_ = _asarray(x, dtype=dtype)
else:
x_ = None
if isinstance(x, int):
try:
x_ = autocast_int(x)
... |
def _find_compound_unit(numerator_unit: str, denominator_unit: str, locale: ((Locale | str) | None)=LC_NUMERIC) -> (str | None):
locale = Locale.parse(locale)
resolved_numerator_unit = _find_unit_pattern(numerator_unit, locale=locale)
resolved_denominator_unit = _find_unit_pattern(denominator_unit, locale=l... |
_optimizer('lamb')
class FairseqLAMB(LegacyFairseqOptimizer):
def __init__(self, args, params):
super().__init__(args)
try:
from apex.optimizers import FusedLAMB
self._optimizer = FusedLAMB(params, **self.optimizer_config)
except ImportError:
raise ImportE... |
class TestOps():
def test_eq(self, dummy_memmap):
memmap = dummy_memmap
assert (memmap == memmap.clone()).all()
assert (memmap.clone() == memmap).all()
def test_fill_(self, dummy_memmap):
memmap = dummy_memmap.fill_(1.0)
assert (memmap == 1).all()
assert isinstanc... |
def get_files(**kwargs):
metadata_directory = kwargs.get('metadata_directory', '')
shared_data_directory = kwargs.get('shared_data_directory', '')
files = []
for f in get_template_files(**kwargs):
if (str(f.path) == 'LICENSE.txt'):
files.append(File(Path(metadata_directory, 'licenses... |
def test_info(run_cli):
funcname = tests.utils.get_funcname()
argsprefix = ('data/mockargs/%s_' % funcname)
cliprefix = ('data/clioutput/%s_' % funcname)
prod_accessible = {'ids': [1, 7]}
prod_get = {'products': [{'id': 1, 'name': 'Prod 1 Test'}, {'id': 7, 'name': 'test-fake-product'}]}
fakebz =... |
def test_on_success_exception(server_app):
custom = MagicMock(side_effect=RuntimeError('something happened'))
server_app.on('custom', custom)
test_client = server_app.sio.test_client(server_app.app)
result = test_client.emit('custom', callback=True)
custom.assert_called_once_with(server_app)
ass... |
_keras_backend_version_to_v2
def convert_h5_model_to_pb_model(h5_model_path: AnyStr, custom_objects: Dict=None):
supported_file_types = ['h5', 'hdf5']
def validate_model_path() -> Tuple[(str, str)]:
if (not os.path.exists(h5_model_path)):
raise FileNotFoundError(errno.ENOENT, os.strerror(err... |
class YolosFeatureExtractor(YolosImageProcessor):
def __init__(self, *args, **kwargs) -> None:
warnings.warn('The class YolosFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please use YolosImageProcessor instead.', FutureWarning)
super().__init__(*args, **kwargs) |
class Solution():
def sumOddLengthSubarrays(self, arr: List[int]) -> int:
gap = 1
res = 0
n = len(arr)
while (gap < (n + 1)):
i = 0
while (i < ((n - gap) + 1)):
for j in range(i, (i + gap)):
res += arr[j]
i +... |
class CmdDrop(COMMAND_DEFAULT_CLASS):
key = 'drop'
locks = 'cmd:all()'
arg_regex = '\\s|$'
def func(self):
caller = self.caller
if (not self.args):
caller.msg('Drop what?')
return
obj = caller.search(self.args, location=caller, nofound_string=("You aren't ... |
class AbstractChunkIO():
def calc_offset(cls, chunk_x: int, chunk_z: int) -> int:
raise NotImplementedError(cls.__name__)
def find_chunk(cls, location: int) -> tuple:
raise NotImplementedError(cls.__name__)
def fetch_chunk(cls, world_path: str, chunk_x: int, chunk_z: int):
raise NotI... |
class FC6_TestCase(CommandTest):
command = 'iscsi'
def runTest(self):
self.assert_parse('iscsi --ipaddr=1.1.1.1', 'iscsi --ipaddr=1.1.1.1\n')
self.assert_parse('iscsi --ipaddr=1.1.1.1 --target=tar --port=1234 --user=name --password=secret', 'iscsi --target=tar --ipaddr=1.1.1.1 --port=1234 --user... |
def setUpModule():
global cell, cell1
cell = gto.Cell()
cell.build(unit='B', a=(numpy.eye(3) * 4), mesh=([11] * 3), atom='H 0 0 0; H 0 0 1.8', verbose=0, basis='sto3g')
cell1 = gto.Cell()
cell1.atom = '\n He 1.3 .2 .3\n He .1 .1 1.1 '
cell1.basis = {'He': [[0, [0.8, 1... |
class SpringMassDataset(object):
def __init__(self, k, m, A0, c, v0=0, et=10):
super(SpringMassDataset, self).__init__()
self.k = k
self.m = m
self.A0 = A0
self.c = c
self.et = et
self.v0 = v0
self.Nt = int(1000)
self.omega_n = np.sqrt((k / m))... |
def _get_command_line_arguments() -> Dict:
parser = argparse.ArgumentParser()
parser.add_argument(('--' + Args.FEATURES_DIR), required=True, help='Dataset directory for reading and writing features')
parser.add_argument(('--' + Args.PCA_PATH), required=True, help='Pickle containing the PCA transform')
p... |
class LSTM_Parrallel(nn.Module):
def __init__(self):
super(LSTM_Parrallel, self).__init__()
self.encoder_1 = LSTM_encoder()
self.encoder_2 = LSTM_encoder()
self.classifier = nn.Linear(64, 14)
def forward(self, x1, x2, flag='unsupervised'):
if (flag == 'supervised'):
... |
class Mean(ScalarOp):
identity = 0
commutative = True
associative = False
nfunc_spec = ('mean', 2, 1)
nfunc_variadic = 'mean'
def impl(self, *inputs):
return (sum(inputs) / len(inputs))
def c_code(self, node, name, inputs, outputs, sub):
(z,) = outputs
if (not inputs)... |
def download_release(release_scans, out_dir, file_types, use_v1_sens):
if (len(release_scans) == 0):
return
print((((('Downloading ScanNet ' + RELEASE_NAME) + ' release to ') + out_dir) + '...'))
for scan_id in release_scans:
scan_out_dir = os.path.join(out_dir, scan_id)
download_sca... |
def generate_sample(intensity, T, n):
Sequnces = []
i = 0
while True:
seq = []
t = 0
while True:
intens1 = intensity.getUpperBound(t, T)
dt = np.random.exponential((1 / intens1))
new_t = (t + dt)
if (new_t > T):
break
... |
def get_sequence(gr, path=None, pyfaidx_fasta=None):
try:
import pyfaidx
except ImportError:
print('pyfaidx must be installed to get fasta sequences. Use `conda install -c bioconda pyfaidx` or `pip install pyfaidx` to install it.')
sys.exit(1)
if (pyfaidx_fasta is None):
if (... |
class PublisherPlacementReportView(PublisherAccessMixin, BaseReportView):
export_view = 'publisher_placement_report_export'
impression_model = PlacementImpression
template_name = 'adserver/reports/publisher-placement.html'
fieldnames = ['index', 'views', 'clicks', 'ctr', 'ecpm', 'revenue', 'revenue_shar... |
class DockerSchema2ManifestList(ManifestListInterface):
METASCHEMA = {'type': 'object', 'properties': {DOCKER_SCHEMA2_MANIFESTLIST_VERSION_KEY: {'type': 'number', 'description': 'The version of the manifest list. Must always be `2`.', 'minimum': 2, 'maximum': 2}, DOCKER_SCHEMA2_MANIFESTLIST_MEDIATYPE_KEY: {'type': ... |
def test_optional_columns(hatch, helpers, temp_dir, config_file):
config_file.model.template.plugins['default']['tests'] = 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_pa... |
class EnumSpecifier(object):
def __init__(self, tag, enumerators):
self.tag = tag
self.enumerators = enumerators
def __repr__(self):
s = 'enum'
if self.tag:
s += (' %s' % self.tag)
if self.enumerators:
s += (' {%s}' % ', '.join([repr(e) for e in se... |
class OOTestCases(unittest.TestCase):
class TestClass():
field1: NonNull[int]
field2: str
class TestSingleton():
field1: str
def test_nonnull(self):
self.assertRaises(ValueError, self.TestClass, None, {'field1': None, 'field2': 'test'})
def test_to_string(self):
s... |
class TestBuiltinMethods(TestNameCheckVisitorBase):
_passes()
def test_method_wrapper(self):
import collections.abc
def capybara():
r = range(10)
assert_is_value(r, KnownValue(range(10)))
assert_is_value(r.__iter__(), GenericValue(collections.abc.Iterator, [Ty... |
def train(model, dataset, optimizer, criterion, epoch, args, data_start_index):
model.train()
if (data_start_index == 0):
dataset.shuffle('train', seed=(epoch + args.seed))
if (args.epoch_max_len is not None):
data_end_index = min((data_start_index + args.epoch_max_len), len(dataset.splits['... |
def test_console_ansiformat():
f = console.ansiformat
c = console.codes
all_attrs = f('+*_blue_*+', 'text')
assert ((c['blue'] in all_attrs) and (c['blink'] in all_attrs))
assert ((c['bold'] in all_attrs) and (c['underline'] in all_attrs))
assert (c['reset'] in all_attrs)
assert raises(KeyEr... |
def split_data(df, window_size, test_size, val_size=0, use_ratio=True):
expected_type = (float if use_ratio else int)
if ((not isinstance(test_size, expected_type)) or (val_size and (not isinstance(val_size, expected_type)))):
raise ValueError('use_ratio={} while size args are of type {}'.format(use_rat... |
class ExprIf(GrammarSymbol):
def __init__(self):
GrammarSymbol.__init__(self)
self.lbp = 5
def led(self, parser, left):
cond_ = left
then_ = parser.expression(self.lbp)
parser.expect(ExprElse, ':')
else_ = parser.expression(self.lbp)
return parser.mgr.Ite(... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('directory')
parser.add_argument('--binary', required=True)
parser.add_argument('--version', required=True)
args = parser.parse_args()
directory = Path(args.directory).absolute()
staged_binary = Path(args.binary).absolute()
... |
class FakeWallet():
def __init__(self, fiat_value):
super().__init__()
self.fiat_value = fiat_value
self.db = WalletDB('{}', manual_upgrades=True)
self.db.transactions = self.db.verified_tx = {'abc': 'Tx'}
def get_tx_height(self, txid):
return TxMinedInfo(height=10, conf=... |
_2_unicode_compatible
class Proposal(TimeAuditModel):
conference = models.ForeignKey(Conference, on_delete=models.CASCADE)
proposal_section = models.ForeignKey(ProposalSection, verbose_name='Proposal Section', on_delete=models.CASCADE)
proposal_type = models.ForeignKey(ProposalType, verbose_name='Proposal T... |
class Transform(Operator):
grouping = Grouping.T(default=SensorGrouping.D())
translation = ReplaceComponentTranslation(suffix='T{system}')
def _out_codes(self, group):
return [self.translation.translate(group[0]).format(component=c, system=self.components.lower()) for c in self.components] |
def learned_context(quality, metric='mse', pretrained=False, progress=True, **kwargs):
if (metric not in ('mse', 'ms-ssim')):
raise ValueError(f'Invalid metric "{metric}"')
if ((quality < 1) or (quality > 8)):
raise ValueError(f'Invalid quality "{quality}", should be between (1, 8)')
return ... |
class EAESolutionVerifier():
def __init__(self, gold_set: set, cur_event: Dict[(str, Any)], tokens: List[str]) -> None:
self.gold_set = gold_set
self.cur_event = cur_event
self.tokens = tokens
def verify(self, event_obj):
predicted_args = convert_event_obj_to_dict(event_obj, rais... |
def remove_duplicates_from_file(infile_path, outfile_path='temp..bopscrk'):
lines_seen = set()
outfile = open(outfile_path, 'w')
infile = open(infile_path, 'r')
for line in infile:
if (line not in lines_seen):
outfile.write(line)
lines_seen.add(line)
outfile.close()
... |
class TestSimpleStubModuleNotPreferred():
(autouse=True, scope='class')
def built(self, builder):
builder('pyiexample2', warningiserror=True)
def test_integration(self, parse):
example_file = parse('_build/html/autoapi/example/index.html')
assert ('DoNotFindThis' not in example_file)... |
def do_LR(op, stack, state):
arg1_val = stack.pop()
size = SIZE
if z3.is_bv(arg1_val):
arg1 = arg1_val
size = arg1.size()
elif isinstance(arg1_val, str):
arg1 = state.registers[arg1_val]
size = arg1.size()
else:
arg1 = prepare(arg1_val)
(arg2,) = pop_value... |
class DataCollatorForMultipleChoice():
tokenizer: PreTrainedTokenizerBase
padding: Union[(bool, str, PaddingStrategy)] = True
max_length: Optional[int] = None
pad_to_multiple_of: Optional[int] = None
def __call__(self, features):
label_name = ('label' if ('label' in features[0].keys()) else ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.