我刚刚为 Python编写了一个简单的@autowired装饰器,它根据类型注释实例化类。
为了启用类的延迟初始化,包提供了一个lazy(type_annotation: (Type, str))函数,以便调用者可以像这样使用它:
@autowired
def foo(bla, *, dep: lazy(MyClass)):
...
Run Code Online (Sandbox Code Playgroud)
这工作得很好,在幕后这个lazy函数只是返回一个函数,该函数返回实际类型并且将lazy_init属性设置为True。也这并没有打破的IDE(例如,PyCharm)代码完成功能。
Lazy类型 use 而不是lazy函数的使用。像这样:
@autowired
def foo(bla, *, dep: Lazy[MyClass]):
...
Run Code Online (Sandbox Code Playgroud)
这会表现得非常像Typing.Union。而当我能够实现标化的类型,Ides的代码完成功能将形同虚设,因为它会出现在为属性的建议Lazy类,而不是MyClass。
我一直在使用此代码:
class LazyMetaclass(type):
def __getitem__(lazy_type, type_annotation):
return lazy_type(type_annotation)
class Lazy(metaclass=LazyMetaclass):
def __init__(self, type_annotation):
self.type_annotation = type_annotation
Run Code Online (Sandbox Code Playgroud)
我尝试重新定义Lazy.__dict__为转发到下标类型的属性,__dict__但这似乎对 PyCharm 的代码完成功能没有影响。
我坚信我想要实现的目标是可能的,因为Typing.Union可以很好地与 IDE 的代码完成配合使用。我一直试图破译 …
拥有一个异步生成器,我希望能够异步迭代它。但是,我遗漏了一些东西或搞砸了一些东西或两者兼而有之,因为我最终得到了一个常规的同步 for 循环:
import asyncio
async def time_consuming(t):
print(f"Going to sleep for {t} seconds")
await asyncio.sleep(t)
print(f"Slept {t} seconds")
return t
async def generator():
for i in range(4, 0, -1):
yield await time_consuming(i)
async def consumer():
async for t in generator():
print(f"Doing something with {t}")
if __name__ == '__main__':
loop = asyncio.new_event_loop()
loop.run_until_complete(consumer())
loop.close()
Run Code Online (Sandbox Code Playgroud)
这将需要大约 12 秒来运行并返回:
Going to sleep for 4 seconds
Slept 4 seconds
Doing something with 4
Going to sleep for 3 seconds
Slept 3 seconds
Doing …Run Code Online (Sandbox Code Playgroud) 我需要找到一种绘制1000x1000正方形网格的方法,每个正方形都是可点击的,它们必须是独立的颜色可变的.喜欢地雷游戏.我可以使用HTML(纯或使用Canvas或SVG),CSS和JavaScript.
我知道如何使用JavaScript和CSS创建一个具有这些特征的网格,它适用于10x10正方形,100x100正方形将变成高矩形并加载1000x1000,但"正方形"压缩太大,边界相互接触并呈现一个完整的灰色页面.
我尝试使用HTML和JavaScript绘制SVG正方形,正方形的大小问题解决了,但我不知道如何使它们在点击时改变颜色,当我设置加载1000x1000正方形时,它将冻结浏览并最终崩溃选项卡.
这有可行吗?
对不起,如果我不清楚,但是,我需要滚动条.对我来说没问题.
你可以看到我在这里描述的两个试验:
JavaScript和CSS
var lastClicked;
var grid = clickableGrid(100,100,function(el,row,col,i){
console.log("You clicked on element:",el);
console.log("You clicked on row:",row);
console.log("You clicked on col:",col);
console.log("You clicked on item #:",i);
el.className='clicked';
if (lastClicked) lastClicked.className='';
lastClicked = el;
});
document.body.appendChild(grid);
function clickableGrid( rows, cols, callback ){
var i=0;
var grid = document.createElement('table');
grid.className = 'grid';
for (var r=0;r<rows;++r){
var tr = grid.appendChild(document.createElement('tr'));
for (var c=0;c<cols;++c){
var cell = tr.appendChild(document.createElement('td'));
++i;
cell.addEventListener('click',(function(el,r,c,i){
return function(){
callback(el,r,c,i);
}
})(cell,r,c,i),false);
}
}
return grid; …Run Code Online (Sandbox Code Playgroud)在有关 Context Vars 的 Python 文档中,描述了 Context::run 方法以启用在上下文中执行可调用对象的更改,以便可调用对象对上下文执行的更改包含在复制的上下文中。如果你需要执行协程怎么办?为了实现相同的行为,你应该怎么做?
就我而言,我想要的是这样的东西来处理可能嵌套事务的事务上下文:
my_ctxvar = ContextVar("my_ctxvar")
async def coro(func, transaction):
token = my_ctxvar.set(transaction)
r = await func()
my_ctxvar.reset(token) # no real need for this, but why not either
return r
async def foo():
ctx = copy_context()
# simplification to one case here: let's use the current transaction if there is one
if tx_owner := my_ctxvar not in ctx:
tx = await create_transaction()
else:
tx = my_ctxvar.get()
try:
r = await ctx.run(coro) # not …Run Code Online (Sandbox Code Playgroud) python coroutine async-await python-asyncio python-contextvars
I am new to C/C++, I already know the basics and I am starting to learn more advanced concepts now.
Currently I am developing a project using C++ and it is quite a big one, so structuring my project will be better.
From what I have already seen, a good structure relies on, at least, to folders: /src and /include. All .cpp files should go in /src folder and .hpp ones in /include. Here the first doubt arose: …
我决定并行化我写的一个巨大的程序,最后我遇到了新的C++ 11智能指针.
我有一个例程,应该执行多次(通常超过1000次),这有点贵.它是在一个简单的for循环中运行的,我所做的是在一个方法中安装这个for循环,该方法将由一些工作线程运行.
是这样做的,做了一些参数包裹std::shared_ptr,关注竞争条件,一切似乎都很好.
但现在,有些时候,进程将被中止,我会收到以下错误之一:
进程以退出代码139结束(由信号11中断:SIGSEGV)
要么
malloc.c:2395:sysmalloc:断言`(old_top == initial_top(av)&& old_size == 0)|| ((unsigned long)(old_size)> = MINSIZE && prev_inuse(old_top)&&((unsigned long)old_end&(pagesize - 1))== 0)'失败.
并行for正在进行时发生所有这些错误; 不是之前,不是一开始,不是最后,而是介于两者之间,这让我闻起来像一个未被覆盖的竞争条件.
该程序是巨大的,但我创建了一个能够重现问题的缩影:
#include <iostream>
#include <vector>
#include <unordered_map>
#include <thread>
#include <set>
#include <memory>
#include <atomic>
namespace std {
template <>
struct hash<std::multiset<unsigned long>>
{
std::size_t operator()(const std::multiset<unsigned long>& k) const
{
std::size_t r = 0;
bool shift = false;
for (auto&& it : k) {
r = (r >> !shift) ^ (std::hash<unsigned long>()(it) …Run Code Online (Sandbox Code Playgroud) python ×3
c++ ×2
async-await ×1
asynchronous ×1
c++11 ×1
coroutine ×1
css ×1
for-loop ×1
g++ ×1
html ×1
javascript ×1
loops ×1
shared-ptr ×1
type-hinting ×1