code stringlengths 281 23.7M |
|---|
def include_subclasses(cl: type, converter: Converter, subclasses: (tuple[(type, ...)] | None)=None, union_strategy: (Callable[([Any, BaseConverter], Any)] | None)=None, overrides: (dict[(str, AttributeOverride)] | None)=None) -> None:
collect()
if (subclasses is not None):
parent_subclass_tree = (cl, *... |
class World():
def __init__(self, locs, objs, relations, args):
self.graph = nx.Graph()
self.graph.add_nodes_from(locs, type='location', fillcolor='yellow', style='filled')
self.graph.add_nodes_from(objs, type='object')
self.graph.add_edges_from(relations)
self.locations = {v... |
class FashionMNIST_truncated_WO_reload(data.Dataset):
def __init__(self, root, dataidxs=None, train=True, transform=None, target_transform=None, full_dataset=None):
self.root = root
self.dataidxs = dataidxs
self.train = train
self.transform = transform
self.target_transform =... |
class AudioSource(Component):
playOnStart = ShowInInspector(bool, False)
loop = ShowInInspector(bool, False)
clip = ShowInInspector(AudioClip, None)
def __init__(self):
super(AudioSource, self).__init__()
global channels
self.channel = channels
channels += 1
if co... |
class Effect4060(BaseEffect):
runTime = 'early'
type = ('projected', 'passive')
def handler(fit, beacon, context, projectionRange, **kwargs):
fit.modules.filteredChargeMultiply((lambda mod: mod.charge.requiresSkill('Rockets')), 'thermalDamage', beacon.getModifiedItemAttr('smallWeaponDamageMultiplier... |
class TestMemcachedCollector(CollectorTestCase):
def setUp(self):
config = get_collector_config('MemcachedCollector', {'interval': 10, 'hosts': ['localhost:11211']})
self.collector = MemcachedCollector(config, None)
def test_import(self):
self.assertTrue(MemcachedCollector)
('socket.... |
class StarletteOpenAPIValidRequestHandler():
def __init__(self, request: Request, call_next: RequestResponseEndpoint):
self.request = request
self.call_next = call_next
async def __call__(self, request_unmarshal_result: RequestUnmarshalResult) -> Response:
self.request.scope['openapi'] =... |
_module()
class UDAConcatDataset(ConcatDataset):
def __init__(self, datasets, separate_eval=True):
try:
super(ConcatDataset, self).__init__(datasets)
except NotImplementedError as e:
print(e)
print('Since our program does not use the special authentication method ... |
def tensors_to_np(tensors):
if isinstance(tensors, dict):
new_np = {}
for (k, v) in tensors.items():
if isinstance(v, torch.Tensor):
v = v.cpu().numpy()
if (type(v) is dict):
v = tensors_to_np(v)
new_np[k] = v
elif isinstance(te... |
class FastAPIInstrumentor(BaseInstrumentor):
_original_fastapi = None
def instrument_app(app: fastapi.FastAPI, server_request_hook: _ServerRequestHookT=None, client_request_hook: _ClientRequestHookT=None, client_response_hook: _ClientResponseHookT=None, tracer_provider=None, meter_provider=None, excluded_urls=N... |
def test_emit_warning_when_event_loop_is_explicitly_requested_in_async_gen_fixture(pytester: Pytester):
pytester.makepyfile(dedent(' import pytest\n import pytest_asyncio\n\n _asyncio.fixture\n async def emits_warning(event_loop):\n yield\n\n .as... |
def with_qutip_qip_stub(tmp_path, monkeypatch):
pkg_dir = (tmp_path / 'qutip_qip')
pkg_dir.mkdir()
init_file = (pkg_dir / '__init__.py')
init_file.write_text("__version__ = 'x.y.z'")
circuit_file = (pkg_dir / 'circuit.py')
circuit_file.write_text('class QubitCircuit:\n pass')
monkeypatch.... |
def parse_args():
parser = argparse.ArgumentParser(description='Semantic Segmentation Training With Pytorch')
parser.add_argument('--teacher-model', type=str, default='deeplabv3', help='model name')
parser.add_argument('--student-model', type=str, default='deeplabv3', help='model name')
parser.add_argum... |
def phi_structure(subsystem: Subsystem, sia: SystemIrreducibilityAnalysis=None, distinctions: CauseEffectStructure=None, relations: Relations=None, sia_kwargs: dict=None, ces_kwargs: dict=None, relations_kwargs: dict=None) -> PhiStructure:
sia_kwargs = (sia_kwargs or dict())
ces_kwargs = (ces_kwargs or dict())
... |
def main():
from server import pypilotServer
server = pypilotServer()
client = pypilotClient(server)
boatimu = BoatIMU(client)
quiet = ('-q' in sys.argv)
lastprint = 0
while True:
t0 = time.monotonic()
server.poll()
client.poll()
data = boatimu.read()
... |
def false_negative_rate(tp: torch.LongTensor, fp: torch.LongTensor, fn: torch.LongTensor, tn: torch.LongTensor, reduction: Optional[str]=None, class_weights: Optional[List[float]]=None, zero_division: Union[(str, float)]=1.0) -> torch.Tensor:
return _compute_metric(_false_negative_rate, tp, fp, fn, tn, reduction=re... |
def pauli_measurement_circuit(op: str, qubit: QuantumRegister, clbit: ClassicalRegister) -> QuantumCircuit:
circ = QuantumCircuit([qubit, clbit])
if (op == 'X'):
circ.h(qubit)
circ.measure(qubit, clbit)
if (op == 'Y'):
circ.sdg(qubit)
circ.h(qubit)
circ.measure(qubit,... |
def test_sqliteio_write_updates_existing_text_item(tmpfile, view):
item = BeeTextItem(text='foo bar')
view.scene.addItem(item)
item.setScale(1.3)
item.setPos(44, 55)
item.setZValue(0.22)
item.setRotation(33)
item.save_id = 1
io = SQLiteIO(tmpfile, view.scene, create_new=True)
io.writ... |
def makeUpdateMatrixGraph(qnnArch, currentUnitaries, lda, currentOutput, adjMatrix, storedStates, l, m):
numInputQubits = qnnArch[(l - 1)]
summ = 0
for i in range(len(adjMatrix[0])):
for j in range(i, len(adjMatrix[0])):
if (adjMatrix[i][j] != 0):
firstPart = updateMatrix... |
class BatchInferenceMethod(PromptMethod):
def __init__(self, **kwargs: Any):
super().__init__(**kwargs)
def run(self, x: List[Union[(str, Dict)]], in_context_examples: List[Dict]=None, prompt_file_path: Optional[str]=None, **kwargs: Any) -> Union[(str, List[str])]:
verbose = kwargs.get('verbose'... |
.usefixtures('dbus')
def test_statusnotifier_defaults_vertical_bar(manager_nospawn, sni_config):
screen = sni_config.screens[0]
screen.left = screen.top
screen.top = None
manager_nospawn.start(sni_config)
widget = manager_nospawn.c.widget['statusnotifier']
assert (widget.info()['height'] == 0)
... |
def bert_binaryclassification_model_fn_builder(bert_config_file, init_checkpoints, args):
def model_fn(features, labels, mode, params):
logger.info('*** Features ***')
if isinstance(features, dict):
features = (features['words'], features['token_type_ids'], features['text_length'])
... |
def ribbon():
cfg = get_config()
disable_ribbon = False
if cfg.has_option('JUPYTER', 'disable_ribbon'):
try:
disable_ribbon = bool(int(cfg.get('JUPYTER', 'disable_ribbon')))
except (ValueError, TypeError):
_log.error('Unexpected value for JUPYTER.disable_ribbon.')
... |
class IndexLoader():
def __init__(self, index_path, use_gpu=True):
self.index_path = index_path
self.use_gpu = use_gpu
self._load_codec()
self._load_ivf()
self._load_doclens()
self._load_embeddings()
def _load_codec(self):
print_message(f'#> Loading codec.... |
class TrainerControl():
should_training_stop: bool = False
should_epoch_stop: bool = False
should_save: bool = False
should_evaluate: bool = False
should_log: bool = False
def _new_training(self):
self.should_training_stop = False
def _new_epoch(self):
self.should_epoch_stop ... |
def polygon_for_parent(polygon, parent):
childp = Polygon(polygon)
if isinstance(parent, PageType):
if parent.get_Border():
parentp = Polygon(polygon_from_points(parent.get_Border().get_Coords().points))
else:
parentp = Polygon([[0, 0], [0, parent.get_imageHeight()], [par... |
class SystemAccount(Base):
__tablename__ = 'systemaccount'
id = Column(Integer, primary_key=True)
discriminator = Column('row_type', String(40))
__mapper_args__ = {'polymorphic_identity': 'systemaccount', 'polymorphic_on': discriminator}
owner_party_id = Column(Integer, ForeignKey(Party.id))
own... |
def xls2ld(fn, header=[], sheetname=True, keymap={}):
try:
import xlrd
except ImportError:
raise Exception('\n\t\t\tIn order to load Excel files, you need to install the xlrd python module. Run:\n\t\t\tpip install xlrd\n\t\t\t')
headerset = (True if len(header) else False)
f = xlrd.open_... |
def format_with_duration(timestamp: (Timestamp | None), other_timestamp: (Timestamp | None)=None, max_units: int=2) -> (str | None):
if (timestamp is None):
return None
if (other_timestamp is None):
other_timestamp = arrow.utcnow()
formatted_timestamp = discord_timestamp(timestamp)
durat... |
def train_and_evaluate(dataset_name, batch_size=100, n_epochs=5, learning_rate=0.0001, z_dim=2, pixel=64, load_model=False, w=1, scale=False):
device = torch.device(('cuda' if torch.cuda.is_available() else 'cpu'))
(siamese, optimizer) = get_instance_model_optimizer(device, learning_rate, z_dim, pixel)
(tra... |
def parallel_map(task, values, task_args=None, task_kwargs=None, reduce_func=None, map_kw=None, progress_bar=None, progress_bar_kwargs={}):
if (task_args is None):
task_args = ()
if (task_kwargs is None):
task_kwargs = {}
map_kw = _read_map_kw(map_kw)
end_time = (map_kw['timeout'] + time... |
class YicesInstaller(SolverInstaller):
SOLVER = 'yices'
def __init__(self, install_dir, bindings_dir, solver_version, mirror_link=None, yicespy_version='HEAD'):
archive_name = ('Yices-%s.tar.gz' % solver_version)
native_link = '
SolverInstaller.__init__(self, install_dir=install_dir, bin... |
.end_to_end()
def test_ini_markers_whitespace(runner, tmp_path):
tmp_path.joinpath('pyproject.toml').write_text("[tool.pytask.ini_options]\nmarkers = {'a1 ' = 'this is a whitespace marker'}")
source = '\n import pytask\n .a1\n def task_markers():\n assert True\n '
tmp_path.joinpath('task_... |
class MP4Cover(bytes):
FORMAT_JPEG = AtomDataType.JPEG
FORMAT_PNG = AtomDataType.PNG
def __new__(cls, data, *args, **kwargs):
return bytes.__new__(cls, data)
def __init__(self, data, imageformat=FORMAT_JPEG):
self.imageformat = imageformat
__hash__ = bytes.__hash__
def __eq__(sel... |
def find_role_replicas(app: specs.AppDef, role_name: Optional[str]) -> List[Tuple[(str, int)]]:
role_replicas = []
for role in app.roles:
if ((role_name is None) or (role_name == role.name)):
for i in range(role.num_replicas):
role_replicas.append((role.name, i))
return r... |
def get_image_metadata(file_path):
size = os.path.getsize(file_path)
with open(file_path, 'rb') as input:
height = (- 1)
width = (- 1)
data = input.read(26)
msg = ' raised while trying to decode as JPEG.'
if ((size >= 10) and (data[:6] in (b'GIF87a', b'GIF89a'))):
... |
('/v1/organization/<orgname>/robots/<robot_shortname>')
_param('orgname', 'The name of the organization')
_param('robot_shortname', 'The short name for the robot, without any user or organization prefix')
_user_resource(UserRobot)
class OrgRobot(ApiResource):
schemas = {'CreateRobot': CREATE_ROBOT_SCHEMA}
_scop... |
def test_expired_membership_with_overlapping_payments():
with time_machine.travel('2020-10-10 10:00:00', tick=False):
membership_1 = MembershipFactory(status=MembershipStatus.CANCELED)
membership_1.add_pretix_payment(organizer='python-italia', event='pycon-demo', order_code='XXYYZZ', total=1000, sta... |
def test_admin_player_kick_last(solo_two_world_session, flask_app, mocker, mock_audit):
mock_emit = mocker.patch('flask_socketio.emit')
user = database.User.get_by_id(1234)
sa = MagicMock()
sa.get_current_user.return_value = user
session = database.MultiplayerSession.get_by_id(1)
with flask_app.... |
class Wing_Loss(torch.nn.Module):
def __init__(self, w=10, eps=2):
super(Wing_Loss, self).__init__()
self.w = w
self.eps = eps
self.C = (w - (w * np.log((1 + (w / eps)))))
def forward(self, prediction, target):
differ = (prediction - target).abs()
log_idxs = (diff... |
def extract_archive(archive, solver, put_inside=False):
print('extracting {0}'.format(archive))
root = os.path.join('solvers', (solver if put_inside else ''))
if archive.endswith('.tar.gz'):
if os.path.exists(archive[:(- 7)]):
shutil.rmtree(archive[:(- 7)])
tfile = tarfile.open(a... |
class TransformValuesMapping(Feature):
def __init__(self, values_to_transforms):
self.values_to_transforms = values_to_transforms.copy()
def on_attach(self, fgraph):
if hasattr(fgraph, 'values_to_transforms'):
raise AlreadyThere()
fgraph.values_to_transforms = self.values_to_... |
class DataConfig(object):
def __init__(self, image_height, shuffle_buffer_size, read_buffer_size_bytes, num_prefetch):
self.image_height = image_height
self.shuffle_buffer_size = shuffle_buffer_size
self.read_buffer_size_bytes = read_buffer_size_bytes
self.num_prefetch = num_prefetch |
def test_equal_diag():
np.random.seed(42)
for _ in range(3):
diag = np.random.rand(5)
x = floatX(np.random.randn(5))
pots = [quadpotential.quad_potential(diag, False), quadpotential.quad_potential((1.0 / diag), True), quadpotential.quad_potential(np.diag(diag), False), quadpotential.quad... |
def entry_point_ensemble_folders():
parser = argparse.ArgumentParser()
parser.add_argument('-i', nargs='+', type=str, required=True, help='list of input folders')
parser.add_argument('-o', type=str, required=True, help='output folder')
parser.add_argument('-np', type=int, required=False, default=default... |
class PasswordField(Field):
def __init__(self, default=None, required=False, required_message=None, label=None, writable=None, min_length=6, max_length=20):
label = (label or '')
super().__init__(default, required, required_message, label, readable=Allowed(False), writable=writable, min_length=min_l... |
class GACOSGrid(object):
def __init__(self, filename, time, data, ulLat, ulLon, dLat, dLon):
self.filename = filename
self.time = time
self.data = data
(self.rows, self.cols) = data.shape
self.dLat = dLat
self.dLon = dLon
self.ulLat = ulLat
self.ulLon ... |
class TestUCCSDHartreeFock(QiskitChemistryTestCase):
def setUp(self):
super().setUp()
self.reference_energy = (- 1.)
self.seed = 700
aqua_globals.random_seed = self.seed
self.driver = HDF5Driver(self.get_resource_path('test_driver_hdf5.hdf5'))
fermionic_transformation... |
class HTTPBackend(BaseStorageBackend):
def get(self, filepath):
value_buf = urlopen(filepath).read()
return value_buf
def get_text(self, filepath, encoding='utf-8'):
value_buf = urlopen(filepath).read()
return value_buf.decode(encoding)
def get_local_path(self, filepath: str)... |
_config
def test_display_kb(manager):
from pprint import pprint
cmd = '-s {} -o cmd -f display_kb'.format(manager.sockfile)
table = run_qtile_cmd(cmd)
print(table)
pprint(table)
assert (table.count('\n') >= 2)
assert re.match('(?m)^Mode\\s{3,}KeySym\\s{3,}Mod\\s{3,}Command\\s{3,}Desc\\s*$', ... |
def _is_character_face_to(state: EnvironmentState, node: Node, char_index: int):
if state.evaluate(ExistsRelation(CharacterNode(char_index), Relation.FACING, NodeInstanceFilter(node))):
return True
for face_node in state.get_nodes_from(_get_character_node(state, char_index), Relation.FACING):
if... |
.parametrize('date_str', ['01-Jan-2000', '29-Feb-2016', '31-Dec-2000', '01-Apr-2003', '01-Apr-2007', '01-Apr-2009', '01-Jan-1990'])
def test_date_checker_valid(date_str: str):
warnings = [warning for (_, warning) in check_peps._date(1, date_str, '<Prefix>')]
assert (warnings == []), warnings |
def validate_3d(config, model, loader, output_dir, writer_dict=None, epoch=None):
batch_time = AverageMeter()
data_time = AverageMeter()
losses_depth = AverageMeter()
losses_pitch = AverageMeter()
losses_depth_mean = AverageMeter()
losses_depth_max = AverageMeter()
model.eval()
(preds, b... |
class Parameters(ConditionDict):
__slots__ = ['broadening_method', 'truncation', 'neighbour_lines', 'chunksize', 'cutoff', 'db_use_cached', 'dbformat', 'dbpath', 'dxL', 'dxG', 'export_lines', 'export_populations', 'folding_thresh', 'include_neighbouring_lines', 'levelsfmt', 'lvl_use_cached', 'optimization', 'parfun... |
class GraphiteSparse(Layer):
def __init__(self, input_dim, output_dim, dropout=0.0, act=tf.nn.relu, **kwargs):
super(GraphiteSparse, self).__init__(**kwargs)
with tf.variable_scope((self.name + '_vars')):
self.vars['weights'] = weight_variable_glorot(input_dim, output_dim, name='weights'... |
def test_write_colormap(tmpdir):
with rasterio.open('tests/data/shade.tif') as src:
shade = src.read(1)
meta = src.meta
tiffname = str(tmpdir.join('foo.png'))
meta['driver'] = 'PNG'
with rasterio.open(tiffname, 'w', **meta) as dst:
dst.write(shade, indexes=1)
dst.write_co... |
class EarthquakeCatalog(object):
def get_event(self, name):
raise NotImplementedError
def iter_event_names(self, time_range, **kwargs):
raise NotImplementedError
def get_event_names(self, time_range, **kwargs):
return list(self.iter_event_names(time_range, **kwargs))
def get_even... |
def validate_unique(self, exclude=None):
(unique_checks, date_checks) = self._get_unique_checks(exclude=exclude)
errors = self._perform_unique_checks(unique_checks)
date_errors = self._perform_date_checks(date_checks)
for (k, v) in date_errors.items():
errors.setdefault(k, []).extend(v)
if e... |
def test_create_venv_finds_no_python_executable(manager: EnvManager, poetry: Poetry, config: Config, mocker: MockerFixture, config_virtualenvs_path: Path, venv_name: str) -> None:
if ('VIRTUAL_ENV' in os.environ):
del os.environ['VIRTUAL_ENV']
poetry.package.python_versions = '^3.6'
mocker.patch('sy... |
def test_normalize_currency():
assert (normalize_currency('EUR') == 'EUR')
assert (normalize_currency('eUr') == 'EUR')
assert (normalize_currency('FUU') is None)
assert (normalize_currency('') is None)
assert (normalize_currency(None) is None)
assert (normalize_currency(' EUR ') is None)
... |
class TrainerModel(torch.nn.Module):
def __init__(self, grid_size, dht):
super().__init__()
self.dummy = torch.nn.Parameter(torch.randn(1, 1), requires_grad=True)
self.head = BalancedRemoteExpert(grid_size=grid_size, dht=dht, forward_timeout=TIMEOUT, backward_timeout=BACKWARD_TIMEOUT, uid_pr... |
def downgrade(op, tables, tester):
op.drop_column('repository', 'state')
op.drop_table('repomirrorconfig')
op.drop_table('repomirrorrule')
for logentrykind in ['repo_mirror_enabled', 'repo_mirror_disabled', 'repo_mirror_config_changed', 'repo_mirror_sync_started', 'repo_mirror_sync_failed', 'repo_mirror... |
class Effect6351(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
fit.modules.filteredChargeBoost((lambda mod: mod.charge.requiresSkill('Missile Launcher Operation')), 'kineticDamage', src.getModifiedItemAttr('shipBonusCC3'), skill='Caldari Cruiser', **kwargs) |
.parametrize('n_bytes, expected_size', [(None, '0 bytes'), (5, '5 bytes'), ((3 * 1024), '3.00 KB'), ((1024 * 3000), '2.93 MB'), (((1024 * 1024) * 5000), '4.88 GB'), ((((1024 * 1024) * 5000) * 1000), '4882.81 GB')])
def test_format_file_size(n_bytes, expected_size):
assert (format_file_size(n_bytes) == expected_size... |
def iter_paths(root: fsnative, exclude: (Iterable[fsnative] | None)=None, skip_hidden: bool=True) -> Generator[(fsnative, None, None)]:
assert isinstance(root, fsnative)
exclude = (exclude or [])
assert all((isinstance(p, fsnative) for p in exclude))
assert os.path.abspath(root)
def skip(path):
... |
def run_segmentation(img, settings=NNUNET_SETTINGS_DEFAULTS):
setup_nnunet_environment()
try:
from nnunet.inference.predict import predict_from_folder
except ImportError:
logger.error('nnUNet is not installed. Please pip install nnunet to use this functionality')
nnunet_model_path = Path... |
def compute_obj_class_precision(metrics, gt_dict, classes_out):
interact_idxs = torch.nonzero(gt_dict['action_valid_interact'])
obj_classes_prob = classes_out[tuple(interact_idxs.T)]
obj_classes_pred = obj_classes_prob.max(1)[1]
obj_classes_gt = torch.cat(gt_dict['object'], dim=0)
precision = (torch... |
class TestReparentNotify(EndianTest):
def setUp(self):
self.evt_args_0 = {'event': , 'override': 0, 'parent': , 'sequence_number': 43356, 'type': 128, 'window': , 'x': (- 19227), 'y': (- 30992)}
self.evt_bin_0 = b'\x80\x00\\\xa9\x05oHo\xf6\xb4tE~\n#;\xe5\xb4\xf0\x86\x00\x00\x00\x00\x00\x00\x00\x00\x... |
def get_syscall_mapper(archtype: QL_ARCH):
syscall_table = {QL_ARCH.X8664: x8664_syscall_table, QL_ARCH.ARM64: arm64_syscall_table}[archtype]
syscall_fixup = {QL_ARCH.X8664: (lambda n: ((n - ) if ( <= n <= ) else n)), QL_ARCH.ARM64: (lambda n: ((n - ) if (n >= ) else n))}[archtype]
def __mapper(syscall_num:... |
def createMailModel(parent):
model = QStandardItemModel(0, 3, parent)
model.setHeaderData(SUBJECT, Qt.Horizontal, 'Subject')
model.setHeaderData(SENDER, Qt.Horizontal, 'Sender')
model.setHeaderData(DATE, Qt.Horizontal, 'Date')
addMail(model, 'Happy New Year!', 'Grace K. <-inc.com>', QDateTime(QDate(... |
def test_rotated_latitude_longitude_operation():
aeaop = RotatedLatitudeLongitudeConversion(o_lat_p=1, o_lon_p=2, lon_0=3)
assert (aeaop.name == 'unknown')
assert (aeaop.method_name == 'PROJ ob_tran o_proj=longlat')
assert (_to_dict(aeaop) == {'o_lat_p': 1.0, 'o_lon_p': 2.0, 'lon_0': 3.0}) |
class LinkStats(ctypes.Structure):
_fields_ = [('maxFlow', ctypes.c_double), ('maxFlowDate', ctypes.c_double), ('maxVeloc', ctypes.c_double), ('maxDepth', ctypes.c_double), ('timeNormalFlow', ctypes.c_double), ('timeInletControl', ctypes.c_double), ('timeSurcharged', ctypes.c_double), ('timeFullUpstream', ctypes.c_... |
class TestClassyModel(unittest.TestCase):
def setUp(self) -> None:
self.base_dir = tempfile.mkdtemp()
self.orig_wrapper_cls_1 = MyTestModel.wrapper_cls
self.orig_wrapper_cls_2 = MyTestModel2.wrapper_cls
def tearDown(self) -> None:
shutil.rmtree(self.base_dir)
MyTestModel.... |
class ClientTests(unittest.TestCase):
def test_connection(self):
with run_server() as server:
with run_client(server) as client:
self.assertEqual(client.protocol.state.name, 'OPEN')
def test_connection_fails(self):
def remove_accept_header(self, request, response):
... |
def _wasserstein_update_input_check(x: torch.Tensor, y: torch.Tensor, x_weights: Optional[torch.Tensor]=None, y_weights: Optional[torch.Tensor]=None) -> None:
if ((x.nelement() == 0) or (y.nelement() == 0)):
raise ValueError('Distribution cannot be empty.')
if ((x.dim() > 1) or (y.dim() > 1)):
r... |
class CornerCornerAssociate(nn.Module):
def __init__(self, im_size, configs):
super(CornerCornerAssociate, self).__init__()
drn_22 = drn.drn_d_22(pretrained=False)
drn_modules = list(drn_22.children())
self.im_size = im_size
self.configs = configs
drn_modules[0][0] = ... |
def test_append_with_strings_unpack():
context = Context({'arblist': [1, 2], 'append': {'list': PyString('arblist'), 'addMe': 'xy', 'unpack': True}})
append.run_step(context)
context['append']['addMe'] = 'z'
append.run_step(context)
assert (context['arblist'] == [1, 2, 'x', 'y', 'z'])
assert (le... |
def kernel2d_conv(feat_in, kernel, ksize):
channels = feat_in.size(1)
(N, kernels, H, W) = kernel.size()
pad = ((ksize - 1) // 2)
feat_in = F.pad(feat_in, (pad, pad, pad, pad), mode='replicate')
feat_in = feat_in.unfold(2, ksize, 1).unfold(3, ksize, 1)
feat_in = feat_in.permute(0, 2, 3, 1, 5, 4)... |
class MultipleAccountsTest(AssociateActionTest):
alternative_user_data_body = json.dumps({'login': 'foobar2', 'id': 2, 'avatar_url': ' 'gravatar_id': 'somehexcode', 'url': ' 'name': 'monalisa foobar2', 'company': 'GitHub', 'blog': ' 'location': 'San Francisco', 'email': '', 'hireable': False, 'bio': 'There once was... |
def compute_acc(gold, pred, slot_temp):
miss_gold = 0
miss_slot = []
for g in gold:
if (g not in pred):
miss_gold += 1
miss_slot.append(g.rsplit('-', 1)[0])
wrong_pred = 0
for p in pred:
if ((p not in gold) and (p.rsplit('-', 1)[0] not in miss_slot)):
... |
class ConvBlockWOutput(nn.Module):
def __init__(self, conv_params, output_params):
super(ConvBlockWOutput, self).__init__()
input_channels = conv_params[0]
output_channels = conv_params[1]
max_pool_size = conv_params[2]
batch_norm = conv_params[3]
add_output = output_... |
_fixture(autouse=True)
def mocked_browser(browser_pool, request):
for browser in browser_pool.values():
browser.quit()
browser_pool.clear()
def mocked_browser(driver_name, *args, **kwargs):
mocked_browser = mock.MagicMock()
mocked_browser.driver = mock.MagicMock()
mocked_brow... |
class RPS(commands.Cog):
(case_insensitive=True)
async def rps(self, ctx: commands.Context, move: str) -> None:
move = move.lower()
player_mention = ctx.author.mention
if ((move not in CHOICES) and (move not in SHORT_CHOICES)):
raise commands.BadArgument(f"Invalid move. Pleas... |
def test_git_clone_default_branch_head(source_url: str, remote_refs: FetchPackResult, remote_default_ref: bytes, mocker: MockerFixture) -> None:
spy = mocker.spy(Git, '_clone')
spy_legacy = mocker.spy(Git, '_clone_legacy')
with Git.clone(url=source_url) as repo:
assert (remote_refs.refs[remote_defau... |
def test_sanity_check():
stp = token.STANDARD_TYPES.copy()
stp[token.Token] = '---'
t = {}
for (k, v) in stp.items():
t.setdefault(v, []).append(k)
if (len(t) == len(stp)):
return
for (k, v) in t.items():
if (len(v) > 1):
pytest.fail(('%r has more than one key... |
class BpsTradeValueCommissionModel(CommissionModel):
def __init__(self, commission: float):
self.commission = commission
def calculate_commission(self, fill_quantity: float, fill_price: float) -> float:
fill_quantity = abs(fill_quantity)
commission = (((fill_price * fill_quantity) * self... |
def get_generation_parser(interactive=False, default_task='translation'):
parser = get_parser('Generation', default_task)
add_dataset_args(parser, gen=True)
add_distributed_training_args(parser, default_world_size=1)
add_generation_args(parser)
if interactive:
add_interactive_args(parser)
... |
def _key_identifier_from_public_key(public_key: CertificatePublicKeyTypes) -> bytes:
if isinstance(public_key, RSAPublicKey):
data = public_key.public_bytes(serialization.Encoding.DER, serialization.PublicFormat.PKCS1)
elif isinstance(public_key, EllipticCurvePublicKey):
data = public_key.public... |
class EnhancedInvBlock(nn.Module):
def __init__(self, subnet_constructor, channel_num, channel_split_num, clamp=1.0):
super(EnhancedInvBlock, self).__init__()
self.split_len1 = channel_split_num
self.split_len2 = (channel_num - channel_split_num)
self.clamp = clamp
self.E = s... |
class ResNeXt3DBase(ClassyModel):
def __init__(self, input_key, input_planes, clip_crop_size, frames_per_clip, num_blocks, stem_name, stem_planes, stem_temporal_kernel, stem_spatial_kernel, stem_maxpool):
super(ResNeXt3DBase, self).__init__()
self._input_key = input_key
self.input_planes = i... |
def _range_indices(df: pd.DataFrame, right: pd.DataFrame, first: tuple, second: tuple):
(left_on, right_on, op) = first
left_c = df[left_on]
right_c = right[right_on]
(left_on, right_on, _) = second
any_nulls = df[left_on].isna()
if any_nulls.any():
left_c = left_c[(~ any_nulls)]
any... |
def remove_already_run_experiments(table, experiments):
res = []
with Database() as db:
for e in experiments:
if (len(db.read(table, ['test_loglik'], e)) == 0):
res.append(e)
s = 'originally {} experiments, but {} have already been run, so running {} experiments'
prin... |
def main(opt):
translator = build_translator(opt)
out_file = codecs.open(opt.output, 'w+', 'utf-8')
src_iter = make_text_iterator_from_file(opt.src)
if (opt.tgt is not None):
tgt_iter = make_text_iterator_from_file(opt.tgt)
else:
tgt_iter = None
translator.translate(src_data_iter... |
class FrameCapture(QObject):
finished = pyqtSignal()
def __init__(self):
super(FrameCapture, self).__init__()
self._percent = 0
self._page = QWebPage()
self._page.mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff)
self._page.mainFrame().setScrollBarPolicy(... |
.supported(only_if=(lambda backend: backend.hash_supported(hashes.SHAKE128(digest_size=16))), skip_message='Does not support SHAKE128')
class TestSHAKE128():
test_shake128 = generate_hash_test(load_hash_vectors, os.path.join('hashes', 'SHAKE'), ['SHAKE128LongMsg.rsp', 'SHAKE128ShortMsg.rsp'], hashes.SHAKE128(digest... |
class AggregationLayer(Block):
def __init__(self, **kwargs):
super(AggregationLayer, self).__init__(**kwargs)
self.alpha1 = nn.Parameter(data=torch.empty(1), requires_grad=True)
self.beta1 = nn.Parameter(data=torch.zeros(1), requires_grad=True)
init.uniform_(self.alpha1, 0, 0.2)
... |
def test_script(path, executable='python'):
import pybamm
b = pybamm.Timer()
print((('Test ' + path) + ' ... '), end='')
sys.stdout.flush()
env = dict(os.environ)
env['MPLBACKEND'] = 'Template'
cmd = [executable, path]
try:
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr... |
class TestMESolveDecay():
N = 10
a = qutip.destroy(N)
kappa = 0.2
tlist = np.linspace(0, 10, 201)
ada = (a.dag() * a)
(params=[pytest.param([ada, (lambda t, args: 1)], id='Hlist_func'), pytest.param([ada, '1'], id='Hlist_str'), pytest.param([ada, np.ones_like(tlist)], id='Hlist_array'), pytest.p... |
def main():
if ('CITYSCAPES_DATASET' in os.environ):
cityscapesPath = os.environ['CITYSCAPES_DATASET']
else:
cityscapesPath = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..')
searchFine = os.path.join(cityscapesPath, 'gtFine', '*', '*', '*_gt*_polygons.json')
searchC... |
def create_dummy_data(size):
user_ids = np.random.randint(1, 1000000, 10)
product_ids = np.random.randint(1, 1000000, 100)
def choice(*values):
return np.random.choice(values, size)
random_dates = [(datetime.date(2016, 1, 1) + datetime.timedelta(days=int(delta))) for delta in np.random.randint(1... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.