code stringlengths 281 23.7M |
|---|
class ELFTest(unittest.TestCase):
def test_tenda_ac15_arm(self):
def nvram_listener():
server_address = '../examples/rootfs/arm_tendaac15/var/cfm_socket'
data = ''
try:
os.unlink(server_address)
except OSError:
if os.path.exists... |
def add_extra_methods_hook(ctx: ClassDefContext) -> None:
add_method(ctx, 'foo_classmethod', [], NoneType(), is_classmethod=True)
add_method(ctx, 'foo_staticmethod', [Argument(Var(''), ctx.api.named_type('builtins.int'), None, ARG_POS)], ctx.api.named_type('builtins.str'), is_staticmethod=True) |
def add_validate_argument(parser: ArgumentParser):
group = parser.add_mutually_exclusive_group()
group.add_argument('--validate', action='store_true', dest='validate', default=True, help="After generating a layout, validate if it's possible. Default behaviour.")
group.add_argument('--no-validate', action='s... |
class APICallResponseDataValidator(BaseAPICallResponseValidator):
def iter_errors(self, request: Request, response: Response) -> Iterator[Exception]:
try:
(_, operation, _, _, _) = self._find_path(request)
except PathError as exc:
(yield exc)
return
(yield... |
class Icassp2018Test(unittest.TestCase):
def test_1000by6_matrix(self):
matrix = np.array((((([[1.0, 0.0, 0.0, 0.0, 0.0, 0.0]] * 400) + ([[0.0, 1.0, 0.0, 0.0, 0.0, 0.0]] * 300)) + ([[0.0, 0.0, 2.0, 0.0, 0.0, 0.0]] * 200)) + ([[0.0, 0.0, 0.0, 1.0, 0.0, 0.0]] * 100)))
noisy = ((np.random.rand(1000, 6)... |
class VOC12SegmentationDataset(Dataset):
def __init__(self, img_name_list_path, label_dir, crop_size, voc12_root, rescale=None, img_normal=TorchvisionNormalize(), hor_flip=False, crop_method='random'):
self.img_name_list = load_img_name_list(img_name_list_path)
self.voc12_root = voc12_root
s... |
.parametrize('files, glob_pattern, upload_statuses, expected', [(['foo.zip', 'bar.whl'], '*.zip', [True], 1), (['foo.whl', 'foo.egg', 'foo.tar.gz'], 'foo.*', [True, True, True], 3), ([], '*', [], 0), (['specialconfig.yaml', 'something.whl', 'desc.md'], '*.yaml', [True], 1), (['specialconfig.yaml', 'something.whl', 'des... |
def test_history_clear(mocker, hist_file):
app = cmd2.Cmd(persistent_history_file=hist_file)
run_cmd(app, 'help')
run_cmd(app, 'alias')
(out, err) = run_cmd(app, 'history')
assert out
verify_hi_last_result(app, 2)
run_cmd(app, 'history --clear')
assert (app.last_result is True)
(out,... |
class GaussianMLPRegressor(LasagnePowered, Serializable):
def __init__(self, input_shape, output_dim, mean_network=None, hidden_sizes=(32, 32), hidden_nonlinearity=NL.rectify, optimizer=None, use_trust_region=True, step_size=0.01, learn_std=True, init_std=1.0, adaptive_std=False, std_share_network=False, std_hidden... |
def test_collection_args_do_not_duplicate_modules(pytester: Pytester) -> None:
pytester.makepyfile(**{'d/test_it': '\n def test_1(): pass\n def test_2(): pass\n '})
result = pytester.runpytest('--collect-only', 'd/test_it.py::test_1', 'd/test_it.py::test_2')
resu... |
def test_update_pfs():
properties = factories.BalanceProofSignedStateProperties(pkey=PRIVKEY)
balance_proof = factories.create(properties)
channel_state = factories.create(factories.NettingChannelStateProperties())
channel_state.our_state.balance_proof = balance_proof
channel_state.partner_state.bal... |
class NoneWordSplitter(object):
def __init__(self, model):
pass
def split(self, string):
return [string]
def process_line(self, string):
return [string]
def finished_word(self, string):
return True
def merge(self, list_of_string):
return ''.join(list_of_string... |
def synchronized(lock: threading.RLock) -> Callable[([CallableT], CallableT)]:
def outside_wrapper(function: CallableT) -> CallableT:
(function)
def wrapper(*args: Any, **kwargs: Any) -> Any:
with lock:
return function(*args, **kwargs)
return cast(CallableT, wrapp... |
class NitrobitNet(SimpleDownloader):
__name__ = 'NitrobitNet'
__type__ = 'downloader'
__version__ = '0.02'
__status__ = 'testing'
__pattern__ = '
__config__ = [('enabled', 'bool', 'Activated', True), ('use_premium', 'bool', 'Use premium account if available', True), ('fallback', 'bool', 'Fallbac... |
class TestVectorize():
def test_elemwise(self):
vec = tensor(shape=(None,))
mat = tensor(shape=(None, None))
node = exp(vec).owner
vect_node = vectorize_node(node, mat)
assert (vect_node.op == exp)
assert (vect_node.inputs[0] is mat)
def test_dimshuffle(self):
... |
class Graphite(Layer):
def __init__(self, input_dim, output_dim, dropout=0.0, act=tf.nn.relu, **kwargs):
super(Graphite, self).__init__(**kwargs)
with tf.variable_scope((self.name + '_vars')):
self.vars['weights'] = weight_variable_glorot(input_dim, output_dim, name='weights')
se... |
def train_mnist(config, data_dir=None, num_epochs=10, num_workers=4, use_gpu=False, callbacks=None):
model = MNISTClassifier(config, data_dir)
callbacks = (callbacks or [])
trainer = pl.Trainer(max_epochs=num_epochs, callbacks=callbacks, strategy=HorovodRayStrategy(num_workers=num_workers, use_gpu=use_gpu))... |
class OrthoMover(Behaviour):
cam = ShowInInspector(Camera)
async def Update(self, dt):
if Input.GetKey(KeyCode.E):
self.cam.orthoSize -= (dt * 3)
if Input.GetKey(KeyCode.Q):
self.cam.orthoSize += (dt * 3)
self.cam.orthoSize = Mathf.Clamp(self.cam.orthoSize, 2, 16)... |
def write_uem(uemf, uem, n_digits=3):
with open(uemf, 'wb') as f:
for file_id in sorted(iterkeys(uem)):
for (onset, offset) in sorted(uem[file_id]):
line = ' '.join([file_id, '1', format_float(onset, n_digits), format_float(offset, n_digits)])
f.write(line.encode(... |
class Network_Triple(Virtue_Triple):
def __init__(self, num_ps, num_qs, num_rs, embedding_dim, arch, reg):
super(Network_Triple, self).__init__(num_ps, num_qs, num_rs, embedding_dim, reg)
self.arch = arch
self.mlp_p = arch['mlp']['p']
self.mlp_q = arch['mlp']['q']
self.mlp_r ... |
.slow
.pydicom
def test_ct(pinn):
for p in pinn:
export_path = os.path.join(working_path, 'output', p.patient_info['MedicalRecordNumber'], 'CT')
os.makedirs(export_path)
export_plan = p.plans[0]
p.export_image(export_plan.primary_image, export_path=export_path)
for f in os.li... |
class TestPriceHistory(unittest.TestCase):
def setUpClass(cls):
cls.session = session_gbl
def tearDownClass(cls):
if (cls.session is not None):
cls.session.close()
def test_daily_index(self):
tkrs = ['BHP.AX', 'IMP.JO', 'BP.L', 'PNL.L', 'INTC']
intervals = ['1d', ... |
class ScriptExecutor(object):
_action_executors = {Action.WALK: WalkExecutor(), Action.FIND: FindExecutor(), Action.SIT: SitExecutor(), Action.STANDUP: StandUpExecutor(), Action.GRAB: GrabExecutor(), Action.OPEN: OpenExecutor(False), Action.CLOSE: OpenExecutor(True), Action.PUTBACK: PutExecutor(Relation.ON), Action... |
def test_linestyle_checks():
sys = ct.tf([100], [1, 1, 1])
lines = ct.nyquist_plot(sys, primary_style=[':', ':'], mirror_style=[':', ':'])
assert all([(line.get_linestyle() == ':') for line in lines[0]])
lines = ct.nyquist_plot(sys, color='g')
assert all([(line.get_color() == 'g') for line in lines[... |
def avg_n_dicts(dicts, experiment=None, step=None):
means = {}
for dic in dicts:
for key in dic:
if (key not in means):
means[key] = 0
means[key] += (dic[key] / len(dicts))
if (experiment is not None):
experiment.log_metrics(means, step=step)
retur... |
class PrimaryKeyIndexLocator(Locator, dict):
def of(primary_key_index_meta: PrimaryKeyIndexMeta) -> PrimaryKeyIndexLocator:
pki_root_path = PrimaryKeyIndexLocator._root_path(primary_key_index_meta.compacted_partition_locator, primary_key_index_meta.primary_keys, primary_key_index_meta.sort_keys, primary_key... |
.parametrize('sampler', [sample_blackjax_nuts, sample_numpyro_nuts])
.skipif((len(jax.devices()) < 2), reason='not enough devices')
def test_deterministic_samples(sampler):
pytensor.config.on_opt_error = 'raise'
np.random.seed(13244)
obs = np.random.normal(10, 2, size=100)
obs_at = pytensor.shared(obs, ... |
def test_all_extras_populates_installer(tester: CommandTester, mocker: MockerFixture) -> None:
assert isinstance(tester.command, InstallerCommand)
mocker.patch.object(tester.command.installer, 'run', return_value=1)
tester.execute('--all-extras')
assert (tester.command.installer._extras == ['extras-a', ... |
def aead_chacha20poly1305_encrypt(key, counter, plain_text, auth_text):
cipher = ChaCha20_Poly1305.new(key=key, nonce=(b'\x00\x00\x00\x00' + counter.to_bytes(8, 'little')))
cipher.update(auth_text)
(cipher_text, digest) = cipher.encrypt_and_digest(plain_text)
return (cipher_text + digest) |
def render_pep8_errors_e128(msg, _node, source_lines):
line = msg.line
res = re.search('column (\\d+)', msg.msg)
col = int(res.group().split()[(- 1)])
(yield from render_context((line - 2), line, source_lines))
(yield (line, slice(0, (col if (col != 0) else None)), LineType.ERROR, source_lines[(line... |
class get_model(LightningBaseModel):
def __init__(self, config):
super().__init__(config, None)
self.save_hyperparameters()
cr = config.model_params.cr
cs = config.model_params.layer_num
cs = [int((cr * x)) for x in cs]
self.pres = self.vres = config.model_params.voxe... |
def generalized_kernel_feature_creator(data, projection_matrix, batch_dims_t, precision, kernel_fn, kernel_epsilon, normalize_data):
if normalize_data:
data_normalizer = (1.0 / jnp.sqrt(jnp.sqrt(data.shape[(- 1)])))
else:
data_normalizer = 1.0
if (projection_matrix is None):
return (... |
.parametrize('modifier', ['lower', 'upper'])
def test_source_add_existing_fails_due_to_other_default(modifier: str, tester: CommandTester, source_existing: Source, source_default: Source, poetry_with_source: Poetry) -> None:
tester.execute(f'--priority=default {source_default.name} {source_default.url}')
tester... |
def create_callbacks(model, training_model, prediction_model, validation_generator, args):
callbacks = []
tensorboard_callback = None
if args.tensorboard_dir:
makedirs(args.tensorboard_dir)
tensorboard_callback = keras.callbacks.TensorBoard(log_dir=args.tensorboard_dir, histogram_freq=0, bat... |
class GoloLexer(RegexLexer):
name = 'Golo'
url = '
filenames = ['*.golo']
aliases = ['golo']
version_added = '2.0'
tokens = {'root': [('[^\\S\\n]+', Whitespace), ('#.*$', Comment), ('(\\^|\\.\\.\\.|:|\\?:|->|==|!=|=|\\+|\\*|%|/|<=|<|>=|>|=|\\.)', Operator), ('(?<=[^-])(-)(?=[^-])', Operator), ('... |
def register(manager: AstroidManager) -> None:
for (func_name, func_src) in METHODS_TO_BE_INFERRED.items():
inference_function = functools.partial(infer_numpy_member, func_src)
manager.register_transform(Attribute, inference_tip(inference_function), functools.partial(attribute_looks_like_numpy_membe... |
def getRobotFishHumanReefWrecks(mask):
(imw, imh) = (mask.shape[0], mask.shape[1])
Human = np.zeros((imw, imh))
Robot = np.zeros((imw, imh))
Fish = np.zeros((imw, imh))
Reef = np.zeros((imw, imh))
Wreck = np.zeros((imw, imh))
for i in range(imw):
for j in range(imh):
if (... |
class WideResNet(nn.Module):
def __init__(self, num_classes: int=10, depth: int=28, width: int=10, activation_fn: nn.Module=nn.ReLU, mean: Union[(Tuple[(float, ...)], float)]=TINY_MEAN, std: Union[(Tuple[(float, ...)], float)]=TINY_STD, padding: int=0, num_input_channels: int=3):
super().__init__()
... |
class MultinodePenalty(PenaltyOption):
def __init__(self, _multinode_penalty_fcn: (Any | type), nodes: tuple[((int | Node), ...)], nodes_phase: tuple[(int, ...)], multinode_penalty: (Any | Callable)=None, custom_function: Callable=None, **params: Any):
if (not isinstance(multinode_penalty, _multinode_penalt... |
class UAVDataset(Dataset):
def __init__(self, name, dataset_root, load_img=False):
super(UAVDataset, self).__init__(name, dataset_root)
with open(os.path.join(dataset_root, (name + '.json')), 'r') as f:
meta_data = json.load(f)
pbar = tqdm(meta_data.keys(), desc=('loading ' + nam... |
class FileAttributes(FileCopying):
def setUp(self):
FileCopying.setUp(self)
self.noperms = rpath.RPath(self.lc, self.mainprefix, ('noperms',))
self.nowrite = rpath.RPath(self.lc, self.mainprefix, ('nowrite',))
self.exec1 = rpath.RPath(self.lc, self.prefix, ('executable',))
se... |
def min_weight_simple_paths_brute_force(graph: nx.Graph, weight_fun: Callable[([nx.Graph, List], float)]=path_weight):
best_weights = defaultdict((lambda : float('inf')))
best_paths = {}
nodelist = list(graph.nodes())
for i in range((len(nodelist) - 1)):
for j in range((i + 1), len(nodelist)):
... |
class DynamicLossScaler():
def __init__(self, init_scale=(2 ** 32), scale_factor=2.0, scale_window=1000, min_scale=1, delayed_shift=1, consecutive_hysteresis=False):
self.cur_scale = init_scale
self.cur_iter = 0
self.last_overflow_iter = (- 1)
self.scale_factor = scale_factor
... |
class ElpiLexer(RegexLexer):
name = 'Elpi'
url = '
aliases = ['elpi']
filenames = ['*.elpi']
mimetypes = ['text/x-elpi']
version_added = '2.11'
lcase_re = '[a-z]'
ucase_re = '[A-Z]'
digit_re = '[0-9]'
schar2_re = "([+*^?/<>`'#~=&!])"
schar_re = '({}|-|\\$|_)'.format(schar2_re... |
def _get_all_tables(connection: pymedphys.mosaiq.Connection, patient_ids: List[str]) -> Tuple[(Dict[(str, pd.DataFrame)], Dict[(str, Dict[(str, str)])])]:
tables: Dict[(str, pd.DataFrame)] = {}
types_map: Dict[(str, Dict[(str, str)])] = {}
tables['Ident'] = get_filtered_table(connection, types_map, 'Ident',... |
def join_path_with_escaped_name_of_legal_length(path: str, stem: str, ext: str) -> str:
max_stem_length = ((os.pathconf(path, 'PC_NAME_MAX') - 1) - len(ext))
escaped_stem = escape_filename(stem)
while (len(escaped_stem) > max_stem_length):
stem = stem[:max_stem_length]
max_stem_length -= 1
... |
class DLRMTrainTest(unittest.TestCase):
def test_basic(self) -> None:
B = 2
D = 8
dense_in_features = 100
eb1_config = EmbeddingBagConfig(name='t2', embedding_dim=D, num_embeddings=100, feature_names=['f2'])
ebc = EmbeddingBagCollection(tables=[eb1_config])
dlrm_modul... |
class Migration(migrations.Migration):
dependencies = [('objects', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('typeclasses', '0001_initial'), ('comms', '0002_msg_db_hide_from_objects')]
operations = [migrations.AddField(model_name='msg', name='db_hide_from_accounts', field=mode... |
def test_optional_and_positional_only():
with pytest.raises(ValueError, match=full_match_regex_str("Field 'a' can not be positional only and optional")):
InputShape(constructor=stub_constructor, kwargs=None, fields=(InputField(id='a', type=int, default=NoDefault(), is_required=False, metadata={}, original=N... |
def compute_metrics(a: Union[(np.array, Image.Image)], b: Union[(np.array, Image.Image)], metrics: Optional[List[str]]=None, max_val: float=255.0) -> Dict[(str, float)]:
if (metrics is None):
metrics = ['psnr']
def _convert(x):
if isinstance(x, Image.Image):
x = np.asarray(x)
... |
def buttons_string(buttons):
button_names = []
if (buttons & LEFT):
button_names.append('LEFT')
if (buttons & MIDDLE):
button_names.append('MIDDLE')
if (buttons & RIGHT):
button_names.append('RIGHT')
if (buttons & MOUSE4):
button_names.append('MOUSE4')
if (buttons... |
class TestClientError(ClientTestCase):
def setUp(self):
super(TestClientError, self).setUp()
self.base_url = '{}/payments'.format(self.base_url)
def test_payment_with_invalid_options(self):
count = 10000
result = {'error': {'field': 'count', 'code': 'BAD_REQUEST_ERROR', 'descript... |
def _ContainedInOther(rect1, rect2):
if ((rect1.left >= rect2.left) and (rect1.top >= rect2.top) and (rect1.right <= rect2.right) and (rect1.bottom <= rect2.bottom)):
return True
elif ((rect2.left >= rect1.left) and (rect2.top >= rect1.top) and (rect2.right <= rect1.right) and (rect2.bottom <= rect1.bot... |
def random_traces(nsamples, code='12', deltat=0.01, dtypes=(num.int8, num.int32, num.float32, num.float64), limit=None):
def decorator(func):
(func)
def wrapper(*args, **kwargs):
for dtype in dtypes:
tr = get_random_trace(nsamples, code, deltat, dtype, limit)
... |
class UpDecoderBlock2D(nn.Module):
def __init__(self, in_channels: int, out_channels: int, dropout: float=0.0, num_layers: int=1, resnet_eps: float=1e-06, resnet_time_scale_shift: str='default', resnet_act_fn: str='swish', resnet_groups: int=32, resnet_pre_norm: bool=True, output_scale_factor=1.0, add_upsample=True... |
class PlayOpenWindow(Packet):
id = 45
to = 1
def __init__(self, window_id: int, window_type: int, title: Chat) -> None:
super().__init__()
self.window_id = window_id
self.window_type = window_type
self.title = title
def encode(self) -> bytes:
return ((Buffer.pack_... |
def invcompress(quality, metric='mse', pretrained=False, progress=True, **kwargs):
if (metric not in ('mse', 'ms-ssim')):
raise ValueError(f'Invalid metric "{metric}"')
if ((quality < 1) or (quality > 8)):
raise ValueError(f'Invalid quality "{quality}", should be between (1, 13)')
if (pretra... |
class Scale(object):
def __init__(self, size):
self.size = size
def __call__(self, img, mask):
assert (img.size == mask.size)
(w, h) = img.size
if (((w >= h) and (w == self.size)) or ((h >= w) and (h == self.size))):
return (img, mask)
if (w > h):
... |
def get_prefix(cfg: DictConfig) -> str:
string = dict(cfg['clean']).__repr__()
string += dict(cfg[__key__]).__repr__()
string += cfg.model.name
string = string.encode()
string = hashlib.md5(string).hexdigest()
string = string[:6]
task = ('rank' if (cfg.task == '1') else 'cls')
string = f... |
def get_incremental_uncovered_lines(abs_path: str, base_commit: str, actual_commit: Optional[str]) -> List[Tuple[(int, str, str)]]:
if (not os.path.isfile(abs_path)):
return []
optional_actual_commit = ([] if (actual_commit is None) else [actual_commit])
unified_diff_lines_str = shell_tools.output_o... |
class DatatableFactory(factory.Factory):
class Meta():
model = dict
id = factory.Sequence((lambda n: n))
vendor_code = factory.Sequence((lambda n: 'VENDOR_CODE{0}'.format(n)))
datatable_code = factory.Sequence((lambda n: 'DATATABLE_CODE{0}'.format(n)))
name = factory.Sequence((lambda n: 'DAT... |
def test_wcs_downsampling():
wcs = WCS(naxis=1)
wcs.wcs.ctype = ['FREQ']
wcs.wcs.crpix = [1.0]
nwcs = slice_wcs(wcs, slice(0, None, 1))
assert (nwcs.wcs.crpix[0] == 1)
nwcs = slice_wcs(wcs, slice(0, None, 2))
assert (nwcs.wcs.crpix[0] == 0.75)
nwcs = slice_wcs(wcs, slice(0, None, 4))
... |
class KerasModel(tf.keras.Model):
def __init__(self, args, architecture='ResNet50', data='CIFAR10'):
super().__init__(name=architecture)
self.args = args
if self.args.bit64:
raise NotImplementedError()
self.architecture = architecture
self.data = data
if (... |
def safe_meet(t: Type, s: Type) -> Type:
from mypy.meet import meet_types
if ((not isinstance(t, UnpackType)) and (not isinstance(s, UnpackType))):
return meet_types(t, s)
if (isinstance(t, UnpackType) and isinstance(s, UnpackType)):
unpacked = get_proper_type(t.type)
if isinstance(u... |
def data_type_format4(signal_data_type, number_of_bytes):
if (signal_data_type == 0):
if (number_of_bytes == 1):
data_type = 'B'
elif (number_of_bytes == 2):
data_type = 'H'
elif (number_of_bytes <= 4):
data_type = 'I'
elif (number_of_bytes <= 8):
... |
def freeze_batch_norm_2d(module):
res = module
if isinstance(module, (torch.nn.modules.batchnorm.BatchNorm2d, torch.nn.modules.batchnorm.SyncBatchNorm)):
res = FrozenBatchNorm2d(module.num_features)
res.num_features = module.num_features
res.affine = module.affine
if module.affin... |
class OrFilter(Filter):
def __init__(self, base, other):
self.base = base
self.other = other
async def __call__(self, client: 'pyrogram.Client', update: Update):
if inspect.iscoroutinefunction(self.base.__call__):
x = (await self.base(client, update))
else:
... |
class Describe_Cell():
def it_knows_what_text_it_contains(self, text_get_fixture):
(cell, expected_text) = text_get_fixture
text = cell.text
assert (text == expected_text)
def it_can_replace_its_content_with_a_string_of_text(self, text_set_fixture):
(cell, text, expected_xml) = t... |
def find_subcommand(action: argparse.ArgumentParser, subcmd_names: List[str]) -> argparse.ArgumentParser:
if (not subcmd_names):
return action
cur_subcmd = subcmd_names.pop(0)
for sub_action in action._actions:
if isinstance(sub_action, argparse._SubParsersAction):
for (choice_na... |
class Logger(object):
def __init__(self, file_name: Optional[str]=None, file_mode: str='w', should_flush: bool=True):
self.file = None
if (file_name is not None):
self.file = open(file_name, file_mode)
self.should_flush = should_flush
self.stdout = sys.stdout
self... |
def check_default_optimizer(optimizer, model, prefix=''):
assert isinstance(optimizer, torch.optim.SGD)
assert (optimizer.defaults['lr'] == base_lr)
assert (optimizer.defaults['momentum'] == momentum)
assert (optimizer.defaults['weight_decay'] == base_wd)
param_groups = optimizer.param_groups[0]
... |
def join_path(path1, path2):
if (path1[(- 1)] == path2[0]):
return (path1 + path2[1:])
elif (path2[(- 1)] == path1[0]):
return (path2 + path1[1:])
elif (path1[(- 1)] == path2[(- 1)]):
return (path1 + path2[1::(- 1)])
elif (path1[0] == path2[0]):
return (path2[:0:(- 1)] + ... |
def main():
args = parse_args()
if (not check(args)):
return
print('Load Embeddings!')
emb_file_path = f'{model_folder}/{args.model}/data/{args.dataset}/{emb_file}'
(train_para, emb_dict) = load(emb_file_path)
print('Start Evaluation!')
(all_tasks, all_scores) = ([], [])
if ((arg... |
class UpdatingVM(VM):
need_update_inputs = False
def __init__(self, fgraph, nodes, thunks, pre_call_clear, storage_map: 'StorageMapType', input_storage: list['StorageCellType'], output_storage: list['StorageCellType'], update_vars: dict[(Variable, Variable)]):
super().__init__(fgraph, nodes, thunks, pre... |
class DHTLocalStorage(TimedStorage[(DHTID, Union[(BinaryDHTValue, DictionaryDHTValue)])]):
def store(self, key: DHTID, value: BinaryDHTValue, expiration_time: DHTExpiration, subkey: Optional[Subkey]=None) -> bool:
if (subkey is not None):
return self.store_subkey(key, subkey, value, expiration_t... |
class SR(IntEnum):
IDTI = (1 << 0)
VBUSTI = (1 << 1)
SRPI = (1 << 2)
VBERRI = (1 << 3)
BCERRI = (1 << 4)
ROLEEXI = (1 << 5)
HNPERRI = (1 << 6)
STOI = (1 << 7)
VBUSRQ = (1 << 9)
ID = (1 << 10)
VBUS = (1 << 11)
SPEED = (3 << 12)
CLKUSABLE = (1 << 14) |
class ModelSection(object):
def __init__(self, model, inp_sections, join_sections=None, rpt_sections=None, columns=None, geomtype='point'):
self.model = model
self.inp = self.model.inp
self.rpt = self.model.rpt
self.inp_sections = inp_sections
self.join_sections = (join_secti... |
class Monitor(Wrapper):
EXT = 'monitor.csv'
f = None
def __init__(self, env, filename, allow_early_resets=False, reset_keywords=(), info_keywords=()):
Wrapper.__init__(self, env=env)
self.tstart = time.time()
self.results_writer = ResultsWriter(filename, header={'t_start': time.time(... |
def get_transform(opt):
transform_list = []
if (opt.resize_or_crop == 'resize_and_crop'):
osize = [opt.loadSize, opt.loadSize]
transform_list.append(transforms.Resize(osize, Image.BICUBIC))
transform_list.append(transforms.RandomCrop(opt.fineSize))
elif (opt.resize_or_crop == 'crop')... |
class MaskRCNNInstanceSegmentationNode(LazyTransport):
def __init__(self):
super().__init__()
self._class_names = morefusion.datasets.ycb_video.class_names
self._blacklist = [5, 10, 12]
self._one_instance_per_class = True
pretrained_model = gdown.cached_download(url=' md5='f1... |
def window_by_position(ds: Dataset, *, size: int, step: Optional[int]=None, offset: int=0, variant_contig: Hashable=variables.variant_contig, variant_position: Hashable=variables.variant_position, window_start_position: Optional[Hashable]=None, merge: bool=True) -> Dataset:
if ((step is not None) and (window_start_... |
class AndroguardImp(BaseApkinfo):
__slots__ = ('apk', 'dalvikvmformat', 'analysis')
def __init__(self, apk_filepath: Union[(str, PathLike)]):
super().__init__(apk_filepath, 'androguard')
if (self.ret_type == 'APK'):
(self.apk, self.dalvikvmformat, self.analysis) = AnalyzeAPK(apk_file... |
class Describe_Column():
def it_provides_access_to_its_cells(self, cells_fixture):
(column, column_idx, expected_cells) = cells_fixture
cells = column.cells
column.table.column_cells.assert_called_once_with(column_idx)
assert (cells == expected_cells)
def it_provides_access_to_th... |
class Statistics():
def __init__(self, data):
self.data = data
self.min_length = 5
self.max_length = 100
self.post_num = 0
self.resp_num = 0
self.err_data = 0
def word_freq(self):
seg = pkuseg.pkuseg(model_name='web')
stopwords = []
text = ... |
class TestDataset(Dataset):
def __init__(self, args, raw_datasets, cache_root):
self.raw_datasets = raw_datasets
self.tab_processor = get_default_processor(max_cell_length=100, tokenizer=AutoTokenizer.from_pretrained(args.bert.location, use_fast=False), max_input_length=args.seq2seq.table_truncation... |
def apply_version_to_source_files(repo: Repo, version_declarations: Iterable[VersionDeclarationABC], version: Version, noop: bool=False) -> list[str]:
working_dir = (os.getcwd() if (repo.working_dir is None) else repo.working_dir)
paths = [str(declaration.path.resolve().relative_to(working_dir)) for declaration... |
_ephem
def test_get_solarposition_method_pyephem(expected_solpos, golden):
times = pd.date_range(datetime.datetime(2003, 10, 17, 13, 30, 30), periods=1, freq='D', tz=golden.tz)
ephem_data = solarposition.get_solarposition(times, golden.latitude, golden.longitude, method='pyephem')
expected_solpos.index = ti... |
class Profiler(object):
def __init__(self, verbose):
super(Profiler, self).__init__()
self.initial = {}
self.verbose = verbose
self.final = OrderedDict()
self.relative_time_percentage = {}
def add_entry(self, dictionary, key, verbose, count):
if (count == verbose)... |
def read_sentence1516_target(file_path, max_offset_len=83):
tk = MosesTokenizer()
with open(file_path, 'rb') as fopen:
raw = fopen.read()
root = etree.fromstring(raw)
for review_xml in root:
sentences_xml = review_xml.find('sentences')
for sentence_xml in sentence... |
class RootEventHandler(EventTarget):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._click_tracker = {}
self._target_tracker = {}
def dispatch_event(self, event: Event):
pointer_id = getattr(event, 'pointer_id', None)
if ((pointer_id is not No... |
class Env(object):
def __new__(cls, *args, **kwargs):
env = super(Env, cls).__new__(cls)
env._env_closer_id = env_closer.register(env)
env._closed = False
env._configured = False
env._unwrapped = None
env.spec = None
return env
metadata = {'render.modes': ... |
def _infer_column(data) -> Union[(ta.BaseColumn, Unresolved, None)]:
if (data is None):
return None
assert isinstance(data, list)
non_null_item = next((item for item in data if (item is not None)), None)
if (non_null_item is None):
return Unresolved()
elif isinstance(non_null_item, l... |
def load_tf2_checkpoint_in_pytorch_model(pt_model, tf_checkpoint_path, tf_inputs=None, allow_missing_keys=False):
try:
import tensorflow as tf
import torch
except ImportError:
logger.error('Loading a TensorFlow model in PyTorch, requires both PyTorch and TensorFlow to be installed. Pleas... |
class BluezAgentManagerAPI(ABC):
name = 'org.bluez'
interface = 'org.bluez.AgentManager1'
path = ObjPath('/org/bluez')
def connect(cls) -> 'BluezAgentManagerAPI':
return cast(BluezAgentManagerAPI, SystemBus().get_proxy(cls.name, cls.path))
def RegisterAgent(self, agent: ObjPath, capability: ... |
class LookupTest(resources.SysPathSetup, unittest.TestCase):
def setUp(self) -> None:
super().setUp()
self.module = resources.build_file('data/module.py', 'data.module')
self.module2 = resources.build_file('data/module2.py', 'data.module2')
self.nonregr = resources.build_file('data/n... |
def handler(ql: Qiling):
ah = ql.arch.regs.ah
leaffunc = {2: __leaf_02, 6: __leaf_02, 9: __leaf_09, 12: __leaf_0c, 37: __leaf_25, 38: __leaf_26, 48: __leaf_30, 51: __leaf_33, 53: __leaf_35, 60: __leaf_3c, 61: __leaf_3d, 62: __leaf_3e, 63: __leaf_3f, 64: __leaf_40, 65: __leaf_41, 67: __leaf_43, 76: __leaf_4c}.ge... |
def pytest_generate_tests(metafunc: Metafunc) -> None:
related: list[str] = []
for arg2fixturedef in metafunc._arg2fixturedefs.values():
fixturedef = arg2fixturedef[(- 1)]
related_fixtures = getattr(fixturedef.func, '_factoryboy_related', [])
related.extend(related_fixtures)
metafunc... |
class HNCMTrainer(object):
def __init__(self, args, model, criterion):
self.args = args
self.model = model
self.criterion = criterion
self.optimizer = torch.optim.Adam(model.parameters(), lr=args.lr, betas=(0.9, 0.999), eps=1e-08, amsgrad=True)
self._num_updates = 0
i... |
class WarmUPScheduler(LRScheduler):
def __init__(self, optimizer, warmup, normal, epochs=50, last_epoch=(- 1)):
warmup = warmup.lr_spaces
normal = normal.lr_spaces
self.lr_spaces = np.concatenate([warmup, normal])
self.start_lr = normal[0]
super(WarmUPScheduler, self).__init_... |
def test_function_complex() -> None:
src = '\n def func(n) -> None:\n return\n for j in range(1, 10):\n continue\n print(j)\n '
cfg = build_cfg(src, is_function=True)
(unreachable, reachable) = extract_blocks(cfg)
assert ({'j', 'range(1, 10)', 'continue', 'print... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.