code stringlengths 281 23.7M |
|---|
class VideoChunkIteratorProvider():
def __init__(self, chunk_frames: int, num_border_frames: int) -> None:
self._chunk_frames = chunk_frames
self._num_border_frames = num_border_frames
def provide(self, video_features: np.ndarray) -> 'VideoChunkIterator':
return VideoChunkIterator(video_... |
def send_unlock(channel_state: NettingChannelState, message_identifier: MessageID, payment_identifier: PaymentID, secret: Secret, secrethash: SecretHash, block_number: BlockNumber, recipient_metadata: AddressMetadata=None) -> SendUnlock:
lock = get_lock(channel_state.our_state, secrethash)
assert lock, 'caller ... |
def iter_by_batch(sequence: Union[(Sized, Iterable, Dataset)], batch_size: int, log_progress: bool=True):
try:
sequence.__getitem__(0)
size = len(sequence)
step = (batch_size if (batch_size < size) else size)
if log_progress:
iterator = tqdm.tqdm(range(0, size, step), tot... |
def fragment_on_atom_pairs(mol, atom_pairs):
bonds = []
bond_dirs = {}
dummy_labels = []
label = 2
for (a1, a2) in atom_pairs:
bond = mol.GetBondBetweenAtoms(a1, a2)
if bond.IsInRing():
raise ValueError(('Cannot fragment a ring bond (between %d and %d)' % (a1, a2)))
... |
('/v1/user/robots/<robot_shortname>/regenerate')
_param('robot_shortname', 'The short name for the robot, without any user or organization prefix')
class RegenerateUserRobot(ApiResource):
_user_admin(disallow_for_restricted_users=True)
('regenerateUserRobotToken')
def post(self, robot_shortname):
pa... |
def write_tokenizer(tokenizer_path, input_tokenizer_path):
os.makedirs(tokenizer_path, exist_ok=True)
write_json({}, os.path.join(tokenizer_path, 'special_tokens_map.json'))
write_json({'bos_token': '', 'eos_token': '', 'model_max_length': int(1e+30), 'tokenizer_class': 'LLaMATokenizer', 'unk_token': ''}, o... |
class TestRFC8441(object):
def test_can_send_headers(self, frame_factory):
headers = [(b':authority', b'example.com'), (b':path', b'/'), (b':scheme', b' (b':method', b'CONNECT'), (b':protocol', b'websocket'), (b'user-agent', b'someua/0.0.1')]
client = h2.connection.H2Connection()
client.init... |
class CmapDropdown(QtWidgets.QComboBox):
def __init__(self, *args, startcmap='viridis', **kwargs):
super().__init__(*args, **kwargs)
self.setIconSize(QSize(100, 15))
self.view().setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
for (label, cmap) in get_cmap_pixmaps():
self... |
class CrossEntropyLoss(torch.nn.Module):
def __init__(self, reduction='mean'):
super().__init__()
self.loss_fn = torch.nn.CrossEntropyLoss(reduction='none')
self.reduction = reduction
def forward(self, output: Dict):
logit = output['logit']
tgt = output['tgt']
tgt... |
def parse_mul_tree(root):
mul_info = is_mul(root)
if (mul_info is None):
neg_info = is_neg(root)
if (neg_info is None):
return [False, root]
else:
(neg, sub_tree) = parse_mul_tree(neg_info)
return [(not neg), sub_tree]
else:
return [False, ... |
def test_list_json(pipx_temp_env, capsys):
pipx_venvs_dir = (constants.PIPX_HOME / 'venvs')
venv_bin_dir = ('Scripts' if constants.WINDOWS else 'bin')
assert (not run_pipx_cli(['install', PKG['pycowsay']['spec']]))
assert (not run_pipx_cli(['install', PKG['pylint']['spec']]))
assert (not run_pipx_cl... |
class _DefaultCmdLineCallback(object):
def __init__(self):
self.train_vals = {}
def __call__(self, viz, mode, it, k, v):
if (mode == 'train'):
self.train_vals[k] = (self.train_vals.get(k, []) + [v])
elif (mode == 'val'):
viz.append_element(k, it, np.mean(np.array(... |
()
('circle-config-file', type=click.File('rt'), default='.circleci/config.yml')
def main(circle_config_file):
try:
config = yaml.safe_load(circle_config_file)
except ParserError as ex:
click.secho(f'Invalid yaml file: {ex}', fg='red')
sys.exit(1)
(result, message) = _check_workflows... |
(params=xdist_sort_hack(['scipy.stats.qmc: centered-discrepancy optimization of a Latin hypercube', 'inverse missing in idstn, idctn (#14479)', 'Merge pull request #14447 from AnirudhDagar/rename_ndimage_modules', 'Add tests for args kwarg in quad_vec', 'badge with version of the doc in the navbar (#14132)', 'Bump scip... |
class SecurityGenerateAuthorization(rq.ReplyRequest):
_request = rq.Struct(rq.Card8('opcode'), rq.Opcode(1), rq.RequestLength(), rq.LengthOf('auth_proto', 2), rq.LengthOf('auth_data', 2), rq.Card32('value_mask'), rq.String8('auth_proto'), rq.Binary('auth_data'), rq.List('values', rq.Card32Obj))
_reply = rq.Stru... |
class TestPerChannelQuantizationKeras(unittest.TestCase):
def test_per_channel_range_learning(self):
if (version.parse(tf.version.VERSION) >= version.parse('2.00')):
tf.keras.backend.clear_session()
inputs = tf.keras.layers.Input(shape=(32, 32, 4))
conv_op = tf.keras.laye... |
def convert(data_dir):
data_dict = {}
for gnt in os.listdir(data_dir):
if (gnt[(- 3):len(gnt)] == 'gnt'):
load_one_file((data_dir + gnt), data_dict)
for (k, v) in data_dict.items():
num = (v.shape[0] / FLAGS.output_size)
v = v.reshape([num, FLAGS.output_size, FLAGS.output... |
def create_structure_set_roi(roi_data: ROIData) -> Dataset:
structure_set_roi = Dataset()
structure_set_roi.ROINumber = roi_data.number
structure_set_roi.ReferencedFrameOfReferenceUID = roi_data.frame_of_reference_uid
structure_set_roi.ROIName = roi_data.name
structure_set_roi.ROIDescription = roi_d... |
class SingleRealsense(mp.Process):
MAX_PATH_LENGTH = 4096
def __init__(self, shm_manager: SharedMemoryManager, serial_number, resolution=(1280, 720), capture_fps=30, put_fps=None, put_downsample=True, record_fps=None, enable_color=True, enable_depth=False, enable_infrared=False, get_max_k=30, advanced_mode_conf... |
class TestBinaryPrecision(unittest.TestCase):
def _test_binary_precision_with_input(self, input: torch.Tensor, target: torch.Tensor, threshold: float=0.5) -> None:
input_np = np.where((input.numpy() < threshold), 0, 1)
target_np = target.squeeze().numpy()
sklearn_result = torch.tensor(precis... |
def _create_basis_sweeps(H_params: List[sympy.Symbol], S_params: List[sympy.Symbol], n_shots: int, rand_state: np.random.RandomState) -> Tuple[(List[Dict[(str, int)]], np.ndarray)]:
assert (len(H_params) == len(S_params))
all_sweeps = []
all_bases = rand_state.randint(0, 3, size=(n_shots, len(H_params)))
... |
class CompilationDatabase(ClangObject):
def __del__(self):
conf.lib.clang_CompilationDatabase_dispose(self)
def from_result(res, fn, args):
if (not res):
raise CompilationDatabaseError(0, 'CompilationDatabase loading failed')
return CompilationDatabase(res)
def fromDirect... |
def generate_distances_network_part5():
alias_method_j_c = {}
layer = 0
while isPickle(('alias_method_j-layer-' + str(layer))):
logging.info('Executing layer {}...'.format(layer))
alias_method_j = restoreVariableFromDisk(('alias_method_j-layer-' + str(layer)))
alias_method_j_c[layer]... |
class LayerDefinitionCreateView(ResourceMixin, ResourceBaseCreateView):
form_class = UploadForm
is_custom_license_agreement = True
def form_valid(self, form):
obj = form.save(commit=False)
obj.creator = self.request.user
obj.url_datasource = get_url_datasource(obj.file.file)
... |
def test_template_basics():
app = flask.Flask(__name__)
babel.Babel(app, default_locale='de_DE')
def t(x):
return flask.render_template_string(('{{ %s }}' % x))
with app.test_request_context():
assert (t("gettext('Hello %(name)s!', name='Peter')") == u'Hallo Peter!')
assert (t("n... |
class VocParser(Parser):
DEFAULT_CLASSES = ('aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor')
def __init__(self, cfg: VocParserCfg):
super().__init__(bbox_yxyx... |
class TestNotificationApp(unittest.TestCase):
def setUpClass(cls):
import notification_app
cls.AppClass = notification_app.MyApp
def setUp(self):
self.AppClass.log_request = (lambda x, y: None)
def tearDown(self):
del self.AppClass.log_request
self.app.on_close()
... |
_module
class MSELoss(nn.Module):
def __init__(self, reduction='mean', loss_weight=1.0):
super().__init__()
self.reduction = reduction
self.loss_weight = loss_weight
def forward(self, pred, target, weight=None, avg_factor=None):
loss = (self.loss_weight * mse_loss(pred, target, w... |
def infer(model, sentences, inputs):
num_sentences = len(sentences)
total_infer_time = 0
results = {}
for i in range(num_sentences):
input_ids = inputs[i]['input_ids']
attention_masks = inputs[i]['attention_mask']
with torch.no_grad():
if (i == 0):
t0 ... |
def parse_changelog(tag_name):
p = (Path(__file__).parent.parent / 'doc/en/changelog.rst')
changelog_lines = p.read_text(encoding='UTF-8').splitlines()
title_regex = re.compile('pytest (\\d\\.\\d+\\.\\d+) \\(\\d{4}-\\d{2}-\\d{2}\\)')
consuming_version = False
version_lines = []
for line in chang... |
((sys.version_info[:2] >= (3, 11)), 'asyncio.coroutine has been removed in Python 3.11')
class YieldFromTests(ClientServerTestsMixin, AsyncioTestCase):
_server()
def test_client(self):
with warnings.catch_warnings():
warnings.simplefilter('ignore')
def run_client():
... |
def create_model(args, model_name, output_dim, pretrained=False, device=None, **kwargs):
logging.info(('create_model. model_name = %s, output_dim = %s' % (model_name, output_dim)))
model = None
logging.info(f'model name: {model_name}')
if args.VHL:
if (args.VHL_label_style == 'extra'):
... |
class TestLatexify(TestCase):
def test_latexify(self):
model_dfn = pybamm.lithium_ion.DFN()
func_dfn = str(model_dfn.latexify())
model_spme = pybamm.lithium_ion.SPMe()
func_spme = str(model_spme.latexify())
self.assertIn('Single Particle Model with electrolyte Equations', fun... |
(params=['single', 'list'])
def hdf5_file_path_or_paths(tmp_path, test_objects, request) -> Union[(os.PathLike, list[os.PathLike])]:
if (request.param == 'single'):
return _write_h5_file((tmp_path / 'test.h5'), test_objects)
elif (request.param == 'list'):
return [_write_h5_file((tmp_path / 'tes... |
class BatchNorm2d(nn.BatchNorm2d, Module):
def __init__(self, num_features, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True, episodic=False, n_episode=4, alpha=False):
super(BatchNorm2d, self).__init__(num_features, eps, momentum, affine, track_running_stats)
self.episodic = episodic
... |
_tokenizers
class LongformerTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
tokenizer_class = LongformerTokenizer
test_slow_tokenizer = True
rust_tokenizer_class = LongformerTokenizerFast
test_rust_tokenizer = True
def setUp(self):
super().setUp()
vocab = ['l', 'o', 'w', '... |
class ProgressCallback(TrainerCallback):
def __init__(self):
self.training_bar = None
self.prediction_bar = None
def on_train_begin(self, args, state, control, **kwargs):
if state.is_local_process_zero:
self.training_bar = tqdm(total=state.max_steps)
self.current_step... |
def _generate_image_and_label_batch(image, label, min_queue_examples, batch_size, shuffle):
num_preprocess_threads = 16
if shuffle:
(images, label_batch) = tf.train.shuffle_batch([image, label], batch_size=batch_size, num_threads=num_preprocess_threads, capacity=(min_queue_examples + (3 * batch_size)), ... |
class CycleBatchNormList(nn.ModuleList):
def __init__(self, length: int, bn_class=nn.BatchNorm2d, **kwargs):
self._affine = kwargs.pop('affine', True)
super().__init__([bn_class(**kwargs, affine=False) for k in range(length)])
if self._affine:
channels = self[0].num_features
... |
def test_same_as_the_reference_implementation() -> None:
d = Path(__file__).parent
ds = read_plink(path='hapmap_JPT_CHB_r23a_filtered')
pcs = da.from_array(pd.read_csv(d.joinpath('pcs.csv').as_posix(), usecols=[1, 2]).to_numpy())
ds[sample_pca_projection] = (('samples', 'components'), pcs)
phi = pc_... |
.parametrize('username, expect_success', [('devtable', True), ('public', True), ('buynlarge', False), ('devtable+dtrobot', False), ('unverified', False)])
def test_common_login(username, expect_success, app):
uuid = model.get_namespace_uuid(username)
with app.app_context():
(success, headers) = common_l... |
class BatchNormalization(tf.layers.BatchNormalization):
def __init__(self, fused=False, **kwargs):
if (fused in (True, None)):
raise ValueError('The TPU version of BatchNormalization does not support fused=True.')
super(BatchNormalization, self).__init__(fused=fused, **kwargs)
def _c... |
class TestNCCL(unittest.TestCase):
def test_newuid(self):
if caffe.has_nccl():
uid = caffe.NCCL.new_uid()
if (sys.version_info.major >= 3):
self.assertTrue(isinstance(uid, bytes))
else:
self.assertTrue(isinstance(uid, str)) |
class TFDecoderLayer(nn.Module):
def __init__(self, d_model=512, d_inner=256, n_head=8, d_k=64, d_v=64, dropout=0.1, qkv_bias=False, act_cfg=dict(type='mmcv.GELU'), operation_order=None):
super().__init__()
self.norm1 = nn.LayerNorm(d_model)
self.norm2 = nn.LayerNorm(d_model)
self.no... |
_moment.register(TruncatedRV)
def truncated_moment(op, rv, *inputs):
(*rv_inputs, lower, upper, rng) = inputs
untruncated_rv = op.base_rv_op.make_node(rng, *rv_inputs).default_output()
untruncated_moment = moment(untruncated_rv)
fallback_moment = pt.switch(pt.and_(pt.bitwise_not(pt.isinf(lower)), pt.bit... |
def run_hook_for_layers(model: torch.nn.Module, input_shapes: Union[(Tuple, List[Tuple])], hook, module_type_for_attaching_hook=None, leaf_node_only=True):
hooks = []
modules = [module for module in model.modules() if ((not leaf_node_only) or is_leaf_module(module))]
if module_type_for_attaching_hook:
... |
class TestChangeGC(EndianTest):
def setUp(self):
self.req_args_0 = {'attrs': {'function': 8, 'plane_mask': , 'foreground': , 'background': , 'line_width': 36097, 'line_style': 0, 'cap_style': 3, 'join_style': 1, 'fill_style': 0, 'fill_rule': 0, 'tile': , 'stipple': , 'tile_stipple_x_origin': (- 24195), 'til... |
class NetOutBlock(nn.Module):
def __init__(self, in_channels, br_channels, out_channels, classes, layers=1):
super(NetOutBlock, self).__init__()
self.up = nn.ConvTranspose2d(in_channels, out_channels, kernel_size=2, stride=2)
self.bn_up = nn.BatchNorm2d(out_channels)
self.af_up = nn.... |
def conv_bn_relu(data, cfg, num_filters, kernel=(3, 3), stride=(1, 1), pad=(1, 1), group=1, workspace=512, bn_mom=0.9, name=''):
body = mx.sym.Convolution(data=data, num_filter=num_filters, kernel=kernel, stride=stride, pad=pad, num_group=group, no_bias=True, workspace=workspace, name=(name + '_conv'))
body = m... |
class Trailer(object):
def set_defaults(self):
self.id = None
def __init__(self, id):
self.set_defaults()
if id:
self.id = id
def is_valid(self):
return (self.file[(- 1)] != '/')
def file(self):
trailer_file = 'gettrailer.php?quality=hd&trailer_id={}'.... |
class Input():
def __init__(self, handle, unit, label, iconID, defaultValue, defaultRange, mainTooltip=None, secondaryTooltip=None, conditions=()):
self.handle = handle
self.unit = unit
self.label = label
self.iconID = iconID
self.defaultValue = defaultValue
self.defa... |
def test_elevationprofile():
elevation = xodr.ElevationProfile()
prettyprint(elevation.get_element())
elevation.add_elevation(xodr.elevation._Poly3Profile(0, 0, 0, 0, 0))
prettyprint(elevation.get_element())
elevation2 = xodr.ElevationProfile()
elevation2.add_elevation(xodr.elevation._Poly3Profi... |
def attach(parser):
parser.add_argument('inputs', nargs='+', help='Sequence of PDF files.')
parser.add_argument('--pages', nargs='+', default=[], help="Sequence of page texts, definig the pages to include from each PDF. Use '_' as placeholder for all pages.")
parser.add_argument('--passwords', nargs='+', de... |
class MockClient(BaseClient):
def api_version(self):
return 'v2018-08-09'
def list_resources(self, **options):
path = '/resources'
return Pager(self, path, **options)
def get_resource(self, resource_id, **options):
path = self._interpolate_path('/resources/%s', resource_id)
... |
class FurthestPointSampling(Function):
def forward(ctx, xyz: torch.Tensor, npoint: int) -> torch.Tensor:
assert xyz.is_contiguous()
(B, N, _) = xyz.size()
output = torch.cuda.IntTensor(B, npoint)
temp = torch.cuda.FloatTensor(B, N).fill_(.0)
pointnet2.furthest_point_sampling_... |
def add_nitsot_outputs(fgraph: FunctionGraph, old_scan_node: Apply, old_scan_args: ScanArgs, new_outputs_inner) -> tuple[(Apply, dict[(Variable, Variable)])]:
assert isinstance(old_scan_node.op, Scan)
nb_new_outs = len(new_outputs_inner)
new_nitsots_initial_value = [old_scan_node.inputs[0] for i in range(nb... |
def main(context_switch=0, thread=(- 1)):
cpus = perf.cpu_map()
threads = perf.thread_map(thread)
evsel = perf.evsel(type=perf.TYPE_SOFTWARE, config=perf.COUNT_SW_DUMMY, task=1, comm=1, mmap=0, freq=0, wakeup_events=1, watermark=1, sample_id_all=1, context_switch=context_switch, sample_type=((perf.SAMPLE_PE... |
def test_custom_python_executable(monkeypatch, tmpdir):
monkeypatch.setenv('PYTHONPATH', BUILDSYS_PKGS)
runner = Mock(autospec=default_subprocess_runner)
hooks = get_hooks('pkg1', runner=runner, python_executable='some-python')
with hooks.subprocess_runner(runner):
with pytest.raises(FileNotFoun... |
class QueryClientResources(rq.ReplyRequest):
_request = rq.Struct(rq.Card8('opcode'), rq.Opcode(ResQueryClientResources), rq.RequestLength(), rq.Card32('client'))
_reply = rq.Struct(rq.ReplyCode(), rq.Pad(1), rq.Card16('sequence_number'), rq.ReplyLength(), rq.LengthOf('types', 4), rq.Pad(20), rq.List('types', T... |
def se_conv_unit(x):
with tf.variable_scope(None, 'se_conv_unit'):
shape = x.get_shape().as_list()
y = slim.avg_pool2d(x, (shape[1], shape[2]), stride=1)
y = slim.conv2d(y, shape[(- 1)], 1, 1, activation_fn=None)
y = slim.batch_norm(y, activation_fn=tf.nn.sigmoid, fused=False)
... |
def test_assert_raises_on_assertthis_not_equals():
context = Context({'assert': {'this': 'boom', 'equals': 'BOOM'}})
with pytest.raises(AssertionError) as err_info:
assert_step.run_step(context)
assert (str(err_info.value) == "assert assert['this'] is of type str and does not equal assert['equals'] ... |
class Pizza(ABC):
name: str = None
dough: Dough = None
sauce: Sauce = None
veggies: List[Veggies] = None
cheese: Cheese = None
pepperoni: Pepperoni = None
clam: Clams = None
def prepare(self) -> None:
raise NotImplementedError
def bake(self) -> None:
print('Bake for 2... |
def annotate_file(path: Union[(str, 'os.PathLike[str]')], *, visitor_cls: Type[NameCheckVisitor]=NameCheckVisitor, verbose: bool=False, dump: bool=False, show_errors: bool=False) -> ast.AST:
filename = os.fspath(path)
try:
(mod, _) = load_module_from_file(filename, verbose=verbose)
except Exception:... |
class OnnxConfigWithPast(OnnxConfig, ABC):
def __init__(self, config: 'PretrainedConfig', task: str='default', patching_specs: List[PatchingSpec]=None, use_past: bool=False):
super().__init__(config, task=task, patching_specs=patching_specs)
self.use_past = use_past
def with_past(cls, config: 'P... |
class UserSetNewPWDHandler(BaseHandler):
.authenticated
async def get(self, userid):
email = (await self.db.user.get(userid, fields=('email',)))['email']
(await self.render('user_setnewpwd.html', userid=userid, usermail=email))
return
.authenticated
async def post(self, userid):
... |
class LiveServerExecutor(object):
def __init__(self):
self.funcs = {}
def register(self, fn_name, fn):
self.funcs[fn_name] = fn
def apply_blueprint_to_app(self, app):
testbp = Blueprint('testbp', __name__)
def build_invoker(fn_name, fn):
path = ('/' + fn_name)
... |
def find_head(arg_start, arg_end, doc):
cur_i = arg_start
while ((doc[cur_i].head.i >= arg_start) and (doc[cur_i].head.i <= arg_end)):
if (doc[cur_i].head.i == cur_i):
break
else:
cur_i = doc[cur_i].head.i
arg_head = cur_i
return (arg_head, arg_head) |
def hf_from_pretrained(cls, pretrained_model_name_or_path: Union[(str, os.PathLike)], custom_process_state_fn: Callable=None, dtype: jnp.dtype=jnp.float32, *model_args, **kwargs):
config = kwargs.pop('config', None)
cache_dir = kwargs.pop('cache_dir', None)
from_pt = kwargs.pop('from_pt', False)
ignore_... |
def test_requirement_source_fix_roundtrip(req_file):
req_path = req_file()
with open(req_path, 'w') as f:
f.write('flask==0.5')
source = requirement.RequirementSource([req_path])
specs = list(source.collect())
flask_dep: (ResolvedDependency | None) = None
for spec in specs:
if (i... |
class ModelConfigs(BaseModelConfigs):
def __init__(self):
super().__init__()
self.model_path = os.path.join('Models/1_image_to_word', datetime.strftime(datetime.now(), '%Y%m%d%H%M'))
self.vocab = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
self.height = 32
self.wid... |
def test_face_COFW_dataset():
dataset = 'FaceCOFWDataset'
dataset_info = Config.fromfile('configs/_base_/datasets/cofw.py').dataset_info
dataset_class = DATASETS.get(dataset)
dataset_class.load_annotations = MagicMock()
dataset_class.coco = MagicMock()
channel_cfg = dict(num_output_channels=29, ... |
def compute_numerator_denominator(lm, h):
log_sum_seen_h = (- math.inf)
log_sum_seen_h_lower = (- math.inf)
base = lm.base
for (w, log_p) in lm._ngrams[len(h)][h].items():
log_sum_seen_h = add_log_p(log_sum_seen_h, log_p, base)
ngram = (h + (w,))
log_p_lower = lm.log_p_raw(ngram[... |
def main():
opts = parse_args()
mkdir2(opts.out_dir)
db = COCO(opts.annot_path)
class_names = [c['name'] for c in db.dataset['categories']]
n_class = len(class_names)
coco_mapping = (None if opts.no_class_mapping else db.dataset.get('coco_mapping', None))
if (coco_mapping is not None):
... |
class ReaderNode(Node):
def __init__(self, unique_id, reader_name):
super().__init__(unique_id, data={'reader_name': reader_name})
def _copy_name_and_data(self, node_cache):
return ReaderNode(self.name, self.data['reader_name'])
def reader_name(self):
return self.data['reader_name'] |
def calc_fees_for_commitment_tx(*, num_htlcs: int, feerate: int, is_local_initiator: bool, round_to_sat: bool=True) -> Dict[('HTLCOwner', int)]:
overall_weight = (COMMITMENT_TX_WEIGHT + (num_htlcs * HTLC_OUTPUT_WEIGHT))
fee = (feerate * overall_weight)
if round_to_sat:
fee = ((fee // 1000) * 1000)
... |
class ModelFormTagFieldTest(TagTestManager, TestCase):
manage_models = [test_models.TagFieldModel]
def setUpExtra(self):
self.form = test_forms.TagFieldModelForm
self.model = test_models.TagFieldModel
self.tag_model = self.model.tags.tag_model
def test_formfield(self):
tag1_f... |
def test__getting_started__custom_plotting():
from bioptim.examples.getting_started import custom_plotting as ocp_module
bioptim_folder = os.path.dirname(ocp_module.__file__)
ocp_module.prepare_ocp(biorbd_model_path=(bioptim_folder + '/models/pendulum.bioMod'), final_time=2, n_shooting=50, phase_dynamics=Ph... |
def test_solver_synchronize_single(package: ProjectPackage, pool: RepositoryPool, io: NullIO) -> None:
package_a = get_package('a', '1.0')
solver = Solver(package, pool, [package_a], [], io)
transaction = solver.solve()
check_solver_result(transaction, [{'job': 'remove', 'package': package_a}], synchron... |
def save_as_playlist(request: WSGIRequest) -> HttpResponse:
try:
(start, end) = _parse_datetimes(request)
except ValueError as error:
return HttpResponseBadRequest(error.args[0])
name = request.POST.get('name')
if (not name):
return HttpResponseBadRequest('Name required')
pla... |
def test_arrays():
apparent_zenith = np.array([10])
apparent_azimuth = np.array([180])
tracker_data = tracking.singleaxis(apparent_zenith, apparent_azimuth, axis_tilt=0, axis_azimuth=0, max_angle=90, backtrack=True, gcr=(2.0 / 7.0))
assert isinstance(tracker_data, dict)
expect = {'tracker_theta': 0,... |
_db
def test_query_events_map(graphql_client, conference_factory, event_factory):
now = timezone.now()
conference = conference_factory(start=now, end=(now + timezone.timedelta(days=3)))
event_factory(conference=conference, latitude=1, longitude=1)
resp = graphql_client.query('query($code: String!) {\n ... |
def test_local_det_chol():
X = matrix('X')
L = pt.linalg.cholesky(X)
det_X = pt.linalg.det(X)
f = function([X], [L, det_X])
nodes = f.maker.fgraph.toposort()
assert (not any((isinstance(node, Det) for node in nodes)))
f = function([X], [L, det_X, X])
nodes = f.maker.fgraph.toposort()
... |
class FSNERTokenizerUtils(object):
def __init__(self, pretrained_model_name_or_path):
self.tokenizer = AutoTokenizer.from_pretrained(pretrained_model_name_or_path)
def tokenize(self, x):
if (isinstance(x, list) and all([isinstance(_x, list) for _x in x])):
d = None
for l ... |
class TestCaseTransfer(TestCase):
def name():
return 'transfer'
def abbreviation():
return 'DC'
def desc():
return 'Stream data is being sent and received correctly. Connection close completes with a zero error code.'
def get_paths(self):
self._files = [self._generate_ran... |
def SM1_policy():
grid = 1
cur_env = SM_env(max_hidden_block=HIDDEN_BLOCK, attacker_fraction=0.4, follower_fraction=GAMMA, dev=0)
sm1_policy = np.zeros((grid, cur_env._state_space_n), dtype=np.int)
for i in range(grid):
for j in range(cur_env._state_space_n):
(h1, h2, status) = cur_e... |
class SIDGuesser(OracleDatabase):
def __init__(self, args, SIDFile, timeSleep=0):
logging.debug('SIDGuesser object created')
OracleDatabase.__init__(self, args)
self.SIDFile = SIDFile
self.sids = []
self.valideSIDS = []
self.args['SYSDBA'] = False
self.args['S... |
def test_expansion_penalty():
x = torch.rand(20, 8192, 3).cuda()
print('Input_size: ', x.shape)
expansion = expansionPenaltyModule()
start_time = time.perf_counter()
(dis, ass, mean_length) = expansion(x, 512, 1.5)
print(('Runtime: %lfs' % (time.perf_counter() - start_time))) |
class AllTests(unittest.TestSuite):
def suite(self):
loader = unittest.defaultTestLoader
self.addTests([loader.loadTestsFromModule(fake_filesystem_test), loader.loadTestsFromModule(fake_filesystem_glob_test), loader.loadTestsFromModule(fake_filesystem_shutil_test), loader.loadTestsFromModule(fake_os... |
class TestGetSynsetsFromIds(tf.test.TestCase):
def test_on_toy_graph(self):
specification = create_toy_graph()
(toy_graph, _, _) = specification
wn_ids = [5, 0, 6]
id_to_synset = imagenet_spec.get_synsets_from_ids(wn_ids, toy_graph)
self.assertEqual(set(id_to_synset.keys()), ... |
def verify_pretrain_params(args):
assert args.embed_bytes, 'To use pretrained weights, embed_bytes must be set to True.'
assert (args.char_cnn_nonlinear_fn == model_constants.PRETRAINED_CHAR_CNN_NONLINEAR_FN), 'To use pretrained weights, the non linearity used should be relu.'
assert (args.char_embed_dim ==... |
class Array(PymiereBaseCollection):
def __init__(self, pymiere_id):
super(Array, self).__init__(pymiere_id, 'length')
def __getitem__(self, index):
return _format_object_to_py(_eval_script_returning_object("$._pymiere['{}'][{}]".format(self._pymiere_id, index)))
def __setitem__(self, key, va... |
def get_cell_html(cell, highlight):
if highlight:
color_str = ' class="highlighted" '
else:
color_str = ''
is_header = cell['is_header']
cell_symbol = 'td'
if is_header:
cell_symbol = 'th'
start_marker = ('<%s%s>' % (cell_symbol, color_str))
end_marker = ('</%s>' % ce... |
class CmdLookDark(Command):
key = 'look'
aliases = ['l', 'feel', 'search', 'feel around', 'fiddle']
locks = 'cmd:all()'
help_category = 'TutorialWorld'
def func(self):
caller = self.caller
nr_searches = caller.ndb.dark_searches
if (nr_searches is None):
nr_searche... |
class Word(gym.spaces.MultiDiscrete):
def __init__(self, max_length, vocab):
if (len(vocab) != len(set(vocab))):
raise VocabularyHasDuplicateTokens()
self.max_length = max_length
self.PAD = '<PAD>'
self.UNK = '<UNK>'
self.BOS = '<S>'
self.EOS = '</S>'
... |
def MirrorTest(source_local, dest_local, list_of_dirnames, compare_hardlinks=1, dest_dirname=abs_output_dir):
Globals.set('preserve_hardlinks', compare_hardlinks)
Globals.set('no_compression_regexp_string', os.fsencode(actions.DEFAULT_NOT_COMPRESSED_REGEXP))
dest_rp = rpath.RPath(Globals.local_connection, d... |
def save_output(browser: Chrome, filename=None, process_func=None):
raw_html = browser.find_element_by_id('markdown-body').get_attribute('innerHTML')
html = re.sub('"pywebio-scope-.*?"', '', raw_html)
html = re.sub('id="pywebio-.*?"', '', html)
html = re.sub("\\('pywebio-.*?'\\)", '', html)
html = r... |
def get_access_code(code: str, flag: str):
if (flag == 'web'):
app_id = current_app.config.get('WEB_ID')
secret = current_app.config.get('WEB_SECRET')
elif (flag == 'app'):
app_id = current_app.config.get('APP_ID')
secret = current_app.config.get('APP_SECRET')
else:
r... |
class OTRMessage(object):
__slots__ = ['payload']
version = 2
msgtype = 0
def __eq__(self, other):
if (not isinstance(other, self.__class__)):
return False
for slot in getslots(self.__class__, OTRMessage):
if (getattr(self, slot) != getattr(other, slot)):
... |
class InteropQubitManager(cirq.ops.SimpleQubitManager):
def __init__(self):
super().__init__()
self._managed_qubits = set()
def manage_qubits(self, qubits: Iterable[cirq.Qid]):
self._managed_qubits |= set(qubits)
def qfree(self, qubits: Iterable[cirq.Qid]):
qs = set(qubits)
... |
_for_td(torch.gather)
def _gather(input: T, dim: int, index: Tensor, *, sparse_grad: bool=False, out: (T | None)=None) -> T:
if sparse_grad:
raise NotImplementedError('sparse_grad=True not implemented for torch.gather(tensordict, ...)')
if (not len(index)):
raise RuntimeError('Cannot use torch.g... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.