code stringlengths 281 23.7M |
|---|
def l1_ewta_waypoint_loss(prediction, target, k=6, waypoint_step=5, eps=1e-07):
num_mixtures = prediction.shape[1]
timesteps = target.shape[1]
target = nn.functional.pad(target, pad=(0, 0, 0, (waypoint_step - 1)))
target = target.unsqueeze(1).expand((- 1), num_mixtures, (- 1), (- 1))
indexes = ((tor... |
def get_time_string(status, options, format='%a %b %d %H:%M:%S +0000 %Y'):
timestamp = options['timestamp']
datestamp = options['datestamp']
t = time.strptime(status['created_at'], format)
i_hate_timezones = time.timezone
if time.daylight:
i_hate_timezones = time.altzone
dt = (datetime.d... |
class DevDataset(Dataset):
def __init__(self, args, raw_datasets, cache_root):
self.raw_datasets = raw_datasets
cache_path = os.path.join(cache_root, 'multiwoz_dev.cache')
if (os.path.exists(cache_path) and args.dataset.use_cache):
self.extended_data = torch.load(cache_path)
... |
def _filter_by_module_availability(datapipes):
filter_set = set()
if (datasets is None):
filter_set.update([iterdp.HuggingFaceHubReader])
if (fsspec is None):
filter_set.update([iterdp.FSSpecFileLister, iterdp.FSSpecFileOpener, iterdp.FSSpecSaver])
if (iopath is None):
filter_set... |
def trainIters(args, lang, dataset, encoder, decoder, critic, performer, extractor, all_ans, n_iters, split_id, max_steps, print_every=1, save_every=100):
start = time.time()
env = ThorEnv(x_display=0)
obj_predictor = FeatureExtractor(archi='maskrcnn', device=device, checkpoint='./logs/pretrained/maskrcnn_m... |
.parametrize('cv2', [0, 1])
.parametrize('cv1', [0, 1])
def test_truth_table_classical(cv1, cv2):
for (cbloq, a, b) in _iter_and_truth_table(cv1, cv2):
(res,) = cbloq.call_classically()
if ((a == cv1) and (b == cv2)):
assert (res == 1)
else:
assert (res == 0) |
def split(s):
scheme = None
netloc = None
path = None
query = None
fragment = None
end = len(s)
pos = 0
scheme_pos = s.find('://')
if (scheme_pos != (- 1)):
pos = (scheme_pos + 3)
scheme = s[:scheme_pos]
for x in scheme:
if ((not (x in scheme_chars... |
class esxiVm():
def __init__(self, serverObject, vmObject):
self.server = serverObject
self.vmObject = vmObject
self.procList = []
self.revertSnapshots = []
self.snapshotList = []
self.testVm = False
self.vmIdentifier = vmObject.summary.config.vmPathName
... |
def test_sync_teams_to_groups(user_creation, invite_only_user_creation, blacklisted_emails, app):
database.LoginService.create(name=_FAKE_AUTH)
sync_team_info = model.team.get_team_sync_information('buynlarge', 'synced')
assert (sync_team_info.last_updated is None)
fake_auth = FakeUsers([])
sync_tea... |
def get_img_annos(nuim, img_info, cat2id, out_dir, data_root, seg_root):
sd_token = img_info['token']
image_id = img_info['id']
name_to_index = name_to_index_mapping(nuim.category)
(width, height) = (img_info['width'], img_info['height'])
semseg_mask = np.zeros((height, width)).astype('uint8')
s... |
def _random_crop(image_list, crop_height, crop_width):
if (not image_list):
raise ValueError('Empty image_list.')
rank_assertions = []
for i in range(len(image_list)):
image_rank = tf.rank(image_list[i])
rank_assert = tf.Assert(tf.equal(image_rank, 3), ['Wrong rank for tensor %s [ex... |
class ModbusBaseSyncClient(ModbusClientMixin, ModbusProtocol):
class _params():
retries: (int | None) = None
retry_on_empty: (bool | None) = None
close_comm_on_error: (bool | None) = None
strict: (bool | None) = None
broadcast_enable: (bool | None) = None
reconnect_de... |
def load_embedding_txt(path):
words = []
vals = []
with codecs.open(path, 'r', encoding='utf-8') as fin:
fin.readline()
for line in fin:
line = line.strip()
if line:
parts = line.split()
words.append(parts[0])
vals += [f... |
class Connection(object):
def __init__(self, conn):
self.__conn = conn
def put(self, *args, **kwargs):
return self.__conn.send(*args, **kwargs)
def get(self, *args, **kwargs):
return self.__conn.recv(*args, **kwargs)
def __getattr__(self, name):
return getattr(self.__conn... |
class DFN(BaseModel):
def __init__(self, options=None, name='Doyle-Fuller-Newman model', build=True):
self.x_average = False
super().__init__(options, name)
self.set_submodels(build)
pybamm.citations.register('Doyle1993')
def set_intercalation_kinetics_submodel(self):
for... |
def _permute_2e_ints(hijkl: np.ndarray, elements: Set[Tuple[(int, ...)]], norb: int, beta: int=0) -> None:
for elem in elements.copy():
shifted = tuple(((e - ((e >= norb) * norb)) for e in elem))
if ((beta != 1) and (elem[::(- 1)] not in elements)):
hijkl[shifted] = hijkl[shifted[::(- 1)... |
class Crossfeed(GStreamerPlugin):
PLUGIN_ID = _PLUGIN_ID
PLUGIN_NAME = _('Crossfeed')
PLUGIN_DESC = _('Mixes the left and right channel in a way that simulates a speaker setup while using headphones, or to adjust for early Stereo recordings.')
PLUGIN_ICON = 'audio-volume-high'
def setup_element(cls)... |
class Effect1596(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
mod = (src.level if ('skill' in context) else 1)
fit.modules.filteredChargeBoost((lambda mod: mod.charge.requiresSkill('Missile Launcher Operation')), 'explosiveDamage', (src.getModifiedItem... |
_api()
class unique(Stream):
def __init__(self, upstream, maxsize=None, key=identity, hashable=True, **kwargs):
self.key = key
self.maxsize = maxsize
if hashable:
self.seen = dict()
if self.maxsize:
from zict import LRU
self.seen = LRU(... |
(allow_output_mutation=True)
def load_indexes():
if LOAD_DENSE_INDEX:
faiss_res = faiss.StandardGpuResources()
wiki40b_passages = datasets.load_dataset(path='wiki_snippets', name='wiki40b_en_100_0')['train']
wiki40b_passage_reps = np.memmap('wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat',... |
_request_params(docs._search_query, docs._pagination)
def get_places_autocomplete(q: Optional[str]=None, **params) -> JsonResponse:
if (params.get('page') == 'all'):
places = PlaceAutocompletePaginator(q=q, **params).all()
else:
places = get(f'{API_V1}/places/autocomplete', q=q, **params).json()... |
class NetModule():
def __init__(self, args):
self.args = args
self.lock = threading.Lock()
self.initializer = tf_initializers.VarianceScaling(seed=args.seed)
self.state = {}
self.models = []
self.heads = []
self.decomposed_layers = {}
self.initial_body... |
class AnnotationTextEdit(QtWidgets.QTextEdit):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setMaximumHeight(70)
def enterEvent(self, e):
if (self.window().showhelp is True):
QtWidgets.QToolTip.showText(e.globalPos(), '<h3>Annotation Text</h3>En... |
class MemoryEfficientSwish(nn.Module):
class F(torch.autograd.Function):
def forward(ctx, x):
ctx.save_for_backward(x)
return (x * torch.sigmoid(x))
def backward(ctx, grad_output):
x = ctx.saved_tensors[0]
sx = torch.sigmoid(x)
return (grad... |
class _DenseLayer(nn.Sequential):
def __init__(self, num_input_features, growth_rate, bn_size, drop_rate):
super(_DenseLayer, self).__init__()
self.add_module('norm.1', nn.BatchNorm3d(num_input_features))
self.add_module('relu.1', nn.ReLU(inplace=True))
self.add_module('conv.1', nn.C... |
class ResNet(nn.Module):
def __init__(self, block, num_blocks, in_channel=3, zero_init_residual=False):
super(ResNet, self).__init__()
self.in_planes = 64
self.conv1 = nn.Conv2d(in_channel, 64, kernel_size=3, stride=1, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(64)
self... |
class WhisperConfig(PretrainedConfig):
model_type = 'whisper'
keys_to_ignore_at_inference = ['past_key_values']
attribute_map = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'}
def __init__(self, vocab_size=51865, num_mel_bins=80, encoder_layers=6, encoder_attention_heads=4, ... |
class DistCrossEntropyFunc(torch.autograd.Function):
def forward(ctx, logits: torch.Tensor, label: torch.Tensor):
batch_size = logits.size(0)
(max_logits, _) = torch.max(logits, dim=1, keepdim=True)
distributed.all_reduce(max_logits, distributed.ReduceOp.MAX)
logits.sub_(max_logits)
... |
class MaskBase(object):
__metaclass__ = abc.ABCMeta
def include(self, data=None, wcs=None, view=(), **kwargs):
self._validate_wcs(data, wcs, **kwargs)
return self._include(data=data, wcs=wcs, view=view)
def view(self, view=()):
return self.exclude(view=view)
def _validate_wcs(sel... |
class Skeleton():
def __init__(self, parents, joints_left, joints_right):
assert (len(joints_left) == len(joints_right))
self._parents = np.array(parents)
self._joints_left = joints_left
self._joints_right = joints_right
self._compute_metadata()
def num_joints(self):
... |
class StandaloneEditor(_KeyValueEditor):
def load_values(cls, filename):
ret = []
if os.path.exists(filename):
fileobj = open(filename, encoding='utf-8')
lines = list(fileobj.readlines())
for i in range((len(lines) // 2)):
ret.append((lines[((i * 2... |
def show_transaction(tx: Transaction, *, parent: 'ElectrumWindow', desc=None, prompt_if_unsaved=False):
try:
d = TxDialog(tx, parent=parent, desc=desc, prompt_if_unsaved=prompt_if_unsaved)
except SerializationError as e:
_logger.exception('unable to deserialize the transaction')
parent.s... |
class TMP4Datatypes(TMP4, TMP4HasTagsMixin):
original = os.path.join(DATA_DIR, 'has-tags.m4a')
def test_has_freeform(self):
key = '----:com.apple.iTunes:iTunNORM'
self.failUnless((key in self.audio.tags))
ff = self.audio.tags[key]
self.failUnlessEqual(ff[0].dataformat, AtomDataTy... |
def get_config_from_root(root: str) -> VersioneerConfig:
root_pth = Path(root)
pyproject_toml = (root_pth / 'pyproject.toml')
setup_cfg = (root_pth / 'setup.cfg')
section: Union[(Dict[(str, Any)], configparser.SectionProxy, None)] = None
if (pyproject_toml.exists() and have_tomllib):
try:
... |
class TestCPythonABI():
.parametrize('py_debug,gettotalrefcount,result', [(1, False, True), (0, False, False), (None, True, True)])
def test_debug(self, py_debug, gettotalrefcount, result, monkeypatch):
config = {'Py_DEBUG': py_debug, 'WITH_PYMALLOC': 0, 'Py_UNICODE_SIZE': 2}
monkeypatch.setattr... |
class PyxParser(object):
def __init__(self, path, unit):
self._path = path
self._includes = []
retargeted = os.path.join(unit.path(), os.path.basename(path))
with open(path, 'rb') as f:
(includes, induced, susp_includes) = self.parse_includes(f.readlines())
fo... |
.parametrize('version,normalized_version', [('1!2.3.4.5.6a7.post8.dev9+local1.123.abc', '1!2.3.4.5.6a7.post8.dev9+local1.123.abc'), ('1.1RC1', '1.1rc1'), ('00', '0'), ('09000', '9000'), ('1.0+foo0100', '1.0+foo0100'), ('1.1.a1', '1.1a1'), ('1.1-a1', '1.1a1'), ('1.1_a1', '1.1a1'), ('1.1a.1', '1.1a1'), ('1.1a-1', '1.1a1'... |
def main():
models = morefusion.datasets.YCBVideoModels()
with concurrent.futures.ProcessPoolExecutor() as executor:
futures = []
for class_id in range(models.n_class):
if (class_id == 0):
continue
future = executor.submit(_get_top_image, class_id)
... |
class FairseqDropout(nn.Module):
def __init__(self, p, module_name=None):
super().__init__()
self.p = p
self.module_name = module_name
self.apply_during_inference = False
def forward(self, x, inplace: bool=False):
if ((self.p > 0) and (self.training or self.apply_during_i... |
class CPIBase(object):
def __init__(self, api, adaptor):
self._session = None
self._adaptor = adaptor
self._cpi_cname = self.__class__.__name__
self._logger = ru.Logger('radical.saga.cpi')
self._api = weakref.ref(api)
self._container = None
def _set_container(self... |
def analogy_singleseq_encoding_model(inputs, params, is_training, reuse):
enc_cell_fn = NAME_TO_RNNCELL[params.enc_model]
recurrent_dropout_prob = 1.0
if is_training:
recurrent_dropout_prob = params.recurrent_dropout_prob
assert (not params.use_bidirection_lstm)
enc_cell = get_rnn_cell(enc_c... |
def should_do_dim_bucketing(embedding_tables: List[ShardedEmbeddingTable]) -> bool:
table_pipeline_count = 0
for table in embedding_tables:
if ((table.fused_params is not None) and ('prefetch_pipeline' in table.fused_params) and table.fused_params['prefetch_pipeline']):
table_pipeline_count ... |
class TensorPartContainer():
def __init__(self, tensors: Sequence[torch.Tensor], peer_fractions: Sequence[float], compression: CompressionBase=NoCompression(), part_size_bytes: int=DEFAULT_PART_SIZE_BYTES, tensor_infos: Optional[Sequence[CompressionInfo]]=None, prefetch: int=5):
if (tensor_infos is None):
... |
('/oauth/authorize', methods=['GET'])
_cache
_required('client_id')
_required('redirect_uri')
_required('scope')
_auth_or_cookie
def request_authorization_code():
provider = FlaskAuthorizationProvider()
response_type = request.args.get('response_type', 'code')
client_id = request.args.get('client_id', None)... |
_on_failure
.parametrize('number_of_nodes', [1])
.parametrize('channels_per_node', [0])
def test_channel_with_self(raiden_network: List[RaidenService], settle_timeout, token_addresses):
(app0,) = raiden_network
registry_address = app0.default_registry.address
token_address = token_addresses[0]
current_c... |
def test_update_empty_directory_blocklist(ad_blocker, config_stub, empty_dir, caplog):
tmpdir_url = QUrl.fromLocalFile(str(empty_dir)).toString()
config_stub.val.content.blocking.adblock.lists = [tmpdir_url]
config_stub.val.content.blocking.enabled = True
config_stub.val.content.blocking.whitelist = Non... |
class SawyerDoorOpenV2Policy(Policy):
_fully_parsed
def _parse_obs(obs):
return {'hand_pos': obs[:3], 'gripper': obs[3], 'door_pos': obs[4:7], 'unused_info': obs[7:]}
def get_action(self, obs):
o_d = self._parse_obs(obs)
action = Action({'delta_pos': np.arange(3), 'grab_effort': 3})
... |
class NullifyContractUseCase(BaseUseCaseWithNotifications):
notifications = [notifications.NullifiedContractLogger(), notifications.RefreshSponsorshipsCache()]
def execute(self, contract, **kwargs):
contract.nullify()
self.notify(request=kwargs.get('request'), contract=contract) |
def get_formatter(action_type, options):
formatters_dict = formatters.get(action_type)
if (not formatters_dict):
raise TwitterError(('There was an error finding a class of formatters for your type (%s)' % action_type))
f = formatters_dict.get(options['format'])
if (not f):
raise TwitterE... |
_test
def test_merge_mask_3d():
rand = (lambda *shape: np.asarray((np.random.random(shape) > 0.5), dtype='int32'))
input_a = layers.Input(shape=(3,), dtype='int32')
input_b = layers.Input(shape=(3,), dtype='int32')
embedding = layers.Embedding(3, 4, mask_zero=True)
embedding_a = embedding(input_a)
... |
class TestMerge(unittest.TestCase):
def setUp(self):
get_dummy_plugin()
def test_merging_nothing(self):
md = Metadata(pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]}, index=pd.Index(['id1', 'id2', 'id3'], name='id')))
with self.assertRaisesRegex(ValueError, 'At least one Metadata.*nothing ... |
.parametrize('required_fixtures', [['git/github.com/demo/pyproject-demo']])
def test_add_directory_with_poetry(app: PoetryTestApplication, repo: TestRepository, tester: CommandTester) -> None:
repo.add_package(get_package('pendulum', '1.4.4'))
path = '../git/github.com/demo/pyproject-demo'
tester.execute(f'... |
class TokenSendLayout(QGridLayout):
def __init__(self, dialog, token, send_callback):
QGridLayout.__init__(self)
self.setSpacing(8)
self.setColumnStretch(3, 1)
self.dialog = dialog
self.token = token
self.send_callback = send_callback
address_lb = QLabel(_('My... |
class fashionmnist_dataset(Data.Dataset):
def __init__(self, train=True, transform=None, target_transform=None, noise_rate=0.2, split_percentage=0.9, seed=1, num_classes=10, feature_size=784, norm_std=0.1):
self.transform = transform
self.target_transform = target_transform
self.train = trai... |
class PointLocator():
def __init__(self, points):
warnings.warn(('PointLocator ' + dep_msg), FutureWarning)
self._locator = BruteForcePointLocator(points)
def nearest(self, query_point):
return self._locator.nearest(query_point)
def region(self, region_rect):
return self._loc... |
def main():
args = parse_args()
root_path = args.root_path
print('Processing training set...')
training_infos = collect_cocotext_info(root_path, 'train')
convert_annotations(training_infos, osp.join(root_path, 'instances_training.json'))
print('Processing validation set...')
val_infos = coll... |
class Entry(cpi_ns.entry.Entry, cpi_att.Attributes):
def __init__(self, api, adaptor):
self._cpi_nsentry = super(Entry, self)
self._cpi_nsentry.__init__(api, adaptor)
def init_instance(self, url, flags, session):
pass
def init_instance_async(self, url, flags, session):
pass
... |
class TriStageLRScheduleConfig(FairseqDataclass):
warmup_steps: int = field(default=0, metadata={'help': 'warmup the learning rate linearly for the first N updates'})
hold_steps: int = field(default=0, metadata={'help': 'steps in hold stage'})
decay_steps: int = field(default=0, metadata={'help': 'steps in ... |
def main():
parser = transformers.HfArgumentParser((ModelArguments, DataArguments, TrainingArguments))
(model_args, data_args, training_args) = parser.parse_args_into_dataclasses()
print('Setup Data')
Train_dataset = PMC_QA_Dataset(data_args.img_dir, data_args.Train_csv_path, data_args.tokenizer_path, t... |
class OperationValidator(KeywordValidator):
def __init__(self, registry: 'KeywordValidatorRegistry'):
super().__init__(registry)
self.operation_ids_registry: Optional[List[str]] = []
def responses_validator(self) -> ResponsesValidator:
return cast(ResponsesValidator, self.registry['respo... |
class Pix3DCodeDataset(BaseDataset):
def initialize(self, opt, phase='train', cat='all'):
self.opt = opt
self.max_dataset_size = opt.max_dataset_size
info_file = json_f_dict[hostname]['pix3d']
info_path = f'preprocess/info_files/{info_file}'
with open(info_path) as f:
... |
class BuildBackendHookCaller():
def __init__(self, source_dir: str, build_backend: str, backend_path: Optional[Sequence[str]]=None, runner: Optional['SubprocessRunner']=None, python_executable: Optional[str]=None) -> None:
if (runner is None):
runner = default_subprocess_runner
self.sour... |
class LEDTokenizer(PreTrainedTokenizer):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
model_input_names = ['input_ids', 'attention_mask']
def __init__(self, vocab_file, merges_file, errors... |
class ModbusPlusStatistics():
__data = OrderedDict({'node_type_id': ([0] * 2), 'software_version_number': ([0] * 2), 'network_address': ([0] * 2), 'mac_state_variable': ([0] * 2), 'peer_status_code': ([0] * 2), 'token_pass_counter': ([0] * 2), 'token_rotation_time': ([0] * 2), 'program_master_token_failed': [0], 'd... |
def fgraph_from_model(model: Model, inlined_views=False) -> Tuple[(FunctionGraph, Dict[(Variable, Variable)])]:
if any(((v is not None) for v in model.rvs_to_initial_values.values())):
raise NotImplementedError('Cannot convert models with non-default initial_values')
if (model.parent is not None):
... |
def test_ansible_unavailable(host):
expected = 'Ansible module is only available with ansible connection backend'
with pytest.raises(RuntimeError) as excinfo:
host.ansible('setup')
assert (expected in str(excinfo.value))
with pytest.raises(RuntimeError) as excinfo:
host.ansible.get_varia... |
class TV():
location: str
channel: int
def __init__(self, location: str):
self.location = location
def on(self) -> None:
print('TV is on')
def off(self) -> None:
print('TV is off')
def setInputChannel(self) -> None:
self.channel = 3
print('Channel is set f... |
def _get_stations_from(uri: str, on_done: Callable[([Iterable[IRFile], str], None)]) -> None:
with Task(_('Internet Radio'), _('Add stations')) as task:
irfs: Collection[IRFile] = []
GLib.idle_add(task.pulse)
if (uri.lower().endswith('.pls') or uri.lower().endswith('.m3u') or uri.lower().end... |
def test_complement():
assert complement((lambda : False))()
assert (not complement((lambda : True))())
assert complement(iseven)(1)
assert (not complement(iseven)(2))
assert complement(complement(iseven))(2)
assert (not complement(complement(isodd))(2))
both_even = (lambda a, b: (iseven(a) ... |
def is_valid_userid_for_address(user_id: Any, address: Address) -> bool:
try:
typecheck(user_id, T_UserID)
except ValueError:
return False
user_id_address = address_from_userid(user_id)
if (not user_id_address):
return False
return (address == user_id_address) |
_on_failure
.parametrize('number_of_nodes', [2])
.parametrize('channels_per_node', [CHAIN])
def test_broadcast_messages_must_be_sent_before_protocol_messages_on_restarts(raiden_network: List[RaidenService], restart_node, number_of_nodes, token_addresses, network_wait):
(app0, app1) = raiden_network
app0.config.... |
class CMakeBuild(build_ext):
user_options = [*build_ext.user_options, ('suitesparse-root=', None, 'suitesparse source location'), ('sundials-root=', None, 'sundials source location')]
def initialize_options(self):
build_ext.initialize_options(self)
self.suitesparse_root = None
self.sundi... |
def timeout_sigalrm(item, settings):
if ((not settings.disable_debugger_detection) and is_debugging()):
return
__tracebackhide__ = True
nthreads = len(threading.enumerate())
if (nthreads > 1):
write_title('Timeout', sep='+')
dump_stacks()
if (nthreads > 1):
write_title('T... |
class nnUNetTrainer_probabilisticOversampling_033(nnUNetTrainer_probabilisticOversampling):
def __init__(self, plans: dict, configuration: str, fold: int, dataset_json: dict, unpack_dataset: bool=True, device: torch.device=torch.device('cuda')):
super().__init__(plans, configuration, fold, dataset_json, unp... |
class Parser(unittest.TestCase):
def test_lf(self):
with tempfile.TemporaryDirectory() as root:
fn = os.path.join(root, '_version.py')
with open(fn, 'wb') as f:
f.write(b"version_json = '''\n{}\n''' # END VERSION_JSON\n")
data = versions_from_file(fn)
... |
class VgmFile(AudioFile):
format = 'VGM'
mimes: list[str] = []
def __init__(self, filename):
with translate_errors():
with open(filename, 'rb') as h:
header = h.read(64)
if ((len(header) != 64) or (header[:4] != b'Vgm ')):
raise Excepti... |
def init_detector(config, checkpoint=None, device='cuda:0', cfg_options=None):
if isinstance(config, str):
config = mmcv.Config.fromfile(config)
elif (not isinstance(config, mmcv.Config)):
raise TypeError(f'config must be a filename or Config object, but got {type(config)}')
if (cfg_options ... |
class ThermalParameters(BaseParameters):
def __init__(self):
self.geo = pybamm.geometric_parameters
self.n = DomainThermalParameters('negative', self)
self.s = DomainThermalParameters('separator', self)
self.p = DomainThermalParameters('positive', self)
self.domain_params = {... |
class MagicEncode():
def __init__(self, driver, encoding=None, disabled=False, defaultsymbol='?', encoder=None):
if (disabled and (not encoding)):
raise Error('If you disable magic encode, you need to define an encoding!')
self.driver = driver
self.encoder = (encoder or Encoder(d... |
.fast
def test_find_first(*args, **kwargs):
a = np.arange(10)
assert (find_first(a, (- 1)) == 0)
assert (find_first(a, 0) == 1)
assert (find_first(a, 5) == 6)
assert (find_first(a, 8) == 9)
assert (find_first(a, 9) == 0)
assert (find_first(a, 20) == 0)
assert (not (find_first(a, (- 1)) =... |
def bloqs_to_proto(*bloqs: Bloq, name: str='', pred: Callable[([BloqInstance], bool)]=(lambda _: True), max_depth: int=1) -> bloq_pb2.BloqLibrary:
bloq_to_idx: Dict[(Bloq, int)] = {}
for bloq in bloqs:
_add_bloq_to_dict(bloq, bloq_to_idx)
_populate_bloq_to_idx(bloq, bloq_to_idx, pred, max_depth)... |
class TestFactory(TestCase):
def setUp(self):
self.factory = MachineFactory()
def test_mixins(self):
machine_cls = self.factory.get_predefined()
self.assertFalse(hasattr(machine_cls, 'set_edge_state'))
graph_cls = self.factory.get_predefined(graph=True)
self.assertTrue(ha... |
def parse_mypy_comments(args: list[tuple[(int, str)]], template: Options) -> tuple[(dict[(str, object)], list[tuple[(int, str)]])]:
errors: list[tuple[(int, str)]] = []
sections = {}
for (lineno, line) in args:
parser = configparser.RawConfigParser()
(options, parse_errors) = mypy_comments_t... |
def test_edit_connections(game_editor):
landing_site = game_editor.game.region_list.area_by_area_location(AreaIdentifier('Temple Grounds', 'Landing Site'))
source = landing_site.node_with_name('Save Station')
target = landing_site.node_with_name('Door to Service Access')
assert (landing_site.connections... |
def train_CE(train_loader, model, model_ema, optimizer_model, epoch):
print(('\nEpoch: %d' % epoch))
train_loss = 0
train_total = 0
train_correct = 0
for (batch_idx, (inputs, targets, index)) in enumerate(train_loader):
model.train()
model_ema.train()
(inputs, targets) = (inp... |
def run_collation():
encodings_raw = load_encodings()
profiles_raw = load_profiles()
profiles_substituted = {}
for profile_name in profiles_raw.keys():
profiles_substituted[profile_name] = substitute_profile(profile_name, profiles_raw, encodings_raw)
encodings_filtered = filter_encodings(enc... |
def test_MaxAbsScaler_no_change_original_dm(decision_matrix):
dm = decision_matrix(seed=42, min_alternatives=10, max_alternatives=10, min_criteria=20, max_criteria=20, min_objectives_proportion=0.5)
expected = dm.copy()
scaler = MaxAbsScaler(target='both')
dmt = scaler.transform(dm)
assert (dm.equal... |
def eval_model(model: torch.nn.Module, dataset: EgoDataset, logger: Logger, d_set: str, iter_num: int, num_scenes_to_unroll: int, num_simulation_steps: int=None, enable_scene_type_aggregation: Optional[bool]=False, scene_id_to_type_path: Optional[str]=None) -> None:
model.eval()
torch.set_grad_enabled(False)
... |
class RequirementEditor():
_editor: (((None | ResourceRequirementEditor) | ArrayRequirementEditor) | TemplateRequirementEditor)
def __init__(self, parent: QWidget, parent_layout: QVBoxLayout, resource_database: ResourceDatabase, *, on_remove=None):
self.parent = parent
self.parent_layout = paren... |
def simple_test(env_fn, learn_fn, min_reward_fraction, n_trials=N_TRIALS):
np.random.seed(0)
np_random.seed(0)
env = DummyVecEnv([env_fn])
with tf.Graph().as_default(), tf.Session(config=tf.ConfigProto(allow_soft_placement=True)).as_default():
tf.set_random_seed(0)
model = learn_fn(env)
... |
class Bits():
__slots__ = ('_nbits', '_uint', '_next')
def nbits(self):
return self._nbits
def __init__(self, nbits, v=0, trunc_int=False):
nbits = int(nbits)
if ((nbits < 1) or (nbits >= 1024)):
raise ValueError(f'Only support 1 <= nbits < 1024, not {nbits}')
sel... |
def test_sync_2():
with cluster() as (s, [a, b]):
with Client(s['address']):
source = Stream()
L = source.scatter().map(inc).gather().sink_to_list()
for i in range(10):
source.emit(i)
assert (len(L) == (i + 1))
assert (L == list... |
class ToggledPlayOrderMenu(Gtk.Box):
__gsignals__ = {'toggled': (GObject.SignalFlags.RUN_LAST, None, ()), 'changed': (GObject.SignalFlags.RUN_LAST, None, (object,))}
def __init__(self, icon_name, orders, current_order, enabled=False, tooltip=None, arrow_down=False):
assert issubclass(current_order, Orde... |
class PluginManager():
def __init__(self, group: str, disable_plugins: bool=False) -> None:
self._group = group
self._disable_plugins = disable_plugins
self._plugins: list[Plugin] = []
def load_plugins(self, env: (Env | None)=None) -> None:
if self._disable_plugins:
r... |
class F28_FcoeData(F13_FcoeData):
removedKeywords = F13_FcoeData.removedKeywords
removedAttrs = F13_FcoeData.removedAttrs
def __init__(self, *args, **kwargs):
F13_FcoeData.__init__(self, *args, **kwargs)
self.autovlan = kwargs.get('autovlan', False)
def _getArgsAsStr(self):
retva... |
class TestListOrValue():
def klass(self):
return configtypes.ListOrValue
def strtype(self):
return configtypes.String()
.parametrize('val, expected', [('["foo"]', ['foo']), ('["foo", "bar"]', ['foo', 'bar']), ('foo', 'foo')])
def test_from_str(self, klass, strtype, val, expected):
... |
def RESNET50(include_top=True, weights='vggface', input_tensor=None, input_shape=None, pooling=None, classes=8631):
input_shape = _obtain_input_shape(input_shape, default_size=224, min_size=32, data_format=K.image_data_format(), require_flatten=include_top, weights=weights)
if (input_tensor is None):
im... |
class TrainerTest(tf.test.TestCase):
def test_configure_trainer_and_train_two_steps(self):
train_config_text_proto = '\n optimizer {\n adam_optimizer {\n learning_rate {\n constant_learning_rate {\n learning_rate: 0.01\n }\n }\n }\n }\n data_augm... |
class UCCSD(UCC):
def __init__(self, num_spatial_orbitals: (int | None)=None, num_particles: (tuple[(int, int)] | None)=None, qubit_mapper: (QubitMapper | None)=None, *, reps: int=1, initial_state: (QuantumCircuit | None)=None, generalized: bool=False, preserve_spin: bool=True, include_imaginary: bool=False) -> Non... |
class Test_keyImport(ElectrumTestCase):
priv_pub_addr = ({'priv': 'KzMFjMC2MPadjvX5Cd7b8AKKjjpBSoRKUTpoAtN6B3J9ezWYyXS6', 'exported_privkey': 'p2pkh:KzMFjMC2MPadjvX5Cd7b8AKKjjpBSoRKUTpoAtN6B3J9ezWYyXS6', 'pub': '02c6467b7eed3e4835b0b4ab7e35266a2ae1c4f8baa19e9ca', 'address': '17azqT8T16coRmWKYFj3UjzJuxiYrYFRBR', 'mi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.