code stringlengths 281 23.7M |
|---|
.skipif((sys.version_info < (3, 8)), reason='added in 3.8')
def test_legacy_display_without_fields_warns(fake_object_no_id):
printer = v4_cli.LegacyPrinter()
with mock.patch('builtins.print') as mocked:
printer.display(fake_object_no_id, obj=fake_object_no_id)
assert ('No default fields to show' in ... |
def get_mask(image, net, size=224):
(image_h, image_w) = (image.shape[0], image.shape[1])
down_size_image = cv2.resize(image, (size, size))
down_size_image = cv2.cvtColor(down_size_image, cv2.COLOR_BGR2RGB)
down_size_image = torch.from_numpy(down_size_image).float().div(255.0).unsqueeze(0)
down_size... |
def check_type_arguments(graph: Graph, scc: list[str], errors: Errors) -> None:
for module in scc:
state = graph[module]
assert state.tree
analyzer = TypeArgumentAnalyzer(errors, state.options, state.tree.is_typeshed_file(state.options), state.manager.semantic_analyzer.named_type)
wi... |
def save_checkpoint(state, save_dir, is_best=False, remove_module_from_keys=True, model_name=''):
mkdir_if_missing(save_dir)
if remove_module_from_keys:
state_dict = state['state_dict']
new_state_dict = OrderedDict()
for (k, v) in state_dict.items():
if k.startswith('module.'... |
class SpecVersionType(GeneratedsSuper):
__hash__ = GeneratedsSuper.__hash__
subclass = None
superclass = None
def __init__(self, major=None, minor=None, gds_collector_=None, **kwargs_):
self.gds_collector_ = gds_collector_
self.gds_elementtree_node_ = None
self.original_tagname_ ... |
def _copy_command_options(pyproject: dict, dist: 'Distribution', filename: _Path):
tool_table = pyproject.get('tool', {})
cmdclass = tool_table.get('setuptools', {}).get('cmdclass', {})
valid_options = _valid_command_options(cmdclass)
cmd_opts = dist.command_options
for (cmd, config) in pyproject.ge... |
class AFT_FULL(nn.Module):
def __init__(self, d_model, n=49, simple=False):
super(AFT_FULL, self).__init__()
self.fc_q = nn.Linear(d_model, d_model)
self.fc_k = nn.Linear(d_model, d_model)
self.fc_v = nn.Linear(d_model, d_model)
if simple:
self.position_biases = t... |
def test_conv_module():
with pytest.raises(AssertionError):
conv_cfg = 'conv'
ConvModule(3, 8, 2, conv_cfg=conv_cfg)
with pytest.raises(AssertionError):
norm_cfg = 'norm'
ConvModule(3, 8, 2, norm_cfg=norm_cfg)
with pytest.raises(KeyError):
act_cfg = dict(type='softmax... |
.parametrize('not_redefine', ['_evaluate_data', '_make_result'])
def test_SKCDecisionMakerABC_not_redefined(not_redefine):
content = {'_skcriteria_parameters': []}
for method_name in ['_evaluate_data', '_make_result', '_validate_data']:
if (method_name != not_redefine):
content[method_name] ... |
class EuropeanCallExpectedValue(UncertaintyProblem):
def __init__(self, uncertainty_model: UnivariateDistribution, strike_price: float, c_approx: float, i_state: Optional[Union[(List[int], np.ndarray)]]=None, i_compare: Optional[int]=None, i_objective: Optional[int]=None) -> None:
super().__init__((uncertai... |
_equal.register(mappingproxy, mappingproxy)
def asssert_mappingproxy_equal(result, expected, path=(), msg='', **kwargs):
_check_sets(set(result), set(expected), msg, (path + ('.keys()',)), 'key')
failures = []
for (k, resultv) in iteritems(result):
expectedv = expected[k]
try:
as... |
def freeze_layers(model, layers=2, use_fcn=False):
if use_fcn:
if (layers >= 2):
model.module.conv1.eval()
model.module.bn1.eval()
model.module.layer1.eval()
model.module.layer2.eval()
for (name, param) in model.module.conv1.named_parameters():
... |
class OnDeletedMessages():
def on_deleted_messages(self=None, filters=None, group: int=0) -> Callable:
def decorator(func: Callable) -> Callable:
if isinstance(self, pyrogram.Client):
self.add_handler(pyrogram.handlers.DeletedMessagesHandler(func, filters), group)
eli... |
def add_railing_to_stairs(bm, top_faces, normal, prop):
steps = sort_faces(top_faces, normal)
first_step = steps[0]
last_step = steps[(- 1)]
(offset, corner_pw) = (prop.rail.offset, prop.rail.corner_post_width)
if prop.landing:
(v1, v2) = railing_verts(bm, sort_verts(first_step.verts, normal... |
def tpu_cross_replica_concat(tensor, tpu_context=None):
if ((tpu_context is None) or (tpu_context.num_replicas <= 1)):
return tensor
num_replicas = tpu_context.num_replicas
with tf.name_scope('tpu_cross_replica_concat'):
ext_tensor = tf.scatter_nd(indices=[[xla.replica_id()]], updates=[tenso... |
class TestUnsatCores(TestCase):
def _helper_check_examples(self, solver_name):
for (f, _, satisfiability, logic) in get_example_formulae():
if (not logic.quantifier_free):
continue
if (satisfiability == False):
with UnsatCoreSolver(name=solver_name, un... |
class TypeTriggersVisitor(TypeVisitor[List[str]]):
def __init__(self, use_logical_deps: bool, seen_aliases: (set[TypeAliasType] | None)=None) -> None:
self.deps: list[str] = []
self.seen_aliases: set[TypeAliasType] = (seen_aliases or set())
self.use_logical_deps = use_logical_deps
def ge... |
def convert_pytorch(nlp: Pipeline, opset: int, output: Path, use_external_format: bool):
if (not is_torch_available()):
raise Exception('Cannot convert because PyTorch is not installed. Please install torch first.')
import torch
from torch.onnx import export
from .pytorch_utils import is_torch_l... |
def _convert_convolution(inexpr, keras_layer, etab):
_check_data_format(keras_layer)
is_deconv = (type(keras_layer).__name__ == 'Conv2DTranspose')
is_depthconv = (type(keras_layer).__name__ == 'DepthwiseConv2D')
weightList = keras_layer.get_weights()
weight = weightList[0]
if (etab.data_layout =... |
def _visit_display(builder: IRBuilder, items: list[Expression], constructor_op: Callable[([list[Value], int], Value)], append_op: CFunctionDescription, extend_op: CFunctionDescription, line: int, is_list: bool) -> Value:
accepted_items = []
for item in items:
if isinstance(item, StarExpr):
a... |
class TestFileMagic():
def test_read_bytes_crash(self, mocker):
mock_open = mocker.patch('io.open')
mock_open().__enter__().read.side_effect = IOError
volume = Volume(disk=Disk(ImageParser(), '...'))
volume.get_raw_path = mocker.Mock(return_value='...')
assert (volume._get_ma... |
def test_trustme_cli_quiet(capsys: pytest.CaptureFixture[str], tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.chdir(tmp_path)
main(argv=['-q'])
assert tmp_path.joinpath('server.key').exists()
assert tmp_path.joinpath('server.pem').exists()
assert tmp_path.joinpath('client.pem'... |
def add_empty_config(args):
keys = ['get_read_time', 'split_row_groups', 'dask_profile', 'verify_results']
for key in keys:
if (key not in args):
args[key] = None
if ('file_format' not in args):
args['file_format'] = 'parquet'
if ('output_filetype' not in args):
args[... |
def upload_training_data(training_dir, api_key=None):
results = monitoring.load_results(training_dir)
if (not results):
raise error.Error("Could not find any manifest files in {}.\n\n(HINT: this usually means you did not yet close() your env.monitor and have not yet exited the process. You should call '... |
def tableify(lines, header=True, topdeco=True, bottomdeco=True):
def rowline(text, maxlens, alignments=['<', '>']):
outline = ''
for (ndx, length) in enumerate(maxlens):
align = (alignments[ndx] if (ndx < len(alignments)) else alignments[(- 1)])
if ((text[ndx] is not None) an... |
class TestAdaroundLoss(unittest.TestCase):
def _compute_recon_loss(self, device):
tf.compat.v1.reset_default_graph()
session = tf.compat.v1.Session()
np.random.seed(0)
inp = np.random.rand(32, 3, 12, 12)
target = np.random.rand(32, 3, 12, 12)
inp_t = np.transpose(inp,... |
class UntrustedServerReturnedError(NetworkException):
def __init__(self, *, original_exception):
self.original_exception = original_exception
def get_message_for_gui(self) -> str:
return str(self)
def __str__(self):
return _('The server returned an error.')
def __repr__(self):
... |
def series_extract_missing(series: pd.Series) -> pd.Series:
def _decode(x):
if (np.issubdtype(type(x), np.floating) and np.isnan(x)):
(code, namespace) = _get_payload_from_nan(x)
if (namespace is None):
return x
elif (namespace == 255):
rai... |
def get_grade_from_index(index_in):
if (index_in == 0):
return 0
elif (index_in < 6):
return 1
elif (index_in < 16):
return 2
elif (index_in < 26):
return 3
elif (index_in < 31):
return 4
elif (index_in == 31):
return 5
else:
raise Valu... |
class WeightedRMSE(BaseMetric):
def __init__(self, label_name):
self._label_name = label_name
def eval(self, predict, labels_map):
label = labels_map[self._label_name]
if ((np.sum(label) == 0) or (np.sum(label) == label.size)):
return MetricResult(result=float('nan'))
... |
def _StatusBarTruncInfo(win):
truncInfo = _WindowTruncInfo(win)
for (i, (title, rect, font, flag)) in enumerate(truncInfo):
rect.bottom -= win.VertBorderWidth
if (i == 0):
rect.right -= win.HorizBorderWidth
else:
rect.right -= win.InterBorderWidth
return trunc... |
def score_2afc_dataset(data_loader, func):
d0s = []
d1s = []
gts = []
for (i, data) in enumerate(data_loader.load_data()):
d0s += func(data['ref'], data['p0']).tolist()
d1s += func(data['ref'], data['p1']).tolist()
gts += data['judge'].cpu().numpy().flatten().tolist()
d0s = n... |
def main(_):
config = _config.build_config()
config['train_epochs'] = 200
config['lr_decay_method'] = 'STEPWISE'
config['train_seconds'] = (- 1)
spec = create_best_nasbench_spec(config)
data = evaluate.augment_and_evaluate(spec, config, FLAGS.model_dir)
tf.logging.info(data) |
def filter_matrix_rows(matrix, keep_rows):
if isinstance(matrix, _kaldi_matrix.Matrix):
return _sparse_matrix._filter_matrix_rows(matrix, keep_rows)
if isinstance(matrix, _sparse_matrix.SparseMatrix):
return _sparse_matrix._filter_sparse_matrix_rows(matrix, keep_rows)
if isinstance(matrix, _... |
class TestNoDataDir(object):
def setup_method(self):
self.temporary_file_list = False
self.saved_data_path = pysat.params['data_dirs']
pysat.params.data['data_dirs'] = []
reload(pysat._files)
return
def teardown_method(self):
pysat.params.data['data_dirs'] = self.... |
class TestCreateColormap(EndianTest):
def setUp(self):
self.req_args_0 = {'alloc': 0, 'mid': , 'visual': , 'window': }
self.req_bin_0 = b'N\x00\x04\x00\xac8VT\x84\x94\xdb\n\xe8\x1cT$'
def testPackRequest0(self):
bin = request.CreateColormap._request.to_binary(*(), **self.req_args_0)
... |
.cuda
.parametrize('quant_scheme', [QuantScheme.post_training_tf, QuantScheme.training_range_learning_with_tf_init, QuantScheme.post_training_tf_enhanced, QuantScheme.training_range_learning_with_tf_enhanced_init])
def test_initialization_and_export_non_strict_symmetric(quant_scheme) -> None:
tf.compat.v1.reset_def... |
class CallC(RegisterOp):
def __init__(self, function_name: str, args: list[Value], ret_type: RType, steals: StealsDescription, is_borrowed: bool, error_kind: int, line: int, var_arg_idx: int=(- 1)) -> None:
self.error_kind = error_kind
super().__init__(line)
self.function_name = function_nam... |
def create_toy_graph():
synsets = {}
for (wn_id, name) in enumerate(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']):
synsets[name] = imagenet_spec.Synset(wn_id, name, set(), set())
is_a_relations = [('a', 'b'), ('a', 'c'), ('b', 'g'), ('c', 'd'), ('c', 'e'), ('e', 'f'), ('e', 'h')]
for t in is_a_relat... |
def _get_in_vals(binst: BloqInstance, reg: Register, soq_assign: Dict[(Soquet, RegPosition)]) -> Union[(RegPosition, NDArray[RegPosition])]:
if (not reg.shape):
return soq_assign[Soquet(binst, reg)]
arg = np.empty(reg.shape, dtype=object)
for idx in reg.all_idxs():
soq = Soquet(binst, reg, i... |
def test_initialize_setup_cfg_only(hatch, helpers, temp_dir):
setup_cfg_file = (temp_dir / 'setup.cfg')
setup_cfg_file.write_text('[metadata]\nname = testapp\nversion = attr:testapp.__version__\ndescription = Foo\nauthor = U.N. Owen\nauthor_email = \nurl = = MIT\n')
with temp_dir.as_cwd():
result =... |
class TestElements():
def setup_method(self):
test_file_path = mm.datasets.get_path('bubenec')
self.df_buildings = gpd.read_file(test_file_path, layer='buildings')
self.df_tessellation = gpd.read_file(test_file_path, layer='tessellation')
self.df_streets = gpd.read_file(test_file_pat... |
class Rosenbrock(object):
def __init__(self):
self._dim = 2
self._search_domain = numpy.repeat([[(- 2.0), 2.0]], self._dim, axis=0)
self._num_init_pts = 3
self._sample_var = 0.0
self._min_value = 0.0
self._observations = []
self._num_fidelity = 0
def evalu... |
def _replace_file(original_path):
(fh, replacement_path) = tempfile.mkstemp()
try:
with os.fdopen(fh, 'w') as replacement:
with open(original_path) as original:
(yield (original, replacement))
except Exception:
raise
else:
shutil.copymode(original_path... |
(4)
def _downgrade_v4(op):
op.drop_index('ix_equities_fuzzy_symbol')
op.drop_index('ix_equities_company_symbol')
op.execute('UPDATE equities SET exchange = exchange_full')
with op.batch_alter_table('equities') as batch_op:
batch_op.drop_column('exchange_full')
op.create_index('ix_equities_fu... |
class NewlinesFilter(UniqueFilter):
name = 'newlines'
events = (Event.MESSAGE,)
extra_fields_type = ExtraNewlinesSettings
async def triggered_on(self, ctx: FilterContext) -> bool:
earliest_relevant_at = (arrow.utcnow() - timedelta(seconds=self.extra_fields.interval))
relevant_messages = ... |
def test_pytest_configure_warning(pytester: Pytester, recwarn) -> None:
pytester.makeconftest('\n def pytest_configure():\n import warnings\n\n warnings.warn("from pytest_configure")\n ')
result = pytester.runpytest()
assert (result.ret == 5)
assert ('INTERNALERROR' n... |
class notMNIST(torch.utils.data.Dataset):
def __init__(self, root, train=True, transform=None, download=False):
self.root = os.path.expanduser(root)
self.transform = transform
self.filename = 'notmnist.zip'
self.url = '
fpath = os.path.join(root, self.filename)
if (no... |
def ResidualNet(network_type, depth, num_classes, att_type, joint):
assert (network_type in ['ImageNet', 'CIFAR10', 'CIFAR100']), 'network type should be ImageNet or CIFAR10 / CIFAR100'
assert (depth in [18, 34, 50, 101]), 'network depth should be 18, 34, 50 or 101'
if (depth == 18):
model = ResNet(... |
class Effect6607(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: (mod.item.requiresSkill('Armored Command') or mod.item.requiresSkill('Information Command'))), 'warfareBuff4Value', src.getModifiedItemAttr('shipBonusSuper... |
class BitStatusWidget(HBox, SiemensWidget, _Mixin_DB_property, _Mixin_Byte_property, _Mixin_Bit_property):
icon = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEUAAAAdCAIAAABzMjbkAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAJrSURBVFhH3ZQxSBtRGMffcpDlpiylEG5xOYTQrUgGN5FMEjIJIhnawVGQuJxwk0O... |
class CalcSwapLocalModuleCommand(wx.Command):
def __init__(self, fitID, position1, position2):
wx.Command.__init__(self, True, 'Swap Modules')
self.fitID = fitID
self.position1 = position1
self.position2 = position2
def Do(self):
pyfalog.debug('Doing swapping between {} a... |
_call_aside
def _initialize_master_working_set():
working_set = WorkingSet._build_master()
_declare_state('object', working_set=working_set)
require = working_set.require
iter_entry_points = working_set.iter_entry_points
add_activation_listener = working_set.subscribe
run_script = working_set.ru... |
def bounding_control_points(beam, beam_collimation, rotation_direction, dose_rate):
cps = {}
cps['first'] = beam.ControlPointSequence[0]
cps['mid'] = beam.ControlPointSequence[1]
cps['last'] = beam.ControlPointSequence[(- 1)]
for cp in cps.values():
cp.BeamLimitingDevicePositionSequence = be... |
def read_left_context_phones(filename):
ans = [line.strip(' \t\r\n') for line in open(filename, 'r', encoding='latin-1')]
if (len(ans) == 0):
raise RuntimeError('The file {0} contains no left-context phones.'.format(filename))
whitespace = re.compile('[ \t]+')
for s in ans:
if (len(white... |
def train_model(args, dr_train: DataReader, model, pset, nset):
assert torch.cuda.is_available(), 'no GPU available'
cuda = torch.device('cuda')
cpu = torch.device('cpu')
model.to(cuda)
gids = {'pos': pset, 'neg': nset}
gdata = {}
loader = {}
for key in ['pos', 'neg']:
gdata[key]... |
class ClippedScoreModifier(ScoreModifier):
def __init__(self, upper_x: float, lower_x=0.0, high_score=1.0, low_score=0.0) -> None:
assert (low_score < high_score)
self.upper_x = upper_x
self.lower_x = lower_x
self.high_score = high_score
self.low_score = low_score
sel... |
def leet_clean(data):
def __convert_leet(word):
word = re.sub('0', 'o', word)
word = re.sub('1', 'i', word)
word = re.sub('3', 'e', word)
word = re.sub('\\$', 's', word)
word = re.sub('\\', 'a', word)
return word
if verbose:
print(('#' * 10), 'Step - L33T ... |
_REGISTRY.register()
class DDAIG(TrainerX):
def __init__(self, cfg):
super().__init__(cfg)
self.lmda = cfg.TRAINER.DDAIG.LMDA
self.clamp = cfg.TRAINER.DDAIG.CLAMP
self.clamp_min = cfg.TRAINER.DDAIG.CLAMP_MIN
self.clamp_max = cfg.TRAINER.DDAIG.CLAMP_MAX
self.warmup = c... |
class TestMagicEncode():
class TestInit():
def test_disabled_requires_encoding(self, driver: printer.Dummy) -> None:
with pytest.raises(Error):
MagicEncode(driver, disabled=True)
class TestWriteWithEncoding():
def test_init_from_none(self, driver: printer.Dummy) -> No... |
.skipif((pytensor.config.floatX == 'float32'), reason='Test is designed for 64bit precision')
def test_log_exp_m1():
check_transform(tr.log_exp_m1, Rplusbig)
check_jacobian_det(tr.log_exp_m1, Rplusbig, elemwise=True)
check_jacobian_det(tr.log_exp_m1, Vector(Rplusbig, 2), pt.vector, [0, 0], elemwise=True)
... |
def _write_splits(splits_path: Path, splits: Splits) -> None:
logging.warning(f'Creating dataset splits file at {splits_path}')
with splits_path.open('w') as splits_file:
writer = csv.DictWriter(splits_file, fieldnames=FIELD_NAMES)
writer.writeheader()
for split_key in splits:
... |
class CustomizedEpitranTokenizer(BaseTokenizer):
def __init__(self, lang_id, writing_system=None, lexicon=None):
super().__init__(lang_id, None)
self.lang_id = lang_id
self.writing_system = writing_system
if writing_system:
lang_id = ((lang_id + '-') + writing_system)
... |
def create_optimizer(init_lr, num_train_steps, num_warmup_steps):
learning_rate_fn = tf.keras.optimizers.schedules.PolynomialDecay(initial_learning_rate=init_lr, decay_steps=num_train_steps, end_learning_rate=0.0)
if num_warmup_steps:
learning_rate_fn = WarmUp(initial_learning_rate=init_lr, decay_schedu... |
class CallReceiver(Receiver):
_e_factors = ('callable',)
protocol = PROTOCOL_CHUNKS
def __init__(self, callable):
self.callable = callable
self.lines = None
super().__init__()
def transmit(self):
if (self.lines is not None):
self.callable(self.lines)
s... |
class _CppLintState(object):
def __init__(self):
self.verbose_level = 1
self.error_count = 0
self.filters = _DEFAULT_FILTERS[:]
self.counting = 'total'
self.errors_by_category = {}
self.output_format = 'emacs'
def SetOutputFormat(self, output_format):
self... |
class TestSVD():
def op_numpy(self, A):
return scipy.linalg.svd(A)
def _gen_dm(self, N, rank, dtype):
return qutip.rand_dm(N, rank=rank, dtype=dtype).data
def _gen_non_square(self, N):
mat = np.random.randn(N, (N // 2))
for i in range((N // 2)):
mat[(i, i)] += 5
... |
class MappingType(BaseType):
MAPPING: DictType[(str, Tuple[(Any, Optional[str])])] = {}
def __init__(self, *, none_ok: bool=False, completions: _Completions=None) -> None:
super().__init__(none_ok=none_ok, completions=completions)
self.valid_values = ValidValues(*[(key, doc) for (key, (_val, doc... |
class TestInputMediaVideoWithoutRequest(TestInputMediaVideoBase):
def test_slot_behaviour(self, input_media_video):
inst = input_media_video
for attr in inst.__slots__:
assert (getattr(inst, attr, 'err') != 'err'), f"got extra slot '{attr}'"
assert (len(mro_slots(inst)) == len(se... |
def convert_cached_name(file_name, batch_size):
prefix = (((CACHE_DIR + 'batch_size_') + str(batch_size)) + '_')
prefix += file_name.strip().split('/')[(- 1)]
train_cache_name = prefix.replace('.txt', '.tfrecord').replace('.csv', '.tfrecord').replace('.libsvm', '.tfrecord')
return train_cache_name |
class ResumeStream(Scaffold):
async def resume_stream(self, chat_id: Union[(int, str)]):
if (self._app is None):
raise NoMTProtoClientSet()
if (not self._is_running):
raise ClientNotStarted()
chat_id = (await self._resolve_chat_id(chat_id))
try:
st... |
class _TopLevelFinder():
def __init__(self, dist: Distribution, name: str):
self.dist = dist
self.name = name
def __call__(self, wheel: 'WheelFile', files: List[str], mapping: Dict[(str, str)]):
src_root = (self.dist.src_root or os.curdir)
top_level = chain(_find_packages(self.di... |
def draw_tsp_solution(G, order, colors, pos):
G2 = nx.DiGraph()
G2.add_nodes_from(G)
n = len(order)
for i in range(n):
j = ((i + 1) % n)
G2.add_edge(order[i], order[j], weight=G[order[i]][order[j]]['weight'])
default_axes = plt.axes(frameon=True)
nx.draw_networkx(G2, node_color=c... |
class DataclassTransformSpec():
__slots__ = ('eq_default', 'order_default', 'kw_only_default', 'frozen_default', 'field_specifiers')
def __init__(self, *, eq_default: (bool | None)=None, order_default: (bool | None)=None, kw_only_default: (bool | None)=None, field_specifiers: (tuple[(str, ...)] | None)=None, fr... |
def main(argv):
parser = argparse.ArgumentParser()
parser.add_argument('--classes', help='The number of classes of dataset.')
parser.add_argument('--size', default=224, help='The image size of train sample.')
parser.add_argument('--batch', default=32, help='The number of train samples per batch.')
p... |
def delete_user(user=None, email=None, password=None):
if ((user is None) or (email is None)):
log.debug('Deletion failed because either User or email is None')
return False
username = user.username
database_user = get_user_from_db_or_none(username, email)
if (database_user is None):
... |
class BoW(nn.Module):
def __init__(self, vocab: List[str], word_weights: Dict[(str, float)]={}, unknown_word_weight: float=1, cumulative_term_frequency: bool=True):
super(BoW, self).__init__()
vocab = list(set(vocab))
self.config_keys = ['vocab', 'word_weights', 'unknown_word_weight', 'cumul... |
def test_multiple_workspaces_from_initialize(pylsp_w_workspace_folders):
(pylsp, workspace_folders) = pylsp_w_workspace_folders
assert (len(pylsp.workspaces) == 2)
folders_uris = [uris.from_fs_path(str(folder)) for folder in workspace_folders]
for folder_uri in folders_uris:
assert (folder_uri i... |
def get_module_cache(dirname: str, init_args=None) -> ModuleCache:
global _module_cache
if (init_args is None):
init_args = {}
if (_module_cache is None):
_module_cache = ModuleCache(dirname, **init_args)
atexit.register(_module_cache._on_atexit)
elif init_args:
warnings.... |
def test_merge_sauce_options(monkeypatch, testdir):
version = {'seleniumVersion': '3.8.1'}
capabilities = {'browserName': 'chrome', 'sauce:options': version}
expected = {'name': 'test_merge_sauce_options.test_sauce_capabilities'}
expected.update(version)
run_w3c_sauce_test(capabilities, expected, mo... |
def sv_l(d_embeddings, l_eval_trial, args):
d_embeddings_all = d_embeddings[0]
d_embeddings_1 = d_embeddings[1]
d_embeddings_2 = d_embeddings[2]
d_embeddings_5 = d_embeddings[3]
(y, y_score_org, y_score_1, y_score_2, y_score_5) = ([], [], [], [], [])
l_trial_split = split_list(l_in=l_eval_trial,... |
def train_model(model, optimizer, train_loader, model_func, lr_scheduler, optim_cfg, start_epoch, total_epochs, start_iter, rank, tb_log, ckpt_save_dir, train_sampler=None, lr_warmup_scheduler=None, ckpt_save_interval=1, max_ckpt_save_num=50, merge_all_iters_to_one_epoch=False):
accumulated_iter = start_iter
wi... |
class BeaverSshTunnel(BeaverSubprocess):
def __init__(self, beaver_config, logger=None):
super(BeaverSshTunnel, self).__init__(beaver_config, logger=logger)
self._log_template = '[BeaverSshTunnel] - {0}'
key_file = beaver_config.get('ssh_key_file')
tunnel = beaver_config.get('ssh_tun... |
def safe_walk(path: str) -> Iterable[tuple[(str, list[str], list[str])]]:
seen = set()
for (root, dirs, files) in os.walk(path, followlinks=True):
stat = os.stat(root)
identifier = (stat.st_dev, stat.st_ino)
if (identifier in seen):
del dirs[:]
continue
se... |
class MMD_NCA_loss(nn.Module):
def __init__(self):
super().__init__()
def kernel_function(self, x1, x2):
k1 = torch.exp(((- torch.pow((x1 - x2), 2)) / 2))
k2 = torch.exp(((- torch.pow((x1 - x2), 2)) / 8))
k4 = torch.exp(((- torch.pow((x1 - x2), 2)) / 32))
k8 = torch.exp((... |
class SegNet(nn.Module):
def __init__(self, input_nbr=3, label_nbr=19):
super(SegNet, self).__init__()
batchNorm_momentum = 0.1
self.conv11 = nn.Conv2d(input_nbr, 64, kernel_size=3, padding=1)
self.bn11 = nn.BatchNorm2d(64, momentum=batchNorm_momentum)
self.conv12 = nn.Conv2d... |
_env('DR-PickCube-v1', max_episode_steps=100, override=True)
class DomainRandomizationPickCubeEnvV1(PickCubeEnv):
def reset(self, seed=None, reconfigure=True):
return super().reset(seed, reconfigure)
def _load_actors(self):
self.cube_half_size = self._episode_rng.uniform(0.01, 0.03, size=3)
... |
class LabelAccuracyEvaluator(SentenceEvaluator):
def __init__(self, dataloader: DataLoader, name: str='', softmax_model=None):
self.dataloader = dataloader
self.name = name
self.softmax_model = softmax_model
if name:
name = ('_' + name)
self.csv_file = (('accuracy... |
def main_worker(gpu, ngpus_per_node, args):
global best_acc1
args.gpu = gpu
if (args.gpu is not None):
print('Use GPU: {} for training'.format(args.gpu))
if args.distributed:
if ((args.dist_url == 'env://') and (args.rank == (- 1))):
args.rank = int(os.environ['RANK'])
... |
.functions
def test_groupby_agg_multi():
df = pd.DataFrame({'date': ['', '', '', '', '', ''], 'user_id': [1, 2, 1, 2, 1, 2], 'values': [1, 2, 3, 4, 5, 6]})
df_new = df.groupby_agg(by=['date', 'user_id'], new_column_name='date_average', agg_column_name='values', agg=np.count_nonzero)
expected_agg = np.array(... |
class AngleCalFitter(BaseGateFitter):
def __init__(self, backend_result, xdata, qubits, fit_p0, fit_bounds):
circuit_names = []
for (cind, _) in enumerate(xdata):
circuit_names.append(('anglecal1Qcircuit_%d_' % cind))
BaseGateFitter.__init__(self, '$AngleCal1Q$', backend_result, ... |
class SawyerPlateSlideBackSideEnvV2(SawyerXYZEnv):
def __init__(self):
goal_low = ((- 0.05), 0.6, 0.015)
goal_high = (0.15, 0.6, 0.015)
hand_low = ((- 0.5), 0.4, 0.05)
hand_high = (0.5, 1, 0.5)
obj_low = ((- 0.25), 0.6, 0.0)
obj_high = ((- 0.25), 0.6, 0.0)
sup... |
def run(config):
if (config['wandb_entity'] is not None):
init_wandb(config, config['experiment_name'], config['wandb_entity'], 'imagenet')
if (config['G_path'] is None):
download_G()
config['G_path'] = 'checkpoints/138k'
(G, state_dict, device, experiment_name) = load_G(config)
... |
def detect_traits(name=None, alias=None, filetype=None):
result = []
if filetype:
filetype = filetype.lstrip('.')
theme = config.traits_by_alias.get(alias)
if (alias and theme):
result = [theme, (filetype or 'other')]
elif (filetype in KIND_AUDIO):
result = ['audio', filetype... |
class SmtLibScript(object):
def __init__(self):
self.annotations = None
self.commands = []
def add(self, name, args):
self.add_command(SmtLibCommand(name=name, args=args))
def add_command(self, command):
self.commands.append(command)
def evaluate(self, solver):
lo... |
def compute_particle_residual(particle_qd_0: wp.array(dtype=wp.vec3), particle_qd_1: wp.array(dtype=wp.vec3), particle_f: wp.array(dtype=wp.vec3), particle_m: wp.array(dtype=float), gravity: wp.vec3, dt: float, residual: wp.array(dtype=wp.vec3)):
tid = wp.tid()
m = particle_m[tid]
v1 = particle_qd_1[tid]
... |
def process_docstring(app, what, name, obj, options, lines):
if ((what == 'class') and issubclass(obj, pyunity.Component)):
indexes = []
for (i, line) in enumerate(lines):
if line.startswith('.. attribute:: '):
indexes.append(i)
for index in reversed(indexes):
... |
class InputInjection(nn.Module):
def __init__(self, downsamplingRatio):
super().__init__()
self.pool = nn.ModuleList()
for i in range(0, downsamplingRatio):
self.pool.append(nn.AvgPool2d(3, stride=2, padding=1))
def forward(self, input):
for pool in self.pool:
... |
class BeatGUI(AObject):
def AOBJECT_TYPE(self):
return 'BeatGUI'
def __init__(self, media=None, path=None, clear_temp=None):
AObject.__init__(self, path=path)
if (media is not None):
self.media = media
def initializeBlank(self):
AObject.initializeBlank(self)
... |
class Timer():
def __init__(self):
self.label = pyglet.text.Label('00:00', font_size=360, x=(window.width // 2), y=(window.height // 2), anchor_x='center', anchor_y='center')
self.reset()
def reset(self):
self.time = 0
self.running = False
self.label.text = '00:00'
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.