code stringlengths 281 23.7M |
|---|
class _GlobalConvModule(nn.Module):
def __init__(self, in_dim, out_dim, kernel_size):
super(_GlobalConvModule, self).__init__()
pad0 = ((kernel_size[0] - 1) // 2)
pad1 = ((kernel_size[1] - 1) // 2)
super(_GlobalConvModule, self).__init__()
self.conv_l1 = nn.Conv2d(in_dim, out... |
class WritePoTestCase(unittest.TestCase):
def test_join_locations(self):
catalog = Catalog()
catalog.add('foo', locations=[('main.py', 1)])
catalog.add('foo', locations=[('utils.py', 3)])
buf = BytesIO()
pofile.write_po(buf, catalog, omit_header=True)
assert (buf.getv... |
def test_get_and_update_iou(one_to_n_address):
request_args = dict(url='url', token_network_address=factories.UNIT_TOKEN_NETWORK_ADDRESS, sender=factories.make_address(), receiver=factories.make_address(), privkey=PRIVKEY)
with pytest.raises(ServiceRequestFailed):
with patch.object(session, 'get', side_... |
class MobileNetV3_Small(nn.Module):
def __init__(self, num_classes=1000, act=nn.Hardswish):
super(MobileNetV3_Small, self).__init__()
self.conv1 = nn.Conv2d(3, 16, kernel_size=3, stride=2, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(16)
self.hs1 = act(inplace=True)
self.... |
def _random_config() -> dict:
rng = np.random.default_rng(seed=RANDOM_SEED)
return {'max_search_radius': rng.uniform(1, 100), 'update_method': rng.choice(list(btrack.constants.BayesianUpdates)), 'return_kalman': bool(rng.uniform(0, 2)), 'store_candidate_graph': bool(rng.uniform(0, 2)), 'verbose': bool(rng.unifo... |
class SWA(Optimizer):
def __init__(self, optimizer, swa_freq=None, swa_lr_factor=None):
(self._auto_mode, (self.swa_freq,)) = self._check_params(swa_freq)
self.swa_lr_factor = swa_lr_factor
if self._auto_mode:
if (swa_freq < 1):
raise ValueError('Invalid swa_freq:... |
def test_profile(testdir):
file_test = testdir.makepyfile('\n import pytest\n from selenium.webdriver.common.by import By\n\n \n def firefox_options(firefox_options):\n firefox_options.set_preference("browser.anchor_color", "#FF69B4")\n firefox_options.set_preferenc... |
def grad_elec(cc_grad, t1=None, t2=None, l1=None, l2=None, eris=None, atmlst=None, verbose=lib.logger.INFO):
mycc = cc_grad.base
if (t1 is None):
t1 = mycc.t1
if (t2 is None):
t2 = mycc.t2
if (l1 is None):
l1 = mycc.l1
if (l2 is None):
l2 = mycc.l2
if (eris is Non... |
class Player(QWidget):
fullScreenChanged = pyqtSignal(bool)
def __init__(self, playlist, parent=None):
super(Player, self).__init__(parent)
self.colorDialog = None
self.trackInfo = ''
self.statusInfo = ''
self.duration = 0
self.player = QMediaPlayer()
self... |
.remote_data
.flaky(reruns=RERUNS, reruns_delay=RERUNS_DELAY)
def test_get_solaranywhere_bad_probability_of_exceedance():
with pytest.raises(ValueError, match='must be an integer'):
pvlib.iotools.get_solaranywhere(latitude=44, longitude=(- 73), api_key='empty', source='SolarAnywherePOELatest', probability_o... |
class VendorImporter():
def __init__(self, root_name, vendored_names=(), vendor_pkg=None):
self.root_name = root_name
self.vendored_names = set(vendored_names)
self.vendor_pkg = (vendor_pkg or root_name.replace('extern', '_vendor'))
def search_path(self):
(yield (self.vendor_pkg ... |
class OnClosedVoiceChat(Scaffold):
def on_closed_voice_chat(self) -> Callable:
method = 'CLOSED_HANDLER'
def decorator(func: Callable) -> Callable:
if (self is not None):
self._on_event_update.add_handler(method, func)
return func
return decorator |
def run():
test_opts = TestOptions().parse()
if (test_opts.resize_factors is not None):
assert (len(test_opts.resize_factors.split(',')) == 1), 'When running inference, provide a single downsampling factor!'
out_path_results = os.path.join(test_opts.exp_dir, 'inference_results', 'downsampling_{}... |
class LazyBatcher():
def __init__(self, config: ColBERTConfig, triples, queries, collection, rank=0, nranks=1):
(self.bsize, self.accumsteps) = (config.bsize, config.accumsteps)
self.nway = config.nway
self.query_tokenizer = QueryTokenizer(config)
self.doc_tokenizer = DocTokenizer(co... |
class TestDBShellout(_BaseTestDB):
class_to_test = TaskWarriorShellout
def should_skip(self):
return (not TaskWarriorShellout.can_use())
def test_filtering_simple(self):
self.tw.task_add('foobar1')
self.tw.task_add('foobar2')
tasks = self.tw.filter_tasks({'description.contain... |
class TestComplexPackage():
(autouse=True, scope='class')
def built(self, builder):
builder('pypackagecomplex')
def test_public_chain_resolves(self, parse):
submodule_file = parse('_build/html/autoapi/complex/subpackage/submodule/index.html')
assert submodule_file.find(id='complex.su... |
class Effect4810(BaseEffect):
type = 'passive'
def handler(fit, module, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: (mod.item.group.name == 'ECM')), 'scanLadarStrengthBonus', module.getModifiedItemAttr('ecmStrengthBonusPercent'), stackingPenalties=True, **kwargs) |
.parametrize('cap_fees, flat_fee, prop_fee, imbalance_fee, initial_amount, expected_amount', [(False, 0, 0, 10000, 50000, (50000 + 2000)), (False, 0, 0, 20000, 50000, (50000 + 3995)), (False, 0, 0, 30000, 50000, (50000 + 5910)), (False, 0, 0, 40000, 50000, (50000 + 7613)), (False, 0, 0, 50000, 50000, (50000 + 9091)), (... |
class TestDescription():
def test_default(self, isolation, isolated_data_dir, platform):
config = {'project': {'name': 'my_app', 'version': '0.0.1'}}
project = Project(isolation, config=config)
environment = MockEnvironment(isolation, project.metadata, 'default', project.config.envs['default... |
class BaseDownloadTests(DownloadMixin, TestCase):
def setUp(self):
self.release_275_page = Page.objects.create(title='Python 2.7.5 Release', path='download/releases/2.7.5', content='whatever', is_published=True)
self.release_275 = Release.objects.create(version=Release.PYTHON2, name='Python 2.7.5', ... |
class CompactLatticeConstFst(_FstBase, _const_fst.CompactLatticeConstFst):
_ops = _clat_ops
_drawer_type = _CompactLatticeFstDrawer
_printer_type = _CompactLatticeFstPrinter
_weight_factory = CompactLatticeWeight
_state_iterator_type = CompactLatticeConstFstStateIterator
_arc_iterator_type = Com... |
class CheckingFinderTest(unittest.TestCase):
def setUp(self):
super().setUp()
self.project = testutils.sample_project()
self.mod1 = testutils.create_module(self.project, 'mod1')
def tearDown(self):
testutils.remove_project(self.project)
super().tearDown()
def test_tri... |
class TestMessageHandler():
test_flag = False
SRE_TYPE = type(re.match('', ''))
def test_slot_behaviour(self):
handler = MessageHandler(filters.ALL, self.callback)
for attr in handler.__slots__:
assert (getattr(handler, attr, 'err') != 'err'), f"got extra slot '{attr}'"
a... |
def test_dead_default() -> None:
blockquote = from_fsm(Fsm(alphabet={Charclass('/'), Charclass('*'), (~ Charclass('/*'))}, states={0, 1, 2, 3, 4, 5}, initial=0, finals={4}, map={0: {Charclass('/'): 1, (~ Charclass('/*')): 5, Charclass('*'): 5}, 1: {Charclass('/'): 5, (~ Charclass('/*')): 5, Charclass('*'): 2}, 2: {... |
def Match(Expr, *, Cases):
assert isinstance(Cases, dict)
t = [(k, w) for (k, v) in Cases.items() for w in (v if isinstance(v, (tuple, list, set, frozenset)) else [v])]
if isinstance(Expr, (Variable, Node)):
return [((expr((~ k.operator), Expr, k.right_operand()) | v) if isinstance(k, Condition) els... |
class Effect991(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Small Energy Turret')), 'maxRange', ship.getModifiedItemAttr('eliteBonusGunship1'), skill='Assault Frigates', **kwargs) |
class LogosLexer(ObjectiveCppLexer):
name = 'Logos'
aliases = ['logos']
filenames = ['*.x', '*.xi', '*.xm', '*.xmi']
mimetypes = ['text/x-logos']
version_added = '1.6'
priority = 0.25
tokens = {'statements': [('(%orig|%log)\\b', Keyword), ('(%c)\\b(\\()(\\s*)([a-zA-Z$_][\\w$]*)(\\s*)(\\))', ... |
def _ignore(module, root):
if (not module.__name__.startswith(root)):
return True
name = module.__name__[len(root):]
if (name in modules_ignored):
return True
while ((idx := name.rfind('.')) > 0):
name = name[:idx]
if (name in modules_ignored):
return True
... |
.skipif(randovania.is_frozen(), reason='graphviz not included in executable')
.parametrize('single_image', [False, True])
.parametrize('include_pickups', [False, True])
def test_render_region_graph_logic(mocker, single_image, include_pickups, blank_game_description):
gd = blank_game_description
args = MagicMock... |
class BatchHardTripletLossDistanceFunction():
def cosine_distance(embeddings):
return (1 - util.pytorch_cos_sim(embeddings, embeddings))
def eucledian_distance(embeddings, squared=False):
dot_product = torch.matmul(embeddings, embeddings.t())
square_norm = torch.diag(dot_product)
... |
class Recorder(object):
def __init__(self, work_dir, print_log, log_interval):
self.cur_time = time.time()
self.print_log_flag = print_log
self.log_interval = log_interval
self.log_path = '{}/log.txt'.format(work_dir)
self.timer = dict(dataloader=0.001, device=0.001, forward=... |
class AMPTrainer(SimpleTrainer):
def __init__(self, model, data_loader, optimizer, grad_scaler=None):
unsupported = 'AMPTrainer does not support single-process multi-device training!'
if isinstance(model, DistributedDataParallel):
assert (not (model.device_ids and (len(model.device_ids) ... |
class CCBlock(dict):
def read_cc(self, fid, pointer):
if ((pointer != 0) and (pointer is not None)):
fid.seek(pointer)
self['pointer'] = pointer
(self['id'], reserved, self['length'], self['link_count'], self['cc_tx_name'], self['cc_md_unit'], self['cc_md_comment'], self[... |
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.BatchNorm2d(planes, momentum=BN_MOMENTUM)
self.relu = nn.ReLU(inplace=True)
... |
def register_optics(name: str, overwrite: bool=False, reason_to_exclude: Optional[str]=None) -> Callable:
return generic_register(name=name, registrator_name='Optics solver', registry=OPTICS_METHOD_REGISTRY, signature=OPTICS_METHOD_SIGNATURE, overwrite=overwrite, reason_to_exclude=reason_to_exclude) |
class Movie(Cog):
def __init__(self, bot: Bot):
self.bot = bot
self. ClientSession = bot.
(name='movies', aliases=('movie',), invoke_without_command=True)
async def movies(self, ctx: Context, genre: str='', amount: int=5) -> None:
if (amount > 20):
(await ctx.send("You ca... |
_test
def test_simplernn_legacy_interface():
old_layer = keras.layers.SimpleRNN(input_shape=[3, 5], output_dim=2, name='d')
new_layer = keras.layers.SimpleRNN(2, input_shape=[3, 5], name='d')
assert (json.dumps(old_layer.get_config()) == json.dumps(new_layer.get_config()))
old_layer = keras.layers.Simpl... |
class IDXGIResource(IDXGIDeviceSubObject):
_iid_ = comtypes.GUID('{035f3ab4-482e-4e50-b41f-8a7f8bd8960b}')
_methods_ = [comtypes.STDMETHOD(comtypes.HRESULT, 'GetSharedHandle'), comtypes.STDMETHOD(comtypes.HRESULT, 'GetUsage'), comtypes.STDMETHOD(comtypes.HRESULT, 'SetEvictionPriority'), comtypes.STDMETHOD(comty... |
def layer(op):
def layer_decorated(self, *args, **kwargs):
name = kwargs.setdefault('name', self.get_unique_name(op.__name__))
if (len(self.inputs) == 0):
raise RuntimeError(('No input variables found for layer %s.' % name))
elif (len(self.inputs) == 1):
layer_input =... |
def main():
global totalMethod
formatNames = list(formats.keys())
formatNames.sort()
optparser = optparse.OptionParser(usage='\n\t%prog [options] [file] ...')
optparser.add_option('-o', '--output', metavar='FILE', type='string', dest='output', help='output filename [stdout]')
optparser.add_optio... |
def _make_args_class(base, argnames):
unroll_argnames = unroll.unrolling_iterable(enumerate(argnames))
class Args(base):
_attrs_ = _immutable_fields_ = argnames
def _init_args(self, *args):
for (i, name) in unroll_argnames:
setattr(self, name, args[i])
def _co... |
def compute_gradient_penalty(discriminator, real_samples, fake_samples, device='cuda'):
alpha = torch.rand([real_samples.size(0), 1], device=device)
interpolates = ((alpha * real_samples) + ((1.0 - alpha) * fake_samples)).requires_grad_(True)
d_interpolates = discriminator(interpolates)
fake = torch.one... |
def convert_weights_to_lp(model: nn.Module, dtype=torch.float16):
def _convert_weights(l):
if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)):
l.weight.data = l.weight.data.to(dtype)
if (l.bias is not None):
l.bias.data = l.bias.data.to(dtype)
if isinstance(l... |
def get_sufficient_info_reward_location(reward_helper_info):
asked_entities = reward_helper_info['_entities']
answers = reward_helper_info['_answers']
observation_before_finish = reward_helper_info['observation_before_finish']
game_finishing_mask = reward_helper_info['game_finishing_mask']
res = []
... |
class NormalizeCaseTest(TestCase):
def setUp(self):
self.filesystem = fake_filesystem.FakeFilesystem(path_separator='/')
self.filesystem.is_case_sensitive = False
def test_normalize_case(self):
self.filesystem.create_file('/Foo/Bar')
self.assertEqual(f'{self.filesystem.root_dir_n... |
def imagenet_pretrain_rcrop(mean=None, std=None):
trans_list = [transforms.RandomResizedCrop(size=224, scale=(0.2, 1.0)), transforms.RandomHorizontalFlip(p=0.5), transforms.RandomApply([transforms.ColorJitter(0.4, 0.4, 0.4, 0.1)], p=0.8), transforms.RandomGrayscale(p=0.2), transforms.RandomApply([GaussianBlur([0.1,... |
def viz_gen_and_dis_losses(all_D_losses, all_G_losses, save_dir=None):
plt.plot(all_D_losses, 'r')
plt.plot(all_G_losses, 'g')
plt.title('Model convergence')
plt.ylabel('Losses')
plt.xlabel('# of steps')
plt.legend(['Discriminator network', 'Generator network'], loc='upper right')
plt.show()... |
def test_transformer_force_over():
transformer = Transformer.from_crs('EPSG:4326', 'EPSG:3857', force_over=True)
(xxx, yyy) = transformer.transform(0, 140)
(xxx_over, yyy_over) = transformer.transform(0, (- 220))
assert (xxx > 0)
assert (xxx_over < 0)
(xxx_inverse, yyy_inverse) = transformer.tra... |
class OpenImagesChallengeEvaluator(OpenImagesDetectionEvaluator):
def __init__(self, categories, evaluate_masks=False, matching_iou_threshold=0.5, evaluate_corlocs=False, group_of_weight=1.0):
if (not evaluate_masks):
metrics_prefix = 'OpenImagesDetectionChallenge'
else:
metr... |
def connect_to_wifi(request: WSGIRequest) -> HttpResponse:
ssid = request.POST.get('ssid')
password = request.POST.get('password')
if ((ssid is None) or (password is None) or (ssid == '') or (password == '')):
return HttpResponseBadRequest('Please provide both SSID and password')
try:
ou... |
.parametrize('is_locked', [False, True])
def test_update_with_use_latest_vs_lock(package: ProjectPackage, repo: Repository, pool: RepositoryPool, io: NullIO, is_locked: bool) -> None:
package.add_dependency(Factory.create_dependency('A', '*'))
package.add_dependency(Factory.create_dependency('B', '*'))
pack... |
class PartialTxInput(TxInput, PSBTSection):
def __init__(self, *args, **kwargs):
TxInput.__init__(self, *args, **kwargs)
self._utxo = None
self._witness_utxo = None
self.part_sigs = {}
self.sighash = None
self.bip32_paths = {}
self.redeem_script = None
... |
class ExternalMultiKernelManager(MultiKernelManager):
def restart_kernel(self, *args, **kwargs):
raise NotImplementedError('Restarting a kernel running in Excel is not supported.')
async def _async_restart_kernel(self, *args, **kwargs):
raise NotImplementedError('Restarting a kernel running in E... |
def compute_dense_reward(self, action):
action = np.clip(action, (- 1), 1)
gripper_pos = self.robot.ee_pose.p
cube_pos = self.cubeA.pose.p
dist_gripper_cube = np.linalg.norm((gripper_pos - cube_pos))
goal_pos = self.goal_position
dist_cube_goal = np.linalg.norm((goal_pos - cube_pos))
graspin... |
class TCustomCommands(PluginTestCase):
def setUp(self):
module = self.modules['CustomCommands']
globals().update(vars(module))
self.plugin = self.plugins['CustomCommands'].cls
config.init()
self.cmd_list = CustomCommands.DEFAULT_COMS
self.commands = JSONObjectDict.fro... |
(frozen=True)
class Result():
code: int
command_run: str
stderr: str
stdout: str
test_case_dir: Path
tempdir: Path
def print_description(self, *, verbosity: Verbosity) -> None:
if self.code:
print(f'{self.command_run}:', end=' ')
print_error('FAILURE\n')
... |
class MessageEntityType(StringEnum):
__slots__ = ()
MENTION = 'mention'
HASHTAG = 'hashtag'
CASHTAG = 'cashtag'
PHONE_NUMBER = 'phone_number'
BOT_COMMAND = 'bot_command'
URL = 'url'
EMAIL = 'email'
BOLD = 'bold'
ITALIC = 'italic'
CODE = 'code'
PRE = 'pre'
TEXT_LINK = ... |
class LongNameTest(unittest.TestCase):
root_rp = rpath.RPath(Globals.local_connection, abs_test_dir)
out_rp = root_rp.append_path('output')
def test_length_limit(self):
Myrm(self.out_rp.path)
self.out_rp.mkdir()
really_long = self.out_rp.append(('a' * NAME_MAX_LEN))
really_lo... |
def _convert_dict_to_message(_dict: dict) -> BaseMessage:
role = _dict['role']
if (role == 'user'):
return HumanMessage(content=_dict['content'])
elif (role == 'assistant'):
return AIMessage(content=_dict['content'])
elif (role == 'system'):
return SystemMessage(content=_dict['co... |
class SetBotCommands():
async def set_bot_commands(self: 'pyrogram.Client', commands: List['types.BotCommand'], scope: 'types.BotCommandScope'=types.BotCommandScopeDefault(), language_code: str='') -> bool:
return (await self.invoke(raw.functions.bots.SetBotCommands(commands=[c.write() for c in commands], s... |
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 TestPack(unittest.TestCase):
def test_over_x(self):
env = AllocatorEnvironment(self, 3, 3)
env.add_fail(3, 4)
def test_over_y(self):
env = AllocatorEnvironment(self, 3, 3)
env.add_fail(4, 3)
def test_1(self):
env = AllocatorEnvironment(self, 4, 4)
for i ... |
def supervised(args):
if (args.dataset == 'TUAB'):
(train_loader, test_loader, val_loader) = prepare_TUAB_dataloader(args)
else:
raise NotImplementedError
if (args.model == 'SPaRCNet'):
model = SPaRCNet(in_channels=args.in_channels, sample_length=int((args.sampling_rate * args.sample... |
class AbstractPlot(object):
__metaclass__ = ABCMeta
def __init__(self):
self.BOKEH_RESIZE = 50
self.TMVA_RESIZE = 80
self.xlim = None
self.ylim = None
self.xlabel = ''
self.ylabel = ''
self.title = ''
self.figsize = (13, 7)
self.fontsize = ... |
class BalancedSampler(Sampler):
def __init__(self, data_source, batch_size, images_per_class=3):
self.data_source = data_source
self.ys = data_source.ys
self.num_groups = (batch_size // images_per_class)
self.batch_size = batch_size
self.num_instances = images_per_class
... |
def get_model_cache(config):
cache_config = config.get('DATA_MODEL_CACHE_CONFIG', {})
engine = cache_config.get('engine', 'noop')
if (engine == 'noop'):
return NoopDataModelCache(cache_config)
if (engine == 'inmemory'):
return InMemoryDataModelCache(cache_config)
if (engine == 'memca... |
def run_one_test(pm, args, index, tidx):
global NAMES
result = True
tresult = ''
tap = ''
res = TestResult(tidx['id'], tidx['name'])
if (args.verbose > 0):
print('\t\n=====> ', end='')
print(((('Test ' + tidx['id']) + ': ') + tidx['name']))
if ('skip' in tidx):
if (tidx['... |
def original_initialization(mask_temp, initial_state_dict):
global model
step = 0
for (name, param) in model.named_parameters():
if ('weight' in name):
weight_dev = param.device
param.data = torch.from_numpy((mask_temp[step] * initial_state_dict[name].cpu().numpy())).to(weigh... |
def hsv_to_rgb(h, s, v):
if (s == 0.0):
return (v, v, v)
i = int((h * 6.0))
f = ((h * 6.0) - i)
p = (v * (1.0 - s))
q = (v * (1.0 - (s * f)))
t = (v * (1.0 - (s * (1.0 - f))))
i = (i % 6)
v = int((v * 255))
t = int((t * 255))
p = int((p * 255))
q = int((q * 255))
... |
def simulated_annealing(ratio):
imgs = {}
masks = {}
t = []
measure = []
true_image_set = []
resolution = []
img_set = []
mask = []
img_true = img('true__out__images.pickle')[0]
mask_true = img('true__out__images.pickle')[1]
img_rotate = img('rotation_var__out__images.pickle'... |
_model
class ProjectUser(User):
project_id: int = field(default=None)
project_user_id: int = field(default=None)
role: str = field(default=None)
def from_json(cls, value: JsonResponse, **kwargs) -> 'ProjectUser':
user = value.get('user', {})
user['project_id'] = value['project_id']
... |
class TestSpanObserver(SpanObserver):
def __init__(self, span):
self.span = span
self.on_start_called = False
self.on_finish_called = False
self.on_finish_exc_info = None
self.tags = {}
self.logs = []
self.children = []
def on_start(self):
assert (... |
('invoice.payment_succeeded')
def invoice_paid_to_slack(event, **kwargs):
data = event.data['object']
invoice_id = data['id']
invoice = Invoice.sync_from_stripe_data(stripe.Invoice.retrieve(invoice_id))
log.debug('Stripe invoice %s is paid. Posting to Slack...', invoice)
slack_message('adserver/slac... |
def dataset_utm_north_down(draw):
x = draw(floats(min_value=(- 1000000.0), max_value=1000000.0, allow_nan=False, allow_infinity=False))
y = draw(floats(min_value=(- 1000000.0), max_value=1000000.0, allow_nan=False, allow_infinity=False))
res = draw(floats(min_value=0.1, max_value=30, allow_nan=False, allow_... |
_execution_thread(None)
class TestStyle(PyScriptTest):
def test_pyscript_not_defined(self):
doc = '\n <html>\n <head>\n <link rel="stylesheet" href="build/core.css" />\n </head>\n <body>\n <py-config>hello</py-config>\n <py-script>hello</s... |
class TestGenericTags():
def test__generic_abi_macos(self, monkeypatch):
monkeypatch.setattr(sysconfig, 'get_config_var', (lambda key: '.cpython-37m-darwin.so'))
monkeypatch.setattr(tags, 'interpreter_name', (lambda : 'cp'))
assert (tags._generic_abi() == ['cp37m'])
def test__generic_abi... |
_error_logging()
class SignalsPlotter(AbstractDocument):
def __init__(self, tickers: Union[(Ticker, Sequence[Ticker])], start_date: datetime, end_date: datetime, data_handler: DataHandler, alpha_models: Union[(AlphaModel, Sequence[AlphaModel])], settings: Settings, pdf_exporter: PDFExporter, title: str='Signals Plo... |
class Migration(migrations.Migration):
dependencies = [('adserver', '0047_breakout_ad_parts')]
operations = [migrations.AddConstraint(model_name='adimpression', constraint=models.UniqueConstraint(condition=models.Q(advertisement=None), fields=('publisher', 'date'), name='null_offer_unique'))] |
_datapipe('save_by_iopath')
class IoPathSaverIterDataPipe(IterDataPipe[str]):
def __init__(self, source_datapipe: IterDataPipe[Tuple[(Any, U)]], mode: str='w', filepath_fn: Optional[Callable]=None, *, pathmgr=None, handler=None):
if (iopath is None):
raise ModuleNotFoundError('Package `iopath` i... |
class Memory(MemoryAPI):
__slots__ = ['_bytes']
logger = logging.getLogger('eth.vm.memory.Memory')
def __init__(self) -> None:
self._bytes = bytearray()
def extend(self, start_position: int, size: int) -> None:
if (size == 0):
return
new_size = ceil32((start_position ... |
class ResNet(nn.Module):
def __init__(self, block, num_block, k=10, num_classes=100):
super(ResNet, self).__init__()
self.in_channels = (1 * k)
self.conv1 = nn.Sequential(nn.Conv2d(3, (1 * k), kernel_size=3, padding=1, bias=False), nn.BatchNorm2d((1 * k)), nn.ReLU(inplace=True))
self... |
def load(filename, file=None, mimetype=None):
decoder = get_decoder(filename, mimetype)
if (not file):
with open(filename) as f:
file_contents = f.read()
else:
file_contents = file.read()
file.close()
if hasattr(file_contents, 'decode'):
file_contents = file_c... |
def wps_webpage_taskreward(sid: str):
tasklist_url = '
r = s.post(tasklist_url, headers={'sid': sid})
if (len(r.history) != 0):
if (r.history[0].status_code == 302):
sio.write(': sid, \n\n')
return 0
resp = json.loads(r.text)
resplist = [resp['data']['1']['task'], res... |
def parse_args():
special_args = [{'name': ['-s', '--size'], 'default': '10000', 'metavar': 'n', 'type': int, 'help': 'The size n in n^2 (default 10000)'}, {'name': ['-t', '--type'], 'choices': ['cpu', 'gpu'], 'default': 'gpu', 'type': str, 'help': 'Use GPU or CPU arrays'}, {'name': ['-c', '--chunk-size'], 'default... |
def listRedundantModules():
mods = {}
for (name, mod) in sys.modules.items():
if (not hasattr(mod, '__file__')):
continue
mfile = os.path.abspath(mod.__file__)
if (mfile[(- 1)] == 'c'):
mfile = mfile[:(- 1)]
if (mfile in mods):
print(('module a... |
class Compressor(object):
_dictionary = None
_dictionary_size = None
def __init__(self, mode=DEFAULT_MODE, quality=lib.BROTLI_DEFAULT_QUALITY, lgwin=lib.BROTLI_DEFAULT_WINDOW, lgblock=0):
enc = lib.BrotliEncoderCreateInstance(ffi.NULL, ffi.NULL, ffi.NULL)
if (not enc):
raise Runt... |
class PublisherReportView(PublisherAccessMixin, BaseReportView):
export_view = 'publisher_report_export'
template_name = 'adserver/reports/publisher.html'
fieldnames = ['index', 'views', 'clicks', 'ctr', 'ecpm', 'revenue', 'revenue_share']
def get_context_data(self, **kwargs):
context = super().... |
def read_corpus(corpus_preprocessd_file, id2term_dict):
id2corpus_terms = {}
for line in tqdm(open(corpus_preprocessd_file)):
term_set = set()
r = line.strip().split('\t')
id = r[0]
for i in range(2, len(r)):
utt = r[i]
for w in utt.split():
... |
class MultiHeadedDotAttention(nn.Module):
def __init__(self, h, d_model, dropout=0.1, scale=1, project_k_v=1, use_output_layer=1, do_aoa=0, norm_q=0, dropout_aoa=0.3):
super(MultiHeadedDotAttention, self).__init__()
assert (((d_model * scale) % h) == 0)
self.d_k = ((d_model * scale) // h)
... |
def add_standard_arguments(parser):
group = parser.add_argument_group('General options')
group.add_argument('--help', '-h', action='help', help='Show this help message and exit.')
loglevel_choices = ['critical', 'error', 'warning', 'info', 'debug']
loglevel_default = 'info'
group.add_argument('--log... |
def test_ahi_l2_area_def(himl2_filename, caplog):
from pyproj import CRS
ps = '+a=6378137 +h= +lon_0=140.7 +no_defs +proj=geos +rf=298. +type=crs +units=m +x_0=0 +y_0=0'
fh = ahil2_filehandler(himl2_filename)
clmk_id = make_dataid(name='cloudmask')
area_def = fh.get_area_def(clmk_id)
assert (are... |
def bot_methods(ext_bot=True, include_camel_case=False):
arg_values = []
ids = []
non_api_methods = ['de_json', 'de_list', 'to_dict', 'to_json', 'parse_data', 'get_bot', 'set_bot', 'initialize', 'shutdown', 'insert_callback_data']
classes = ((Bot, ExtBot) if ext_bot else (Bot,))
for cls in classes:
... |
def retrieve_artifact(name: str, gpu: Optional[str]):
if (gpu not in [None, 'single', 'multi']):
raise ValueError(f'Invalid GPU for artifact. Passed GPU: `{gpu}`.')
if (gpu is not None):
name = f'{gpu}-gpu_{name}'
_artifact = {}
if os.path.exists(name):
files = os.listdir(name)
... |
def save_summaries(summaries, path, original_document_name):
for (summary, document_name) in zip(summaries, original_document_name):
if ('.' in document_name):
bare_document_name = '.'.join(document_name.split('.')[:(- 1)])
extension = document_name.split('.')[(- 1)]
name... |
def test_move_items_by(qapp):
item1 = BeePixmapItem(QtGui.QImage())
item1.setPos(0, 0)
item2 = BeePixmapItem(QtGui.QImage())
item2.setPos(30, 40)
command = commands.MoveItemsBy([item1, item2], QtCore.QPointF(50, 100))
command.redo()
assert (item1.pos().x() == 50)
assert (item1.pos().y() ... |
class DiscriminatorPointConv():
def __init__(self, name, sorting_method='cxyz', activation_fn=tf.nn.leaky_relu, bn=True):
self.name = name
self.sorting_method = sorting_method
self.activation_fn = activation_fn
self.bn = bn
self.reuse = False
def __call__(self, point_clou... |
def test_proj_imshow(data_vda_jybeam_lower, use_dask):
plt = pytest.importorskip('matplotlib.pyplot')
(cube, data) = cube_and_raw(data_vda_jybeam_lower, use_dask=use_dask)
mom0 = cube.moment0()
if (LooseVersion(plt.matplotlib.__version__) < LooseVersion('2.1')):
plt.imshow(mom0.value)
else:
... |
def get_lon_lat(pixel, nav_params):
scan_angles = transform_image_coords_to_scanning_angles(pixel, nav_params.proj_params.image_offset, nav_params.proj_params.scanning_angles)
view_vector_sat = transform_scanning_angles_to_satellite_coords(scan_angles, nav_params.proj_params.scanning_angles.misalignment)
vi... |
def make_dataset(path, impl, fix_lua_indexing=False, dictionary=None):
if ((impl == 'raw') and IndexedRawTextDataset.exists(path)):
assert (dictionary is not None)
return IndexedRawTextDataset(path, dictionary)
elif ((impl == 'lazy') and IndexedDataset.exists(path)):
return IndexedDatase... |
def ws_sacpz(network=None, station=None, location=None, channel=None, time=None, tmin=None, tmax=None):
d = {}
if network:
d['network'] = network
if station:
d['station'] = station
if location:
d['location'] = location
else:
d['location'] = '--'
if channel:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.