code stringlengths 281 23.7M |
|---|
def retrieve_artifact(name: str):
_artifact = {}
if os.path.exists(name):
files = os.listdir(name)
for file in files:
try:
with open(os.path.join(name, file)) as f:
_artifact[file.split('.')[0]] = f.read()
except UnicodeDecodeError as e... |
class Video_TANetDataSet(data.Dataset):
def __init__(self, list_file, num_segments=3, new_length=1, modality='RGB', vid_format='.mp4', transform=None, random_shift=True, test_mode=False, video_data_dir=None, remove_missing=False, dense_sample=False, test_sample='dense-10', if_sample_tta_aug_views=None, tta_view_sam... |
class TemporaryFileItem():
__slots__ = ['_tree', '_proxy', '__weakref__']
def __init__(self, tree, pathProxy):
self._tree = tree
self._proxy = pathProxy
self._proxy.taskFinished.connect(self.onSearchResult)
tree._temporaryItems.add(self)
def search(self, searchFilter):
... |
class UdemyChapters(object):
def __init__(self):
self._chapter_id = None
self._chapter_index = None
self._chapter_title = None
self._lectures_count = None
self._lectures = []
def __repr__(self):
chapter = '{title}'.format(title=self.title)
return chapter
... |
class TestReference():
def test_complex_scalar(self):
nblock = np.array([1])
itype = np.array([2])
z = np.array([[(1 + 2j)]])
mu = ab13md(z, nblock, itype)[0]
assert_allclose(mu, abs(z))
def test_real_scalar_real_uncertainty(self):
nblock = np.array([1])
i... |
def get_jalali_date_from_julian_day(julian_day):
julian_day = (floor(julian_day) + 0.5)
offset = (julian_day - 2121445.5)
cycle = floor((offset / 1029983))
remaining = (offset % 1029983)
if (remaining == 1029982):
year_cycle = 2820
else:
a1 = floor((remaining / 366))
a2 =... |
def MGGAN_main(opt):
g = Globals()
opt.workers = 2
opt.batchSize = 64
opt.imageSize = 64
nc = (1 if opt.data.startswith('mnist') else 3)
opt.nz = 100
opt.ngf = 64
opt.ndf = 64
opt.niter = 30
opt.lr = 0.0002
opt.beta1 = 0.5
opt.cuda = True
opt.ngpu = 1
opt.netG = '... |
def get_fock(h1e, s1e, vhf, dm, cycle=(- 1), diis=None, diis_start_cycle=None, level_shift_factor=None, damp_factor=None):
if (cycle < 5):
level_shift_factor = (level_shift0 * (0.5 ** cycle))
print(('Set level shift to %g' % level_shift_factor))
else:
level_shift_factor = 0
return ol... |
class TestMPMWithMechanics(TestCase):
def test_well_posed_negative_cracking_not_implemented(self):
options = {'particle mechanics': ('swelling and cracking', 'none')}
with self.assertRaises(NotImplementedError):
pybamm.lithium_ion.MPM(options)
def test_well_posed_positive_cracking_no... |
def gen_br2_template(num_nops_src0, num_nops_src1, reg_src0, reg_src1, inst, src0, src1, taken):
if taken:
control_flow_pattern = 42
else:
control_flow_pattern = 63
global gen_br2_template_id
id_a = 'label_{}'.format((gen_br2_template_id + 1))
id_b = 'label_{}'.format((gen_br2_templa... |
class TestPywrRandomGenerator():
def test_current_model(self, two_reservoir_problem):
generator = PywrRandomGenerator(wrapper=two_reservoir_problem)
algorithm = NSGAII(two_reservoir_problem.problem, population_size=10, generator=generator)
algorithm.initialize()
solution = algorithm.... |
class Tget_gtk_bookmarks(TestCase):
def test_main(self):
paths = get_gtk_bookmarks()
assert all((isinstance(p, fsnative) for p in paths))
def test_parse(self):
if is_windows():
return
data = b'file:///foo/bar\nfile:///home/user\nfile:///home/user/Downloads Downloads\n... |
def export(preprocessor: Union[('PreTrainedTokenizer', 'FeatureExtractionMixin', 'ProcessorMixin')], model: Union[('PreTrainedModel', 'TFPreTrainedModel')], config: OnnxConfig, opset: int, output: Path, tokenizer: 'PreTrainedTokenizer'=None, device: str='cpu') -> Tuple[(List[str], List[str])]:
if (not (is_torch_ava... |
class MaskFormerSwinModelTester():
def __init__(self, parent, batch_size=13, image_size=32, patch_size=2, num_channels=3, embed_dim=16, depths=[1, 2, 1], num_heads=[2, 2, 4], window_size=2, mlp_ratio=2.0, qkv_bias=True, hidden_dropout_prob=0.0, attention_probs_dropout_prob=0.0, drop_path_rate=0.1, hidden_act='gelu'... |
class MalGAN():
def __init__(self):
self.apifeature_dims = 74
self.z_dims = 10
self.hide_layers = 256
self.generator_layers = [(self.apifeature_dims + self.z_dims), self.hide_layers, self.apifeature_dims]
self.substitute_detector_layers = [self.apifeature_dims, self.hide_laye... |
class BuildSourceSet():
def __init__(self, sources: list[BuildSource]) -> None:
self.source_text_present = False
self.source_modules: dict[(str, str)] = {}
self.source_paths: set[str] = set()
for source in sources:
if (source.text is not None):
self.source... |
class Message(Message):
_e_label = property((lambda x: getattr(x, 'details').get('severity', 'MESSAGE')))
_e_factors = ('creator',)
def _e_metas(self, get0=itemgetter(0)):
(yield (None, self.message))
if (self.code and (self.code != '00000')):
(yield ('CODE', self.code))
... |
class QuestionViewSet(ModelViewSet):
permission_classes = ((HasModelPermission | HasObjectPermission),)
serializer_class = QuestionSerializer
filter_backends = (SearchFilter, DjangoFilterBackend)
search_fields = ('uri', 'text')
filterset_fields = ('attribute', 'uri', 'uri_prefix', 'uri_path', 'is_co... |
def parse_basic_str_escape(src: str, pos: Pos, *, multiline: bool=False) -> Tuple[(Pos, str)]:
escape_id = src[pos:(pos + 2)]
pos += 2
if (multiline and (escape_id in {'\\ ', '\\\t', '\\\n'})):
if (escape_id != '\\\n'):
pos = skip_chars(src, pos, TOML_WS)
try:
... |
class NodeNG():
is_statement: ClassVar[bool] = False
optional_assign: ClassVar[bool] = False
is_function: ClassVar[bool] = False
is_lambda: ClassVar[bool] = False
_astroid_fields: ClassVar[tuple[(str, ...)]] = ()
_other_fields: ClassVar[tuple[(str, ...)]] = ()
_other_other_fields: ClassVar[t... |
.parametrize('env_name', ML1.ENV_NAMES)
def test_all_ml1(env_name):
ml1 = ML1(env_name)
train_env_instances = {env_name: env_cls() for (env_name, env_cls) in ml1.train_classes.items()}
train_env_rand_vecs = check_tasks_unique(ml1.train_tasks, ml1._train_classes.keys())
for task in ml1.train_tasks:
... |
class CTRLModelTester():
def __init__(self, parent, batch_size=14, seq_length=7, is_training=True, use_token_type_ids=True, use_input_mask=True, use_labels=True, use_mc_token_ids=True, vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37, hidden_act='gelu', hidden_dropout_... |
def _clean_header(header):
if isinstance(header, str):
header = {'description': header}
typedef = header.get('type', 'string')
if (isinstance(typedef, Hashable) and (typedef in PY_TYPES)):
header['type'] = PY_TYPES[typedef]
elif (isinstance(typedef, (list, tuple)) and (len(typedef) == 1)... |
class CompositeOptimizerConfig(FairseqDataclass):
groups: Dict[(str, OptimizerAndSchedulerConfig)] = field(default_factory=(lambda : {}), metadata={'help': 'optimizer name -> optimizer OptimizerAndSchedulerConfig. Configures a different optimizer and (optionally) lr scheduler for each parameter group'}) |
def test_no_missing_resource_types():
request_interceptor = interceptor.RequestInterceptor()
qb_keys = set(request_interceptor._resource_types.keys())
qt_keys = set(testutils.enum_members(QWebEngineUrlRequestInfo, QWebEngineUrlRequestInfo.ResourceType).values())
assert (qt_keys == qb_keys) |
def get_ytplayer_js(html: str) -> Any:
js_url_patterns = ['(/s/player/[\\w\\d]+/[\\w\\d_/.]+/base\\.js)']
for pattern in js_url_patterns:
regex = re.compile(pattern)
function_match = regex.search(html)
if function_match:
logger.debug('finished regex search, matched: %s', patt... |
class FullyConnectedContextMerge(SequenceMapperWithContext):
def __init__(self, output_size, init='glorot_uniform', activation='tanh', use_dots=False, keep_probs=1, context_keep_probs=1):
self.output_size = output_size
self.activation = activation
self.init = init
self.context_keep_p... |
class TransformerPredictor(nn.Module):
def __init__(self, config):
super(TransformerPredictor, self).__init__()
self.transformer_decoder = TransformerDecoder(config)
self.area_decoder = nn.Sequential(nn.Linear(config['encode_dim'], config['area_num'], bias=False))
self.shot_decoder =... |
_node(_all_prototype_parents, _prototype_load_select)
def node_prototype_load(caller, **kwargs):
text = '\n Select a prototype to load. This will replace any prototype currently being edited!\n '
_set_actioninfo(caller, _format_list_actions('examine', 'delete'))
helptext = '\n Loading a pro... |
def average_models(model_files, fp32=False):
vocab = None
opt = None
avg_model = None
avg_generator = None
for (i, model_file) in enumerate(model_files):
m = torch.load(model_file, map_location='cpu')
model_weights = m['model']
generator_weights = m['generator']
if fp... |
def test_povm():
coeff = (sqrt(2) / (1 + sqrt(2)))
E_1 = (coeff * ket2dm(basis(2, 1)))
E_2 = (coeff * ket2dm(((basis(2, 0) - basis(2, 1)) / sqrt(2))))
E_3 = ((identity(2) - E_1) - E_2)
M_1 = E_1.sqrtm()
M_2 = E_2.sqrtm()
M_3 = E_3.sqrtm()
ket1 = basis(2, 0)
ket2 = ((basis(2, 0) + bas... |
class InsetMaps(Maps):
def __init__(self, parent, crs=4326, layer=None, xy=(45, 45), xy_crs=4326, radius=5, radius_crs=None, plot_position=(0.5, 0.5), plot_size=0.5, shape='ellipses', indicate_extent=True, indicator_line=False, boundary=True, background_color='w', **kwargs):
self._parent_m = self._proxy(par... |
def weight_quantization(b, grids, power=True):
def uniform_quant(x, b):
xdiv = x.mul(((2 ** b) - 1))
xhard = xdiv.round().div(((2 ** b) - 1))
return xhard
def power_quant(x, value_s):
shape = x.shape
xhard = x.view((- 1))
value_s = value_s.type_as(x)
idxs ... |
class MetricList(EvalMetric):
def __init__(self, *args, name='metric_list'):
assert all([issubclass(type(x), EvalMetric) for x in args]), 'MetricList input is illegal: {}'.format(args)
self.metrics = [metric for metric in args]
super(MetricList, self).__init__(name=name)
def update(self,... |
def run_experiment(dataset: Dataset, method: PromptMethod, evaluator: Evaluator) -> Dict:
(predictions, gold_answers) = ([], [])
with open(group_file, 'r') as f:
groups = json.load(f)
grouped_dataset = [[] for _ in range(len(groups))]
for (group_idx, group) in enumerate(groups):
grouped_... |
class RandomVerticalFlip(object):
def __call__(self, sample):
img1 = sample['image'][0]
img2 = sample['image'][1]
mask = sample['label']
if (random.random() < 0.5):
img1 = img1.transpose(Image.FLIP_TOP_BOTTOM)
img2 = img2.transpose(Image.FLIP_TOP_BOTTOM)
... |
class PriorProbability(keras.initializers.Initializer):
def __init__(self, probability=0.01):
self.probability = probability
def get_config(self):
return {'probability': self.probability}
def __call__(self, shape, dtype=None):
result = (np.ones(shape, dtype=dtype) * (- math.log(((1 -... |
class SubmitControl(ScalarControl):
def __init__(self, type, name, attrs, index=None):
ScalarControl.__init__(self, type, name, attrs, index)
if (self.value is None):
self.__dict__['_value'] = ''
self.readonly = True
def get_labels(self):
res = []
if self.valu... |
class CSVPrettyTable(PrettyTable):
def get_string(self, **kwargs: (str | list[str])) -> str:
def esc_quotes(val: (bytes | str)) -> str:
try:
return cast(str, val).replace('"', '""')
except UnicodeDecodeError:
return cast(bytes, val).decode('utf-8').rep... |
def test_uniquifier_error():
obj1 = [1]
obj2 = [2]
obj3 = [3]
obj4 = [4]
objs = [obj1, obj2, obj1, obj1, obj2]
objs2 = [obj1, obj2, obj1, obj1, obj2, obj2]
uniq = Uniquifier(objs)
try:
unique_objs = uniq.get_unique_objs(objs2)
assert False, 'Expected a RuntimeError'
e... |
def assert_database_is_reset(conn):
conn.execute('ALTER TABLE names ADD COLUMN deprecated_column')
(names_ddl,) = [ddl for ddl in conn.iterdump() if ('CREATE TABLE names' in ddl)]
assert ('deprecated_column' in names_ddl)
(yield)
(names_ddl,) = [ddl for ddl in conn.iterdump() if ('CREATE TABLE names... |
class garmintools_full():
def __init__(self, parent=None, validate=False):
self.parent = parent
self.pytrainer_main = parent.pytrainer_main
self.confdir = self.pytrainer_main.profile.confdir
self.tmpdir = self.pytrainer_main.profile.tmpdir
os.environ['GARMIN_SAVE_RUNS'] = sel... |
def run_process(gpu, train_data, valid_data, dicts, opt, checkpoint, constants):
from onmt.train_utils.mp_trainer import Trainer
from onmt.train_utils.clip_trainer import ClipTrainer
if opt.clip_learning:
trainer = ClipTrainer(gpu, dicts, opt, constants)
trainer.run(checkpoint=checkpoint, tr... |
def gen_verify_hash(shared_key: bytes, public_key: bytes):
verify_hash = hashlib.sha1()
verify_hash.update((' ' * 20).encode('utf-8'))
verify_hash.update(shared_key)
verify_hash.update(public_key)
return format(int.from_bytes(verify_hash.digest(), byteorder='big', signed=True), 'x') |
class NeuMF(torch.nn.Module):
def __init__(self, config):
super(NeuMF, self).__init__()
self.config = config
self.num_users = config['num_users']
self.num_items = config['num_items']
self.latent_dim_mf = config['latent_dim_mf']
self.latent_dim_mlp = config['latent_dim... |
def show_proj_bbox_img(input, out_dir, show=False, is_nus_mono=False):
gt_bboxes = input['gt_bboxes_3d']._data
img_metas = input['img_metas']._data
img = input['img']._data.numpy()
img = img.transpose(1, 2, 0)
if (gt_bboxes.tensor.shape[0] == 0):
gt_bboxes = None
filename = Path(img_meta... |
class DateTimeProperty(JSONProperty):
def make_expression(self, base_exp):
try:
return base_exp.astext.cast(sa.DateTime)
except AttributeError:
return sa.func.json_unquote(base_exp).cast(mysql.DATETIME(fsp=6))
def decode(self, val):
if val:
val = datet... |
class SponsorshipBenefitModelTests(TestCase):
def test_with_conflicts(self):
(benefit_1, benefit_2, benefit_3) = baker.make(SponsorshipBenefit, _quantity=3)
benefit_1.conflicts.add(benefit_2)
qs = SponsorshipBenefit.objects.with_conflicts()
self.assertEqual(2, qs.count())
sel... |
def XForwardedForMiddleware(get_response):
def middleware(request):
if ('HTTP_X_FORWARDED_FOR' in request.META.keys()):
request.META['HTTP_X_PROXY_REMOTE_ADDR'] = request.META['REMOTE_ADDR']
parts = request.META['HTTP_X_FORWARDED_FOR'].split(',', 1)
request.META['REMOTE_A... |
def test_resolve_package_path(tmp_path: Path) -> None:
pkg = (tmp_path / 'pkg1')
pkg.mkdir()
(pkg / '__init__.py').touch()
(pkg / 'subdir').mkdir()
(pkg / 'subdir/__init__.py').touch()
assert (resolve_package_path(pkg) == pkg)
assert (resolve_package_path((pkg / 'subdir/__init__.py')) == pkg... |
class GridSearch():
def __init__(self, appr_ft, seed, gs_config='gridsearch_config', acc_drop_thr=0.2, hparam_decay=0.5, max_num_searches=7):
self.seed = seed
GridSearchConfig = getattr(importlib.import_module(name=gs_config), 'GridSearchConfig')
self.appr_ft = appr_ft
self.gs_config... |
class DeepFM(nn.Module):
def __init__(self, dense_module: nn.Module) -> None:
super().__init__()
self.dense_module = dense_module
def forward(self, embeddings: List[torch.Tensor]) -> torch.Tensor:
deepfm_input = _get_flatten_input(embeddings)
deepfm_output = self.dense_module(dee... |
class _TestFileObj(object):
def __init__(self, fileobj, stop_after=(- 1), fail_after=(- 1)):
self._fileobj = fileobj
self._stop_after = stop_after
self._fail_after = fail_after
self.dataread = 0
self.operations = 0
fileobj.seek(0, 0)
def _check_fail(self):
... |
class CaffeineBeverageWithHook(ABC):
def prepareRecipe(self) -> None:
self.boilWater()
self.brew()
self.pourInCup()
if self.customerWantsCondiments():
self.addCondiments()
def brew(self) -> None:
pass
def addCondiments(self) -> None:
pass
def b... |
class GC(Fontable):
__gc__ = resource.Resource.__resource__
def change(self, onerror=None, **keys):
request.ChangeGC(display=self.display, onerror=onerror, gc=self.id, attrs=keys)
def copy(self, src_gc, mask, onerror=None):
request.CopyGC(display=self.display, onerror=onerror, src_gc=src_gc,... |
class DAEModel(BaseModel):
def __init__(self, args):
super().__init__(args)
self.input_dropout = nn.Dropout(p=args.dae_dropout)
dims = (([args.dae_hidden_dim] * 2) * args.dae_num_hidden)
dims = (([args.num_items] + dims) + [args.dae_latent_dim])
(encoder_modules, decoder_modu... |
class CopyLoader(Loadable, FileManagerAware):
progressbar_supported = True
def __init__(self, copy_buffer, do_cut=False, overwrite=False, dest=None, make_safe_path=get_safe_path):
self.copy_buffer = tuple(copy_buffer)
self.do_cut = do_cut
self.original_copy_buffer = copy_buffer
s... |
.asyncio(scope='class')
class TestInOneEventLoopPerClass():
loop: asyncio.AbstractEventLoop
async def test_remember_loop(self):
TestInOneEventLoopPerClass.loop = asyncio.get_running_loop()
async def test_assert_same_loop(self):
assert (asyncio.get_running_loop() is TestInOneEventLoopPerClass... |
(permission_classes=[IsAuthenticated])
def subscribe_user_to_association(info: Info) -> SubscribeUserResult:
user = info.context.request.user
membership = Membership.objects.of_user(user).first()
local_stripe_customer = None
if (not membership):
membership = Membership.objects.create(user=user)
... |
.parametrize('info1, info2, equal', [(keyutils.KeyInfo(Qt.Key.Key_A, Qt.KeyboardModifier.NoModifier), keyutils.KeyInfo(Qt.Key.Key_A, Qt.KeyboardModifier.NoModifier), True), (keyutils.KeyInfo(Qt.Key.Key_A, Qt.KeyboardModifier.NoModifier), keyutils.KeyInfo(Qt.Key.Key_B, Qt.KeyboardModifier.NoModifier), False), (keyutils.... |
class ProjectMergeRequestResourceStateEventManager(RetrieveMixin, RESTManager):
_path = '/projects/{project_id}/merge_requests/{mr_iid}/resource_state_events'
_obj_cls = ProjectMergeRequestResourceStateEvent
_from_parent_attrs = {'project_id': 'project_id', 'mr_iid': 'iid'}
def get(self, id: Union[(str,... |
class Actor(nn.Module):
def __init__(self, state_dim, action_dim, max_action):
super(Actor, self).__init__()
self.l1 = nn.Linear(state_dim, 256)
self.l2 = nn.Linear(256, 256)
self.l3 = nn.Linear(256, action_dim)
self.max_action = max_action
def forward(self, state):
... |
class Check():
module: str
origin: str
browser: Browser
browser_binary: Optional[str]
include_paths: List[str]
headless: bool
capture_screenshots: bool
cookies: List[Cookie]
driver_log_file: Optional[str]
extra_desired_capabilities: Optional[Dict[(str, Any)]]
remote_webdriver... |
class MakeBBoxSquare(BBoxTransform):
def __call__(self, bbox: List[float], image_size: Tuple[(int, int)]) -> List[float]:
(x, y, w, h) = (bbox[0], bbox[1], bbox[2], bbox[3])
larger_dim = max(w, h)
w_half_extra = ((larger_dim - w) / 2)
h_half_extra = ((larger_dim - h) / 2)
new... |
class AffineTransformed(TransformedDistribution):
def __init__(self, base_distribution: Distribution, loc=None, scale=None, event_dim=0):
self.scale = (1.0 if (scale is None) else scale)
self.loc = (0.0 if (loc is None) else loc)
super().__init__(base_distribution, [AffineTransform(loc=self.... |
def test_update_legacy_questions(db, settings):
xml_file = ((((Path(settings.BASE_DIR) / 'xml') / 'elements') / 'legacy') / 'questions.xml')
root = read_xml_file(xml_file)
version = root.attrib.get('version')
elements = flat_xml_to_elements(root)
elements = convert_elements(elements, version)
el... |
class FrozenSet(node_classes.BaseContainer):
def pytype(self) -> Literal['builtins.frozenset']:
return 'builtins.frozenset'
def _infer(self, context: (InferenceContext | None)=None, **kwargs: Any):
(yield self)
_property
def _proxied(self):
ast_builtins = AstroidManager().builtin... |
def create_classifier_and_diffusion(image_size, classifier_use_fp16, classifier_width, classifier_depth, classifier_attention_resolutions, classifier_use_scale_shift_norm, classifier_resblock_updown, classifier_pool, learn_sigma, diffusion_steps, noise_schedule, timestep_respacing, use_kl, predict_xstart, rescale_times... |
class CNN_DUQ(Model):
def __init__(self, num_classes, embedding_size, learnable_length_scale, length_scale, gamma):
super().__init__()
self.gamma = gamma
self.W = nn.Parameter(torch.normal(torch.zeros(embedding_size, num_classes, 256), 0.05))
self.register_buffer('N', (torch.ones(num... |
def assert_kraus_equivalence(a, b, tol=tol):
assert (a.shape == b.shape)
assert (a.dims == b.dims)
assert (a.type == b.type)
(a, b) = (a.full(), b.full())
a_nz = np.nonzero((np.abs(a) > tol))
if (len(a_nz[0]) == 0):
np.testing.assert_allclose(b, 0, atol=tol)
(a_el, b_el) = (a[(a_nz[0... |
def train(args, model, train_data_loader, dev_data_loader):
loss_func = CrossEntropyLoss()
if (args['type'] == 'BERT'):
param_optimizer = list(model.named_parameters())
no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
optimizer_grouped_parameters = [{'params': [p for (n, p) in p... |
def build_network(config, channels, num_classes, anchors, num_layers):
depth_mul = config.model.depth_multiple
width_mul = config.model.width_multiple
num_repeat_backbone = config.model.backbone.num_repeats
channels_list_backbone = config.model.backbone.out_channels
num_repeat_neck = config.model.ne... |
def _make_constraints(*rhos):
constraints = [(cvxpy.trace(rho.re) == 1) for rho in rhos]
for rho in rhos:
constraints += ([(rho.re == rho.re.T)] + [(rho.im == (- rho.im.T))])
constraints += [(cvxpy.bmat([[rho.re, (- rho.im)], [rho.im, rho.re]]) >> 0) for rho in rhos]
return constraints |
class AnswersExportMixin():
def get_data(self):
self.project.catalog.prefetch_elements()
project_wrapper = ProjectWrapper(self.project, self.snapshot)
data = []
for question in project_wrapper.questions:
set_prefixes = view_tags.get_set_prefixes({}, question['attribute'],... |
class BallQuery(Function):
def forward(ctx, radius: float, nsample: int, xyz: torch.Tensor, new_xyz: torch.Tensor) -> torch.Tensor:
assert new_xyz.is_contiguous()
assert xyz.is_contiguous()
(B, N, _) = xyz.size()
npoint = new_xyz.size(1)
idx = torch.cuda.IntTensor(B, npoint, ... |
class TorchXArgumentHelpFormatter(argparse.HelpFormatter):
def _get_help_string(self, action: argparse.Action) -> str:
help = (action.help or '')
if (action.default is argparse.SUPPRESS):
return help
if action.required:
help += ' (required)'
else:
... |
class Crypt(CryptAbstract):
encryption_algorithm = 'SYMMETRIC_DEFAULT'
key_id = ''
def __init__(self, *args, **kwargs) -> None:
self._init_boto()
super().__init__(*args, **kwargs)
def encrypt(self, message: str) -> str:
ciphertext = self.client.encrypt(KeyId=self.config.key_id, P... |
def relaxation_frequency_nitrogen(pressure, temperature, h, reference_pressure=REFERENCE_PRESSURE, reference_temperature=REFERENCE_TEMPERATURE):
return (((pressure / reference_pressure) * ((temperature / reference_temperature) ** (- 0.5))) * (9.0 + ((280.0 * h) * np.exp(((- 4.17) * (((temperature / reference_temper... |
def test_failing_command(tmp_path):
project_dir = (tmp_path / 'project')
test_projects.new_c_project().generate(project_dir)
with pytest.raises(subprocess.CalledProcessError):
utils.cibuildwheel_run(project_dir, add_env={'CIBW_BEFORE_BUILD': 'false', 'CIBW_BEFORE_BUILD_WINDOWS': 'exit /b 1'}) |
class Effect7080(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Large Precursor Weapon')), 'damageMultiplier', ship.getModifiedItemAttr('shipBonusPBS2'), skill='Precursor Battleship', **kwargs) |
(scope='function')
def sapm_dc_snl_ac_system(sapm_module_params, cec_inverter_parameters, sapm_temperature_cs5p_220m):
module = 'Canadian_Solar_CS5P_220M___2009_'
module_parameters = sapm_module_params.copy()
temp_model_params = sapm_temperature_cs5p_220m.copy()
system = PVSystem(surface_tilt=32.2, surf... |
def get_dependencies(argv: Optional[List[str]]=None) -> None:
parser = get_parser()
args = parser.parse_args(argv)
pkg_mgr = args.pkg_mgr.lower()
fn_names = {f"get_reqs_{pkg_mgr}{('_dev' if args.dev else '')}", f'get_reqs_{pkg_mgr}', f"get_reqs_{pkg_mgr}{('_torch' if args.torch else '')}", f"get_reqs_{p... |
def get_tl_line_values(line, LTRB=True, withTranscription=False, withConfidence=False, imWidth=0, imHeight=0):
confidence = 0.0
transcription = ''
points = []
numPoints = 4
if LTRB:
numPoints = 4
if (withTranscription and withConfidence):
m = re.match('^\\s*(-?[0-9]+)\\s*... |
def make_zone_file(zone, filename, serial, header, record_list):
try:
with open(filename, 'w') as f:
f.writelines(header)
run_command_with_code(('sed -i "s/pre_serial/%s/" %s' % (str(serial), filename)))
with open(filename, 'a') as f:
for item in record_list:
... |
def get_all_tags(skopeo: SkopeoMirror, mirror: RepoMirrorConfig) -> list[str]:
verbose_logs = (os.getenv('DEBUGLOG', 'false').lower() == 'true')
username = (mirror.external_registry_username.decrypt() if mirror.external_registry_username else None)
password = (mirror.external_registry_password.decrypt() if ... |
def test_DecisionMatrixDominanceAccessor_bt():
dm = data.mkdm(matrix=[[10, 40], [20, 70]], objectives=[max, min], alternatives=['A0', 'A1'], criteria=['C0', 'C1'])
dom = dominance.DecisionMatrixDominanceAccessor(dm)
expected = pd.DataFrame([[0, 1], [1, 0]], index=['A0', 'A1'], columns=['A0', 'A1'])
expe... |
class TestRuntime(TestNameCheckVisitorBase):
_passes()
def test_overload(self):
from pyanalyze.extensions import deprecated, overload
('int support is deprecated')
def deprecated_overload(x: int) -> int:
...
def deprecated_overload(x: str) -> str:
...
... |
(cc=STDCALL, params={'lpTopLevelExceptionFilter': LPTOP_LEVEL_EXCEPTION_FILTER})
def hook_SetUnhandledExceptionFilter(ql: Qiling, address: int, params):
addr = params['lpTopLevelExceptionFilter']
handle = ql.os.handle_manager.search('TopLevelExceptionHandler')
if (handle is None):
handle = Handle(na... |
class BTOOLS_OT_materials_clear(bpy.types.Operator):
bl_idname = 'btools.materials_clear'
bl_label = 'Clear Empty Material Groups'
bl_options = {'REGISTER', 'UNDO'}
def poll(cls, context):
obj = context.object
return (obj and (obj.type == 'MESH'))
def execute(self, context):
... |
.parametrize('tuf_prefix,server_hostname,namespace,repo,gun', [('quay.dev', 'quay.io', 'ns', 'repo', 'quay.dev/ns/repo'), (None, 'quay.io', 'ns', 'repo', 'quay.io/ns/repo'), ('quay.dev/', 'quay.io', 'ns', 'repo', 'quay.dev/ns/repo'), (None, 'quay.io/', 'ns', 'repo', 'quay.io/ns/repo'), (None, 'localhost:5000/', 'ns', '... |
class uvm_nonblocking_put_port(uvm_port_base):
def try_put(self, data):
try:
success = self.export.try_put(data)
return success
except AttributeError:
raise UVMTLMConnectionError(f'Missing or wrong export in {self.get_full_name()}. Did you connect it?')
def ca... |
class QtileMigrate():
def __call__(self, args: argparse.Namespace) -> None:
if ('libcst' not in sys.modules):
print("libcst can't be found. Unable to migrate config file.")
print('Please install it and try again.')
sys.exit(1)
self.args = args
self.filter_... |
class TrainingSampler(Sampler):
def __init__(self, size: int, shuffle: bool=True, seed: Optional[int]=None):
self._size = size
assert (size > 0)
self._shuffle = shuffle
if (seed is None):
seed = comm.shared_random_seed()
self._seed = int(seed)
self._rank =... |
class GifReplyDataset(torch.utils.data.Dataset):
tokenizer = AutoTokenizer.from_pretrained('vinai/bertweet-base')
def __init__(self, dataset_path, metadata_path, train=True, test=False, dev_size=0.05, multiclass=False, max_seq_length=128, random_state=42, reuse_data=None, **kwargs):
self.train = train
... |
_lr_scheduler('triangular')
class TriangularSchedule(LegacyFairseqLRScheduler):
def __init__(self, args, optimizer):
super().__init__(args, optimizer)
if (len(args.lr) > 1):
raise ValueError('Cannot use a fixed learning rate schedule with triangular. Consider --lr-scheduler=fixed instead... |
class TestUser1DSubMesh(TestCase):
def test_exceptions(self):
edges = np.array([0, 0.3, 1])
submesh_params = {'edges': edges}
mesh = pybamm.MeshGenerator(pybamm.UserSupplied1DSubMesh, submesh_params)
lims = {'x_n': {'min': 0, 'max': 1}}
npts = {'x_n': 10}
with self.as... |
def update_pkg_resources():
vendor = Path('pkg_resources/_vendor')
install(vendor)
rewrite_packaging((vendor / 'packaging'), 'pkg_resources.extern')
rewrite_jaraco_text((vendor / 'jaraco/text'), 'pkg_resources.extern')
rewrite_jaraco((vendor / 'jaraco'), 'pkg_resources.extern')
rewrite_importlib... |
def extract_games(zip_filename, dst, force=False):
zipped_file = zipfile.ZipFile(zip_filename)
filenames_to_extract = [f for f in zipped_file.namelist() if (f.endswith('.z8') or f.endswith('.json'))]
subdirs = {'train': pjoin(dst, 'train'), 'valid': pjoin(dst, 'valid'), 'test': pjoin(dst, 'test')}
for d... |
class SpectralVolume1DSubMesh(SubMesh1D):
def __init__(self, lims, npts, edges=None, order=2):
(spatial_var, spatial_lims, tabs) = self.read_lims(lims)
npts = npts[spatial_var.name]
if (edges is None):
edges = np.linspace(spatial_lims['min'], spatial_lims['max'], (npts + 1))
... |
class Topic(TimeStampedModel, models.Model):
CACHE_KEY = 'keyword-topic-mapping'
CACHE_TIMEOUT = (60 * 30)
name = models.CharField(max_length=255)
slug = models.SlugField(_('Slug'), max_length=200, unique=True)
selectable = models.BooleanField(default=False, help_text=_('Whether advertisers can sele... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.