我正在努力学习如何使用该Control.Parallel模块,但我认为我做得不对.
我正在尝试运行以下代码(fibs.hs).
import Control.Parallel
fib :: Int -> Int
fib 0 = 0
fib 1 = 1
fib n = p `par` (q `pseq` (p + q))
where
p = fib (n-1)
q = fib (n-2)
main = print $ fib 30
Run Code Online (Sandbox Code Playgroud)
我编译了这个:
ghc -O2 --make -threaded fibs.hs
Run Code Online (Sandbox Code Playgroud)
然后我得到以下执行该程序的结果(输出每个程序100次的Python脚本并返回执行时间的平均值和标准差):
./fibs +RTS -N1 -> avg= 0.060203 s, deviation = 0.004112 s
./fibs +RTS -N2 -> avg= 0.052335 s, deviation = 0.006713 s
./fibs +RTS -N3 -> avg= …Run Code Online (Sandbox Code Playgroud) 我终于掌握了如何使用monads(不知道我是否理解它们......),但我的代码从来都不是很优雅.我想是因为缺乏对所有这些功能如何Control.Monad真正起作用的把握.所以我认为在使用状态monad的特定代码段中询问关于此的提示会很好.
代码的目标是计算多种随机游走,这是我在更复杂的事情之前尝试做的事情.问题是我同时有两个有状态计算,我想知道如何用优雅组合它们:
Seed -> (DeltaPosition, Seed)DeltaPosition -> Position -> (Log, Position)(Log我只能通过某种方式报告随机游走者的当前位置).我做的是这样的:
我有一个函数来组成这两个有状态的计算:
composing :: (g -> (b, g)) -> (b -> s -> (v,s)) -> (s,g) -> (v, (s, g))
composing generate update (st1, gen1) = let (rnd, gen2) = generate gen1
(val, st2) = update rnd st1
in (val, (st2, gen2))
Run Code Online (Sandbox Code Playgroud)
然后我把它变成一个组成状态的函数:
stateComposed :: State g b -> (b -> State s v) -> State (s,g) v
stateComposed rndmizer updater …Run Code Online (Sandbox Code Playgroud) 我正在学习c ++,最近我学习了(这里是堆栈溢出)有关复制和交换的习惯用法,我对它有一些问题.所以,假设我有以下类使用复制和交换习惯用法,例如:
class Foo {
private:
int * foo;
int size;
public:
Foo(size_t size) : size(size) { foo = new int[size](); }
~Foo(){delete foo;}
Foo(Foo const& other){
size = other.size;
foo = new int[size];
copy(other.foo, other.foo + size, foo);
}
void swap(Foo& other) {
std::swap(foo, other.foo);
std::swap(size, other.size);
}
Foo& operator=(Foo g) {
g.swap(*this);
return *this;
}
int& operator[] (const int idx) {return foo[idx];}
};
Run Code Online (Sandbox Code Playgroud)
我的问题是,假设我有另一个类,它有一个Foo对象作为数据但没有指针或其他可能需要自定义复制或赋值的资源:
class Bar {
private:
Foo bar;
public:
Bar(Foo foo) : bar(foo) {};
~Bar(){};
Bar(Bar …Run Code Online (Sandbox Code Playgroud) 合并时我做错了什么,我无法理解它是什么.我已经完成以下工作来估计一系列整数值的直方图:
import pandas as pnd
import numpy as np
series = pnd.Series(np.random.poisson(5, size = 100))
tmp = {"series" : series, "count" : np.ones(len(series))}
hist = pnd.DataFrame(tmp).groupby("series").sum()
freq = (hist / hist.sum()).rename(columns = {"count" : "freq"})
Run Code Online (Sandbox Code Playgroud)
如果我打印hist,freq这就是我得到的:
> print hist
count
series
0 2
1 4
2 13
3 15
4 12
5 16
6 18
7 7
8 8
9 3
10 1
11 1
> print freq
freq
series
0 0.02
1 0.04
2 0.13 …Run Code Online (Sandbox Code Playgroud) 我正在尝试加载我使用NLTK安装程序安装的一些语料库,但我得到了:
>>> from nltk.corpus import machado
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name machado
Run Code Online (Sandbox Code Playgroud)
但是在下载管理器(nltk.download())中,包machado被标记为已安装,我有一个nltk_data/corpus/machado文件夹.
我如何从python intepreter里面看到安装的语料库是什么?
另外,我应该安装哪个软件包来使用这个方法? http://nltk.googlecode.com/svn/trunk/doc/howto/portuguese_en.html
我找不到该方法中nltk.examples提到的模块.
我真的很喜欢lambdas并且有能力在C++中使用它是一种乐趣.但是,因为我已经习惯了Haskell,lambdas非常适合语法,我正在努力学习如何在C++中使用它们而不会编写难以理解的混乱长代码行.
所以,举个例子,假设我写这个:
vector<double> foo(10,0.2);
for_each(foo.begin(), foo.end(), [](double x){ std::cout << x << " ";})
Run Code Online (Sandbox Code Playgroud)
这不是那么难读,lambda表达式非常小.但是如果我在for_each中有两个或三个行长函数,这可能会成为我的代码阅读技能的问题:
vector<double> foo(10,0.2);
randomNumberGenerator bar;
for_each(foo.begin(), foo.end(), [](double x){ std::cout << "hello!"; x+=bar()/(1+bar()); std::cout << x << " ";})
//sorry, I couldn't think of a less stupid example...
Run Code Online (Sandbox Code Playgroud)
这条线开始变得烦人的长,难以阅读我的口味......
对于这种情况,您首选的代码约定是什么?我应该写:
for_each(foo.begin(), foo.end(),
[] (double x) {
std::cout << "hello!"
x += bar()/(1+bar());
std::cout << x << " ";
});
Run Code Online (Sandbox Code Playgroud)
或类似的东西?我仍然认为这种语法有点不自然,难以阅读...... :(
假设我想使用 mypy 编写一个泛型类,但是该类的类型参数本身就是一个泛型类型。例如:
from typing import TypeVar, Generic, Callable
A = TypeVar("A")
B = TypeVar("B")
T = TypeVar("T")
class FunctorInstance(Generic[T]):
def __init__(self, map: Callable[[Callable[[A], B], T[A]], T[B]]):
self._map = map
def map(self, x: T[A], f: Callable[[A], B]) -> T[B]:
return self._map(f, x)
Run Code Online (Sandbox Code Playgroud)
当我尝试在上面的定义中调用 mypy 时,出现错误:
$ mypy typeclasses.py
typeclasses.py:9: error: Type variable "T" used with arguments
typeclasses.py:12: error: Type variable "T" used with arguments
Run Code Online (Sandbox Code Playgroud)
我尝试在T TypeVar's 定义中添加约束,但未能完成这项工作。是否有可能做到这一点?
我有一个程序使用python的包多处理和队列.我的一个函数有这个结构:
from multiprocessing import Process, Queue
def foo(queue):
while True:
try:
a = queue.get(block = False)
doAndPrintStuff(a)
except:
print "the end"
break
if __name__ == "__main__"
nthreads = 4
queue = Queue.Queue()
# put stuff in the queue here
for stuff in moreStuff:
queue.put(stuff)
procs = [Process(target = foo, args = (queue,)) for i in xrange(nthreads)]
for p in procs:
p.start()
for p in procs:
p.join()
Run Code Online (Sandbox Code Playgroud)
我的想法是,当我尝试从队列中提取并且它是空的时,它将引发异常并终止循环.所以我有两个问题:
1)这是一个安全的成语吗?有没有更好的方法来做到这一点?
2)我试图找到当我尝试.get()从空队列中引发的确切异常.目前我的程序正在捕获所有异常,当错误发生在其他地方并且我只收到"结束"消息时会很糟糕.
我试过了:
import Queue
queue = Queue.Queue()
[queue.put(x) for x …Run Code Online (Sandbox Code Playgroud) 当我需要使用aggregateMongoDB上的命令按日期聚合事物时,我通常这样做:
db.mycollection.aggregate(
{
$project: {
day: {$dayOfMonth: "$date"},
mon: {$month: "$date"},
year: {$year: "$date"},
}
},
{
$group: {
_id : {day: "$day", mon: "$mon", year: "$year"},
count: {$sum: 1}
}
}
)
Run Code Online (Sandbox Code Playgroud)
并最终将day,mon和year字段连接到应用程序中的日期字符串.但是出于很多原因,有时我想在离开数据库之前连接字段,所以我最初尝试过:
db.mycollection.aggregate(
{
$project: {
day: {$dayOfMonth: "$date"},
mon: {$month: "$date"},
year: {$year: "$date"},
}
},
$project: {
datestr: {
$concat : ["$year", "-", "$month", "-", "$day"]
}
}
},
{
$group: {
_id : {day: "$day", mon: "$mon", …Run Code Online (Sandbox Code Playgroud) 我试图了解如何在SQLAlchemy上使用复合外键进行连接,并且我尝试这样做的尝试失败了.
我的玩具模型上有以下模型类(我使用的是Flask-SQLAlchemy,但我不确定这与问题有什么关系):
# coding=utf-8
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)
class Asset(db.Model):
__tablename__ = 'asset'
user = db.Column('usuario', db.Integer, primary_key=True)
profile = db.Column('perfil', db.Integer, primary_key=True)
name = db.Column('nome', db.Unicode(255))
def __str__(self):
return u"Asset({}, {}, {})".format(self.user, self.profile, self.name).encode('utf-8')
class Zabumba(db.Model):
__tablename__ = 'zabumba'
db.ForeignKeyConstraint(
['asset.user', 'asset.profile'],
['zabumba.user', 'zabumba.profile']
)
user = db.Column('usuario', db.Integer, primary_key=True)
profile = db.Column('perfil', db.Integer, primary_key=True)
count = db.Column('qtdade', db.Integer)
def __str__(self):
return u"Zabumba({}, {}, {})".format(self.user, self.profile, …Run Code Online (Sandbox Code Playgroud) python ×5
c++ ×2
haskell ×2
c++11 ×1
class ×1
coding-style ×1
corpus ×1
foreign-keys ×1
lambda ×1
monads ×1
mongodb ×1
multicore ×1
mypy ×1
nlp ×1
nltk ×1
orm ×1
pandas ×1
queue ×1
sqlalchemy ×1
state-monad ×1
type-hinting ×1