code stringlengths 281 23.7M |
|---|
def getOpenFileName(*, parent, title, filter='', config: 'SimpleConfig') -> Optional[str]:
directory = config.get('io_dir', os.path.expanduser('~'))
(fileName, __) = QFileDialog.getOpenFileName(parent, title, directory, filter)
if (fileName and (directory != os.path.dirname(fileName))):
config.set_k... |
class TestInvalidityDate():
def test_invalid_invalidity_date(self):
with pytest.raises(TypeError):
x509.InvalidityDate('notadate')
def test_eq(self):
invalid1 = x509.InvalidityDate(datetime.datetime(2015, 1, 1, 1, 1))
invalid2 = x509.InvalidityDate(datetime.datetime(2015, 1, ... |
.parametrize(['summary', 'details', 'description'], [('fakesummary', 'fakedetails', 'fakesummary'), ('fakesummary\nanother line', 'fakedetails', 'fakesummary another line'), (None, 'fakedetails', 'fakedetails'), (None, 'fakedetails\nanother line', 'fakedetails another line'), (None, None, 'N/A')])
def test_pypi_vuln_de... |
def test_direct_origin_does_not_download_url_dependency_when_cached(fixture_dir: FixtureDirGetter, mocker: MockerFixture) -> None:
artifact_cache = MagicMock()
artifact_cache.get_cached_archive_for_link = MagicMock(return_value=(fixture_dir('distributions') / 'demo-0.1.2-py2.py3-none-any.whl'))
direct_origi... |
def test_invalid_tuple_sizes():
with pytest.raises(ValueError, match='HUD color must be a tuple of 3 ints.'):
PrimeCosmeticPatches(hud_color=(0, 0, 0, 0))
with pytest.raises(ValueError, match='Suit color rotations must be a tuple of 4 ints.'):
PrimeCosmeticPatches(suit_color_rotations=(0, 0, 0)) |
class ConfigDialog(QtWidgets.QDialog):
attributes = ['show_cursor', 'default_gf_dir', 'nvectors', 'vector_color', 'vector_relative_length', 'vector_pen_thickness', 'view_east', 'view_north', 'view_down', 'view_los']
def __init__(self, *args, **kwargs):
QtWidgets.QDialog.__init__(self, *args, **kwargs)
... |
class Message(TLObject):
ID =
__slots__ = ['msg_id', 'seq_no', 'length', 'body']
QUALNAME = 'Message'
def __init__(self, body: TLObject, msg_id: int, seq_no: int, length: int):
self.msg_id = msg_id
self.seq_no = seq_no
self.length = length
self.body = body
def read(d... |
def cmd_venv_create(options, root, python, benchmarks):
from . import _venv
from .venv import Requirements, VenvForBenchmarks
if _venv.venv_exists(root):
sys.exit(f'ERROR: the virtual environment already exists at {root}')
requirements = Requirements.from_benchmarks(benchmarks)
venv = VenvFo... |
class Effect1585(BaseEffect):
type = 'passive'
def handler(fit, skill, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Capital Energy Turret')), 'damageMultiplier', (skill.getModifiedItemAttr('damageMultiplierBonus') * skill.level), **kwargs) |
class TDK_Gen40_38(TDK_Lambda_Base):
voltage_values = [0, 40]
current_values = [0, 38]
over_voltage_values = [2, 44]
under_voltage_values = [0, 38]
def __init__(self, adapter, name='TDK Lambda Gen40-38', address=6, **kwargs):
super().__init__(adapter, name, address, **kwargs) |
def _weighting(filter_type, first, last):
third_oct_bands = third(12.5, 20000.0).tolist()
low = third_oct_bands.index(first)
high = third_oct_bands.index(last)
if (filter_type == 'a'):
freq_weightings = THIRD_OCTAVE_A_WEIGHTING
elif (filter_type == 'c'):
freq_weightings = THIRD_OCTAV... |
class Effect11373(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Capital Shield Operation')), 'shieldBonus', src.getModifiedItemAttr('shipBonusDreadnoughtM1'), skill='Minmatar Dreadnought', **kwa... |
(version_base=None, config_path='.', config_name='gpt2_train_cfg')
def main(cfg: DictConfig):
ddp_setup()
gpt_cfg = GPTConfig(**cfg['gpt_config'])
opt_cfg = OptimizerConfig(**cfg['optimizer_config'])
data_cfg = DataConfig(**cfg['data_config'])
trainer_cfg = TrainerConfig(**cfg['trainer_config'])
... |
('/comparison', methods=['GET', 'POST'])
def comparison():
form = MainForm()
if form.validate_on_submit():
if form.upload.data:
process_upload(form)
if form.upload2.data:
process_upload(form, True)
if ((not session.get('SAVEPATH')) or (not session.get('SAVEPATH2')... |
class TenluaVn(BaseAccount):
__name__ = 'TenluaVn'
__type__ = 'account'
__version__ = '0.02'
__status__ = 'testing'
__description__ = 'TenluaVn account plugin'
__license__ = 'GPLv3'
__authors__ = [('GammaC0de', 'nitzo2001[AT]yahoo[DOT]com')]
API_URL = '
def api_request(self, method, ... |
class NetworkCIFAR(nn.Module):
def __init__(self, C, num_classes, layers, auxiliary, genotype, reweight=False):
super(NetworkCIFAR, self).__init__()
self._layers = layers
self._auxiliary = auxiliary
self.drop_path_prob = 0
stem_multiplier = 3
C_curr = (stem_multiplier... |
def decompose_union(expected_type: Value, parent_value: Value, ctx: CanAssignContext, exclude_any: bool) -> Optional[Tuple[(BoundsMap, Value)]]:
value = unannotate(parent_value)
if isinstance(value, MultiValuedValue):
bounds_maps = []
remaining_values = []
for val in value.vals:
... |
def make_field(arr, dtype=None):
dtype = (dtype or arr.dtype)
if (arr.name is None):
name = 'values'
else:
name = arr.name
field = {'name': name, 'type': as_json_table_type(dtype)}
if is_categorical_dtype(arr):
if hasattr(arr, 'categories'):
cats = arr.categories
... |
class DependingTransition(Transition):
def __init__(self, source, dest, conditions=None, unless=None, before=None, after=None, prepare=None, **kwargs):
self._result = self._dest = None
super(DependingTransition, self).__init__(source, dest, conditions, unless, before, after, prepare)
if isin... |
def clean_voltage(df):
repl_voltage = {'medium': '33000', '19.1 kV': '19100', 'high': '220000', '240 VAC': '240', '2*220000': '220000;220000', 'KV30': '30kV'}
df.dropna(subset=['voltage'], inplace=True)
df['voltage'] = df['voltage'].astype(str).replace(repl_voltage).str.lower().str.replace(' ', '').str.repl... |
def main(args):
at_step = args.step
output_dir_name = args.output_dir
layer_name = args.layer_name
block_type = args.block_type
postfix = args.postfix
probe_type = args.probe_type
normalized = args.normalized
smoothed = args.smoothed
lasso = (True if (args.lasso == 'yes') else False)... |
def test_json_index_page() -> None:
c = ConfigParser()
c.add_section('mirror')
c['mirror']['workers'] = '1'
s = SimpleAPI(FilesystemStorage(config=c), SimpleFormat.ALL, [], 'sha256', False, None)
with TemporaryDirectory() as td:
td_path = Path(td)
simple_dir = (td_path / 'simple')
... |
def evaluate_code_prompt(path):
def _parse_option(option: str, question: str):
solution = question.split(option)[1].split(')')[0]
if ('none' in solution.lower()):
return None
solution = ''.join([c for c in solution if (c.isdigit() or (c == '.'))])
if ((solution[0] == '.')... |
class ITypeHintingFactory():
def make_param_provider(self):
raise NotImplementedError
def make_return_provider(self):
raise NotImplementedError
def make_assignment_provider(self):
raise NotImplementedError
def make_resolver(self):
raise NotImplementedError |
class RemoteExpert(nn.Module):
def __init__(self, uid, endpoint: Endpoint):
super().__init__()
(self.uid, self.endpoint) = (uid, endpoint)
self._info = None
def stub(self):
return _get_expert_stub(self.endpoint)
def forward(self, *args, **kwargs):
assert (len(kwargs) ... |
def main():
app = Flask(__name__)
app.config.update(DB_CONNECTION_STRING=':memory:', SQLALCHEMY_DATABASE_URI='sqlite://')
app.debug = True
with app.app_context():
injector = Injector([AppModule(app)])
configure_views(app=app)
FlaskInjector(app=app, injector=injector)
client = app.tes... |
class HFAttribute(HFProxy):
def __init__(self, root, attr: str):
self.root = root
self.attr = attr
self.tracer = root.tracer
self._node = None
def node(self):
if (self._node is None):
self._node = self.tracer.create_proxy('call_function', getattr, (self.root, ... |
class SitemapGenerator(object):
def __init__(self, context, settings, path, theme, output_path, *null):
self.output_path = output_path
self.context = context
self.now = datetime.now()
self.siteurl = settings.get('SITEURL')
self.default_timezone = settings.get('TIMEZONE', 'UTC... |
class ChangeOccurrencesTest(unittest.TestCase):
def setUp(self):
self.project = testutils.sample_project()
self.mod = testutils.create_module(self.project, 'mod')
def tearDown(self):
testutils.remove_project(self.project)
super().tearDown()
def test_simple_case(self):
... |
def h3_input_df(spark_context, spark_session):
data = [{'id': 1, 'origin_ts': '2016-04-11 11:31:11', 'feature1': 200, 'feature2': 200, 'lat': (- 23.55419), 'lng': (- 46.670723), 'house_id': 8921}, {'id': 1, 'origin_ts': '2016-04-11 11:44:12', 'feature1': 300, 'feature2': 300, 'lat': (- 23.55419), 'lng': (- 46.67072... |
def compare_proposer_leaders(x, y):
print('Leader diff')
x_list = [(int(i[0]), i[1]) for i in x['proposer_leaders'].items()]
y_list = [(int(i[0]), i[1]) for i in y['proposer_leaders'].items()]
for (idx, l, r) in compare_list(x_list, y_list):
if (l is not None):
l = 'hash {} (lvl {:3}... |
def test_user(host):
user = host.user('sshd')
assert user.exists
assert (user.name == 'sshd')
assert (user.uid == 100)
assert (user.gid == 65534)
assert (user.group == 'nogroup')
assert (user.gids == [65534])
assert (user.groups == ['nogroup'])
assert (user.shell == '/usr/sbin/nologi... |
def _set_allowed_requests(sec_class, sec_level):
requests = {'RedirectedRun', 'VirtualFile.readfromid', 'VirtualFile.closebyid', 'Globals.get', 'log.Log.open_logfile_allconn', 'log.Log.close_logfile_allconn', 'log.Log.log_to_file', 'robust.install_signal_handlers', 'SetConnections.add_redirected_conn', 'sys.stdout.... |
def gen_grid2d(grid_size: int, left_end: float=(- 1), right_end: float=1) -> torch.Tensor:
x = torch.linspace(left_end, right_end, grid_size)
(x, y) = torch.meshgrid([x, x], indexing='ij')
grid = torch.cat((x.reshape((- 1), 1), y.reshape((- 1), 1)), dim=1).reshape(grid_size, grid_size, 2)
return grid |
class ViewRecordDal(object):
def create_view_domain(domain_name):
if domain_name.endswith(VIEW_ZONE):
for (k, v) in NORMAL_TO_VIEW.items():
if domain_name.endswith(v):
return (domain_name, k)
raise BadParam('invalid domain', msg_ch=(u'view: %s' % N... |
def report_results(split_df, opt, report_obs_number=False, max_char=None, rename_model_ids=False, VM_path=True):
difficulty_groups = ['Po', 'Pn', 'No', 'Nn', 'F1_o', 'F1_n']
accuracies = []
f1s = []
cases = []
for case in difficulty_groups:
if ('F1_' in case):
case = case[(- 1)]
... |
class OpenLidState(DefaultScript):
def at_script_creation(self):
self.key = 'open_lid_script'
self.desc = 'Script that manages the opened-state cmdsets for red button.'
self.persistent = True
def at_start(self):
self.obj.cmdset.add(cmdsetexamples.LidOpenCmdSet)
def is_valid(s... |
class _TrafficSignalState(VersionBase):
def __init__(self, signal_id, state):
self.signal_id = signal_id
self.state = state
def __eq__(self, other):
if isinstance(other, _TrafficSignalState):
if (self.get_attributes() == other.get_attributes()):
return True
... |
def cut_tsv(file, debug):
m = TSV_REGEX.match(file)
if (m is None):
raise ValueError(f'{file} is not matching tsv pattern')
src = m.groups()[0]
tgt = m.groups()[1]
to_file1 = f'{file}.{src}'
to_file2 = f'{file}.{tgt}'
cmd1 = f"cat {file} | cut -f1 |awk '{{$1=$1}};1' > {to_file1}"
... |
class NetworkCardAssets(models.Model):
asset = models.ForeignKey('Assets', related_name='network_card_assets', on_delete=models.CASCADE)
network_card_name = models.CharField(max_length=20, blank=True, null=True, verbose_name='')
network_card_mac = models.CharField(max_length=64, blank=True, null=True, verbo... |
class Polyline(VersionBase):
def __init__(self, time, positions):
if (time and (len(time) < 2)):
raise ValueError('not enough time inputs')
if (len(positions) < 2):
raise ValueError('not enough position inputs')
if (time and (len(time) != len(positions))):
... |
class TestInstallColormap(EndianTest):
def setUp(self):
self.req_args_0 = {'cmap': }
self.req_bin_0 = b'Q\x00\x02\x00&\xf0DO'
def testPackRequest0(self):
bin = request.InstallColormap._request.to_binary(*(), **self.req_args_0)
self.assertBinaryEqual(bin, self.req_bin_0)
def t... |
class TernaryOpMixin(_GenericOpMixin):
def test_mathematically_correct(self, op, data_l, data_m, data_r, out_type):
(left, mid, right) = (data_l(), data_m(), data_r())
expected = self.op_numpy(left.to_array(), mid.to_array(), right.to_array())
test = op(left, mid, right)
assert isins... |
class PVTNetwork_2(nn.Module):
def __init__(self, channel=32, n_classes=1, deep_supervision=True):
super().__init__()
self.deep_supervision = deep_supervision
print(f'use Conv2d(7, 1) Conv2d(1, 7) and My attention layer'.center(80, '='))
self.backbone = pvt_v2_b2()
path = '/a... |
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [migrations.CreateModel(name='AudienceLevel', fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100, unique=True))], options={'ve... |
class MatrixMultiplication(BinaryOperator):
def __init__(self, left, right):
super().__init__('', left, right)
def diff(self, variable):
raise NotImplementedError("diff not implemented for symbol of type 'MatrixMultiplication'")
def _binary_jac(self, left_jac, right_jac):
(left, righ... |
def conv_bn(data, cfg, num_filters, kernel=(3, 3), stride=(1, 1), pad=(1, 1), group=1, workspace=512, bn_mom=0.9, name=''):
body = mx.sym.Convolution(data=data, num_filter=num_filters, kernel=kernel, stride=stride, pad=pad, num_group=group, no_bias=True, workspace=workspace, name=(name + '_conv'))
body = mx.sym... |
def generate_parity_permutations(seq):
if isinstance(seq, str):
seq = [x for x in seq]
indices = seq[1:]
permutations = [([seq[0]], 1)]
while indices:
index_to_inject = indices.pop(0)
new_permutations = []
for perm in permutations:
for put_index in range((len(... |
def discriminator(image, options, reuse=False, name='discriminator'):
with tf.variable_scope(name):
if reuse:
tf.get_variable_scope().reuse_variables()
else:
assert (tf.get_variable_scope().reuse is False)
h0 = lrelu(conv2d(image, options.df_dim, name='d_h0_conv'))
... |
def electrolyte_conductivity_base_Landesfeind2019(c_e, T, coeffs):
c = (c_e / 1000)
(p1, p2, p3, p4, p5, p6) = coeffs
A = (p1 * (1 + (T - p2)))
B = ((1 + (p3 * pybamm.sqrt(c))) + ((p4 * (1 + (p5 * np.exp((1000 / T))))) * c))
C = (1 + ((c ** 4) * (p6 * np.exp((1000 / T)))))
sigma_e = (((A * c) * ... |
class StepLRScheduler(Scheduler):
def __init__(self, optimizer: torch.optim.Optimizer, decay_t: float, decay_rate: float=1.0, warmup_t=0, warmup_lr_init=0, t_in_epochs=True, noise_range_t=None, noise_pct=0.67, noise_std=1.0, noise_seed=42, initialize=True) -> None:
super().__init__(optimizer, param_group_fi... |
def is_hermitian(operator):
if isinstance(operator, (FermionOperator, BosonOperator, InteractionOperator)):
return (normal_ordered(operator) == normal_ordered(hermitian_conjugated(operator)))
if isinstance(operator, (QubitOperator, QuadOperator)):
return (operator == hermitian_conjugated(operato... |
class PositionWeightedModuleTest(unittest.TestCase):
def test_populate_weights(self) -> None:
pw = PositionWeightedModule(max_feature_length=10)
features = KeyedJaggedTensor.from_offsets_sync(keys=['f1', 'f2'], values=torch.tensor([0, 1, 2, 3, 4, 5, 6, 7]), offsets=torch.tensor([0, 2, 2, 3, 4, 5, 8]... |
def test_preloop_hook(capsys):
testargs = ['prog', 'say hello', 'quit']
with mock.patch.object(sys, 'argv', testargs):
app = PluggedApp()
app.register_preloop_hook(app.prepost_hook_one)
app.cmdloop()
(out, err) = capsys.readouterr()
assert (out == 'one\nhello\n')
assert (not err) |
class ShapeNetPart(Dataset):
def __init__(self, root: str, split: str='train', point_num: int=2500, transform=None):
super().__init__()
self.root = root
self.point_num = point_num
self.transform = transform
self.category_id = {}
with open(os.path.join(root, 'synsetoff... |
class SIMIaccess():
def __init__(self, path=None):
assert os.path.exists(path), 'similarity matrix {} is not exists.'.format(path)
df_sim = pd.read_csv(path, index_col=0)
self.matrix = df_sim.values
self.labels = list(df_sim.columns)
def findSimi(self, dt_label, gt_label):
... |
def get_random_outer_outputs(scan_args: ScanArgs) -> List[Tuple[(int, TensorVariable, TensorVariable)]]:
rv_vars = []
for (n, oo_var) in enumerate([o for o in scan_args.outer_outputs if (not isinstance(o.type, RandomType))]):
oo_info = scan_args.find_among_fields(oo_var)
io_type = oo_info.name[(... |
def _generate_list_url(mailto: str) -> str:
list_name_domain = mailto.lower().removeprefix('mailto:').strip()
list_name = list_name_domain.split('')[0]
if list_name_domain.endswith(''):
return f'
if (not list_name_domain.endswith('')):
return mailto
if (list_name in {'csv', 'db-sig',... |
def demo(opt):
os.environ['CUDA_VISIBLE_DEVICES'] = opt.gpus_str
opt.debug = max(opt.debug, 1)
Detector = detector_factory[opt.task]
detector = Detector(opt)
if ((opt.demo == 'webcam') or (opt.demo[(opt.demo.rfind('.') + 1):].lower() in video_ext)):
cam = cv2.VideoCapture((0 if (opt.demo == ... |
def _create_test_scenes(num_scenes=2, shape=DEFAULT_SHAPE, area=None):
from satpy import Scene
ds1 = _create_test_dataset('ds1', shape=shape, area=area)
ds2 = _create_test_dataset('ds2', shape=shape, area=area)
scenes = []
for _ in range(num_scenes):
scn = Scene()
scn['ds1'] = ds1.co... |
class TestQueueConsumerServer():
def build_server(self):
server = [None]
def _build_server(max_concurrency=5, pump_raises=None, handler_raises=None):
server[0] = QueueConsumerServer.new(consumer_factory=FakeQueueConsumerFactory(pump_raises=pump_raises, handler_raises=handler_raises), max... |
class PromptView(QuotientView):
def __init__(self, ctx: Context, alert: Alert):
super().__init__(ctx, timeout=300)
self.ctx = ctx
self.alert = alert
.button(style=discord.ButtonStyle.green, label='Read Now')
async def read_now(self, inter: discord.Interaction, btn: discord.Button):
... |
def load_dataset_splits(args, task):
task.load_dataset(args.train_subset, combine=True)
for split in args.valid_subset.split(','):
for k in itertools.count():
split_k = (split + (str(k) if (k > 0) else ''))
try:
task.load_dataset(split_k, combine=False)
... |
.slow
_figures_equal()
def test_DecisionMatrixPlotter_bar(decision_matrix, fig_test, fig_ref):
dm = decision_matrix(seed=42, min_alternatives=3, max_alternatives=3, min_criteria=3, max_criteria=3)
plotter = plot.DecisionMatrixPlotter(dm=dm)
test_ax = fig_test.subplots()
plotter.bar(ax=test_ax)
df = ... |
def _basic_diff(f, x, n=1):
if isinstance(f, (Expr, Symbol, numbers.Number)):
return diff(f, x, n)
elif hasattr(f, '_eval_derivative_n_times'):
return f._eval_derivative_n_times(x, n)
else:
raise ValueError((('In_basic_diff type(arg) = ' + str(type(f))) + ' not allowed.')) |
('/v1/organization/<orgname>/private')
_param('orgname', 'The name of the organization')
_only
_user_resource(PrivateRepositories)
_if(features.BILLING)
class OrgPrivateRepositories(ApiResource):
_scope(scopes.ORG_ADMIN)
('getOrganizationPrivateAllowed')
def get(self, orgname):
permission = CreateRe... |
class ModuleInPathTest(resources.SysPathSetup, unittest.TestCase):
def test_success(self) -> None:
datadir = resources.find('')
assert modutils.module_in_path('data.module', datadir)
assert modutils.module_in_path('data.module', (datadir,))
assert modutils.module_in_path('data.module... |
('enqueue-files', args=1)
def _enqueue_files(app, value):
library = app.library
window = app.window
songs = []
for param in split_escape(value, ','):
try:
song_path = uri2fsn(param)
except ValueError:
song_path = param
if (song_path in library):
... |
class Generator(nn.Module):
def __init__(self, latent_dim, target_dim):
super().__init__()
self.net = nn.Sequential(nn.Linear(latent_dim, 600), nn.LayerNorm(600), nn.ReLU(), nn.Linear(600, 200), nn.LayerNorm(200), nn.ReLU(), nn.Linear(200, 100), nn.LayerNorm(100), nn.ReLU(), nn.Linear(100, target_di... |
def _get_remaining_args(obj: dict, cls: type, constructor_args: dict, strict: bool, fork_inst: type) -> dict:
remaining_attrs = {attr_name: obj[attr_name] for attr_name in obj if ((attr_name not in constructor_args) and (attr_name != META_ATTR))}
if (strict and remaining_attrs):
unexpected_arg = list(re... |
class TestMacroResolving(unittest.TestCase):
def setUp(self):
self.environment = pynag.Utils.misc.FakeNagiosEnvironment()
self.environment.create_minimal_environment()
self.environment.update_model()
resource_cfg_file = os.path.join(tests_dir, 'testconfigs/custom.macros.resource.cfg'... |
class TestUngrabPointer(EndianTest):
def setUp(self):
self.req_args_0 = {'time': }
self.req_bin_0 = b'\x1b\x00\x00\x02\x07k\x17\x8d'
def testPackRequest0(self):
bin = request.UngrabPointer._request.to_binary(*(), **self.req_args_0)
self.assertBinaryEqual(bin, self.req_bin_0)
... |
def make_dot(var, params=None):
if (params is not None):
assert isinstance(params.values()[0], Variable)
param_map = {id(v): k for (k, v) in params.items()}
node_attr = dict(style='filled', shape='box', align='left', fontsize='12', ranksep='0.1', height='0.2')
dot = Digraph(node_attr=node_at... |
def do_train(cfg, model, resume=False):
model.train()
optimizer = build_optimizer(cfg, model)
scheduler = build_lr_scheduler(cfg, optimizer)
checkpointer = DetectionCheckpointer(model, cfg.OUTPUT_DIR, optimizer=optimizer, scheduler=scheduler)
start_iter = (checkpointer.resume_or_load(cfg.MODEL.WEIGH... |
_rewriter([NegBinomialRV])
def negative_binomial_from_gamma_poisson(fgraph, node):
(rng, *other_inputs, n, p) = node.inputs
(next_rng, g) = _gamma.make_node(rng, *other_inputs, n, ((1 - p) / p)).outputs
(next_rng, p) = poisson.make_node(next_rng, *other_inputs, g).outputs
return [next_rng, p] |
def weights_init_normal(m):
classname = m.__class__.__name__
if (classname.find('Conv') != (- 1)):
init.normal_(m.weight.data, 0.0, 0.02)
elif (classname.find('Linear') != (- 1)):
init.normal_(m.weight.data, 0.0, 0.02)
elif (classname.find('BatchNorm2d') != (- 1)):
init.normal_(m... |
class ResnetFeatureExtractor(nn.Module):
def __init__(self, weights: Optional[str]='DEFAULT') -> None:
super().__init__()
self.model = models.resnet.resnet18(weights=weights)
self.model.fc = nn.Identity()
self.model.eval()
def forward(self, x: Tensor) -> Tensor:
x = F.int... |
(max_runs=3, min_passes=1)
_test(timeout=60)
def test_from_kafka():
j = random.randint(0, 10000)
ARGS = {'bootstrap.servers': 'localhost:9092', 'group.id': ('streamz-test%i' % j)}
with kafka_service() as kafka:
(kafka, TOPIC) = kafka
stream = Stream.from_kafka([TOPIC], ARGS, asynchronous=Tru... |
def pytest_namespace():
try:
import numpy as np
except ImportError:
np = None
try:
import scipy
except ImportError:
scipy = None
try:
from pybind11_tests.eigen import have_eigen
except ImportError:
have_eigen = False
pypy = (platform.python_imp... |
class GraphFactorization(object):
def __init__(self, graph, rep_size=128, epoch=120, learning_rate=0.003, weight_decay=1.0):
self.g = graph
self.node_size = graph.G.number_of_nodes()
self.rep_size = rep_size
self.max_iter = epoch
self.lr = learning_rate
self.lamb = we... |
class ReactpyAsyncWebsocketConsumer(AsyncJsonWebsocketConsumer):
async def connect(self) -> None:
from reactpy_django import models
from reactpy_django.config import REACTPY_AUTH_BACKEND, REACTPY_BACKHAUL_THREAD
(await super().connect())
user = self.scope.get('user')
if (user... |
class DTFC(nn.Module):
def __init__(self, in_channels, out_channels, num_layers, gr, kt, kf, activation):
super(DTFC, self).__init__()
assert (num_layers > 2)
self.first_conv = nn.Sequential(nn.Conv2d(in_channels=in_channels, out_channels=gr, kernel_size=(kf, kt), stride=1, padding=((kt // 2... |
class TestNot_():
DEFAULT_EXC_TYPES = (ValueError, TypeError)
def test_not_all(self):
assert (not_.__name__ in validator_module.__all__)
def test_repr(self):
wrapped = in_([3, 4, 5])
v = not_(wrapped)
assert (f'<not_ validator wrapping {wrapped!r}, capturing {v.exc_types!r}>'... |
def main():
(log_level, directory, output, ar, paths) = parse_arguments()
level = getattr(logging, log_level)
logging.basicConfig(format='%(levelname)s: %(message)s', level=level)
line_matcher = re.compile(_LINE_PATTERN)
compile_commands = []
for path in paths:
if os.path.isdir(path):
... |
def update_camera_cfgs_from_dict(camera_cfgs: Dict[(str, CameraConfig)], cfg_dict: Dict[(str, dict)]):
if cfg_dict.pop('use_stereo_depth', False):
from .depth_camera import StereoDepthCameraConfig
for (name, cfg) in camera_cfgs.items():
camera_cfgs[name] = StereoDepthCameraConfig.fromCam... |
def test_observation__flags():
obs_json = deepcopy(j_observation_v2)
obs_json['flags'] = [j_flag_1]
obs = Observation.from_json(obs_json)
flag = obs.flags[0]
assert isinstance(flag, Flag)
assert (flag.id == 123456)
assert (flag.resolved is False)
assert (flag.user.login == 'some_user')
... |
def _create_dense_predictor(args: SharedArgs, input_shape: InputShape, label_maps: Dict[(Task, LabelMap)], chunk_prediction_border: float) -> DensePredictor:
predictor_heads = _dense_predictor_heads(args, label_maps)
model = _create_keras_model(args, input_shape, predictor_heads)
return _dense_predictor(mod... |
class DocCog(commands.Cog):
def __init__(self, bot: Bot):
self.base_urls = {}
self.bot = bot
self.doc_symbols: dict[(str, DocItem)] = {}
self.item_fetcher = _batch_parser.BatchParser()
self.renamed_symbols = defaultdict(list)
self.inventory_scheduler = Scheduler(self.... |
class ModelSpecTest(tf.test.TestCase):
def test_prune_noop(self):
model1 = model_spec.ModelSpec(np.array([[0, 1, 0], [0, 0, 1], [0, 0, 0]]), [0, 0, 0])
assert model1.valid_spec
assert np.array_equal(model1.original_matrix, model1.matrix)
assert (model1.original_ops == model1.original... |
def to_bytes(something, encoding='utf8') -> bytes:
if isinstance(something, bytes):
return something
if isinstance(something, str):
return something.encode(encoding)
elif isinstance(something, bytearray):
return bytes(something)
else:
raise TypeError('Not a string or byte... |
class InviteDismissViewTest(TestCase):
def setUpTestData(cls):
add_default_data()
def login(self, name, password=None):
self.client.login(username=name, password=(password if password else name))
self.pu = PytitionUser.objects.get(user__username=name)
return self.pu
def logou... |
def gen_tutorials(repo_dir: str) -> None:
with open(os.path.join(repo_dir, 'website', 'tutorials.json'), 'r') as infile:
tutorial_config = json.loads(infile.read())
tutorial_ids = {x['id'] for v in tutorial_config.values() for x in v}
for tid in tutorial_ids:
print('Generating {} tutorial'.f... |
_module()
def orthogonal_init(module, gain=1, bias=0):
if hasattr(module, 'weight'):
nn.init.orthogonal_(module.weight, gain)
elif hasattr(module, 'kernel'):
nn.init.orthogonal_(module.kernel, gain)
if (hasattr(module, 'bias') and (module.bias is not None)):
nn.init.constant_(module.... |
def pause_splitter_tokens(tokens, split_by={':', ';', '--', '', ''}):
sents = []
sent = []
for tok in tokens:
sent += [tok]
if (tok in split_by):
if sent:
sents += [sent]
sent = []
if sent:
sents += [sent]
return sents |
def changeDirectory(path):
global currentDirectory
pathC = path.split('>')
if (pathC[0] == ''):
pathC.remove(pathC[0])
myPath = ((currentDirectory + '/') + '/'.join(pathC))
print(myPath)
try:
os.chdir(myPath)
ans = True
if (currentDirectory not in os.getcwd()):
... |
class UCCSD(VariationalForm):
def __init__(self, num_orbitals: int, num_particles: Union[(Tuple[(int, int)], List[int], int)], reps: int=1, active_occupied: Optional[List[int]]=None, active_unoccupied: Optional[List[int]]=None, initial_state: Optional[Union[(QuantumCircuit, InitialState)]]=None, qubit_mapping: str=... |
class GetFieldsTests(OptionsBaseTests):
def test_get_fields_is_immutable(self):
msg = (IMMUTABLE_WARNING % 'get_fields()')
for _ in range(2):
fields = CassandraThing._meta.get_fields()
with self.assertRaisesMessage(AttributeError, msg):
fields += ['errors'] |
class EpisodicBatchSampler(object):
def __init__(self, n_classes, n_way, n_episodes):
self.n_classes = n_classes
self.n_way = n_way
self.n_episodes = n_episodes
def __len__(self):
return self.n_episodes
def __iter__(self):
for i in range(self.n_episodes):
... |
def focal_loss_legacy(logits, targets, alpha: float, gamma: float, normalizer):
positive_label_mask = (targets == 1.0)
cross_entropy = F.binary_cross_entropy_with_logits(logits, targets.to(logits.dtype), reduction='none')
neg_logits = ((- 1.0) * logits)
modulator = torch.exp((((gamma * targets) * neg_lo... |
def check_chain_id(chain_id: ChainID, web3: Web3) -> None:
while True:
try:
current_id = web3.eth.chain_id
except requests.exceptions.ConnectionError:
raise RuntimeError('Could not reach ethereum RPC. Please check that your ethereum node is running and accessible.')
i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.