小编Mik*_*and的帖子

模式 - 没有 else if 的事件调度程序?

我正在为 Detours 库创建一个 Python 包装器。该工具的一个部分是一个调度程序,用于将所有挂钩的 API 调用发送到各种处理程序。

现在我的代码是这样的:

if event == 'CreateWindowExW':
    # do something
elif event == 'CreateProcessW':
    # do something
elif ...
Run Code Online (Sandbox Code Playgroud)

这感觉很丑。是否有一种模式可以创建事件调度程序,而不必elif为每个 Windows API 函数创建一个分支?

python design-patterns event-handling

1
推荐指数
1
解决办法
867
查看次数

为什么xmlrpc客户端无法通过xmlrpc服务器过程将项目附加到列表中?

服务器代码(基于Python库参考):

from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandler

class RequestHandler(SimpleXMLRPCRequestHandler):
    rpc_paths = ()

server = SimpleXMLRPCServer(("127.0.0.1", 8000),
                            requestHandler=RequestHandler)
server.register_introspection_functions()

l = list()

def say_hi():
    return 'hi !'

def append(event):
    l.append(event)

server.register_function(say_hi)
server.register_function(append)

server.serve_forever()
Run Code Online (Sandbox Code Playgroud)

客户端(解释器从另一个终端窗口启动):

>>> from xmlrpc.client import ServerProxy
>>> s = ServerProxy('http://127.0.0.1', allow_none=True)
>>> s.say_hi()
'hi !'
>>> s.append(1)
Traceback (most recent call last):
...
xmlrpc.client.Fault(Fault 1: "<class 'TypeError'>:cannot
                    marshal None unless allow_none is enabled")
Run Code Online (Sandbox Code Playgroud)

我该如何解决?我不正确地使用xmlrpc吗?

python xml-rpc simplexmlrpcserver xmlrpcclient

1
推荐指数
1
解决办法
7866
查看次数

有没有更好的方法用urlopen做csv/namedtuple?

在Python 3.3中使用namedtuple文档示例作为我的模板,我有以下代码来下载csv并将其转换为一系列namedtuple子类实例:

from collections import namedtuple
from csv import reader
from urllib.request import urlopen    

SecurityType = namedtuple('SecurityType', 'sector, name')

url = 'http://bsym.bloomberg.com/sym/pages/security_type.csv'
for sec in map(SecurityType._make, reader(urlopen(url))):
    print(sec)
Run Code Online (Sandbox Code Playgroud)

这引发了以下异常:

Traceback (most recent call last):
  File "scrap.py", line 9, in <module>
    for sec in map(SecurityType._make, reader(urlopen(url))):
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
Run Code Online (Sandbox Code Playgroud)

我知道问题是urlopen返回字节而不是字符串,我需要在某些时候解码输出.以下是我现在使用StringIO的方法:

from collections import namedtuple
from csv import reader
from urllib.request import urlopen
import io

SecurityType = namedtuple('SecurityType', …
Run Code Online (Sandbox Code Playgroud)

python csv namedtuple python-3.x

1
推荐指数
1
解决办法
356
查看次数

scipy-为什么COBYLA不遵守约束?

我正在使用COBYLA对具有约束的线性目标函数进行成本最小化。我正在通过为每个限制都包含一个约束来实现上下限。

import numpy as np
import scipy.optimize

def linear_cost(factor_prices):
    def cost_fn(x):
        return np.dot(factor_prices, x)
    return cost_fn


def cobb_douglas(factor_elasticities):
    def tech_fn(x):
        return np.product(np.power(x, factor_elasticities), axis=1)
    return tech_fn

def mincost(targets, cost_fn, tech_fn, bounds):

    n = len(bounds)
    m = len(targets)

    x0 = np.ones(n)  # Do not use np.zeros.

    cons = []

    for factor in range(n):
        lower, upper = bounds[factor]
        l = {'type': 'ineq',
             'fun': lambda x: x[factor] - lower}
        u = {'type': 'ineq',
             'fun': lambda x: upper - x[factor]}
        cons.append(l)
        cons.append(u)

    for output …
Run Code Online (Sandbox Code Playgroud)

scipy lexical-scope

1
推荐指数
1
解决办法
1164
查看次数

解决 MultiParameterTypeClass 中的歧义

根据对此问题的反馈,我使用 MultiParamTypeClass 来表示强化学习环境Environment,使用 3 个类型变量:e对于环境实例本身(例如,下面的 Nim 之类的游戏),s对于特定对象使用的状态数据类型游戏,以及a特定游戏使用的动作数据类型。

{-# LANGUAGE MultiParamTypeClasses #-}

class MultiAgentEnvironment e s a where
    baseState :: e -> s
    nextState :: e -> s -> a -> s
    reward :: (Num r) => e -> s -> a -> [r]

data Game = Game { players :: Int
                 , initial_piles :: [Int]
                 } deriving (Show)

data State = State { player :: Int
                   , piles :: [Int]} …
Run Code Online (Sandbox Code Playgroud)

haskell

1
推荐指数
1
解决办法
61
查看次数

如何使自定义数据类型可订购?

我有一个Haskell的自定义数据类型,我想作为一个键使用Data.MapData.Graph以及其他的查找表。

data State = State
  { playerIdx :: Int
  , piles :: [Int]
  } deriving Show
Run Code Online (Sandbox Code Playgroud)

我如何使它可订购?以下似乎不起作用:

data State = State
  { playerIdx :: Int
  , piles :: [Int]
  } deriving (Show, Ord)
Run Code Online (Sandbox Code Playgroud)

haskell

0
推荐指数
1
解决办法
67
查看次数