code stringlengths 281 23.7M |
|---|
def get_split_enum(split):
if (split == TRAIN_SPLIT):
split_enum = learning_spec.Split.TRAIN
elif (split == VALID_SPLIT):
split_enum = learning_spec.Split.VALID
elif (split == TEST_SPLIT):
split_enum = learning_spec.Split.TEST
else:
raise UnexpectedSplitError(split)
r... |
class IncrValueModular(Component):
def construct(s):
s.in_ = InPort(Bits8)
s.out = OutPort(Bits8)
s.buf1 = Wire(Bits8)
s.buf2 = Wire(Bits8)
connect(s.in_, s.buf1)
s.out //= s.buf2
def upB():
s.buf2 = (s.buf1 + b8(1))
def line_trace(s):
... |
def open_mmpa_writer(destination, format, title, fragment_options, fragment_index, index_options, properties, environment_cache):
from . import index_writers
return index_writers.open_mmpa_writer(destination=destination, format=format, title=title, fragment_options=fragment_options, fragment_index=fragment_inde... |
class TestExceptions():
def test_listen_error(self, qlocalserver):
qlocalserver.listen(None)
exc = ipc.ListenError(qlocalserver)
assert (exc.code == QAbstractSocket.SocketError.HostNotFoundError)
assert (exc.message == 'QLocalServer::listen: Name error')
msg = 'Error while li... |
class Effect6426(BaseEffect):
type = ('active', 'projected')
def handler(fit, module, context, projectionRange, **kwargs):
if ('projected' not in context):
return
if fit.ship.getModifiedItemAttr('disallowOffensiveModifiers'):
return
appliedBoost = (module.getModif... |
def process(output_dir, wav_files, train_dir, test_dir, num_workers):
executor = ProcessPoolExecutor(max_workers=num_workers)
results = []
names = []
random.shuffle(wav_files)
train_num = int((len(wav_files) * train_rate))
for wav_file in wav_files[0:train_num]:
fid = os.path.basename(wa... |
def test_envget_pass_with_substitutions():
os.environ['ARB_DELETE_ME1'] = 'arb value from $ENV ARB_DELETE_ME1'
context = Context({'key1': 'value1', 'key2': 'value2', 'env_val1': 'ARB_DELETE_ME1', 'env_val2': 'ARB_DELETE_ME2', 'default_val': 'blah', 'key_val': 'key3', 'envGet': [{'env': '{env_val1}', 'key': '{ke... |
class UNet(nn.Module):
def __init__(self, num_classes, input_channels=3, **kwargs):
super().__init__()
nb_filter = [32, 64, 128, 256, 512]
self.pool = nn.MaxPool2d(2, 2)
self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
self.conv0_0 = VGGBlock(input_c... |
def test_verify_is_single_image():
single_image = torch.zeros(1, 1, 1)
image_.verify_is_single_image(single_image)
for dtype in (torch.uint8, torch.int):
with pytest.raises(TypeError):
image = single_image.clone().to(dtype)
image_.verify_is_single_image(image)
for dim in ... |
def bind_socket(endpoint: EndpointConfiguration) -> socket.socket:
sock = socket.socket(endpoint.family, socket.SOCK_STREAM)
flags = fcntl.fcntl(sock.fileno(), fcntl.F_GETFD)
fcntl.fcntl(sock.fileno(), fcntl.F_SETFD, (flags | fcntl.FD_CLOEXEC))
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
... |
_vectorize_node.register(Op)
def vectorize_node_fallback(op: Op, node: Apply, *bached_inputs) -> Apply:
for inp in node.inputs:
if (not isinstance(inp.type, (TensorType, ScalarType))):
raise NotImplementedError(f'Cannot vectorize node {node} with input {inp} of type {inp.type}')
if hasattr(o... |
def get_variant_spec_base(universe, domain, task, policy, algorithm, env_params):
print('get algorithms', algorithm)
algorithm_params = deep_update(env_params, ALGORITHM_PARAMS_PER_DOMAIN.get(domain, {}))
algorithm_params = deep_update(algorithm_params, ALGORITHM_PARAMS_ADDITIONAL.get(algorithm, {}))
va... |
def get_distance(model, sentence_emb, sentences_dict, query, similarity_treshold):
query_embedding = model.encode(query.lower(), show_progress_bar=False)
highlights = []
for sentence in sentences_dict:
sentence_embedding = sentence_emb[sentence]
score = (1 - distance.cosine(sentence_embeddin... |
class SKCImputerABC(SKCTransformerABC):
_skcriteria_abstract_class = True
def _impute(self, matrix):
raise NotImplementedError()
_inherit(SKCTransformerABC._transform_data)
def _transform_data(self, matrix, **kwargs):
imputed_matrix = self._impute(matrix=matrix)
kwargs.update(mat... |
def _limit_font_scale(target_font_scale: float, image_height: int) -> float:
min_font_scale = max((FONT_SCALE_MIN_RELATIVE * image_height), FONT_SCALE_MIN_ABSOLUTE)
max_font_scale = (FONT_SCALE_MAX_RELATIVE * image_height)
return min(max(min_font_scale, target_font_scale), max_font_scale) |
class AbsoluteAxis(Control):
X = 'x'
Y = 'y'
Z = 'z'
RX = 'rx'
RY = 'ry'
RZ = 'rz'
HAT = 'hat'
HAT_X = 'hat_x'
HAT_Y = 'hat_y'
def __init__(self, name, minimum, maximum, raw_name=None, inverted=False):
super().__init__(name, raw_name, inverted)
self.min = minimum
... |
def test_do_class_cleanups_on_success(pytester: Pytester) -> None:
testpath = pytester.makepyfile('\n import unittest\n class MyTestCase(unittest.TestCase):\n values = []\n \n def setUpClass(cls):\n def cleanup():\n cls.values.append(1... |
class GmmRecognizer(Recognizer):
def __init__(self, transition_model, acoustic_model, decoder, symbols=None, allow_partial=True, acoustic_scale=0.1):
if (not isinstance(acoustic_model, _gmm_am.AmDiagGmm)):
raise TypeError('acoustic_model argument should be a diagonal GMM')
self.transitio... |
class GdbExpandVariable(sublime_plugin.TextCommand):
def run(self, edit):
gdb_variables_view.expand_collapse_variable(self.view)
def is_enabled(self):
if (not is_running()):
return False
(row, col) = self.view.rowcol(self.view.sel()[0].a)
if (gdb_variables_view.is_ope... |
class F22_TestCase(CommandTest):
command = 'sshkey'
key = 'ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBJGDmFSzIWSvnFYhExf+FbzSiZxsoohJdrKlmPKQhdts8nSg5PH7jyG5X+w6RgWhSetlD3WouKoo3zFOR5nCYq4= '
def runTest(self):
self.assert_parse(('sshkey --username=root "%s"' % self.key... |
def _dict_get_impl(ctx: CallContext) -> ImplReturn:
default = ctx.vars['default']
def inner(key: Value) -> Value:
self_value = ctx.vars['self']
if isinstance(self_value, AnnotatedValue):
self_value = self_value.value
if (not _check_dict_key_hashability(key, ctx, 'k')):
... |
def test_replica_get_size(config):
try:
cfg = config()
replica_url = cfg.replica_url
tmp_dir = '/tmp/'
with open((tmp_dir + TEMP_FILENAME), 'wb') as f:
f.write(('x' * (FILE_SIZE * pow(2, 20))))
_ = rs.replica.LogicalDirectory(replica_url)
myfile = rs.repli... |
class MajoranaOperator():
def __init__(self, term=None, coefficient=1.0):
self.terms = {}
if (term is not None):
(term, parity) = _sort_majorana_term(term)
self.terms[term] = (coefficient * ((- 1) ** parity))
def from_dict(terms):
op = MajoranaOperator()
o... |
class AttentionQAWithYesNo(MultipleContextModel):
def __init__(self, encoder: QuestionsAndParagraphsEncoder, word_embed: Optional[WordEmbedder], char_embed: Optional[CharWordEmbedder], embed_mapper: Optional[Union[(SequenceMapper, ElmoWrapper)]], question_mapper: Optional[SequenceMapper], context_mapper: Optional[S... |
class HardExampleMinerTest(tf.test.TestCase):
def testHardMiningWithSingleLossType(self):
location_losses = tf.constant([[100, 90, 80, 0], [0, 1, 2, 3]], tf.float32)
cls_losses = tf.constant([[0, 10, 50, 110], [9, 6, 3, 0]], tf.float32)
box_corners = tf.constant([[0.1, 0.1, 0.9, 0.9], [0.1, ... |
class AssignTypeNode(NodeNG):
def assign_type(self):
return self
def _get_filtered_stmts(self, lookup_node, node, _stmts, mystmt: (Statement | None)):
if (self is mystmt):
return (_stmts, True)
if (self.statement() is mystmt):
return ([node], True)
return ... |
def test_alive_gc_multi_derived(capture):
class Derived(m.Parent, m.Child):
def __init__(self):
m.Parent.__init__(self)
m.Child.__init__(self)
n_inst = ConstructorStats.detail_reg_inst()
p = Derived()
p.addChildKeepAlive(m.Child())
assert (ConstructorStats.detail_reg_... |
()
('--input_dir', '-i', required=True, type=click.Path(), help='Input DICOM directory. This should be at the same level as the parent field (default=PatientName).')
('--output_dir', '-o', default='./', show_default=True, required=False, type=click.Path(), help='Output directory. A folder structure will be created at t... |
def avg_nr_of_trades_per1y(trades_returns: QFSeries, start_date: datetime, end_date: datetime):
period_length = (end_date - start_date)
period_length_in_years = (to_days(period_length) / DAYS_PER_YEAR_AVG)
avg_number_of_trades_1y = (len(trades_returns) / period_length_in_years)
return avg_number_of_trad... |
def weld_unwelded_result(d):
constant_smiles = d['constant']
to_smiles = d['to_smiles']
start_num_heavies = d.pop('start_num_heavies')
(new_smiles, welded_mol) = weld_fragments(constant_smiles, to_smiles)
final_num_heavies = welded_mol.GetNumHeavyAtoms()
d['final'] = new_smiles
d['heavies_di... |
class TestDebugError(unittest.TestCase):
def setUp(self):
self._old_debug = pyppeteer.DEBUG
self.logger = logging.getLogger('pyppeteer.test')
def tearDown(self):
pyppeteer.DEBUG = self._old_debug
def test_debug_default(self):
with self.assertLogs('pyppeteer.test', logging.DEB... |
def test_has_unsupported_features(preset_manager):
preset = preset_manager.default_preset_for_game(RandovaniaGame.METROID_DREAD).get_preset()
assert isinstance(preset.configuration, DreadConfiguration)
configuration = preset.configuration
gd = default_database.game_description_for(preset.game)
suitl... |
def write_to_cache(db_name, data):
if (not os.path.exists(os.path.dirname(CACHE_FILE))):
try:
os.makedirs(os.path.dirname(CACHE_FILE))
with open(CACHE_FILE, 'w') as _:
_.write(json.dumps({}))
LOG.debug('Cache file created')
except OSError as ex... |
class SubVector(_VectorBase, _matrix_ext.SubVector):
def __init__(self, obj, start=0, length=None):
if (not isinstance(obj, _kaldi_vector.VectorBase)):
obj = numpy.array(obj, dtype=numpy.float32, copy=False, order='C')
if (obj.ndim != 1):
raise ValueError('obj should ... |
class LeaveOrgViewTest(TestCase):
def setUpTestData(cls):
add_default_data()
def login(self, name, password=None):
self.client.login(username=name, password=(password if password else name))
self.pu = PytitionUser.objects.get(user__username=name)
return self.pu
def logout(sel... |
('mini-imagenet')
class MiniImageNet(Dataset):
def __init__(self, root_path, split='train', **kwargs):
split_tag = split
if (split == 'train'):
split_tag = 'train_phase_train'
split_file = 'miniImageNet_category_split_{}.pickle'.format(split_tag)
with open(os.path.join(ro... |
def test_register_equilibrium_solver(mocker):
from solcore import registries
mock_gr = mocker.patch('solcore.registries.generic_register')
name = 'custom_equilibrium'
overwrite = False
reason_to_exclude = None
_equilibrium_solver(name, overwrite=overwrite, reason_to_exclude=reason_to_exclude)
... |
_checkable
class BackendType(Protocol[_App]):
Options: Callable[(..., Any)]
def configure(self, app: _App, component: RootComponentConstructor, options: (Any | None)=None) -> None:
def create_development_app(self) -> _App:
async def serve_development_app(self, app: _App, host: str, port: int, started: (... |
class DataTrainingArguments():
dataset_name: Optional[str] = field(default=None, metadata={'help': 'The name of the dataset to use (via the datasets library).'})
dataset_config_name: Optional[str] = field(default=None, metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'}... |
def main():
args = parse_args()
os.environ['CUDA_VISIBLE_DEVICES'] = args.cuda_devices
os.environ['NVIDIA_VISIBLE_DEVICES'] = args.cuda_devices
accelerator = Accelerator()
args.device = accelerator.device
logger = get_logger(args, accelerator)
(raw_datasets, label_list, num_labels) = get_dat... |
class BCELoss(nn.Module):
def __init__(self, num_classes, epsilon=0.1, use_gpu=True, label_smooth=True):
super(BCELoss, self).__init__()
self.num_classes = num_classes
self.epsilon = (epsilon if label_smooth else 0)
self.use_gpu = use_gpu
self.sigmoid = nn.Sigmoid()
def f... |
def test_matrix_variable_selection_inclusion(hatch, helpers, temp_dir, config_file):
config_file.model.template.plugins['default']['tests'] = False
config_file.save()
project_name = 'My.App'
with temp_dir.as_cwd():
result = hatch('new', project_name)
assert (result.exit_code == 0), result.ou... |
def plot_trajectories(trajectory_dict, title, add_legend=True):
carla_map = CarlaMap('Town01_nemesis', 0.1653, 50)
image = mpimg.imread('carla/planner/Town01_nemesis.png')
(fig, ax) = plt.subplots(1)
pad = 30
fig.set_size_inches(10, 10)
plt.rcParams.update({'font.size': 12})
ax.imshow(image,... |
class AlpinePackage(Package):
def is_installed(self):
return (self.run_test('apk -e info %s', self.name).rc == 0)
def version(self):
out = self.check_output('apk -e -v info %s', self.name).split('-')
return out[(- 2)]
def release(self):
out = self.check_output('apk -e -v info... |
class LogCmd():
def __init__(self, cmd, env=None) -> None:
self.cmd = cmd
self.env = env
def __repr__(self) -> str:
cmd_repr = ' '.join((quote(str(c)) for c in self.cmd))
if (self.env is not None):
cmd_repr = f'{cmd_repr} env of {self.env!r}'
return cmd_repr |
def test_set_pypi_token(config: Config, with_simple_keyring: None, dummy_keyring: DummyBackend) -> None:
manager = PasswordManager(config)
assert manager.keyring.is_available()
manager.set_pypi_token('foo', 'baz')
assert (config.get('pypi-token.foo') is None)
assert (dummy_keyring.get_password('poet... |
class DirectionalLightShadow(LightShadow):
def __init__(self) -> None:
super().__init__(OrthographicCamera(1000, 1000, depth_range=((- 500), 500)))
def _update_matrix(self, light):
camera = self.camera
camera.update_projection_matrix()
super()._update_matrix(light) |
def handle_network_errors(fn: typing.Callable[(typing.Concatenate[(MultiplayerSessionApi, Param)], RetType)]) -> typing.Callable[(Param, RetType)]:
(fn)
async def wrapper(self: MultiplayerSessionApi, *args, **kwargs):
parent = self.widget_root
try:
return (await fn(self, *args, **kwa... |
class GraphConv(nn.Module):
def __init__(self, edge_feature_dim, node_feature_in_dim, node_feature_out_dim, hidden_dims=[32, 64], aggr='mean', batch_norm=True, mlp_activation=torch.nn.Sigmoid(), final_activation=torch.nn.LeakyReLU()):
super(GraphConv, self).__init__()
self.mlp = MLP(in_dim=edge_feat... |
def render_notebook(nbspec: NotebookSpecV2) -> None:
(nb, nb_path) = _init_notebook(path_stem=nbspec.path_stem, directory=nbspec.directory)
cells = {'title_cell': _MarkdownCell('\n'.join(_get_title_lines(nbspec.title, nbspec.module)), cell_id='title_cell'), 'top_imports': _PyCell(_IMPORTS, cell_id='top_imports'... |
def fort_file(filename, txts, header=None):
try:
if header:
f = open(filename, 'a')
f.write((json.dumps(header) + '\n'))
for txt in txts:
f.write((json.dumps(txt) + '\n'))
f.close()
else:
with open(filename, 'a') as f:
... |
class CmdExamine(ObjManipCommand):
key = 'investigate'
aliases = []
locks = 'cmd:perm(examine) or perm(Builder)'
help_category = 'Building'
arg_regex = '(/\\w+?(\\s|$))|\\s|$'
account_mode = False
def list_attribute(self, crop, attr, category, value):
if crop:
if (not isi... |
def train_step(model, dataset, optimizer, scheduler, scaler, amp=False):
model.train()
with autocast(enabled=amp):
logits = model(graph=dataset.graph, x=dataset.node_features)
loss = dataset.loss_fn(input=logits[dataset.train_idx], target=dataset.labels[dataset.train_idx])
scaler.scale(loss)... |
def parse_dates(data, tree, sup, regions, territory):
week_data = data.setdefault('week_data', {})
supelem = sup.find('.//weekData')
for elem in supelem.findall('minDays'):
if _should_skip_elem(elem):
continue
territories = elem.attrib['territories'].split()
if ((territor... |
_grad()
def scan_evaluate(predictions):
num_heads = len(predictions)
output = []
for head in predictions:
probs = head['probabilities']
neighbors = head['neighbors']
anchors = torch.arange(neighbors.size(0)).view((- 1), 1).expand_as(neighbors)
entropy_loss = entropy(torch.mea... |
class FillFormatter(Formatter):
def __init__(self, num_headers=1):
super().__init__()
self.__num_headers = num_headers
self.__prev_cell = None
def clear(self, cell):
self.__prev_cell = cell
def apply(self, cell, *args, **kwargs):
if (self.__prev_cell is None):
... |
class FC6_XConfig(FC3_XConfig):
removedKeywords = (FC3_XConfig.removedKeywords + ['card', 'hsync', 'monitor', 'noProbe', 'server', 'vsync'])
removedAttrs = (FC3_XConfig.removedAttrs + ['card', 'hsync', 'monitor', 'noProbe', 'server', 'vsync'])
def __init__(self, writePriority=0, *args, **kwargs):
FC... |
def record_time(time_tracker):
if time_tracker:
average = defaultdict(float)
for check in time_tracker['Iteration 1']:
iterations = 0
for values in time_tracker.values():
if (check in values):
average[check] += values[check]
... |
_module()
class CLAMP(BasePose):
def __init__(self, backbone, text_encoder, context_decoder, class_names, context_length, score_concat_index=3, identity_head=None, upconv_head=None, token_embed_dim=512, text_dim=1024, clip_pretrained=None, matching_only=False, visual_dim=256, CL_ratio=1.0, prompt_encoder=None, keyp... |
class W_Plumber(values.W_Object):
_attrs_ = ['callbacks', 'weak_callbacks']
def __init__(self, callbacks={}, weak_callbacks={}):
self.callbacks = callbacks
self.weak_callbacks = weak_callbacks
def get_callbacks(self):
return self.callbacks
def get_weak_callbacks(self):
re... |
def finalize_construction(breakpoints):
breakpoints.sort()
breakpoints_out = []
f_last = None
for (f, c) in breakpoints:
if ((f_last is not None) and (f == f_last)):
breakpoints_out[(- 1)][1] += c
else:
breakpoints_out.append([f, c])
f_last = f
breakpo... |
def test_function_utils():
def dummmy_func2d(x):
return (x + 1)
(T, D) = (10, 24)
np.random.seed(1234)
X = np.random.rand(2, T, D)
lengths = [60, 100]
Y = apply_each2d_padded(dummmy_func2d, X, lengths)
for (i, l) in enumerate(lengths):
assert np.allclose((X[i][:l] + 1), Y[i][... |
def test_svg_circuit():
g = cq_testing.GateHelper(MultiAnd(cvs=(1, 1, 1)))
svg = svg_circuit(g.circuit, g.r)
svg_str = svg.data
assert (svg_str.find('ctrl') < svg_str.find('junk') < svg_str.find('target'))
with pytest.raises(ValueError):
svg_circuit(cirq.Circuit())
with pytest.raises(Val... |
def test_stdsim_line_buffering(base_app):
import os
import tempfile
file = tempfile.NamedTemporaryFile(mode='wt')
file.line_buffering = True
stdsim = cu.StdSim(file, echo=True)
saved_size = os.path.getsize(file.name)
bytes_to_write = b'hello\n'
stdsim.buffer.write(bytes_to_write)
ass... |
def main():
pp.connect(use_gui=True)
pp.add_data_path()
p.resetDebugVisualizerCamera(cameraDistance=1.5, cameraPitch=(- 20), cameraYaw=80, cameraTargetPosition=[0, 0, 0.2])
p.loadURDF('plane.urdf')
ri = safepicking.pybullet.PandaRobotInterface()
cube = pp.create_box(0.03, 0.05, 0.1, mass=0.1, co... |
class ExtendedNet(nn.Module):
def __init__(self):
super(ExtendedNet, self).__init__()
self.conv1 = nn.Conv2d(1, 32, kernel_size=5, padding=(2, 2))
self.conv2 = nn.Conv2d(32, 64, kernel_size=5, padding=(2, 2), bias=False)
self.conv2_drop = nn.Dropout2d()
self.conv3 = nn.Conv2d... |
def mask_requests_args(url, validating=False, params_checker=None, **kwargs):
requests_kwargs = {key: val for (key, val) in iteritems(kwargs) if (key in ALLOWED_REQUESTS_KWARGS)}
if (params_checker is not None):
(url, s_params) = params_checker(url)
if s_params:
if ('params' in reque... |
def all_gather(data):
world_size = get_world_size()
if (world_size == 1):
return [data]
buffer = pickle.dumps(data)
storage = torch.ByteStorage.from_buffer(buffer)
tensor = torch.ByteTensor(storage).to('cuda')
local_size = torch.IntTensor([tensor.numel()]).to('cuda')
size_list = [tor... |
class HKCCM1(FinTS3Segment):
account = DataElementGroupField(type=KTI1, _d='Kontoverbindung international')
sum_amount = DataElementGroupField(type=Amount1, _d='Summenfeld')
request_single_booking = DataElementField(type='jn', _d='Einzelbuchung gewunscht')
sepa_descriptor = DataElementField(type='an', m... |
def create_floors(bm, faces, prop):
(slabs, walls, roof) = extrude_slabs_and_floors(bm, faces, prop)
bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
add_faces_to_group(bm, slabs, MaterialGroup.SLABS)
add_faces_to_group(bm, walls, MaterialGroup.WALLS)
add_faces_to_group(bm, roof, MaterialGroup.ROOF... |
class BaseListSchema(Schema):
OPTIONS_CLASS = BaseOpts
_load
def wrap_data_envelope(self, data, **kwargs):
data = dict(data=data)
return data
_dump
def unwrap_data_envelope(self, data, **kwargs):
return data['data']
_load
def make_object(self, data, **kwargs):
... |
def create_dialogue(utterances, segment_ids, redundancy_ids):
dialogue = []
for (index, utterance) in enumerate(utterances):
if (index in segment_ids):
dialogue.append('[TS]')
if (index in redundancy_ids):
words = utterance.split()
assert (words[1] == ':')
... |
class Model(nn.Module):
def __init__(self, *, n_num_features: int, n_bin_features: int, cat_cardinalities: list[int], n_classes: Optional[int], num_embeddings: Optional[dict], backbone: dict) -> None:
assert (n_num_features or n_bin_features or cat_cardinalities)
if (num_embeddings is not None):
... |
def loss_fn(cls_outputs: List[torch.Tensor], box_outputs: List[torch.Tensor], cls_targets: List[torch.Tensor], box_targets: List[torch.Tensor], num_positives: torch.Tensor, num_classes: int, alpha: float, gamma: float, delta: float, box_loss_weight: float, label_smoothing: float=0.0, new_focal: bool=False) -> Tuple[(to... |
def write_stack_trace(ex: Exception) -> None:
file = NamedTemporaryFile('w', prefix=f'raiden-exception-{datetime.datetime.utcnow():%Y-%m-%dT%H-%M}', suffix='.txt', delete=False)
with file as traceback_file:
traceback.print_exc(file=traceback_file)
traceback.print_exc()
click.secho(f'''FA... |
.parametrize('protocol', ['ucx', 'ucxx'])
.parametrize('params', [{'enable_infiniband': False, 'enable_nvlink': False, 'enable_rdmacm': False}, {'enable_infiniband': True, 'enable_nvlink': True, 'enable_rdmacm': False}, {'enable_infiniband': True, 'enable_nvlink': False, 'enable_rdmacm': True}, {'enable_infiniband': Tr... |
class TestEnvFileCombinations(EnvironmentTestCase):
def test_run_with_both_env_files(self, runner, target, env1, env2):
env = self.run_environ(runner, *target, '--default-env-file', env1, '--env-file', env2)
assert (env.get('SECRET') == 'unknown')
assert (env.get('PASSWORD') == 'bitter')
... |
def test_log_player_take_damage():
events = telemetry.events_from_type('LogPlayerTakeDamage')
data = events[0]
assert isinstance(data, LogPlayerTakeDamage)
assert isinstance(data.attacker, Character)
assert isinstance(data.victim, Character)
assert (data.damage > 0)
assert (data.damage_type_... |
def runDbmsSchedulerModule(args):
status = True
if (checkOptionsGivenByTheUser(args, ['test-module', 'exec', 'reverse-shell', 'make-download']) == False):
return EXIT_MISS_ARGUMENT
dbmsScheduler = DbmsScheduler(args)
status = dbmsScheduler.connection(stopIfError=True)
if (args['test-module']... |
class TestBiasCorrection(unittest.TestCase):
.cuda
def test_correct_bias_on_mnist(self):
def modified_parse(serialized_example):
dim = 28
features = tf.compat.v1.parse_single_example(serialized_example, features={'label': tf.compat.v1.FixedLenFeature([], tf.int64), 'image_raw': t... |
def accuracy(output, target, meta):
batch_size = target.size(0)
target = target.cpu().numpy()
(err, cnt) = (0, 0)
for i in range(batch_size):
if (meta[(i, 0)] < (1 + ref.eps)):
cnt += 1
for j in range(ref.J):
err += (((((output[i][(j * 3)] - target[i][j][0... |
def print_final_status_json(iterations, cerberus_status, exit_status_code):
status_json = {'iterations': iterations, 'cluster_health': cerberus_status, 'exit_status': exit_status_code}
with open('final_cerberus_info.json', 'w') as file:
file.write(str(status_json))
logging.info('Final status informa... |
class Packages_OldVersion_CamelCase_TestCase(ParserTest):
def __init__(self, *args, **kwargs):
ParserTest.__init__(self, *args, **kwargs)
self.version = RHEL8
self.ks = '%packages --instLangs cs_CZ --excludeWeakdeps\nsomething\n\n%end\n'
def runTest(self):
with warnings.catch_war... |
.parametrize(('word', 'result'), [('', ['', '', '']), ('', ['', '', '']), ('', ['', '', '']), ('', ['', '', '']), ('', ['', '', '']), ('', ['', '', '']), ('', ['', '', '']), ('', ['', '', '']), ('', ['', '', ''])])
def test_plural_forms(word, result, morph):
parsed = morph.parse(word)
assert len(parsed)
for... |
class AgdaLexer(RegexLexer):
name = 'Agda'
url = '
aliases = ['agda']
filenames = ['*.agda']
mimetypes = ['text/x-agda']
version_added = '2.0'
reserved = ('abstract', 'codata', 'coinductive', 'constructor', 'data', 'do', 'eta-equality', 'field', 'forall', 'hiding', 'in', 'inductive', 'infix'... |
class ComplexParameter(pTypes.GroupParameter):
def __init__(self, **opts):
opts['type'] = 'bool'
opts['value'] = True
pTypes.GroupParameter.__init__(self, **opts)
self.addChild({'name': 'A = 1/B', 'type': 'float', 'value': 7, 'suffix': 'Hz', 'siPrefix': True})
self.addChild({... |
def get_pretraining_file(backbone):
if ('mitb5' in backbone):
return 'pretrained/mit_b5.pth'
if ('mitb4' in backbone):
return 'pretrained/mit_b4.pth'
if ('mitb3' in backbone):
return 'pretrained/mit_b3.pth'
if ('r101v1c' in backbone):
return 'open-mmlab://resnet101_v1c'
... |
class RecordsExtractor(object):
def _clean_up_cols(self, columns):
return re.sub(' +', '', columns).split(',')
def _generate_data_payloads(self, data_count, payload, cols=[], index=0):
payload = clean_up_offset_payload(payload)
payloads = {}
for i in range(index, data_count):
... |
def test_SumScaler_simple_both():
dm = skcriteria.mkdm(matrix=[[1, 2, 3], [4, 5, 6]], objectives=[min, max, min], weights=[1, 2, 3])
expected = skcriteria.mkdm(matrix=[[(1 / 5), (2 / 7), (3 / 9)], [(4 / 5), (5 / 7), (6 / 9)]], objectives=[min, max, min], weights=[(1 / 6), (2 / 6), (3 / 6)], dtypes=[float, float... |
class CuFile():
def __init__(self, file: (pathlib.Path | str), flags: str='r'):
assert ('a' not in flags)
self._closed = False
self._filepath = str(file)
self._flags = flags
with open(self._filepath, mode=flags):
pass
def close(self) -> None:
self._clo... |
class Migration(migrations.Migration):
dependencies = [('adserver', '0081_rollout_ad_prioritization_pacing')]
operations = [migrations.AddField(model_name='historicalpublisher', name='allowed_domains', field=models.CharField(blank=True, default='', help_text="A space separated list of domains where the publishe... |
def test_validate_well_structured_bad_gate():
(q0, q1) = cirq.LineQubit.range(2)
circuit = cirq.Circuit([cirq.Moment([cirq.PhasedXPowGate(phase_exponent=0).on(q0)]), cirq.Moment([cirq.XPowGate(exponent=0.5).on(q0)]), cirq.Moment([cg.SYC(q0, q1)]), cirq.measure(q0, q1, key='z')])
with pytest.raises(BadlyStru... |
class FxThread(ThreadJob):
def __init__(self, config: SimpleConfig, network: Optional[Network]):
ThreadJob.__init__(self)
self.config = config
self.network = network
util.register_callback(self.set_proxy, ['proxy_set'])
self.ccy = self.get_currency()
self.history_used... |
class ContextStringFormatter(string.Formatter):
def __init__(self, formatters: ChainMap) -> None:
super().__init__()
self.__formatters = formatters
def vformat(self, format_string: str, args: Sequence[Any], kwargs: Mapping[(str, Any)]) -> str:
used_args = set()
(result, _) = self... |
def dict_from_prop(prop):
valid_types = (int, str, bool, float, tuple, Vector, bpy.types.Material, bpy.types.Object)
result = {}
for p in dir(prop):
if (p.startswith('__') or (p in ['rna_type', 'bl_rna'])):
continue
if (not hasattr(prop, p)):
continue
pn = get... |
.parametrize(('version', 'expected_next'), [pytest.param(meta('1.0.0', config=c), '1.0.0', id='SemVer exact stays'), pytest.param(meta('1.0.0', config=c_non_normalize, dirty=True), '09.02.13.1.dev0', id='SemVer dirty is replaced by date', marks=pytest.mark.filterwarnings('ignore:.*legacy version.*:UserWarning'))])
def ... |
def test_update_merge_request_approvals_set_approvers(project, resp_mr_approval_rules):
approvals = project.mergerequests.get(1, lazy=True).approvals
assert isinstance(approvals, gitlab.v4.objects.merge_request_approvals.ProjectMergeRequestApprovalManager)
assert (approvals._update_method is UpdateMethod.PO... |
def project_delta_file_metadata_on_table(delta_file_envelope: DeltaFileEnvelope) -> pa.Table:
table = delta_file_envelope.table
ordered_file_number = delta_file_envelope.file_index
ordered_file_number_iterator = repeat(int(ordered_file_number), len(table))
table = append_file_idx_column(table, ordered_f... |
def file_handler(loglevel, logfile, log_format, command):
if (logfile is not None):
filename = logfile
else:
filename = os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), 'faceswap')
filename += ('_gui.log' if (command == 'gui') else '.log')
should_rotate = os.path.isfile(f... |
def _file_handler_exists(logger: Logger, log_dir: str, log_base_file_name: str) -> bool:
handler_exists = False
base_file_path = os.path.join(log_dir, log_base_file_name)
if (len(logger.handlers) > 0):
norm_base_file_path = os.path.normpath(base_file_path)
handler_exists = any([(isinstance(h... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.