code stringlengths 281 23.7M |
|---|
def deconv2d(input_, output_dim, ks=4, s=2, stddev=0.02, name='deconv2d'):
with tf.variable_scope(name):
return slim.conv2d_transpose(input_, output_dim, ks, s, padding='SAME', activation_fn=None, weights_initializer=tf.truncated_normal_initializer(stddev=stddev), biases_initializer=None) |
class TestClickThroughRate(MetricClassTester):
def test_ctr_with_valid_input(self) -> None:
input = torch.tensor([[1, 0, 0, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]])
self.run_class_implementation_tests(metric=ClickThroughRate(), state_names={'click_total', 'weight_total'}, update_kwargs={'input... |
def test_graph_crf_class_weights():
crf = GraphCRF(n_states=3, n_features=3)
w = np.array([1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0])
x = (np.array([[1, 1.5, 1.1]]), np.empty((0, 2)))
assert_equal(crf.inference(x, w), 1)
assert_equal(crf.loss_augmented_inference(x, [1], w), 2)
crf = GraphCRF(... |
('beeref.view.BeeGraphicsView.reset_previous_transform')
('beeref.view.BeeGraphicsView.pan')
def test_zoom_out(pan_mock, reset_mock, view, imgfilename3x3):
item = BeePixmapItem(QtGui.QImage(imgfilename3x3))
view.scale(100, 100)
view.scene.addItem(item)
view.zoom((- 40), QtCore.QPointF(10.0, 10.0))
a... |
_module()
class FPEM_FFM(BaseModule):
def __init__(self, in_channels, conv_out=128, fpem_repeat=2, align_corners=False, init_cfg=dict(type='Xavier', layer='Conv2d', distribution='uniform')):
super().__init__(init_cfg=init_cfg)
self.reduce_conv_c2 = nn.Sequential(nn.Conv2d(in_channels=in_channels[0],... |
def pytest_configure(config: Config) -> None:
reporter = TerminalReporter(config, sys.stdout)
config.pluginmanager.register(reporter, 'terminalreporter')
if (config.option.debug or config.option.traceconfig):
def mywriter(tags, args):
msg = ' '.join(map(str, args))
reporter.w... |
class Repeat(Op):
__props__ = ('axis',)
def __init__(self, axis=None):
self.axis = axis
def make_node(self, x, repeats):
x = ptb.as_tensor_variable(x)
repeats = ptb.as_tensor_variable(repeats)
if (repeats.dtype not in integer_dtypes):
raise TypeError('repeats.dtyp... |
def _b(mu, nu, sigma, n, a, k, collection):
if (nu == (mu + 1)):
while (a[nu] < (mu - 1)):
(yield _visit(n, a, k, collection))
a[nu] = (a[nu] + 1)
(yield _visit(n, a, k, collection))
a[mu] = 0
elif (nu > (mu + 1)):
if (((a[nu] + sigma) % 2) == 1):
... |
_funcify.register(Unique)
def jax_funcify_Unique(op, **kwargs):
axis = op.axis
if (axis is not None):
raise NotImplementedError('jax.numpy.unique is not implemented for the axis argument')
return_index = op.return_index
return_inverse = op.return_inverse
return_counts = op.return_counts
... |
class WaveEncoder(MediaEncoder):
def get_file_extensions(self):
return ('.wav', '.wave', '.riff')
def encode(self, source, filename, file):
opened_file = None
if (file is None):
file = open(filename, 'wb')
opened_file = True
source.seek(0)
wave_wri... |
_cache(maxsize=None)
def parse_constraint(constraints: str) -> BaseConstraint:
if (constraints == '*'):
return AnyConstraint()
or_constraints = re.split('\\s*\\|\\|?\\s*', constraints.strip())
or_groups = []
for constraints in or_constraints:
and_constraints = re.split('(?<!^)(?<![=>< ,]... |
class ImplantSet():
def __init__(self, name=None):
self.name = name
self.__implants = HandledImplantList()
def implants(self):
return self.__implants
def exportSets(cls, *sets):
out = '# Exported from pyfa\n#\n# Values are in following format:\n# [Implant Set name]\n# [Implan... |
_test
def test_gaussiandropout_legacy_interface():
old_layer = keras.layers.GaussianDropout(p=0.6, name='drop')
new_layer_1 = keras.layers.GaussianDropout(rate=0.6, name='drop')
new_layer_2 = keras.layers.GaussianDropout(0.6, name='drop')
assert (json.dumps(old_layer.get_config()) == json.dumps(new_laye... |
def test_task_will_be_executed_after_another_one_with_function(tmp_path):
source = '\n from pytask import task\n from pathlib import Path\n from typing_extensions import Annotated\n\n def task_first() -> Annotated[str, Path("out.txt")]:\n return "Hello, World!"\n\n (after=task_first)\n def ... |
def pytest_configure(config: Config) -> None:
config.addinivalue_line('markers', "parametrize(argnames, argvalues): call a test function multiple times passing in different arguments in turn. argvalues generally needs to be a list of values if argnames specifies only one name or a list of tuples of values if argnam... |
def main():
logging.basicConfig(level=logging.DEBUG)
logging.info(sys.argv)
if (len(sys.argv) != 4):
logging.error('Usage: python3 scripts/tests_required.py <image.name> <image.github_location> <output.txt>')
sys.exit(1)
image_name = sys.argv[1]
image_github_location = sys.argv[2]
... |
class PingCollector(diamond.collector.ProcessCollector):
def get_default_config_help(self):
config_help = super(PingCollector, self).get_default_config_help()
config_help.update({'bin': 'The path to the ping binary'})
return config_help
def get_default_config(self):
config = supe... |
class TestHatchPersonalProjectConfigFile():
def test_correct(self, temp_dir, helpers):
metadata = ProjectMetadata(str(temp_dir), PluginManager(), {'project': {'name': 'foo', 'dynamic': ['version']}, 'tool': {'hatch': {'build': {'reproducible': False}}}})
file_path = ((temp_dir / 'a') / 'b')
... |
def main():
args = parse_args()
model_zoo = args.model_zoo
dst_folder = args.dst_folder
bucket = oss2.Bucket(oss2.Auth(ACCESS_KEY_ID, ACCESS_KEY_SECRET), ENDPOINT, BUCKET_NAME)
for (root, dirs, files) in os.walk(model_zoo):
for file in files:
file_path = osp.relpath(osp.join(root... |
class BaseDatasetBuilder():
def __init__(self, dataset_name):
self.dataset_name = dataset_name
def load(self, dataset_type, config, *args, **kwargs):
dataset = self._load(dataset_type, config, *args, **kwargs)
if (dataset is not None):
dataset.init_processors()
da... |
class NormalisedGaussianKDEStorageRecorder(NumpyArrayNormalisedStorageRecorder):
def __init__(self, *args, **kwargs):
self.resample_freq = kwargs.pop('resample_freq', None)
self.resample_func = kwargs.pop('resample_func', None)
self.use_reflection = kwargs.pop('use_reflection', True)
... |
def _remove_from_contactgroup(my_object, contactgroup):
if isinstance(contactgroup, six.string_types):
contactgroup = Contactgroup.objects.get_by_shortname(contactgroup)
contactgroup_name = contactgroup.contactgroup_name
if (my_object.object_type == 'contact'):
return _remove_object_from_gro... |
def floats_tensor(shape, scale=1.0, rng=None, name=None):
if (rng is None):
rng = global_rng
total_dims = 1
for dim in shape:
total_dims *= dim
values = []
for _ in range(total_dims):
values.append((rng.random() * scale))
return torch.tensor(data=values, dtype=torch.float... |
class TestVersions():
def test_default_known(self, isolation):
builder = MockBuilder(str(isolation))
builder.PLUGIN_NAME = 'foo'
builder.get_version_api = (lambda : {'2': str, '1': str})
assert (builder.config.versions == builder.config.versions == ['2', '1'])
def test_default_ov... |
def recover_coef2(seed):
input_list = ['m', 'k', 'A0', 'c']
output_coef = 'k_coef'
D_in = np.mat('1, 0, 0; 1, 0, -2; 0, 1, 0; 1, 0, -1').T
D_out = np.mat('0;, 0; -1')
dimension_info = [D_in, D_out]
basis1_in = np.array([1, 1, 0, (- 2)]).reshape((- 1), 1)
basis2_in = np.array([0, 1, 0, (- 1)]... |
class Effect4256(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
groups = ('Missile Launcher Heavy', 'Missile Launcher Rapid Light', 'Missile Launcher Heavy Assault')
fit.modules.filteredItemBoost((lambda mod: (mod.item.group.name in groups)), 'speed', sr... |
class TestDynamoDBDict():
def test_to_dynamodb_dict(self):
dt = datetime(2022, 12, 31, 23, 59, 59, tzinfo=timezone.utc)
test_model = DictTestModel()
test_model.number_attr = 1
test_model.unicode_attr = 'foo'
test_model.datetime_attr = dt
test_model.bool_attr = True
... |
def get_problem_graph(problem_type, n=None, instance_i=0):
if (n is None):
if (problem_type == 'HardwareGridProblem'):
n = 4
elif (problem_type == 'SKProblem'):
n = 3
elif (problem_type == 'ThreeRegularProblem'):
n = 4
else:
raise Value... |
def extract_first_line_failure(failures_short_lines):
failures = {}
file = None
in_error = False
for line in failures_short_lines.split('\n'):
if re.search('_ \\[doctest\\]', line):
in_error = True
file = line.split(' ')[2]
elif (in_error and (not line.split(' ')[... |
def test_create_df_from_collection(spark_context, spark_session):
input_data = [{'json_column': '{"abc": 123}', 'a': 123, 'b': 'abc'}]
output_df = create_df_from_collection(input_data, spark_context, spark_session)
target_df = spark_session.sql("select 123 as a, 'abc' as b, replace(to_json(named_struct('abc... |
class Dashboard():
def __init__(self, port):
self.vis = Visdom(port=port)
def loss(self, losses, title):
x = np.arange(1, (len(losses) + 1), 1)
self.vis.line(losses, x, env='loss', opts=dict(title=title))
def image(self, image, title):
if image.is_cuda:
image = im... |
class TransformerDecoderTest(TestFairseqDecoderBase):
def setUp(self):
super().setUp()
dict = get_dummy_dictionary(vocab_size=DEFAULT_TEST_VOCAB_SIZE)
decoder = TransformerDecoder(dict)
dummy_encoder_output = get_dummy_encoder_output(encoder_out_shape=(50, 5, 256))
self.setUp... |
class SharedEvent():
def __init__(self):
self._active_count = 0
self._event = asyncio.Event()
self._event.set()
def __enter__(self):
self._active_count += 1
self._event.clear()
def __exit__(self, _exc_type, _exc_val, _exc_tb):
self._active_count -= 1
i... |
class Servo(object):
pypilot_dir = (os.getenv('HOME') + '/.pypilot/')
calibration_filename = (pypilot_dir + 'servocalibration')
def __init__(self, client, sensors):
self.client = client
self.sensors = sensors
self.lastdir = 0
self.calibration = self.register(JSONValue, 'calib... |
def write_manifest_stats_file(bucket: str, column_name: str, manifest_entry_stats: ManifestEntryStats) -> None:
logger.info(f'writing stats completion file contents: {manifest_entry_stats}')
stats_completion_file_s3_url = get_manifest_stats_s3_url(bucket, column_name, manifest_entry_stats.delta_locator)
log... |
class TestPassportBase():
driver_license_selfie_file_id = 'DgADBAADEQQAAkopgFNr6oi-wISRtAI'
driver_license_selfie_file_unique_id = 'd4e390cca57b4da5a65322b304762a12'
driver_license_front_side_file_id = 'DgADBAADxwMAApnQgVPK2-ckL2eXVAI'
driver_license_front_side_file_unique_id = 'd9d52a700cbb4a189a80104a... |
class Effect2489(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: (mod.item.group.name == 'Remote Tracking Computer')), 'falloffEffectiveness', ship.getModifiedItemAttr('shipBonusMC'), skill='Minmatar Cruiser', **kwargs) |
('social_core.backends.base.BaseAuth.request', side_effect=MockAuthCanceled)
class TestMiddleware(TestCase):
def setUp(self):
session = self.client.session
session['facebook_state'] = '1'
session.save()
self.complete_url = reverse('social:complete', kwargs={'backend': 'facebook'})
... |
(stability='beta')
def train(params: Dict, dtrain: RayDMatrix, num_boost_round: int=10, *args, evals: Union[(List[Tuple[(RayDMatrix, str)]], Tuple[(RayDMatrix, str)])]=(), evals_result: Optional[Dict]=None, additional_results: Optional[Dict]=None, ray_params: Union[(None, RayParams, Dict)]=None, _remote: Optional[bool]... |
class AugmentedHelpFormatter(argparse.RawDescriptionHelpFormatter):
def __init__(self, prog: str) -> None:
super().__init__(prog=prog, max_help_position=28)
def _fill_text(self, text: str, width: int, indent: str) -> str:
if ('\n' in text):
return super()._fill_text(text, width, inde... |
class ResizeLongestSide():
def __init__(self, target_length: int) -> None:
self.target_length = target_length
def apply_image(self, image: np.ndarray) -> np.ndarray:
target_size = self.get_preprocess_shape(image.shape[0], image.shape[1], self.target_length)
return np.array(resize(to_pil_... |
class ConditionalExpressionNode(ExpressionNode):
def __init__(self, condition, left, right):
self.condition = condition
self.left = left
self.right = right
def evaluate(self, context):
if self.condition.evaluate(context):
return self.left.evaluate(context)
els... |
def test_timedynamic_geo_json():
import geopandas as gpd
assert ('naturalearth_lowres' in gpd.datasets.available)
datapath = gpd.datasets.get_path('naturalearth_lowres')
gdf = gpd.read_file(datapath)
n_periods = 3
dt_range = pd.Series(pd.date_range('2001-08-1', periods=n_periods, freq='M'))
... |
def _pause() -> None:
player.pause()
try:
current_song = models.CurrentSong.objects.get()
current_song.last_paused = timezone.now()
current_song.save()
except models.CurrentSong.DoesNotExist:
pass
storage.put('paused', True)
redis.put('paused', True) |
.parametrize(['sparse', 'dtype'], [pytest.param(True, 'csr', id='sparse'), pytest.param(False, 'csr', id='sparse2dense'), pytest.param(False, 'dense', id='dense')])
def test_eigen_small(sparse, dtype):
H = (qutip.sigmax() + qutip.sigmaz()).to(dtype)
all_spvals = H.eigenenergies(sparse=sparse)
(spvals, spvec... |
def word_ngrams_indices(s, n):
tokens_with_indices = split_indices(s)
ngram_seqs_with_indices = form_ngrams(tokens_with_indices, n)
ngram_indices_pairs = (zip(*ngram_with_indices) for ngram_with_indices in ngram_seqs_with_indices)
return ((' '.join(ngram_seq), (indices[0][0], indices[(- 1)][1])) for (ng... |
class DrudeLorentzPadeBath(BosonicBath):
def __init__(self, Q, lam, gamma, T, Nk, combine=True, tag=None):
(eta_p, gamma_p) = self._corr(lam=lam, gamma=gamma, T=T, Nk=Nk)
ck_real = [np.real(eta) for eta in eta_p]
vk_real = [gam for gam in gamma_p]
ck_imag = [np.imag(eta_p[0])]
... |
class TestSerialise(TestCase):
def test_symbol_encoder_symbol(self):
(a, a_dict) = scalar_var_dict()
a_ser_json = Serialise._SymbolEncoder().default(a)
self.assertEqual(a_ser_json, a_dict)
add = pybamm.Addition(2, 4)
add_json = {'py/id': mock.ANY, 'py/object': 'pybamm.express... |
def update_repository_score(repo):
today = date.today()
final_score = 0.0
last_end_timedelta = timedelta(days=0)
for bucket in SEARCH_BUCKETS:
start_date = (today - bucket.delta)
end_date = (today - last_end_timedelta)
last_end_timedelta = bucket.delta
query = RepositoryA... |
class ExpvalMeasMitigatorFitter():
def __init__(self, result: Result, metadata: List[Dict[(str, any)]]):
self._num_qubits = None
self._cal_data = None
self._mitigator = None
(self._cal_data, self._num_qubits, self._method) = calibration_data(result, metadata)
def mitigator(self):... |
def run_and_display(prompts: List[str], controller: AttentionStore, indices_to_alter: List[int], generator: torch.Generator, run_standard_sd: bool=False, scale_factor: int=20, thresholds: Dict[(int, float)]={0: 0.05, 10: 0.5, 20: 0.8}, max_iter_to_alter: int=25, display_output: bool=False, sd_2_1: bool=False):
conf... |
class ItemAccessor(Accessor):
def __init__(self, key: Union[(int, str)], access_error: Optional[Catchable], path_element: TrailElement):
self.key = key
self._access_error = access_error
self._path_element = path_element
def getter(self, obj):
return obj[self.key]
def access_e... |
def _spotting_delta_model_dir(feature_name: str, dataset_type: str, protocol_name: str, run_name: str, models_dir: str) -> str:
delta_train_hyperparameters = TRAIN_HYPERPARAMETERS[dataset_type][feature_name][DELTA]
return os.path.join(models_dir, create_name(delta_train_hyperparameters, run_name, DELTA, feature... |
class Attention(nn.Module):
def __init__(self):
super(Attention, self).__init__()
if config.is_coverage:
self.W_c = nn.Linear(1, (config.hidden_dim * 2), bias=False)
self.decode_proj = nn.Linear((config.hidden_dim * 2), (config.hidden_dim * 2))
self.v = nn.Linear((config.... |
def ql_syscall_socketcall(ql: Qiling, call: int, args: int):
handlers: Mapping[(SOCKETCALL, Callable)] = {SOCKETCALL.SYS_SOCKET: ql_syscall_socket, SOCKETCALL.SYS_BIND: ql_syscall_bind, SOCKETCALL.SYS_CONNECT: ql_syscall_connect, SOCKETCALL.SYS_LISTEN: ql_syscall_listen, SOCKETCALL.SYS_ACCEPT: ql_syscall_accept, SO... |
class LayoutSkyTempleKeyMode(BitPackEnum, Enum):
ALL_BOSSES = 'all-bosses'
ALL_GUARDIANS = 'all-guardians'
ZERO = 0
ONE = 1
TWO = 2
THREE = 3
FOUR = 4
FIVE = 5
SIX = 6
SEVEN = 7
EIGHT = 8
NINE = 9
def num_keys(self):
if (self == self.ALL_BOSSES):
r... |
('/v1/repository/<apirepopath:repository>/permissions/team/')
_param('repository', 'The full path of the repository. e.g. namespace/name')
class RepositoryTeamPermissionList(RepositoryParamResource):
_repo_admin(allow_for_superuser=True)
('listRepoTeamPermissions')
def get(self, namespace_name, repository_n... |
def convert_diarization(base_model_name, hf_config, downstream_dict):
model = WavLMForAudioFrameClassification.from_pretrained(base_model_name, config=hf_config)
model.classifier.weight.data = downstream_dict['model.linear.weight']
model.classifier.bias.data = downstream_dict['model.linear.bias']
return... |
def forward(source, destination, recv_timeout=None, buffering=1024):
timeout = source.gettimeout()
source.settimeout(recv_timeout)
try:
raw_data = source.recv(buffering)
except socket.timeout:
pass
else:
while raw_data:
destination.sendall(raw_data)
tr... |
.online
def test_pypi(cache_dir):
pypi = service.PyPIService(cache_dir)
dep = service.ResolvedDependency('jinja2', Version('2.4.1'))
results: dict[(service.Dependency, list[service.VulnerabilityResult])] = dict(pypi.query_all(iter([dep])))
assert (len(results) == 1)
assert (dep in results)
vulns... |
class ElixirToDeclarativeWebDeclarativeChanges(MigrateElixirToDeclarative):
def schedule_upgrades(self):
super().schedule_upgrades()
self.replace_elixir()
def rename_primary_key_constraints(self):
self.rename_pk('sessiondata', ['id'])
def rename_foreign_keys_constraints(self):
... |
def save_model(epoch, args, model, optimizer, tr_loss, type_name=''):
model_to_save = (model.module if hasattr(model, 'module') else model)
output_model_file = os.path.join(args.output_dir, 'pytorch_model.bin.{}{}'.format(('' if (type_name == '') else (type_name + '.')), epoch))
optimizer_state_file = os.pa... |
def critic_weights(matrix, objectives, correlation='pearson', scale=True):
matrix = np.asarray(matrix, dtype=float)
matrix = (matrix_scale_by_cenit_distance(matrix, objectives=objectives) if scale else matrix)
dindex = np.std(matrix, axis=0)
import pandas as pd
corr_m1 = (1 - pd.DataFrame(matrix).co... |
def fc(x, K, name, relu=True, reuse=False):
c = int(x.get_shape()[1])
with tf.variable_scope(name, reuse=reuse) as scope:
weights = tf.get_variable('weights', shape=[c, K])
biases = tf.get_variable('biases', shape=[K])
relu_value = tf.nn.xw_plus_b(x, weights, biases, name=scope.name)
... |
def test_from_dict_complex_struct_type():
input_dict = {'type': 'struct', 'fields': [{'type': 'list', 'values': {'type': 'map', 'keys': {'type': 'int', 'bits': 32}, 'values': {'type': 'string', 'bytes': 50}}}]}
result = from_dict(input_dict)
assert isinstance(result, StructType)
assert isinstance(result... |
class Insert(COp):
__props__ = ('inplace',)
def __init__(self, inplace=False):
self.inplace = inplace
if self.inplace:
self.destroy_map = {0: [0]}
else:
self.view_map = {0: [0]}
def make_node(self, x, index, toInsert):
assert isinstance(x.type, TypedLi... |
def count_overlaps(grs, features=None, strandedness=None, how=None, nb_cpu=1):
kwargs = {'as_pyranges': False, 'nb_cpu': nb_cpu, 'strandedness': strandedness, 'how': how, 'nb_cpu': nb_cpu}
names = list(grs.keys())
if (features is None):
features = pr.concat(grs.values()).split(between=True)
else... |
class DebertaTokenizerFast(PreTrainedTokenizerFast):
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', 'token_type_ids']
slow_tokenizer_class... |
def test_measurement_parameters_for_values():
class Fake(FakeBase):
x = CommonBase.measurement('JUNK%d', '', preprocess_reply=(lambda v: v.replace('JUNK', '')), cast=int, values_kwargs={'testing': True})
def values(self, cmd, testing=False, **kwargs):
self.testing = testing
r... |
def create_wideresnet32_4(models_path, task, save_type, get_params=False):
print('Creating wrn32_4 untrained {} models...'.format(task))
model_params = get_task_params(task)
model_params['num_blocks'] = [5, 5, 5]
model_params['widen_factor'] = 4
model_params['dropout_rate'] = 0.3
model_name = '{... |
def main():
parser = argparse.ArgumentParser(description='Benchmark dataloading')
parser.add_argument('config', help='train config file path')
args = parser.parse_args()
cfg = Config.fromfile(args.config)
logger = get_root_logger()
logger.info(f'MMAction2 Version: {__version__}')
logger.info... |
def write_csv(table: pa.Table, path: str, *, filesystem: AbstractFileSystem, **kwargs) -> None:
with filesystem.open(path, 'wb') as f:
with pa.CompressedOutputStream(f, ContentEncoding.GZIP.value) as out:
if (kwargs.get('write_options') is None):
kwargs['write_options'] = pacsv.W... |
def plot_histogram(scores_csv: str, score_col: int, name: str, k: int, log: bool=True, clip: bool=False, maximize: bool=False):
scores = extract_scores(scores_csv, score_col)
if clip:
scores = (scores[(scores < 0)] if (not maximize) else scores[(scores >= 0)])
cutoff = (scores[k] if (not maximize) e... |
class UpdateInitTestCase(UpdateBaseTest):
def test_init_empty(self):
update = Update([], self.config)
self.assertEqual(update, dict())
def test_init_with_reqs(self):
with patch('pyup.requirements.Requirement') as req:
req.needs_update = True
req_files = [Requireme... |
def main():
with tf.variable_scope('resnet'):
with tf.device(tf.train.replica_device_setter(ps_tasks=NUM_PS, ps_device='/job:ps/', worker_device='/job:worker/task:0/')):
inputs = tf.random_uniform([BATCH_SIZE, 299, 299, 3], name='Inputs')
(logit, _) = nets.resnet_v1.resnet_v1_152(inp... |
class MobileViTIntermediate(nn.Module):
def __init__(self, config: MobileViTConfig, hidden_size: int, intermediate_size: int) -> None:
super().__init__()
self.dense = nn.Linear(hidden_size, intermediate_size)
if isinstance(config.hidden_act, str):
self.intermediate_act_fn = ACT2F... |
class BlenderbotSmallTokenizerFast(PreTrainedTokenizerFast):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
slow_tokenizer_class = BlenderbotSmallTokenizer
def __init__(self, vocab_file=None... |
class EnsembleDecoderOutput(object):
def __init__(self, model_dec_outs):
self.model_dec_outs = tuple(model_dec_outs)
def squeeze(self, dim=None):
return EnsembleDecoderOutput([x.squeeze(dim) for x in self.model_dec_outs])
def __getitem__(self, index):
return self.model_dec_outs[index... |
class InscDict(MutableMapping):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def __getitem__(self, key):
return self.__dict__[key.lower()][(- 1)]
def __setitem__(self, key, value):
self.__dict__[key.lower()] = (key, value)
def __delitem__(self, key):
... |
class Notification():
id: int
type: EventID
flags: EventFlag
def parse(cls, data: bytes) -> 'Notification':
[type, flags, _, _, id] = struct.unpack('<BBBBI', bytearray(data))
return cls(id=id, type=type, flags=flags)
def is_preexisting(self) -> bool:
return ((self.flags & Eve... |
def se_resnext101_32x4d(num_classes, loss, pretrained='imagenet', **kwargs):
model = SENet(num_classes=num_classes, loss=loss, block=SEResNeXtBottleneck, layers=[3, 4, 23, 3], groups=32, reduction=16, dropout_p=None, inplanes=64, input_3x3=False, downsample_kernel_size=1, downsample_padding=0, last_stride=2, fc_dim... |
class ENet(BaseModel):
def __init__(self, num_classes, in_channels=3, freeze_bn=False, **_):
super(ENet, self).__init__()
self.initial = InitalBlock(in_channels)
self.bottleneck10 = BottleNeck(16, 64, downsample=True, p_drop=0.01)
self.bottleneck11 = BottleNeck(64, p_drop=0.01)
... |
class LatentDepthwiseXCorrCls(nn.Module):
def __init__(self, in_channels, hidden, out_channels, kernel_size=3, n_latent=128, de_hidden=128, is_meta_training=True):
super(LatentDepthwiseXCorrCls, self).__init__()
self.conv_kernel = nn.Sequential(nn.Conv2d(in_channels, hidden, kernel_size=kernel_size,... |
def _f(mu, nu, sigma, n, a, k, collection):
if (mu == 2):
(yield _visit(n, a, k, collection))
else:
for v in _f((mu - 1), (nu - 1), ((mu + sigma) % 2), n, a, k, collection):
(yield v)
if (nu == (mu + 1)):
a[mu] = (mu - 1)
(yield _visit(n, a, k, collection))
... |
class TypeclassManager(TypedObjectManager):
def smart_search(self, query):
querysplit = shlex.split(query)
(queries, plustags, plusattrs, negtags, negattrs) = ([], [], [], [], [])
for (ipart, part) in enumerate(querysplit):
(key, rest) = (part, '')
if (':' in part):
... |
def test_cache_get_miss():
cache = Cache()
creator_mock = MagicMock()
creator_mock.return_value = 'created obj'
with patch_logger('pypyr.cache', logging.DEBUG) as mock_logger_debug:
obj = cache.get('one', (lambda : creator_mock('1')))
assert (obj == 'created obj')
creator_mock.assert_cal... |
def main(args):
save_path = './saved_model/{}'.format(args.name)
if (not os.path.exists(save_path)):
os.makedirs(save_path)
log_path = './log/{}'.format(args.name)
if (not os.path.exists(log_path)):
os.makedirs(log_path)
out_path = './output/{}'.format(args.name)
if (not os.path.... |
def main(model, config):
set_seed(config.seed)
device = torch.device(config.device)
if device.type.startswith('cuda'):
torch.cuda.set_device((device.index or 0))
model_config = torch.load(config.config_load)
model_vocab = torch.load(config.vocab_load)
model_state = torch.load(config.mode... |
def make_sdist(project: TestProject, working_dir: Path) -> Path:
project_dir = (working_dir / 'project')
project_dir.mkdir(parents=True, exist_ok=True)
project.generate(project_dir)
sdist_dir = (working_dir / 'sdist')
subprocess.run([sys.executable, '-m', 'build', '--sdist', '--outdir', str(sdist_di... |
class ResNeXt(nn.Module):
def __init__(self, block, layers, sample_size=224, sample_duration=16, pretrained=True, shortcut_type='B', cardinality=32, num_classes=400):
self.inplanes = 64
super(ResNeXt, self).__init__()
self.conv1 = nn.Conv3d(3, 64, kernel_size=7, stride=(1, 2, 2), padding=(3,... |
class MP2Info():
def __init__(self, qmolecule, threshold=1e-12):
(self._terms, self._mp2_delta) = _compute_mp2(qmolecule, threshold)
self._mp2_energy = (qmolecule.hf_energy + self._mp2_delta)
self._num_orbitals = qmolecule.num_orbitals
self._core_orbitals = qmolecule.core_orbitals
... |
class _IPC():
def unpack(data: bytes, *, is_json: (bool | None)=None) -> tuple[(Any, bool)]:
if ((is_json is None) or is_json):
try:
return (json.loads(data.decode()), True)
except ValueError as e:
if is_json:
raise IPCError('Unable... |
.slow
_figures_equal()
def test_DecisionMatrixPlotter_heatmap(decision_matrix, fig_test, fig_ref):
dm = decision_matrix(seed=42, min_alternatives=3, max_alternatives=3, min_criteria=3, max_criteria=3)
plotter = plot.DecisionMatrixPlotter(dm=dm)
test_ax = fig_test.subplots()
plotter.heatmap(ax=test_ax)
... |
class VibrationalStructureResult(EigenstateResult):
def __init__(self) -> None:
super().__init__()
self._algorithm_result: Optional[AlgorithmResult] = None
self._computed_vibrational_energies: Optional[np.ndarray] = None
self._num_occupied_modals_per_mode: Optional[List[List[float]]]... |
_stabilize
_specialize
_rewriter([log])
def local_log_add_exp(fgraph, node):
if (node.op == log):
z = node.inputs[0]
if (z.owner and (z.owner.op == add)):
zi = z.owner.inputs
pre_exp = [x.owner.inputs[0] for x in zi if (x.owner and (x.owner.op == exp))]
if (len(pr... |
def simplified_domain_concatenation(children, mesh, copy_this=None):
concat = DomainConcatenation(children, mesh, copy_this=copy_this)
if all((isinstance(child, pybamm.StateVector) for child in children)):
longest_eval_array = len(children[(- 1)]._evaluation_array)
eval_arrays = {}
for c... |
def ArtistList():
(artists, set_artists) = use_state(['Marta Colvin Andrade', 'Lamidi Olonade Fakeye', 'Louise Nevelson'])
def handle_sort_click(event):
set_artists(sorted(artists))
def handle_reverse_click(event):
set_artists(list(reversed(artists)))
return html.div(html.h1('Inspiring s... |
_server.route('/services/<service>/keys/<kid>', methods=['PUT'])
def put_service_key(service, kid):
metadata = {'ip': get_request_ip()}
rotation_duration = request.args.get('rotation', None)
expiration_date = request.args.get('expiration', None)
if (expiration_date is not None):
try:
... |
def test_pth_in_site_vs_python_path(tmp_path):
session = cli_run([str(tmp_path)])
site_packages = str(session.creator.purelib)
with open(os.path.join(site_packages, 'test.pth'), 'w', encoding='utf-8') as f:
f.write('import sys; sys.testpth="ok"\n')
out = subprocess.check_output([str(session.crea... |
class CorrMM_gradWeights(BaseCorrMM):
_direction = 'backprop weights'
def make_node(self, img, topgrad, shape=None):
img = as_tensor_variable(img)
topgrad = as_tensor_variable(topgrad)
(img, topgrad) = self.as_common_dtype(img, topgrad)
if (img.type.ndim != 4):
raise ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.