code stringlengths 281 23.7M |
|---|
class MonocularModel(nn.Module):
def __init__(self):
super(MonocularModel, self).__init__()
self.model = MonocularVGG16(use_pretrained_weights=True)
self.model_loss = MonocularDistillLoss()
self.enable_flip_aug = True
def forward(self, sample):
(left, right) = (sample['le... |
class FlaskClientWrapper(BaseClientWrapper):
def __init__(self, client, ignore_css_selectors=None):
self.client = client
self.ignore_css_selectors = (ignore_css_selectors or [])
def get(self, path, fields=None):
return self.client.get(path, query_string=(fields or None))
def post(sel... |
class TestDictEqual(TestCase):
def test_simple(self):
assert (dict(superset, **{'a: 1'}) == superset)
def test_simple_msg(self):
assert (dict({'a: 1'}, **subset) == {'a: 1'}), 'This is wrong!'
def test_simple_msg2(self):
assert (dict({'a: 1'}, **subset) == {'a: 1'}), 'This is wrong!'... |
class CuModule():
def __init__(self, context, module_name):
self.module_name = module_name
self.context = context
self.mode = 'GPU'
global _modules
_modules.append(self)
self._module = c_void_p(0)
self._func_dict = {}
self._global_dict = {}
_mo... |
def straight_line_points(path, scale):
points = np.array([[path.line_origin.item(0), path.line_origin.item(1), path.line_origin.item(2)], [(path.line_origin.item(0) + (scale * path.line_direction.item(0))), (path.line_origin.item(1) + (scale * path.line_direction.item(1))), (path.line_origin.item(2) + (scale * path... |
class BBox():
west: float
south: float
east: float
north: float
def __post_init__(self):
if (is_null(self.west) or is_null(self.south) or is_null(self.east) or is_null(self.north)):
raise ValueError('NaN or None values are not allowed.')
def intersects(self, other: Union[('BB... |
def get_features():
commits = list(REPO.iter_commits('master'))
couplings = {}
features = []
for hexsha in os.listdir('/h/oskars/data_all'):
couplings[hexsha] = os.path.join(os.path.join('/h/oskars/data_all', hexsha), '{}_coupling.log.res'.format(hexsha))
features.append([commits[0].hexsha, ... |
class SegmentationBlock(nn.Module):
def __init__(self, in_channels, out_channels, n_upsamples=0):
super().__init__()
blocks = [Conv3x3GNReLU(in_channels, out_channels, upsample=bool(n_upsamples))]
if (n_upsamples > 1):
for _ in range(1, n_upsamples):
blocks.append... |
class StateTestCase(unittest.TestCase):
def test_definition(self):
self.assertRaises(ValueError, base.State, 'a--b', 'A--B')
def test_equality(self):
self.assertNotEqual(base.State('foo', 'Foo'), base.State('foo', 'Foo'))
def test_repr(self):
a = base.State('foo', 'Foo')
self... |
class Detection():
def __init__(self, box: Box, score: Optional[float]=None, class_id: Optional[int]=None, feature: Optional[Vector]=None):
self.box = box
self.score = score
self.class_id = class_id
self.feature = feature
def __repr__(self):
return f'Detection(box={self.b... |
_config
def test_focus_by_index(manager):
manager.c.group['a'].toscreen()
manager.test_window('one')
manager.test_window('two')
info = manager.c.group.info()
assert (info.get('focus') == 'two')
manager.c.group.focus_by_index(1)
info = manager.c.group.info()
assert (info.get('focus') == '... |
_fixtures(ConfigWithFiles)
def test_config_defaults_automatic(config_with_files):
fixture = config_with_files
egg_needing_injection = EasterEgg('test-inject')
fixture.set_config_spec(egg_needing_injection, 'reahl.component_dev.test_config:ConfigWithInjectedSetting')
pkg_resources.working_set.add(egg_nee... |
def _demo_mm_inputs(input_shape=(1, 3, 256, 256), num_outputs=None, num_frames=1):
(N, C, H, W) = input_shape
rng = np.random.RandomState(0)
imgs = rng.rand(*input_shape)
if (num_outputs is not None):
target = np.zeros([N, num_outputs, 17, (H // 4), (W // 4)], dtype=np.float32)
target_we... |
class RoCBertBasicTokenizer(object):
def __init__(self, do_lower_case=True, never_split=None, tokenize_chinese_chars=True, strip_accents=None):
if (never_split is None):
never_split = []
self.do_lower_case = do_lower_case
self.never_split = set(never_split)
self.tokenize_... |
def bn_relu_conv(x, out_channel, kernel_size, strides=1, dilation=1):
with tf.variable_scope(None, 'bn_relu_conv'):
x = slim.batch_norm(x, activation_fn=tf.nn.relu, fused=False)
x = slim.conv2d(x, out_channel, kernel_size, strides, rate=dilation, biases_initializer=None, activation_fn=None)
retu... |
def main(args):
img_size = 128
z_dim = 128
lamb_obj = 1.0
lamb_app = 1.0
lamb_img = 0.1
num_classes = (184 if (args.dataset == 'coco') else 179)
num_obj = (8 if (args.dataset == 'coco') else 31)
args.out_path = os.path.join(args.out_path, args.dataset, str(img_size))
num_gpus = torch... |
class LatencyScorer():
def __init__(self, start_from_zero=True):
self.recorder = []
self.scores = {}
self.scorer = LatencyInference()
self.start_from_zero = start_from_zero
def update_reorder(self, list_of_dict):
self.recorder = []
for info in list_of_dict:
... |
class CmdSmashGlass(Command):
key = 'smash glass'
aliases = ['smash lid', 'break lid', 'smash']
locks = 'cmd:all()'
def func(self):
rand = random.random()
if (rand < 0.2):
string = 'You smash your hand against the glass'
string += " with all your might. The lid wo... |
def modulate2(x, type_, center):
if (center is None):
center = array([[0, 0]])
if (x.ndim > 1):
s = array([x.shape])
else:
x = array([x])
s = array(x.shape)
o = (floor((s / 2.0)) + center)
n1 = (array([s[0][0]]) - o[0][0])
n2 = (array([s[0][1]]) - o[0][1])
if ... |
def parse_netconnections(file_to_read):
parsed = BeautifulStoneSoup(file(file_to_read).read())
entries = parsed.findAll('connection')
host_list = []
for entry in entries:
if (not entry.has_key('state')):
continue
if ((entry['state'].lower() != 'established') and (entry['state... |
class AverageValueMeter(Meter):
def __init__(self):
super(AverageValueMeter, self).__init__()
self.reset()
self.val = 0
def add(self, value, n=1):
self.val = value
self.sum += value
self.var += (value * value)
self.n += n
if (self.n == 0):
... |
_fixtures(FieldFixture)
def test_boolean_validation(fixture):
obj = EmptyStub()
field = BooleanField()
field.bind('boolean_attribute', obj)
invalid_boolean_name = ['negative', 'affirmative', '+', '-', None]
for boolean_candidate in invalid_boolean_name:
with expected(AllowedValuesConstraint)... |
class BranchSeparables(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, pad_type='', stem_cell=False):
super(BranchSeparables, self).__init__()
middle_channels = (out_channels if stem_cell else in_channels)
self.act_1 = nn.ReLU()
self.separable_1 = Sep... |
class SampleMultiplexerDataPipe(IterDataPipe[T_co]):
def __init__(self, pipes_to_weights_dict: Dict[(IterDataPipe[T_co], float)], seed: Optional[int]=None):
if (not pipes_to_weights_dict):
raise ValueError('Empty dictionary passed to SampleMultiplexerDataPipe')
total_weight: float = 0
... |
def get_cached_models(cache_dir: Union[(str, Path)]=None) -> List[Tuple]:
if (cache_dir is None):
cache_dir = TRANSFORMERS_CACHE
elif isinstance(cache_dir, Path):
cache_dir = str(cache_dir)
cached_models = []
for file in os.listdir(cache_dir):
if file.endswith('.json'):
... |
def disable_text_recog_aug_test(cfg, set_types=None):
assert ((set_types is None) or isinstance(set_types, list))
if (set_types is None):
set_types = ['val', 'test']
cfg = copy.deepcopy(cfg)
warnings.simplefilter('once')
for set_type in set_types:
assert (set_type in ['val', 'test'])... |
def responsive(period=0.1, default=True):
def wrapper(f):
t = [0]
(f)
def _(*args, **kwargs):
now = time.time()
if ((now - t[0]) > period):
t[0] = now
return f(*args, **kwargs)
else:
return default
re... |
class Annotation():
def __init__(self, word):
self.word = word
self.syllables = make_syllables(word)
self.split_sylls = [split_syllable(syll) for syll in self.syllables]
self.weights = make_weights(self.split_sylls)
self.sonorities = make_sonorities(self.split_sylls)
... |
def read_to_stationxml_response(input_unit, output_unit, normalization_frequency=1.0, filename=None, file=None, string=None):
from pyrocko.io import stationxml
presponse = read_to_pyrocko_response(filename=filename, file=file, string=string)
return stationxml.Response.from_pyrocko_pz_response(presponse, inp... |
class KatfileCom(XFSDownloader):
__name__ = 'KatfileCom'
__type__ = 'downloader'
__version__ = '0.03'
__status__ = 'testing'
__pattern__ = '
__config__ = [('enabled', 'bool', 'Activated', True), ('use_premium', 'bool', 'Use premium account if available', True), ('fallback', 'bool', 'Fallback to ... |
class _PSPModule(nn.Module):
def __init__(self, in_channels, bin_sizes):
super(_PSPModule, self).__init__()
out_channels = (in_channels // len(bin_sizes))
self.stages = nn.ModuleList([self._make_stages(in_channels, out_channels, b_s) for b_s in bin_sizes])
self.bottleneck = nn.Sequen... |
class Edge(ChromiumBased):
def __init__(self, cookie_file=None, domain_name='', key_file=None):
args = {'linux_cookies': ['~/.config/microsoft-edge/Default/Cookies', '~/.config/microsoft-edge-dev/Default/Cookies'], 'windows_cookies': [{'env': 'APPDATA', 'path': '..\\Local\\Microsoft\\Edge\\User Data\\Defaul... |
.parametrize('filter_kinds, expect_results', [pytest.param(None, True), pytest.param(['push_repo'], True, id='push_repo filter'), pytest.param(['pull_repo'], True, id='pull_repo filter'), pytest.param(['push_repo', 'pull_repo'], False, id='push and pull filters')])
def test_lookup_latest_logs(filter_kinds, expect_resul... |
class TestWriteHexFileByteCount(unittest.TestCase):
def setUp(self):
self.f = StringIO(hex8)
def tearDown(self):
self.f.close()
del self.f
def test_write_hex_file_bad_byte_count(self):
ih = intelhex.IntelHex(self.f)
sio = StringIO()
self.assertRaises(ValueErro... |
(tryfirst=True, hookwrapper=True)
def pytest_pyfunc_call(pyfuncitem: Function) -> Optional[object]:
if (pyfuncitem.get_closest_marker('asyncio') is not None):
if isinstance(pyfuncitem, PytestAsyncioFunction):
pass
else:
pyfuncitem.warn(pytest.PytestWarning(f"The test {pyfunci... |
def split_provision(value):
global _provision_rx
if (_provision_rx is None):
_provision_rx = re.compile('([a-zA-Z_]\\w*(?:\\.[a-zA-Z_]\\w*)*)(?:\\s*\\(\\s*([^)\\s]+)\\s*\\))?$', re.ASCII)
value = value.strip()
m = _provision_rx.match(value)
if (not m):
raise ValueError(('illegal prov... |
def get_rxn_smarts_make_rings(probs):
X = {'[#6R': 'X4', '[#7R': 'X3'}
rxn_smarts = []
for key in probs:
if chembl_problematic_case(key):
logger.warning(f'Ignoring unsupported key {key} in get_rxn_smarts_make_rings')
continue
tokens = key.split(']')
smarts = '... |
class _CommandCfdSolverFenics(CfdCommand):
def __init__(self):
super(_CommandCfdSolverFenics, self).__init__()
self.resources = {'Pixmap': 'cfd-solver-fenics', 'MenuText': QtCore.QT_TRANSLATE_NOOP('Cfd_SolverFenics', 'Create a Fenics CFD solver'), 'Accel': 'C, S', 'ToolTip': QtCore.QT_TRANSLATE_NOOP... |
class TestLicenseValidator(TestCase):
def setUp(self) -> None:
plugin_without_license = os.path.join(TESTFILE_DIR, 'plugin_without_license.zip_')
self.plugin_package = open(plugin_without_license, 'rb')
def tearDown(self):
self.plugin_package.close()
def test_plugin_without_license(s... |
.parametrize('username,password', users)
.parametrize('project_id', projects)
def test_project_update_views_get(db, client, username, password, project_id):
client.login(username=username, password=password)
url = reverse('project_update_views', args=[project_id])
response = client.get(url)
if (project_... |
def build_model(cfg_model, dataset_helper, logger):
assert (cfg_model['name'] in ['fpointnet', 'patchnet'])
if (cfg_model['name'] == 'fpointnet'):
return FPointNet(cfg=cfg_model, num_heading_bin=dataset_helper.num_heading_bin, num_size_cluster=dataset_helper.num_size_cluster, mean_size_arr=dataset_helpe... |
def _fold_given_batch_norms(model: tf.keras.Model, conv_bn_pairs: Iterable[Tuple[(tf.keras.layers.Layer, tf.keras.layers.Layer)]], bn_conv_pairs: Iterable[Tuple[(tf.keras.layers.Layer, tf.keras.layers.Layer)]]) -> Optional[tf.keras.Model]:
for (bn, conv) in bn_conv_pairs:
if isinstance(conv, QcQuantizeWrapp... |
def test_hover_flip_event_top_edge_rotated_90(view, item):
view.scene.addItem(item)
item.setSelected(True)
item.setRotation(90)
event = MagicMock()
event.pos.return_value = QtCore.QPointF(50, 0)
with patch.object(item, 'bounding_rect_unselected', return_value=QtCore.QRectF(0, 0, 100, 80)):
... |
class PhobertTokenizer(PreTrainedTokenizer):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
def __init__(self, vocab_file, merges_file, bos_token='<s>', eos_token='</s>', sep_token='</s>', cls_t... |
_infer_shape
_useless
_canonicalize('fast_compile')
_specialize
_rewriter([Elemwise])
def local_useless_elemwise(fgraph, node):
if isinstance(node.op, Elemwise):
dtype = node.outputs[0].dtype
if ((node.op.scalar_op == ps.eq) and (len(node.inputs) == 2)):
if (node.inputs[0] == node.inputs... |
class TDF(nn.Module):
def __init__(self, channels, f, bf=16, bias=False, min_bn_units=16):
super(TDF, self).__init__()
if (bf is None):
self.tdf = nn.Sequential(nn.Linear(f, f, bias), nn.BatchNorm2d(channels), nn.ReLU())
else:
bn_unis = max((f // bf), min_bn_units)
... |
def hausdorff_distance(test=None, reference=None, confusion_matrix=None, nan_for_nonexisting=True, voxel_spacing=None, connectivity=1, **kwargs):
if (confusion_matrix is None):
confusion_matrix = ConfusionMatrix(test, reference)
(test_empty, test_full, reference_empty, reference_full) = confusion_matrix... |
('pyinaturalist.v0.observations.upload_sounds')
('pyinaturalist.v0.observations.put')
def test_update_observation__with_sounds(put, mock_upload_sounds):
update_observation(1234, access_token='token', sounds='photo.jpg')
request_params = put.call_args[1]['json']['observation']
assert ('sounds' not in request... |
def convert_fairseq_mbart_checkpoint_from_disk(checkpoint_path, hf_config_path='facebook/mbart-large-en-ro', finetuned=False, mbart_50=False):
state_dict = torch.load(checkpoint_path, map_location='cpu')['model']
remove_ignore_keys_(state_dict)
vocab_size = state_dict['encoder.embed_tokens.weight'].shape[0]... |
class DataProcessor(object):
def get_train_examples(self, data_dir):
raise NotImplementedError()
def get_dev_examples(self, data_dir):
raise NotImplementedError()
def get_labels(self):
raise NotImplementedError()
def _read_tsv(cls, input_file, quotechar=None):
with open(i... |
def group_rms(x, groups: int=32, eps: float=1e-05):
(B, C, H, W) = x.shape
_assert(((C % groups) == 0), '')
x_dtype = x.dtype
x = x.reshape(B, groups, (C // groups), H, W)
rms = x.float().square().mean(dim=(2, 3, 4), keepdim=True).add(eps).sqrt_().to(x_dtype)
return rms.expand(x.shape).reshape(B... |
class TestUnSeekable():
def __init__(self, text):
if (not isinstance(text, bytes)):
text = text.encode('utf-8')
self._file = BytesIO(text)
self.log = []
def tell(self):
return self._file.tell()
def seek(self, offset, whence=0):
assert False
def read(se... |
class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000):
self.inplanes = 64
super(ResNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
... |
class ClassificationModel(object):
def __init__(self, K, is_test=False, seed=0):
if is_test:
class ARGS():
num_inducing = 2
iterations = 1
small_iterations = 1
initial_likelihood_var = 0.01
else:
class ARGS():
... |
class Results(tuple):
def __new__(cls, fields, values):
fields = tuple(fields)
values = tuple(values)
if (len(fields) != len(values)):
raise ValueError(('`fields` and `values` must have matching length: %d != %d' % (len(fields), len(values))))
self = super().__new__(cls, ... |
class Effect4161(BaseEffect):
type = 'passive'
def handler(fit, container, context, projectionRange, **kwargs):
level = (container.level if ('skill' in context) else 1)
fit.modules.filteredChargeBoost((lambda mod: mod.charge.requiresSkill('Astrometrics')), 'baseMaxScanDeviation', (container.getM... |
def test_tranform_wgs84_to_custom():
custom_proj = pyproj.Proj('+proj=geos +lon_0=0.000000 +lat_0=0 +h=35807.414063 +a=6378.169000 +b=6356.583984')
wgs84 = pyproj.Proj('+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs')
(lat, lon) = (51.04715, 3.23406)
with pytest.warns(FutureWarning):
(xx, yy) ... |
def test_limits_enforcement():
p = pt.Parameter.create(name='params', type='group', children=[dict(name='float', type='float', limits=[0, 1]), dict(name='int', type='int', bounds=[0, 1]), dict(name='list', type='list', limits=['x', 'y']), dict(name='dict', type='list', limits={'x': 1, 'y': 2})])
t = pt.Paramete... |
class LP(Escpos):
def is_usable() -> bool:
return is_usable()
_linux_lp
def __init__(self, printer_name: str='', *args, **kwargs):
Escpos.__init__(self, *args, **kwargs)
self.printer_name = printer_name
self.auto_flush = kwargs.get('auto_flush', False)
self._flushed =... |
def remove_system_log(days=90):
deadline = (datetime.datetime.now() - datetime.timedelta(days))
m = MongoOps(settings.MONGODB_HOST, settings.MONGODB_PORT, settings.RECORD_DB, settings.RECORD_COLL, settings.MONGODB_USER, settings.MONGODB_PASS)
(rs, _) = m.find({'datetime': {'$lt': deadline}})
m.delete({'... |
class OpenRole(TourneyButton):
def __init__(self, ctx: Context, letter: str):
super().__init__(emoji=ri(letter))
self.ctx = ctx
async def callback(self, interaction: discord.Interaction):
(await interaction.response.defer())
m = (await self.ctx.simple('Mention the role for which ... |
class kitti(imdb):
def __init__(self, image_set, data_path, mc):
imdb.__init__(self, ('kitti_' + image_set), mc)
self._image_set = image_set
self._data_root_path = data_path
self._lidar_2d_path = os.path.join(self._data_root_path, 'lidar_2d')
self._image_idx = self._load_imag... |
class MBartConfig(PretrainedConfig):
model_type = 'mbart'
keys_to_ignore_at_inference = ['past_key_values']
attribute_map = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'}
def __init__(self, vocab_size=50265, max_position_embeddings=1024, encoder_layers=12, encoder_ffn_dim=4... |
def model_train(model: torch.nn.Module, train_loader: DataLoader, epochs: int, optimizer: optim.Optimizer, scheduler):
use_cuda = next(model.parameters()).is_cuda
model.train()
if use_cuda:
device = torch.device('cuda:0')
else:
device = torch.device('cpu')
criterion = nn.CrossEntropy... |
class OdeSolver():
class RK1(RK):
def integrator(self):
return integrator.RK1
class RK2(RK):
def integrator(self):
return integrator.RK2
class RK4(RK):
def integrator(self):
return integrator.RK4
class RK8(RK):
def integrator(self):
... |
def total_size(o, handlers={}, verbose=False):
dict_handler = (lambda d: chain.from_iterable(d.items()))
all_handlers = {tuple: iter, list: iter, deque: iter, dict: dict_handler, set: iter, frozenset: iter}
all_handlers.update(handlers)
seen = set()
default_size = sys.getsizeof(0)
def sizeof(o):... |
def add_configuration(configurations: list[MypyDistConf], distribution: str) -> None:
with Path('stubs', distribution, 'METADATA.toml').open('rb') as f:
data = tomli.load(f)
mypy_tests_conf: dict[(str, dict[(str, Any)])] = data.get('mypy-tests', {})
if (not mypy_tests_conf):
return
asser... |
def launch_distributed(cfg: AttrDict, node_id: int, engine_name: str, hook_generator: Callable[([Any], List[ClassyHook])]):
setup_logging(__name__)
node_id = get_node_id(node_id)
dist_run_id = get_dist_run_id(cfg, cfg.DISTRIBUTED.NUM_NODES)
world_size = (cfg.DISTRIBUTED.NUM_NODES * cfg.DISTRIBUTED.NUM_P... |
class QuantizableTransformerDecoderLayer(nn.TransformerDecoderLayer):
__constants__ = ['batch_first', 'norm_first']
def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation=nnF.relu, layer_norm_eps=1e-05, batch_first=False, norm_first=False, device=None, dtype=None) -> None:
supe... |
def write_game_descriptions(game_descriptions: dict[(RandovaniaGame, GameDescription)]):
from randovania.game_description import data_writer, pretty_print
for (game, gd) in game_descriptions.items():
logging.info('Writing %s', game.long_name)
new_data = data_writer.write_game_description(gd)
... |
_module
class HTCMaskHead(FCNMaskHead):
def __init__(self, *args, **kwargs):
super(HTCMaskHead, self).__init__(*args, **kwargs)
self.conv_res = ConvModule(self.conv_out_channels, self.conv_out_channels, 1, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg)
def init_weights(self):
super(HTCM... |
def test_dns_service_record_hashablity():
srv1 = r.DNSService('irrelevant', const._TYPE_SRV, const._CLASS_IN, const._DNS_HOST_TTL, 0, 0, 80, 'a')
srv2 = r.DNSService('irrelevant', const._TYPE_SRV, const._CLASS_IN, const._DNS_HOST_TTL, 0, 1, 80, 'a')
srv3 = r.DNSService('irrelevant', const._TYPE_SRV, const._... |
def PullVideo(name=None, source_location=None, max_height=240, **kwargs):
if isinstance(name, VisBeatExampleVideo):
assert (source_location is None), 'Provided VisBeatExampleVideo and source location? What are you trying to do?'
source_location = name.url
vname = name.name
elif (name is ... |
def dev_distil_model_joint(full_model, small_model, val_iter, full_model_args, small_model_args):
full_model.eval()
small_model.eval()
(full_model_corrects, full_model_avg_loss) = (0.0, 0.0)
(small_model_corrects, small_model_avg_loss) = (0.0, 0.0)
small_temperature = 1
for batch in val_iter:
... |
class decoder(nn.Module):
def __init__(self, dim, nc=1):
super(decoder, self).__init__()
self.dim = dim
self.upc1 = nn.Sequential(nn.ConvTranspose2d(dim, 512, 4, 1, 0), nn.BatchNorm2d(512), nn.LeakyReLU(0.2, inplace=True))
self.upc2 = nn.Sequential(vgg_layer((512 * 2), 512), vgg_laye... |
class DeformConvFunction(Function):
def forward(ctx, input, offset, weight, stride=1, padding=0, dilation=1, groups=1, deformable_groups=1, im2col_step=64):
if ((input is not None) and (input.dim() != 4)):
raise ValueError('Expected 4D tensor as input, got {}D tensor instead.'.format(input.dim()... |
def synchronize():
if (not dist.is_available()):
return
if (not dist.is_initialized()):
return
world_size = dist.get_world_size()
if (world_size == 1):
return
if (dist.get_backend() == dist.Backend.NCCL):
dist.barrier(device_ids=[torch.cuda.current_device()])
else... |
class GaussianProcessLogLikelihoodMCMC(object):
def __init__(self, historical_data, derivatives, prior, chain_length, burnin_steps, n_hypers, log_likelihood_type=C_GP.LogLikelihoodTypes.log_marginal_likelihood, noisy=True, rng=None):
self._historical_data = copy.deepcopy(historical_data)
self._deriv... |
class RoIAlignMax(Module):
def __init__(self, aligned_height, aligned_width, spatial_scale):
super(RoIAlignMax, self).__init__()
self.aligned_width = int(aligned_width)
self.aligned_height = int(aligned_height)
self.spatial_scale = float(spatial_scale)
def forward(self, features,... |
_cache(maxsize=512)
def service_type_name(type_: str, *, strict: bool=True) -> str:
if (len(type_) > 256):
raise BadTypeInNameException(('Full name (%s) must be > 256 bytes' % type_))
if type_.endswith((_TCP_PROTOCOL_LOCAL_TRAILER, _NONTCP_PROTOCOL_LOCAL_TRAILER)):
remaining = type_[:(- len(_TCP... |
def fomo_wrapper_module(name):
try:
if (not re.match(gf.meta.StringID.pattern, name)):
raise ValueError('invalid name')
words = name.split('.', 1)
if (len(words) == 2):
(name, variant) = words
else:
name = words[0]
variant = None
... |
def parse_args():
parser = argparse.ArgumentParser(description='Initialize PASCAL VOC dataset.', epilog='Example: python pascal_voc.py --download-dir ~/VOCdevkit', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--download-dir', type=str, default=None, help='dataset directory on dis... |
def qdmr_args(qdmr_ex):
args_ex = {}
is_operator = {'is_comparative': [], 'is_superlative': [], 'is_sort': []}
comparative_ref = {}
for (num_step, ex) in enumerate(convert_str_to_list(qdmr_ex)):
(comparative_idx, filter_idx) = (ex.find('COMPARATIVE'), ex.find('FILTER'))
(superlative_idx,... |
class PREGGNN_node(torch.nn.Module):
def __init__(self, num_layer, emb_dim, drop_ratio=0.5, JK='last', residual=False, gnn_type='gin'):
super(PREGGNN_node, self).__init__()
self.m1 = GNN_node(num_layer, emb_dim, drop_ratio, JK, residual, gnn_type)
self.conv = IConv(emb_dim)
def forward(s... |
class Symbol():
def __init__(self):
self.arg_shape_dict = None
self.out_shape_dict = None
self.aux_shape_dict = None
self.sym = None
def symbol(self):
return self.sym
def get_symbol(self, cfg, is_train=True):
raise NotImplementedError()
def init_weights(se... |
def test_empirical_from_trace():
with models.another_simple_model():
step = pm.Metropolis()
trace = pm.sample(100, step=step, chains=1, tune=0, return_inferencedata=False)
emp = Empirical(trace)
assert (emp.histogram.shape[0].eval() == 100)
trace = pm.sample(100, step=step, c... |
.pydicom
def test_structure_dedupe():
data_paths = pymedphys.zip_data_paths('structure-deduplication.zip')
input_paths = [path for path in data_paths if (path.parent.name == 'input')]
for input_path in input_paths:
input_dcm = pydicom.read_file(str(input_path), force=True)
baseline_path = in... |
class MetaDims(type):
def __call__(cls, *args, rep=None):
if ((len(args) == 1) and isinstance(args[0], Dimensions)):
return args[0]
elif ((len(args) == 1) and (len(args[0]) == 2)):
args = (Space(args[0][1], rep=rep), Space(args[0][0], rep=rep))
elif (len(args) != 2):
... |
class ACVNet(MetaModule):
def __init__(self, input, hidden1, hidden2, output, num_classes):
super(ACVNet, self).__init__()
self.feature = share(input, hidden1, hidden2)
self.classfier = task(hidden2, output, num_classes)
def forward(self, x, num, c):
num = torch.argmax(num, (- 1)... |
def load_txt_info(gt_file, img_info):
(contours, words) = get_contours_txt(gt_file)
anno_info = []
for (contour, word) in zip(contours, words):
if ((contour.shape[0] == 2) or (word == '###')):
continue
coordinates = np.array(contour).reshape((- 1), 2)
polygon = Polygon(co... |
.parametrize('v, new_order', [(set_test_value(pt.lscalar(name='a'), np.array(1, dtype=np.int64)), ('x', 'x')), (set_test_value(pt.matrix('a'), np.array([[1.0, 2.0], [3.0, 4.0]], dtype=config.floatX)), (1, 0)), (set_test_value(pt.matrix('a'), np.array([[1.0, 2.0], [3.0, 4.0]], dtype=config.floatX)), (1, 0, 'x')), (set_t... |
class ClassyMeter():
def __init__(self):
log_class_usage('Meter', self.__class__)
def from_config(cls, config: Dict[(str, Any)]) -> 'ClassyMeter':
raise NotImplementedError
def name(self) -> str:
raise NotImplementedError
def value(self) -> Any:
raise NotImplementedError
... |
def main():
args = parse_args()
assert (args.out or args.eval or args.format_only or args.show or args.show_dir), 'Please specify at least one operation (save/eval/format/show the results / save the results) with the argument "--out", "--eval", "--format-only", "--show" or "--show-dir"'
if (args.eval and ar... |
def test_simplified_solis_nans_series():
length = 6
apparent_elevation = pd.Series(np.full(length, 80.0))
apparent_elevation[0] = np.nan
aod700 = np.full(length, 0.1)
aod700[1] = np.nan
precipitable_water = np.full(length, 0.5)
precipitable_water[2] = np.nan
pressure = np.full(length, 98... |
def main():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-t', '--task_ids', nargs='+', help="List of integers belonging to the task ids you wish to run experiment planning and preprocessing for. Each of these ids must, have a matching folder 'TaskXXX_' in the raw data folder")
... |
def test_hwep__raise_on_no_coords():
ds = simulate_genotype_call_dataset(n_variant=10, n_sample=5, n_allele=2, seed=0)
ds['variant_genotype_count'] = (['variants', 'genotypes'], np.ones((10, 3), dtype=int))
with pytest.raises(ValueError, match="No coordinates for dimension 'genotypes'"):
hwep_test(d... |
class TFKPoly(TFKernel):
def __init__(self, c, d):
if (c < 0):
raise ValueError('c has to be positive real. Was {}'.format(c))
if (d < 0):
raise ValueError('d has to be positive integer. Was {}'.format(d))
self.c = c
self.d = d
def eval(self, X, Y):
... |
def setAccessURLs(pageid):
global accessurls
with open(f'api/player/models/{pageid}/files_type2', 'r', encoding='UTF-8') as f:
filejson = json.load(f)
accessurls.append(filejson['base.url'].split('?')[(- 1)])
with open(f'api/player/models/{pageid}/files_type3', 'r', encoding='UTF-8') as f:
... |
def pytest_addoption(parser):
parser.addoption('--ro-functional', action='store_true', default=False, help='Run readonly functional tests against actual bugzilla instances. This will be very slow.')
parser.addoption('--rw-functional', action='store_true', default=False, help='Run read/write functional tests aga... |
def pytask_execute(session: Session) -> None:
session.hook.pytask_execute_log_start(session=session)
session.scheduler = session.hook.pytask_execute_create_scheduler(session=session)
session.hook.pytask_execute_build(session=session)
session.hook.pytask_execute_log_end(session=session, reports=session.e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.