code stringlengths 281 23.7M |
|---|
def copy_config(config, config_path):
def _get_last_subfolder_path(path):
subfolders = [f.path for f in os.scandir(path) if f.is_dir()]
return max(subfolders, default=None)
checkpoint_dir = os.path.join(config['trainer'].pop('checkpoint_dir'), 'logs')
last_run_dir = _get_last_subfolder_path(... |
class KiteQuadtree(KiteView):
title = 'Scene.quadtree'
def __init__(self, spool):
model = spool.model
self.model = model
self.main_widget = KiteQuadtreePlot(model)
self.tools = {}
self.param_quadtree = KiteParamQuadtree(model, self.main_widget, expanded=True)
self... |
class FlexibleReplayPool(ReplayPool):
def __init__(self, max_size, fields_attrs, obs_filter=False, modify_rew=False):
super(FlexibleReplayPool, self).__init__()
max_size = int(max_size)
self._max_size = max_size
self.fields = {}
self.fields_attrs = {}
self.add_fields(... |
class TestSpectralClusterer(unittest.TestCase):
def setUp(self):
super().setUp()
pass
def test_6by2_matrix(self):
matrix = np.array([[1.0, 0.0], [1.1, 0.1], [0.0, 1.0], [0.1, 1.0], [0.9, (- 0.1)], [0.0, 1.2]])
refinement_options = refinement.RefinementOptions(gaussian_blur_sigma=... |
def mirror_files(*path_patterns: str, exclude_name_patterns: Sequence[str]=['.*', '_*'], include_directories: bool=True, cwd: Optional[Union[(Path, str)]]=None, verbose: Optional[bool]=None) -> List[Path]:
log.bad('workflow: mirror_files() has been deprecated')
if (cwd is None):
cwd = Path.cwd()
eli... |
class SmtLibCommand(namedtuple('SmtLibCommand', ['name', 'args'])):
def serialize(self, outstream=None, printer=None, daggify=True):
if ((outstream is None) and (printer is not None)):
outstream = printer.stream
elif ((outstream is not None) and (printer is None)):
if daggify... |
class SocketTests(unittest.TestCase):
def setUp(self):
self.orgsocket = socket.socket
socket.socket = MockSocket
self.proxy = Proxy()
self.proxy._fdmap = {}
def tearDown(self):
socket.socket = self.orgsocket
def testProxyFd(self):
self.proxy._poll = MockPoll()... |
def upgrade(op, tables, tester):
op.create_table('namespaceautoprunepolicy', sa.Column('id', sa.Integer(), nullable=False), sa.Column('uuid', sa.String(length=36), nullable=False), sa.Column('namespace_id', sa.Integer(), nullable=False), sa.Column('policy', sa.Text(), nullable=False), sa.ForeignKeyConstraint(['name... |
class ReportSlaveIdResponse(ModbusResponse):
function_code = 17
_rtu_byte_count_pos = 2
def __init__(self, identifier=b'\x00', status=True, **kwargs):
ModbusResponse.__init__(self, **kwargs)
self.identifier = identifier
self.status = status
self.byte_count = None
def enco... |
def call_cmd(command, *args, **kwargs):
ignore_errors = kwargs.pop('ignore_errors', False)
try:
sp = exec_cmd(command, *args, **kwargs)
except Exception as exc:
if (not ignore_errors):
raise
returncode = 1
stdoutdata = ''
stderrdata = to_str(exc).strip()
... |
def get_cifar100c(ctype, intensity, mean=(0.5071, 0.4867, 0.4408), std=(0.2675, 0.2565, 0.2761), root='./data', download=True, **kwargs):
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize(mean, std)])
return cifarc.CIFAR100C(root, ctype, intensity, transform=transform, download=downloa... |
class PSPModule(nn.Module):
def __init__(self, in_channels, sizes=(1, 2, 3, 6), use_bathcnorm=True):
super().__init__()
self.blocks = nn.ModuleList([PSPBlock(in_channels, (in_channels // len(sizes)), size, use_bathcnorm=use_bathcnorm) for size in sizes])
def forward(self, x):
xs = ([bloc... |
.parametrize('source, result', [('\nfrom __future__ import print_function,\n division, with_statement,\n unicode_literals\n', (((_FF.print_function | _FF.division) | _FF.with_statement) | _FF.unicode_literals)), ("\nfrom __future__ import print_function, division\nprint('hello')\n", (_FF.print_function | _FF.divi... |
def test_H_opt():
o = check_success('-H', 'formatter', 'html')
assert ('HTML' in o)
o = check_success('-H', 'lexer', 'python')
assert ('Python' in o)
o = check_success('-H', 'filter', 'raiseonerror')
assert ('raiseonerror' in o)
e = check_failure('-H', 'lexer', 'foobar')
assert ('not fou... |
class GraphDisplay(DisplayOptionalPage):
def __init__(self, parent, tabname, helptext, waittime, command=None):
self.trace_var = None
super().__init__(parent, tabname, helptext, waittime, command)
def add_options(self):
self.add_option_refresh()
super().add_options()
self... |
class Effect11942(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredChargeBoost((lambda mod: mod.charge.requiresSkill('Missile Launcher Operation')), 'kineticDamage', ship.getModifiedItemAttr('shipBonusGD1'), skill='Gallente Destroyer', **kwarg... |
class ImageNetEvaluator():
def __init__(self, tfrecord_dir: str, training_inputs: List[str], data_inputs: List[str], validation_inputs: List[str], image_size: int=224, batch_size: int=128, format_bgr: bool=False, model_type: str='resnet'):
if (not data_inputs):
raise ValueError('data_inputs list... |
def test_set_observation_field(requests_mock):
requests_mock.post(f'{API_V1}/observation_field_values', json=SAMPLE_DATA['post_put_observation_field_value'], status_code=200)
response = set_observation_field(observation_id=, observation_field_id=31, value='fouraging', access_token='token')
assert (response[... |
class PublisherPaidImpression(BasePublisherImpression):
publisher = models.ForeignKey(Publisher, related_name='publisher_paid_impressions', on_delete=models.PROTECT, null=True)
class Meta():
ordering = ('-date',)
unique_together = ('publisher', 'date')
verbose_name_plural = _('Publisher ... |
def train(epoch):
print(('Epoch: %d' % epoch))
net.train()
train_loss = 0
correct = 0
total = 0
for (batch_idx, (inputs, targets)) in enumerate(trainloader):
(inputs, targets) = (inputs.cuda(), targets.cuda())
optimizer.zero_grad()
(outputs, kl) = net(inputs)
loss... |
class BinPacking(OptimizationApplication):
def __init__(self, weights: List[int], max_weight: int, max_number_of_bins: Optional[int]=None) -> None:
self._weights = weights
self._max_weight = max_weight
if (max_number_of_bins is None):
self._max_number_of_bins = len(weights)
... |
class F28_TestCase(CommandTest):
command = 'authselect'
def runTest(self):
self.assert_parse('authselect')
self.assert_parse('authselect select winbind', 'authselect select winbind\n')
self.assert_parse('authselect select sssd with-mkhomedir', 'authselect select sssd with-mkhomedir\n') |
class CSSHeaderFile(object):
def __init__(self, filename):
self.fn = filename
self.data = []
self.read()
def read_wf_file(self, fn, nbytes, dtype, foff=0):
with open(fn, 'rb') as f:
fmt = (dtype % nbytes)
f.seek(foff)
try:
data ... |
class Host(ni_abc.CLAHost):
def __init__(self, server: ni_abc.ServerHost) -> None:
self.server = server
async def problems(self, aio_client: aio usernames: AbstractSet[str]) -> Mapping[(ni_abc.Status, AbstractSet[str])]:
base_url = '
url = (base_url + ','.join(usernames))
self.se... |
def decoding_layer(target_letter_to_int, decoding_embedding_size, num_layers, rnn_size, target_sequence_length, max_target_sequence_length, encoder_state, decoder_input):
target_vocab_size = len(target_letter_to_int)
decoder_embeddings = tf.Variable(tf.random_uniform([target_vocab_size, decoding_embedding_size]... |
def visualize_data():
data = contrib.get_data()
models = morefusion.datasets.YCBVideoModels()
colormap = imgviz.label_colormap()
scenes = {'pcd': trimesh.Scene(), 'grid_target': trimesh.Scene(), 'grid_nontarget_empty': trimesh.Scene(), 'cad': trimesh.Scene()}
rgb = data['rgb']
depth = data['dept... |
.parametrize('proc_name', ['s1', 's2', 's3'])
def test_clean_shutdown(tcp_port, proc_name, xprocess):
class Starter(ProcessStarter):
pattern = 'started'
args = [sys.executable, server_path, tcp_port]
xprocess.ensure(proc_name, Starter)
info = xprocess.getinfo(proc_name)
assert info.isrun... |
_exception
def get_seatmap(html_seatmap, return_empty_seat=False) -> dict:
seat_map = {}
try:
soup = BeautifulSoup(html_seatmap, 'html.parser')
layout_grid = soup.find(name='div', attrs={'class': 'layout_grid', 'id': 'content-container'})
if return_empty_seat:
reg_expression ... |
def decode_dxt3(data, width, height):
out = (ctypes.c_ubyte * ((width * height) * 4))()
pitch = (width << 2)
image_offset = 0
for (a0, a1, a2, a3, a4, a5, a6, a7, c0_lo, c0_hi, c1_lo, c1_hi, b0, b1, b2, b3) in split_16byte.findall(data):
color0 = (ord(c0_lo) | (ord(c0_hi) << 8))
color1 =... |
class DoubleConv(nn.Sequential):
def __init__(self, in_channels, out_channels, encoder, kernel_size=3, order='crg', num_groups=8):
super(DoubleConv, self).__init__()
if encoder:
conv1_in_channels = in_channels
conv1_out_channels = (out_channels // 2)
if (conv1_out... |
class CmdHelp(Command):
key = 'help'
aliases = ['?']
locks = 'cmd:all()'
arg_regex = '\\s|$'
return_cmdset = True
help_more = HELP_MORE
suggestion_cutoff = 0.6
suggestion_maxnum = 5
def msg_help(self, text):
if type(self).help_more:
usemore = True
if (... |
class GuiChangeLocalModuleMutationCommand(wx.Command):
def __init__(self, fitID, position, mutation, oldMutation=None):
wx.Command.__init__(self, True, 'Change Local Module Mutation')
self.internalHistory = InternalCommandHistory()
self.fitID = fitID
self.position = position
... |
class RS485(serial.Serial):
def __init__(self, *args, **kwargs):
super(RS485, self).__init__(*args, **kwargs)
self._alternate_rs485_settings = None
def write(self, b):
if (self._alternate_rs485_settings is not None):
self.setRTS(self._alternate_rs485_settings.rts_level_for_tx... |
def get_cfg(blocks: list[BasicBlock]) -> CFG:
succ_map = {}
pred_map: dict[(BasicBlock, list[BasicBlock])] = {}
exits = set()
for block in blocks:
assert (not any((isinstance(op, ControlOp) for op in block.ops[:(- 1)]))), 'Control-flow ops must be at the end of blocks'
succ = list(block.... |
def sample_data(opt):
dataset = CECT_dataset(path=opt['src_data'])
n = len(dataset)
X = torch.Tensor(n, 1, 28, 28, 28)
Y = torch.LongTensor(n)
inds = torch.randperm(len(dataset))
for (i, index) in enumerate(inds):
(x, y) = dataset[index]
X[i] = x
Y[i] = y
return (X, Y... |
class RBitfield(BitfieldBase):
def _more(self):
c = self._read(1)
self.bitfield <<= 8
self.bitfield += ord(c)
self.bits += 8
def snoopbits(self, n=8):
if (n > self.bits):
self.needbits(n)
return ((self.bitfield >> (self.bits - n)) & self._mask(n))
... |
_torch
_vision
class CLIPImageProcessingTestFourChannels(ImageProcessingSavingTestMixin, unittest.TestCase):
image_processing_class = (CLIPImageProcessor if is_vision_available() else None)
def setUp(self):
self.image_processor_tester = CLIPImageProcessingTester(self, num_channels=4)
self.expect... |
class MyghtyJavascriptLexer(DelegatingLexer):
name = 'JavaScript+Myghty'
aliases = ['javascript+myghty', 'js+myghty']
mimetypes = ['application/x-javascript+myghty', 'text/x-javascript+myghty', 'text/javascript+mygthy']
url = '
version_added = '0.6'
def __init__(self, **options):
super()... |
def load_modules(location):
if (os.name == 'nt'):
location = location.replace('$PWD', os.getcwd())
location = os.path.expanduser(os.path.expandvars(location))
if (not os.path.exists(location)):
raise OSError("Location '{0}' to load modules does not exist".format(location))
for (p, _, f) ... |
class LockedDropout(nn.Module):
def __init__(self, dropout):
super().__init__()
self.dropout = dropout
def forward(self, x):
dropout = self.dropout
if (not self.training):
return x
m = x.data.new(x.size(0), 1, x.size(2)).bernoulli_((1 - dropout))
mask ... |
class OffensiveMessageValidatorsTests(TestCase):
def test_accepts_future_date(self):
future_date_validator(datetime(3000, 1, 1, tzinfo=UTC))
def test_rejects_non_future_date(self):
with self.assertRaises(ValidationError):
future_date_validator(datetime(1000, 1, 1, tzinfo=UTC)) |
def randomNetworkOnly(qnnArch):
networkUnitaries = [[]]
for l in range(1, len(qnnArch)):
numInputQubits = qnnArch[(l - 1)]
numOutputQubits = qnnArch[l]
networkUnitaries.append([])
for j in range(numOutputQubits):
unitary = randomQubitUnitary((numInputQubits + 1))
... |
class VacationDirector():
def main(*args) -> None:
outdoorsyVacationBuilder: VacationBuilder = OutdoorsVacationBuilder()
outdoorsyVacation: Vacation = outdoorsyVacationBuilder.addAccommodation_3('Two person tent', 2020, 7, 1, 5, 34).addEvent('Beach').addAccommodation_2('Two person tent').addEvent('M... |
def test_fileformatjson_pass_no_substitutions(fs):
payload = '{\n "key1": "value1",\n "key2": "value2",\n "key3": "value3"\n}\n'
in_path = './tests/testfiles/test.json'
fs.create_file(in_path, contents=payload)
context = Context({'ok1': 'ov1', 'fileFormatJson': {'in': in_path, 'out': './tests/t... |
.parametrize('rank', range((_WORLD_SIZE * 2)))
def test_replicated_entries_only_on_rank_0(rank: int) -> None:
local_manifest_0 = get_manifest_for_rank(metadata=SnapshotMetadata(version='0.0.0', world_size=_WORLD_SIZE, manifest=_MANIFEST_0), rank=rank)
local_manifest_1 = get_manifest_for_rank(metadata=SnapshotMe... |
def freeze_training_mode(model):
classes = {type(x) for x in model.modules()}
classes = {x for x in classes if (not hasattr(x, '__constants__'))}
for cls in classes:
cls.__annotations__['training'] = torch.jit.Final[bool]
(yield)
for cls in classes:
cls.__annotations__['training'] = ... |
class HttpPostHandler(Handler):
def __init__(self, config=None):
Handler.__init__(self, config)
self.metrics = []
self.batch_size = int(self.config['batch'])
self.format = self.config['format']
self.url = self.config['url']
def get_default_config_help(self):
confi... |
class SliderCardsSection(blocks.StructBlock):
title = blocks.CharBlock(required=False)
spacing = blocks.ChoiceBlock(default='xl', choices=[('xl', 'Extra Large'), ('3xl', '3 Extra Large')])
snake_background = blocks.BooleanBlock(required=False, default=False)
cards = blocks.StreamBlock([('simple_text_car... |
def create_user_access_token(user_obj, client_id, scope, access_token=None, expires_in=9000):
access_token = (access_token or random_string_generator(length=40)())
token_name = access_token[:ACCESS_TOKEN_PREFIX_LENGTH]
token_code = access_token[ACCESS_TOKEN_PREFIX_LENGTH:]
assert (len(token_name) == ACC... |
def find_candidate_tile_locations(num_rings, base_tile: Tile, align_tiles: list, integer_align=True):
result_tiles = [base_tile]
last_ring = [base_tile]
for i in range(0, num_rings):
print(f'computing ring_{i}')
last_ring_num = len(last_ring)
for last_ring_idx in range(last_ring_num)... |
_task('self_supervision_zero_task')
class SelfSupervisionZeroTask(SelfSupervisionTask):
def __init__(self, config: AttrDict):
super().__init__(config)
def init_distributed_data_parallel_model(self):
super().init_distributed_data_parallel_model()
broadcast_buffers = (self.broadcast_buffer... |
class Effect1472(BaseEffect):
type = 'passive'
def handler(fit, container, context, projectionRange, **kwargs):
level = (container.level if ('skill' in context) else 1)
penalize = (False if (('skill' in context) or ('implant' in context) or ('booster' in context)) else True)
fit.modules.... |
def repass_backward(model, subnet, model_checkpoints, opt_checkpoints, outer_grads_w, loader, theta):
subnet_grads = 0
theta_grads = 0
old_params = model_checkpoints[0]
old_opt = opt_checkpoints[0]
for (batch_idx, (train_x, train_y, _, _)) in enumerate(loader):
(train_x, train_y) = (train_x.... |
class FullSyncPeriodicTimerTest(unittest.TestCase):
def _full_sync_worker_without_timeout(cls) -> bool:
process_group = dist.group.WORLD
interval_threshold = timedelta(seconds=5)
fsp_timer = FullSyncPeriodicTimer(interval_threshold, none_throws(process_group))
return fsp_timer.check(... |
class BreakHamiltonianIntoPotentialKineticArraysTest(unittest.TestCase):
def test_simple_hamiltonian(self):
hamiltonian = (((FermionOperator('3^ 1^ 3 1') + FermionOperator('1^ 1')) - FermionOperator('1^ 2')) - FermionOperator('2^ 1'))
(potential_terms, kinetic_terms) = diagonal_coulomb_potential_and... |
def test_audit_dry_run(monkeypatch, vuln_service, dep_source):
service = vuln_service()
source = dep_source()
auditor = Auditor(service, options=AuditOptions(dry_run=True))
service = pretend.stub(query_all=pretend.call_recorder((lambda s: None)))
logger = pretend.stub(info=pretend.call_recorder((lam... |
def get_translated_function(corefunc, language, stage=False):
if (language == 'core'):
return corefunc
lang = importlib.import_module(f'pystage.{language}')
cls = (lang.stage_class if stage else lang.sprite_class)
for (name, func) in inspect.getmembers(cls, predicate=inspect.isfunction):
... |
class WeekdayCalendarTestCase(ExchangeCalendarTestBase, TestCase):
answer_key_filename = '24-5'
calendar_class = WeekdayCalendar
start_date = pd.Timestamp('2018-01-01', tz=UTC)
end_date = pd.Timestamp('2018-12-31', tz=UTC)
MAX_SESSION_HOURS = 24
GAPS_BETWEEN_SESSIONS = False
HAVE_EARLY_CLOSE... |
def handler(ql: Qiling):
ah = ql.arch.regs.ah
leaffunc = {0: __leaf_00, 2: __leaf_02, 8: __leaf_08, 65: __leaf_41, 66: __leaf_42, 67: __leaf_43}.get(ah)
if (leaffunc is None):
ql.log.exception(f'leaf {ah:02x}h of INT 13h is not implemented')
raise NotImplementedError()
leaffunc(ql) |
def configure_views(app):
('/<key>')
def get(key, db: SQLAlchemy):
try:
kv = db.session.query(KeyValue).filter((KeyValue.key == key)).one()
except NoResultFound:
response = jsonify(status='No such key', context=key)
response.status = '404 Not Found'
... |
class GetImage(rq.ReplyRequest):
_request = rq.Struct(rq.Opcode(73), rq.Set('format', 1, (X.XYPixmap, X.ZPixmap)), rq.RequestLength(), rq.Drawable('drawable'), rq.Int16('x'), rq.Int16('y'), rq.Card16('width'), rq.Card16('height'), rq.Card32('plane_mask'))
_reply = rq.Struct(rq.ReplyCode(), rq.Card8('depth'), rq... |
class BCPPCompiler(CCompiler):
compiler_type = 'bcpp'
executables = {}
_c_extensions = ['.c']
_cpp_extensions = ['.cc', '.cpp', '.cxx']
src_extensions = (_c_extensions + _cpp_extensions)
obj_extension = '.obj'
static_lib_extension = '.lib'
shared_lib_extension = '.dll'
static_lib_for... |
class Migration(migrations.Migration):
dependencies = [('sponsors', '0004_auto__1622')]
operations = [migrations.RenameField(model_name='sponsorshipbenefit', old_name='value', new_name='internal_value'), migrations.AddField(model_name='sponsorshipbenefit', name='capacity', field=models.PositiveIntegerField(blan... |
def main():
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
if ((len(sys.argv) == 2) and sys.argv[1].endswith('.json')):
(model_args, data_args, training_args) = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
else:
(model_args, data_args,... |
class QuotedString(Token):
def __init__(self, quoteChar, escChar=None, escQuote=None, multiline=False, unquoteResults=True, endQuoteChar=None, convertWhitespaceEscapes=True):
super().__init__()
quoteChar = quoteChar.strip()
if (not quoteChar):
warnings.warn('quoteChar cannot be t... |
(frozen=True, order=True, slots=True)
class AreaIdentifier():
region_name: str
area_name: str
def __post_init__(self) -> None:
assert isinstance(self.region_name, str)
assert isinstance(self.area_name, str)
def as_json(self) -> dict:
return {'region': self.region_name, 'area': se... |
.parametrize('url, rev', [('git+ None), ('git+ 'master')])
def test_add_with_git_constraint_with_subdirectory(url: str, rev: (str | None), tester: CommandTester, repo: TestRepository) -> None:
repo.add_package(Package('pendulum', '2.0.5'))
tester.execute(url)
expected = '\nUpdating dependencies\nResolving d... |
def setup_logging(args):
project_name = args.model_ckpt.split('/')[(- 1)]
logger = logging.getLogger(__name__)
log_dir = (Path(args.save_dir) / 'log/')
log_dir.mkdir(exist_ok=True)
filename = f'debug_{accelerator.process_index}.log'
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(nam... |
class NoMPLineBufferedPipeEnd(object):
def __init__(self, name):
self.name = name
self.lines = []
def fileno(self):
return 0
def flush(self):
pass
def close(self):
pass
def write(self, data, udp=False):
self.send(data)
def recv(self, timeout=0):
... |
class Migration(migrations.Migration):
dependencies = [migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('plugins', '0004_merge__0223')]
operations = [migrations.AddField(model_name='plugin', name='maintainer', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE,... |
class MetricLogger():
def __init__(self, delimiter='\t'):
self.meters = defaultdict(SmoothedValue)
self.delimiter = delimiter
def update(self, **kwargs):
for (k, v) in kwargs.items():
if isinstance(v, torch.Tensor):
v = v.item()
assert isinstance(v... |
def main(argv):
display = Display()
if (not display.has_extension('XFIXES')):
if (display.query_extension('XFIXES') is None):
print('XFIXES extension not supported', file=sys.stderr)
return 1
xfixes_version = display.xfixes_query_version()
print(('Found XFIXES version %s.... |
def load_dataset_files(vol_files=None, load_n=None, mode='train', load_segs=True, load_contours=False, do_mask_vols=False, use_labels=None):
if (vol_files is None):
vol_files = get_dataset_files_list(mode=mode)
if (load_n is None):
load_n = len(vol_files)
vol_size = (160, 192, 224)
vols ... |
class TypeOfAny():
__slots__ = ()
unannotated: Final = 1
explicit: Final = 2
from_unimported_type: Final = 3
from_omitted_generics: Final = 4
from_error: Final = 5
special_form: Final = 6
from_another_any: Final = 7
implementation_artifact: Final = 8
suggestion_engine: Final = 9 |
class ImageNetDataPipeline():
def get_val_dataloader() -> torch.utils.data.DataLoader:
data_loader = ImageNetDataLoader(DATASET_DIR, image_size=image_net_config.dataset['image_size'], batch_size=image_net_config.evaluation['batch_size'], is_training=False, num_workers=image_net_config.evaluation['num_worker... |
class FrozenBot():
def __init__(self, api, about, owner, hide_commands, before_help, after_help, link_preview_in_help, validate_callback_signatures, process_backlog, lang, itself, commands_re, commands, chains, scheduler, main_component_id, bot_id, shared_memory, update_processors, override_i18n):
object.__... |
def main(args: argparse.Namespace):
log_level = logging.INFO
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', handlers=[logging.StreamHandler(sys.stdout)], level=log_level)
logger.setLevel(log_level)
set_seed(args.seed)
wandb.init()
... |
class UrlFieldTest(StringTestMixin, BaseFieldTestMixin, FieldTestCase):
field_class = partial(fields.Url, 'endpoint')
def test_defaults(self):
field = fields.Url('endpoint')
assert (not field.required)
assert (field.__schema__ == {'type': 'string'})
def test_invalid_object(self, app)... |
def generate_bin_op_both_wrappers(cl: ClassIR, fn: FuncIR, fn_rev: FuncIR, emitter: Emitter, gen: WrapperGenerator) -> None:
emitter.emit_line('if (PyObject_IsInstance(obj_left, (PyObject *){})) {{'.format(emitter.type_struct_name(cl)))
gen.emit_arg_processing(error=GotoHandler('typefail'), raise_exception=Fals... |
def Transpose2D_block(filters, stage, kernel_size=(3, 3), upsample_rate=(2, 2), transpose_kernel_size=(4, 4), use_batchnorm=False, skip=None):
def layer(input_tensor):
(conv_name, bn_name, relu_name, up_name) = handle_block_names(stage)
x = Conv2DTranspose(filters, transpose_kernel_size, strides=ups... |
def define_test_input(args):
if (args.test_case == 1):
a = np.array([[1, 2], [3, 4]])
elif (args.test_case == 2):
np.random.seed(42)
(dim1, dim2) = np.random.randint(1, 100, (2,))
a = np.random.rand(dim1, dim2)
elif (args.test_case == 3):
a = np.arange(24).reshape(2, ... |
def hyphenate_each_word(language: str, transcribed_data: list[TranscribedData]) -> (list[list[str]] | None):
lang_region = language_check(language)
if (lang_region is None):
print(f"{ULTRASINGER_HEAD} {red_highlighted('Error in hyphenation for language ')} {blue_highlighted(language)}{red_highlighted(',... |
def test_create_lane_links_junction3():
planview = []
lanec = []
lanel = []
laner = []
lanesec = []
lanes = []
rm = pyodrx.RoadMark(pyodrx.RoadMarkType.solid, 0.2, rule=pyodrx.MarkRule.no_passing)
geom = []
geom.append(pyodrx.Line(50))
geom.append(pyodrx.Arc(0.01, angle=(np.pi / ... |
def get_inference_utils(opt):
assert (opt.inference_crop in ['center', 'nocrop'])
normalize = get_normalize_method(opt.mean, opt.std, opt.no_mean_norm, opt.no_std_norm)
if (opt.train_crop == 'other'):
spatial_transform = [Resize((opt.scale_h, opt.scale_w)), RandomCrop(opt.sample_size), ToTensor()]
... |
class MiscTests(unittest.TestCase):
def test_client_default_logger(self):
client = Protocol(CLIENT)
logger = logging.getLogger('websockets.client')
self.assertIs(client.logger, logger)
def test_server_default_logger(self):
server = Protocol(SERVER)
logger = logging.getLog... |
class TableDataModel(DataModel):
db_view: DataModel = None
def set_db_view(self, db_data_model: DataModel) -> None:
self.db_view = db_data_model
def get_llm_side_data(self, serialize_method: str='tsv', num_visible_rows: int=3) -> Any:
table_data = self.raw_data
table_name = self.raw_... |
.end_to_end()
def test_errors_during_loading_nodes_have_info(runner, tmp_path):
source = '\n from __future__ import annotations\n from pathlib import Path\n from typing import Any\n import attrs\n import pickle\n\n \n class PickleNode:\n name: str\n path: Path\n signature: ... |
def positive_region(region):
(west, east, south, north) = [float(x) for x in region]
assert (((- 180.0) - 360.0) <= west < 180.0)
assert ((- 180.0) < east <= (180.0 + 360.0))
assert ((- 90.0) <= south < 90.0)
assert ((- 90.0) < north <= 90.0)
if (east < west):
east += 360.0
if (west ... |
def test_unset_setting(tester: CommandTester, config: Config, config_cache_dir: Path) -> None:
tester.execute('virtualenvs.path /some/path')
tester.execute('virtualenvs.path --unset')
tester.execute('--list')
cache_dir = json.dumps(str(config_cache_dir))
venv_path = json.dumps(os.path.join('{cache-d... |
('I wait until the editor has started')
def wait_editor(qtbot, editor_pid_watcher):
if (not editor_pid_watcher.has_pidfile):
with qtbot.wait_signal(editor_pid_watcher.appeared, raising=False):
pass
if (not editor_pid_watcher.manual_check()):
pytest.fail('Editor pidfile failed to appe... |
_scoring('wer')
class WerScorer(object):
def __init__(self, *unused):
self.reset()
def reset(self):
self.distance = 0
self.ref_length = 0
def add_string(self, ref, pred):
import editdistance
ref_items = ref.split()
pred_items = pred.split()
self.distan... |
def set_max_weight(ctx, param, value):
if (value is not None):
prev = ctx.meta.get(SET_LIMIT, None)
if (prev is None):
ctx.meta[SET_LIMIT] = 'max-weight'
elif (prev != 'max-weight'):
raise click.UsageError('Cannot specify both --num-files and --max-weight')
return... |
def find_enums(tree):
for node in ast.walk(tree):
if (not isinstance(node, ast.Assign)):
continue
if (node.type_comment is None):
continue
if ('.' not in node.type_comment):
continue
if (not node.type_comment.startswith('Q')):
continue
... |
.parametrize('package', invalid_files)
def test_upload_badFilename(package, root, testapp):
resp = testapp.post('/', params={':action': 'file_upload'}, upload_files=[('content', package, b'')], expect_errors=1)
assert (resp.status == '400 Bad Request')
assert (f'Bad filename: {package}' in resp.text) |
.requires_user_action
class TextMotionSelectWindowEventsTest(WindowEventsTestCase):
number_of_checks = 10
motion_keys = (key.MOTION_UP, key.MOTION_RIGHT, key.MOTION_DOWN, key.MOTION_LEFT, key.MOTION_NEXT_PAGE, key.MOTION_PREVIOUS_PAGE, key.MOTION_BACKSPACE, key.MOTION_DELETE)
def setUp(self):
super(... |
def test_preferred_colorscheme_unsupported(request, quteproc_new):
if request.config.webengine:
pytest.skip('preferred-color-scheme is supported')
args = (_base_args(request.config) + ['--temp-basedir'])
quteproc_new.start(args)
quteproc_new.open_path('data/darkmode/prefers-color-scheme.html')
... |
class D_GET_LOGITS(nn.Module):
def __init__(self, ndf):
super(D_GET_LOGITS, self).__init__()
self.df_dim = ndf
self.joint_conv = nn.Sequential(nn.Conv2d(((ndf * 16) + 256), (ndf * 2), 3, 1, 1, bias=False), nn.LeakyReLU(0.2, inplace=True), nn.Conv2d((ndf * 2), 1, 4, 1, 0, bias=False))
def... |
def construct_attr(attr_base, attr):
base_rtype = attr_base.get_rtype()
if isinstance(attr_base, CurComp):
if base_rtype.has_property(attr):
return CurCompAttr(attr_base, attr)
if isinstance(base_rtype, rt.Component):
if base_rtype.has_property(attr):
return SubCompAt... |
def model_loader(model_name, dataset_name, device, num_channels, num_classes, img_size):
logger.info(('Load model [%s] for dataset [%s]. Train using device [%s].' % (model_name, dataset_name, device)))
net_glob = None
if ((model_name == 'cnn') and (dataset_name == 'cifar')):
net_glob = CNNCifar(num_... |
class DeletionTests(AuthenticatedAPITestCase):
def setUpTestData(cls):
cls.test_name = OffTopicChannelName.objects.create(name='lemons-lemonade-stand')
cls.test_name_2 = OffTopicChannelName.objects.create(name='bbq-with-bisk')
def test_deleting_unknown_name_returns_404(self):
url = rever... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.