我有一个Enum
这样的:
from enum import Enum
class Animal(Enum):
cat = 'meow'
dog = 'woof'
never_heard_of = None
def talk(self):
print(self.value)
Run Code Online (Sandbox Code Playgroud)
我想覆盖该__call__
方法,以便像Animal('hee-haw')
返回Animals.never_heard_of
或None
而不是 raise 之类的调用 ValueError
。我宁愿避免try
每次调用Animal
.
什么是纯 Python 等价物Enum.__call__
?
我有这样的2 numpy矩阵。
矩阵1
arr1 =
array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 1., 0.]])
Run Code Online (Sandbox Code Playgroud)
矩阵2
arr2 =
array([[ 0., 0., 0.],
[ 0., 0., 1.],
[ 0., 0., 0.]])
Run Code Online (Sandbox Code Playgroud)
我想找到这些矩阵的相似性。我认为xor
可以在矩阵上使用。Xor操作应显示出值之间的差异,然后我可以对值1进行计数以计算相似性百分比。我不知道如何xor
在python中使用。
该代码不起作用:a = arr1 xor arr2
。
我遇到的问题以前从未发生过,也许某些规则已更改。
Traceback (most recent call last)
<ipython-input-3-f47687e192a7> in <module>()
5 n_examples = X.shape[0]
6 n_train = n_examples * 0.5
----> 7 train_idx = np.random.choice(range(0,n_examples), size=n_train, replace=False)
8 test_idx = list(set(range(0,n_examples))-set(train_idx))
9 X_train = X[train_idx]
mtrand.pyx in mtrand.RandomState.choice (numpy/random/mtrand/mtrand.c:18822)()
TypeError: 'float' object cannot be interpreted as an index
Run Code Online (Sandbox Code Playgroud) 我编写下面的代码来测试 numba 的缓存功能
import numba
import numpy as np
import time
@numba.njit(cache=True)
def sum2d(arr):
M, N = arr.shape
result = 0.0
for i in range(M):
for j in range(N):
result += arr[i,j]
return result
a=np.random.random((1000,100))
print(time.time())
sum2d(a)
print(time.time())
print(time.time())
sum2d(a)
print(time.time())
Run Code Online (Sandbox Code Playgroud)
虽然pycache文件夹中生成了一些缓存文件,但时间总是相同的
1576855294.8787484
1576855295.5378428
1576855295.5378428
1576855295.5388253
Run Code Online (Sandbox Code Playgroud)
无论我运行这个脚本多少次,这意味着第一次运行sum2d
需要更多的时间来编译。那么pycache文件夹中的缓存文件有什么用呢?
我需要在简单连接(并且大部分时间是凸的)的域上计算许多 2D 集成。我正在使用 python 函数scipy.integrate.nquad
来做这个集成。但是,与矩形域上的积分相比,此操作所需的时间要长得多。有没有可能更快的实现?
这是一个例子;我首先在圆形域(使用函数内部的约束)上集成常数函数,然后在矩形域(nquad
函数的默认域)上集成。
from scipy import integrate
import time
def circular(x,y,a):
if x**2 + y**2 < a**2/4:
return 1
else:
return 0
def rectangular(x,y,a):
return 1
a = 4
start = time.time()
result = integrate.nquad(circular, [[-a/2, a/2],[-a/2, a/2]], args=(a,))
now = time.time()
print(now-start)
start = time.time()
result = integrate.nquad(rectangular, [[-a/2, a/2],[-a/2, a/2]], args=(a,))
now = time.time()
print(now-start)
Run Code Online (Sandbox Code Playgroud)
矩形域只需0.00029
几秒钟,而圆形域则需要2.07061
几秒钟才能完成。
此外,循环积分给出以下警告:
IntegrationWarning: The maximum number of subdivisions (50) has been achieved. …
Run Code Online (Sandbox Code Playgroud) 当我做:
def create_funcs():
return (lambda: i for i in range(5))
for f in create_funcs():
print(f())
Run Code Online (Sandbox Code Playgroud)
我得到了预期的:
1
2
3
4
Run Code Online (Sandbox Code Playgroud)
但当我这样做时:
def create_funcs():
return [lambda: i for i in range(5)]
for f in create_funcs():
print(f())
Run Code Online (Sandbox Code Playgroud)
我觉得很奇怪:
4
4
4
4
Run Code Online (Sandbox Code Playgroud)
有谁能解释为什么?
我在github上有一个小型应用程序项目,该项目可在Windows上运行,并且需要pythonnet
。
我的requirement.txt
包含:
beautifulsoup4==4.6
pythonnet==2.3
Run Code Online (Sandbox Code Playgroud)
现在我想为它建立一个文档并放上它readthedocs.org
。将文档推送到github,将项目导入之后readthedocs.org
,我尝试构建文档,但是此操作失败,并显示以下信息:
Collecting pythonnet==2.3 (from -r /home/docs/checkouts/readthedocs.org/user_builds/trelloradar/checkouts/latest/requirements.txt (line 2))
Using cached pythonnet-2.3.0.tar.gz
Building wheels for collected packages: pythonnet
Running setup.py bdist_wheel for pythonnet: started
Running setup.py bdist_wheel for pythonnet: finished with status 'error'
Complete output from command /home/docs/checkouts/readthedocs.org/user_builds/trelloradar/envs/latest/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-iU2ADR/pythonnet/setup.py'; f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /tmp/tmpnPH_1rpip-wheel- --python-tag cp27:
running bdist_wheel
running build
running build_ext
/bin/sh: 1: mono: not found
Traceback (most recent call …
Run Code Online (Sandbox Code Playgroud) 我有一个项目正在使用pathlib
,我想做相当于shutil.rmtree
.
我想用类似的方法来做:
def pathlib_rmtree(folder):
if folder.exists():
for file in folder.glob('**/*'):
if file.is_dir():
file.rmdir()
else:
file.unlink()
folder.rmdir()
Run Code Online (Sandbox Code Playgroud)
但我不确定是否folder.glob('**/*')
保证订购 ,以便在调用之前所有子文件夹都是空的rmdir
。
所以问题是双重的:
pathlib
?glob
保证其结果的顺序,以便所有文件在它们所属的子文件夹之前返回?关于java中的异常,我有几个问题:
什么是java异常?
被视为错误的异常?
什么时候应该抛出异常?
有多少例外?
我有一个从虚拟环境运行的Django应用程序。我正在编写一个bash脚本来测试虚拟环境。PostgreSQL用户名和密码是Django拉入的虚拟环境中的环境变量settings.py
。
为了测试与数据库的连接,我编写了以下内容:
echo -n 'Testing database connection ...'
export COMMAND="from psycopg2 import connect; import sys; c=connect(dbname='myappdb',\
user='$POSTGRESQL_USER', password='$POSTGRESQL_PWD', host='127.0.0.1', port=5432); \
sys.exit(c.closed)"
test `python -c "$COMMAND" 2>/dev/null && echo true `
Run Code Online (Sandbox Code Playgroud)
测试是一个函数:
function test {
[ $1 ] && echo "[OK]" || echo "[FAIL]"
}
Run Code Online (Sandbox Code Playgroud)
似乎即使使用了错误的凭据,也不会引发异常,并且c.closed
始终为零。有什么方法可以测试凭据在虚拟环境中是否正确?