code stringlengths 281 23.7M |
|---|
.skipif("sys.platform != 'win32'")
def test_path_to_url_win() -> None:
assert (path_to_url('c:/tmp/file') == 'file:///c:/tmp/file')
assert (path_to_url('c:\\tmp\\file') == 'file:///c:/tmp/file')
assert (path_to_url('\\\\unc\\as\\path') == 'file://unc/as/path')
path = (Path('.') / 'file')
assert (pat... |
def check_data(args):
source_data_dir = os.path.expanduser('~/Data/AI2thor_offline_data_2.0.2/')
scene_data_dir = args.data_dir
if (os.path.exists(scene_data_dir) and os.listdir(scene_data_dir) and (len(filecmp.dircmp(source_data_dir, scene_data_dir, ignore=['images.hdf5', 'metadata.json']).left_only) == 0)... |
class FileServingWorker(qc.QObject):
def __init__(self, dirname, *args, **kwargs):
super(FileServingWorker, self).__init__(*args, **kwargs)
self.dirname = dirname
self. = None
(int)
def run(self, port):
server_address = ('', port)
self. = RootedHTTPServer(self.dirname... |
class MetaFormerBlock(nn.Module):
def __init__(self, dim, token_mixer=nn.Identity, mlp=Mlp, norm_layer=nn.LayerNorm, drop=0.0, drop_path=0.0, layer_scale_init_value=None, res_scale_init_value=None):
super().__init__()
self.norm1 = norm_layer(dim)
self.token_mixer = token_mixer(dim=dim, drop=... |
_serializable
class TFRegNetMainLayer(tf.keras.layers.Layer):
config_class = RegNetConfig
def __init__(self, config, **kwargs):
super().__init__(**kwargs)
self.config = config
self.embedder = TFRegNetEmbeddings(config, name='embedder')
self.encoder = TFRegNetEncoder(config, name=... |
class Everything():
class AnIntEnum(IntEnum):
A = 1
class AStringEnum(str, Enum):
A = 'a'
string: str
bytes: bytes
an_int: int
a_float: float
a_dict: Dict[(str, int)]
a_list: List[int]
a_homogenous_tuple: TupleSubscriptable[(int, ...)]
a_hetero_tuple: TupleSubscri... |
def inference_detector(model, img, scores_thr=0.3, augment=False, half=False, merge=False):
cfg = model.cfg
device = next(model.parameters()).device
test_pipeline = ([LoadImage()] + cfg.data.test.pipeline[1:])
test_pipeline = Compose(test_pipeline)
data = dict(img=img)
data = test_pipeline(data)... |
class DistInfoPkg(OnSysPath, SiteBuilder):
files: FilesSpec = {'distinfo_pkg-1.0.0.dist-info': {'METADATA': "\n Name: distinfo-pkg\n Author: Steven Ma\n Version: 1.0.0\n Requires-Dist: wheel >= 1.0\n Requires-Dist: pytest; extra == 'test'\n ... |
class BartTokenizer(PreTrainedTokenizer):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
model_input_names = ['input_ids', 'attention_mask']
def __init__(self, vocab_file, merges_file, error... |
class GenerateCode(Command):
name = commands.COMMAND_GENERATE_CODE
kind: CodeActionKind = 'quickfix'
document_uri: DocumentUri
position: typing.Range
generate_kind: str
def validate(self, info):
generate.create_generate(kind=self.generate_kind, project=self.project, resource=info.resourc... |
_module()
class DefaultFormatBundle(object):
def __call__(self, results):
if ('img' in results):
img = results['img']
results = self._add_default_meta_keys(results)
if (len(img.shape) < 3):
img = np.expand_dims(img, (- 1))
img = np.ascontiguous... |
.requires_user_action
class EVENT_MOUSE_ENTER_LEAVE(InteractiveTestCase):
def on_mouse_enter(self, x, y):
print(('Entered at %f, %f' % (x, y)))
def on_mouse_leave(self, x, y):
print(('Left at %f, %f' % (x, y)))
def test_motion(self):
w = Window(200, 200)
try:
w.pu... |
def clean_check_command(f):
(f)
def inner(ctx, key, db, full_report, stdin, files, cache, ignore, ignore_unpinned_requirements, output, json, html, bare, proxy_protocol, proxy_host, proxy_port, exit_code, policy_file, save_json, save_html, audit_and_monitor, project, apply_remediations, auto_remediation_limit, ... |
class FontBase(BaseType):
default_family: Optional[str] = None
default_size: Optional[str] = None
font_regex = re.compile('\n (\n (\n # style\n (?P<style>normal|italic|oblique) |\n # weight (named | 100..900)\n (\n ... |
def get(fn: str, add_ver: bool=False, unquote: bool=False, do_strip: bool=False, do_readme: bool=False) -> str:
with open(fn) as f:
text = f.read()
if add_ver:
text = ver(text)
if unquote:
text = text.replace('%', '%%')
if do_strip:
text = ''.join((line for line in text.s... |
class FortConsumer(MySSH):
def __init__(self, *args, **kwargs):
super(FortConsumer, self).__init__(*args, **kwargs)
self.fort_server = ServerAssets.objects.select_related('assets').get(id=self.scope['path'].split('/')[3])
self.fort_user = FortServerUser.objects.get(id=self.scope['path'].spli... |
class RGAlbum():
def __init__(self, rg_songs, process_mode):
self.songs = rg_songs
self.gain = None
self.peak = None
self.__should_process = None
self.__process_mode = process_mode
def progress(self):
all_ = 0.0
done = 0.0
for song in self.songs:
... |
class ItemList():
def __init__(self):
self._items = []
def __len__(self):
return len(self._items)
def __getitem__(self, index):
return self._items[index]
def __iter__(self):
return iter(self._items)
def __repr__(self):
return f"<List {', '.join((it.__str__() f... |
def main(args):
device = torch.device('cuda')
num_classes = (184 if (args.dataset == 'coco') else 179)
num_o = (8 if (args.dataset == 'coco') else 31)
args.num_img = (1 if (args.dataset == 'vg') else 5)
args.model_path = args.model_path.format(args.load_eopch)
args.sample_path = args.sample_path... |
class LibrsyncTest(unittest.TestCase):
basis = rpath.RPath(Globals.local_connection, os.path.join(abs_test_dir, b'basis'))
new = rpath.RPath(Globals.local_connection, os.path.join(abs_test_dir, b'new'))
new2 = rpath.RPath(Globals.local_connection, os.path.join(abs_test_dir, b'new2'))
sig = rpath.RPath(G... |
class ActionCompleteTest(unittest.TestCase):
def test_action_complete(self):
self.assertEqual(comtst.rdiff_backup_action(True, True, None, None, ('--api-version', '201'), b'complete', ()), Globals.RET_CODE_ERR)
self.assertEqual(comtst.rdiff_backup_action(True, True, None, None, ('--api-version', '20... |
class MobileNet(nn.Module):
def __init__(self, channels, first_stage_stride, in_channels=3, in_size=(224, 224), num_classes=1000):
super(MobileNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
init_block_channels = cha... |
class Picture(MetadataBlock):
code = 6
_distrust_size = True
def __init__(self, data=None):
self.type = 0
self.mime = u''
self.desc = u''
self.width = 0
self.height = 0
self.depth = 0
self.colors = 0
self.data = b''
super(Picture, self)... |
def get_most_confident_predictions(predictions_voc):
memo = {}
for (i, p) in enumerate(predictions_voc):
img_id = p['image_id']
p['id'] = i
p['area'] = int((p['bbox'][2] * p['bbox'][3]))
if ((img_id not in memo) or (memo[img_id]['score'] < p['score'])):
memo[img_id] =... |
class HatchVersionConfig(Generic[PluginManagerBound]):
def __init__(self, root: str, config: dict[(str, Any)], plugin_manager: PluginManagerBound) -> None:
self.root = root
self.config = config
self.plugin_manager = plugin_manager
self._cached: (str | None) = None
self._sourc... |
class TestEdit():
def parse_config(filename):
parser = configparser.ConfigParser()
with open(filename, encoding='utf-8') as reader:
parser.read_file(reader)
return parser
def write_text(file, content):
with open(file, 'wb') as strm:
strm.write(content.enco... |
def base_units_convert(q_format: str, a_format: str) -> QuizEntry:
unit = random.choice(list(UNITS_TO_BASE_UNITS))
question = q_format.format(((unit + ' ') + UNITS_TO_BASE_UNITS[unit][0]))
answer = a_format.format(UNITS_TO_BASE_UNITS[unit][1])
return QuizEntry(question, [answer], DYNAMICALLY_GEN_VARIATI... |
def test_very_deep_dag():
class Inner(Component):
def construct(s):
s.in_ = InPort(Bits32)
s.out = OutPort(Bits32)
def up():
s.out = (s.in_ + 1)
def done(s):
return True
def line_trace(s):
return '{} > {}'.format(s.a... |
def infer_output_norm(module, output_norm=None):
if (output_norm == module.output_norm()):
return (None, NoOp())
if ((output_norm is None) and (module.output_norm() is not None)):
logger = logging.getLogger('infer_output_norm()')
logger.warning((('trying to set output_norm ({}) '.format(... |
def create_bar_chart(series_list: List[QFSeries], names_list, title: str, lines: List[QFSeries], recession_series: QFSeries=None, start_x: datetime=None, end_x: datetime=None, quarterly: bool=False, date_label_format: Tuple[(str, str)]=('%Y', '%y Q{}'), recession_name: str=None) -> BarChart:
assert (len(names_list)... |
class IWICComponentInfo(com.pIUnknown):
_methods_ = [('GetComponentType', com.STDMETHOD()), ('GetCLSID', com.STDMETHOD()), ('GetSigningStatus', com.STDMETHOD()), ('GetAuthor', com.STDMETHOD()), ('GetVendorGUID', com.STDMETHOD()), ('GetVersion', com.STDMETHOD()), ('GetSpecVersion', com.STDMETHOD()), ('GetFriendlyNam... |
def main(graph_fname, node_vec_fname, options):
print('Load a HIN...', flush=True)
g = loader.load_a_HIN(graph_fname)
print('Generate random walks...', flush=True)
tmp_walk_fname = 'data/random_walk.txt'
with open(tmp_walk_fname, 'w') as f:
for walk in g.random_walks(options.walk_num, option... |
class LexerContext():
def __init__(self, text, pos, stack=None, end=None):
self.text = text
self.pos = pos
self.end = (end or len(text))
self.stack = (stack or ['root'])
def __repr__(self):
return ('LexerContext(%r, %r, %r)' % (self.text, self.pos, self.stack)) |
class TerminationCondition(object):
def __init__(self, f_tol: float, f_rtol: float, x_tol: float, x_rtol: float, verbose: bool):
self.f_tol = f_tol
self.f_rtol = f_rtol
self.x_tol = x_tol
self.x_rtol = x_rtol
self.verbose = verbose
self._ever_converge = False
... |
class FewVLMPretraining(FewVLM):
def __init__(self, config):
super().__init__(config)
self.losses = self.config.losses.split(',')
def train_step(self, batch):
device = next(self.parameters()).device
vis_feats = batch['vis_feats'].to(device)
input_ids = batch['input_ids'].... |
class HuggingFaceTokenizer(object):
def __init__(self, pretrained_tokenizer):
if (pretrained_tokenizer == 'facebook/mbart-large-50'):
from transformers import MBart50TokenizerFast
tokenizer_ = MBart50TokenizerFast.from_pretrained('facebook/mbart-large-50', src_lang='en_XX')
e... |
def test_version_check_regex():
text1 = 'Something OTHER UPDATE. [CRITICAL UPDATE Some text.:)]. Something else.'
text2 = '\n\n[CRITICAL\t UPDATE] some text goes here.'
text3 = '[NOTHING]'
text4 = 'asd[CRITICAL UPDATE]'
text5 = 'Other text [CRITICAL UPDATE:>>>>>>>]><<<<asdeqsffqwe qwe sss.'
text... |
class MobileNetV3(nn.Module):
def __init__(self, block_args, num_classes=1000, in_chans=3, stem_size=16, fix_stem=False, num_features=1280, head_bias=True, pad_type='', act_layer=None, norm_layer=None, se_layer=None, se_from_exp=True, round_chs_fn=round_channels, drop_rate=0.0, drop_path_rate=0.0, global_pool='avg'... |
class Lambda(Layer):
_lambda_support
def __init__(self, function, output_shape=None, mask=None, arguments=None, **kwargs):
super(Lambda, self).__init__(**kwargs)
self.function = function
self.arguments = (arguments if arguments else {})
if (mask is not None):
self.sup... |
class WebKitElement(webelem.AbstractWebElement):
_tab: 'webkittab.WebKitTab'
def __init__(self, elem: QWebElement, tab: 'webkittab.WebKitTab') -> None:
super().__init__(tab)
if isinstance(elem, self.__class__):
raise TypeError('Trying to wrap a wrapper!')
if elem.isNull():
... |
class RegexUserAgentParser(UserAgentParser):
def __init__(self, regexes, handler, *, name=None):
if (name is None):
name = handler.__name__
self._regexes = [(re.compile(regex) if isinstance(regex, str) else regex) for regex in regexes]
self._handler = handler
self._name =... |
.supported(only_if=(lambda backend: backend.hash_supported(hashes.BLAKE2b(digest_size=64))), skip_message='Does not support BLAKE2b')
class TestBLAKE2b():
test_blake2b = generate_base_hash_test(hashes.BLAKE2b(digest_size=64), digest_size=64)
def test_invalid_digest_size(self, backend):
with pytest.raise... |
def test_classes_reordered(ourtester):
ourtester.makepyfile(test_one='\n from unittest import TestCase\n\n\n class A(TestCase):\n def test_a(self):\n pass\n\n\n class B(TestCase):\n def test_b(self):\n pass\n\n\n class C(TestCase):\n ... |
def test_bwlimit():
with expected_protocol(LeCroyT3DSO1204, [(b'CHDR OFF', None), (b'BWL C1,OFF', None), (b'C1:BWL?', b'OFF'), (b'BWL C1,ON', None), (b'C1:BWL?', b'ON')]) as instr:
instr.ch_1.bwlimit = False
assert (instr.ch_1.bwlimit is False)
instr.ch_1.bwlimit = True
assert (instr... |
class RunEvaluationTest(tf.test.TestCase):
def setUp(self):
self.output_dir = tempfile.mkdtemp()
self.models_file = os.path.join(self.output_dir, 'models_file.json')
self.toy_data = {'abc': ([[0, 1, 1], [0, 0, 1], [0, 0, 0]], [(- 1), 0, (- 2)]), 'abd': ([[0, 1, 0], [0, 0, 1], [0, 0, 0]], [(-... |
class TestEventHandler(PyScriptTest):
def test_when_decorator_with_event(self):
self.pyscript_run('\n <button id="foo_id">foo_button</button>\n <script type="py">\n from pyscript import when\n ("click", selector="#foo_id")\n def foo(evt):\n ... |
def as_index_variable(idx):
if (idx is None):
return NoneConst.clone()
if isinstance(idx, slice):
return make_slice(idx)
if (isinstance(idx, Variable) and isinstance(idx.type, SliceType)):
return idx
if (isinstance(idx, Variable) and isinstance(idx.type, NoneTypeT)):
retu... |
def _bottleneck_block_v2(inputs, filters, training, projection_shortcut, strides, data_format):
shortcut = inputs
inputs = batch_norm(inputs, training, data_format)
inputs = tf.nn.relu(inputs)
if (projection_shortcut is not None):
shortcut = projection_shortcut(inputs)
inputs = conv2d_fixed_... |
def assert_payment_secret_and_hash(response, payment):
assert (len(response) == 7)
assert ('secret' in response)
assert ('secret_hash' in response)
secret = Secret(to_bytes(hexstr=response['secret']))
assert (len(secret) == SECRET_LENGTH)
assert (payment['amount'] == response['amount'])
asse... |
def s_y_operator(num_spatial_orbitals: int, overlap: (np.ndarray | None)=None) -> FermionicOp:
if (overlap is None):
op = FermionicOp({f'+_{orb} -_{((orb + num_spatial_orbitals) % (2 * num_spatial_orbitals))}': (0.5j * ((- 1.0) ** (orb < num_spatial_orbitals))) for orb in range((2 * num_spatial_orbitals))})... |
def run(args):
(segments, reco2utt) = read_segments(args.segments)
ctms = read_ctm(args.ctm_in, segments)
for (reco, utts) in reco2utt.items():
ctms_for_reco = []
for utt in sorted(utts, key=(lambda x: segments[x][1])):
if ((reco, utt) in ctms):
ctms_for_reco.appe... |
def nrl_colors(img, **kwargs):
nrl_tpw_colors = {'colors': [[0.0, [188, 132, 98]], [0., [188, 130, 99]], [0., [187, 128, 100]], [0., [186, 125, 101]], [1., [185, 124, 102]], [1., [184, 122, 103]], [1., [183, 120, 103]], [1., [182, 119, 104]], [2., [182, 118, 106]], [2., [181, 116, 107]], [2., [180, 114, 108]], [3.,... |
class UpdaterProcess(BaseProcess):
name = 'Updater'
def setup(self, bot, commands):
self.bot = bot
self.bot_id = bot._bot_id
self.commands = commands
self.fetcher = updates_module.UpdatesFetcher(bot)
def should_stop(self):
try:
command = self.commands.get(... |
class WMS_GLAD(WMSBase):
layer_prefix = 'GLAD_'
name = 'GLAD'
def __init__(self, m=None):
self.m = m
try:
self.wmslayers = [key for key in self.m.add_wms.GLAD.add_layer.__dict__.keys() if (not ((key in ['m']) or key.startswith('_')))]
except Exception:
self.wm... |
def _init_gst():
arch_key = ('64' if (sys.maxsize > (2 ** 32)) else '32')
registry_name = f'gst-registry-{sys.platform}-{arch_key}.bin'
os.environ['GST_REGISTRY'] = os.path.join(get_cache_dir(), registry_name)
assert ('gi.repository.Gst' not in sys.modules)
import gi
assert ('gi.overrides.Gst' n... |
def test_method_dynamic_instance_attr_6() -> None:
node = builder.extract_node('\n class A:\n # Note: no initializer, so the only assignment happens in get_x\n\n def get_x(self, x):\n self.set_x(x + 1)\n return self.x\n\n def set_x(self, x):\n self.x = x\n\n ... |
def processData(live=False, quiet=False):
if (not quiet):
pprint(('PROCESSING: %s' % sysvals.htmlfile))
sysvals.vprint(('usetraceevents=%s, usetracemarkers=%s, usekprobes=%s' % (sysvals.usetraceevents, sysvals.usetracemarkers, sysvals.usekprobes)))
error = ''
if sysvals.usetraceevents:
(... |
def assert_(condition: object) -> None:
try:
assert condition
except AssertionError:
if (debugmode == 'PRODUCTION'):
log.error(('Deviation from expectations found. %s' % ERR_FRAGMENT), exc_info=True)
elif (debugmode == 'DEBUG_PDB'):
log.error('Deviation from expe... |
def delete_all_services_namespace(kubecli: KrknKubernetes, namespace: str):
try:
services = kubecli.get_all_services(namespace)
for service in services:
logging.info(('Deleting services' + service))
kubecli.delete_services(service, namespace)
except Exception as e:
... |
_HEAD_REGISTRY.register()
class StandardRPNHead(nn.Module):
def __init__(self, *, in_channels: int, num_anchors: int, box_dim: int=4, conv_dims: List[int]=((- 1),)):
super().__init__()
cur_channels = in_channels
if (len(conv_dims) == 1):
out_channels = (cur_channels if (conv_dims... |
class CustomCompleterApp(cmd2.Cmd):
def __init__(self):
super().__init__()
self.is_ready = True
default_completer_parser = Cmd2ArgumentParser(description='Testing app-wide argparse completer')
default_completer_parser.add_argument('--myflag', complete_when_ready=True)
_argparser(default_... |
class SimpleReplayPool(PoolBase, Serializable):
def __init__(self, env_spec, max_pool_size, replacement_policy='stochastic', replacement_prob=1.0, max_skip_episode=10):
Serializable.quick_init(self, locals())
super(SimpleReplayPool, self).__init__(env_spec)
max_pool_size = int(max_pool_size)... |
def test_resnet3d_backbone():
with pytest.raises(AssertionError):
ResNet3d(34, None, num_stages=0)
with pytest.raises(AssertionError):
ResNet3d(34, None, num_stages=5)
with pytest.raises(AssertionError):
ResNet3d(50, None, num_stages=0)
with pytest.raises(AssertionError):
... |
def channels_setup(amount: TokenAmount, our_address: Address, refund_address: Address) -> ChannelSet:
funded = factories.NettingChannelEndStateProperties(balance=amount, address=our_address)
broke = factories.replace(funded, balance=0)
funded_partner = factories.replace(funded, address=refund_address)
p... |
('regexp-max-lookbehind', [values.W_Object])
def regexp_max_lookbehind(obj):
if ((not isinstance(obj, values_regex.W_Regexp)) and (not isinstance(obj, values_regex.W_ByteRegexp))):
raise SchemeException('regexp-max-lookbehind: expected regexp or bytes-regexp')
return values.W_Fixnum(1000) |
class SearchsortedOp(COp):
params_type = Generic()
__props__ = ('side',)
check_input = False
def __init__(self, side='left'):
if ((side == 'left') or (side == 'right')):
self.side = side
else:
raise ValueError(f"'{side}' is an invalid value for keyword 'side'")
... |
class ThanksWidget(TitledWidget):
def __init__(self, view):
super().__init__(view)
self.add_child(P(view, text=_('Thank you for verifying your email address.')))
self.add_child(P(view, text=_('Your account is now active, and you can proceed to log in using the details you provided.'))) |
def _special_method_cache(method, cache_wrapper):
name = method.__name__
special_names = ('__getattr__', '__getitem__')
if (name not in special_names):
return
wrapper_name = ('__cached' + name)
def proxy(self, *args, **kwargs):
if (wrapper_name not in vars(self)):
bound =... |
class ResnetDiscriminator(chainer.Chain):
def __init__(self, bottom_width=8, ch=128, wscale=0.02, output_dim=1):
w = chainer.initializers.Normal(wscale)
super(ResnetDiscriminator, self).__init__()
self.bottom_width = bottom_width
self.ch = ch
with self.init_scope():
... |
class conv_block(nn.Module):
def __init__(self, ch_in, ch_out, kernel_size=3, stride=1, padding=1, act='relu'):
super(conv_block, self).__init__()
if (act == None):
self.conv = nn.Sequential(nn.Conv2d(ch_in, ch_out, kernel_size=kernel_size, stride=stride, padding=padding), nn.BatchNorm2d... |
def main(source_data_csv_path):
dfs = []
for (species, hyperparam_expt_dict) in HYPERPARAM_EXPTS.items():
for (hyperparam_expt, params_list) in hyperparam_expt_dict.items():
for param_tuple in params_list:
(param_val, location) = param_tuple
if (location == 'e... |
class GetCurrentInputCommand(ItemInfoCommandBase):
def __init__(self, device_type: str) -> None:
super(GetCurrentInputCommand, self).__init__(device_type, 'CURRENT_INPUT')
def process_response(self, json_obj: Dict[(str, Any)]) -> Optional[InputItem]:
items = dict_get_case_insensitive(json_obj, R... |
def test():
try:
if (implementation.name == 'circuitpython'):
import board
from busio import SPI
from digitalio import DigitalInOut
cs_pin = DigitalInOut(board.P0_15)
dc_pin = DigitalInOut(board.P0_17)
rst_pin = DigitalInOut(board.P0_20... |
def peer_learning_loss(logits_1, logits_2, labels, drop_rate):
dist_1 = F.softmax(logits_1, dim=1)
dist_2 = F.softmax(logits_2, dim=1)
(_, pred_1) = dist_1.topk(1, dim=1, largest=True, sorted=True)
(_, pred_2) = dist_2.topk(1, dim=1, largest=True, sorted=True)
pred_1 = pred_1.squeeze(dim=1)
pred... |
(config_name='../config/kitti_ssc.yaml')
def main(config: DictConfig):
exp_name = config.exp_prefix
exp_name += '_{}_{}'.format(config.dataset, config.run)
exp_name += '_FrusSize_{}'.format(config.frustum_size)
exp_name += '_nRelations{}'.format(config.n_relations)
exp_name += '_WD{}_lr{}'.format(co... |
def main():
args = parse_args()
cityscapes_path = args.cityscapes_path
out_dir = (args.out_dir if args.out_dir else cityscapes_path)
mmcv.mkdir_or_exist(out_dir)
gt_dir = osp.join(cityscapes_path, args.gt_dir)
poly_files = []
for poly in mmcv.scandir(gt_dir, '_polygons.json', recursive=True)... |
.parametrize('comm_pairs, value', (([(b'REFN 7', b'')], 7), ([(b'REFN 7', b'')], 7), ([(b'REFN 7', b'')], 7), ([(b'REFN 7', b'')], 7), ([(b'REFN 7', b'')], 7), ([(b'REFN 7', b'')], 7)))
def test_harmonic_setter(comm_pairs, value):
with expected_protocol(Ametek7270, comm_pairs) as inst:
inst.harmonic = value |
class F23_TestCase(F21_TestCase):
def runTest(self):
F21_TestCase.runTest(self)
self.assert_parse_error('logvol / --size=4096 --name=LVNAME --vgname=VGNAME --mkfsoptions=some,thing --fsprofile=PROFILE')
self.assert_parse('logvol /home --name=home --vgname=vg --size=500 --cachesize=250 --cach... |
def _cut_matrices(n, symmetric=False):
repeat = ((n ** 2) - n)
if symmetric:
repeat = (repeat // 2)
mid = (repeat // 2)
for combination in itertools.islice(product([0, 1], repeat=repeat), 1, None):
cm = np.zeros([n, n], dtype=int)
if symmetric:
triu = tril = combinati... |
def assert_bronchus_mask(bronchus_mask):
label_shape_statistics_image_filter = sitk.LabelShapeStatisticsImageFilter()
label_shape_statistics_image_filter.Execute(bronchus_mask)
print(label_shape_statistics_image_filter.GetPhysicalSize(1))
print(label_shape_statistics_image_filter.GetElongation(1))
p... |
.skipif(pytest.__version__.startswith('3.7.'), reason='pytest-dependency < 0.5 does not support session scope')
def test_dependency_in_modules(test_path):
test_path.makepyfile(test_unnamed_dep1="\n import pytest\n\n class Test1:\n def test_one(self):\n assert ... |
def _aead_cipher_supported(backend: Backend, cipher: _AEADTypes) -> bool:
if _is_evp_aead_supported_cipher(backend, cipher):
return True
else:
cipher_name = _evp_cipher_cipher_name(cipher)
if (backend._fips_enabled and (cipher_name not in backend._fips_aead)):
return False
... |
class TestLayerOutputUtil():
def test_generate_layer_output(self):
base_model = keras_model()
qs_obj = get_quantsim_artifacts(base_model)
temp_folder_name = f"temp_keras_layer_output_{datetime.now().strftime('%Y-%m-%d-%H-%M-%S')}"
save_dir = os.path.join(os.getcwd(), temp_folder_name... |
class UtteranceSequence(nn.Module):
def __init__(self, config):
super(UtteranceSequence, self).__init__()
self.gpu = config.use_gpu
self.droplstm = nn.Dropout(config.dp)
self.bilstm_flag = config.bilstm
self.lstm_layer = config.layer_num
self.batch_size = config.batch... |
def test_for_with_continue_break() -> None:
src = '\n for i in range(10):\n if i > 5:\n break\n print(unreachable)\n elif i > 2:\n continue\n print(k)\n print(i)\n '
cfg = build_cfg(src)
expected_blocks = [['range(10)'], ['i'], ['i > 5'], ['brea... |
(StepsRunner, 'run_pipeline_steps')
def test_run_step_group_pass(mock_run_steps):
StepsRunner(get_valid_test_pipeline(), Context()).run_step_group(step_group_name='sg1')
mock_run_steps.assert_called_once_with(steps=['step1', 'step2', {'name': 'step3key1', 'in': {'in3k1_1': 'v3k1', 'in3k1_2': 'v3k2'}}, 'step4']) |
.parametrize(['tp', 'alias'], [(list, List), (set, Set), (frozenset, FrozenSet), (collections.Counter, typing.Counter), (collections.deque, typing.Deque)])
def test_generic_concrete_one_arg(tp, alias):
assert_normalize(tp, tp, [nt_zero(Any)])
assert_normalize(alias, tp, [nt_zero(Any)])
if HAS_STD_CLASSES_GE... |
class MultiProcessTestBase(unittest.TestCase):
_and_log
def setUp(self) -> None:
os.environ['MASTER_ADDR'] = str('localhost')
os.environ['MASTER_PORT'] = str(get_free_port())
os.environ['GLOO_DEVICE_TRANSPORT'] = 'TCP'
os.environ['NCCL_SOCKET_IFNAME'] = 'lo'
torch.use_det... |
def test_zoom_range_limit():
vb = pg.ViewBox()
vb.setLimits(minXRange=5, maxXRange=10, minYRange=5, maxYRange=10)
testRange = pg.QtCore.QRect((- 15), (- 15), 7, 7)
vb.setRange(testRange, padding=0)
expected = [[testRange.left(), testRange.right()], [testRange.top(), testRange.bottom()]]
vbViewRa... |
class IoLexer(RegexLexer):
name = 'Io'
url = '
filenames = ['*.io']
aliases = ['io']
mimetypes = ['text/x-iosrc']
version_added = '0.10'
tokens = {'root': [('\\n', Whitespace), ('\\s+', Whitespace), ('//(.*?)$', Comment.Single), ('#(.*?)$', Comment.Single), ('/(\\\\\\n)?[*](.|\\n)*?[*](\\\\\... |
(frozen=True)
class AmmoPickupConfiguration(bitpacking.BitPackValue):
pickups_state: dict[(AmmoPickupDefinition, AmmoPickupState)]
def __post_init__(self):
for (ammo, state) in self.pickups_state.items():
state.check_consistency(ammo)
def bit_pack_encode(self, metadata) -> Iterator[tuple... |
class nnUNetTrainerDA5(nnUNetTrainer):
def configure_rotation_dummyDA_mirroring_and_inital_patch_size(self):
patch_size = self.configuration_manager.patch_size
dim = len(patch_size)
if (dim == 2):
do_dummy_2d_data_aug = False
if ((max(patch_size) / min(patch_size)) > ... |
_module()
class CyclicMomentumUpdaterHook(MomentumUpdaterHook):
def __init__(self, by_epoch=False, target_ratio=((0.85 / 0.95), 1), cyclic_times=1, step_ratio_up=0.4, **kwargs):
if isinstance(target_ratio, float):
target_ratio = (target_ratio, (target_ratio / 100000.0))
elif isinstance(t... |
class SystemSymPy(with_metaclass(System, SystemBase)):
_id = 2
def __init__(self, obj):
super(SystemSymPy, self).__init__(obj)
_AlgoType.attach(obj)
def onDetach(self, obj):
_AlgoType.detach(obj, True)
def getName(cls):
return 'SymPy + SciPy'
def isConstraintSupported... |
def get_requirement_files(allowlist: 'SectionProxy') -> Iterator[Path]:
try:
requirements_path = Path(allowlist['requirements_path'])
except KeyError:
requirements_path = Path()
try:
lines = allowlist['requirements']
requirements_lines = lines.split('\n')
except KeyError:... |
def upscale(scale, dir, do_face_enhance):
command = 'python inference_realesrgan.py -n RealESRGAN_x4plus --suffix u -s '
try:
float(scale)
command += str(scale)
except:
command += '2'
command += (((' -i ..//' + dir) + ' -o ..//') + dir)
if do_face_enhance:
command += ... |
class fileChooserDialog():
def __init__(self, title='Choose a file', multiple=False):
warnings.warn('Deprecated fileChooserDialog class called', DeprecationWarning, stacklevel=2)
self.inputfiles = open_file_chooser_dialog(title=title, multiple=multiple)
def getFiles(self):
return self.in... |
class OrthographicHarker():
def __init__(self, data):
self.method_name = 'orthographic_harker'
print('running {}...'.format(self.method_name))
method_start = time.time()
(H, W) = data.mask.shape
zy_hat = ((- data.n[(..., 0)]) / data.n[(..., 2)])
zx_hat = ((- data.n[(.... |
class Effect1019(BaseEffect):
type = 'passive'
def handler(fit, skill, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Large Autocannon Specialization')), 'damageMultiplier', (skill.getModifiedItemAttr('damageMultiplierBonus') * skill.level), **kwa... |
def _skip() -> None:
player.skip()
redis.put('backup_playing', False)
try:
current_song = models.CurrentSong.objects.get()
current_song.created = (timezone.now() - datetime.timedelta(seconds=current_song.duration))
current_song.save()
except models.CurrentSong.DoesNotExist:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.