code stringlengths 281 23.7M |
|---|
_WRAPPERS.register_module('mmseg.DDPWrapper')
class DistributedDataParallelWrapper(nn.Module):
def __init__(self, module, device_ids, dim=0, broadcast_buffers=False, find_unused_parameters=False, **kwargs):
super().__init__()
assert (len(device_ids) == 1), f'Currently, DistributedDataParallelWrapper... |
def setup_environ_items(environ, headers):
for (key, value) in environ.items():
if isinstance(value, string_types):
environ[key] = wsgi_encoding_dance(value)
for (key, value) in headers.items():
key = ('HTTP_' + key.upper().replace('-', '_'))
if (key not in ('HTTP_CONTENT_TYP... |
class TAPETextValue(TestCase):
from mutagen.apev2 import APETextValue as TV
TV = TV
def setUp(self):
self.sample = ['foo', 'bar', 'baz']
self.value = mutagen.apev2.APEValue('\x00'.join(self.sample), mutagen.apev2.TEXT)
def test_parse(self):
self.assertRaises(APEBadItemError, self... |
class BNBlurBlock(nn.Module):
def __init__(self, in_filters, sfilter=(1, 1), pad_mode='constant', **kwargs):
super(PreactBlurBlock, self).__init__()
self.bn = layers.bn(in_filters)
self.relu = layers.relu()
self.blur = layers.blur(in_filters, sfilter=sfilter, pad_mode=pad_mode)
d... |
class __diag__(__config_flags):
_type_desc = 'diagnostic'
warn_multiple_tokens_in_named_alternation = False
warn_ungrouped_named_tokens_in_collection = False
warn_name_set_on_empty_Forward = False
warn_on_multiple_string_args_to_oneof = False
enable_debug_on_named_expressions = False
_all_na... |
class TrialShortNamer():
PREFIX = 'hp'
DEFAULTS = {}
NAMING_INFO = None
def set_defaults(cls, prefix, defaults):
cls.PREFIX = prefix
cls.DEFAULTS = defaults
cls.build_naming_info()
def shortname_for_word(info, word):
if (len(word) == 0):
return ''
... |
class Grey(DefaultTheme):
DEFAULTS = dict(legendgroup_postfix=' (greyed)', direction=dict(cause_color='black', effect_color='black'), purviews=dict(marker=dict(opacity=0.75, colorscale='greys')), cause_effect_links=dict(opacity=0.2, line=dict(color='grey')), mechanism_purview_links=dict(opacity=0.2, line=dict(color... |
class PluginRenameTestCase(TestCase):
fixtures = ['fixtures/styles.json', 'fixtures/auth.json', 'fixtures/simplemenu.json']
_settings(MEDIA_ROOT='api/tests')
def setUp(self):
self.client = Client()
self.url_upload = reverse('plugin_upload')
self.user = User.objects.create_user(userna... |
class TRandomAlbum(PluginTestCase):
WEIGHTS = {'rating': 0, 'added': 0, 'laststarted': 0, 'lastplayed': 0, 'length': 0, 'skipcount': 0, 'playcount': 0}
def setUp(self):
config.init()
init_fake_app()
app.player.paused = False
app.library.clear()
app.window.browser = AlbumL... |
class UnsupportedPasswordHashVersion(InvalidPassword, WalletFileException):
def __init__(self, version):
self.version = version
def __str__(self):
return '{unsupported}: {version}\n{instruction}'.format(unsupported=_('Unsupported password hash version'), version=self.version, instruction=f'''To ... |
def save_progress(object_to_save, placeholder_token, output_dir, name='learned_embeds.bin', method='inversion'):
logger.info('Saving embeddings')
base_path = os.path.join(output_dir, 'embeds')
os.makedirs(base_path, exist_ok=True)
save_path = os.path.join(base_path, name)
if (method == 'inversion'):... |
_tests('aes_gcm_test.json')
def test_aes_gcm(backend, wycheproof):
key = binascii.unhexlify(wycheproof.testcase['key'])
iv = binascii.unhexlify(wycheproof.testcase['iv'])
aad = binascii.unhexlify(wycheproof.testcase['aad'])
msg = binascii.unhexlify(wycheproof.testcase['msg'])
ct = binascii.unhexlify... |
class NonLinearElementMultiply(nn.Module):
def __init__(self, image_feat_dim, ques_emb_dim, **kwargs):
super(NonLinearElementMultiply, self).__init__()
self.fa_image = ReLUWithWeightNormFC(image_feat_dim, kwargs['hidden_dim'])
self.fa_txt = ReLUWithWeightNormFC(ques_emb_dim, kwargs['hidden_d... |
class GraphPartition(GraphOptimizationApplication):
def to_quadratic_program(self) -> QuadraticProgram:
mdl = Model(name='Graph partition')
n = self._graph.number_of_nodes()
x = {i: mdl.binary_var(name=f'x_{i}') for i in range(n)}
for (w, v) in self._graph.edges:
self._gr... |
class RepositoryLocalState():
def __init__(self, repository):
self.repository = repository
self.uploaded_project_ids = set()
def is_uploaded(self, package):
return (package.unique_id in self.uploaded_project_ids)
def set_uploaded(self, package):
self.uploaded_project_ids.add(... |
def test_lid_unit_params():
with Simulation(MODEL_LIDS_PATH) as sim:
sub_2_lid_units = LidGroups(sim)['2']
first_unit = sub_2_lid_units[0]
assert (first_unit.unit_area == approx(10000, rel=UT_PRECISION))
assert (first_unit.full_width == approx(20, rel=UT_PRECISION))
assert (f... |
def get_raw(path, fin, fout, cat='other', new=True, is_dev=True, form='conll', is_space=False):
fout = codecs.open(((path + '/') + fout), 'w', encoding='utf-8')
fout_dev = None
if (not is_dev):
fout_dev = codecs.open((path + '/raw_dev.txt'), 'w', encoding='utf-8')
cter = 0
if (form == 'conll... |
class TrainUnit(AppStateMixin, _OnExceptionMixin, Generic[TTrainData], ABC):
def __init__(self) -> None:
super().__init__()
self.train_progress = Progress()
def on_train_start(self, state: State) -> None:
pass
def on_train_epoch_start(self, state: State) -> None:
pass
def... |
class _SerializedRelationship():
def __init__(self, baseURI, rel_elm):
super(_SerializedRelationship, self).__init__()
self._baseURI = baseURI
self._rId = rel_elm.rId
self._reltype = rel_elm.reltype
self._target_mode = rel_elm.target_mode
self._target_ref = rel_elm.ta... |
def associated_cell_is_useful(a_i, a_j, type_c, pos_i, pos_j, cell_id, useful_cell_positions, useful_cell_ids, betas):
if ((a_i, a_j) in useful_cell_positions):
_c_id = useful_cell_ids[useful_cell_positions.index((a_i, a_j))]
else:
return False
associated_beta = betas[_c_id][type_c]
if (... |
def compare_two(P: Sequence[cirq.Qid], Q: Sequence[cirq.Qid], equal, less_than, greater_than) -> cirq.OP_TREE:
P = P[::(- 1)]
Q = Q[::(- 1)]
xor = cirq.NamedQubit('xor')
(yield cirq.CNOT(P[1], xor))
(yield cirq.CNOT(Q[1], xor))
(yield cirq.CSWAP(xor, *P))
(yield cirq.CSWAP(xor, *Q))
anc ... |
(os.environ.get('CIRCLECI'), 'Caffe2 tests crash on CircleCI.')
class TestCaffe2Export(unittest.TestCase):
def setUp(self):
setup_logger()
def _test_model(self, config_path, device='cpu'):
cfg = model_zoo.get_config(config_path)
cfg.MODEL.DEVICE = device
model = model_zoo.get(con... |
class TestUmap(unittest.TestCase):
def setUp(self):
(X, y) = fetch_openml('mnist_784', version=1, return_X_y=True)
X = normalize(X)
self.X = X
self.y = y
def tearDown(self):
pass
def test_numberDataPoints(self):
reducer = humap.UMAP(n_neighbors=15)
emb... |
(bdd.parsers.re('the (?P<what>primary selection|clipboard) should contain "(?P<content>.*)"'))
def clipboard_contains(quteproc, server, what, content):
expected = content.replace('(port)', str(server.port))
expected = expected.replace('\\n', '\n')
expected = expected.replace('(linesep)', os.linesep)
qut... |
class GPT4AllHandler(LLMHandler):
def __init__(self, settings, modelspath, llm):
self.key = 'local'
self.settings = settings
self.modelspath = modelspath
self.model = None
self.llm = llm
self.history = {}
self.prompts = []
if (not os.path.isdir(self.mo... |
def get_indexed_dataset_to_local(path):
local_index_path = PathManager.get_local_path(index_file_path(path))
local_data_path = PathManager.get_local_path(data_file_path(path))
assert (local_index_path.endswith('.idx') and local_data_path.endswith('.bin')), f'PathManager.get_local_path does not return files ... |
class Signal(_SignalObjectBase):
def __init__(self, s, t, country, Type, subtype='-1', countryRevision=None, id=None, name=None, dynamic=Dynamic.no, value=None, unit=None, zOffset=1.5, orientation=Orientation.positive, hOffset=0, pitch=0, roll=0, height=None, width=None):
super().__init__(s, t, id, Type, su... |
class OneAlbum(qltk.Notebook):
def __init__(self, songs):
super().__init__()
swin = SW()
swin.title = _('Information')
vbox = Gtk.VBox(spacing=12)
vbox.set_border_width(12)
swin.add_with_viewport(vbox)
songs = sorted(songs)
self._title(songs, vbox)
... |
def test_custom_theme_options_become_text():
my_theme = CustomTheme(bg='yellow', fg='blue', text_size=12, text_font='arial', text_align='left', outline='yes', line_wrap=0.5)
options_dict = my_theme
assert (options_dict.get('bg') == 'yellow')
assert (options_dict.get('fg') == 'blue')
assert (options_... |
def print_progress(iteration, total, prefix='', suffix='', decimals=1, bar_length=100):
str_format = (('{0:.' + str(decimals)) + 'f}')
percents = str_format.format((100 * (iteration / float(total))))
filled_length = int(round(((bar_length * iteration) / float(total))))
bar = (('' * filled_length) + ('-'... |
.parametrize('has_custom_path', [False, True])
def test_on_custom_path_button_exists(skip_qtbot, tmp_path, mocker, has_custom_path):
mock_prompt = mocker.patch('randovania.gui.lib.common_qt_lib.prompt_user_for_output_file', autospec=True)
if has_custom_path:
output_directory = tmp_path.joinpath('output_... |
def generate_format_ops(specifiers: list[ConversionSpecifier]) -> (list[FormatOp] | None):
format_ops = []
for spec in specifiers:
if ((spec.whole_seq == '%s') or (spec.whole_seq == '{:{}}')):
format_op = FormatOp.STR
elif (spec.whole_seq == '%d'):
format_op = FormatOp.IN... |
class PointCompoundSourceDelegate(SourceDelegate):
__represents__ = 'PointCompoundSource'
display_backend = 'Compound Model'
display_name = 'PointCompoundSource'
parameters = ['easting', 'northing', 'depth', 'dVx', 'dVy', 'dVz', 'rotation_x', 'rotation_y', 'rotation_z', 'nu']
ro_parameters = ['volum... |
def parse_arch(arch_str):
if isinstance(arch_str, str):
match = re.match('^(\\d+)bit$', arch_str)
if match:
return int(next(iter(match.groups())))
error = f'invalid format {arch_str}'
else:
error = f'arch is not string: {arch_str!r}'
raise ValueError(error) |
class TDSF(TestCase):
silence_1 = os.path.join(DATA_DIR, '2822400-1ch-0s-silence.dsf')
silence_2 = os.path.join(DATA_DIR, '5644800-2ch-s01-silence.dsf')
has_tags = os.path.join(DATA_DIR, 'with-id3.dsf')
no_tags = os.path.join(DATA_DIR, 'without-id3.dsf')
def setUp(self):
self.filename_1 = ge... |
def _preset_with_locked_pb(preset: Preset, locked: bool):
pickup_database = default_database.pickup_database_for_game(RandovaniaGame.METROID_DREAD)
preset = dataclasses.replace(preset, configuration=dataclasses.replace(preset.configuration, ammo_configuration=preset.configuration.ammo_pickup_configuration.repla... |
def main():
args = parse_args()
send_example_telemetry('run_image_classification_no_trainer', args)
accelerator_log_kwargs = {}
if args.with_tracking:
accelerator_log_kwargs['log_with'] = args.report_to
accelerator_log_kwargs['logging_dir'] = args.output_dir
accelerator = Accelerator... |
class TestLanguageModel(unittest.TestCase):
def testLanguageModelTest(self):
(vocab_size, data) = getTestingData()
opts = LanguageModelOptions()
opts.no_prune_ngram_order = kaldi_math.rand_int(1, 3)
opts.ngram_order = (opts.no_prune_ngram_order + kaldi_math.rand_int(0, 3))
op... |
class InceptionTest(tf.test.TestCase):
def testBuildLogits(self):
batch_size = 5
(height, width) = (299, 299)
num_classes = 1000
inputs = tf.random_uniform((batch_size, height, width, 3))
(logits, end_points) = inception.inception_v4(inputs, num_classes)
auxlogits = e... |
class DescribeZipPkgWriter():
def it_is_used_by_PhysPkgWriter_unconditionally(self, tmp_docx_path):
phys_writer = PhysPkgWriter(tmp_docx_path)
assert isinstance(phys_writer, _ZipPkgWriter)
def it_opens_pkg_file_zip_on_construction(self, ZipFile_):
pkg_file = Mock(name='pkg_file')
... |
def _option(info, title, predicate):
model = completionmodel.CompletionModel(column_widths=(20, 70, 10))
options = ((opt.name, opt.description, info.config.get_str(opt.name)) for opt in configdata.DATA.values() if predicate(opt))
model.add_category(listcategory.ListCategory(title, options))
return model |
.parametrize('metric', ['euclidean', 'minkowski', 'cityblock', 'chebyshev', 'haversine'])
def test_metric_k(metric):
data = (grocs.to_crs(4326) if (metric == 'haversine') else grocs)
if ((not HAS_SKLEARN) and (metric in ['chebyshev', 'haversine'])):
pytest.skip('metric not supported by scipy')
(head... |
def current_migration():
if (os.getenv('ENSURE_NO_MIGRATION', '').lower() == 'true'):
raise Exception('Cannot call migration when ENSURE_NO_MIGRATION is true')
if (not app.config.get('SETUP_COMPLETE', False)):
return 'head'
elif (ActiveDataMigration is not None):
return ActiveDataMig... |
def try_parse(code, args, args_ctypes, compile_opt):
if (not compile_opt['try_parse']):
variables = [(('self.' + name), name, 'object') for name in args if (name in code)]
(code, variables) = use_hinted_type(variables, code, args_ctypes)
return (code, variables, [], True)
(ncode, variabl... |
class DropboxOAuth2V2(BaseOAuth2):
name = 'dropbox-oauth2'
ID_KEY = 'uid'
AUTHORIZATION_URL = '
ACCESS_TOKEN_URL = '
ACCESS_TOKEN_METHOD = 'POST'
REDIRECT_STATE = False
def get_user_details(self, response):
name = response.get('name')
return {'username': str(response.get('acc... |
def test_combine_molecules_offxml_plugin_deepdiff(tmpdir, coumarin, rfree_data):
coumarin_copy = coumarin.copy(deep=True)
MBISCharges.apply_symmetrisation(coumarin_copy)
with tmpdir.as_cwd():
_combine_molecules_offxml(molecules=[coumarin_copy], parameters=elements, rfree_data=rfree_data, filename='o... |
class GANLoss(nn.Module):
def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0, tensor=torch.FloatTensor, opt=None):
super(GANLoss, self).__init__()
self.real_label = target_real_label
self.fake_label = target_fake_label
self.real_label_tensor = None
self... |
class BoosterSideEffects(ContextMenuSingle):
def __init__(self):
self.mainFrame = gui.mainFrame.MainFrame.getInstance()
def display(self, callingWindow, srcContext, mainItem):
if ((self.mainFrame.getActiveFit() is None) or (srcContext not in 'boosterItem')):
return False
if (... |
def make_stage(block_class, num_blocks, first_stride, *, in_channels, out_channels, **kwargs):
assert ('stride' not in kwargs), 'Stride of blocks in make_stage cannot be changed.'
blocks = []
for i in range(num_blocks):
blocks.append(block_class(in_channels=in_channels, out_channels=out_channels, st... |
def weird_physchem() -> GoalDirectedBenchmark:
min_bertz = RdkitScoringFunction(descriptor=bertz, score_modifier=MaxGaussianModifier(mu=1500, sigma=200))
mol_under_400 = RdkitScoringFunction(descriptor=mol_weight, score_modifier=MinGaussianModifier(mu=400, sigma=40))
aroma = RdkitScoringFunction(descriptor=... |
def get_D(xp: list[int], Ann):
S = sum(xp)
if (S == 0):
return 0
n_coins = len(xp)
d_prev = 0.0
d = float(S)
for i in range(255):
d_p = d
for x in xp:
d_p = ((d_p * d) / (x * n_coins))
d_prev = d
d = ((((Ann * S) + (d_p * n_coins)) * d) / (((An... |
class H2StreamStateMachine():
def __init__(self, stream_id):
self.state = StreamState.IDLE
self.stream_id = stream_id
self.client = None
self.headers_sent = None
self.trailers_sent = None
self.headers_received = None
self.trailers_received = None
self.... |
class HSTPIPIMR(IntEnum):
RXINE = (1 << 0)
TXOUTE = (1 << 1)
TXSTPE = (1 << 2)
UNDERFIE = (1 << 2)
PERRE = (1 << 3)
NAKEDE = (1 << 4)
OVERFIE = (1 << 5)
RXSTALLDE = (1 << 6)
CRCERRE = (1 << 6)
SHORTPACKETIE = (1 << 7)
NBUSYBKE = (1 << 12)
FIFOCON = (1 << 14)
PDISHDMA ... |
def unravel(list_):
result = [list_]
for (i, x) in enumerate(list_):
if (len(list(x[1])) > 1):
members = list(x[1])
temp = copy.deepcopy(result)
for each_list in result:
each_list[i][1] = members[0]
for n in range(1, len(members)):
... |
def filter_acceptable_routes(route_states: List[RouteState], blacklisted_channel_ids: List[ChannelID], addresses_to_channel: Dict[(Tuple[(TokenNetworkAddress, Address)], NettingChannelState)], token_network_address: TokenNetworkAddress, our_address: Address) -> List[RouteState]:
acceptable_routes = []
for route... |
class CompositeEncoder(FairseqEncoder):
def __init__(self, encoders):
super().__init__(next(iter(encoders.values())).dictionary)
self.encoders = encoders
for key in self.encoders:
self.add_module(key, self.encoders[key])
def forward(self, src_tokens, src_lengths):
enc... |
def main():
if (len(sys.argv) < 3):
sys.exit('Needs args: hook_name, control_dir')
hook_name = sys.argv[1]
control_dir = sys.argv[2]
if (hook_name not in HOOK_NAMES):
sys.exit(('Unknown hook: %s' % hook_name))
hook = globals()[hook_name]
hook_input = read_json(pjoin(control_dir, ... |
def test_class_weights_rescale_C():
from sklearn.svm import LinearSVC
(X, Y) = make_blobs(n_samples=210, centers=3, random_state=1, cluster_std=3, shuffle=False)
X = np.hstack([X, np.ones((X.shape[0], 1))])
weights = (1.0 / np.bincount(Y))
weights *= (len(weights) / np.sum(weights))
pbl_class_we... |
class SendEmail(object):
local_dir = path.dirname(__file__)
with open(os.path.join(local_dir, 'mailbox.txt'), 'r') as f:
mail_setting = f.readlines()
from_addr = mail_setting[0].strip()
password = mail_setting[1].strip()
smtp_server = mail_setting[2].strip()
def __init__(self, text, send... |
def read_pep621_metadata(proj, path) -> LoadedConfig:
lc = LoadedConfig()
md_dict = lc.metadata
if ('name' not in proj):
raise ConfigError('name must be specified in [project] table')
_check_type(proj, 'name', str)
md_dict['name'] = proj['name']
lc.module = md_dict['name'].replace('-', '... |
def build_filter_repr_dict(filter_list: FilterList, list_type: ListType, filter_type: type[Filter], settings_overrides: dict, extra_fields_overrides: dict) -> dict:
default_setting_values = {}
for settings_group in filter_list[list_type].defaults:
for (_, setting) in settings_group.items():
... |
.parametrize('screenshot_manager', [{}, {'icon_size': 30}], indirect=True)
.usefixtures('dbus')
def ss_statusnotifier(screenshot_manager):
win = screenshot_manager.test_window('TestSNI', export_sni=True)
wait_for_icon(screenshot_manager.c.widget['statusnotifier'], hidden=False)
screenshot_manager.take_scree... |
.skipif((not HAVE_DEPS_FOR_RESOURCE_ESTIMATES), reason='pyscf and/or jax not installed.')
def test_costing_helper():
nRe = 108
lamRe = 294.8
dE = 0.001
LRe = 360
LxiRe = 13031
chi = 10
betaRe = 16
nLi = 152
lamLi = 1171.2
LLi = 394
LxiLi = 20115
betaLi = 20
res = comp... |
def obtain_discrm_data(disc_enc_type, molecules_reference, smiles_mutated, selfies_mutated, max_molecules_len, num_processors, generation_index):
if (disc_enc_type == 'smiles'):
random_dataset_selection = np.random.choice(list(molecules_reference.keys()), size=len(smiles_mutated)).tolist()
dataset_s... |
class GaussianPolicy(NNPolicy, Serializable):
def __init__(self, env_spec, hidden_layer_sizes=(100, 100), reg=0.001, squash=True, reparameterize=True, todropoutpi=False, dropoutpi=1.0, batchnormpi=False, name='gaussian_policy'):
Serializable.quick_init(self, locals())
self._hidden_layers = hidden_la... |
def makeUpdateMatrixTensoredSv(updateMatrix, qnnArch, l, m):
numInputQubits = qnnArch[(l - 1)]
numOutputQubits = qnnArch[l]
if ((numOutputQubits - 1) != 0):
updateMatrix = qt.tensor(updateMatrix, tensoredId((numOutputQubits - 1)))
return swappedOp(updateMatrix, numInputQubits, (numInputQubits + ... |
class File(object):
def __init__(self, f, type_label='TEST', version='0000', record_formats={}):
assert (len(type_label) == 4)
assert (len(version) == 4)
self._file_type_label = type_label
self._file_version = version
self._record_formats = record_formats
self._curren... |
class F39_NetworkData(F27_NetworkData):
removedKeywords = F27_NetworkData.removedKeywords
removedAttrs = F27_NetworkData.removedAttrs
def __init__(self, *args, **kwargs):
F27_NetworkData.__init__(self, *args, **kwargs)
self.ipv4_dns_search = kwargs.get('ipv4_dns_search', None)
self.i... |
.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION)
class Glue(datasets.Metric):
def _info(self):
if (self.config_name not in ['sst2', 'mnli', 'mnli_mismatched', 'mnli_matched', 'cola', 'stsb', 'mrpc', 'qqp', 'qnli', 'rte', 'wnli', 'hans', 'ag', 'amazon', 'chemprot', 'citation_intent', 'hype... |
class TestSetAttr():
def test_change(self):
def hook(*a, **kw):
return 'hooked!'
class Hooked():
x = attr.ib(on_setattr=hook)
y = attr.ib()
h = Hooked('x', 'y')
assert ('x' == h.x)
assert ('y' == h.y)
h.x = 'xxx'
h.y = 'yyy'... |
class RequestPresetsView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
.button(label='Attach presets', style=discord.ButtonStyle.secondary, custom_id='attach_presets_of_permalink')
async def button_callback(self, button: Button, interaction: discord.Interaction):
try:
... |
def ExtendRule(Valid, Curr, order, MaxOrder, Trajectory, MinSupport):
if (order >= MaxOrder):
AddToRules(Valid)
else:
Distr = Distribution[Valid]
if (KLD(MaxDivergence(Distribution[Curr]), Distr) < KLDThreshold((order + 1), Curr)):
AddToRules(Valid)
else:
... |
class Migration(migrations.Migration):
dependencies = [('sponsors', '0076_auto__1550')]
operations = [migrations.CreateModel(name='SponsorshipCurrentYear', fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('year', models.PositiveIntegerField(validators=[... |
class TestUUIDField(TestCase):
def setUp(self):
self.field = fields.UUIDField()
def test_serialize(self):
arbitrary_uuid = uuid.uuid4()
actual_result = self.field.serialize(arbitrary_uuid)
expected_result = str(arbitrary_uuid)
self.assertEqual(actual_result, expected_resu... |
class AvgMeterHolder():
def __init__(self):
self.time_to_get_batch = AverageMeter()
self.time_to_forward = AverageMeter()
self.time_to_step = AverageMeter()
def reset(self):
for elem in self.__dict__.values():
if isinstance(elem, AverageMeter):
elem.re... |
def test_aggregated_storage_scenarios(three_storage_model):
from pywr.core import Scenario
from pywr.parameters import ConstantScenarioParameter
m = three_storage_model
sc = Scenario(m, 'A', size=5)
agg_stg = m.nodes['Total Storage']
stgs = [m.nodes['Storage {}'.format(num)] for num in range(3)]... |
def get_linear_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, last_epoch=(- 1)):
def lr_lambda(current_step: int):
if (current_step < num_warmup_steps):
return (float(current_step) / float(max(1, num_warmup_steps)))
return max(0.0, (float((num_training_steps - curr... |
def format_time(time):
if (time < 0):
time = abs(time)
prefix = '-'
else:
prefix = ''
if (time >= 3600):
return ('%s%d:%02d:%02d' % (prefix, (time // 3600), ((time % 3600) // 60), (time % 60)))
else:
return ('%s%d:%02d' % (prefix, (time // 60), (time % 60))) |
def do_train(cfg, model, train_loader, val_loader, optimizer, scheduler, loss_fn, num_query):
log_period = cfg.SOLVER.LOG_PERIOD
checkpoint_period = cfg.SOLVER.CHECKPOINT_PERIOD
eval_period = cfg.SOLVER.EVAL_PERIOD
output_dir = cfg.OUTPUT_DIR
device = cfg.MODEL.DEVICE
epochs = cfg.SOLVER.MAX_EPO... |
def test_cached_inputoutput():
(Z, nblock, itype) = slicot_example()
m = len(nblock)
mr = np.count_nonzero((1 == itype))
(mu0, d0, g0, x0) = ab13md(Z, nblock, itype)
assert (((m + mr) - 1) == len(x0))
(mu1, d1, g1, x1) = ab13md(Z, nblock, itype, x0)
assert_allclose(mu1, mu0)
with pytest.... |
def test_asyncio_mark_on_sync_function_emits_warning(pytester: Pytester):
pytester.makepyfile(dedent(' import pytest\n\n .asyncio\n def test_a():\n pass\n '))
result = pytester.runpytest('--asyncio-mode=strict', '-W default')
result.assert_outcomes(... |
class PikeLexer(CppLexer):
name = 'Pike'
aliases = ['pike']
filenames = ['*.pike', '*.pmod']
mimetypes = ['text/x-pike']
version_added = '2.0'
tokens = {'statements': [(words(('catch', 'new', 'private', 'protected', 'public', 'gauge', 'throw', 'throws', 'class', 'interface', 'implement', 'abstra... |
class NativeScalerWithGradNormCount():
state_dict_key = 'amp_scaler'
def __init__(self):
self._scaler = torch.cuda.amp.GradScaler()
def __call__(self, loss, optimizer, clip_grad=None, parameters=None, create_graph=False, update_grad=True):
self._scaler.scale(loss).backward(create_graph=creat... |
class ApplicationSettingsManager(GetWithoutIdMixin, UpdateMixin, RESTManager):
_path = '/application/settings'
_obj_cls = ApplicationSettings
_update_attrs = RequiredOptional(optional=('id', 'default_projects_limit', 'signup_enabled', 'password_authentication_enabled_for_web', 'gravatar_enabled', 'sign_in_t... |
def render(raw, stream=None):
if (stream is None):
stream = io.StringIO()
settings = SETTINGS.copy()
settings['warning_stream'] = stream
writer = Writer()
writer.translator_class = ReadMeHTMLTranslator
try:
parts = publish_parts(raw, writer=writer, settings_overrides=settings)
... |
def get_trainer(cfg: DictConfig) -> Trainer:
logger = get_logger(cfg)
checkpoint_callback = get_saver(cfg)
args = dict(cfg[__key__])
args = {str(k).lower(): v for (k, v) in args.items()}
args['logger'] = logger
args['callbacks'] = [checkpoint_callback]
return Trainer(**args) |
def compute_mAP(index, good_index, junk_index):
ap = 0
cmc = torch.IntTensor(len(index)).zero_()
if (good_index.size == 0):
cmc[0] = (- 1)
return (ap, cmc)
mask = np.in1d(index, junk_index, invert=True)
index = index[mask]
ngood = len(good_index)
mask = np.in1d(index, good_in... |
class KITTIDepthDataset(KITTIDataset):
def __init__(self, *args, **kwargs):
super(KITTIDepthDataset, self).__init__(*args, **kwargs)
def get_image_path(self, folder, frame_index, side):
f_str = '{:010d}{}'.format(frame_index, self.img_ext)
image_path = os.path.join(self.data_path, folder... |
class TestExecution():
pytestmark = skiponwin32
def test_sysfind_no_permisson_ignored(self, monkeypatch, tmpdir):
noperm = tmpdir.ensure('noperm', dir=True)
monkeypatch.setenv('PATH', str(noperm), prepend=':')
noperm.chmod(0)
try:
assert (local.sysfind('jaksdkasldqwe'... |
class QcQuantizeOp():
def __init__(self, quant_info: libquant_info.QcQuantizeInfo, quant_scheme: QuantScheme=QuantScheme.post_training_tf_enhanced, rounding_mode: str='nearest', encodings: Union[(libpymo.TfEncoding, None)]=None, op_mode: Union[(OpMode, None)]=None, bitwidth: int=8, use_symmetric_encodings: bool=Fal... |
def differentiable_graph2smiles_v0(origin_smiles, differentiable_graph, leaf_extend_idx_pair, leaf_nonleaf_lst, max_num_offspring=100, topk=3):
new_smiles_set = set()
origin_mol = Chem.rdchem.RWMol(Chem.MolFromSmiles(origin_smiles))
(origin_idx_lst, origin_node_mat, origin_substructure_lst, origin_atomidx_2... |
class ProxiesOnHost(Proxies):
def mem_usage_add(self, proxy: ProxyObject) -> None:
self._mem_usage += sizeof(proxy)
def mem_usage_remove(self, proxy: ProxyObject) -> None:
self._mem_usage -= sizeof(proxy)
def buffer_info(self) -> List[Tuple[(float, int, List[ProxyObject])]]:
ret = []... |
class Mesh(object):
def __init__(self, vertices, faces, textures=None, texture_size=4):
self.vertices = vertices
self.faces = faces
self.num_vertices = self.vertices.shape[0]
self.num_faces = self.faces.shape[0]
if (textures is None):
shape = (self.num_faces, text... |
class ItemStats(ContextMenuSingle):
def __init__(self):
self.mainFrame = gui.mainFrame.MainFrame.getInstance()
def display(self, callingWindow, srcContext, mainItem):
if (srcContext not in ('marketItemGroup', 'marketItemMisc', 'fittingModule', 'fittingCharge', 'fittingShip', 'baseShip', 'cargoIt... |
class HalloweenFacts(commands.Cog):
def random_fact(self) -> tuple[(int, str)]:
return random.choice(FACTS)
(name='spookyfact', aliases=('halloweenfact',), brief='Get the most recent Halloween fact')
async def get_random_fact(self, ctx: commands.Context) -> None:
(index, fact) = self.random_... |
def parameters():
params = TrackerParams()
params.debug = 0
params.visualization = False
params.use_gpu = True
deep_params = TrackerParams()
params.max_image_sample_size = ((18 * 16) ** 2)
params.min_image_sample_size = ((18 * 16) ** 2)
params.search_area_scale = 5
params.feature_siz... |
class Res15DataProcessor(DataProcessor):
def __init__(self, tokenizer, max_length):
self.tokenizer = tokenizer
self.max_length = max_length
def get_train_examples(self, data_dir):
return self._create_examples(self._read_txt(os.path.join(data_dir, 'train_triplets.txt')), 'train')
def ... |
class J0(UnaryScalarOp):
nfunc_spec = ('scipy.special.j0', 1, 1)
def st_impl(x):
return scipy.special.j0(x)
def impl(self, x):
return self.st_impl(x)
def grad(self, inp, grads):
(x,) = inp
(gz,) = grads
return [((gz * (- 1)) * j1(x))]
def c_code(self, node, na... |
class File(PymiereBaseObject):
def __init__(self, pymiere_id=None):
super(File, self).__init__(pymiere_id)
' If true, the object refers to a file system alias or shortcut. '
def alias(self):
return self._eval_on_this_object('alias')
def alias(self, alias):
raise AttributeError("A... |
class IntegersRV(RandomVariable):
name = 'integers'
ndim_supp = 0
ndims_params = [0, 0]
dtype = 'int64'
_print_name = ('integers', '\\operatorname{integers}')
def __call__(self, low, high=None, size=None, **kwargs):
if (high is None):
(low, high) = (0, low)
return sup... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.