code stringlengths 281 23.7M |
|---|
class Installation(pg_api.Installation):
version = None
version_info = None
type = None
configure_options = None
info = None
pg_executables = ('pg_config', 'psql', 'initdb', 'pg_resetxlog', 'pg_controldata', 'clusterdb', 'pg_ctl', 'pg_dump', 'pg_dumpall', 'postgres', 'postmaster', 'reindexdb', '... |
class Class_Aes():
def buqi_key(self, aes_type, aes_key, aes_zifuji):
if (aes_type == 'AES-128'):
length = 16
elif (aes_type == 'AES-192'):
length = 24
elif (aes_type == 'AES-256'):
length = 32
else:
length = 16
if (len(aes_key)... |
def register(manager: AstroidManager) -> None:
manager.register_transform(nodes.ClassDef, dataclass_transform, is_decorated_with_dataclass)
manager.register_transform(nodes.Call, inference_tip(infer_dataclass_field_call, raise_on_overwrite=True), _looks_like_dataclass_field_call)
manager.register_transform(... |
class Migration(migrations.Migration):
initial = True
dependencies = [('conferences', '0031_fix_keynote_details_save')]
operations = [migrations.CreateModel(name='ReviewSession', fields=[('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', model_u... |
def _read_mat_binary(fd):
header = fd.read(3).decode()
if header.startswith('CM'):
return _read_compressed_mat(fd, header)
elif header.startswith('SM'):
return _read_sparse_mat(fd, header)
elif (header == 'FM '):
sample_size = 4
elif (header == 'DM '):
sample_size = 8... |
class TagFormSet(forms.BaseInlineFormSet):
def save(self, commit=True):
def get_handler(finished_object):
related = getattr(finished_object, self.related_field)
try:
tagtype = finished_object.tag_type
except AttributeError:
tagtype = finish... |
class PVTNetwork_4(nn.Module):
def __init__(self, channel=32, n_classes=1, deep_supervision=True):
super().__init__()
self.deep_supervision = deep_supervision
print(f'use SpatialAtt + ChannelAtt and My attention layer'.center(80, '='))
self.backbone = pvt_v2_b2()
path = '/afs... |
def step(base, data, hh):
def flt():
for l in data.split('\n'):
if (l in hh):
pp = os.path.join(base, hh[l])
(yield (('\n\n' + load_file(pp)) + '\n\n'))
os.unlink(pp)
else:
(yield l)
return '\n'.join(flt()) |
def evaluate(config, workdir, eval_folder='eval'):
eval_dir = os.path.join(workdir, eval_folder, f'host_{jax.process_index()}')
tf.io.gfile.makedirs(eval_dir)
rng = jax.random.PRNGKey((config.seed + 1))
rng = jax.random.fold_in(rng, jax.process_index())
test_data_dir = {'ct2d_320': 'LIDC_320.npz', '... |
def has_checkpoint(checkpoint_folder: str, skip_final: bool=False):
checkpointed_files = PathManager.ls(checkpoint_folder)
checkpoint_exists = False
for f in checkpointed_files:
if (f.endswith('.torch') and (('model_final' not in f) or (not skip_final))):
checkpoint_exists = True
... |
(netloc='fakegitlab', path='/api/v4/projects/4/hooks/1$', method='DELETE')
def delete_hook_handler(_, request):
if (not (request.headers.get('Authorization') == 'Bearer foobar')):
return {'status_code': 401}
return {'status_code': 200, 'headers': {'Content-Type': 'application/json'}, 'content': json.dum... |
class TestPower():
def test_numpy_compare(self):
rng = np.random.default_rng(utt.fetch_seed())
A = matrix('A', dtype=config.floatX)
Q = power(A, 3)
fn = function([A], [Q])
a = rng.random((4, 4)).astype(config.floatX)
n_p = np.power(a, 3)
t_p = fn(a)
as... |
class CssGenshiLexer(DelegatingLexer):
name = 'CSS+Genshi Text'
aliases = ['css+genshitext', 'css+genshi']
version_added = ''
alias_filenames = ['*.css']
mimetypes = ['text/css+genshi']
url = '
def __init__(self, **options):
super().__init__(CssLexer, GenshiTextLexer, **options)
... |
def main(_):
if (FLAGS.input == ''):
print('You must specify --input value (--output is optional)')
return
if (not os.path.exists((FLAGS.input + '.meta'))):
print(('Input %s.meta does not exist' % FLAGS.input))
return
meta = tf.train.import_meta_graph((FLAGS.input + '.meta'),... |
def init_cli(cli_obj, reset=False):
if reset:
global MANAGE_DICT
MANAGE_DICT = {}
sys.path.insert(0, '.')
load_manage_dict_from_sys_args()
cli.help = MANAGE_DICT.get('help_text', '{project_name} Interactive shell!').format(**MANAGE_DICT)
load_groups(cli, MANAGE_DICT)
load_command... |
def execute_and_export_notebooks(output_nbs: bool, output_html: bool, only_out_of_date: bool=True):
reporoot = get_git_root()
sourceroot = (reporoot / 'qualtran')
nb_rel_paths = get_nb_rel_paths(sourceroot=sourceroot)
bad_nbs = []
for nb_rel_path in nb_rel_paths:
paths = _NBInOutPaths.from_n... |
class ProcessView(gui.Svg, FBD_model.Process):
selected_input = None
selected_output = None
def __init__(self, *args, **kwargs):
gui.Svg.__init__(self, *args, **kwargs)
FBD_model.Process.__init__(self)
self.css_border_color = 'black'
self.css_border_width = '1'
self.c... |
.parametrize('minimum_unit, seconds, expected', [('seconds', ONE_MICROSECOND, 'a moment'), ('seconds', FOUR_MICROSECONDS, 'a moment'), ('seconds', ONE_MILLISECOND, 'a moment'), ('seconds', FOUR_MILLISECONDS, 'a moment'), ('seconds', MICROSECONDS_101_943, 'a moment'), ('seconds', MILLISECONDS_1_337, 'a second'), ('secon... |
_grad()
def evaluate_similarity(model, *, lowercase, batch_size=256, datasets=tuple(SIMILARITY_BENCHMARKS.keys()), **kwargs):
metrics = {}
for dataset_name in datasets:
sim_data = SimilarityDataset(dataset_name, lowercase=lowercase)
word_occurences = Counter((word for word in sim_data.word_pairs... |
class DescriptionWrapper(Dataset):
def __init__(self, dataset, description):
self.dataset = dataset
self.description = description
def __getitem__(self, index):
item = self.dataset[index]
item['description'] = self.description
return item
def __len__(self):
re... |
class Encoder(nn.Module):
def __init__(self, D_ch=64, D_wide=True, resolution=128, D_kernel_size=3, D_attn='64', n_classes=1000, num_D_SVs=1, num_D_SV_itrs=1, D_activation=nn.ReLU(inplace=False), D_lr=0.0002, D_B1=0.0, D_B2=0.999, adam_eps=1e-08, SN_eps=1e-12, output_dim=1, D_mixed_precision=False, D_fp16=False, D_... |
class CompileCatalog(CommandMixin):
description = 'compile message catalogs to binary MO files'
user_options = [('domain=', 'D', "domains of PO files (space separated list, default 'messages')"), ('directory=', 'd', 'path to base directory containing the catalogs'), ('input-file=', 'i', 'name of the input file'... |
def test_update_iou():
privkey = bytes(([2] * 32))
sender = Address(privatekey_to_address(privkey))
receiver = Address(bytes(([1] * 20)))
one_to_n_address = Address(bytes(([2] * 20)))
iou = IOU(sender=sender, receiver=receiver, amount=10, expiration_block=1000, chain_id=4, one_to_n_address=one_to_n_... |
def _unquote(name):
assert isinstance(name, bytes), ('Input %s to function must be bytes not %s.' % (name, type(name)))
def unquoted_char(match):
if (not (len(match.group()) == 4)):
return match.group
try:
return bytes([int(match.group()[1:])])
except Exception:
... |
_module()
class ResNet3dSlowFast(nn.Module):
def __init__(self, pretrained, resample_rate=8, speed_ratio=8, channel_ratio=8, slow_pathway=dict(type='resnet3d', depth=50, pretrained=None, lateral=True, conv1_kernel=(1, 7, 7), dilations=(1, 1, 1, 1), conv1_stride_t=1, pool1_stride_t=1, inflate=(0, 0, 1, 1)), fast_pat... |
def test_download_one_point():
with expected_protocol(LeCroyT3DSO1204, [(b'CHDR OFF', None), (b'WFSU SP,1', None), (b'WFSU NP,1', None), (b'WFSU FP,0', None), (b'SANU? C1', b'7.00E+06'), (b'WFSU NP,1', None), (b'WFSU FP,0', None), (b'C1:WF? DAT2', ((b'DAT2,#' + b'\x01') + b'\n\n')), (b'WFSU?', b'SP,1,NP,2,FP,0'), (... |
def build_dataset(is_train, args):
transform = build_transform(is_train, args)
if (args.data_set == 'CIFAR'):
dataset = datasets.CIFAR100(args.data_path, train=is_train, transform=transform)
nb_classes = 100
elif (args.data_set == 'IMNET'):
if (not args.use_mcloader):
roo... |
class BadMsgNotification(Exception):
descriptions = {16: 'The msg_id is too low, the client time has to be synchronized.', 17: 'The msg_id is too high, the client time has to be synchronized.', 18: 'Incorrect two lower order of the msg_id bits, the server expects the client message msg_id to be divisible by 4.', 19... |
.parametrize('mu, beta, size', [(np.array(0, dtype=config.floatX), np.array(1, dtype=config.floatX), None), (np.array(0, dtype=config.floatX), np.array(1, dtype=config.floatX), []), (np.full((1, 2), 0, dtype=config.floatX), np.array(1, dtype=config.floatX), None)])
def test_gumbel_samples(mu, beta, size):
compare_s... |
def convert_execution_result_to_train_instance(row):
success = row['execution_result']['success']
problem = row['prompt']
generated_solution = row['generation']
if (not success):
if ('traceback' not in row['execution_result']):
language_feedback = row['execution_result']['reason']
... |
class DataLoader_Target(object):
def __init__(self, batch_size, target_file, user_feat_dict_file, item_feat_dict_file, context_dict_file):
self.batch_size = batch_size
self.target_file = open(target_file, 'r')
if (user_feat_dict_file != None):
with open(user_feat_dict_file, 'rb')... |
('I load a third-party iframe')
def load_iframe(quteproc, server, ssl_server):
quteproc.set_setting('content.tls.certificate_errors', 'load-insecurely')
quteproc.open_path(f' port=server.port)
msg = quteproc.wait_for(message='Certificate error: *')
msg.expected = True
msg = quteproc.wait_for(message... |
class TestOrbitsGappyLongDataXarray(TestOrbitsGappyData):
def setup_method(self):
self.testInst = pysat.Instrument('pysat', 'testing_xarray', clean_level='clean', orbit_info={'index': 'longitude', 'kind': 'longitude'}, use_header=True)
self.stime = pysat.instruments.pysat_testing._test_dates['']['']... |
def parse3(f):
state = [None, None, []]
for (block, content) in parse2(f):
if ((block == b'050') and state[0] and state[1]):
(yield state)
state = [None, None, []]
if (block == b'050'):
state[0] = content
elif (block == b'052'):
state[1] = ... |
def expand_named_state_definition(source, loc, tokens):
indent = (' ' * (pp.col(loc, source) - 1))
statedef = []
states = set()
transitions = set()
baseStateClass = tokens.name
fromTo = {}
for tn in tokens.transitions:
states.add(tn.from_state)
states.add(tn.to_state)
... |
def get_parser():
parser = argparse.ArgumentParser(epilog="Run 'electrum help <command>' to see the help for a command")
add_global_options(parser)
add_wallet_option(parser)
subparsers = parser.add_subparsers(dest='cmd', metavar='<command>')
parser_gui = subparsers.add_parser('gui', description="Run... |
def _extract_tolerances(data_frame: DataFrame, methods: List[str]) -> List[float]:
tolerance_set = set(data_frame[SpottingEvaluation.TOLERANCE])
for method in methods:
method_tolerance_set = set(data_frame[(data_frame[METHOD] == method)][SpottingEvaluation.TOLERANCE])
tolerance_set = tolerance_s... |
def get_prefix_from_len(sentence, bpe_symbol, prefix_len):
bpe_count = sum([(bpe_symbol.strip(' ') in t) for t in sentence[:prefix_len]])
if (bpe_count == 0):
return sentence[:prefix_len]
else:
return (sentence[:prefix_len] + get_prefix_from_len(sentence[prefix_len:], bpe_symbol, bpe_count)) |
def crack(passwd):
ql = Qiling(['../../examples/rootfs/mcu/stm32f407/backdoorlock.hex'], archtype=QL_ARCH.CORTEX_M, ostype=QL_OS.MCU, env=stm32f407, verbose=QL_VERBOSE.DISABLED)
ql.hw.create('spi2')
ql.hw.create('gpioe')
ql.hw.create('gpiof')
ql.hw.create('usart1')
ql.hw.create('rcc')
ql.hw.... |
class ClientManager(Observer):
def __init__(self, args, comm=None, rank=0, size=0, backend='MPI'):
if (args.mode == 'distributed'):
from mpi4py import MPI
self.args = args
self.size = size
self.rank = rank
self.backend = backend
if (backend == 'MPI'):
... |
_stabilize
_rewriter([Blockwise])
def psd_solve_with_chol(fgraph, node):
if (isinstance(node.op.core_op, Solve) and (node.op.core_op.b_ndim == 2)):
(A, b) = node.inputs
if (getattr(A.tag, 'psd', None) is True):
L = cholesky(A)
Li_b = solve(L, b, assume_a='sym', lower=True, b_... |
def ensemble(training_output_folder1, training_output_folder2, output_folder, task, validation_folder, folds, allow_ensembling: bool=True):
print('\nEnsembling folders\n', training_output_folder1, '\n', training_output_folder2)
output_folder_base = output_folder
output_folder = join(output_folder_base, 'ens... |
.parametrize('default_config', ['ini', 'cmdline'])
def test_filterwarnings_mark(pytester: Pytester, default_config) -> None:
if (default_config == 'ini'):
pytester.makeini('\n [pytest]\n filterwarnings = always::RuntimeWarning\n ')
pytester.makepyfile("\n import warni... |
class AgilentE4980(Instrument):
ac_voltage = Instrument.control(':VOLT:LEV?', ':VOLT:LEV %g', 'AC voltage level, in Volts', validator=strict_range, values=[0, 20])
ac_current = Instrument.control(':CURR:LEV?', ':CURR:LEV %g', 'AC current level, in Amps', validator=strict_range, values=[0, 0.1])
frequency = ... |
class DuckTestDrive():
def main(*args):
duck: Duck = MallardDuck()
turkey: Turkey = WildTurkey()
turkeyAdapter: Duck = TurkeyAdapter(turkey)
print('The Turkey says...')
turkey.gobble()
turkey.fly()
print('\nThe Duck says...')
DuckTestDrive.testDuck(duc... |
class SmoothedValue(object):
def __init__(self, window_size=20):
self.deque = deque(maxlen=window_size)
self.series = []
self.total = 0.0
self.count = 0
def update(self, value):
self.deque.append(value)
self.series.append(value)
self.count += 1
sel... |
class Effect6473(BaseEffect):
dealsDamage = True
type = 'active'
def handler(fit, mod, context, projectionRange, **kwargs):
fit.ship.boostItemAttr('maxVelocity', mod.getModifiedItemAttr('speedFactor'), stackingPenalties=True, **kwargs)
fit.ship.increaseItemAttr('warpScrambleStatus', mod.getM... |
def run_colmap(basedir, match_type):
logfile_name = os.path.join(basedir, 'colmap_output.txt')
logfile = open(logfile_name, 'w')
feature_extractor_args = ['colmap', 'feature_extractor', '--database_path', os.path.join(basedir, 'database.db'), '--image_path', os.path.join(basedir, 'image'), '--ImageReader.si... |
def test_incorrect_interface_type_is_flagged():
class WrongInterfaceInstrument(Instrument):
def __init__(self, adapter, name='Instrument with incorrect interface name', **kwargs):
super().__init__(adapter, name=name, arsl={'read_termination': '\r\n'}, **kwargs)
with pytest.raises(ValueError,... |
class LegacyDistributedDataParallel(nn.Module):
def __init__(self, module, process_group, buffer_size=(2 ** 28)):
super().__init__()
self.module = module
self.process_group = process_group
self.world_size = distributed_utils.get_world_size(self.process_group)
self.buffer_size... |
('pypyr.moduleloader.get_module')
(Step, 'invoke_step', side_effect=ValueError('arb error here'))
def test_run_pipeline_steps_complex_round_trip(mock_invoke_step, mock_get_module):
complex_step_info = CommentedMap({'name': 'step1', 'swallow': 0})
complex_step_info._yaml_set_line_col(5, 6)
step = Step(comple... |
def split_splittable_port(port, k, lanes, dev):
new_split_group = split(k, port)
cmd = 'udevadm settle'
(stdout, stderr) = run_command(cmd)
assert (stderr == '')
if (new_split_group != []):
test(exists_and_lanes(new_split_group, (lanes / k), dev), ('split port %s into %s' % (port.name, k)))
... |
class RequiredImgAssetTests(TestCase):
def test_required_asset_class_inherits_from_expected_classed(self):
classes = (RequiredAssetMixin, BaseRequiredImgAsset, BenefitFeature)
issubclass(RequiredImgAsset, classes)
def test_build_form_field_from_input(self):
text_asset = baker.make(Requir... |
def test_upload_collection_list_np_arrays():
vectors_dim = 50
local_client = init_local()
remote_client = init_remote()
vectors = np.random.randn(UPLOAD_NUM_VECTORS, vectors_dim).tolist()
vectors = [np.array(vector) for vector in vectors]
vectors_config = models.VectorParams(size=vectors_dim, di... |
class MainConfigTest(unittest.TestCase):
def setUp(self):
os.chdir(tests_dir)
os.chdir('dataset01')
cfg_file = './nagios/nagios.cfg'
self.main_config = pynag.Parsers.main.MainConfig(filename=cfg_file)
def test_normal(self):
self.assertEqual('test.cfg', self.main_config.ge... |
.parametrize('dist_name, py_module', [('my.pkg', 'my_pkg'), ('my-pkg', 'my_pkg'), ('my_pkg', 'my_pkg'), ('pkg', 'pkg')])
def test_dist_default_py_modules(tmp_path, dist_name, py_module):
(tmp_path / f'{py_module}.py').touch()
(tmp_path / 'setup.py').touch()
(tmp_path / 'noxfile.py').touch()
attrs = {**E... |
class F40Handler(BaseHandler):
version = F40
commandMap = {'auth': commands.authconfig.F35_Authconfig, 'authconfig': commands.authconfig.F35_Authconfig, 'authselect': commands.authselect.F28_Authselect, 'autopart': commands.autopart.F38_AutoPart, 'autostep': commands.autostep.F34_AutoStep, 'bootloader': command... |
.parametrize('flat_fee, prop_fee, initial_amount, expected_amount', [(50, 0, 1000, ((1000 - 50) - 50)), (0, 1000000, 2000, 1000), (0, 100000, 1100, 1000), (0, 50000, 1050, 1000), (0, 10000, 1010, 1000), (0, 10000, 101, 100), (0, 4990, 100, 100), (1, 500000, ((1000 + 500) + 2), 1000), (10, 500000, ((1000 + 500) + 20), 9... |
def test_mpris2_no_scroll(fake_qtile, patched_module, fake_window):
mp = patched_module.Mpris2(scroll_chars=None)
fakebar = FakeBar([mp], window=fake_window)
mp.timeout_add = fake_timer
mp._configure(fake_qtile, fakebar)
mp.configured = True
mp.parse_message(*METADATA_PLAYING.body)
assert (m... |
def check_if_user_can_vote(user: User, conference: Conference):
if user.is_staff:
return True
if Submission.objects.filter(speaker_id=user.id, conference=conference).exists():
return True
additional_events = [{'organizer_slug': included_voting_event.pretix_organizer_id, 'event_slug': include... |
def ql_syscall_wait4(ql: Qiling, pid: int, wstatus: int, options: int, rusage: int):
pid = ql.unpack32s(ql.pack32(pid))
try:
(spid, status, _) = os.wait4(pid, options)
if wstatus:
ql.mem.write_ptr(wstatus, status, 4)
retval = spid
except ChildProcessError:
retval ... |
def verify(image, dimension):
value = image.__getattribute__(dimension)
while (value > 1):
div_float = (float(value) / 2.0)
div_int = int(div_float)
if (not (div_float == div_int)):
raise Exception(('image %s is %d, which is not a power of 2' % (dimension, image.__getattribut... |
def test_cache_race_condition():
with tempfile.TemporaryDirectory() as dir_name:
_flags(on_opt_error='raise', on_shape_error='raise')
def f_build(factor):
a = pt.vector()
f = pytensor.function([a], (factor * a))
return f(np.array([1], dtype=config.floatX))
... |
def _get_next_free_filename():
global _free_name_counter
def scan_next_free():
log.Log('Setting next free from long filenames dir', log.INFO)
cur_high = 0
for filename in _get_long_rp().listdir():
try:
i = int(filename.split(b'.')[0])
except ValueE... |
class APETextValue(_APEUtf8Value, MutableSequence):
kind = TEXT
def __iter__(self):
return iter(self.value.split(u'\x00'))
def __getitem__(self, index):
return self.value.split(u'\x00')[index]
def __len__(self):
return (self.value.count(u'\x00') + 1)
def __setitem__(self, ind... |
def recursive_find_python_class(folder: str, class_name: str, current_module: str):
tr = None
for (importer, modname, ispkg) in pkgutil.iter_modules([folder]):
if (not ispkg):
m = importlib.import_module(((current_module + '.') + modname))
if hasattr(m, class_name):
... |
class TPBGroupedWeightedPauliOperator(WeightedPauliOperator):
def __init__(self, paulis, basis, z2_symmetries=None, atol=1e-12, name=None, grouping_func=None, kwargs=None):
super().__init__(paulis, basis, z2_symmetries, atol, name)
self._grouping_func = grouping_func
self._kwargs = (kwargs o... |
def tfm_assert_array_to_file_output(input_file, output_file, tfm, dtype_in='int16', dtype_out='int16', test_file_out=True, skip_array_tests=False, **kwargs):
(input_array, rate) = sf.read(input_file, dtype=dtype_in)
(actual_output, _) = sf.read(output_file, dtype=dtype_out)
if (not skip_array_tests):
... |
def lexical_overlap_rate(premise, hypothesis):
premise_token_list = tokenizer.tokenize(premise.lower())
hypothesis_token_list = tokenizer.tokenize(hypothesis.lower())
overlap_cnt = 0
for tok in hypothesis_token_list:
if (tok in premise_token_list):
overlap_cnt += 1
return ((1.0 *... |
def create_duel_q_network(input_frames, num_actions, trainable, noisy):
(flat_output, flat_output_size, parameter_list) = create_conv_network(input_frames, trainable)
if (noisy == False):
fcV_W = tf.get_variable(shape=[flat_output_size, 512], name='fcV_W', trainable=trainable, initializer=tf.contrib.lay... |
class IndexedDatasetBuilder(object):
element_sizes = {np.uint8: 1, np.int8: 1, np.int16: 2, np.int32: 4, np.int64: 8, float: 4, np.double: 8}
def __init__(self, out_file, dtype=np.int32):
self.out_file = open(out_file, 'wb')
self.dtype = dtype
self.data_offsets = [0]
self.dim_off... |
def similarity_transform(xsys, T, timescale=1, inverse=False):
zsys = StateSpace(xsys)
T = np.atleast_2d(T)
def rsolve(M, y):
return transpose(solve(transpose(M), transpose(y)))
if (not inverse):
zsys.A = (rsolve(T, (T zsys.A)) / timescale)
zsys.B = ((T zsys.B) / timescale)
... |
def wait_for_gpus(world_size, timeout_secs=3600):
n_gpus = int(ray.cluster_resources().get('GPU', 0))
elapsed_time = 0
while (n_gpus < world_size):
logging.warning(f'Not enough GPUs available ({n_gpus} available,need {world_size}), waiting 10 seconds')
time.sleep(10)
elapsed_time += ... |
def _override_attr(sub_node: str, data_class: Type[FairseqDataclass], args: Namespace) -> List[str]:
overrides = []
for k in data_class.__dataclass_fields__.keys():
if (k == '_name'):
continue
if (not hasattr(args, k)):
continue
if (getattr(args, k) is None):
... |
def split_rxn_parts(rxn):
rxn_parts = rxn.strip().split('>')
rxn_reactants = set(rxn_parts[0].split('.'))
rxn_agents = (None if (not rxn_parts[1]) else set(rxn_parts[1].split('.')))
rxn_products = set(rxn_parts[2].split('.'))
(reactants, agents, products) = (set(), set(), set())
for r in rxn_rea... |
def test_not_strict_mode():
code = 'K9L2 100958Z AUTO 33006KT 10SM CLR M A3007 RMK AO2 SLPNO FZRANO $'
raisesParserError(code)
with warnings.catch_warnings(record=True) as w:
report = Metar.Metar(code, strict=False)
assert (len(w) == 1)
assert (not report.decode_completed)
assert (report... |
class ClientTests(CommonTests, AsyncioTestCase):
def setUp(self):
super().setUp()
self.protocol.is_client = True
self.protocol.side = 'client'
def test_local_close_send_close_frame_timeout(self):
self.protocol.close_timeout = (10 * MS)
self.make_drain_slow((50 * MS))
... |
def display_suite_metadata(suite, title=None):
metadata = suite.get_metadata()
empty = True
for (key, fmt) in (('performance_version', 'Performance version: %s'), ('python_version', 'Python version: %s'), ('platform', 'Report on %s'), ('cpu_count', 'Number of logical CPUs: %s')):
if (key not in meta... |
def get_ordered_ops(graph: tf.Graph, starting_op_names: List[str], output_op_names: List[str]) -> List[tf.Operation]:
def add_children_ops_before_parent_op(current_op: tf.Operation):
visited_ops.add(current_op)
for output_tensor in current_op.outputs:
for consumer_op in output_tensor.con... |
def test_one_parameter_multiple_calls() -> None:
with RecursionTable('fib') as table:
def fib(n):
if (n in [0, 1]):
return 1
else:
return (fib((n - 2)) + fib((n - 1)))
fib(3)
recursive_dict = table.get_recursive_dict()
assert (len(list(... |
def clip_gradients(model, i_iter, writer, config):
max_grad_l2_norm = config['training_parameters']['max_grad_l2_norm']
clip_norm_mode = config['training_parameters']['clip_norm_mode']
if (max_grad_l2_norm is not None):
if (clip_norm_mode == 'all'):
norm = nn.utils.clip_grad_norm_(model.... |
class LockTimeRawEdit(QLineEdit, _LockTimeEditor):
def __init__(self, parent=None):
QLineEdit.__init__(self, parent)
self.setFixedWidth((14 * char_width_in_lineedit()))
self.textChanged.connect(self.numbify)
def numbify(self):
text = self.text().strip()
chars = ''
... |
def calc_sim(sent_visual, sent_caption):
def sent_preprocess(sent):
sent = word_tokenize(sent)
sent = [ps.stem(word.lower()) for word in sent]
sent_remove_stop_words = [word for word in sent if (word not in stop_words)]
return (sent, sent_remove_stop_words)
visual_words = [list(s... |
def fopsort(filename):
temporaryfile = f'{filename}.temp'
check_lines = 10
section = []
lineschecked = 1
filterlines = elementlines = 0
with open(filename, 'r', encoding='utf-8', newline='\n') as inputfile, open(temporaryfile, 'w', encoding='utf-8', newline='\n') as outputfile:
def combi... |
def print_usage():
print('Usage: imapbackup [OPTIONS] -s HOST -u USERNAME [-p PASSWORD]')
print(' -d DIR --mbox-dir=DIR Write mbox files to directory. (defaults to cwd)')
print(' -a --append-to-mboxes Append new messages to mbox files. (default)')
print(' -y --yes-overwrite-mboxes Ov... |
def _r2_score_compute(sum_squared_obs: torch.Tensor, sum_obs: torch.Tensor, rss: torch.Tensor, num_obs: torch.Tensor, multioutput: str, num_regressors: int) -> torch.Tensor:
if (num_obs < 2):
raise ValueError('There is no enough data for computing. Needs at least two samples to calculate r2 score.')
if ... |
def main():
args = parse_args()
cfg = Config.fromfile(args.config)
assert (args.eval is not None)
if (args.cfg_options is not None):
cfg.merge_from_dict(args.cfg_options)
cfg.data.test.test_mode = True
dataset = build_dataset(cfg.data.test)
outputs = mmcv.load(args.results)
kwarg... |
def main():
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
if ((len(sys.argv) == 2) and sys.argv[1].endswith('.json')):
(model_args, data_args, training_args) = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
else:
(model_args, data_args,... |
class PathManager():
def __init__(self):
self.path = MsgPath()
self.manager_requests_waypoints = True
def update(self, target_position):
self.path.type = 'orbit'
self.path.airspeed = 25
self.path.orbit_center[(0, 0)] = target_position.item(0)
self.path.orbit_cente... |
class ImgEncoder(BaseNet):
def __init__(self, obs_shape, hidden_size=256):
super().__init__(False, hidden_size, hidden_size)
self.n_channels = obs_shape[0]
self.net = nn.Sequential(nn.Conv2d(self.n_channels, 32, kernel_size=8, stride=3), nn.ReLU(), nn.Conv2d(32, 64, kernel_size=4, stride=2),... |
class opcodes(IntEnum):
OP_0 = 0
OP_FALSE = OP_0
OP_PUSHDATA1 = 76
OP_PUSHDATA2 = 77
OP_PUSHDATA4 = 78
OP_1NEGATE = 79
OP_RESERVED = 80
OP_1 = 81
OP_TRUE = OP_1
OP_2 = 82
OP_3 = 83
OP_4 = 84
OP_5 = 85
OP_6 = 86
OP_7 = 87
OP_8 = 88
OP_9 = 89
OP_10 =... |
class session(Thread):
def __init__(self, conn, pSocket, connectURLs, redirectURLs, FwdTarget, force_redirect):
Thread.__init__(self)
self.pSocket = pSocket
self.connectURLs = connectURLs
self.conn = conn
self.connect_closed = False
self.session_connected = False
... |
class TensorFlowBenchmarkArguments(BenchmarkArguments):
deprecated_args = ['no_inference', 'no_cuda', 'no_tpu', 'no_speed', 'no_memory', 'no_env_print', 'no_multi_process']
def __init__(self, **kwargs):
for deprecated_arg in self.deprecated_args:
if (deprecated_arg in kwargs):
... |
def apply_rotary_emb(q, sinu_pos):
sinu_pos = rearrange(sinu_pos, 'n (j d) -> n j d', j=2)
(sin, cos) = sinu_pos.unbind(dim=(- 2))
(sin, cos) = map((lambda t: repeat(t, 'n d -> n (d j)', j=2)), (sin, cos))
print(q.size(), cos.size(), sin.size())
q = ((q * cos.unsqueeze(1)) + (rotate_every_two(q) * s... |
class DeleteDialog(WarningMessage):
RESPONSE_DELETE = 1
def for_songs(cls, parent, songs):
description = _('The selected songs will be removed from the library and their files deleted from disk.')
paths = [s('~filename') for s in songs]
return cls(parent, paths, description)
def for_... |
_unraisablehook()
def test_last_minute_gc_edge_case() -> None:
saved: list[AsyncGenerator[(int, None)]] = []
record = []
needs_retry = True
async def agen() -> AsyncGenerator[(int, None)]:
try:
(yield 1)
finally:
record.append('cleaned up')
def collect_at_oppo... |
class Migration(migrations.Migration):
dependencies = [('api', '0086_infraction_jump_url')]
operations = [migrations.AlterField(model_name='infraction', name='type', field=models.CharField(choices=[('note', 'Note'), ('warning', 'Warning'), ('watch', 'Watch'), ('timeout', 'Timeout'), ('kick', 'Kick'), ('ban', 'B... |
def test_method_and_teardown_failing_reporting(pytester: Pytester) -> None:
pytester.makepyfile('\n import unittest\n class TC(unittest.TestCase):\n def tearDown(self):\n assert 0, "down1"\n def test_method(self):\n assert False, "down2"\n ')
... |
class NotificationManager(object):
def __init__(self, config, data_manager):
self.config = config
self.data_manager = data_manager
self.logger = getLogger()
self.apprise = self.build_apprise()
def build_apprise(self):
asset = apprise.AppriseAsset(image_url_mask=' default_... |
def make_dataset():
if (opt.dataset in ('imagenet', 'dog_and_cat_64', 'dog_and_cat_128')):
trans = tfs.Compose([tfs.Resize(opt.img_width), tfs.ToTensor(), tfs.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])])
data = ImageFolder(opt.root, transform=trans)
loader = DataLoader(data, batch_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.