code stringlengths 281 23.7M |
|---|
class VGG(nn.Module):
def __init__(self, num_classes=10, depth=16, dropout=0.0, multi_fc=False):
super(VGG, self).__init__()
self.inplances = 64
self.conv1 = nn.Conv2d(3, self.inplances, kernel_size=3, padding=1)
self.bn1 = nn.BatchNorm2d(self.inplances)
self.conv2 = nn.Conv2... |
def generate_model_output_test1() -> Dict[(str, torch._tensor.Tensor)]:
return {'predictions': torch.tensor([[1.0, 0.0, 0.51, 0.8, 1.0, 0.0, 0.51, 0.8, 1.0, 0.0, 0.51, 0.8]]), 'session': torch.tensor([[1, 1, 1, 1, 1, 1, 1, (- 1), (- 1), (- 1), (- 1), (- 1)]]), 'labels': torch.tensor([[0.9, 0.1, 0.2, 0.3, 0.9, 0.9, ... |
class KBKDFHMAC(KeyDerivationFunction):
def __init__(self, algorithm: hashes.HashAlgorithm, mode: Mode, length: int, rlen: int, llen: (int | None), location: CounterLocation, label: (bytes | None), context: (bytes | None), fixed: (bytes | None), backend: typing.Any=None, *, break_location: (int | None)=None):
... |
class ListDataset(BaseWrapperDataset):
def __init__(self, dataset, sizes=None):
super().__init__(dataset)
self._sizes = sizes
def collater(self, samples):
return samples
def sizes(self):
return self._sizes
def num_tokens(self, index):
return self.sizes[index]
... |
class JTNNDecoder(nn.Module):
def __init__(self, vocab, hidden_size, latent_size, embedding):
super(JTNNDecoder, self).__init__()
self.hidden_size = hidden_size
self.vocab_size = vocab.size()
self.vocab = vocab
self.embedding = embedding
self.W_z = nn.Linear((2 * hidd... |
class MultipleLMDBManager():
def __init__(self, files: list, data_type, get_key=False, sync=True):
self.files = files
self._is_init = False
self.data_type = data_type
assert (data_type in decode_funcs)
self.get_key = get_key
if sync:
print('sync', files)
... |
def setup_axes(axes_amplitude=None, axes_phase=None):
if (axes_amplitude is not None):
axes_amplitude.set_ylabel('Amplitude ratio')
axes_amplitude.set_xscale('log')
axes_amplitude.set_yscale('log')
axes_amplitude.grid(True)
axes_amplitude.axhline(1.0, lw=0.5, color='black')
... |
class depthDataset_iBims1(Dataset):
def __init__(self, imagelist, transform=None):
with open(imagelist) as f:
image_names = f.readlines()
self.image_names = [x.strip() for x in image_names]
self.transform = transform
def __getitem__(self, idx):
image_name = self.image... |
class Solution(object):
def maxProfit(self, prices):
length = len(prices)
if (length == 0):
return 0
(max_profit, low) = (0, prices[0])
for i in range(1, length):
if (low > prices[i]):
low = prices[i]
else:
temp = (p... |
class BaseOutputTest():
def __init__(self, model, param, disc, solution, operating_condition):
self.model = model
self.param = param
self.disc = disc
self.solution = solution
self.operating_condition = operating_condition
self.phase_name_n = ('' if (self.model.options... |
def add_preprocess_args(parser):
group = parser.add_argument_group('Preprocessing')
group.add_argument('-s', '--source-lang', default=None, metavar='SRC', help='source language')
group.add_argument('-t', '--target-lang', default=None, metavar='TARGET', help='target language')
group.add_argument('--train... |
def _generate_default_transformer_epoch_optim_loop_asset(file, image_loader, transformer, criterion, criterion_update_fn, epochs, get_lr_scheduler, get_optimizer=None):
input_transformer = deepcopy(transformer)
if (get_optimizer is None):
get_optimizer = default_model_optimizer
optimizer = get_optim... |
class Munkres():
def __init__(self):
self.C = None
self.row_covered = []
self.col_covered = []
self.n = 0
self.Z0_r = 0
self.Z0_c = 0
self.marked = None
self.path = None
def make_cost_matrix(profit_matrix, inversion_function):
import munkre... |
class BTOOLS_OT_add_array(bpy.types.Operator):
bl_idname = 'btools.add_array'
bl_label = 'Add Array'
bl_options = {'REGISTER', 'UNDO', 'PRESET'}
def poll(cls, context):
return (context.mode == 'OBJECT')
def execute(self, context):
Array.build(context)
return {'FINISHED'} |
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName('MainWindow')
MainWindow.resize(400, 413)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName('centralwidget')
self.vboxlayout = QtWidgets.QVBoxLayout(self.cen... |
def backpressure(func, *argslist, inflight_limit=1000, **kwargs):
result_refs = []
for (i, args) in enumerate(zip(*argslist)):
if (len(result_refs) > inflight_limit):
num_ready = (i - inflight_limit)
ray.wait(result_refs, num_returns=num_ready)
result_refs.append(func.rem... |
class TestDwf(TestCase):
def test_00_new_node_type(self):
self.assertNotIn(199, CUSTOM_NODE_TYPES, 'Initially there should be no custom node with id 199')
idx = new_node_type(node_id=199)
self.assertIsNotNone(idx)
with self.assertRaises(AssertionError):
new_node_type(idx)... |
def get_parsed_context(args):
logger.debug('starting')
if (not args):
logger.debug('pipeline invoked without context arg set. For this dict parser you can use something like:\npypyr pipelinename key1=value1 key2=value2')
return {'argDict': {}}
return {'argDict': {k: v for (k, _, v) in (eleme... |
class EmojiParserOptions(ParserOptions):
major_tags: Tuple[(str, ...)] = (':boom:',)
minor_tags: Tuple[(str, ...)] = (':sparkles:', ':children_crossing:', ':lipstick:', ':iphone:', ':egg:', ':chart_with_upwards_trend:')
patch_tags: Tuple[(str, ...)] = (':ambulance:', ':lock:', ':bug:', ':zap:', ':goal_net:'... |
def get_data(data_path):
with open(data_path, 'rb') as f:
train_test_paths_labels = pickle.load(f)
train_paths_80 = train_test_paths_labels[0]
val_paths_80 = train_test_paths_labels[1]
train_labels_80 = train_test_paths_labels[2]
val_labels_80 = train_test_paths_labels[3]
train_num_each_... |
def get_files(**kwargs):
return [File(Path('LICENSE.txt'), MIT.replace('<year>', f"{kwargs['year']}-present", 1).replace('<copyright holders>', f"{kwargs['author']} <{kwargs['email']}>", 1)), File(Path('src', kwargs['package_name'], '__init__.py'), f'''# SPDX-FileCopyrightText: {kwargs['year']}-present {kwargs['aut... |
class Effect804(BaseEffect):
type = 'passive'
def handler(fit, module, context, projectionRange, **kwargs):
rawAttr = module.item.getAttribute('capacitorNeed')
if ((rawAttr is not None) and (rawAttr >= 0)):
module.boostItemAttr('capacitorNeed', (module.getModifiedChargeAttr('capNeedB... |
def _calcparams_correct_Python_type_check(out_value, numeric_args):
if any((isinstance(a, pd.Series) for a in numeric_args)):
return isinstance(out_value, pd.Series)
elif any((isinstance(a, np.ndarray) for a in numeric_args)):
return isinstance(out_value, np.ndarray)
return np.isscalar(out_v... |
_model()
_legacy_interface(weights=('pretrained', ResNet101_Weights.IMAGENET1K_V1))
def resnet101(*, weights: Optional[ResNet101_Weights]=None, progress: bool=True, **kwargs: Any) -> ResNet:
weights = ResNet101_Weights.verify(weights)
return _resnet(Bottleneck, [3, 4, 23, 3], weights, progress, **kwargs) |
def when_program_starts_1(self):
while True:
self.glide_to_random_position(1.0)
self.point_towards_mouse_pointer()
self.if_on_edge_bounce()
self.wait(1.0)
if self.list_contains_item('l', 't'):
self.delete_all_from_list('l')
self.add_value_to_list('l', ... |
class RepositoryNotification(BaseModel):
uuid = CharField(default=uuid_generator, index=True)
repository = ForeignKeyField(Repository)
event = EnumField(ExternalNotificationEvent)
method = EnumField(ExternalNotificationMethod)
title = CharField(null=True)
config_json = TextField()
event_conf... |
class TestAbstractmethod(TestCase):
def testInit(self):
class ABCTest(metaclass=ABCMeta):
def meth(self):
pass
assert (ABCTest.meth.__name__ == 'meth')
with self.assertRaises(ABCException) as exc:
abstractmethod(1)
assert (exc.value == 'Functio... |
class TypedListType(CType):
def __init__(self, ttype, depth=0):
if (depth < 0):
raise ValueError('Please specify a depth superior or equal to 0')
if (not isinstance(ttype, Type)):
raise TypeError('Expected an PyTensor Type')
if (depth == 0):
self.ttype = t... |
class Net(torch.nn.Module):
def __init__(self, input_size=784, hidden_size=500, num_classes=10):
super(Net, self).__init__()
self.fc1 = torch.nn.Linear(input_size, hidden_size)
self.relu = torch.nn.ReLU()
self.fc2 = torch.nn.Linear(hidden_size, num_classes)
def forward(self, inpu... |
def get_bucket_files(glob_pattern, base_dir, force=False, pattern_slice=None):
if (pattern_slice is None):
pattern_slice = slice(None)
if (gcsfs is None):
raise RuntimeError("Missing 'gcsfs' dependency for GCS download.")
if (not os.path.isdir(base_dir)):
raise OSError('Directory doe... |
def pointnet_sa_module(xyz, points, npoint, radius, nsample, mlp, mlp2, group_all, is_training, bn_decay, scope, bn=True, pooling='max', knn=False, use_xyz=True, use_nchw=False):
data_format = ('NCHW' if use_nchw else 'NHWC')
sample_idx = None
with tf.variable_scope(scope) as sc:
if group_all:
... |
class FixedPortfolioPercentagePositionSizer(PositionSizer):
def __init__(self, broker: Broker, data_provider: DataProvider, order_factory: OrderFactory, signals_register: SignalsRegister, fixed_percentage: float, tolerance_percentage: float=0.0):
super().__init__(broker, data_provider, order_factory, signal... |
class DisconnectedType(Type):
def filter(self, data, strict=False, allow_downcast=None):
raise AssertionError("If you're assigning to a DisconnectedType you're doing something wrong. It should only be used as a symbolic placeholder.")
def fiter_variable(self, other):
raise AssertionError("If you... |
def pre_trained_model_to_finetune(checkpoint, args):
checkpoint = checkpoint['model']
num_layers = ((args.dec_layers + 1) if args.two_stage else args.dec_layers)
for l in range(num_layers):
del checkpoint['class_embed.{}.weight'.format(l)]
del checkpoint['class_embed.{}.bias'.format(l)]
... |
def extract_mid_stage_label_dataframe(dataset_filename):
if (type(dataset_filename) == str):
logging.info('Dataset: {}'.format(dataset_filename))
annotated_dataset = get_dataset(dataset_filename)
else:
annotated_dataset = []
logging.info('Datasets : {}'.format(', '.join((f for f ... |
class PullRequestEQTest(TestCase):
def test_is_eq(self):
pr1 = pullrequest_factory('yay', number=1)
pr2 = pullrequest_factory('yay', number=2)
self.assertNotEqual(pr1, pr2)
pr1.number = pr2.number
self.assertEqual(pr1, pr2)
pr1.number = 3
self.assertNotEqual(p... |
def eval(config, index_arg, verbose=0):
((train_x, train_y), (test_x, test_y)) = load_imdb()
if config['use_mixed']:
cell = MixedCfcCell(units=config['size'], hparams=config)
else:
cell = CfcCell(units=config['size'], hparams=config)
inputs = tf.keras.layers.Input(shape=(maxlen,))
to... |
class TCRA(TestCase):
def test_upgrade(self):
frame = CRA(owner='a', preview_start=1, preview_length=2, data=b'foo')
new = AENC(frame)
self.assertEqual(new.owner, 'a')
self.assertEqual(new.preview_start, 1)
self.assertEqual(new.preview_length, 2)
self.assertEqual(new.... |
class TokenizerTesterMixin():
tokenizer_class = None
rust_tokenizer_class = None
test_slow_tokenizer = True
test_rust_tokenizer = True
space_between_special_tokens = False
from_pretrained_kwargs = None
from_pretrained_filter = None
from_pretrained_vocab_key = 'vocab_file'
test_seq2se... |
def get_parser():
parser = argparse.ArgumentParser('cli_pytition')
subparsers = parser.add_subparsers(help='sub-command help', dest='action')
genorga = subparsers.add_parser('gen_orga', help='create Pytition Organization')
genorga.add_argument('--orga', '-o', type=str, required=True)
genusers = subp... |
class XmlDjangoLexer(DelegatingLexer):
name = 'XML+Django/Jinja'
aliases = ['xml+django', 'xml+jinja']
filenames = ['*.xml.j2', '*.xml.jinja2']
version_added = ''
alias_filenames = ['*.xml']
mimetypes = ['application/xml+django', 'application/xml+jinja']
url = '
def __init__(self, **opti... |
def sharded_tensor_test_cases(use_gpu: bool) -> TestCase:
spec = ChunkShardingSpec(dim=0, placements=(['rank:0/cpu'] * 4))
srcs = [sharded_tensor.empty(spec, TENSOR_SHAPE) for _ in range(NUM_TENSORS)]
dsts = [sharded_tensor.empty(spec, TENSOR_SHAPE) for _ in range(NUM_TENSORS)]
for (idx, (src, dst)) in ... |
def trapezoidal_slit(top, base, wstep, center=0, norm_by='area', bplot=False, wunit='', scale=1, footerspacing=0, waveunit=None):
if (top > base):
(top, base) = (base, top)
FWHM = ((base + top) / 2)
b = ((2 * int(((top / wstep) // 2))) + 1)
slope = (1 / (FWHM - (b * wstep)))
a = (int((FWHM /... |
def solve_lla(sub_prob, penalty_func, init, init_upv=None, sp_init=None, sp_upv_init=None, sp_other_data=None, transform=abs, objective=None, max_steps=1, tol=1e-05, rel_crit=False, stop_crit='x_max', tracking_level=1, verbosity=0):
current = deepcopy(init)
current_upv = deepcopy(init_upv)
T = transform(cur... |
def assert_string_classification_works(clf):
string_classes = ['cls{}'.format(x) for x in range(num_class)]
str_y_train = np.array(string_classes)[y_train]
clf.fit(X_train, str_y_train, batch_size=batch_size, epochs=epochs)
score = clf.score(X_train, str_y_train, batch_size=batch_size)
assert (np.is... |
class GT(CNF, object):
def __init__(self, size, topv=0, verb=False):
super(GT, self).__init__()
vpool = IDPool(start_from=(topv + 1))
var = (lambda i, j: vpool.id('v_{0}_{1}'.format(i, j)))
for i in range(1, size):
for j in range((i + 1), (size + 1)):
self... |
def run_kcell_complex(cell, nk):
abs_kpts = cell.make_kpts(nk, wrap_around=True)
kmf = pbcscf.KRHF(cell, abs_kpts)
kmf.conv_tol = 1e-12
ekpt = kmf.scf()
kmf.mo_coeff = [kmf.mo_coeff[i].astype(np.complex128) for i in range(np.prod(nk))]
mp = pyscf.pbc.mp.kmp2.KMP2(kmf).run()
return (ekpt, mp.... |
class LazyTensor(AbstractLazyTensor):
def __init__(self, function, args):
self.function = function
self.args = args
def tensor(self):
tensor_args = []
for arg in self.args:
if issubclass(arg.__class__, AbstractLazyTensor):
tensor_args.append(arg.tensor... |
class ModelSingleTagFieldConcreteInheritanceTest(ModelSingleTagFieldTest):
manage_models = [test_models.SingleTagFieldConcreteInheritanceModel]
def setUpExtra(self):
self.test_model = test_models.SingleTagFieldConcreteInheritanceModel
self.tag_model = test_models.SingleTagFieldConcreteInheritanc... |
class Effect1773(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Small Hybrid Turret')), 'falloff', ship.getModifiedItemAttr('shipBonusGF2'), skill='Gallente Frigate', **kwargs) |
class Entity(MessageFilter):
__slots__ = ('entity_type',)
def __init__(self, entity_type: str):
self.entity_type: str = entity_type
super().__init__(name=f'filters.Entity({self.entity_type})')
def filter(self, message: Message) -> bool:
return any(((entity.type == self.entity_type) f... |
def strip_query(query: str) -> Tuple[(List[str], List[str])]:
(query_keywords, all_values) = ([], [])
toks = sqlparse.parse(query)[0].flatten()
values = [t.value for t in toks if ((t.ttype == sqlparse.tokens.Literal.String.Single) or (t.ttype == sqlparse.tokens.Literal.String.Symbol))]
for val in values... |
def main():
parser = argparse.ArgumentParser(description='PyTorch Object Detection Inference')
parser.add_argument('--config-file', default='/private/home/fmassa/github/detectron.pytorch_v2/configs/e2e_faster_rcnn_R_50_C4_1x_caffe2.yaml', metavar='FILE', help='path to config file')
parser.add_argument('--lo... |
class LocalIndexedModel(Model):
class Meta():
table_name = 'LocalIndexedModel'
user_name = UnicodeAttribute(hash_key=True)
email = UnicodeAttribute()
email_index = LocalEmailIndex()
numbers = NumberSetAttribute()
aliases = UnicodeSetAttribute()
icons = BinarySetAttribute(legacy_encod... |
def main():
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
if ((len(sys.argv) == 2) and sys.argv[1].endswith('.json')):
(model_args, data_args, training_args) = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
else:
(model_args, data_args,... |
class Encoder(PymiereBaseObject):
def __init__(self, pymiere_id=None):
super(Encoder, self).__init__(pymiere_id)
def ENCODE_ENTIRE(self):
return self._eval_on_this_object('ENCODE_ENTIRE')
_ENTIRE.setter
def ENCODE_ENTIRE(self, ENCODE_ENTIRE):
raise AttributeError("Attribute 'ENCO... |
def dummy_dist(tmp_path_factory):
basedir = tmp_path_factory.mktemp('dummy_dist')
basedir.joinpath('setup.py').write_text(SETUPPY_EXAMPLE, encoding='utf-8')
for fname in (DEFAULT_LICENSE_FILES | OTHER_IGNORED_FILES):
basedir.joinpath(fname).write_text('', encoding='utf-8')
licensedir = basedir.j... |
class _DepthwiseConv(nn.Module):
def __init__(self, in_channels, out_channels, stride, norm_layer=nn.BatchNorm2d, **kwargs):
super(_DepthwiseConv, self).__init__()
self.conv = nn.Sequential(_ConvBNReLU(in_channels, in_channels, 3, stride, 1, groups=in_channels, norm_layer=norm_layer), _ConvBNReLU(in... |
class ListColumnCpu(ColumnCpuMixin, ListColumn):
def __init__(self, device, dtype, data, offsets, mask):
assert dt.is_list(dtype)
ListColumn.__init__(self, device, dtype)
self._data = velox.Column((velox.VeloxArrayType(get_velox_type(dtype.item_dtype)) if (dtype.fixed_size == (- 1)) else vel... |
def test_create_translator_gates_field(echoes_game_description):
c = NodeIdentifier.create
def make_req(item_id: int):
return RequirementAnd([ResourceRequirement.simple(ItemResourceInfo(0, 'Scan Visor', 'Scan', 1, frozendict({'item_id': 9}))), ResourceRequirement.simple(ItemResourceInfo(1, 'Other', 'Oth... |
def test_FreiHand2D_dataset():
dataset = 'FreiHandDataset'
dataset_info = Config.fromfile('configs/_base_/datasets/freihand2d.py').dataset_info
dataset_class = DATASETS.get(dataset)
channel_cfg = dict(num_output_channels=21, dataset_joints=21, dataset_channel=[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, ... |
class Object():
_add_threshold = 0.02
_adds_threshold = 0.01
def __init__(self, class_id, pcd, is_symmetric, n_votes=3):
self.class_id = class_id
self._pcd = pcd
self._is_symmetric = is_symmetric
self._n_votes = n_votes
self._poses = queue.deque([], 6)
self.is... |
class LearnedGridTensorQuantizer(TensorQuantizer):
def __init__(self, bitwidth: int, round_mode: libpymo.RoundingMode, quant_scheme: QuantScheme, use_symmetric_encodings: bool, enabled_by_default: bool, data_type: QuantizationDataType):
if (data_type != QuantizationDataType.int):
raise ValueErro... |
_tokenizers
class ESMTokenizationTest(unittest.TestCase):
tokenizer_class = EsmTokenizer
def setUp(self):
super().setUp()
self.tmpdirname = tempfile.mkdtemp()
vocab_tokens: List[str] = ['<cls>', '<pad>', '<eos>', '<unk>', 'L', 'A', 'G', 'V', 'S', 'E', 'R', 'T', 'I', 'D', 'P', 'K', 'Q', '... |
class SendSticker():
async def send_sticker(self: 'pyrogram.Client', chat_id: Union[(int, str)], sticker: Union[(str, BinaryIO)], disable_notification: bool=None, reply_to_message_id: int=None, schedule_date: datetime=None, protect_content: bool=None, reply_markup: Union[('types.InlineKeyboardMarkup', 'types.ReplyK... |
('pypyr.venv.subprocess.run')
def test_env_builder_install_pip_extras_quiet(mock_subproc_run):
eb = EnvBuilderWithExtraDeps(is_quiet=True)
context = get_simple_context()
eb.post_setup(context)
eb.pip_install_extras('package1 package2==1.2.3 package3>=4.5.6,<7.8.9')
mock_subproc_run.assert_called_onc... |
class TestFDDBRetinaNet(TestFDDB):
def eval(self):
retinanet = build_whole_network.DetectionNetworkRetinaNet(cfgs=self.cfgs, is_training=False)
all_boxes_r = self.eval_with_plac(img_dir=self.args.img_dir, det_net=retinanet, image_ext=self.args.image_ext)
imgs = os.listdir(self.args.img_dir)
... |
def make_github_url(file_name):
URL_BASE = '
if any(((d in file_name) for d in sphinx_gallery_conf['gallery_dirs'])):
if (file_name.split('/')[(- 1)] == 'index'):
example_file = 'README.rst'
else:
example_file = file_name.split('/')[(- 1)].replace('.rst', '.py')
t... |
.parametrize('username,password', users)
def test_project_create_import_post_upload_file(db, settings, client, username, password):
client.login(username=username, password=password)
url = reverse('project_create_import')
xml_file = os.path.join(settings.BASE_DIR, 'xml', 'project.xml')
with open(xml_fil... |
class TestROI(ROI):
def __init__(self, pos, size, **args):
ROI.__init__(self, pos, size, **args)
self.addTranslateHandle([0.5, 0.5])
self.addScaleHandle([1, 1], [0, 0])
self.addScaleHandle([0, 0], [1, 1])
self.addScaleRotateHandle([1, 0.5], [0.5, 0.5])
self.addScaleHa... |
.xfail(reason='See PR #938')
class TestImportmap(PyScriptTest):
def test_importmap(self):
src = '\n export function say_hello(who) {\n console.log("hello from", who);\n }\n '
self.writefile('mymod.js', src)
self.pyscript_run('\n <script ... |
class SignalRegistrationInterface():
__slots__ = ('_handlers',)
def __init__(self, handlers: List[Callable[(..., None)]]) -> None:
self._handlers = handlers
def register_handler(self, handler: Callable[(..., None)]) -> 'SignalRegistrationInterface':
self._handlers.append(handler)
ret... |
class TypeshedFinder():
ctx: CanAssignContext = field(repr=False)
verbose: bool = True
resolver: typeshed_client.Resolver = field(default_factory=typeshed_client.Resolver)
_assignment_cache: Dict[(Tuple[(str, ast.AST)], Value)] = field(default_factory=dict, repr=False, init=False)
_attribute_cache: ... |
class ZhongFen():
def __init__(self, ck, index):
self.ck = ck
self.index = index
self.headers = {'Host': 'lses-lcae.ihuju.cn', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Linux; Android 13; AC Build/TP1A.220624.014; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chr... |
def _discretize_probability_distribution(unnormalized_probabilities, epsilon):
n = len(unnormalized_probabilities)
sub_bit_precision = max(0, int(math.ceil((- math.log((epsilon * n), 2)))))
bin_count = ((2 ** sub_bit_precision) * n)
cumulative = list(_partial_sums(unnormalized_probabilities))
total ... |
def test_opwiseclinker_straightforward():
(x, y, z) = inputs()
e = add(mul(add(x, y), div(x, y)), bad_sub(bad_sub(x, y), z))
lnk = OpWiseCLinker().accept(FunctionGraph([x, y, z], [e]))
fn = make_function(lnk)
if config.cxx:
assert (fn(2.0, 2.0, 2.0) == 2.0)
else:
assert (fn(2.0, ... |
class WipeExecutor(ActionExecutor):
def execute(self, script: Script, state: EnvironmentState, info: ExecutionInfo, char_index, modify=True, in_place=False):
current_line = script[0]
info.set_current_line(current_line)
node = state.get_state_node(current_line.object())
if (node is No... |
class QuantopianUSFuturesCalendar(TradingCalendar):
def __init__(self, start=Timestamp('2000-01-01', tz=UTC), end=end_default):
super(QuantopianUSFuturesCalendar, self).__init__(start=start, end=end)
name = 'us_futures'
tz = timezone('America/New_York')
open_times = ((None, time(18, 1)),)
cl... |
def gen_visualization(image, decisions):
keep_indices = get_keep_indices(decisions)
image = np.asarray(image)
image_tokens = image.reshape(14, 16, 14, 16, 3).swapaxes(1, 2).reshape(196, 16, 16, 3)
stages = [recover_image(gen_masked_tokens(image_tokens, keep_indices[i])) for i in range(3)]
viz = np.c... |
class OverlapPatchEmbed(nn.Module):
def __init__(self, patch_size=7, stride=4, in_chans=3, embed_dim=768):
super().__init__()
patch_size = to_2tuple(patch_size)
assert (max(patch_size) > stride), 'Set larger patch_size than stride'
self.patch_size = patch_size
self.proj = nn.... |
class Escpos(object, metaclass=ABCMeta):
_device: Union[(Literal[False], Literal[None], object)] = False
def __init__(self, profile=None, magic_encode_args=None, **kwargs) -> None:
self.profile = get_profile(profile)
self.magic = MagicEncode(self, **(magic_encode_args or {}))
def __del__(sel... |
class TweetCache(db.Entity):
tweet_id = PrimaryKey(int, size=64)
data = Required(Json)
blocked = Optional(bool, sql_default=False)
has_media = Optional(bool, sql_default=False)
created_at = Required(int, size=64, index=True)
_session
def fetch(tweet_id: int) -> typing.Optional['TweetCache']:... |
def freq_gauge(stdscr, pos_y, pos_x, size, freq_data):
name = (freq_data['name'] if ('name' in freq_data) else '')
curr_string = unit_to_string(freq_data['cur'], 'k', 'Hz')
if ('max' in freq_data):
value = ((((freq_data['cur'] - freq_data['min']) / (freq_data['max'] - freq_data['min'])) * 100) if (f... |
class _LazyConfigMapping(OrderedDict):
def __init__(self, mapping):
self._mapping = mapping
self._extra_content = {}
self._modules = {}
def __getitem__(self, key):
if (key in self._extra_content):
return self._extra_content[key]
if (key not in self._mapping):
... |
def test_poetry_with_non_default_secondary_source(fixture_dir: FixtureDirGetter, with_simple_keyring: None) -> None:
poetry = Factory().create_poetry(fixture_dir('with_non_default_secondary_source'))
assert poetry.pool.has_repository('PyPI')
assert isinstance(poetry.pool.repository('PyPI'), PyPiRepository)
... |
class Effect3591(BaseEffect):
type = 'passive'
def handler(fit, container, context, projectionRange, **kwargs):
level = (container.level if ('skill' in context) else 1)
fit.modules.filteredItemBoost((lambda mod: (mod.item.group.name == 'Sensor Dampener')), 'maxTargetRangeBonus', (container.getMo... |
class PerMessageDeflate(Extension):
name = ExtensionName('permessage-deflate')
def __init__(self, remote_no_context_takeover: bool, local_no_context_takeover: bool, remote_max_window_bits: int, local_max_window_bits: int, compress_settings: Optional[Dict[(Any, Any)]]=None) -> None:
if (compress_settings... |
def dumpgen(data, only_str):
generator = genchunks(data, 16)
for (addr, d) in enumerate(generator):
line = ''
if (not only_str):
line = ('%08X: ' % (addr * 16))
dumpstr = dump(d)
line += dumpstr[:(8 * 3)]
if (len(d) > 8):
line += ('... |
class ProphetNetTokenizer(PreTrainedTokenizer):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
model_input_names: List[str] = ['... |
class PageFactory(DjangoModelFactory):
class Meta():
model = Page
django_get_or_create = ('path',)
title = factory.Faker('sentence', nb_words=5)
path = factory.LazyAttribute((lambda o: slugify(o.title)))
content = factory.Faker('paragraph', nb_sentences=5)
creator = factory.SubFactor... |
def _migrate_old_base_preset_uuid(preset_manager: PresetManager, options: Options):
for (uuid, preset) in preset_manager.custom_presets.items():
if ((options.get_parent_for_preset(uuid) is None) and ((parent_uuid := preset.recover_old_base_uuid()) is not None)):
options.set_parent_for_preset(uui... |
class ClapProcessor(ProcessorMixin):
feature_extractor_class = 'ClapFeatureExtractor'
tokenizer_class = ('RobertaTokenizer', 'RobertaTokenizerFast')
def __init__(self, feature_extractor, tokenizer):
super().__init__(feature_extractor, tokenizer)
def __call__(self, text=None, audios=None, return_... |
class LinknetDecoder(nn.Module):
def __init__(self, encoder_channels, prefinal_channels=32, n_blocks=5, use_batchnorm=True):
super().__init__()
encoder_channels = encoder_channels[1:]
encoder_channels = encoder_channels[::(- 1)]
channels = (list(encoder_channels) + [prefinal_channels... |
('beeref.view.BeeGraphicsView.recalc_scene_rect')
('beeref.scene.BeeGraphicsScene.on_view_scale_change')
def test_scale(view_scale_mock, recalc_mock, view):
view.scale(3.3, 3.3)
view_scale_mock.assert_called_once_with()
recalc_mock.assert_called_once_with()
assert (view.get_scale() == 3.3) |
def curve_distance(w1, I1, w2, I2, discard_out_of_bounds=True):
norm_w1 = (np.max(w1) - np.min(w1))
norm_w2 = (np.max(w2) - np.min(w2))
norm_I1 = (np.max(I1) - np.min(I1))
norm_I2 = (np.max(I2) - np.min(I2))
dist = cdist(np.array(((w1 / norm_w1), (I1 / norm_I1))).T, np.array(((w2 / norm_w2), (I2 / n... |
def DBInMemory_test():
def rollback():
with sd_lock:
saveddata_session.rollback()
print('Creating database in memory')
from os.path import realpath, join, dirname, abspath
debug = False
gamedataCache = True
saveddataCache = True
gamedata_version = ''
gamedata_connecti... |
_time('2020-02-02')
.parametrize('test_input, expected', [(NOW_UTC, 'now'), ((NOW_UTC - dt.timedelta(seconds=1)), 'a second ago'), ((NOW_UTC - dt.timedelta(seconds=30)), '30 seconds ago'), ((NOW_UTC - dt.timedelta(minutes=1, seconds=30)), 'a minute ago'), ((NOW_UTC - dt.timedelta(minutes=2)), '2 minutes ago'), ((NOW_UT... |
class CatalogSearch(Snuffling):
def help(self):
return '\n<html>\n<head>\n<style type="text/css">\nbody { margin-left:10px };\n</style>\n</head>\n<body>\n <h1 align="center">Catalog Search</h1>\n<p>\n Retrieve event data from online catalogs.\n</p>\n <b>Parameters:</b><br />\n <b>· Catalo... |
def test__contact_and_muscle_forces_example():
from bioptim.examples.muscle_driven_with_contact import contact_forces_inequality_constraint_muscle as ocp_module
bioptim_folder = os.path.dirname(ocp_module.__file__)
ocp_module.prepare_ocp(biorbd_model_path=(bioptim_folder + '/models/2segments_4dof_2contacts_... |
class CoreStage(_LooksStage, _Sound, _Events, _Control, _Operators, _Sensing, _Variables):
def __init__(self, name='Welcome to pyStage!', width=480, height=360):
pygame_major = int(pygame.ver.split('.')[0])
if (pygame_major < 2):
print('pygame version 2 or higher is required for PyStage.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.