code stringlengths 281 23.7M |
|---|
class PyMTLTypeError(Exception):
def __init__(self, blk, ast, msg):
fname = os.path.abspath(inspect.getsourcefile(blk))
line = inspect.getsourcelines(blk)[1]
col = 0
code = ''
try:
line += (ast.lineno - 1)
col = ast.col_offset
code_line = i... |
class SetupCallback(Callback):
def __init__(self, resume, now, logdir, ckptdir, cfgdir, config, lightning_config):
super().__init__()
self.resume = resume
self.now = now
self.logdir = logdir
self.ckptdir = ckptdir
self.cfgdir = cfgdir
self.config = config
... |
class HwndMeta(BaseMeta):
re_wrappers = {}
str_wrappers = {}
def __init__(cls, name, bases, attrs):
BaseMeta.__init__(cls, name, bases, attrs)
for win_class in cls.windowclasses:
HwndMeta.re_wrappers[re.compile(win_class)] = cls
HwndMeta.str_wrappers[win_class] = cls
... |
class TestGivensMatrix(QiskitNatureTestCase):
((0, (1 + 1j)), ((1 + 1j), 0), ((1 + 2j), (3 - 4j)))
def test_givens_matrix(self, a: complex, b: complex):
givens_mat = givens_matrix(a, b)
product = (givens_mat np.array([a, b]))
np.testing.assert_allclose(product[1], 0.0, atol=1e-08) |
class ProbabilisticTensorDictModule(TensorDictModuleBase):
def __init__(self, in_keys: ((NestedKey | List[NestedKey]) | Dict[(str, NestedKey)]), out_keys: ((NestedKey | List[NestedKey]) | None)=None, *, default_interaction_mode: (str | None)=None, default_interaction_type: InteractionType=InteractionType.MODE, dist... |
.parametrize('unary_op', [pytest.param((lambda a: a.conj()), id='conj'), pytest.param((lambda a: a.dag()), id='dag'), pytest.param((lambda a: a.trans()), id='trans'), pytest.param((lambda a: (- a)), id='neg')])
def test_unary_ket(unary_op):
obj = QobjEvo(rand_ket(5))
for t in TESTTIMES:
transformed = un... |
def simple_eval(dataset, prompts, eval_template='Instruction: [PROMPT]\nInput: [INPUT]\nOutput: [OUTPUT]', demos_template='Input: [INPUT]\nOutput: [OUTPUT]', eval_model='text-davinci-002', num_samples=50):
eval_template = template.EvalTemplate(eval_template)
demos_template = template.DemosTemplate(demos_templat... |
class Boundary():
def __init__(self, frequency, flow_resistivity, density=DENSITY, soundspeed=SOUNDSPEED, porosity_decrease=POROSITY_DECREASE, specific_heat_ratio=SPECIFIC_HEAT_RATIO, angle=None, distance=None, impedance_model='db', reflection_model='plane'):
self.frequency = frequency
self.flow_res... |
def trapping_instance(layout: QubitsLayout, u: float, dt: float=0.3, up_particles: int=2, down_particles: int=2) -> FermiHubbardParameters:
hamiltonian = Hamiltonian(sites_count=layout.size, j=1.0, u=u)
initial_state = IndependentChainsInitialState(up=GaussianTrappingPotential(particles=up_particles, center=0.5... |
.skipif((not HAVE_DEPS_FOR_RESOURCE_ESTIMATES), reason='pyscf and/or jax not installed.')
.slow
def test_sf_helper_trunc():
mf = make_diamond_113_szv()
exact_cc = cc.KRCCSD(mf)
eris = exact_cc.ao2mo()
(exact_emp2, _, _) = exact_cc.init_amps(eris)
mymp = mp.KMP2(mf)
Luv = cholesky_from_df_ints(my... |
def netmf_large(args):
logger.info('Running NetMF for a large window size...')
logger.info('Window size is set to be %d', args.window)
A = load_adjacency_matrix(args.input, variable_name=args.matfile_variable_name)
vol = float(A.sum())
(evals, D_rt_invU) = approximate_normalized_graph_laplacian(A, r... |
def cached_path(url_or_filename, cache_dir=None, force_download=False, proxies=None, resume_download=False, user_agent=None):
if (cache_dir is None):
cache_dir = TRANSFORMERS_CACHE
if isinstance(url_or_filename, Path):
url_or_filename = str(url_or_filename)
if isinstance(cache_dir, Path):
... |
class TestS3PartialParquetFileToTable(TestCase):
def test_s3_partial_parquet_file_to_table_sanity(self):
pq_file = ParquetFile(PARQUET_FILE_PATH)
partial_parquet_params = PartialParquetParameters.of(pq_metadata=pq_file.metadata)
self.assertEqual(partial_parquet_params.num_row_groups, 2, 'tes... |
def main():
vk_session = vk_api.VkApi(token='your_group_token')
longpoll = VkBotLongPoll(vk_session, 'your_group_id')
for event in longpoll.listen():
if (event.type == VkBotEventType.MESSAGE_NEW):
print(' :')
print(' : ', end='')
print(event.obj.from_id)
... |
class TestCase(unittest.TestCase):
is_windows = (sys.platform == 'win32')
is_cygwin = (sys.platform == 'cygwin')
is_macos = (sys.platform == 'darwin')
symlinks_can_be_tested = None
def assert_mode_equal(self, expected, actual):
return self.assertEqual(stat.S_IMODE(expected), stat.S_IMODE(act... |
class Mirror(_Widget):
def __init__(self, reflection, **config):
_Widget.__init__(self, reflection.length, **config)
self.reflects = reflection
self._length = 0
self.length_type = self.reflects.length_type
def _configure(self, qtile, bar):
_Widget._configure(self, qtile, ... |
class TestLogTime():
def test_duration(self, caplog):
logger_name = 'qt-tests'
with caplog.at_level(logging.DEBUG, logger_name):
with debug.log_time(logger_name, action='foobar'):
time.sleep(0.1)
assert (len(caplog.records) == 1)
pattern = re.compi... |
def create_line_chart(data_list: List[Union[(QFSeries, DataElementDecorator)]], names_list, title: str=None, recession_series: QFSeries=None, horizontal_lines_list: List[float]=None, vertical_lines_list: List[float]=None, disable_dot: bool=False, start_x: datetime=None, end_x: datetime=None, upper_y: float=None, lower_... |
class HDFEOSBaseFileReader(BaseFileHandler):
def __init__(self, filename, filename_info, filetype_info, **kwargs):
BaseFileHandler.__init__(self, filename, filename_info, filetype_info)
try:
self.sd = SD(self.filename)
except HDF4Error as err:
error_message = 'Could n... |
class TestImportModelCreate():
def loaded_model_class(self):
class BarModel():
a: str
b: int
foo_module = ModuleType('foo')
foo_module.BarModel = BarModel
modules['foo'] = foo_module
(yield BarModel)
del modules['foo']
def test_dynamic_mode... |
def _form_datetimes(days, msecs):
all_datetimes = []
for i in range(days.size):
day = int(days[i])
msec = msecs[i]
scanline_datetimes = []
for j in range(int((VALUES_PER_SCAN_LINE / 4))):
usec = (1000 * ((j * VIEW_TIME_ADJUSTMENT) + msec))
delta = dt.timed... |
def create_stairs(bm, faces, prop):
for f in faces:
f.select = False
if (not valid_ngon(f)):
popup_message('Stairs creation not supported for non-rectangular n-gon!', 'Ngon Error')
return False
f = create_stairs_split(bm, f, prop)
add_faces_to_group(bm, [f], M... |
.parametrize('chunk', [False, True])
.parametrize('genotypes', [[[0, 0], [0, 1], [1, 1]], [[0, 0], [0, 1], [1, 1], [0, 2], [1, 2], [2, 2]], [[0, 0, 0], [0, 0, 1], [0, 1, 1], [1, 1, 1], [0, 0, 2], [0, 1, 2], [1, 1, 2], [0, 2, 2], [1, 2, 2]], [[0, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1], [1, 1, 1, 1]], [[0, 0,... |
class TextureArrayBin():
def __init__(self, texture_width: int=2048, texture_height: int=2048, max_depth: Optional[int]=None) -> None:
max_texture_size = pyglet.image.get_max_texture_size()
self.max_depth = (max_depth or pyglet.image.get_max_array_texture_layers())
self.texture_width = min(t... |
def average_it_results(it_rep_results: Sequence[Sequence[Tuple]]):
d_metric_results = {'avg': [], 'smis': [], 'scores': []}
for it_reps in it_rep_results:
(it_avgs, it_smiss, it_scoress) = zip(*it_reps)
d_metric_results['avg'].append(mean_and_sd(it_avgs))
d_metric_results['smis'].append(... |
class TxOutputColoring():
def __init__(self, *, legend: str, color: ColorSchemeItem, tooltip: str):
self.color = color.as_color(background=True)
self.legend_label = QLabel('<font color={color}>{box_char}</font> = {label}'.format(color=self.color.name(), box_char='', label=legend))
font = sel... |
class BaseLegacyTest(BaseBackendTest):
form = ''
response_body = ''
def setUp(self):
super().setUp()
self.strategy.set_settings({f'SOCIAL_AUTH_{self.name}_FORM_URL': self.strategy.build_absolute_uri(f'/login/{self.backend.name}')})
def extra_settings(self):
return {f'SOCIAL_AUTH_... |
class TestSuggestedType(TestNameCheckVisitorBase):
_passes(settings={ErrorCode.suggested_return_type: True})
def test_return(self):
def capybara():
return 1
def kerodon(cond):
if cond:
return 1
else:
return 2
_passes(setting... |
class ResNetShard2(ResNetBase):
def __init__(self, device, *args, **kwargs):
super(ResNetShard2, self).__init__(Bottleneck, 512, *args, num_classes=num_classes, **kwargs)
self.device = device
self.seq = nn.Sequential(self._make_layer(256, 6, stride=2), self._make_layer(512, 3, stride=2), nn.... |
class LabelContextAttentionBlock(nn.Module):
def __init__(self, in_channels, out_channels, context_type, last_affine=True):
super().__init__()
self.context_type = context_type
self.query_project = nn.Sequential(utils_heads.ConvBNReLU(in_channels, out_channels, kernel_size=1, norm_layer=nn.Ba... |
class PassportElementErrorReverseSide(PassportElementError):
__slots__ = ('file_hash',)
def __init__(self, type: str, file_hash: str, message: str, *, api_kwargs: Optional[JSONDict]=None):
super().__init__('reverse_side', type, message, api_kwargs=api_kwargs)
with self._unfrozen():
s... |
class EchoesGameExportDialog(GameExportDialog, Ui_EchoesGameExportDialog):
_prompt_input_file: bool
_use_prime_models: bool
def game_enum(cls):
return RandovaniaGame.METROID_PRIME_ECHOES
def __init__(self, options: Options, patch_data: dict, word_hash: str, spoiler: bool, games: list[RandovaniaG... |
def get_xpubs_and_der_suffixes_from_txinout(tx: PartialTransaction, txinout: Union[(PartialTxInput, PartialTxOutput)]) -> List[Tuple[(str, List[int])]]:
xfp_to_xpub_map = {xfp: bip32node for (bip32node, (xfp, path)) in tx.xpubs.items()}
xfps = [txinout.bip32_paths[pubkey][0] for pubkey in txinout.pubkeys]
t... |
def log_mid_epoch_stats(trainer, progress, extra_meters, log_output):
stats = get_training_stats(trainer)
for (k, v) in log_output.items():
if (k in ['loss', 'nll_loss', 'ntokens', 'nsentences', 'sample_size']):
continue
if ('loss' in k):
extra_meters[k].update(v, log_out... |
class VideoTester():
def __init__(self, args, my_model, ckp):
self.args = args
self.scale = args.scale
self.ckp = ckp
self.model = my_model
(self.filename, _) = os.path.splitext(os.path.basename(args.dir_demo))
def test(self):
torch.set_grad_enabled(False)
... |
class Object(ValueField):
def __init__(self, name, type, default=None):
ValueField.__init__(self, name, default)
self.type = type
self.structcode = self.type.structcode
self.structvalues = self.type.structvalues
def parse_binary_value(self, data, display, length, format):
... |
class DLA(nn.Module):
def __init__(self, inp, oup, kernel_size=3, stride=1, expand_ratio=3, refine_mode='conv_exapnd'):
super(DLA, self).__init__()
hidden_dim = round((inp * expand_ratio))
self.expand_ratio = expand_ratio
self.identity = ((stride == 1) and (inp == oup))
(self... |
.parametrize('username,password', users)
.parametrize('url_name', url_names)
def test_next(db, client, username, password, url_name):
client.login(username=username, password=password)
url = reverse(urlnames['next'], args=[url_name])
response = client.post(url)
if password:
assert (response.stat... |
class NormalDistribution(QuantumCircuit):
def __init__(self, num_qubits: Union[(int, List[int])], mu: Optional[Union[(float, List[float])]]=None, sigma: Optional[Union[(float, List[float])]]=None, bounds: Optional[Union[(Tuple[(float, float)], List[Tuple[(float, float)]])]]=None, upto_diag: bool=False, name: str='P... |
def group_score_lama_eval(lm_results: Dict):
patterns = list(lm_results.keys())
points = 0
data = lm_results[patterns[0]]['data']
for (datum_ind, datum) in enumerate(data):
obj = datum['obj_label']
consistent_true = True
for pattern in patterns:
preds = lm_results[pat... |
def process_game(rand, moves):
wumpus = Wumpus(rand)
creature = rand.choice([Dog, Bear, Horse, Skeleton, Snake, Dragon])(rand)
messages = [f'You are fighting a {creature.name}!']
state = None
for move in moves:
messages.clear()
wumpus.defending = (move == 'DEF')
if wumpus.def... |
def get_param_shape_using_connected_graph(connected_graph: ConnectedGraph, param_name: str):
ops = connected_graph.get_all_ops()
for op in ops.values():
if op.parameters:
for (param, _) in op.parameters.values():
if (param.name == param_name):
return param... |
def sinkhorn(C, epsilon, niter=50, device='cuda'):
m = C.size(0)
n = C.size(1)
mu = Variable(((1.0 / m) * torch.FloatTensor(m).fill_(1).to('cuda')), requires_grad=False)
nu = Variable(((1.0 / n) * torch.FloatTensor(n).fill_(1).to('cuda')), requires_grad=False)
rho = 1
tau = (- 0.8)
lam = (rh... |
def bench_regex_effbot(loops):
if (bench_regex_effbot.data is None):
bench_regex_effbot.data = init_benchmarks()
data = bench_regex_effbot.data
range_it = range(loops)
search = re.search
t0 = pyperf.perf_counter()
for _ in range_it:
for (regex, string) in data:
search... |
def find_fonts_paths(directory, recursive):
if (not os.path.isdir(directory)):
raise OSError(f'Not a directory: {directory}')
extensions = ('.ttf', '.otf')
dir_paths = set()
file_paths = set()
if (not recursive):
dir_paths.add(directory)
for fname in os.listdir(directory):
... |
class BaseLowdimDataset(torch.utils.data.Dataset):
def get_validation_dataset(self) -> 'BaseLowdimDataset':
return BaseLowdimDataset()
def get_normalizer(self, **kwargs) -> LinearNormalizer:
raise NotImplementedError()
def get_all_actions(self) -> torch.Tensor:
raise NotImplementedEr... |
def packageSingleFile(path):
from Cython.Build import cythonize
directives = {'language_level': '3'}
if (path.endswith('.pyc') or path.endswith('.pyo')):
return
current = multiprocessing.current_process()
print(f'Worker-{current.pid}: cythonizing', path)
(dirpath, file) = os.path.split(p... |
def get_coco_imgs_labels_info(split, data_source_dir, args):
from pycocotools.coco import COCO
json_file = f'{data_source_dir}/annotations/instances_{split}2014.json'
assert PathManager.exists(json_file), 'Annotations file does not exist. Abort'
json_data = json.load(PathManager.open(json_file, 'r'))
... |
def main(args):
cfg = setup(args)
if args.eval_only:
model = Trainer.build_model(cfg)
DetectionCheckpointer(model, save_dir=cfg.OUTPUT_DIR).resume_or_load(cfg.MODEL.WEIGHTS, resume=args.resume)
res = Trainer.test(cfg, model)
if comm.is_main_process():
verify_results(c... |
def router_application(num_mock_deployments: int=1, hooks=None):
deployment_map = {}
for i in range(num_mock_deployments):
deployment_map[f'model_{i}'] = MockDeployment.options(name=f'MockDeployment:model_{i}').bind(VLLMApp.parse_yaml(vllm_app_def))
merged_client = MockRouterQueryClient(deployment_m... |
def get_locale_identifier(tup: ((((tuple[str] | tuple[(str, (str | None))]) | tuple[(str, (str | None), (str | None))]) | tuple[(str, (str | None), (str | None), (str | None))]) | tuple[(str, (str | None), (str | None), (str | None), (str | None))]), sep: str='_') -> str:
tup = tuple(tup[:5])
(lang, territory, ... |
.skipif((sys.platform.startswith('linux') and (pg.Qt.QT_LIB == 'PySide6') and ((6, 0) < pg.Qt.PySide6.__version_info__ < (6, 4, 3))), reason='taking gui thread causes segfault')
def test_nested_busy_cursors_clear_after_all_exit():
with pg.BusyCursor():
wait_cursor = pg.Qt.QtCore.Qt.CursorShape.WaitCursor
... |
class UserInputProtocol(SessionDataProtocol, metaclass=ABCMeta):
def get_previously_entered_for_form(cls, form, input_name, entered_input_type):
def save_input_value_for_form(cls, form, input_name, value, entered_input_type):
def get_persisted_for_view(cls, view, key, value_type):
def add_persisted_for_... |
def test_type_param() -> None:
func_node = extract_node('def func[T]() -> T: ...')
assert isinstance(func_node.type_params[0], TypeVar)
assert (func_node.type_params[0].name.name == 'T')
assert (func_node.type_params[0].bound is None)
class_node = extract_node('class MyClass[T]: ...')
assert isi... |
class Conv1d(_ConvBase):
def __init__(self, in_size: int, out_size: int, *, kernel_size: int=1, stride: int=1, padding: int=0, activation=nn.ReLU(inplace=True), bn: bool=False, init=nn.init.kaiming_normal_, bias: bool=True, preact: bool=False, name: str=''):
super().__init__(in_size, out_size, kernel_size, ... |
def disable_all_quantizers(model: torch.nn.Module) -> Handle:
(param_quantizers, input_quantizers, output_quantizers) = get_all_quantizers(model)
all_quantizers = ((param_quantizers + input_quantizers) + output_quantizers)
active_quantizers = set((quantizer for quantizer in all_quantizers if quantizer.enabl... |
def demo():
import textwrap
hello_source = textwrap.dedent('\n def hello():\n try:\n hello_ = "Hello"\n world_ = "World"\n print(f"{hello_}, {world_}!")\n except TypeError as exc:\n print("failed: {}".format(exc))\n \n if __name__ == "__main__":... |
_attr(allow_interpreted_subclasses=True)
class StatementVisitor(Generic[T]):
def visit_assignment_stmt(self, o: mypy.nodes.AssignmentStmt) -> T:
pass
def visit_for_stmt(self, o: mypy.nodes.ForStmt) -> T:
pass
def visit_with_stmt(self, o: mypy.nodes.WithStmt) -> T:
pass
def visit_... |
class KannelBackendView(BaseHttpBackendView):
= ['get']
form_class = KannelForm
def get(self, *args, **kwargs):
return self.post(*args, **kwargs)
def get_form_kwargs(self):
kwargs = super(KannelBackendView, self).get_form_kwargs()
kwargs['data'] = self.request.GET
return... |
def test_std_color_re():
for color in ansi.Fg:
assert ansi.STD_FG_RE.match(str(color))
assert (not ansi.STD_BG_RE.match(str(color)))
for color in ansi.Bg:
assert ansi.STD_BG_RE.match(str(color))
assert (not ansi.STD_FG_RE.match(str(color)))
assert (not ansi.STD_FG_RE.match(f'... |
class TestLogger(logging.Logger):
def initialize(cls):
logging.addLevelName(TRACE, 'TRACE')
logging.setLoggerClass(cls)
if any(((i in sys.argv) for i in ('-v', '--verbose'))):
logging.getLogger().setLevel(TRACE)
elif any(((i in sys.argv) for i in ('-q', '--quiet'))):
... |
def create_cityscapes_label_colormap():
colormap = np.zeros((256, 3), dtype=np.uint8)
colormap[0] = [128, 64, 128]
colormap[1] = [244, 35, 232]
colormap[2] = [70, 70, 70]
colormap[3] = [102, 102, 156]
colormap[4] = [190, 153, 153]
colormap[5] = [153, 153, 153]
colormap[6] = [250, 170, 30... |
class ProjectCommitDiscussionNoteManager(GetMixin, CreateMixin, UpdateMixin, DeleteMixin, RESTManager):
_path = '/projects/{project_id}/repository/commits/{commit_id}/discussions/{discussion_id}/notes'
_obj_cls = ProjectCommitDiscussionNote
_from_parent_attrs = {'project_id': 'project_id', 'commit_id': 'com... |
def _maybe_typed_value(val: Union[(type, str)]) -> Value:
if (val is type(None)):
return KnownValue(None)
elif (val is Hashable):
return _HashableValue(val)
elif ((val is Callable) or is_typing_name(val, 'Callable')):
return CallableValue(ANY_SIGNATURE)
return TypedValue(val) |
def test_multiple_macros(base_app):
macro1 = 'h1'
macro2 = 'h2'
run_cmd(base_app, 'macro create {} help'.format(macro1))
run_cmd(base_app, 'macro create {} help -v'.format(macro2))
(out, err) = run_cmd(base_app, macro1)
verify_help_text(base_app, out)
(out2, err2) = run_cmd(base_app, macro2)... |
class DistillDiffPruningLoss_dynamic(torch.nn.Module):
def __init__(self, teacher_model, base_criterion: torch.nn.Module, ratio_weight=2.0, distill_weight=0.5, dynamic=False, pruning_loc=[3, 6, 9], keep_ratio=[0.75, 0.5, 0.25], clf_weight=0, mse_token=False, print_mode=True):
super().__init__()
self... |
def test_regress(ansi_bar: ProgressBar, ansi_io: BufferedIO) -> None:
ansi_bar.start()
ansi_bar.advance()
ansi_bar.advance()
ansi_bar.advance((- 1))
output = [' 0 [>]', ' 1 [->]', ' 2 [-->]', ' 1 [->]']
expected = generate_output(output)
assert (expected == ansi_io.fetch_error()) |
class WarmupStepLR(torch.optim.lr_scheduler._LRScheduler):
def __init__(self, optimizer, step_size=2, gamma=0.9, warmup_factor=(1.0 / 3), warmup_iters=500, warmup_method='linear', last_epoch=(- 1)):
if (warmup_method not in ('constant', 'linear')):
raise ValueError("Only 'constant' or 'linear' w... |
def get_last_epoch() -> str:
if (constants.job_type != 'fine-tune'):
convergence_path = (constants.job_dir + 'convergence.log')
try:
(epoch_key, _, _) = read_row(path=convergence_path, row=(- 1), col=(0, 1, 2))
except ValueError:
epoch_key = 'Epoch 1'
generati... |
def test(args):
outdir = args.save_folder
if (not os.path.exists(outdir)):
os.makedirs(outdir)
input_transform = transform.Compose([transform.ToTensor(), transform.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])
testset = get_segmentation_dataset(args.dataset, split=args.split, mode=ar... |
class STM32F1xxSpi(QlConnectivityPeripheral):
class Type(ctypes.Structure):
_fields_ = [('CR1', ctypes.c_uint32), ('CR2', ctypes.c_uint32), ('SR', ctypes.c_uint32), ('DR', ctypes.c_uint32), ('CRCPR', ctypes.c_uint32), ('RXCRCR', ctypes.c_uint32), ('TXCRCR', ctypes.c_uint32), ('I2SCFGR', ctypes.c_uint32)]
... |
class Linear(nn.Linear, DiffEqModule):
def __init__(self, in_features: int, out_features: int):
super(Linear, self).__init__(in_features=in_features, out_features=out_features)
def forward(self, t, y, params: Optional[List]=None):
(w, b) = ((self.weight, self.bias) if (params is None) else param... |
class TestDataFrame(unittest.TestCase):
def base_test_internals_empty(self):
empty = ta.dataframe(device=self.device)
self.assertTrue(isinstance(empty, DataFrame))
self.assertEqual(empty.length, 0)
self.assertEqual(empty.null_count, 0)
self.assertEqual(empty.columns, [])
... |
class GetMediaGroup():
async def get_media_group(self: 'pyrogram.Client', chat_id: Union[(int, str)], message_id: int) -> List['types.Message']:
if (message_id <= 0):
raise ValueError('Passed message_id is negative or equal to zero.')
messages = (await self.get_messages(chat_id=chat_id, ... |
def get_test_loaders(config):
assert ('loaders' in config), 'Could not find data loaders configuration'
loaders_config = config['loaders']
logger.info('Creating test set loaders...')
dataset_cls_str = loaders_config.get('dataset', None)
if (dataset_cls_str is None):
dataset_cls_str = 'Standa... |
class CondenseUnit(nn.Module):
def __init__(self, in_channels, out_channels, groups):
super(CondenseUnit, self).__init__()
bottleneck_size = 4
inc_channels = (out_channels - in_channels)
mid_channels = (inc_channels * bottleneck_size)
self.conv1 = condense_complex_conv1x1(in_... |
class CutExecutor(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 Non... |
def test_serializer_update_missing_updated(db):
value = Value.objects.get(project_id=project_id, snapshot=None, attribute__path=attribute_path)
class MockedRequest():
data = {}
class MockedView():
request = MockedRequest()
project = Project.objects.get(id=project_id)
validator = ... |
def loadAWSOrganizations(neo4j_uri, neo4j_user, neo4j_password, data_path, account_name):
neo4j_auth = (neo4j_user, neo4j_password)
neo4j_driver = GraphDatabase.driver(neo4j_uri, auth=neo4j_auth, encrypted=False)
with neo4j_driver.session() as neo4j_session:
loadAWSServiceControlPolicy(neo4j_session... |
class Soil(object):
def __init__(self, model, lidcontrol):
self._model = model
self._lidcontrol = lidcontrol
self._lidcontrolid = lidcontrol._lidcontrolid
def thickness(self):
return self._model.getLidCParam(self._lidcontrolid, LidLayers.soil.value, LidLayersProperty.thickness.va... |
def get_edges(o: object) -> Iterator[tuple[(object, object)]]:
for (s, e) in get_edge_candidates(o):
if isinstance(e, FUNCTION_TYPES):
if hasattr(e, '__closure__'):
(yield ((s, '__closure__'), e.__closure__))
if hasattr(e, '__self__'):
se = e.__self__
... |
class FusedEmbeddingBagCollectionSharder(BaseEmbeddingSharder[FusedEmbeddingBagCollection]):
def shard(self, module: FusedEmbeddingBagCollection, params: Dict[(str, ParameterSharding)], env: ShardingEnv, device: Optional[torch.device]=None) -> ShardedEmbeddingBagCollection:
return ShardedFusedEmbeddingBagCo... |
class InceptionBUnit(nn.Module):
def __init__(self):
super(InceptionBUnit, self).__init__()
in_channels = 1024
self.branches = Concurrent()
self.branches.add_module('branch1', Conv1x1Branch(in_channels=in_channels, out_channels=384))
self.branches.add_module('branch2', ConvSe... |
class KitchenLowdimWrapper(gym.Env):
def __init__(self, env: KitchenBase, init_qpos: Optional[np.ndarray]=None, init_qvel: Optional[np.ndarray]=None, render_hw=(240, 360)):
self.env = env
self.init_qpos = init_qpos
self.init_qvel = init_qvel
self.render_hw = render_hw
def action_... |
class id_parser(object):
reserved = ['AND', 'OR', 'WITH']
tokens = (['LPAR', 'RPAR', 'ID', 'EXC'] + reserved)
precedence = (('nonassoc', 'AND', 'OR'),)
t_ignore = ' \t'
def __init__(self, spdx):
self.spdx = spdx
self.lasttok = None
self.lastid = None
self.lexer = lex.... |
class OddLength(LengthField):
structcode = 'B'
structvalues = 1
def __init__(self, name):
self.name = name
def calc_length(self, length):
return (length % 2)
def parse_value(self, value, display):
if (value == 0):
return 'even'
else:
return 'od... |
def load_conv3d(state_dict, name_pt, sess, name_tf, bias=False, bn=True):
conv_name_tf = os.path.join(name_tf, 'conv_3d')
conv_params = get_conv_params(sess, conv_name_tf, bias=bias)
if bias:
(conv_weights, kernel_shape, in_channels, out_channels, strides, padding, conv_bias) = conv_params
else:... |
class F38Handler(BaseHandler):
version = F38
commandMap = {'auth': commands.authconfig.F35_Authconfig, 'authconfig': commands.authconfig.F35_Authconfig, 'authselect': commands.authselect.F28_Authselect, 'autopart': commands.autopart.F38_AutoPart, 'autostep': commands.autostep.F34_AutoStep, 'bootloader': command... |
def build_detection_train_loader(cfg, mapper=None):
num_workers = get_world_size()
images_per_batch = cfg.SOLVER.IMS_PER_BATCH
assert ((images_per_batch % num_workers) == 0), 'SOLVER.IMS_PER_BATCH ({}) must be divisible by the number of workers ({}).'.format(images_per_batch, num_workers)
assert (images... |
def parse_binary_job(ingress: Queue, egress: Queue, root_directory: Path) -> None:
while True:
try:
path = ingress.get(timeout=0.5)
try:
res = Binary(path, gen_fw_path(path, root_directory))
except Exception as e:
res = e
egress... |
.skip('Disable tests that requires eager execution')
def test_quantizable_mha_export_backwards_pass():
vocab_size = 20000
maxlen = 200
embed_dim = 32
num_heads = 2
ff_dim = 32
inputs = keras.layers.Input(shape=(maxlen,))
positions = tf.range(start=0, limit=maxlen, delta=1)
positions = ke... |
def transfer_tasks_view(transfer_tasks: Dict[(SecretHash, TransferTask)], token_address: TokenAddress=None, channel_id: ChannelID=None) -> List[Dict[(str, Any)]]:
view = []
for (secrethash, transfer_task) in transfer_tasks.items():
transfer = get_transfer_from_task(secrethash, transfer_task)
if ... |
class mySequential(nn.Sequential, BaseNetwork):
def __init__(self, *args):
super(mySequential, self).__init__(*args)
def forward(self, *inputs):
for module in self._modules.values():
if (type(inputs) == tuple):
inputs = module(*inputs)
else:
... |
class MVTecDataset(Dataset):
def __init__(self, dataset_path='D:/dataset/mvtec_anomaly_detection', class_name='bottle', is_train=True, resize=256, cropsize=256):
assert (class_name in CLASS_NAMES), 'class_name: {}, should be in {}'.format(class_name, CLASS_NAMES)
self.dataset_path = dataset_path
... |
class SimulatorProcessStateExchange(SimulatorProcessBase):
def __init__(self, idx, pipe_c2s, pipe_s2c):
super(SimulatorProcessStateExchange, self).__init__(idx)
self.c2s = pipe_c2s
self.s2c = pipe_s2c
def run(self):
player = self._build_player()
context = zmq.Context()
... |
def raise_winerror(winerror: (int | None)=None, *, filename: (str | None)=None, filename2: (str | None)=None) -> NoReturn:
if (winerror is None):
err = ffi.getwinerror()
if (err is None):
raise RuntimeError('No error set?')
(winerror, msg) = err
else:
err = ffi.getwin... |
def dual_basis_jellium_model(grid: Grid, spinless: bool=False, kinetic: bool=True, potential: bool=True, include_constant: bool=False, non_periodic: bool=False, period_cutoff: Optional[float]=None) -> FermionOperator:
n_points = grid.num_points
position_prefactor = ((2.0 * numpy.pi) / grid.volume_scale())
o... |
class LiveSessionTimeFlowController(TimeFlowController):
def __init__(self, scheduler: Scheduler, event_manager: EventManager, real_timer: RealTimer, empty_queue_event_notifier: EmptyQueueEventNotifier):
super().__init__(event_manager, empty_queue_event_notifier)
self.scheduler = scheduler
s... |
class ReduceScatterV_Req(Function):
def forward(ctx, pg: dist.ProcessGroup, myreq: Request[Tensor], rsi: ReduceScatterVInfo, input: Tensor) -> Tensor:
my_rank = dist.get_rank(pg)
if (rsi.codecs is not None):
input = rsi.codecs.forward.encode(input)
output = input.new_empty(rsi.in... |
def get_share_attributes(movie1, movie2):
genre_list1 = movie1.genre
genre_list2 = movie2.genre
(len1, len2) = (len(genre_list1), len(genre_list2))
if ((len1 == 1) and (len2 == 1)):
if (genre_list1[0] == genre_list2[0]):
shared_genre = genre_list1
else:
shared_gen... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.