code stringlengths 281 23.7M |
|---|
def test_project_file_uploads(project):
filename = 'test.txt'
file_contents = 'testing contents'
uploaded_file = project.upload(filename, file_contents)
(alt, url) = (uploaded_file['alt'], uploaded_file['url'])
assert (alt == filename)
assert url.startswith('/uploads/')
assert url.endswith(f... |
class Decoder(nn.Module):
def __init__(self, num_classes, pretrain, do_segmentation=False):
super().__init__()
self.pretrain = pretrain
self.layers = nn.ModuleList()
self.layers.append(UpsamplerBlock(128, 64))
self.layers.append(non_bottleneck_1d(64, 0, 1))
self.layer... |
class MS_SSIM(nn.Module):
def __init__(self, size_average=True, max_val=255):
super(MS_SSIM, self).__init__()
self.size_average = size_average
self.channel = 3
self.max_val = max_val
def _ssim(self, img1, img2, size_average=True):
(_, c, w, h) = img1.size()
window... |
def eval_net(model, loader, classifier_criterion, model_type):
model.eval()
correct = 0
cls_loss = 0.0
for (images, labels, idx, y_hm, gaze_img, attributes) in loader:
images = images.cuda()
labels = labels.long()
labels = labels.cuda()
y_hm = y_hm.cuda()
gaze_img... |
class Summary_Info(object):
def __init__(self):
self.reset()
def reset(self):
self.things = []
self.info = {}
self.summary_n_samples = {}
def get_things(self):
return self.things
def get_info(self):
return self.info
def get_summary_n_samples(self):
... |
class ImageNetDataPipeline():
def __init__(self, _config: argparse.Namespace):
self._config = _config
def data_loader(self):
data_loader = ImageNetDataLoader(self._config.tfrecord_dir, image_size=image_net_config.dataset['image_size'], batch_size=image_net_config.evaluation['batch_size'], num_ep... |
def bvh_node_dict2armature(context, bvh_name, bvh_nodes, bvh_frame_time, rotate_mode='XYZ', frame_start=1, IMPORT_LOOP=False, global_matrix=None, use_fps_scale=False):
if (frame_start < 1):
frame_start = 1
scene = context.scene
for obj in scene.objects:
obj.select_set(False)
arm_data = b... |
class StructBahAttnDecoder(RnnDecoder):
def __init__(self, emb_dim, vocab_size, fc_emb_dim, struct_vocab_size, attn_emb_dim, dropout, d_model, **kwargs):
super().__init__(emb_dim, vocab_size, fc_emb_dim, attn_emb_dim, dropout, d_model, **kwargs)
attn_size = kwargs.get('attn_size', self.d_model)
... |
def deprecated_alias(old_qualname: str, new_fn: Callable[(ArgsT, RetT)], version: str, *, issue: (int | None)) -> Callable[(ArgsT, RetT)]:
(version, issue=issue, instead=new_fn)
(new_fn, assigned=('__module__', '__annotations__'))
def wrapper(*args: ArgsT.args, **kwargs: ArgsT.kwargs) -> RetT:
retur... |
_funcify.register(SVD)
def numba_funcify_SVD(op, node, **kwargs):
full_matrices = op.full_matrices
compute_uv = op.compute_uv
out_dtype = np.dtype(node.outputs[0].dtype)
inputs_cast = int_to_float_fn(node.inputs, out_dtype)
if (not compute_uv):
_basic.numba_njit()
def svd(x):
... |
def process_position(solar_cell, options, layer_widths):
if (options.position is None):
options.position = [max(1e-10, (width / 5000)) for width in layer_widths]
layer_offsets = np.insert(np.cumsum(layer_widths), 0, 0)
options.position = np.hstack([np.arange(layer_offsets[j], (layer_offsets[... |
class DepthwiseSeparableConv2d(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, padding=1, dilation=1, *, norm1=None, activation1=None, norm2=None, activation2=None):
super().__init__()
self.depthwise = Conv2d(in_channels, in_channels, kernel_size=kernel_size, padding=padding... |
def test_prompt(hatch, devpi, temp_dir_cache, helpers, published_project_name, config_file):
config_file.model.publish['index']['ca-cert'] = devpi.ca_cert
config_file.model.publish['index']['repo'] = 'dev'
config_file.model.publish['index']['repos'] = {'dev': devpi.repo}
config_file.save()
with temp... |
def test_choice_samples():
with pytest.raises(NotImplementedError):
choice._supp_shape_from_params(np.asarray(5))
compare_sample_values(choice, np.asarray(5))
compare_sample_values(choice, np.asarray([5]))
compare_sample_values(choice, np.array([1.0, 5.0], dtype=config.floatX))
compare_sampl... |
def LoadWav(path, cfg):
wav_name = os.path.basename(path).split('.')[0]
sr = cfg.sampling_rate
(wav, fs) = sf.read(path)
(wav, _) = librosa.effects.trim(y=wav, top_db=cfg.top_db)
if (fs != sr):
wav = resampy.resample(x=wav, sr_orig=fs, sr_new=sr, axis=0)
fs = sr
assert (fs == 160... |
def parse_args():
parser = ArgumentParser()
parser.add_argument('pcd', help='Point cloud file')
parser.add_argument('config', help='Config file')
parser.add_argument('checkpoint', help='Checkpoint file')
parser.add_argument('model_name', help='The model name in the server')
parser.add_argument('... |
class ExperienceReplay():
def __init__(self, memory_size: int=100, replay_number: int=10):
self.buffer = pd.DataFrame(columns=['smiles', 'likelihood', 'scores'])
self.memory_size = memory_size
self.replay_number = replay_number
def add_to_buffer(self, smiles, scores, neg_likelihood):
... |
def get_process_listening_port(proc):
conn = None
if (platform.system() == 'Windows'):
current_process = psutil.Process(proc.pid)
children = []
while (children == []):
time.sleep(0.01)
children = current_process.children(recursive=True)
if ((3, 6) <= s... |
class CalcChangeLocalDroneAmountCommand(wx.Command):
def __init__(self, fitID, position, amount):
wx.Command.__init__(self, True, 'Change Local Drone Amount')
self.fitID = fitID
self.position = position
self.amount = amount
self.savedDroneInfo = None
def Do(self):
... |
def test_extra_files_are_ok():
with tempfile.TemporaryDirectory() as tempdir:
config_file = os.path.join(tempdir, 'config.py')
with open(config_file, 'w') as config:
config.write('from bar import foo\n')
with open(os.path.join(tempdir, 'bar.py'), 'w') as config:
confi... |
def _create_chain_initial_circuit(parameters: FermiHubbardParameters, qubits: List[cirq.Qid], chain: ChainInitialState) -> cirq.Circuit:
if isinstance(chain, SingleParticle):
return create_one_particle_circuit(qubits, chain.get_amplitudes(len(qubits)))
elif isinstance(chain, TrappingPotential):
... |
class TemplateSelectorWidget(QWidget):
def __init__(self, theChoice=None, parent=None):
super(TemplateSelector, self).__init__(parent)
self.setWindowTitle('select how Foam case is generated')
choices = ['fromScratch', 'fromExisting']
helpTexts = ['generate Foam case dicts from templa... |
def get_injectable_payloads(url='', data='', base='', injection_type='', session_filepath='', is_json=False, is_multipart=False, injected_and_vulnerable=False):
Injections = collections.namedtuple('Injections', ['retval', 'template_msg', 'tested_parameters'])
retval = session.fetchall(session_filepath=session_f... |
def get_res_fc_seq_fc(model_rnn_dim, rnn: bool, self_att: bool, keep_rate=0.8):
seq_mapper = []
if ((not rnn) and (not self_att)):
raise NotImplementedError()
if rnn:
seq_mapper.extend([VariationalDropoutLayer(keep_rate), CudnnGru(model_rnn_dim, w_init=TruncatedNormal(stddev=0.05))])
if ... |
class Linear(nn.Linear, Module):
def __init__(self, in_features, out_features, bias=True):
super(Linear, self).__init__(in_features, out_features, bias=bias)
def forward(self, x, params=None, episode=None):
if (params is None):
x = super(Linear, self).forward(x)
else:
... |
def dict_of_class(tup: Tuple[(List[Tuple[(_CountingAttr, SearchStrategy)]], Tuple[(Type, PosArgs, KwArgs)])], defaults: Tuple[(PosArgs, KwArgs)]):
nested_cl = tup[1][0]
nested_cl_args = tup[1][1]
nested_cl_kwargs = tup[1][2]
default = Factory((lambda : {'cls': nested_cl(*defaults[0], **defaults[1])}))
... |
def test_cursor_usage_to_add_a_chain():
(a, b, c) = get_pseudo_nodes(*'abc')
g = Graph()
(((g.get_cursor() >> a) >> b) >> c)
assert (len(g) == 3)
assert (g.outputs_of(BEGIN) == {g.index_of(a)})
assert (g.outputs_of(a) == {g.index_of(b)})
assert (g.outputs_of(b) == {g.index_of(c)})
assert... |
def test_subcommand_tab_completion(sc_app):
text = 'Foot'
line = 'base sport {}'.format(text)
endidx = len(line)
begidx = (endidx - len(text))
first_match = complete_tester(text, line, begidx, endidx, sc_app)
assert ((first_match is not None) and (sc_app.completion_matches == ['Football '])) |
class Model(models.Model):
created = models.DateTimeField(editable=False, verbose_name=_('created'))
updated = models.DateTimeField(editable=False, verbose_name=_('updated'))
class Meta():
abstract = True
def save(self, *args, **kwargs):
if (self.created is None):
self.create... |
class AveragerArguments():
averaging_expiration: float = field(default=5.0, metadata={'help': 'Averaging group will wait for stragglers for at most this many seconds'})
averaging_timeout: float = field(default=30.0, metadata={'help': 'Give up on averaging step after this many seconds'})
listen_on: str = fie... |
class TestOrderMethods(zf.WithConstantEquityMinuteBarData, zf.WithConstantFutureMinuteBarData, zf.WithMakeAlgo, zf.ZiplineTestCase):
START_DATE = T('2006-01-03')
END_DATE = T('2006-01-06')
SIM_PARAMS_START_DATE = T('2006-01-04')
ASSET_FINDER_EQUITY_SIDS = (1,)
EQUITY_DAILY_BAR_SOURCE_FROM_MINUTE = T... |
class HeadQABase(MultipleChoiceTask):
VERSION = 0
DATASET_PATH = inspect.getfile(lm_eval.datasets.headqa.headqa)
def has_training_docs(self):
return True
def has_validation_docs(self):
return True
def has_test_docs(self):
return True
def training_docs(self):
if (s... |
class iSendBase():
def make_td(ones):
raise NotImplementedError
def client(cls, pseudo_rand):
torch.distributed.init_process_group('gloo', rank=1, world_size=2, init_method='tcp://localhost:10017')
td = cls.make_td(True)
td.isend(0, pseudo_rand=pseudo_rand)
def server(cls, qu... |
def test_body3d_semi_supervision_dataset_compatibility():
labeled_data_cfg = dict(num_joints=17, seq_len=27, seq_frame_interval=1, causall=False, temporal_padding=True, joint_2d_src='gt', subset=1, subjects=['S1'], need_camera_param=True, camera_param_file='tests/data/h36m/cameras.pkl')
labeled_dataset = dict(t... |
def _lenarray(d):
if (len(d) == 5):
l = ((d[4] * qcmio.lind4(False, d[0], d[1], d[2], d[3], 0, abs(d[0]), abs(d[1]), abs(d[2]), abs(d[3]))[0]) + 1)
elif (len(d) == 4):
l = (qcmio.lind4(False, d[0], d[1], d[2], d[3], 0, abs(d[0]), abs(d[1]), abs(d[2]), abs(d[3]))[0] + 1)
elif (len(d) == 3):
... |
def cmd_obj(args) -> None:
if args.obj_spec:
sock_file = (args.socket or find_sockfile())
ipc_client = Client(sock_file)
cmd_object = IPCCommandInterface(ipc_client)
cmd_client = CommandClient(cmd_object)
obj = get_object(cmd_client, args.obj_spec)
if (args.function =... |
def test_get_operators():
operator_00 = QubitOperator(((1, 'X'), (3, 'Y'), (8, 'Z')), 1)
operator_01 = QubitOperator(((2, 'Z'), (3, 'Y')), 1)
sum_operator = (operator_00 + operator_01)
operators = list(sum_operator.get_operators())
assert (operators in [[operator_00, operator_01], [operator_01, oper... |
def get_final_results(log_json_path, epoch, results_lut):
result_dict = dict()
with open(log_json_path, 'r') as f:
for line in f.readlines():
log_line = json.loads(line)
if ('mode' not in log_line.keys()):
continue
if ((log_line['mode'] == 'train') and... |
.parametrize('tensor_shape', [FC_SHAPE, CONV_SHAPE], ids=['FC', 'CONV'])
def test_glorot_uniform(tensor_shape):
(fan_in, fan_out) = initializers._compute_fans(tensor_shape)
scale = np.sqrt((6.0 / (fan_in + fan_out)))
_runner(initializers.glorot_uniform(), tensor_shape, target_mean=0.0, target_max=scale, tar... |
('/v1/organization/<orgname>/marketplace/<subscription_id>')
_param('orgname', 'The name of the organization')
_param('subscription_id', 'Marketplace subscription id')
_user_resource(UserPlan)
_if(features.BILLING)
class OrganizationRhSkuSubscriptionField(ApiResource):
_scope(scopes.ORG_ADMIN)
def delete(self, ... |
def add_CCL_constraints(n, config):
agg_p_nom_limits = config['electricity'].get('agg_p_nom_limits')
try:
agg_p_nom_minmax = pd.read_csv(agg_p_nom_limits, index_col=list(range(2)))
except IOError:
logger.exception("Need to specify the path to a .csv file containing aggregate capacity limits ... |
class Plugin(BasePlugin):
def __init__(self, parent, config, name):
BasePlugin.__init__(self, parent, config, name)
if self.is_available():
self.modem_config = amodem.config.slowest()
self.library_name = {'Linux': 'libportaudio.so'}[platform.system()]
def is_available(sel... |
class MessageBroker():
def __init__(self):
self.__latest_values = {}
self.__subscribers = {}
self.__lock = threading.RLock()
def subscribe(self, topic, callback):
with self.__lock:
subscribers = self.__subscribers.setdefault(topic, [])
subscribers.append(c... |
def patchify_augmentation(args, batch):
aug_batch = dict()
img = batch['image']
label = batch['label']
batch_size = img.size()[0]
patch_dim = (img.size()[(- 1)] // args.mask_patch_size)
images_patch = rearrange(img, 'b c (h p1) (w p2) (d p3) -> (b h w d) c p1 p2 p3 ', p1=args.mask_patch_size, p2... |
def _scale_stage_depth(stack_args, repeats, depth_multiplier=1.0, depth_trunc='ceil'):
num_repeat = sum(repeats)
if (depth_trunc == 'round'):
num_repeat_scaled = max(1, round((num_repeat * depth_multiplier)))
else:
num_repeat_scaled = int(math.ceil((num_repeat * depth_multiplier)))
repea... |
def get_label(task, line):
if (task in ['MNLI', 'MRPC', 'QNLI', 'QQP', 'RTE', 'SNLI', 'SST-2', 'STS-B', 'WNLI', 'CoLA']):
line = line.strip().split('\t')
if (task == 'CoLA'):
return line[1]
elif (task == 'MNLI'):
return line[(- 1)]
elif (task == 'MRPC'):
... |
def run_inference(onnx_session, input_size, image):
temp_image = copy.deepcopy(image)
resize_image = cv.resize(temp_image, dsize=(input_size[0], input_size[1]))
x = cv.cvtColor(resize_image, cv.COLOR_BGR2RGB)
x = np.array(x, dtype=np.float32)
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.2... |
class SinusoidalEmbeddings(nn.Module):
def __init__(self, dim):
super().__init__()
inv_freq = (1.0 / (10000 ** (torch.arange(0, dim, 2).float() / dim)))
self.register_buffer('inv_freq', inv_freq)
def forward(self, x):
n = x.shape[0]
t = torch.arange(n, device=x.device).ty... |
.parametrize('test_args, expected', [([100], '100'), ([1000], '1,000'), ([10123], '10,123'), ([10311], '10,311'), ([1000000], '1,000,000'), ([1234567.25], '1,234,567.25'), (['100'], '100'), (['1000'], '1,000'), (['10123'], '10,123'), (['10311'], '10,311'), (['1000000'], '1,000,000'), (['1234567.1234567'], '1,234,'), ([... |
.end_to_end()
def test_two_tasks_have_the_same_product(tmp_path, runner, snapshot_cli):
source = '\n import pytask\n\n .produces("out.txt")\n def task_1(produces):\n produces.write_text("1")\n\n .produces("out.txt")\n def task_2(produces):\n produces.write_text("2")\n '
tmp_path.... |
def get_MNIST(root='./'):
input_size = 28
num_classes = 10
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])
train_dataset = datasets.MNIST((root + 'data/'), train=True, download=True, transform=transform)
test_dataset = datasets.MNIST((root + 'data/... |
def test_custom_pane_show():
m = Map()
pane = CustomPane('test-name', z_index=625, pointer_events=False).add_to(m)
rendered = pane._template.module.script(this=pane, kwargs={})
expected = f'''
var {pane.get_name()} = {m.get_name()}.createPane("test-name");
{pane.get_name()}.style.zIndex = 625;
... |
def train_rcnn(cfg, dataset, image_set, root_path, dataset_path, frequent, kvstore, flip, shuffle, resume, ctx, pretrained, epoch, prefix, begin_epoch, end_epoch, train_shared, lr, lr_step, proposal, logger=None, output_path=None):
mx.random.seed(np.random.randint(10000))
np.random.seed(np.random.randint(10000)... |
class Paragraph(Block):
accepts_lines = True
def continue_(parser=None, container=None):
return (1 if parser.blank else 0)
def finalize(parser=None, block=None):
has_reference_defs = False
while (peek(block.string_content, 0) == '['):
pos = parser.inline_parser.parseRefer... |
class TestProcessTomography(unittest.TestCase):
def setUp(self):
super().setUp()
self.method = 'lstsq'
def test_bell_2_qubits(self):
q2 = QuantumRegister(2)
bell = QuantumCircuit(q2)
bell.h(q2[0])
bell.cx(q2[0], q2[1])
(choi, choi_ideal) = run_circuit_and_... |
class THCRotations(Bloq):
num_mu: int
num_spin_orb: int
num_bits_theta: int
kr1: int = 1
kr2: int = 1
two_body_only: bool = False
adjoint: bool = False
_property
def signature(self) -> Signature:
return Signature([Register('nu_eq_mp1', bitsize=1), Register('data', bitsize=sel... |
def test_prompt_format_equivalency_mistral():
model = 'mistralai/Mistral-7B-Instruct-v0.1'
tokenizer = AutoTokenizer.from_pretrained(model)
prompt_format = PromptFormat(system='{instruction} + ', assistant='{instruction}</s> ', trailing_assistant='', user='[INST] {system}{instruction} [/INST]', default_syst... |
class TestDirUtil(support.TempdirManager):
def test_mkpath_remove_tree_verbosity(self, caplog):
mkpath(self.target, verbose=0)
assert (not caplog.records)
remove_tree(self.root_target, verbose=0)
mkpath(self.target, verbose=1)
wanted = [('creating %s' % self.root_target), ('c... |
class Pedestrian(_BaseCatalog):
def __init__(self, name, mass, category, boundingbox, model=None, role=None):
super().__init__()
self.name = name
self.model = model
self.mass = convert_float(mass)
self.category = convert_enum(category, PedestrianCategory)
if (not isin... |
(short_help='Publish distributions to VCS Releases', context_settings={'help_option_names': ['-h', '--help']})
('--tag', 'tag', help='The tag associated with the release to publish to', default='latest')
_context
def publish(ctx: click.Context, tag: str='latest') -> None:
runtime = ctx.obj
repo = runtime.repo
... |
def test_trim_turns():
turns = [Turn(1, 5, speaker_id='S1', file_id='FILE1'), Turn(6, 10, speaker_id='S1', file_id='FILE1'), Turn(0, 10, speaker_id='S1', file_id='FILE2')]
uem = UEM({'FILE1': [(2, 6), (5.8, 7)], 'FILE2': [(2, 3), (4, 5)]})
expected_turns = [Turn(2, 5, speaker_id='S1', file_id='FILE1'), Turn... |
class Logic(object):
def __init__(self, name, description, quantifier_free=False, theory=None, **theory_kwargs):
self.name = name
self.description = description
self.quantifier_free = quantifier_free
if (theory is None):
self.theory = Theory(**theory_kwargs)
else:... |
class TestRawFeatureVector(QiskitMLTestCase):
def test_construction(self):
circuit = RawFeatureVector(4)
with self.subTest('check number of qubits'):
self.assertEqual(circuit.num_qubits, 2)
with self.subTest('check parameters'):
self.assertEqual(len(circuit.parameters... |
class DummyEncoderModel(FairseqEncoderModel):
def __init__(self, encoder):
super().__init__(encoder)
def build_model(cls, args, task):
return cls(DummyEncoder())
def get_logits(self, net_output):
return torch.log(torch.div(net_output['encoder_out'], (1 - net_output['encoder_out']))) |
def get_op_key(instr):
parts = instr['opcode'].split(' ')
op = parts[0]
args = []
if (len(parts) > 1):
args_str = ''.join(parts[1:])
for arg in args_str.split(','):
if (arg[0] == '-'):
args.append((- 1))
elif ((arg[:2] == '0x') or arg.isdigit()):
... |
.xfail(reason="Remote driver currently doesn't support logs")
def test_no_service_log_path(testdir):
file_test = testdir.makepyfile("\n import pytest\n \n def driver_log():\n return None\n\n .nondestructive\n def test_pass(driver_kwargs):\n assert driver_kwar... |
class Adahessian(torch.optim.Optimizer):
def __init__(self, params, lr=0.1, betas=(0.9, 0.999), eps=1e-08, weight_decay=0.0, hessian_power=1.0, update_each=1, n_samples=1, avg_conv_kernel=False):
if (not (0.0 <= lr)):
raise ValueError(f'Invalid learning rate: {lr}')
if (not (0.0 <= eps))... |
.integration
def test_export_and_import_metadata_df(simple_project):
metadata = simple_project.export_metadata(format_type='df', df_kwargs={'index_col': 'field_name', 'dtype': {'text_validation_min': pd.Int64Dtype(), 'text_validation_max': pd.Int64Dtype()}})
assert (metadata.index.name == 'field_name')
res ... |
def get_random_ddf(args):
total_size = (args.chunk_size * args.in_parts)
chunk_kwargs = {'unique_size': max(int((args.unique_ratio * total_size)), 1), 'gpu': (True if (args.type == 'gpu') else False)}
return dd.from_map(generate_chunk, [(i, args.chunk_size) for i in range(args.in_parts)], meta=generate_chun... |
class ImageDescription(NamedTuple):
id: int
file_name: str
original_size: Tuple[(int, int)]
url: Optional[str] = None
license: Optional[int] = None
coco_url: Optional[str] = None
date_captured: Optional[str] = None
flickr_url: Optional[str] = None
flickr_id: Optional[str] = None
... |
def same_pyname(expected, pyname):
if ((expected is None) or (pyname is None)):
return False
if (expected == pyname):
return True
if ((not isinstance(expected, (pynames.ImportedModule, pynames.ImportedName))) and (not isinstance(pyname, (pynames.ImportedModule, pynames.ImportedName)))):
... |
def playback_results(trackers, sequence):
plot_draw_styles = get_plot_draw_styles()
tracker_results = []
for (trk_id, trk) in enumerate(trackers):
base_results_path = '{}/{}'.format(trk.results_dir, sequence.name)
results_path = '{}.txt'.format(base_results_path)
if os.path.isfile(re... |
def make_annotation(word):
words = [word]
words = split_initial_compounds(words)
words = (words[:(- 1)] + words[(- 1)].split(ORTHOGRAPHIC_COMPOUND_MARKER))
words = split_suffix(words)
words = split_preannotated_compounds(words)
annotations = [Annotation(word) for word in words]
for i in rang... |
def create_path(root: Path, path: Path):
if path.is_absolute():
raise ValueError('Only test using relative paths to prevent leaking outside test environment')
fullpath = (root / path)
if (not fullpath.parent.exists()):
fullpath.parent.mkdir(parents=True)
fullpath.touch() |
class Solution():
def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]:
(m, n) = (len(box), len(box[0]))
queue = deque()
for i in range(m):
j = (n - 1)
temp = ['.' for _ in range(n)]
rest = (n - 1)
while (j >= 0):
if ... |
class W_InputPort(W_Port):
errorname = 'input-port'
_attrs_ = []
def read(self, n):
raise NotImplementedError('abstract class')
def peek(self):
raise NotImplementedError('abstract class')
def readline(self):
raise NotImplementedError('abstract class')
def get_read_handler... |
class LoadTo(SimpleDownloader):
__name__ = 'LoadTo'
__type__ = 'downloader'
__version__ = '0.29'
__status__ = 'testing'
__pattern__ = '
__config__ = [('enabled', 'bool', 'Activated', True), ('use_premium', 'bool', 'Use premium account if available', True), ('fallback', 'bool', 'Fallback to free ... |
.parametrize('kwargs', ({'redirect_to_fallback': False, 'disable_fallback': False}, {'disable_fallback': False, 'redirect_to_fallback': False}))
def test_backwards_compat_kwargs_duplicate_check(kwargs: t.Dict[(str, t.Any)]) -> None:
with pytest.raises(ValueError) as err:
pypiserver.backwards_compat_kwargs(k... |
def attribute_list(names=PROPERTY_NAMES, values=PROPERTY_VALUES):
return st.tuples(st.just(ConvertChildrenToText('attributeList')), st.lists(st.tuples((st.just('attribute') | names), st.lists(((st.tuples(st.just('name'), names) | st.tuples(st.just('values'), values)) | st.tuples(names, values)), max_size=3)), max_s... |
def test_launch_legacy(testdir):
file_test = testdir.makepyfile("\n import pytest\n .nondestructive\n def test_pass(webtext):\n assert webtext == u'Success!'\n ")
testdir.quick_qa('--driver', 'remote', '--capability', 'browserName', 'edge', file_test, passed=1) |
class _BusIterator(_objfinalizer.AutoFinalizedObject):
def __init__(self):
self.buslist = POINTER(_openusb_busid)()
num_busids = c_uint32()
_check(_lib.openusb_get_busid_list(_ctx.handle, byref(self.buslist), byref(num_busids)))
self.num_busids = num_busids.value
def __iter__(sel... |
class CDAE(nn.Module):
def __init__(self, NUM_USER, NUM_MOVIE, NUM_BOOK, EMBED_SIZE, dropout, is_sparse=False):
super(CDAE, self).__init__()
self.NUM_MOVIE = NUM_MOVIE
self.NUM_BOOK = NUM_BOOK
self.NUM_USER = NUM_USER
self.emb_size = EMBED_SIZE
self.user_embeddings = ... |
class RandomGoalAntEnv(AntEnv):
('ctrl_cost_coeff', type=float, help='cost coefficient for controls')
('survive_reward', type=float, help='bonus reward for being alive')
('contact_cost_coeff', type=float, help='cost coefficient for contact')
def __init__(self, reward_type='dense', terminate_at_goal=True... |
class Model(nn.Module):
def __init__(self, args, embedding, encoder, target, subencoder=None):
super(Model, self).__init__()
self.embedding = embedding
self.encoder = encoder
self.target = target
if (subencoder is not None):
(self.vocab, self.sub_vocab) = (args.vo... |
class TestLibraryError(BaseTestCase):
def test_from_exception_not_found(self):
exc = errors.LibraryError.from_exception(ValueError('visa.dll: image not found'), 'visa.dll')
assert ('File not found' in str(exc))
def test_from_exception_wrong_arch(self):
exc = errors.LibraryError.from_exce... |
class StructTypeSpecifier(object):
def __init__(self, is_union, tag, declarations):
self.is_union = is_union
self.tag = tag
self.declarations = declarations
def __repr__(self):
if self.is_union:
s = 'union'
else:
s = 'struct'
if self.tag:
... |
def _consolidate_replicated_chunked_tensor_entries(rank_to_entries: List[Dict[(str, Entry)]]) -> List[Dict[(str, Entry)]]:
groups: Dict[(str, List[ChunkedTensorEntry])] = defaultdict(list)
for entries in rank_to_entries:
for (logical_path, entry) in entries.items():
if (is_replicated_entry(e... |
class BasicClosureCompiler(ClosureCompiler):
def _make_source_builder(self, builder: CodeBuilder) -> CodeBuilder:
main_builder = CodeBuilder()
main_builder += 'def _closure_maker():'
with main_builder:
main_builder.extend(builder)
return main_builder
def _compile(self... |
class Queries():
def __init__(self, path=None, data=None):
self.path = path
if data:
assert isinstance(data, dict), type(data)
(self._load_data(data) or self._load_file(path))
def __len__(self):
return len(self.data)
def __iter__(self):
return iter(self.da... |
def circ_vtest(angles, dir=0.0, w=None, d=None):
angles = np.asarray(angles)
if (w is None):
r = circ_r(angles)
mu = circ_mean(angles)
n = len(angles)
else:
assert (len(angles) == len(w)), 'Input dimensions do not match'
r = circ_r(angles, w, d)
mu = circ_mean... |
def test_transform_radians():
with pytest.warns(FutureWarning):
WGS84 = pyproj.Proj('+init=EPSG:4326')
ECEF = pyproj.Proj(proj='geocent', ellps='WGS84', datum='WGS84')
with pytest.warns(FutureWarning):
assert_almost_equal(pyproj.transform(ECEF, WGS84, (- 2704026.01), (- 4253051.81), 3895878.... |
def build_model(opt, dicts):
opt = backward_compatible(opt)
onmt.constants.layer_norm = opt.layer_norm
onmt.constants.weight_norm = opt.weight_norm
onmt.constants.activation_layer = opt.activation_layer
onmt.constants.version = 1.0
onmt.constants.attention_out = opt.attention_out
onmt.consta... |
def _parse_yaml_area_file(area_file_name, *regions):
area_dict = _read_yaml_area_file_content(area_file_name)
area_list = (regions or area_dict.keys())
res = []
for area_name in area_list:
params = area_dict.get(area_name)
if (params is None):
raise AreaNotFound('Area "{0}" n... |
def test_replace_component_list_of_foo_by_real():
foo_wrap = Foo_shamt_list_wrap(32)
foo_wrap.elaborate()
order = list(range(5))
random.shuffle(order)
for i in order:
foo_wrap.replace_component(foo_wrap.inner[i], Real_shamt)
simple_sim_pass(foo_wrap)
print()
foo_wrap.in_ = Bits32... |
_config
def test_toggle_max(manager):
manager.c.next_layout()
assert (len(manager.c.layout.info()['stacks']) == 2)
manager.test_window('two')
manager.test_window('one')
assert (manager.c.group.info()['focus'] == 'one')
assert (manager.c.window.info()['width'] == 398)
assert (manager.c.window... |
.skip
.allow_bad_gc
def test_background_plotter_export_vtkjs(qtbot, tmpdir, plotting):
output_dir = str(tmpdir.mkdir('tmpdir'))
assert os.path.isdir(output_dir)
plotter = BackgroundPlotter(show=False, off_screen=False, title='Testing Window')
assert_hasattr(plotter, 'app_window', MainWindow)
window ... |
()
def update_flight_traffic_fill():
max_objects = 20
threshold = 0.01
log.info('Updating flight traffic fill')
for flight in Flight.objects.filter(live=True, campaign__campaign_type=PAID_CAMPAIGN, total_views__gt=0):
publisher_traffic_fill = {}
country_traffic_fill = {}
region_t... |
def task_create_random_data(node: Annotated[(PickleNode, Product)]=data_catalog['data']) -> None:
rng = np.random.default_rng(0)
beta = 2
x = rng.normal(loc=5, scale=10, size=1000)
epsilon = rng.standard_normal(1000)
y = ((beta * x) + epsilon)
df = pd.DataFrame({'x': x, 'y': y})
node.save(df... |
def train(args, epoch, train_data, device, model, criterion, optimizer):
model.train()
train_loss = 0.0
top1 = AvgrageMeter()
top5 = AvgrageMeter()
for (step, (inputs, targets)) in enumerate(train_data):
(inputs, targets) = (inputs.to(device), targets.to(device))
optimizer.zero_grad(... |
class AudioFormatTestCase(unittest.TestCase):
def test_equality_true(self):
af1 = AudioFormat(2, 8, 44100)
af2 = AudioFormat(2, 8, 44100)
self.assertEqual(af1, af2)
def test_equality_false(self):
channels = [1, 2]
sample_sizes = [8, 16]
sample_rates = [11025, 2205... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.