code stringlengths 281 23.7M |
|---|
def apply_overrides(env_name, source, condition, condition_value, options, new_config, option_types=None):
if (option_types is None):
option_types = RESERVED_OPTIONS
for (raw_option, data) in options.items():
(_, separator, option) = raw_option.rpartition('set-')
overwrite = bool(separat... |
def reflected_binary_operator(op):
assert (not is_comparison(op))
_name(method_name_for_op(op, commute=True))
_numbers_to_my_dtype
def reflected_binary_operator(self, other):
if isinstance(self, NumericalExpression):
(self_expr, other_expr, new_inputs) = self.build_binary_op(op, othe... |
def test_drrgloss():
drrgloss = losses.DRRGLoss()
assert np.allclose(drrgloss.ohem_ratio, 3.0)
pred = torch.tensor([[0, 1, 0], [1, 1, 1], [0, 1, 0]], dtype=torch.float)
target = torch.tensor([[0, 1, 0], [1, 0, 1], [0, 1, 0]], dtype=torch.long)
mask = torch.tensor([[0, 1, 0], [1, 0, 1], [0, 1, 0]], d... |
def _get_channel_state_by_partner_address(chain_state: ChainState, token_network_registry_address: TokenNetworkRegistryAddress, token_address: TokenAddress, partner_address: Address) -> Optional[NettingChannelState]:
token_network = views.get_token_network_by_token_address(chain_state=chain_state, token_network_reg... |
class ResidualConv(nn.Module):
def __init__(self, input_dim, output_dim, stride, padding):
super(ResidualConv, self).__init__()
self.conv_block = nn.Sequential(nn.BatchNorm2d(input_dim), nn.ReLU(), nn.Conv2d(input_dim, output_dim, kernel_size=3, stride=stride, padding=padding), nn.BatchNorm2d(output... |
class Random_NAS():
def __init__(self, B, model, seed, save_dir):
self.save_dir = save_dir
self.B = B
self.model = model
self.seed = seed
self.iters = 0
self.arms = {}
self.node_id = 0
def print_summary(self):
logging.info(self.parents)
obj... |
def load_model(model, model_path, location=None):
state_dict = torch.load(model_path, map_location=location)
if ('state_dict' in state_dict.keys()):
state_dict = state_dict['state_dict']
state_dict = {(k[7:] if k.startswith('module.') else k): v for (k, v) in state_dict.items()}
model.load_state... |
class SpatialAdaptiveSynBatchNorm2d(nn.Module):
def __init__(self, num_features, num_w=512, batchnorm_func=SynchronizedBatchNorm2d, eps=1e-05, momentum=0.1, affine=False, track_running_stats=True):
super(SpatialAdaptiveSynBatchNorm2d, self).__init__()
self.num_features = num_features
self.we... |
def plot_erie(y_true, mean, lb, ub, trainlen, n, r):
plt.plot(range(len(y_true)), y_true, 'b', label='Actual')
plt.plot(range(len(y_true)), mean, 'r', label='ESN Prediction')
plt.fill_between(range(len(y_true)), lb, ub, facecolor='grey', alpha=0.3)
(lo, hi) = plt.ylim()
plt.plot([trainlen, trainlen]... |
def return_somethingv2(modality):
filename_categories = 'something/v2/category.txt'
if (modality == 'RGB'):
root_data = '/mnt/localssd2/aandonia/something/v2/20bn-something-something-v2-frames'
filename_imglist_train = 'something/v2/train_videofolder.txt'
filename_imglist_val = 'somethin... |
class PortfolioLayer(nn.Module):
def __init__(self, latent_size, stock_size, hidden_size=32):
super(PortfolioLayer, self).__init__()
self.net = MLP(input_size=latent_size, output_size=1, hidden_size=hidden_size)
def forward(self, latent_features):
out = self.net(latent_features)
... |
def _create_keras_model(args: SharedArgs, input_shape: InputShape, predictor_heads: List[PredictorHeadInterface]) -> Model:
main_input = create_main_input(input_shape)
if (args.input_weight_decay is None):
input_weight_decay = args.layer_weight_decay
else:
input_weight_decay = args.input_wei... |
class _KeySerializationEncryption(KeySerializationEncryption):
def __init__(self, format: PrivateFormat, password: bytes, *, kdf_rounds: (int | None), hmac_hash: (HashAlgorithm | None), key_cert_algorithm: (PBES | None)):
self._format = format
self.password = password
self._kdf_rounds = kdf_... |
def corpus_align(src_data, tgt_data, ali_data):
(align_dict, align_dict_rev) = (dict(), dict())
for idx in range(len(src_data)):
src = src_data[idx].strip('\n').split()
tgt = tgt_data[idx].strip('\n').split()
ali = ali_data[idx].strip('\n').split()
(align_dict, align_dict_rev) = ... |
class ComponentMetadata():
def pyproject_file(cls):
return pathlib.Path('pyproject.toml').absolute()
def from_pyproject(cls):
data = {}
if cls.pyproject_file().exists():
try:
data = toml.load(cls.pyproject_file()).get('tool', {}).get('reahl-component', {})
... |
class EasybytezComFolder(XFSDecrypter):
__name__ = 'EasybytezComFolder'
__type__ = 'decrypter'
__version__ = '0.19'
__status__ = 'testing'
__pattern__ = '
__config__ = [('enabled', 'bool', 'Activated', True), ('use_premium', 'bool', 'Use premium account if available', True), ('folder_per_package... |
_fixtures(WebFixture)
def test_event_names_are_canonicalised(web_fixture):
fixture = web_fixture
class ModelObject():
def handle_event(self, some_argument):
self.received_argument = some_argument
events = ExposedNames()
events.an_event = (lambda i: Event(label='click me', act... |
.xfail(reason='merge_frame is deprecated.')
def test_return_dataframe_merge_is_None(returns_frame_1):
expected_output = returns_frame_1['ticker'].str.split(' ', expand=True)
result = returns_frame_1.process_text(column_name='ticker', string_function='split', expand=True, pat=' ')
assert_frame_equal(result, ... |
class MaxActivationFusion(nn.Module):
def __init__(self, features=64, feature_extractor=Features4Layer, activation=relu):
super(MaxActivationFusion, self).__init__()
self.features = feature_extractor(features, activation=activation)
def forward(self, frame_1, frame_2, frame_3, frame_4, frame_5):... |
class ToPandasMixin():
def to_pandas(self):
pandas_type = pd.Series
if hasattr(self, 'to_json'):
data = self.to_json()
if isinstance(data, Sequence):
data = [try_to_dict(d) for d in data]
pandas_type = pd.DataFrame
elif hasattr(self, 't... |
class Recognizer(object):
def __init__(self, decoder, symbols=None, allow_partial=True, acoustic_scale=0.1):
self.decoder = decoder
self.symbols = symbols
self.allow_partial = allow_partial
self.acoustic_scale = acoustic_scale
def _make_decodable(self, loglikes):
if (logl... |
def summary_detail_baseline(memo):
DETAIL_ARTERIAL = True
total_summary = []
records_dir = os.path.join('records', memo)
for traffic_file in os.listdir(records_dir):
ANON_ENV = False
if (('.xml' not in traffic_file) and ('anon' not in traffic_file)):
continue
if ('ano... |
class InfiniteSampler(torch.utils.data.Sampler):
def __init__(self, dataset, rank=0, num_replicas=1, shuffle=True, seed=0, window_size=0.5):
assert (len(dataset) > 0)
assert (num_replicas > 0)
assert (0 <= rank < num_replicas)
assert (0 <= window_size <= 1)
super().__init__(d... |
def parse_args(argv: List[str]) -> argparse.Namespace:
parser = argparse.ArgumentParser(description='torchrec dlrm example trainer')
parser.add_argument('--epochs', type=int, default=1, help='number of epochs to train')
parser.add_argument('--batch_size', type=int, default=32, help='batch size to use for tr... |
class ATSBase(Instrument):
remote_mode = Instrument.setting('%s', '``True`` disables TS GUI but displays a Return to local" switch.', validator=strict_discrete_set, values={True: '%RM', False: '%GL'}, map_values=True)
maximum_test_time = Instrument.control('TTIM?', 'TTIM %g', 'Control maximum allowed test time ... |
def test_validate_problem_qubit_nodes():
def random_sk_model_with_qubit_nodes(n: int):
graph = nx.complete_graph(n)
graph = nx.relabel_nodes(graph, mapping={i: cirq.LineQubit(i) for i in range(n)})
return random_plus_minus_1_weights(graph)
problem_graph = random_sk_model_with_qubit_nodes... |
class Interpolate(nn.Module):
def __init__(self, scale_factor, mode):
super(Interpolate, self).__init__()
self.interp = nn.functional.interpolate
self.scale_factor = scale_factor
self.mode = mode
def forward(self, x):
x = self.interp(x, scale_factor=self.scale_factor, mod... |
def test_discovery_fallback_ok(session_app_data, caplog):
caplog.set_level(logging.DEBUG)
builtin = Builtin(Namespace(app_data=session_app_data, try_first_with=[], python=['magic-one', sys.executable], env=os.environ))
result = builtin.run()
assert (result is not None), caplog.text
assert (result.ex... |
class Migration(migrations.Migration):
dependencies = [('views', '0027_view_editors')]
operations = [migrations.AlterModelOptions(name='view', options={'ordering': ('uri',), 'verbose_name': 'View', 'verbose_name_plural': 'Views'}), migrations.RenameField(model_name='view', old_name='key', new_name='uri_path'), ... |
def test_bad_optional_dumping(retort, debug_trail):
raises_exc(with_cause(NoSuitableProvider(f'Cannot produce dumper for type {Union[(int, Callable[([int], str)])]}'), with_notes(CannotProvide(message=f'All cases of union must be class, but found {[Callable[([int], str)]]}', is_demonstrative=True, is_terminal=True)... |
class MaskingFilter(logging.Filter):
REPLACE_STR = ('*' * 4)
_UNWANTED = frozenset([s for obj in ('', None) for s in (repr(obj), str(obj))])
def __init__(self, _use_named_masks: bool=False, **patterns: Iterable[(str | re.Pattern[str])]) -> None:
super().__init__()
self._redact_patterns = def... |
def test_bare_parameters():
proj = CRS.from_string('+proj=lcc +lon_0=-95 +ellps=GRS80 +y_0=0 +no_defs=True +x_0=0 +units=m +lat_2=77 +lat_1=49 +lat_0=0')
with pytest.warns(UserWarning):
assert ('+no_defs' in proj.to_proj4(4))
proj = CRS.from_string('+lon_0=-95 +ellps=GRS80 +proj=lcc +y_0=0 +no_defs=... |
class MultiViewPCDataset(torch.utils.data.Dataset):
def __init__(self, root_path, data_list_path, labels_path):
self.root_path = root_path
self.data_list_path = data_list_path
self.labels_path = labels_path
self.labels = self.load_labels(labels_path)
self.data_list = self.loa... |
def init_default_config(pelican):
from pelican.settings import DEFAULT_CONFIG
bootstrapify_default = {'table': ['table', 'table-striped', 'table-hover'], 'img': ['img-responsive']}
set_default_config(DEFAULT_CONFIG, bootstrapify_default)
if pelican:
set_default_config(pelican.settings, bootstrap... |
def compute_on_dataset(model, data_loader, device, predict_folder, timer=None, vis=False, eval_score_iou=False, eval_depth=False, eval_trunc_recall=False):
model.eval()
cpu_device = torch.device('cpu')
dis_ious = defaultdict(list)
depth_errors = defaultdict(list)
differ_ious = []
with torch.no_g... |
class GVector(object):
def __init__(self, x=0, y=0, z=0):
self.x = x
self.y = y
self.z = z
def Mag(self):
return math.sqrt((((self.x ** 2) + (self.y ** 2)) + (self.z ** 2)))
def dist(self, other):
return math.sqrt(((((self.x - other.x) ** 2) + ((self.y - other.y) ** 2... |
def main(_):
(model_config, train_config, input_config) = get_configs_from_pipeline_file()
model_fn = functools.partial(build_man_model, model_config=model_config, is_training=True)
create_input_dict_fn = functools.partial(input_reader.read, input_config)
trainer.train(model_fn, create_input_dict_fn, tr... |
def get_scanengine(job, timeout=None):
job_type = job[0]
for import_job in scan_job_description.keys():
if (re.search(import_job, job_type) is not None):
name = scan_job_description[import_job]._whats_your_name()
if (timeout is None):
return scan_job_description[i... |
class DistanceAdj(nn.Module):
def __init__(self, sigma, bias):
super(DistanceAdj, self).__init__()
self.w = nn.Parameter(torch.FloatTensor(1))
self.b = nn.Parameter(torch.FloatTensor(1))
self.w.data.fill_(sigma)
self.b.data.fill_(bias)
def forward(self, batch_size, seq_le... |
class DemtHead(BaseHead):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.head_endpoints = ['final']
out_channels = (self.in_channels // 8)
dim_ = 256
self.bottleneck = nn.ModuleDict({t: utils_heads.ConvBNReLU(dim_, out_channels, kernel_size=3, norm_layer=nn.Bat... |
class vgg16(_fasterRCNN):
def __init__(self, classes, pretrained=False, class_agnostic=False):
self.model_path = 'data/pretrained_model/vgg16_caffe.pth'
self.dout_base_model = 512
self.pretrained = pretrained
self.class_agnostic = class_agnostic
_fasterRCNN.__init__(self, cla... |
def get_monitorengine(job):
job_type = job[0]
for import_job in monitor_description.keys():
if (re.search(import_job, job_type) is not None):
name = monitor_description[import_job]._whats_your_name()
return monitor_description[import_job].__dict__[name](job)
return False |
def report_notprint(counts, out=None):
if (out is None):
out = sys.stdout
(overall, by_type) = metrics(counts)
c = counts
final_report = []
line = []
line.append(('processed %d tokens with %d phrases; ' % (c.token_counter, c.found_correct)))
line.append(('found: %d phrases; correct: ... |
class TrainDataset(Dataset):
def __init__(self, args, raw_datasets, cache_root):
self.raw_datasets = raw_datasets
self.tab_processor = get_default_processor(max_cell_length=100, tokenizer=AutoTokenizer.from_pretrained(args.bert.location, use_fast=False), max_input_length=args.seq2seq.table_truncatio... |
def detr_resnet50(pretrained=False, num_classes=91, return_postprocessor=False):
model = _make_detr('resnet50', dilation=False, num_classes=num_classes)
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(url=' map_location='cpu', check_hash=True)
model.load_state_dict(checkpoint['mod... |
class ImageOverlay(Layer):
_template = Template('\n {% macro script(this, kwargs) %}\n var {{ this.get_name() }} = L.imageOverlay(\n {{ this.url|tojson }},\n {{ this.bounds|tojson }},\n {{ this.options|tojson }}\n );\n {% endmacro %}\n... |
_model_architecture('lightconv_lm', 'lightconv_lm')
def base_lm_architecture(args):
args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 512)
args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', 2048)
args.decoder_layers = getattr(args, 'decoder_layers', 6)
args.decoder_attention_h... |
class ConvNextFeatureExtractor(FeatureExtractionMixin, ImageFeatureExtractionMixin):
model_input_names = ['pixel_values']
def __init__(self, do_resize=True, size=224, resample=Image.BICUBIC, crop_pct=None, do_normalize=True, image_mean=None, image_std=None, **kwargs):
super().__init__(**kwargs)
... |
.chrome
def test_launch(testdir):
file_test = testdir.makepyfile("\n import pytest\n .nondestructive\n def test_pass(webtext):\n assert webtext == u'Success!'\n ")
testdir.quick_qa('--driver', 'Remote', '--capability', 'browserName', 'chrome', file_test, passed=1) |
def run_program(args):
if (len(args) < 1):
sys.exit(usage)
command = args.pop(0)
if (command in ('--help', '-h', 'help')):
sys.exit(usage)
if (command in ('--multiple', '-m')):
glbs = globals()
cmds = []
while (args and (args[0] in subcmds_desc)):
cmds... |
def decode_data_with_region_reader(data: dict) -> tuple[(RegionReader, GameDescription)]:
data = game_migration.migrate_to_current(data)
game = RandovaniaGame(data['game'])
resource_database = read_resource_database(game, data['resource_database'])
dock_weakness_database = read_dock_weakness_database(da... |
.usefixtures('temp_app_data')
def test_create_parallel(tmp_path):
def create(count):
subprocess.check_call([sys.executable, '-m', 'virtualenv', '-vvv', str((tmp_path / f'venv{count}')), '--without-pip'])
threads = [Thread(target=create, args=(i,)) for i in range(1, 4)]
for thread in threads:
... |
class Marker():
def __init__(self, marker: str) -> None:
try:
self._markers = _normalize_extra_values(_parse_marker(marker))
except ParserSyntaxError as e:
raise InvalidMarker(str(e)) from e
def __str__(self) -> str:
return _format_marker(self._markers)
def __... |
.parametrize('data', [[10, 100, (- 1), 1, 3], [10, 50, (- 1), 1, 3], [10, 100, (- 1), 1, 3], [10, 100, (- 1), 2, 3], [10, 100, (- 1), 10, 3], [10, 100, (- 1), 10, 5]])
def test_create_straight_road(data):
road = xodr.create_road([xodr.Line(data[1])], data[0], data[3], data[3], data[2], lane_width=data[4])
odr =... |
class Sentinel(type):
def __new__(cls: Type[_T_Sentinel], name: str, bases: Tuple[(type, ...)], namespace: Dict[(str, Any)], **kwds: Any) -> _T_Sentinel:
assert (bases == (Sentinel,))
v = super().__new__(cls, name, bases, namespace, **kwds)
v.__class__ = v
return v
def __repr__(s... |
def main(birdsongrec_root, data_root):
birdsongrec_root = Path(birdsongrec_root).expanduser().resolve()
if (not birdsongrec_root.exists()):
raise NotADirectoryError(f'birdsongrec_root not recognized as a directory: {birdsongrec_root}')
data_root = Path(data_root).expanduser().resolve()
if (not d... |
class Solution():
def findPairs(self, nums: List[int], k: int) -> int:
if (k < 0):
return 0
count = Counter(nums)
pairs = set([])
for num in count.keys():
if (k == 0):
if (count[num] > 1):
pairs.add((num, num))
e... |
def test_format_check_passing(run_line_simple, tmp_path):
schemafile = (tmp_path / 'schema.json')
schemafile.write_text(json.dumps(FORMAT_SCHEMA))
doc1 = (tmp_path / 'doc1.json')
doc1.write_text(json.dumps(PASSING_DOCUMENT))
run_line_simple(['--schemafile', str(schemafile), str(doc1)]) |
def make_custom_sort(orders):
orders = [{k: (- i) for (i, k) in enumerate(reversed(order), 1)} for order in orders]
def process(stuff):
if isinstance(stuff, dict):
l = [(k, process(v)) for (k, v) in stuff.items()]
keys = set(stuff)
for order in orders:
... |
class MultiEpochSampler(torch.utils.data.Sampler):
def __init__(self, data_source, num_epochs, start_itr=0, batch_size=128):
self.data_source = data_source
self.num_samples = len(self.data_source)
self.num_epochs = num_epochs
self.start_itr = start_itr
self.batch_size = batch... |
def test_default_caps_in_W3C(monkeypatch, testdir):
capabilities = {'browserName': 'chrome', 'bstack:options': {}}
monkeypatch.setenv('BROWSERSTACK_USERNAME', 'foo')
monkeypatch.setenv('BROWSERSTACK_ACCESS_KEY', 'bar')
variables = testdir.makefile('.json', '{{"capabilities": {}}}'.format(json.dumps(capa... |
def test_as_composite_bloq():
tb = TestAtom()
assert (not tb.supports_decompose_bloq())
cb = tb.as_composite_bloq()
assert isinstance(cb, CompositeBloq)
bloqs = list(cb.bloq_instances)
assert (len(bloqs) == 1)
assert (bloqs[0].bloq == tb)
cb2 = cb.as_composite_bloq()
assert (cb is cb... |
def _get_config(config_name, subfolder):
if (config_name is not None):
with open(os.path.join(os.path.dirname(__file__), 'config', subfolder, '{}.yaml'.format(config_name)), 'r') as f:
try:
config_dict = yaml.safe_load(f)
except yaml.YAMLError as exc:
... |
def reg_event(bot):
gif_media_id = functools.partial(_gif_media_id, bot=bot)
def media_id_by(keyword):
img = meme.image_url(keyword)
if img:
media_id = gif_media_id(*img)
logger.info('image: "%s", media_id: %s', img, media_id)
return media_id
(msg_types=TE... |
def _vgg_loader(arch: str) -> Callable[(..., torchvision.models.VGG)]:
loader = cast(Callable[(..., torchvision.models.VGG)], getattr(torchvision.models, arch))
def vgg(pretrained: bool=False, framework: str='torch', progress: bool=True, num_classes: int=1000) -> torchvision.models.VGG:
if (pretrained a... |
def load_resume_state(opt):
resume_state_path = None
if opt['auto_resume']:
state_path = osp.join('experiments', opt['name'], 'training_states')
if osp.isdir(state_path):
states = list(scandir(state_path, suffix='state', recursive=False, full_path=False))
if (len(states) ... |
class AcceptRejectTests(unittest.TestCase):
def test_receive_accept(self):
with unittest.mock.patch('websockets.client.generate_key', return_value=KEY):
client = ClientProtocol(parse_uri('ws://example.com/test'))
client.connect()
client.receive_data(f'''HTTP/1.1 101 Switching Pro... |
def update(i: int, j: int, order, score):
edge_bump = 0
old_score = 0
new_score = 0
for k in range(j, (i + 1)):
z = order.get(k)
z_parents = order.get_parents(z)
edge_bump -= len(z_parents)
old_score += order.get_local_score(z)
candidates = [order.get(l) for l in ... |
def crf_inference_inf(img, probs, t=10, scale_factor=1, labels=21):
import pydensecrf.densecrf as dcrf
from pydensecrf.utils import unary_from_softmax
(h, w) = img.shape[:2]
n_labels = labels
d = dcrf.DenseCRF2D(w, h, n_labels)
unary = unary_from_softmax(probs)
unary = np.ascontiguousarray(u... |
def test_remove_all_and_version(tester: CommandTester, venvs_in_cache_dirs: list[str], venv_name: str, venv_cache: Path) -> None:
expected = {''}
tester.execute(f'--all {venvs_in_cache_dirs[0]}')
for name in venvs_in_cache_dirs:
assert (not (venv_cache / name).exists())
expected.add(f'Delete... |
def _format_envvar(param):
(yield '.. envvar:: {}'.format(param.envvar))
(yield ' :noindex:')
(yield '')
if isinstance(param, click.Argument):
param_ref = param.human_readable_name
else:
param_ref = param.opts[0]
(yield _indent('Provide a default for :option:`{}`'.format(param_... |
def test_call_inexisting_address(deploy_client: JSONRPCClient) -> None:
inexisting_address = (b'\x01\x02\x03\x04\x05' * 4)
assert (len(deploy_client.web3.eth.get_code(inexisting_address)) == 0)
transaction = {'from': deploy_client.address, 'to': inexisting_address, 'data': b'', 'value': 0}
assert (deplo... |
def test_init_sanity():
parent = QtWidgets.QMainWindow()
figsize = (1.0, 4.0)
dpi = 256
assert (figsize != default_figsize)
assert (dpi != default_dpi)
mplw = MatplotlibWidget(parent, figsize=figsize)
assert_widget_fields(mplw, parent, figsize, default_dpi)
mplw = MatplotlibWidget(parent... |
def main(argv=sys.argv[1:]):
global _old_hook
dist = pkg_resources.get_distribution('pyladies')
parser = argparse.ArgumentParser(description='Everything you need to start your own PyLadies location')
parser.add_argument('handbook', help='read the handbook')
parser.add_argument('--version', action='v... |
def loader(snr):
path = 'dataset/'
dataset = np.load(os.path.join(path, (('dataset_snr' + str(snr)) + '.npz')))
data = dataset['data']
label = dataset['label']
data = np.expand_dims(data, axis=4)
label1 = np.reshape(label, (label.shape[0], np.prod(label.shape[1:])))
label = keras.utils.to_ca... |
def test_importorskip(monkeypatch) -> None:
importorskip = pytest.importorskip
def f():
importorskip('asdlkj')
try:
sysmod = importorskip('sys')
assert (sysmod is sys)
excinfo = pytest.raises(pytest.skip.Exception, f)
assert (excinfo is not None)
excrepr = exc... |
def validate(model, dataloader, criterion):
model.eval()
device = model.device
epoch_start = time.time()
running_loss = 0.0
preds = []
golds = []
with torch.no_grad():
for batch in dataloader:
premises = batch['premise'].to(device)
premises_lengths = batch['pr... |
class SwapNetworkProblemUnitary(ProblemUnitary):
def _decompose_(self, qubits) -> 'cirq.OP_TREE':
(yield from super()._decompose_(qubits))
(yield cirq.QubitPermutationGate(list(range(len(qubits)))[::(- 1)]).on(*qubits))
def _circuit_diagram_info_(self, args: 'cirq.CircuitDiagramInfoArgs') -> 'ci... |
def sample_sdf(num_sample, bandwidth, iso_val, sdf_dict, sdf_res, reduce):
start = time.time()
params = sdf_dict['param']
sdf_values = sdf_dict['value'].flatten()
n_sample = (sdf_res // reduce)
x = np.linspace(params[0], params[3], num=n_sample).astype(np.float32)
y = np.linspace(params[1], para... |
.end_to_end()
def test_raise_error_if_parametrization_produces_non_unique_tasks(tmp_path):
source = '\n from pytask import task\n\n for i in [0, 0]:\n (id=str(i))\n def task_func(i=i):\n pass\n '
tmp_path.joinpath('task_module.py').write_text(textwrap.dedent(source))
sessio... |
_module()
class RSN(BaseBackbone):
def __init__(self, unit_channels=256, num_stages=4, num_units=4, num_blocks=[2, 2, 2, 2], num_steps=4, norm_cfg=dict(type='BN'), res_top_channels=64, expand_times=26):
norm_cfg = cp.deepcopy(norm_cfg)
num_blocks = cp.deepcopy(num_blocks)
super().__init__()
... |
def setsub(a, b):
junks_a = []
useless_constraint = ['temperature', 'week', 'est ', 'quick', 'reminder', 'near']
for i in a:
flg = False
for j in b:
if similar(i, j):
flg = True
if (not flg):
junks_a.append(i)
for junk in junks_a:
f... |
class MixedCfcCell(tf.keras.layers.Layer):
def __init__(self, units, hparams, **kwargs):
self.units = units
self.state_size = (units, units)
self.initializer = 'glorot_uniform'
self.recurrent_initializer = 'orthogonal'
self.forget_gate_bias = 1
if ('forget_bias' in hp... |
class KeyChecker():
def __init__(self, keys, warn_empty=True, important=default_important, essential=None):
self.keys = keys
self.warn_empty = warn_empty
self.important = important
self.essential = essential
if (self.essential is None):
self.essential = [] |
.parametrize('archive_file', ['.git_archival.txt', '.hg_archival.txt'])
def test_archive(wd: WorkDir, monkeypatch: pytest.MonkeyPatch, archive_file: str) -> None:
monkeypatch.chdir(wd.cwd)
sha = 'a1bda3d984d1a40d7b00ae1d0869354d6d503001'
(wd.cwd / archive_file).write_text(f'node: {sha}', encoding='utf-8')
... |
def main(options):
if (options['model']['name'] == 'GaLR'):
from layers import GaLR as models
else:
raise NotImplementedError
vocab = deserialize_vocab(options['dataset']['vocab_path'])
vocab_word = sorted(vocab.word2idx.items(), key=(lambda x: x[1]), reverse=False)
vocab_word = [tup... |
def test_do_posterior_predictive():
with pm.Model() as m:
x = pm.Normal('x', 0, 1)
y = pm.Normal('y', x, 1)
z = pm.Normal('z', (y + x), 0.001)
idata_m = az.from_dict({'x': np.full((2, 500), 25), 'y': np.full((2, 500), np.nan), 'z': np.full((2, 500), np.nan)})
m_do = do(m, {y: 100.0})... |
def add_args(parser, cfg, prefix=''):
for (k, v) in cfg.items():
if isinstance(v, str):
parser.add_argument((('--' + prefix) + k))
elif isinstance(v, int):
parser.add_argument((('--' + prefix) + k), type=int)
elif isinstance(v, float):
parser.add_argument(... |
def read_dataset(fid, key):
dsid = DSET_NAMES[key['name']]
dset = fid[('/PWLR/' + dsid)]
if (dset.ndim == 3):
dims = ['y', 'x', 'level']
else:
dims = ['y', 'x']
data = xr.DataArray(da.from_array(dset[()], chunks=CHUNK_SIZE), name=key['name'], dims=dims).astype(np.float32)
data = ... |
('section.{propname}.is_linked_to_previous is True')
def then_section_hdrftr_prop_is_linked_to_previous_is_True(context: Context, propname: str):
actual = getattr(context.section, propname).is_linked_to_previous
expected = True
assert (actual == expected), ('section.%s.is_linked_to_previous is %s' % (propna... |
def warn_population_size(*, step: Union[(BlockedStep, CompoundStep)], initial_points: Sequence[PointType], model: Model, chains: int):
has_demcmc = np.any([isinstance(m, DEMetropolis) for m in (step.methods if isinstance(step, CompoundStep) else [step])])
initial_point_model_size = sum((initial_points[0][n.name... |
()
def cs_panties_pickup(default_generator_params) -> PickupEntry:
cs_pickup_database = default_database.pickup_database_for_game(RandovaniaGame.CAVE_STORY)
return PickupEntry(name="Curly's Panties", model=PickupModel(game=RandovaniaGame.CAVE_STORY, name=''), pickup_category=cs_pickup_database.pickup_categories... |
class Effect6021(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: (mod.item.group.name == 'Energy Nosferatu')), 'maxRange', src.getModifiedItemAttr('eliteBonusReconShip3'), skill='Recon Ships', **kwargs) |
(scope='session')
def swath_def_1d_xarray_dask():
chunks = 5
tlons_1d = xr.DataArray(da.from_array(np.array([11.280789, 12.649354, 12.080402]), chunks=chunks), dims=('my_dim1',))
tlats_1d = xr.DataArray(da.from_array(np.array([56.011037, 55.629675, 55.641535]), chunks=chunks), dims=('my_dim1',))
return ... |
def deepspeed_init(trainer, num_training_steps, resume_from_checkpoint=None, inference=False):
import deepspeed
from deepspeed.utils import logger as ds_logger
model = trainer.model
args = trainer.args
if hasattr(trainer, 'hf_deepspeed_config_orig'):
hf_deepspeed_config = deepcopy(trainer.hf... |
def main():
learner_ip = get_environ()
args = argparser()
param_queue = Queue(maxsize=3)
procs = [Process(target=exploration, args=(args, (- 1), param_queue)), Process(target=recv_param, args=(learner_ip, (- 1), param_queue))]
for p in procs:
p.start()
for p in procs:
p.join()
... |
def mypycify(paths: list[str], *, only_compile_paths: (Iterable[str] | None)=None, verbose: bool=False, opt_level: str='3', debug_level: str='1', strip_asserts: bool=False, multi_file: bool=False, separate: (bool | list[tuple[(list[str], (str | None))]])=False, skip_cgen_input: (Any | None)=None, target_dir: (str | Non... |
def test_colored_ansi_esc_caplogtext(pytester: Pytester) -> None:
pytester.makepyfile("\n import logging\n\n logger = logging.getLogger(__name__)\n\n def test_foo(caplog):\n logger.info('text going to logger from call')\n assert '\x1b' not in caplog.text\n ")
re... |
(Role)
class RoleAdmin(admin.ModelAdmin):
search_fields = ('user__username', 'user__email')
list_filter = ('member', 'manager', 'editor', 'reviewer')
list_display = ('user', 'email', 'members', 'managers', 'editors', 'reviewers')
def get_queryset(self, request):
return Role.objects.prefetch_rela... |
class GeneratorReach():
def reach_from_state(cls, game: GameDescription, initial_state: State) -> GeneratorReach:
raise NotImplementedError
def game(self) -> GameDescription:
raise NotImplementedError
def victory_condition_satisfied(self) -> bool:
return self.game.victory_condition.s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.