code stringlengths 281 23.7M |
|---|
def pod_labels(app: AppDef, role_idx: int, role: Role, replica_id: int, coscheduler_name: Optional[str], app_id: str) -> Dict[(str, str)]:
labels = object_labels(app, app_id)
pod_labels = {LABEL_VERSION: torchx.__version__, LABEL_APP_NAME: app.name, LABEL_ROLE_INDEX: str(role_idx), LABEL_ROLE_NAME: role.name, L... |
class GmetricHandler(Handler):
def __init__(self, config=None):
Handler.__init__(self, config)
if (gmetric is None):
logging.error('Failed to load gmetric module')
return
self.socket = None
self.host = self.config['host']
self.port = int(self.config['p... |
def test_dsl_async_cmd_error_throws_with_save_true():
cmd = get_cmd('tests/testfiles/cmds/exitwitherr.sh', 'tests\\testfiles\\cmds\\exitwitherr.bat')
context = Context({'cmds': {'run': cmd, 'save': True}})
step = AsyncCmdStep('blah', context)
with pytest.raises(MultiError):
step.run_step()
o... |
_start_docstrings('The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top.', POOLFORMER_START_DOCSTRING)
class PoolFormerModel(PoolFormerPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.config = config
self.encoder = Poo... |
def create_random_square_matrix(n, is_hermitian=False, min_eival=1.0, max_eival=1.0, minabs_eival=0.0, seed=(- 1)):
dtype = torch.float64
eivals = torch.linspace(min_eival, max_eival, n, dtype=dtype)
idx = (eivals.abs() < minabs_eival)
eivals[idx] = (torch.sign(eivals[idx]) * minabs_eival)
eivals = ... |
def test_compat_runner_args():
cfg = ConfigDict(dict(total_epochs=12))
with pytest.warns(None) as record:
cfg = compat_runner_args(cfg)
assert (len(record) == 1)
assert ('runner' in record.list[0].message.args[0])
assert ('runner' in cfg)
assert (cfg.runner.type == 'EpochBasedRunner')
... |
def check_multilayer_graph_consistency(G_intralayer, G_interlayer, layer_vec, model, m_t, T, N=None, Nt=None):
if (G_intralayer.is_directed() != G_interlayer.is_directed()):
warnings.warn('Intralayer graph is {}, but Interlayer graph is {}.'.format(('directed' if G_intralayer.is_directed() else 'undirected'... |
class Layer_param():
def __init__(self, name='', type='', top=(), bottom=()):
self.param = pb.LayerParameter()
self.name = self.param.name = name
self.type = self.param.type = type
self.top = self.param.top
self.top.extend(top)
self.bottom = self.param.bottom
... |
def perturb_texts(args, texts, mask_model, mask_tokenizer, base_tokenizer, ceil_pct=False):
outputs = []
for i in tqdm(range(0, len(texts), args.chunk_size), desc='Applying perturbations'):
outputs.extend(perturb_texts_(args, texts[i:(i + args.chunk_size)], mask_model, mask_tokenizer, base_tokenizer, ce... |
def test_model_nodes(model):
node = Input(model, 'test')
assert (model.nodes['test'] is node)
with pytest.raises(KeyError):
model.nodes['invalid']
all_nodes = [node for node in model.nodes]
assert (all_nodes == [node])
del model.nodes['test']
all_nodes = [node for node in model.nodes... |
def train(args, sess, epoch, learning_rate_placeholder, phase_train_placeholder, global_step, loss, train_op, summary_op, summary_writer, learning_rate_schedule_file):
batch_number = 0
lr = args.learning_rate
while (batch_number < args.epoch_size):
start_time = time.time()
print('Running for... |
def test_dsl_async_cmd_dict_input_sequence_with_cwd_interpolate():
if is_windows:
cmd = cmd_path.joinpath('pwd.bat').as_posix()
else:
cmd = 'testfiles/cmds/pwd.sh'
context = Context({'k1': 'tests', 'cmds': {'run': cmd, 'save': True, 'cwd': '{k1}'}})
step = AsyncCmdStep('blah', context)
... |
def get_pca_latent(args, latents, text, degrees, exp_name):
save_dir = 'text_pca/'
if (not os.path.exists(save_dir)):
os.makedirs(save_dir, exist_ok=True)
text_latents = []
new_latents = [torch.zeros_like(l) for l in latents]
for i in range(latents[0].shape[0]):
new_tensor = torch.ze... |
class ServiceKey(namedtuple('ServiceKey', ['name', 'kid', 'service', 'jwk', 'metadata', 'created_date', 'expiration_date', 'rotation_duration', 'approval'])):
def to_dict(self):
return {'name': self.name, 'kid': self.kid, 'service': self.service, 'jwk': self.jwk, 'metadata': self.metadata, 'created_date': s... |
def screening_cost_analyzer(cost_miss_case, cost_false_pos, prevalence, sensitivity, specificity, population=10000, decimal=3):
warnings.warn('NOTE: When calculating costs, be sure to consult experts in health policy or related fields. Costs should encompass more than only monetary costs, like relative costs (regre... |
def _blas_info():
config = np.__config__
if hasattr(config, 'blas_ilp64_opt_info'):
blas_info = config.blas_ilp64_opt_info
elif hasattr(config, 'blas_opt_info'):
blas_info = config.blas_opt_info
else:
blas_info = {}
def _in_libaries(name):
return any(((name in lib) fo... |
class TestTurnBattleMagicFunc(EvenniaTest):
def setUp(self):
super(TestTurnBattleMagicFunc, self).setUp()
self.testroom = create_object(DefaultRoom, key='Test Room')
self.attacker = create_object(tb_magic.TBMagicCharacter, key='Attacker', location=self.testroom)
self.defender = creat... |
class Parser():
auto_post_parse = True
def __init__(self, file_name, strict=False, encoding='utf-8'):
self.file_name = Path(file_name).resolve()
self.strict = strict
self.encoding = encoding
self.dir = Path(file_name).parent
self.dispatcher = self._build_dispatch_map()
... |
class TestCallbacks(KazooTestCase):
def test_async_result_callbacks_are_always_called(self):
callback_mock = Mock()
async_result = self.client.handler.async_result()
async_result.rawlink(callback_mock)
self.client.stop()
async_result.set_exception(Exception('Anything that thr... |
class bytes():
def __init__(self) -> None:
...
def __init__(self, x: object) -> None:
...
def __add__(self, x: bytes) -> bytes:
...
def __mul__(self, x: int) -> bytes:
...
def __rmul__(self, x: int) -> bytes:
...
def __eq__(self, x: object) -> bool:
... |
.parametrize('repo, commit_parser, translator, commit_messages,prerelease, expected_new_version', xdist_sort_hack([(lazy_fixture(repo_fixture_name), lazy_fixture(parser_fixture_name), translator, commit_messages, prerelease, expected_new_version) for ((repo_fixture_name, parser_fixture_name, translator), values) in {('... |
def compute_labels_xs(font_scale: float, text_sizes: List[OpenCVTextSizes]) -> List[int]:
label_widths = np.array([t[0][0] for t in text_sizes])
relative_shifts = np.insert(label_widths[:(- 1)], 0, 0)
relative_shifts_with_gaps = (relative_shifts + (font_scale * LABEL_TEXT_RELATIVE_GAP_X))
label_shifts =... |
def _update_incomplete_dict(self_val: Value, pairs: Sequence[KVPair], ctx: CallContext, varname: Optional[VarnameWithOrigin]) -> ImplReturn:
self_pairs = kv_pairs_from_mapping(self_val, ctx.visitor)
if isinstance(self_pairs, CanAssignError):
ctx.show_error('self is not a mapping', arg='self', detail=str... |
def _get_files(*, verbose: bool, ignored: List[pathlib.Path]=None) -> Iterator[pathlib.Path]:
filenames = subprocess.run(['git', 'ls-files', '--cached', '--others', '--exclude-standard', '-z'], stdout=subprocess.PIPE, text=True, check=True)
all_ignored = (ignored or [])
all_ignored.append(pathlib.Path('test... |
def restoreVariableFromDisk(name):
logging.info('Recovering variable...')
t0 = time()
val = None
with open(((folder_pickles + name) + '.pickle'), 'rb') as handle:
val = pickle.load(handle)
t1 = time()
logging.info('Variable recovered. Time: {}m'.format(((t1 - t0) / 60)))
return val |
class MeanInterbuildingDistance():
def __init__(self, gdf, spatial_weights, unique_id, order=3, verbose=True):
self.gdf = gdf
self.sw = spatial_weights
self.id = gdf[unique_id]
data = gdf.set_index(unique_id).geometry
results_list = []
adj_list = spatial_weights.to_ad... |
class Cell(nn.Module):
def __init__(self, steps, multiplier, C_prev_prev, C_prev, C, reduction, reduction_prev):
super(Cell, self).__init__()
self.reduction = reduction
self.primitives = self.PRIMITIVES[('primitives_reduct' if reduction else 'primitives_normal')]
if reduction_prev:
... |
class TestLowRankCrossNet(unittest.TestCase):
def test_cross_net_numercial_forward(self) -> None:
torch.manual_seed(0)
batch_size = 3
num_layers = 20
in_features = 2
input = torch.randn(batch_size, in_features)
dcn = LowRankCrossNet(in_features=in_features, num_layers... |
def simxReadVisionSensor(clientID, sensorHandle, operationMode):
detectionState = ct.c_ubyte()
auxValues = ct.POINTER(ct.c_float)()
auxValuesCount = ct.POINTER(ct.c_int)()
ret = c_ReadVisionSensor(clientID, sensorHandle, ct.byref(detectionState), ct.byref(auxValues), ct.byref(auxValuesCount), operationM... |
def bravyi_kitaev_tree(operator, n_qubits=None):
from openfermion.utils import count_qubits
if (n_qubits is None):
n_qubits = count_qubits(operator)
if (n_qubits < count_qubits(operator)):
raise ValueError('Invalid number of qubits specified.')
fenwick_tree = FenwickTree(n_qubits)
tr... |
class Solution(object):
def numIslands2(self, m, n, positions):
ans = []
islands = Union()
for p in map(tuple, positions):
islands.add(p)
for dp in ((0, 1), (0, (- 1)), (1, 0), ((- 1), 0)):
q = ((p[0] + dp[0]), (p[1] + dp[1]))
if (q in ... |
def main(config):
assert (config.num_neighbors == (- 1)), 'KNN features is deprecated due to PrepWrap'
model = ResidualGatedGCNModel(config, dtypeFloat, dtypeLong)
if (('sparse' in config) and (config.sparse is not None)):
model = wrap_sparse(model, config.sparse)
model = PrepWrapResidualGatedGC... |
def test_session_env_lazy_with_nested_env(monkeypatch, gdalenv):
monkeypatch.setenv('AWS_ACCESS_KEY_ID', 'id')
monkeypatch.setenv('AWS_SECRET_ACCESS_KEY', 'key')
monkeypatch.setenv('AWS_SESSION_TOKEN', 'token')
expected = {'AWS_ACCESS_KEY_ID': 'id', 'AWS_SECRET_ACCESS_KEY': 'key', 'AWS_SESSION_TOKEN': '... |
.parametrize('ndim,dims,valid', [(1, ('dim0',), True), (1, ({'dim0', 'dim1'},), True), (2, ({'dim0', 'dim1'}, 'dim2'), True), ({1, 2}, ({'dim0', None}, 'dim1'), True), (2, ('dim0',), False), ({1, 2}, ({'dim0', 'dim1'},), False), ({1, 2}, ({'dim0', 'dim1'}, 'dim2'), False), (2, ({'dim0', None}, 'dim1'), False)])
def tes... |
class VOCAugDataset(BaseDataSet):
def __init__(self, **kwargs):
self.num_classes = 21
self.palette = palette.get_voc_palette(self.num_classes)
super(VOCAugDataset, self).__init__(**kwargs)
def _set_files(self):
self.root = os.path.join(self.root, 'VOCdevkit/VOC2012')
file... |
def SDEActWrapper(layer):
(init_fn, apply_fn) = layer
def apply_fun(params, inputs, rng, **kwargs):
(preds, postw, postkl, priorx, priorw, priorkl) = inputs
preds = apply_fn(params, preds, **kwargs)
return (preds, postw, postkl, priorx, priorw, priorkl)
return (init_fn, apply_fun) |
def stc_curve(tl):
ref_curve = np.array([0, 3, 6, 9, 12, 15, 16, 17, 18, 19, 20, 20, 20, 20, 20, 20])
top_curve = ref_curve
res_sum = 0
while True:
diff = (tl - top_curve)
residuals = np.clip(diff, np.min(diff), 0)
res_sum = np.sum(residuals)
if (res_sum < (- 32)):
... |
def test_sentence_argument_errors(capsys):
def foo(step, foo, bar):
pass
steps = {re.compile('What (.*?) can (.*)'): foo}
config = [{'sentence': 'What FOO can BAR', 'should_match': 'foo', 'with_arguments': [{'foo': 'foooooooo'}, {'bar': 'baaaaaaar'}]}]
expected_returncode = (1, 0)
actual_ret... |
class AppStateMixin():
def __init__(self) -> None:
self._modules: Dict[(str, torch.nn.Module)] = {}
self._optimizers: Dict[(str, torch.optim.Optimizer)] = {}
self._lr_schedulers: Dict[(str, TLRScheduler)] = {}
self._progress: Dict[(str, Progress)] = {}
self._misc_statefuls: D... |
def do_check(squirrel, codes=None, tmin=None, tmax=None, time=None, ignore=[]):
codes_set = set()
for kind in ['waveform', 'channel', 'response']:
if (codes is not None):
codes_pat = codes_patterns_for_kind(to_kind_id(kind), codes)
else:
codes_pat = None
codes_fil... |
def test_is_transaction_effect_satisfied(chain_state, token_network_address, netting_channel_state):
canonical_identifier = netting_channel_state.canonical_identifier
assert (token_network_address == canonical_identifier.token_network_address)
transaction = ContractSendChannelBatchUnlock(canonical_identifie... |
class V2VNet(nn.Module):
def __init__(self, input_channels, output_channels):
super(V2VNet, self).__init__()
self.front_layers = nn.Sequential(Basic3DBlock(input_channels, 16, 7), Res3DBlock(16, 32))
self.encoder_decoder = EncoderDecorder()
self.output_layer = nn.Conv3d(32, output_ch... |
class TPLVarHandler(BaseHandler):
async def get(self, tplid):
user = self.current_user
tpl = (await self.db.tpl.get(tplid, fields=('id', 'note', 'userid', 'sitename', 'siteurl', 'variables', 'init_env')))
if (not self.permission(tpl)):
self.evil((+ 5))
(await self.fin... |
def get_path_from_template(path_template: str, path_type: PathType=PathType.AUTO) -> str:
if (path_type == PathType.AUTO):
if (platform.system() == 'Windows'):
path_type = PathType.WINDOWS
elif (platform.system() == 'Linux'):
path_type = PathType.LINUX
else:
... |
class _TPattern(TestCase):
def setUp(self):
s1 = {'tracknumber': '5/6', 'artist': 'Artist', 'title': 'Title5', '~filename': '/path/to/a.mp3', 'xmltest': '<&>'}
s2 = {'tracknumber': '6', 'artist': 'Artist', 'title': 'Title6', '~filename': '/path/to/b.ogg', 'discnumber': '2', 'unislash': 'foo/bar'}
... |
def extract_reactions(reaction_dataset) -> typing.Tuple[(typing.List[Reaction], typing.Set[str], dict)]:
reactions = []
logger.debug('Extracting reactions')
run_through_stats = dict(num_skipped_due_to_multiple_products=0, num_multiple_same_reactants=0, num_multiple_same_products=0, num_overlap_between_react... |
def run_cmdline(*args, **kwds):
saved_stdin = sys.stdin
saved_stdout = sys.stdout
saved_stderr = sys.stderr
stdin_buffer = BytesIO()
stdout_buffer = BytesIO()
stderr_buffer = BytesIO()
new_stdin = sys.stdin = io.TextIOWrapper(stdin_buffer, 'utf-8')
new_stdout = sys.stdout = io.TextIOWrap... |
def login_with_guest(sa: ServerApp, encrypted_login_request: bytes):
if (sa.guest_encrypt is None):
raise error.NotAuthorizedForActionError
try:
login_request_bytes = sa.guest_encrypt.decrypt(encrypted_login_request)
except cryptography.fernet.InvalidToken:
raise error.NotAuthorizedF... |
def mk_TestStructuralTranslator(_StructuralTranslator):
def make_indent(src, nindent):
indent = ' '
for (idx, s) in enumerate(src):
src[idx] = ((nindent * indent) + s)
def get_string(obj):
if isinstance(obj, type):
return obj.__name__
return str(obj)
... |
class Scenario(ScenarioGenerator):
def __init__(self):
ScenarioGenerator.__init__(self)
self.naming = 'numerical'
def road(self, **kwargs):
road = xodr.create_road([xodr.Spiral(1e-10, kwargs['road_curvature'], 100), xodr.Arc(kwargs['road_curvature'], 50), xodr.Spiral(kwargs['road_curvatu... |
class LightningBaseModel(pl.LightningModule):
def __init__(self, args):
super().__init__()
self.args = args
self.train_acc = Accuracy()
self.val_acc = Accuracy(compute_on_step=False)
self.val_iou = IoU(self.args['dataset_params'], compute_on_step=False)
if self.args['... |
def test_create_legacy_questions(db, settings):
Catalog.objects.all().delete()
Section.objects.all().delete()
Page.objects.all().delete()
QuestionSet.objects.all().delete()
Question.objects.all().delete()
xml_file = ((((Path(settings.BASE_DIR) / 'xml') / 'elements') / 'legacy') / 'questions.xml'... |
class Spiral(XodrBase):
def __init__(self, curvstart, curvend, length=None, angle=None, cdot=None):
super().__init__()
self.curvstart = curvstart
self.curvend = curvend
if ((length == None) and (angle == None) and (cdot == None)):
raise NotEnoughInputArguments('Spiral is ... |
.parametrize('username,password', users)
.parametrize('project_id', projects)
def test_create(db, client, files, username, password, project_id):
client.login(username=username, password=password)
project = Project.objects.get(id=project_id)
snapshot_count = project.snapshots.count()
values_count = proj... |
def exec_cmd_in_pod(cli, command, pod_name, namespace, container=None):
exec_command = command
try:
if container:
ret = stream(cli.connect_get_namespaced_pod_exec, pod_name, namespace, container=container, command=exec_command, stderr=True, stdin=False, stdout=True, tty=False)
else:
... |
class ImageContainerBilinear(ImageContainer):
def __init__(self, image_data, geo_def, radius_of_influence, epsilon=0, fill_value=0, reduce_data=False, nprocs=1, segments=None, neighbours=32):
super(ImageContainerBilinear, self).__init__(image_data, geo_def, fill_value=fill_value, nprocs=nprocs)
self... |
class BaseNetworkError(Exception):
def human_readable_name(cls) -> str:
return cls.__name__
def code(cls):
return NotImplementedError()
def detail(self):
return None
def as_json(self) -> dict:
return {'error': {'code': self.code(), 'detail': self.detail}}
def from_det... |
def query_execute_wrapper(db_conn, query_string=None, query_list=None, max_tries=3, no_return=True):
for i in range(0, max_tries):
try:
with db_conn:
if (query_list is None):
curs = db_conn.execute(query_string)
else:
curs =... |
class LEBertModel(BertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.config = config
self.embeddings = BertEmbeddings(config)
self.encoder = BertEncoder(config)
self.pooler = BertPooler(config)
self.init_weights()
def get_input_embeddi... |
class AnimOsdPrefs(Gtk.VBox):
def __init__(self, plugin):
super().__init__(spacing=6)
self.Conf = plugin.Conf
self.plugin = plugin
def __coltofloat(x):
return (x / 65535.0)
def __floattocol(x):
return int((x * 65535))
def show_preview():
... |
class AEADCipher(BaseCipher):
PACKET_LIMIT = ((16 * 1024) - 1)
def setup_iv(self, iv=None):
self.iv = (os.urandom(self.IV_LENGTH) if (iv is None) else iv)
randkey = hmac.new(self.iv, self.key, hashlib.sha1).digest()
blocks_needed = (((self.KEY_LENGTH + len(randkey)) - 1) // len(randkey))... |
def main(argv):
parser = optparse.OptionParser(add_help_option=False)
parser.disable_interspersed_args()
parser.add_option('-?', '--help', dest='help', action='store_true', default=None, help='print help')
parser.add_option('-t', dest='t', action='store', default=None)
(opts, argv_rest) = parser.par... |
def setUpModule():
global h2o, h2o_scanner, o2, o2_scanner
h2o = gto.M(verbose=3, output='/dev/null', atom='O -2. -15. -14.\n H -2. -14. -15.\n H -2. -16. -15.', basis='def2-svp')
h2o_scanner = scf.RHF(h2o)
h2o_scanner.build()
h2o_scann... |
class MLP(nn.Module):
def __init__(self, *, d_in: int, d_layers: ty.List[int], dropout: float, d_out: int, categories: ty.Optional[ty.List[int]], d_embedding: int) -> None:
super().__init__()
if (categories is not None):
d_in += (len(categories) * d_embedding)
category_offset... |
def prepare_test(plugin_name, code, tagname='', html='', template=HTML_TEMPLATE_WITH_TAG):
def dec(f):
def _inner(self, *args, **kws):
self.writefile(f'{plugin_name}.py', code)
page_html = template.format(plugin_name=plugin_name, tagname=tagname, html=html)
self.pyscript_... |
def create_network(n_dense=6, dense_units=16, activation='selu', dropout=AlphaDropout, dropout_rate=0.1, kernel_initializer='lecun_normal', optimizer='adam', num_classes=1, max_words=max_words):
model = Sequential()
model.add(Dense(dense_units, input_shape=(max_words,), kernel_initializer=kernel_initializer))
... |
class FC3_TestCase(CommandTest):
command = 'xconfig'
def runTest(self):
if ('--card' in self.optionList):
self.assert_parse('xconfig --card=cardA --hsync=H --vsync=V --monitor=monitorA --noprobe', 'xconfig --card=cardA --hsync=H --monitor=monitorA --noprobe --vsync=V\n')
if ('--dept... |
def decompress_and_load(key: str, serialized: bytes, flags: int) -> Any:
if (flags & Flags.ZLIB):
serialized = zlib.decompress(serialized)
flags ^= Flags.ZLIB
if (flags == 0):
return serialized
if (flags in (Flags.INTEGER, Flags.LONG)):
return int(serialized)
if (flags ==... |
class SysCapture(SysCaptureBinary):
EMPTY_BUFFER = ''
def snap(self) -> str:
res = self.tmpfile.getvalue()
self.tmpfile.seek(0)
self.tmpfile.truncate()
return res
def writeorg(self, data: str) -> None:
self._assert_state('writeorg', ('started', 'suspended'))
s... |
class Trainer(DefaultTrainer):
def build_evaluator(cls, cfg, dataset_name, output_folder=None):
if (output_folder is None):
output_folder = os.path.join(cfg.OUTPUT_DIR, 'inference')
evaluator_list = []
evaluator_type = MetadataCatalog.get(dataset_name).evaluator_type
if (... |
def construct_noise_model(network: Union[(Network_DQNN, Network_QAOA)]) -> None:
provider = training.get_provider()
backend = provider.get_backend('ibmq_16_melbourne')
network.coupling_map = backend.configuration().coupling_map
noise_model = noise.NoiseModel(['cx', 'rz', 'sx', 'x'])
for (gate, value... |
def Ck(input, k, slope=0.2, stride=2, reuse=False, norm='instance', is_training=True, name=None, sn=False):
with tf.variable_scope(name, reuse=reuse):
weights = _weights('weights', shape=[4, 4, 4, input.get_shape()[4], k])
if sn:
conv = tf.nn.conv3d(input, spectral_norm(weights), strides... |
def arg(name, type=None, help=None, nargs=None, mapper=None, choices=None, prefix=True):
def wrap(fn):
assert (fn.__name__ == '__init__')
if (not hasattr(fn, '_autoargs_info')):
fn._autoargs_info = dict()
fn._autoargs_info[name] = dict(type=type, help=help, nargs=nargs, choices=c... |
class Dimensions(VersionBase):
def __init__(self, width, length, height):
self.width = convert_float(width)
self.length = convert_float(length)
self.height = convert_float(height)
def parse(element):
width = convert_float(element.attrib['width'])
height = convert_float(el... |
class Link(object):
def __init__(self, model, linkid):
if (not model.fileLoaded):
raise PYSWMMException('SWMM Model Not Open')
if (linkid not in model.getObjectIDList(ObjectType.LINK.value)):
raise PYSWMMException('ID Not valid')
self._model = model
self._link... |
class UnmarshallingProcessor(UnmarshallingIntegration[(RequestType, ResponseType)]):
def handle_request(self, request: RequestType, valid_handler: ValidRequestHandlerCallable[ResponseType], errors_handler: ErrorsHandlerCallable[ResponseType]) -> ResponseType:
request_unmarshal_result = self.unmarshal_reques... |
.parametrize('ident', ('.', '...', ':::', 'a:::c', 'a+-b', '\\nhe\\\\l\\lo\\n\\t\\rbye', 'a/b', '', 'aacc', 'a[bcd]', '1234', '1234abcd', '1234and', 'notandor', 'not_and_or', 'not[and]or', '1234+5678', '123.232', 'True', 'False', 'None', 'if', 'else', 'while'))
def test_valid_idents(ident: str) -> None:
assert eval... |
def bech32_decode(bech, ignore_long_length=False):
if (any((((ord(x) < 33) or (ord(x) > 126)) for x in bech)) or ((bech.lower() != bech) and (bech.upper() != bech))):
return (None, None)
bech = bech.lower()
pos = bech.rfind('1')
if ((pos < 1) or ((pos + 7) > len(bech)) or ((not ignore_long_lengt... |
def tensorboard(logdir: str, image: str=torchx.IMAGE, timeout: float=(60 * 60), port: int=6006, start_on_file: str='', exit_on_file: str='') -> specs.AppDef:
return specs.AppDef(name='tensorboard', roles=[specs.Role(name='tensorboard', image=image, entrypoint='python', args=['-m', 'torchx.apps.utils.process_monitor... |
class TestWMS(unittest.TestCase):
def setUp(self):
pass
def test_WMS_OSM(self):
try:
m = Maps(Maps.CRS.GOOGLE_MERCATOR)
m.add_wms.OpenStreetMap.add_layer.default()
plt.close(m.f)
except requests.exceptions.ConnectionError:
warnings.warn('En... |
class Optimizer(object):
def __init__(self, method, learning_rate, learning_rate2, max_grad_norm, lr_decay=1, start_decay_steps=None, decay_steps=None, beta1=0.9, beta2=0.999, adagrad_accum=0.0, decay_method=None, warmup_steps=4000, warmup_steps2=4000, model_size=None):
self.last_ppl = None
self.lea... |
class Logger(object):
DEFAULT = None
CURRENT = None
def __init__(self, dir, output_formats):
self.name2val = defaultdict(float)
self.name2cnt = defaultdict(int)
self.level = INFO
self.dir = dir
self.output_formats = output_formats
def logkv(self, key, val):
... |
def test_ki_protection_works() -> None:
async def sleeper(name: str, record: set[str]) -> None:
try:
while True:
(await _core.checkpoint())
except _core.Cancelled:
record.add((name + ' ok'))
async def raiser(name: str, record: set[str]) -> None:
tr... |
class PlatiPyClient():
def __init__(self, host, port, api_key, algorithm_name, verify=None):
protocol = '
if (verify is None):
logger.warning('Running without SSL. Not Suitable for Production.')
protocol = '
elif (not os.path.exists(verify)):
raise FileNot... |
def parse_hp_block_header(block: Union[(bytes, bytearray)], is_big_endian: bool, length_before_block: Optional[int]=None, raise_on_late_block: bool=False) -> Tuple[(int, int)]:
begin = block.find(b'#A')
if (begin < 0):
raise ValueError(('Could not find the standard block header (#A) indicating the start... |
.parametrize('nelec, nx', ((2, 10), (6, 8), (8, 12)))
def test_potential_bloq(nelec, nx):
ngrid_x = ((2 * nx) + 1)
bitsize = ((ngrid_x - 1).bit_length() + 1)
poly_bitsize = 15
pe = PotentialEnergy(nelec, ngrid_x)
qlt_testing.assert_valid_bloq_decomposition(pe)
poly_coeffs = get_inverse_square_ro... |
class AwaitLayer(MergeLayer):
def __init__(self, incoming, layer_to_await, **kwargs):
super(AwaitLayer, self).__init__([incoming, layer_to_await], **kwargs)
def get_output_for(self, inputs, **kwargs):
return inputs[0]
def get_output_shape_for(self, input_shapes, **kwargs):
return inp... |
class lmdbDataset(Dataset):
def __init__(self, root=None, transform=None, target_transform=None):
self.env = lmdb.open(root, max_readers=1, readonly=True, lock=False, readahead=False, meminit=False)
if (not self.env):
print(('cannot creat lmdb from %s' % root))
sys.exit(0)
... |
class DummyConnection():
description_format = 'DummyConnection<>'
def __init__(self, **kwargs):
self.kwargs = kwargs
self.pid = os.getpid()
def connect(self):
pass
def can_read(self):
return False
def send_command(self, command):
pass
def read_response(sel... |
def compute_dense_reward(self, action: np.ndarray):
reward = 0
ee_coords = np.array(self.robot.get_ee_coords())
handle_pcd = self.cabinet.handle.get_world_pcd()
dist_ees_to_handle = sdist.cdist(ee_coords.reshape((- 1), 3), handle_pcd)
dist_ees_to_handle = dist_ees_to_handle.min(0)
dist_ee_to_han... |
class GateSetBasis():
def __init__(self, name: str, gates: Dict[(str, Union[(Callable, Gate)])], spam: Dict[(str, Tuple[str])]):
self.name = name
self.gate_labels = list(gates.keys())
self.gates = gates
self.gate_matrices = {name: np.real(self._gate_matrix(gate)) for (name, gate) in ... |
(bdd.parsers.parse('I setup a fake editor replacing "{text}" by "{replacement}"'))
def set_up_editor_replacement(quteproc, server, tmpdir, text, replacement):
text = text.replace('(port)', str(server.port))
script = (tmpdir / 'script.py')
script.write(textwrap.dedent('\n import sys\n\n with op... |
class MainWindow(TemplateBaseClass):
def __init__(self):
TemplateBaseClass.__init__(self)
self.setWindowTitle('pyqtgraph example: Qt Designer')
self.ui = WindowTemplate()
self.ui.setupUi(self)
self.ui.plotBtn.clicked.connect(self.plot)
self.show()
def plot(self):
... |
class TFDistributionGaussianDiag(TFDistribution):
class StdType(Enum):
Default = 0
Constant = 1
Variable = 2
def identity(dim, name='identity'):
mean = np.zeros(dim)
logstd = np.zeros(dim)
dist = TFDistributionGaussianDiag(input=None, dim=dim, std_type=TFDistribut... |
_metaclass(ABCMeta)
class SecurityScannerAPIInterface(object):
def state(self):
pass
def index(self, manifest, layers):
pass
def index_report(self, manifest_hash):
pass
def vulnerability_report(self, manifest_hash):
pass
def retrieve_notification_page(self, notificati... |
def convert_loras_to_safeloras_with_embeds(modelmap: Dict[(str, Tuple[(str, Set[str], int)])]={}, embeds: Dict[(str, torch.Tensor)]={}, outpath='./lora.safetensors'):
weights = {}
metadata = {}
for (name, (path, target_replace_module, r)) in modelmap.items():
metadata[name] = json.dumps(list(target_... |
class TestReturn(TestNameCheckVisitorBase):
_passes()
def test_type_inference(self):
from asynq import async_proxy, AsyncTask, asynq, ConstFuture, FutureBase
def returns_3():
return 3
(pure=True)
def pure_async_fn():
return 4
()
def async_f... |
def test_compose_1():
transform = tta.Compose([tta.HorizontalFlip(), tta.VerticalFlip(), tta.Rotate90(angles=[0, 90, 180, 270]), tta.Scale(scales=[1, 2, 4], interpolation='nearest')])
assert (len(transform) == (((2 * 2) * 4) * 3))
dummy_label = torch.ones(2).reshape(2, 1).float()
dummy_image = torch.ara... |
def main():
Format()
(ex, ey, ez) = MV.setup('e*x|y|z')
A = MV('A', 'mv')
print('\\bm{A} =', A)
A.Fmt(2, '\\bm{A}')
A.Fmt(3, '\\bm{A}')
X = (x, y, z) = symbols('x y z')
(ex, ey, ez, grad) = MV.setup('e_x e_y e_z', metric='[1,1,1]', coords=X)
f = MV('f', 'scalar', fct=True)
A = MV... |
class VGGNet(nn.Module):
def __init__(self):
super(VGGNet, self).__init__()
def _initialize_weights(self, mode='fan_in'):
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode=mode, nonlinearity='relu')
if (m.bias... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.