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


Python LifoQueue.get方法代码示例

本文整理汇总了Python中Queue.LifoQueue.get方法的典型用法代码示例。如果您正苦于以下问题:Python LifoQueue.get方法的具体用法?Python LifoQueue.get怎么用?Python LifoQueue.get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Queue.LifoQueue的用法示例。


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

示例1: lifo_queue_usage

# 需要导入模块: from Queue import LifoQueue [as 别名]
# 或者: from Queue.LifoQueue import get [as 别名]
def lifo_queue_usage():
    from Queue import LifoQueue

    lifo_queue = LifoQueue()
    lifo_queue.put(1)
    lifo_queue.put(2)

    print lifo_queue.get()
    print lifo_queue.get()
开发者ID:WenyuChang,项目名称:PythonDeepUsage,代码行数:11,代码来源:module_queue.py

示例2: graham_scan

# 需要导入模块: from Queue import LifoQueue [as 别名]
# 或者: from Queue.LifoQueue import get [as 别名]
def graham_scan(points):
    """

    :param points: numpy array of 2-dimensional points
    :return: Convex hull as another numpy array of points
    """
    ch = LifoQueue()
    leftmost = points[np.argmin(points[:, 0])]  # finding the leftmost point... definitely in CH

    dtype = [('x', np.float64), ('y', np.float64), ('slope', np.float64)]  # preparing a nicer object for sorting
    cpts = np.zeros(len(points) - 1, dtype=dtype)
    cpts[:]['x'] = points[1:, 0]
    cpts[:]['y'] = points[1:, 1]
    cpts[:]['slope'] = (cpts[:]['y'] - leftmost[1]) / (cpts[:]['x'] - leftmost[0])  # angle <-> slope from leftmost

    sorted_pts = np.sort(cpts, order=['slope', 'x'])  # sort by angle (slope), then distance from leftmost
                                                      # shows which points are colinear

    mask = np.zeros(len(sorted_pts), dtype=bool)  # getting rid of points with same angle from leftmost
    mask = np.logical_not(mask)
    for i in range(len(sorted_pts[1:])):
        mask[i - 1] = not sorted_pts[i - 1]['slope'] == sorted_pts[i]['slope']  # only keep farthest away
    sorted_pts = sorted_pts[mask]

    sorted_pts[:] = sorted_pts[::-1]  # sort greatest slope to lowest (move clockwise)

    pts = np.zeros((len(sorted_pts) + 1, 2))  # putting leftmost back into a new array object
    pts[1:, 0] = sorted_pts[:]['x']
    pts[1:, 1] = sorted_pts[:]['y']
    pts[0] = leftmost

    ch.put(pts[0])  # leftmost and the point with the highest slope are in the CH for sure
    ch.put(pts[1])
    for i, pt in enumerate(pts):
        if i < 2:
            continue
        else:
            last = ch.get()
            second_to_last = ch.get()
            side = which_side(second_to_last, pts[i], last)  # Less than 0 => on the left, o/w on the right
            while side > 0:  # if last point put in on right side, it must have been wrong to be in CH
                last = second_to_last
                second_to_last = ch.get()
                side = which_side(second_to_last, pts[i], last)
            ch.put(second_to_last)
            ch.put(last)
            ch.put(pt)

    return np.array([ch.get() for i in range(ch.qsize())])  # Put the queue into an array
开发者ID:idelbrid,项目名称:Algorithms,代码行数:51,代码来源:convex_hull.py

示例3: PooledIncomingQueue

# 需要导入模块: from Queue import LifoQueue [as 别名]
# 或者: from Queue.LifoQueue import get [as 别名]
class PooledIncomingQueue(IncomingQueue):
    def init_queues(self, n=5, buffsize=0, maxsize=1000*1000*1000):
        maxsize = maxsize / n
        self.write_executor = ThreadPoolExecutor(poolsize=1, queuesize=100)
        self.rqfile = FileDequeue(self.qdir, reader=FPSortingQueueFileReader)
        #self.rqfile = DummyFileDequeue(self.qdir)
        self.qfiles = [FileEnqueue(self.qdir, suffix=str(i),
                                   maxsize=maxsize,
                                   buffer=buffsize,
                                   executor=self.write_executor)
                       for i in range(n)]
        self.avail = LifoQueue()
        for q in self.qfiles:
            self.avail.put(q)

    def shutdown(self):
        super(PooledIncomingQueue, self).shutdown()
        self.write_executor.shutdown()

    def add(self, curis):
        processed = 0
        t0 = time.time()
        enq = self.avail.get()
        t = time.time() - t0
        if t > 0.1: logging.warn('self.avail.get() %.4f', t)
        try:
            enq.queue(curis)
            self.addedcount += len(curis)
            processed += len(curis)
            return dict(processed=processed)
        finally:
            t0 = time.time()
            self.avail.put(enq)
            t = time.time() - t0
            if t > 0.1: logging.warn('slow self.avail.put() %.4f', t)
开发者ID:travisfw,项目名称:crawlhq,代码行数:37,代码来源:hq.py

示例4: _find_path_dfs

# 需要导入模块: from Queue import LifoQueue [as 别名]
# 或者: from Queue.LifoQueue import get [as 别名]
 def _find_path_dfs(self):
     """Finding augmenting paths in the residual network."""
     parent = dict((node, None) for node in self.residual.iternodes())
     # Capacity of found path to node.
     capacity = {self.source: float("inf")}
     Q = LifoQueue()
     Q.put(self.source)
     while not Q.empty():
         node = Q.get()
         for edge in self.residual.iteroutedges(node):
             cap = edge.weight - self.flow[edge.source][edge.target]
             if cap > 0 and parent[edge.target] is None:
                 parent[edge.target] = edge.source
                 capacity[edge.target] = min(capacity[edge.source], cap)
                 if edge.target != self.sink:
                     Q.put(edge.target)
                 else:
                     # Backtrack search and write flow.
                     target = self.sink
                     while target != self.source:
                         node = parent[target]
                         self.flow[node][target] += capacity[self.sink]
                         self.flow[target][node] -= capacity[self.sink]
                         target = node
                     return capacity[self.sink]
     return 0
开发者ID:ufkapano,项目名称:graphs-dict,代码行数:28,代码来源:fordfulkerson.py

示例5: get_max_flow

# 需要导入模块: from Queue import LifoQueue [as 别名]
# 或者: from Queue.LifoQueue import get [as 别名]
def get_max_flow(directed_graph, source, sink):
    residual = {edge: edge.capacity for edges in directed_graph.values() for edge in edges}
    flow_paths = []

    def flow_path(path):
        max_flow = float("inf")
        for edge in path:
            max_flow = min(max_flow, residual[edge])
        for edge in path:
            residual[edge] -= max_flow
        flow_paths.append((max_flow, path))

    bfs_queue = LifoQueue()
    bfs_queue.put([])
    while not bfs_queue.empty():
        path = bfs_queue.get()
        for edge in directed_graph[source if not path else path[-1].to_node]:
            if residual[edge] > 0:
                new_path = path[:]
                new_path.append(edge)
                if edge.to_node == sink:
                    flow_path(new_path)
                else:
                    bfs_queue.put(new_path)
    return flow_paths
开发者ID:dave322942780,项目名称:AlgoLand,代码行数:27,代码来源:max_flow_algorithm.py

示例6: _visit

# 需要导入模块: from Queue import LifoQueue [as 别名]
# 或者: from Queue.LifoQueue import get [as 别名]
 def _visit(self, node, pre_action=None, post_action=None):
     """Explore the connected component,"""
     self.time = self.time + 1
     self.dd[node] = self.time
     self.color[node] = "GREY"
     Q = LifoQueue()
     Q.put(node)   # node is GREY
     if pre_action:   # when Q.put
         pre_action(node)
     while not Q.empty():
         source = Q.get()    # GREY node is processed
         for edge in self.graph.iteroutedges(source):
             if self.color[edge.target] == "WHITE":
                 self.parent[edge.target] = source
                 self.dag.add_edge(edge)
                 self.time = self.time + 1
                 self.dd[edge.target] = self.time
                 self.color[edge.target] = "GREY"
                 Q.put(edge.target)   # target is GREY
                 if pre_action:   # when Q.put
                     pre_action(edge.target)
         self.time = self.time + 1
         self.ff[source] = self.time
         self.color[source] = "BLACK"
         if post_action:   # source became BLACK
             post_action(source)
开发者ID:ufkapano,项目名称:graphs-dict,代码行数:28,代码来源:dfs.py

示例7: DummyMessageHandler

# 需要导入模块: from Queue import LifoQueue [as 别名]
# 或者: from Queue.LifoQueue import get [as 别名]
class DummyMessageHandler(MessageHandler):
    # TODO(steffen): locking
    def __init__(self):
        MessageHandler.__init__(self)
        self._messages = LifoQueue()
        self._devices = []

    def register(self, device):
        self._devices.append(device)

    def read_message(self):
        return self._messages.get()

    def write_message_from_device(self, message):
        self._messages.put(message)

    def write_message(self, message):
        for d in self._devices:
            d.handle_message(message)

    def has_messages(self):
        for d in self._devices:
            d.loop()

        return not self._messages.empty()

    def stop(self):
        pass
开发者ID:stege,项目名称:HomeControl,代码行数:30,代码来源:message_handler.py

示例8: LiveviewStreamThread

# 需要导入模块: from Queue import LifoQueue [as 别名]
# 或者: from Queue.LifoQueue import get [as 别名]
    class LiveviewStreamThread(threading.Thread):
        def __init__(self, url):
            # Direct class call `threading.Thread` instead of `super()` for python2 capability
            threading.Thread.__init__(self)
            self.lv_url = url
            self._lilo_head_pool = LifoQueue()
            self._lilo_jpeg_pool = LifoQueue()

            self.header = None
            self.frameinfo = []

        def run(self):
            sess = urlopen(self.lv_url)

            while True:
                header = sess.read(8)
                ch = common_header(header)

                data = sess.read(128)
                payload = payload_header(data, payload_type=ch['payload_type'])

                if ch['payload_type'] == 1:
                    data_img = sess.read(payload['jpeg_data_size'])
                    assert len(data_img) == payload['jpeg_data_size']

                    self._lilo_head_pool.put(header)
                    self._lilo_jpeg_pool.put(data_img)

                elif ch['payload_type'] == 2:
                    self.frameinfo = []

                    for x in range(payload['frame_count']):
                        data_img = sess.read(payload['frame_size'])
                        self.frameinfo.append(payload_frameinfo(data_img))

                sess.read(payload['padding_size'])

        def get_header(self):
            if not self.header:
                try:
                    self.header = self._lilo_head_pool.get_nowait()
                except Exception as e:
                    self.header = None
            return self.header

        def get_latest_view(self):
            # note this is a blocking call
            data_img = self._lilo_jpeg_pool.get()

            # retrive next header
            try:
                self.header = self._lilo_head_pool.get_nowait()
            except Exception as e:
                self.header = None

            return data_img

        def get_frameinfo(self):
            return self.frameinfo
开发者ID:Bloodevil,项目名称:sony_camera_api,代码行数:61,代码来源:pysony.py

示例9: Plan

# 需要导入模块: from Queue import LifoQueue [as 别名]
# 或者: from Queue.LifoQueue import get [as 别名]
    def Plan(self, start_config, goal_config):
        start_time = time.time()
        if self.visualize and hasattr(self.planning_env, "InitializePlot"):
            self.planning_env.InitializePlot(goal_config)

        plan = []
        # TODO: Here you will implement the breadth first planner
        #  The return path should be a numpy array
        #  of dimension k x n where k is the number of waypoints
        #  and n is the dimension of the robots configuration space
        q = LifoQueue()
        start_id = self.planning_env.discrete_env.ConfigurationToNodeId(start_config)
        goal_id = self.planning_env.discrete_env.ConfigurationToNodeId(goal_config)
        found = False
        q.put(start_id)
        explored =[start_id]
        backtrack = {}
        backtrack[start_id] = None
        n= 0
        while (q.qsize()>0) and not found:
            current = q.get()          
            successors = self.planning_env.GetSuccessors(current)
            for successor in successors:
                if not successor in backtrack:
                    n = n+1
                    q.put(successor)
                    #explored.append(successor)
                    backtrack[successor] = current
                    if self.visualize: 
                        s = self.planning_env.discrete_env.NodeIdToConfiguration(successor)
                        c = self.planning_env.discrete_env.NodeIdToConfiguration(current)
                        self.planning_env.PlotEdge(c,s)
                    if successor == goal_id:
                        found = True
                        break
        # Shortest Path
        path = []
        path.append(self.planning_env.discrete_env.NodeIdToConfiguration(goal_id))
        element = backtrack[goal_id]
        while element is not None:
            path.append(self.planning_env.discrete_env.NodeIdToConfiguration(element))
            element = backtrack[element]
        plan = path[::-1]

        if self.visualize: 
            for i in range(len(path) - 1):
                self.planning_env.PlotRedEdge(path[i],path[i+1])
        print "number of nodes"
        print n
        print "time (in seconds):" 
        print time.time()- start_time
        path_length = 0
        for i in range(len(path) - 1):
            path_length = path_length + self.planning_env.ComputeDistance(self.planning_env.discrete_env.ConfigurationToNodeId(path[i]), self.planning_env.discrete_env.ConfigurationToNodeId(path[i+1]))
            
        print "path path_length"
        print path_length
        return plan
开发者ID:rushat,项目名称:RobotAutonomyHW3,代码行数:60,代码来源:DepthFirstPlanner.py

示例10: stack

# 需要导入模块: from Queue import LifoQueue [as 别名]
# 或者: from Queue.LifoQueue import get [as 别名]
class stack():
    def __init__(self):
        self.s = LifoQueue()

    def push(self, x):
        self.s.put(x)

    def pop(self):
        return self.s.get()

    def empty(self):
        return self.s.empty()
开发者ID:kumar-abhishek,项目名称:CompetitiveProgramming,代码行数:14,代码来源:stack.py

示例11: MenuAction

# 需要导入模块: from Queue import LifoQueue [as 别名]
# 或者: from Queue.LifoQueue import get [as 别名]
class MenuAction(object):
    def __init__(self):
        self.undo_commands = LifoQueue()
        self.commands = defaultdict(Actions)

    def set_command(self, item, activate, deactivate):
        self.commands[item] = Actions(activate, deactivate)

    def activate(self, item):
        action = self.commands[item].activate
        action.execute()
        self.undo_commands.put(action)

    def deactivate(self, item):
        action = self.commands[item].deactivate
        action.execute()
        self.undo_commands.put(action)

    def undo(self):
        if not self.undo_commands.empty():
            self.undo_commands.get().undo()
开发者ID:benjaminhuanghuang,项目名称:python_designpattern,代码行数:23,代码来源:menu_action.py

示例12: dfSearch

# 需要导入模块: from Queue import LifoQueue [as 别名]
# 或者: from Queue.LifoQueue import get [as 别名]
def dfSearch(start, actions, goalTest, depthLimit=False):
  """Depth-First Search"""
  queue = LifoQueue()
  queue.put(start)
  while True:
    if queue.empty():
      return node
    node = queue.get()
    if goalTest(node):
      return node
    if (node.depth <= depthLimit) or (depthLimit is False):
      queue = node.expand(queue, actions)
开发者ID:neyre,项目名称:Toy-Search,代码行数:14,代码来源:Search.py

示例13: stackDFS

# 需要导入模块: from Queue import LifoQueue [as 别名]
# 或者: from Queue.LifoQueue import get [as 别名]
def stackDFS(Graph, vroot):
    """
        Depth First Search: stack version
    """
    Stack=LifoQueue()
    Stack.put(vroot)
    while not Stack.empty():
        iV=Stack.get()
        print ("Visit :", iV)
        Graph.setVisited(iV)
        for jV in Graph.VertexList:
            if Graph.Edges[iV,jV] and not Graph.Visited[jV]:
                Stack.put(jV)
开发者ID:habiboulaye,项目名称:pyGraphs,代码行数:15,代码来源:GraphSearch.py

示例14: PooledEnqueue

# 需要导入模块: from Queue import LifoQueue [as 别名]
# 或者: from Queue.LifoQueue import get [as 别名]
class PooledEnqueue(object):
    def __init__(self, qdir, n=5, maxsize=1000*1000*1000, **qargs):
        maxsize = maxsize / n
        self.qdir = qdir
        self.write_executor = ThreadPoolExecutor(poolsize=1, queuesize=100)
        self.queues = [FileEnqueue(self.qdir, suffix=str(i),
                                   maxsize=maxsize,
                                   executor=self.write_executor,
                                   **qargs)
                       for i in range(n)]
        self.avail = LifoQueue()
        for q in self.queues:
            self.avail.put(q)
        self.addedcount = 0

    def get_status(self):
        qq = [q.get_status() for q in self.queues]
        r = dict(
            buffered=sum(s['buffered'] for s in qq),
            pending=sum(s['pending'] for s in qq),
            queues=qq)
        return r

    def _flush(self):
        for q in self.queues:
            q._flush()

    def close(self):
        for q in self.queues:
            q.close()
        self.write_executor.shutdown()

    def queue(self, curis):
        t0 = time.time()
        enq = self.avail.get()
        t = time.time() - t0
        if t > 0.1:
            logging.warn('self.avail.get() %.4f', t)
        try:
            enq.queue(curis)
            self.addedcount += len(curis)
        finally:
            t0 = time.time()
            self.avail.put(enq)
            t = time.time() - t0
            if t > 0.1:
                logging.warn('slow self.avail.put() %.4f', t)
开发者ID:kngenie,项目名称:crawlhq,代码行数:49,代码来源:pooledqueue.py

示例15: __init__

# 需要导入模块: from Queue import LifoQueue [as 别名]
# 或者: from Queue.LifoQueue import get [as 别名]
	def __init__(self,g,s):
		queue = LifoQueue()
		self.marked = {}
		self.edgeTo = {}
		self.s = s
		for v in range(1,g.vertices()+1):
			self.marked[v]=False
			self.edgeTo[v]=-1
		self.marked[s] = True
		queue.put(s)
		while not queue.empty():
			v = queue.get()
			for w in g.adj(v):
				if not self.marked[w]:
					queue.put(w)
					self.marked[w] = True
					self.edgeTo[w] = v
开发者ID:akshaydixi,项目名称:graph-works,代码行数:19,代码来源:breadthFirstPaths.py


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