code stringlengths 281 23.7M |
|---|
_model_spec('named_tuple')
def test_single_inheritance_generic_child(model_spec):
_spec.decorator
class Parent(*model_spec.bases, Generic[T]):
a: T
_spec.decorator
class Child(Parent[int], Generic[T]):
b: str
c: T
assert_fields_types(Child[bool], {'a': int, 'b': str, 'c': boo... |
def yield_sphinx_only_markup(lines):
substs = [(':abbr:`([^`]+)`', '\\1'), (':ref:`([^`]+)`', '`\\1`_'), (':term:`([^`]+)`', '**\\1**'), (':dfn:`([^`]+)`', '**\\1**'), (':(samp|guilabel|menuselection):`([^`]+)`', '``\\2``'), (':(\\w+):`([^`]*)`', '\\1(``\\2``)'), ('\\.\\. doctest', 'code-block'), ('\\.\\. plot::', ... |
class Dependency(XodrBase):
def __init__(self, id, type):
super().__init__()
self.id = id
self.type = type
def __eq__(self, other):
if (isinstance(other, Dependency) and super().__eq__(other)):
if (self.get_attributes() == other.get_attributes()):
retu... |
class TestCustomDistanceKmeans(unittest.TestCase):
def setUp(self):
super().setUp()
pass
def test_6by2_matrix_cosine_dist(self):
matrix = np.array([[1.0, 0.0], [1.1, 0.1], [0.0, 1.0], [0.1, 1.0], [0.9, (- 0.1)], [0.0, 1.2]])
labels = custom_distance_kmeans.run_kmeans(matrix, n_cl... |
def ffmpeg_microphone_live(sampling_rate: int, chunk_length_s: float, stream_chunk_s: Optional[int]=None, stride_length_s: Optional[Union[(Tuple[(float, float)], float)]]=None, format_for_conversion: str='f32le'):
if (stream_chunk_s is not None):
chunk_s = stream_chunk_s
else:
chunk_s = chunk_le... |
def test_show_basic_with_not_installed_packages_non_decorated(tester: CommandTester, poetry: Poetry, installed: Repository) -> None:
poetry.package.add_dependency(Factory.create_dependency('cachy', '^0.1.0'))
poetry.package.add_dependency(Factory.create_dependency('pendulum', '^2.0.0'))
cachy_010 = get_pack... |
class LinUnsRes_cluster(nn.Module):
def __init__(self, channel=128, w=64, h=64, cluster_num=4):
super(LinUnsRes_cluster, self).__init__()
self.channel = channel
self.w = w
self.h = h
self.cluster_num = cluster_num
def forward(self, x):
try:
out = x.vie... |
class Literals():
def __init__(self) -> None:
self.str_literals: dict[(str, int)] = {}
self.bytes_literals: dict[(bytes, int)] = {}
self.int_literals: dict[(int, int)] = {}
self.float_literals: dict[(float, int)] = {}
self.complex_literals: dict[(complex, int)] = {}
s... |
.functions
def test_null_values(dataframe):
dataframe = dataframe.copy()
dataframe.loc[(1, 'a')] = None
dataframe.loc[(4, 'a')] = None
dataframe.loc[(3, 'cities')] = None
dataframe.loc[(3, 'Bell__Chart')] = None
dataframe.loc[(6, 'decorated-elephant')] = None
df = dataframe.data_description.... |
class MultiChoiceConstraint(ValidationConstraint):
def __init__(self, choices, error_message=None):
error_message = (error_message or _('$label should be a subset of $choice_input_values'))
super().__init__(error_message=error_message)
self._choices = choices
def choices(self):
i... |
def resp_page_1():
headers = {'X-Page': '1', 'X-Next-Page': '2', 'X-Per-Page': '1', 'X-Total-Pages': '2', 'X-Total': '2', 'Link': '< rel="next"'}
return {'method': responses.GET, 'url': ' 'json': [{'a': 'b'}], 'headers': headers, 'content_type': 'application/json', 'status': 200, 'match': helpers.MATCH_EMPTY_QU... |
def generate_setting_info(bot, domain: str) -> Tuple[(str, InlineKeyboardMarkup)]:
settings = {**dict(last_id=0, last_story_id=0, pinned_id=0, what_to_send='', header='', footer=''), **bot.config.get('settings', {}), **bot.config.get('domains', {}).get(domain, {})}
if (domain != 'global'):
text = (messa... |
def test_list_repos(initialized_db, app):
with client_with_identity('devtable', app) as cl:
params = {'starred': 'true', 'repo_kind': 'application'}
response = conduct_api_call(cl, RepositoryList, 'GET', params).json
repo_states = {r['state'] for r in response['repositories']}
for st... |
class TorchMhaWrapper(torch.nn.Module):
def __init__(self, multihead_attn, need_weights: bool=True, attn_mask: Optional[torch.Tensor]=None, average_attn_weights: bool=True):
super().__init__()
self.multihead_attn = multihead_attn
self.need_weights = need_weights
self.attn_mask = attn... |
def Add2_fun(input1, input2):
output = SparseConvNetTensor()
output.metadata = input2.metadata
output.spatial_size = input2.spatial_size
input1_features = torch.zeros(input2.features.size()).cuda()
idxs = input2.getLocationsIndexInRef(input1)
hit = (idxs != (- 1)).nonzero().view((- 1))
input... |
def test_synthesis_element():
a = np.random.random((5, 5))
b = np.random.random((4, 4))
c = np.random.random((3, 3))
at = Tensor(tensor=a, name='a')
bt = Tensor(tensor=b, name='b')
ct = Tensor(tensor=c, name='c')
mt = MultiTensor([at, bt, ct])
dbe = DualBasisElement()
dbe.add_element... |
class MyApplication(tornado.web.Application):
class MainPage(tornado.web.RequestHandler):
def get(self):
manager = self.application.manager
ws_uri = 'ws://{req.host}/'.format(req=self.request)
content = (html_content % {'ws_uri': ws_uri, 'fig_id': manager.num})
... |
class TestEnumeratorMatchCombinations(object):
(_CONTEXT_STRATEGY, _SUBSYSTEM_STRATEGY, _SYSNAME_STRATEGY, _MATCH_PROPERTY_STRATEGY)
(max_examples=10)
def test_match(self, context, subsystem, sysname, ppair):
(prop_name, prop_value) = ppair
kwargs = {prop_name: prop_value}
devices = ... |
def calculate_prototypes(model, data_loader, logger, epochs):
dev = torch.device(model.output_device)
loader_indices = data_loader.batch_sampler
class_features = ClassFeatures(numbers=model.module.num_classes, dev=dev)
for epoch in range(epochs):
logger.info(f'Calculating the prototypes on Epoch... |
def build_custom_activation(name='relu', **kwargs):
if (name == 'relu'):
return nn.ReLU(inplace=True)
elif (name == 'silu'):
return SiLU()
elif (name == 'soft_exp'):
alpha = kwargs.get('alpha', 0)
return soft_exponential(alpha)
elif (name == 'brelu'):
raise NotImp... |
class Spiral(_SimpleLayoutBase):
split_ratio: float
defaults = [('border_focus', '#0000ff', 'Border colour(s) for the focused window.'), ('border_normal', '#000000', 'Border colour(s) for un-focused windows.'), ('border_width', 1, 'Border width.'), ('margin', 0, 'Margin of the layout (int or list of ints [N E S... |
def correct_address(cls, sentence, max_length_address=True):
max_seq_list = []
keys = cls.max_match_cut(sentence)
all_ = key_to_address(cls, keys)
filter_address = dict(map(max_key_filter(keys), all_))
if filter_address:
sort_address = list(sorted(filter_address.items(), key=(lambda x: x[1])... |
def _init_default_profile():
global default_profile
if machinery.IS_QT6:
default_profile = QWebEngineProfile('Default')
else:
default_profile = QWebEngineProfile.defaultProfile()
assert (not default_profile.isOffTheRecord())
assert (parsed_user_agent is None)
non_ua_version = ver... |
class Reached():
def __init__(self, left, right, left_id, right_id, spatial_weights=None, mode='count', values=None, verbose=True):
self.left = left
self.right = right
self.sw = spatial_weights
self.mode = mode
results_list = []
if (not isinstance(right_id, str)):
... |
def unfold1d(x, kernel_size, padding_l, pad_value=0):
if (kernel_size > 1):
(T, B, C) = x.size()
x = F.pad(x, (0, 0, 0, 0, padding_l, ((kernel_size - 1) - padding_l)), value=pad_value)
x = x.as_strided((T, B, C, kernel_size), ((B * C), C, 1, (B * C)))
else:
x = x.unsqueeze(3)
... |
class GraphNetBlock(nn.Module):
def __init__(self, model_fn, output_size, message_passing_aggregator, attention=False):
super().__init__()
self.mesh_edge_model = model_fn(output_size)
self.world_edge_model = model_fn(output_size)
self.node_model = model_fn(output_size)
self.a... |
def test_connect_rd_x_conn_As_wr_y_conn_no_driver():
class Top(ComponentLevel3):
def construct(s):
s.x = Wire(Bits24)
s.A = Wire(Bits32)
s.y = Wire(Bits4)
connect(s.A[8:32], s.x)
connect(s.A[0:4], s.y)
def up_rd_x():
ass... |
class Effect5865(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredChargeBoost((lambda mod: mod.charge.requiresSkill('Missile Launcher Operation')), 'explosiveDamage', ship.getModifiedItemAttr('shipBonusCB'), skill='Caldari Battleship', **kwarg... |
.parametrize('args', [{'h_labels': ['H0', 'H0+Hint']}, {'energy_levels': [(- 2), 0, 2]}])
def test_plot_energy_levels(args):
H0 = (qutip.tensor(qutip.sigmaz(), qutip.identity(2)) + qutip.tensor(qutip.identity(2), qutip.sigmaz()))
Hint = (0.1 * qutip.tensor(qutip.sigmax(), qutip.sigmax()))
(fig, ax) = qutip.... |
(params=['with-subclasses', 'with-subclasses-and-tagged-union', 'wo-subclasses'])
def conv_w_subclasses(request):
c = Converter()
if (request.param == 'with-subclasses'):
include_subclasses(Parent, c)
include_subclasses(CircularA, c)
elif (request.param == 'with-subclasses-and-tagged-union')... |
def compute_prf1_single_type(fname, type_, data=None):
print(((' ' + type_) + ' '))
with open(fname) as f:
total = json.load(f)
gold_binary = []
pred_binary = []
for (k, v) in total.items():
if (type_ in v['gold']):
gold_binary.append(1.0)
else:
gold_b... |
def on_pic_button_clicked():
if (pic_tab.preview_check.isChecked() and rec_button.isEnabled()):
switch_config('still')
picam2.capture_request(signal_function=qpicamera2.signal_done)
else:
picam2.capture_request(signal_function=qpicamera2.signal_done)
rec_button.setEnabled(False)
... |
def _create_retry_decorator(llm: ChatOpenAI) -> Callable[([Any], Any)]:
import openai
min_seconds = 1
max_seconds = 60
return retry(reraise=True, stop=stop_after_attempt(llm.max_retries), wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds), retry=((((retry_if_exception_type(openai.erro... |
def get_display_names(county: Dict) -> Tuple:
admin_division = ' County'
county_name = county['county_name']
if (county['state_abbr'] == 'PR'):
return (f"{county['county_name']}, PR", f"{county['county_name']}, Puerto Rico", f"{county['county_name']}")
if (county['state_abbr'] == 'AS'):
... |
class DatasetFolder(data.Dataset):
def __init__(self, root, loader, extensions, transform=None, target_transform=None, label_mapping=None):
(classes, class_to_idx) = self._find_classes(root)
if (label_mapping is not None):
(classes, class_to_idx) = label_mapping(classes, class_to_idx)
... |
class ModuleAdapter(SerializableModule):
def __init__(self, f):
super(ModuleAdapter, self).__init__()
self.f = f
def __call__(self, *args, **kwargs):
return self.forward(*args, **kwargs)
def forward(self, *args, **kwargs):
f = self.f
return f(*args, **kwargs) |
def test_get_upward_paths(graph_nodes, test_instance, subgraph_root=None):
graph_nodes_list = list(graph_nodes)
num_tested = 0
while (num_tested < 10):
start_node = np.random.choice(graph_nodes_list)
if (not start_node.parents):
continue
paths = imagenet_spec.get_upward_p... |
class PreActBottleneck(nn.Module):
def __init__(self, in_chs, out_chs=None, bottle_ratio=0.25, stride=1, dilation=1, first_dilation=None, groups=1, act_layer=None, conv_layer=None, norm_layer=None, proj_layer=None, drop_path_rate=0.0):
super().__init__()
first_dilation = (first_dilation or dilation)... |
def predict_entry_point_modelfolder():
import argparse
parser = argparse.ArgumentParser(description='Use this to run inference with nnU-Net. This function is used when you want to manually specify a folder containing a trained nnU-Net my_models. This is useful when the nnunet environment variables (nnUNet_resul... |
def _add_lonlat_coords(data_arr: xr.DataArray) -> xr.DataArray:
data_arr = data_arr.copy()
area = data_arr.attrs['area']
ignore_dims = {dim: 0 for dim in data_arr.dims if (dim not in ['x', 'y'])}
chunks = getattr(data_arr.isel(**ignore_dims), 'chunks', None)
(lons, lats) = area.get_lonlats(chunks=ch... |
def change_release_description(release, filename, description):
assets = [asset for asset in release.assets() if (asset.name == filename)]
if (not assets):
raise Error(f'No assets found for {filename}')
if (len(assets) > 1):
raise Error(f'Multiple assets found for {filename}: {assets}')
... |
def pad_tensor(input, divide=16):
shape = input.get_shape().as_list()
height = shape[1]
width = shape[2]
if (((width % divide) != 0) or ((height % divide) != 0)):
width_res = (width % divide)
height_res = (height % divide)
if (width_res != 0):
width_div = (divide - wi... |
def net_test(args, cfg):
AAF = importlib.import_module('.{}'.format(args.model.name.lower()), package='Model_zoo')
torch.backends.cudnn.benchmark = True
device = torch.device('cuda')
print('> Build model')
SRmodel = AAF.create_model(args.training)
pretrained_model = os.path.join(args.ckp.save_ro... |
class Policy(nn.Module):
def __init__(self):
super(Policy, self).__init__()
self.affine1 = nn.Linear(4, 128)
self.action_head = nn.Linear(128, 2)
self.value_head = nn.Linear(128, 1)
self.saved_actions = []
self.rewards = []
def forward(self, x):
x = F.relu... |
class RepeatAugSampler(Sampler):
def __init__(self, dataset, num_replicas=None, rank=None, shuffle=True, num_repeats=3, selected_round=256, selected_ratio=0):
if (num_replicas is None):
if (not dist.is_available()):
raise RuntimeError('Requires distributed package to be available... |
class RawSection(sections.Section):
def __init__(self, handler, **kwargs):
sections.Section.__init__(self, handler, **kwargs)
self.handler.raw = ''
self.sectionOpen = '%raw'
def handleLine(self, line):
if (not self.handler):
return
self.handler.raw += line |
def get_datasets(data_params):
train_transform = transforms.Augmentation(data_params['data_augmentation']['aug_together'], data_params['data_augmentation']['aug_pc2'], data_params['data_process'], data_params['num_points'])
test_transform = transforms.ProcessData(data_params['data_process'], data_params['data_a... |
class AcceptFileDragDrop():
def __init__(self, file_type=''):
assert isinstance(self, QWidget)
self.setAcceptDrops(True)
self.file_type = file_type
def validateEvent(self, event):
if (not event.mimeData().hasUrls()):
event.ignore()
return False
for... |
class CheckBoxDemo(ttk.LabelFrame):
def __init__(self, parent):
super().__init__(parent, text='Checkbuttons', padding=15)
self.var_1 = tkinter.BooleanVar(self, False)
self.var_2 = tkinter.BooleanVar(self, True)
self.add_widgets()
def add_widgets(self):
self.checkbox_1 = t... |
class MyMAEScorer(object):
def __init__(self, test_data, test_labels):
self.test_data = test_data
self.test_labels = test_labels
def __call__(self, base_estimator, params, X, y, sample_weight=None):
cl = clone(base_estimator)
cl.set_params(**params)
cl.fit(X, y)
r... |
class SegformerDecodeHead(SegformerPreTrainedModel):
def __init__(self, config):
super().__init__(config)
mlps = []
for i in range(config.num_encoder_blocks):
mlp = SegformerMLP(config, input_dim=config.hidden_sizes[i])
mlps.append(mlp)
self.linear_c = nn.Modu... |
def compute_dense_reward(self, action, obs) -> float:
distance_to_handle = np.linalg.norm((self.robot.ee_position - self.obj1.position))
distance_to_goal = np.linalg.norm((self.obj1.position - self.goal_position))
reach_reward = (- distance_to_handle)
push_reward = (- distance_to_goal)
gripper_rewar... |
class LogHelper():
def __init__(self, funcs_to_call: typing.List[typing.Callable[([typing.Mapping[(str, typing.Any)]], None)]]):
self.funcs_to_call = funcs_to_call
def should_run_collect_extra_statistics(self):
return bool(len(self.funcs_to_call))
def add_statistics(self, statistics: dict):
... |
def _to_range(workflow_range: str) -> Tuple[(int, int)]:
workflow_range = workflow_range.split('-')
workflow_range = [s for s in workflow_range if s]
if (len(workflow_range) != 2):
logger.error("Workflow range is incorrect. Correct format: 'number-number', e.g '100-200'.")
exit(1)
return... |
def test_arb_loader():
loader_cache.clear()
pipeline = Pipeline('arb pipe', context_args='arb context input', loader='arbpack.arbloader', py_dir='tests')
pipeline.load_and_run_pipeline(Context(), parent='/arb/dir')
loader = loader_cache.get_pype_loader('arbpack.arbloader')
assert (loader.name == 'ar... |
def test_select_column_using_expression_in_parenthesis():
sql = 'INSERT INTO tab1\nSELECT (col1 + col2)\nFROM tab2'
assert_column_lineage_equal(sql, [(ColumnQualifierTuple('col1', 'tab2'), ColumnQualifierTuple('(col1 + col2)', 'tab1')), (ColumnQualifierTuple('col2', 'tab2'), ColumnQualifierTuple('(col1 + col2)'... |
class Solution(object):
def threeSum(self, nums):
res = []
nums.sort()
ls = len(nums)
for i in range((ls - 2)):
if ((i > 0) and (nums[i] == nums[(i - 1)])):
continue
j = (i + 1)
k = (ls - 1)
while (j < k):
... |
('/v1/repository/<apirepopath:repository>/tag/<tag>')
_param('repository', 'The full path of the repository. e.g. namespace/name')
_param('tag', 'The name of the tag')
class RepositoryTag(RepositoryParamResource):
schemas = {'ChangeTag': {'type': 'object', 'description': 'Makes changes to a specific tag', 'properti... |
def _create_trading_session(init_risk: float):
start_date = str_to_date('2016-01-01')
end_date = str_to_date('2017-12-31')
session_builder = container.resolve(BacktestTradingSessionBuilder)
session_builder.set_data_provider(daily_data_provider)
session_builder.set_position_sizer(InitialRiskPositionS... |
class HgBEVBackbone(nn.Module):
def __init__(self, model_cfg, input_channels):
super().__init__()
self.model_cfg = model_cfg
self.num_channels = model_cfg.num_channels
self.GN = model_cfg.GN
self.rpn3d_conv2 = nn.Sequential(convbn(input_channels, self.num_channels, 3, 1, 1, 1... |
class TimeTest(unittest.TestCase):
def cmp_times(self, time1, time2):
if (type(time1) is str):
time1 = Time.stringtotime(time1)
self.assertIsNotNone(time1)
if (type(time2) is str):
time2 = Time.stringtotime(time2)
self.assertIsNotNone(time2)
if... |
class SelectionInputWidget(Container):
datalist = None
selection_input = None
_attribute_decorator('WidgetSpecific', 'Defines the actual value for the widget.', str, {})
def attr_value(self):
return self.selection_input.attr_value
_value.setter
def attr_value(self, value):
self.s... |
class EnG2p(G2p):
word_tokenize = TweetTokenizer().tokenize
def __call__(self, text):
words = EnG2p.word_tokenize(text)
tokens = pos_tag(words)
prons = []
for (word, pos) in tokens:
if (re.search('[a-z]', word) is None):
pron = [word]
elif ... |
def handler(request, operation, current_url):
if (operation != QNetworkAccessManager.Operation.GetOperation):
return networkreply.ErrorNetworkReply(request, 'Unsupported request type', QNetworkReply.NetworkError.ContentOperationNotPermittedError)
url = request.url()
if ((url.scheme(), url.host(), ur... |
_task
def send_transmissions(backend_id, message_id, transmission_ids):
from rapidsms.models import Backend
from rapidsms.router import get_router
from rapidsms.router.db.models import Message, Transmission
backend = Backend.objects.get(pk=backend_id)
dbm = Message.objects.select_related('in_respons... |
class AdminNoCaching():
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
if request.path.startswith('/admin'):
response['Cache-Control'] = 'private'
return response |
class DeepGuidedFilterAdvanced(DeepGuidedFilter):
def __init__(self, radius=1, eps=0.0001):
super(DeepGuidedFilterAdvanced, self).__init__(radius, eps)
self.guided_map = nn.Sequential(nn.Conv2d(3, 15, 1, bias=False), AdaptiveNorm(15), nn.LeakyReLU(0.2, inplace=True), nn.Conv2d(15, 3, 1))
sel... |
def tx_from_any(raw: Union[(str, bytes)], *, deserialize: bool=True) -> Union[('PartialTransaction', 'Transaction')]:
if isinstance(raw, bytearray):
raw = bytes(raw)
raw = convert_raw_tx_to_hex(raw)
try:
return PartialTransaction.from_raw_psbt(raw)
except BadHeaderMagic:
if (raw[... |
def normal_loss(output_normals, target_normals, nearest_idx, weight=1.0, phase='train'):
nearest_idx = nearest_idx.expand(3, (- 1), (- 1)).permute([1, 2, 0]).long()
target_normals_chosen = torch.gather(target_normals, dim=1, index=nearest_idx)
assert (output_normals.shape == target_normals_chosen.shape)
... |
class TASFIssue29(TestCase):
original = os.path.join(DATA_DIR, 'issue_29.wma')
def setUp(self):
self.filename = get_temp_copy(self.original)
self.audio = ASF(self.filename)
def tearDown(self):
os.unlink(self.filename)
def test_pprint(self):
self.audio.pprint()
def tes... |
def extract_python(fileobj: IO[bytes], keywords: Mapping[(str, _Keyword)], comment_tags: Collection[str], options: _PyOptions) -> Generator[(_ExtractionResult, None, None)]:
funcname = lineno = message_lineno = None
call_stack = (- 1)
buf = []
messages = []
translator_comments = []
in_def = in_t... |
class OSBlock(nn.Module):
def __init__(self, in_channels, out_channels, bn_norm, IN=False, bottleneck_reduction=4, **kwargs):
super(OSBlock, self).__init__()
mid_channels = (out_channels // bottleneck_reduction)
self.conv1 = Conv1x1(in_channels, mid_channels, bn_norm)
self.conv2a = L... |
class Demo(data.Dataset):
def __init__(self, args, name='Demo', train=False, benchmark=False):
self.args = args
self.name = name
self.scale = args.scale
self.idx_scale = 0
self.train = False
self.benchmark = benchmark
self.filelist = []
for f in os.lis... |
class Effect6508(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Capital Repair Systems')), 'duration', src.getModifiedItemAttr('shipBonusDreadnoughtG3'), skill='Gallente Dreadnought', **kwargs) |
.parametrize('valid', [False, True])
def test_on_permalink_changed(skip_qtbot, mocker, valid):
mock_from_str: MagicMock = mocker.patch('randovania.layout.permalink.Permalink.from_str')
mock_from_str.return_value.as_base64_str = ''
if (not valid):
mock_from_str.side_effect = ValueError('Invalid perma... |
class LassoLexer(RegexLexer):
name = 'Lasso'
aliases = ['lasso', 'lassoscript']
filenames = ['*.lasso', '*.lasso[89]']
version_added = '1.6'
alias_filenames = ['*.incl', '*.inc', '*.las']
mimetypes = ['text/x-lasso']
url = '
flags = ((re.IGNORECASE | re.DOTALL) | re.MULTILINE)
tokens... |
class KnownValues(unittest.TestCase):
def test_ccsd(self):
mycc = cc.CCSD(mf)
ecc = mycc.kernel()[0]
norb = mf.mo_coeff.shape[1]
nelec = mol.nelec
h2e = ao2mo.restore(1, ao2mo.kernel(mf._eri, mf.mo_coeff), norb)
h1e = reduce(numpy.dot, (mf.mo_coeff.T, mf.get_hcore(), ... |
def main(json_files, merged_filename='', pretty_print_json=True):
if (not json_files):
print('No JSON files were found.')
return ''
json_files = list(set(json_files))
try:
if (not merged_filename):
now = time.localtime()
timestamp = time.strftime('%Y%m%d_%H%M%... |
class ResNet(torch.nn.Module):
def __init__(self, net_name, pretrained=False, use_fc=False):
super().__init__()
base_model = models.__dict__[net_name](pretrained=pretrained)
self.encoder = torch.nn.Sequential(*list(base_model.children())[:(- 1)])
self.use_fc = use_fc
if self.... |
class TestMockConfig():
SOME_VERBOSITY_LEVEL = 3
SOME_OTHER_VERBOSITY_LEVEL = 10
def test_verbose_exposes_value(self):
config = mock_config(verbose=TestMockConfig.SOME_VERBOSITY_LEVEL)
assert (config.get_verbosity() == TestMockConfig.SOME_VERBOSITY_LEVEL)
def test_get_assertion_override_... |
(repr=False, eq=False)
class Processed(SignedRetrieableMessage):
cmdid: ClassVar[CmdId] = CmdId.PROCESSED
message_identifier: MessageID
def from_event(cls, event: SendMessageEvent) -> 'Processed':
return cls(message_identifier=event.message_identifier, signature=EMPTY_SIGNATURE)
def _data_to_sig... |
class SingleConv(nn.Module):
def __init__(self, in_ch, out_ch, kernel_size=[3, 3, 3], stride=1, norm=nn.BatchNorm3d, act=nn.ReLU, preact=False):
super().__init__()
assert (norm in [nn.BatchNorm3d, nn.InstanceNorm3d, LayerNorm, True, False])
assert (act in [nn.ReLU, nn.ReLU6, nn.GELU, nn.SiLU... |
class BaseOptions():
def __init__(self):
self.parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
self.initialized = False
def initialize(self):
self.parser.add_argument('--dataroot', required=True, help='path to meshes (should have subfolders train, ... |
class Effect4934(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Repair Systems')), 'armorDamageAmount', ship.getModifiedItemAttr('shipBonusGF2'), skill='Gallente Frigate', **kwargs) |
def without_low_degree_nodes(G, minimum=1, eligible=None):
def low_degree(G, threshold):
if (eligible is None):
return [n for (n, d) in G.degree() if (d < threshold)]
return [n for (n, d) in G.degree() if ((d < threshold) and G.nodes[n][eligible])]
to_remove = low_degree(G, minimum)
... |
def extract_sum(article_file, results_our, results_pacsum, outdir, rerank):
articles = doc2sents(article_file, False)
our_scores = results_our['Score']
pacsum_scores = results_pacsum['Score']
assert (len(pacsum_scores) == len(our_scores))
for lam1 in range(11):
lam1 = (lam1 / 10.0)
w... |
def _collect_gradients(gradients, variables):
ops = []
for (grad, var) in zip(gradients, variables):
if isinstance(grad, tf.Tensor):
ops.append(tf.assign_add(var, grad))
else:
ops.append(tf.scatter_add(var, grad.indices, grad.values))
return tf.group(*ops, name='colle... |
class TestFindFilesAndReaders():
def setup_method(self):
from satpy.readers.viirs_sdr import VIIRSSDRFileHandler
from satpy.tests.reader_tests.test_viirs_sdr import FakeHDF5FileHandler2
self.p = mock.patch.object(VIIRSSDRFileHandler, '__bases__', (FakeHDF5FileHandler2,))
self.fake_ha... |
def test_emit_warning_when_event_loop_is_explicitly_requested_in_coroutine_fixture(pytester: Pytester):
pytester.makepyfile(dedent(' import pytest\n import pytest_asyncio\n\n _asyncio.fixture\n async def emits_warning(event_loop):\n pass\n\n .asy... |
def flatten_dict(d):
flat_params = dict()
for (k, v) in d.items():
if isinstance(v, dict):
v = flatten_dict(v)
for (subk, subv) in flatten_dict(v).items():
flat_params[((k + '.') + subk)] = subv
else:
flat_params[k] = v
return flat_params |
def RSU7(x, mid_ch=12, out_ch=3):
x0 = REBNCONV(x, out_ch, 1)
x1 = REBNCONV(x0, mid_ch, 1)
x = MaxPool2D(2, 2)(x1)
x2 = REBNCONV(x, mid_ch, 1)
x = MaxPool2D(2, 2)(x2)
x3 = REBNCONV(x, mid_ch, 1)
x = MaxPool2D(2, 2)(x3)
x4 = REBNCONV(x, mid_ch, 1)
x = MaxPool2D(2, 2)(x4)
x5 = REBN... |
def backwardbig(trainingset, unitaries, qnnarch):
n = len(trainingset)
L = len(unitaries)
layerunits = layerunitaries(unitaries)
chi = []
chim = [tensoredId(qnnarch[0])]
for x in range((n - 1), 0, (- 1)):
chix = [qt.tensor(chim[(- 1)], qt.ket2dm(trainingset[x][1]))]
for l in rang... |
def energy_from_params(gamma_value: float, beta_value: float, qaoa: cirq.Circuit, h: np.ndarray) -> float:
sim = cirq.Simulator()
params = cirq.ParamResolver({'': gamma_value, '': beta_value})
wf = sim.simulate(qaoa, param_resolver=params).final_state_vector
return energy_from_wavefunction(wf, h) |
def _run_purerpc_service_in_process(service, ssl_context=None):
def target_fn():
import purerpc
import socket
with socket.socket() as sock:
sock.bind(('127.0.0.1', 0))
port = sock.getsockname()[1]
server = purerpc.Server(port=port, ssl_context=ssl_context)
... |
((enum is None), 'enum is not available')
class TestEnumsAsStates(TestCase):
def setUp(self):
class States(enum.Enum):
RED = 1
YELLOW = 2
GREEN = 3
self.machine_cls = Machine
self.States = States
def test_pass_enums_as_states(self):
m = self.ma... |
class TestImportModeImportlib():
def test_collect_duplicate_names(self, pytester: Pytester) -> None:
pytester.makepyfile(**{'tests_a/test_foo.py': 'def test_foo1(): pass', 'tests_b/test_foo.py': 'def test_foo2(): pass'})
result = pytester.runpytest('-v', '--import-mode=importlib')
result.std... |
class MeanActivationFusion(nn.Module):
def __init__(self, features=64, feature_extractor=Features4Layer, activation=relu):
super(MeanActivationFusion, self).__init__()
self.features = feature_extractor(features, activation=activation)
def forward(self, frame_1, frame_2, frame_3, frame_4, frame_5... |
class FastDataLoader():
def __init__(self, dataset, batch_size, num_workers, shuffle=False):
super().__init__()
if shuffle:
sampler = torch.utils.data.RandomSampler(dataset, replacement=False)
else:
sampler = torch.utils.data.SequentialSampler(dataset)
batch_s... |
_test()
def test_accumulate_errors_log():
a = Stream(asynchronous=True)
b = a.delay(0.001).accumulate((lambda x, y: (x / y)), with_state=True)
with captured_logger('streamz') as logger:
a._emit(1)
a._emit(0)
(yield gen.sleep(0.1))
out = logger.getvalue()
assert ('Zero... |
def test_deterministic():
pvs = OSC.ParameterValueSet()
pvs.add_parameter('myparam1', '1')
dr = OSC.DistributionRange(1, OSC.Range(0, 3))
dist = OSC.DeterministicMultiParameterDistribution()
dist.add_value_set(pvs)
det = OSC.Deterministic()
det.add_multi_distribution(dist)
det.add_single... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.