当前位置: 首页>>代码示例>>Python>>正文


Python pool.Pool类代码示例

本文整理汇总了Python中pool.Pool的典型用法代码示例。如果您正苦于以下问题:Python Pool类的具体用法?Python Pool怎么用?Python Pool使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Pool类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: runStrategy

def runStrategy(in_prices):
	global prices, mas, emas, smas, lwmas, vmas, vemas, vsmas, vlwmas
	log.debug('beginning vma strategy ...')
	prices = in_prices
	
	vols = [p['vol'] for p in prices]
	
	vmalength = const.VMA_MAX + 1
	vmas = [0] * vmalength
	vemas = [0] * vmalength
	vsmas = [0] * vmalength
	vlwmas = [0] * vmalength
	for period in range(1, vmalength):
		vmas[period] = ma.calc_ma(vols, period)
		vemas[period] = ma.calc_ema(vols, period)
		vsmas[period] = ma.calc_sma(vols, period)
		vlwmas[period] = ma.calc_lwma(vols, period)
		
	ps = [p['close'] for p in prices]
	
	malength = const.MA_MAX + 1
	mas = [0] * malength
	emas = [0] * malength
	smas = [0] * malength
	lwmas = [0] * malength
	for period in range(1, malength):
		mas[period] = ma.calc_ma(ps, period)
		emas[period] = ma.calc_ema(ps, period)
		smas[period] = ma.calc_sma(ps, period)
		lwmas[period] = ma.calc_lwma(ps, period)
	
	log.debug('running ma strategy ...')
	starttime = datetime.datetime.now()
	
	pool = Pool(const.POOL_SIZE)
	
	for vft, vf in [(matype, period) for matype in const.VMA_TYPES for period in const.VMA_FAST]:
		for vst, vs in [(matype, period) for matype in const.VMA_TYPES for period in const.VMA_SLOW]:
			if vs != 0 and vs <= vf: continue
			poola = Pool(const.POOL_SIZE)
			poolb = Pool(const.POOL_SIZE)
			
			for ft, f in [(matype, period) for matype in const.MA_TYPES for period in const.MA_FAST]:
				for s1t, s1 in [(matype, period) for matype in const.MA_TYPES for period in const.MA_SLOW1]:
					if s1 != 0 and s1 <= f: continue
					elapsed = (datetime.datetime.now() - starttime).seconds
					log.debug('== ' + str(elapsed) + ',' + vft + '_' + str(vf) + ',' + vst + '_' + str(vs) + ',' + ft + '_' + str(f) + ',' + s1t + '_' + str(s1) + ' ==')
					
					doTrade(poola, vft, vf, vst, vs, ft, f, s1t, s1, '', 0, '', 0)
					doTrade(poolb, vft, vf, vst, vs, '', 0, '', 0, ft, f, s1t, s1)
			
			for ia in range(len(poola.strategies)):
				for ib in range(len(poolb.strategies)):
					sa = poola.strategies[ia]
					sb = poolb.strategies[ib]
					if sa[0] == 0 or sb[0] == 0: continue
					t = doTrade(pool, vft, vf, vst, vs, sa[0].args[0], sa[0].args[1], sa[0].args[2], sa[0].args[3], sb[0].args[4], sb[0].args[5], sb[0].args[6], sb[0].args[7])
				
	pool.showStrategies()
	return pool.strategies[0][0]
开发者ID:ongbe,项目名称:pymisc,代码行数:60,代码来源:vmaStrategy.py

示例2: testAdd

 def testAdd(self):
   results = set()
   pool = Pool(3)
   for result in pool.imap_unordered(Run, [[x] for x in range(0, 10)]):
     results.add(result.value)
     if result.value < 30:
       pool.add([result.value + 20])
   self.assertEquals(set(range(0, 10) + range(20, 30) + range(40, 50)),
                     results)
开发者ID:BazisSoft,项目名称:node-delphi,代码行数:9,代码来源:pool_unittest.py

示例3: fullPool

def fullPool(spec):
  """Creates a pool and fills it with the world drawn from the provided specification, before returning it."""
  pool = Pool()
  
  data = sampleWorld(spec)
  for pair in data:
    pool.store(pair[0], pair[1])

  return pool
开发者ID:PeterZhouSZ,项目名称:helit,代码行数:9,代码来源:test_synth.py

示例4: testException

 def testException(self):
   results = set()
   pool = Pool(3)
   for result in pool.imap_unordered(Run, [[x] for x in range(0, 12)]):
     # Item 10 will not appear in results due to an internal exception.
     results.add(result.value)
   expect = set(range(0, 12))
   expect.remove(10)
   self.assertEquals(expect, results)
开发者ID:119120119,项目名称:node,代码行数:9,代码来源:pool_unittest.py

示例5: run

def run(IP, PORT):
    # Simulated "event queue"
    eventQueue = deque()
    
    # Process queue used for async rpc system.
    processQ = Queue()
    sessionManager = MasterSessionManager(IP, PORT, processQ)
    rpcManager = RPCManager(sessionManager, processQ)
    containerAllocator = RMContainerAllocator(eventQueue, sessionManager)
    committerEventHandler = CommitterEventHandler(eventQueue)
    printed = False;
    serverList = []
    assignedServers = []
    serverAssignments = defaultdict(list)
    
    pool = Pool()
    
    job = Job(work, pool, rpcManager, eventQueue)
    
    # Simulate Delayed Job init and start.
    eventQueue.append(("JOB_INIT", job))
    eventQueue.append(("JOB_START", job))
    
    while True:
        # Simulate "event delivery"
        containerAllocator.pushNewEvents(eventQueue)
        committerEventHandler.pushNewEvents(eventQueue)
        pool.pushNewEvents(eventQueue)
        eventQueue.clear()
        
        # Simulate async mechanisums
        sessionManager.poll()
        rpcManager.poll()
        containerAllocator.heartbeat()
        committerEventHandler.heartbeat()
        
        # For server failure
        for locator in serverList:
            if (locator not in sessionManager.serverList()):
                eventQueue.append(("JOB_UPDATED_NODES", locator))
        if serverList != sessionManager.serverList():
            print "serverList change"
        serverList = sessionManager.serverList()
    
        # Run tasks
        pool.poll()

        if job.getStatus() == "SUCCEEDED" and not printed:
            print "Job Complete"
            print job
            printed = True
开发者ID:rstutsman,项目名称:mappy,代码行数:51,代码来源:master.py

示例6: TestPoolFunctions

class TestPoolFunctions(unittest.TestCase):

    def setUp(self):
        self.pool = Pool(MsgPackPoolableFactory(), **config)
    def tearDown(self):
        unittest.TestCase.tearDown(self)
        self.pool.destroy()
    def test_ping(self):
        try:
            client = self.pool.borrowObject()
            self.assertIsNotNone(client, "client is None")
            rs = client.call("ping")
            self.assertEqual(rs, "pong", "is pinged")
            print rs
        finally:
            self.pool.returnObject(client)
开发者ID:wing1000,项目名称:wb3,代码行数:16,代码来源:testPool.py

示例7: run_neuron_experiment

def run_neuron_experiment(N, input_rates, weights, threshold,
    T=None, nspikes=None, neuron_model=RegularNeuron):
    """Run an experiment with a single neuron
    """
    spike_rates = set_list_var(input_rates, N)
    weights = set_list_var(weights, N)
    
    neurons = [neuron_model(spike_rate, weight) for 
               spike_rate, weight in
               zip(spike_rates, weights)]
    pool = Pool(neurons=neurons, threshold=threshold)
    spks_in = pool.gen_nrn_spikes(T=T, nspikes=nspikes)
    
    merged_spks_in = pool.merge_spikes(spks_in)
    spks_out, acc_state = pool.gen_acc_spikes(merged_spks_in)
    return spks_in, acc_state, spks_out
开发者ID:fragapanagos,项目名称:notebooks,代码行数:16,代码来源:exp.py

示例8: go

def go(filename, max_size, use_donor_weight):
    def edge_score_fun(e):
        return 1# + (e.patient.weight - e.donor.weight)/999.0

    sys.stdout.write(filename + "\t")
    sys.stdout.write("1\t" if use_donor_weight else "0\t")

    pool = Pool.from_file(filename)
    pool.create_donor_patient_arcs(use_donor_weight)
    sys.stdout.write(str(len(pool.patients)) + "\t")

    unrestricted_obj_val, optimal_exchanges = pool.solve_uef(edge_score_fun)
    sys.stdout.write(str(unrestricted_obj_val) + "\t")

    obj_val = None
    for i in range(2, max_size+1):
        if obj_val==unrestricted_obj_val:
            pass
        elif i < 6:
            obj_val, optimal_exchanges = pool.solve_cycle_formulation(i, edge_score_fun)
        else:
            obj_val, optimal_exchanges = pool.solve_eef(i, edge_score_fun)

        sys.stdout.write(str(obj_val) + "\t")
        sys.stdout.flush()

    sys.stdout.write(str(pool.n_patients_with_2_compat_donors()) + "\n")
开发者ID:jamestrimble,项目名称:lungexchange,代码行数:27,代码来源:optimise.py

示例9: __init__

    def __init__(self, peers, host, port):
        self.host = host
        self.port = port
        self.peer_id = '{}:{}'.format(host, port)

        self._logger = logging.getLogger(__name__)
        self._loop = asyncio.get_event_loop()
        self._pool = Pool(self, peers)

        # heartbeat constants and bookkeeping variables
        self._heartbeat_interval = 1000  # ms
        self._last_interval = None

        self._min_heartbeat_timeout = 2000  # ms
        self._max_heartbeat_timeout = 4000  # ms
        self._heartbeat_timeout = None
        self._last_heartbeat = None

        self.reset_heartbeat()
        self.reset_timeout()

        self._log = Log(Machine())
        self.state = State.FOLLOWER
        self.term = 0
        self.voted = None
        self.votes = set()

        self._pending_clients = {}

        self.handlers = {'append_entries_req': self.handle_append_entries_req,
                         'append_entries_resp': self.handle_append_entries_resp,
                         'request_vote_req': self.handle_request_vote_req,
                         'request_vote_resp': self.handle_request_vote_resp}
开发者ID:guilload,项目名称:aio-raft,代码行数:33,代码来源:server.py

示例10: runStrategy

def runStrategy(in_prices):
	global mas, emas, smas, lwmas, std, prices
	log.debug('beginning ma strategy ...')
	
	prices = in_prices
	ps = [p['close'] for p in prices]
	
	std = [0] * 51
	l = len(prices)
	for period in range(2, 51):
		std[period] = [0] * l
		for i in range(period - 1, l):
			std[period][i] = np.std(ps[i-period+1 : i+1], dtype=np.float64, ddof=0)
	
	malength = const.MA_MAX + 1
	mas = [0] * malength
	emas = [0] * malength
	smas = [0] * malength
	lwmas = [0] * malength
	for period in range(1, malength):
		mas[period] = ma.calc_ma(ps, period)
		emas[period] = ma.calc_ema(ps, period)
		smas[period] = ma.calc_sma(ps, period)
		lwmas[period] = ma.calc_lwma(ps, period)
	
	log.debug('running ma strategy ...')
	starttime = datetime.datetime.now()
	
	matypes = ['MA', 'EMA', 'SMA', 'LWMA']
	
	pool = Pool(const.POOL_SIZE)
	for ft, f in [(matype, period) for matype in matypes for period in const.MA_FAST]:
		for s1t, s1 in [(matype, period) for matype in matypes for period in const.MA_SLOW1]:
			if s1 != 0 and s1 <= f: continue
			elapsed = (datetime.datetime.now() - starttime).seconds
			log.debug('== ' + str(elapsed) + ',' + ft + '_' + str(f) + ',' + s1t + '_' + str(s1) + ' ==')
			for s2t, s2 in [(matype, period) for matype in matypes for period in const.MA_SLOW2]:
				if s2 != 0 and s2 <= s1: continue
				#run 
				doTrade(pool, ft, f, s1t, s1, s2t, s2)
				
	pool.showStrategies()
	return pool.strategies[0][0]
开发者ID:ongbe,项目名称:pymisc,代码行数:43,代码来源:maStrategy.py

示例11: __init__

 def __init__(self, app, **kwargs):
     self.app = app or self.app
     super(Guard, self).init(**kwargs)
     self.rpc_server = PyroServer(GUARD_PORT)
     self.rpc_client = PyroClient(self.app.conf['HUB_IP'], HUB_PORT)
     self.pool = Pool(self.app)
     self.machine = Machine(healthy_mock=app.conf['HEALTHY_MOCK'], labels=self.labels)
     self.__shutdown_guard = threading.Event()
     self.LOOP_INTERVAL = 10  # second
     self.alive = False
开发者ID:demien-aa,项目名称:popcorn,代码行数:10,代码来源:__init__.py

示例12: cli_entrypoint

def cli_entrypoint():
    parser = argparse.ArgumentParser()
    parser.add_argument('-c', help='config file', default='./config.ini')
    args = parser.parse_args()

    DemoConfig.config_file = args.c
    config = DemoConfig()

    # create table
    session = DemoData.get_session(config)
    session.close()

    logging.basicConfig(level=config.log_level)
    vacuum = Vacuum()
    pool = Pool()
    try:
        vacuum.start()
        pool.start()
        server = ThreadedHTTPServer(('0.0.0.0', config.http_port), Handler)
        server.serve_forever()
    except (KeyboardInterrupt, SystemExit):
        logging.info("Exit signal catched")
        vacuum.stop = True
开发者ID:pmsipilot,项目名称:demoinstance,代码行数:23,代码来源:cli.py

示例13: runStrategy

def runStrategy(in_prices):
	global prices, ps
	log.debug('beginning pattern strategy ...')
	
	prices = in_prices
	ps = [p['close'] for p in prices]
	
	starttime = datetime.datetime.now()
	
	pool = Pool(const.POOL_SIZE)
	
	for i in range(20, 81)[::5]:
		for j in range(1, 6)[::1]:
			if i < j: continue
			for f in range(5, 16)[::2]:
				elapsed = (datetime.datetime.now() - starttime).seconds
				log.debug('== ' + str(elapsed) + ', ' + str(i) + ',' + str(j) + ',' + str(f) + ' ==')
				for sl in range(15, 31)[::3]:
					for si in range(3, 16)[::2]:
						doTrade(pool, i, j, f, sl, si)
		
	pool.showStrategies()
	return pool.strategies[0][0]
开发者ID:ongbe,项目名称:pymisc,代码行数:23,代码来源:patternStrategy.py

示例14: CPServer

class CPServer(object):
	def __init__(self,statefile=None,load=False):
		self.pool=Pool()
		self.statefile=statefile
		if self.statefile and load:
			self.pool.load_state(self.statefile)

	def dispatch_request(self,request):
		#if not request.json:
		#	return BadRequest('No JSON found!')
		result=self.pool.doMultipleCommandsAsync(request.json)
		return Response(dumps(result),content_type='text/json')

	def wsgi_app(self, environ, start_response):
		request = Request(environ)
		response = self.dispatch_request(request)
		return response(environ, start_response)

	def __call__(self, environ, start_response):
		return self.wsgi_app(environ,start_response)

	def close(self):
		if self.statefile:
			self.pool.save_state('state.json')
开发者ID:ervanalb,项目名称:cesspool,代码行数:24,代码来源:cpserver.py

示例15: CPServer

class CPServer(object):
	def __init__(self):
		self.pool=Pool()

	def dispatch_request(self,request):
		#if not request.json:
		#	return BadRequest('No JSON found!')
		result=self.pool.doMultipleCommandsAsync(request.json)
		return Response(dumps(result),content_type='text/json')

	def wsgi_app(self, environ, start_response):
		request = Request(environ)
		response = self.dispatch_request(request)
		return response(environ, start_response)

	def __call__(self, environ, start_response):
		return self.wsgi_app(environ,start_response)
开发者ID:zbanks,项目名称:cesspool,代码行数:17,代码来源:cpserver.py


注:本文中的pool.Pool类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。