Exemplo n.º 1
0
 def fill_queue(self, deque):
     while (1):
         camera = PiCamera()
         camera.framerate = 3
         camera.vflip = True
         camera.hflip = True
         camera.resolution = (2592, 1944)
         camera.exposure_mode = 'sports'
         stream = io.BytesIO()
         for i, frame in enumerate(
                 camera.capture_continuous(stream,
                                           format="jpeg",
                                           use_video_port=True)):
             stream.seek(0)
             data = np.frombuffer(stream.getvalue(), dtype=np.uint8)
             image = cv2.imdecode(data, 1)
             deque.append((datetime.now(pytz.timezone(
                 'Europe/Zurich')).strftime("%Y_%m_%d_%H-%M-%S.%f"), image))
             #deque.pop()
             print("Quelength: " + str(len(deque)) + "\tStreamsize: " +
                   str(sys.getsizeof(stream)))
             if i == 60:
                 print("Loop ended, starting over.")
                 camera.close()
                 break
Exemplo n.º 2
0
    def append(self,x):
        h = None
	if len(self)>0:
	    h = self[0]
	deque.append(self, x)
	if ( len(self)>0 and h!=self[0] ):
	    self[0].handle_head_of_queue()
Exemplo n.º 3
0
def isCousins(root, x, y):
    # same depth but diff parents
    que = deque()
    deque.append(root)
    while que is not None:
        sib, cousin = False, False
        size = len(que)
        for i in range(size):
            node = que.popleft()
            if node is None:
                sib = False
            else:
                if node.left == x or node.right == y:
                    if not cousin:
                        sib, cousin = True, True
                    else:
                        return not sib
            if node.left:
                que.append(node.left)
            if node.right:
                que.append(node.right)
            que.append(None)
        if cousin:
            return False
        return False
Exemplo n.º 4
0
 def insert(q, n, item):
     if n == len(q):
         deque.append(q, item)
     else:
         q.rotate(-(n + 1))
         q.appendleft(item)
         q.rotate(n + 1)
Exemplo n.º 5
0
    def append(self, item):

        if len(self) > self.maxdepth:
            raise DeepReferenceError("Formula chain exceeded the %s limit" %
                                     self.maxdepth)
        deque.append(self, item)
        self.counter += 1
Exemplo n.º 6
0
def task_events(interval, deque, times, index, rectangles, workers, last_seen):
    i = 0
    with log_errors():
        stream = yield eventstream('%(host)s:%(tcp-port)d' % options, 0.100)
        while True:
            try:
                msgs = yield read(stream)
            except StreamClosedError:
                break
            else:
                if not msgs:
                    continue

                last_seen[0] = time()
                for msg in msgs:
                    if 'compute_start' in msg:
                        deque.append(msg)
                        times.append(msg['compute_start'])
                        index.append(i)
                        i += 1
                        if msg.get('transfer_start') is not None:
                            index.append(i)
                            i += 1
                        if msg.get('disk_load_start') is not None:
                            index.append(i)
                            i += 1
                        task_stream_append(rectangles, msg, workers)
Exemplo n.º 7
0
def task_events(interval, deque, times, index, rectangles, workers, last_seen):
    i = 0
    try:
        stream = yield eventstream('%(host)s:%(tcp-port)d' % options, 0.100)
        while True:
            msgs = yield read(stream)
            if not msgs:
                continue

            last_seen[0] = time()
            for msg in msgs:
                if 'startstops' in msg:
                    deque.append(msg)
                    count = task_stream_append(rectangles, msg, workers)
                    for _ in range(count):
                        index.append(i)
                        i += 1

    except StreamClosedError:
        pass  # don't log StreamClosedErrors
    except Exception as e:
        logger.exception(e)
    finally:
        try:
            sys.exit(0)
        except:
            pass
Exemplo n.º 8
0
def maxSlidingWindow3(nums: List[int], k: int) -> List[int]:
    '''
    法三
    :param nums:
    :param k:
    :return:
    '''
    from collections import deque
    # deque 是一个单调递减的队列,队首元素始终是当前窗口的最大值
    if not nums or k == 0: return []
    deque = deque()
    res = []
    n = len(nums)
    # 窗口未形成前
    for i in range(k):
        while deque and nums[i] >= deque[-1]:
            deque.pop()
        deque.append(nums[i])
    res.append(deque[0])

    # 窗口形成后
    for i in range(k, n):
        if deque[0] == nums[i - k]:
            deque.popleft()
        while deque and nums[i] >= deque[-1]:
            deque.pop()
        deque.append(nums[i])
        res.append(deque[0])
    return res
Exemplo n.º 9
0
 def dijkstra():
     COST = [[1e4]*m for _ in range(n)]
     COST[0][0] = 0
     deque = [(0, 0)]
 
     while True:
         x, y = deque.pop(0) 
         if x == m-1 and y == n-1:
             return COST[n-1][m-1]
 
         cost = COST[y][x]
         for x, y in [(x, y-1), (x-1, y), (x+1, y), (x, y+1)]:
             if not (0 <= x < m and 0 <= y < n):
                 continue
 
             is_wall = status[y][x] == '1'
             new_cost = cost + (1 if is_wall else 0)
 
             if COST[y][x] <= new_cost:
                 continue
 
             COST[y][x] = new_cost
             if is_wall:
                 deque.append((x, y))
             else:
                 deque.insert(0, (x, y))
Exemplo n.º 10
0
def bfs (flow,source,target):
    """Pre: El flujo por el cual estoy pasando en ese momento, lo dequeue dequeuiere decir
    es no perder la ruta y no visitar rutas no adecuadas
    Pos: si en caso no encontre un camino hasta el fin del grafo, retorna false
    si en cado caso SI llego al target, pues existe un camino seguro para llegar
    """
    
    global rta, n, m
    p = [[]for i in range(m+n+2)];deque = [];deque.append(source)
    visitados = [0 for i in range(m+n+2)]
    while deque:
        vertex = deque.pop(0)
        for v in range(m+n+2):
            #pilas con el flujo, tiene que ser mayor a 0 y no haberlo visitado nunca
            if not visitados[v] and (rta[vertex][v]-flow[vertex][v] > 0) :
                lineadeataque = p[vertex][:]
                lineadeataque.append((vertex,v))
                p[v] = lineadeataque
                visitados[v] = 1
                
                if v == target: return p[v]
                #agregar la v a la cola
                deque.append(v)
                
    return False
Exemplo n.º 11
0
def deque_update(deque):
    if deque[0].isDead():
        left = deque[-1].get_right()
        top = deque[-1].get_top()
        temp = deque.popleft()
        temp.update(left, top)
        deque.append(temp)
 def maxSlidingWindow(self, nums, k):
     # write your code here
     from collections import deque
     
     if k == 0 or len(nums) < k:
         return []
         
     res = []
     deque = deque([])
     
     for i in range(k):
         while deque and nums[i] > nums[deque[-1]]:
             deque.pop()
         deque.append(i)
             
     for i in range(k, len(nums)):
         res.append(nums[deque[0]])
         if i - deque[0] == k: 
             deque.popleft()
         while deque and nums[i] > nums[deque[-1]]:
             deque.pop()
         deque.append(i)
     res.append(nums[deque[0]])    
     
     return res
Exemplo n.º 13
0
def findMinHeightTrees( n, edges):
    if n <= 2:
        return [i for i in range(n)]
    in_degrees = [0] * n
    res = [True] * n
    adjs = defaultdict(list)
    for edge in edges:
        in_degrees[edge[0]] += 1
        in_degrees[edge[1]] += 1
        adjs[edge[0]].append(edge[1])
        adjs[edge[1]].append(edge[0])
    from collections import deque
    deque = deque()

    for i in range(n):
        if in_degrees[i] == 1:
            deque.append(i)
    while n > 2:
        size = len(deque)
        n -= size
        for i in range(size):
            top = deque.popleft()
            res[top] = False

            successors = adjs[top]
            successors.append(top)

            for item in successors:
                in_degrees[item] -= 1

                if in_degrees[item] == 1:
                    deque.append(item)

    return [i for i in range(len(res)) if res[i]]
 def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
     """
     思路:
     1. 暴力方法:一重循环遍历左侧起始位置,然后向右遍历k个位置,期间更新最大值
                 时间复杂度O(n * k)
     2. 高效思路:由于滑动窗口,右侧添加元素,左侧弹出元素,所以可以使用队列模拟
                 如果窗口内出现[a, b] b < a 的情况,那么向右滑动时a总是无效的
                 因此需要弹出a,添加b,由此形成了类似于单调递减栈的结构
                 由于左侧只有弹出,由于存在弹出和添加两种情况,因此使用双端队列
                 并且队列保存单调递减,左侧总是max
     """
     from collections import deque
     ret, deque = list(), deque()
     for i in range(len(nums)):
         # 维护队列的单调递减特性
         while deque and nums[deque[-1]] < nums[i]:
             deque.pop()
         # 添加当前元素
         deque.append(i)
         # 弹出头部元素
         if i - deque[0] >= k:
             deque.popleft()
         # 添加到结果中
         if i >= k - 1:
             ret.append(nums[deque[0]])
     return ret
Exemplo n.º 15
0
    def get_current_hash_rate(self, deque: Deque[WeightValue],
                              total_weight: float, fn: Callable[[], None],
                              interval: int) -> float:
        """ Calculate new hash rate and schedule next call

            :param deque: deque to get first and last hash rate values
            :type deque: deque[WeightValue]

            :param total_weight: total weight of blocks/txs
            :type total_weight: float

            :param fn: method to be called in the scheduler
            :type fn: function

            :param interval: interval (in seconds) for the next method call
            :type interval: int

            :return: new hash rate
            :rtype: float
        """
        deque.append(WeightValue(self.reactor.seconds(), total_weight))

        last = deque[-1]
        first = deque[0]
        if first.time == last.time:
            hash_rate = 0.0
        else:
            hash_rate = (2**sub_weights(
                last.value, first.value)) / (last.time - first.time)

        if self.is_running:
            self.reactor.callLater(interval, fn)

        return hash_rate
Exemplo n.º 16
0
def gcd(a_, b_):
    deque = [(a_, b_)]

    while deque:
        item = deque[-1]
        X = MEMO

        if item in MEMO:
            result = MEMO[item]
            while deque:
                item = deque.pop()
                MEMO[item] = result
            return result

        a, b = item
        if a == 0 or b == 0:
            MEMO[(a, b)] = 0

        if a == b:
            MEMO[(a, b)] = a
            continue

        # a is greater
        if a > b:
            deque.append((a - b, b))
            continue

        deque.append((a, b - a))

    return MEMO[(a_, b_)]
Exemplo n.º 17
0
def BFS(visited, deque, board):
    global answer
    while deque:
        x, y, direc, result = deque.popleft()
        if result >= answer:
            continue
        if x == len(board) - 1 and y == len(board) - 1:
            answer = min(answer, result)
            continue
        # print("(",x,",", y,")","방향:", direc,"금액", result)
        # for line in visited:
        #     print(line)
        for mode in range(4):
            xx = x + dx[mode]
            yy = y + dy[mode]
            new_direc = mode
            if isWall(xx, yy, len(board)):
                continue
            if board[xx][yy]:
                continue
            if new_direc != direc:
                new_result = result + 600
            else:
                new_result = result + 100
            if 0 < visited[xx][yy][0] <= new_result:
                continue
            
            visited[xx][yy][0] = new_result

            deque.append((xx, yy, new_direc, new_result))
Exemplo n.º 18
0
def task_events(interval, deque, times, index, rectangles, workers, last_seen):
    i = 0
    try:
        stream = yield eventstream('%(host)s:%(tcp-port)d' % options, 0.100)
        while True:
            msgs = yield read(stream)
            if not msgs:
                continue

            last_seen[0] = time()
            for msg in msgs:
                if 'compute_start' in msg:
                    deque.append(msg)
                    times.append(msg['compute_start'])
                    index.append(i)
                    i += 1
                    if msg.get('transfer_start') is not None:
                        index.append(i)
                        i += 1
                    if msg.get('disk_load_start') is not None:
                        index.append(i)
                        i += 1
                    task_stream_append(rectangles, msg, workers)
    except StreamClosedError:
        pass  # don't log StreamClosedErrors
    except Exception as e:
        logger.exception(e)
    finally:
        try:
            sys.exit(0)
        except:
            pass
Exemplo n.º 19
0
 def overfull_append(self, item):
     """
       Append from right and pop leftest item
       (RingBuffer if «overfull»).
     """
     deque.append(self, item)
     # full, pop the oldest item, left most item
     self.popleft()
Exemplo n.º 20
0
 def append(self, msg):
     seq = msg.get_header_field_value(msg.fix.MsgSeqNum)
     if not len(self):
         deque.append(self, msg)
     else:
         if self.last + 1 != seq:
             raise OutOfSequenceException("%s vs %s" % (seq, self.last + 1))
     self.last = seq
Exemplo n.º 21
0
    def __init__(self, query):
        graph = [[] for i in range(N)]
        dist = [{} for i in range(N)]
        # 0-index
        for x, y, z in query:
            graph[x].append(y)
            graph[y].append(x)
            dist[x][y] = z
            dist[y][x] = z

        self.graph = graph
        self.dist = dist
        # トポロジカルソート Rに収納する
        P = [-1] * N
        Q = deque([0])
        R = []
        while Q:
            i = deque.popleft(Q)
            R.append(i)
            for a in self.graph[i]:
                if a != P[i]:
                    P[a] = i
                    self.graph[a].remove(i)
                    deque.append(Q, a)

        ##### Settings #####
        self.unit = 0
        self.merge = lambda a, b: max(a, b)
        self.adj_bu = lambda a, i: a + dist[i][P[i]]
        self.adj_td = lambda a, i, p: a + dist[i][P[i]]
        self.adj_fin = lambda a, i: a
        ####################

        # 順向きのものの答え ME
        ME = [self.unit] * N  # resの暫定値
        XX = [0] * N  # ME + 親要素に伸びる辺の重み
        for i in R[1:][::-1]:  # 根以外について逆順に辿る bottom-up
            XX[i] = self.adj_bu(ME[i], i)  # resの更新
            p = P[i]  # 親pを取り出す
            ME[p] = self.merge(ME[p], XX[i])  # dpの累積を更新する
        XX[R[0]] = self.adj_fin(ME[R[0]], R[0])

        TD = [self.unit] * N
        for i in R:  # 根から順にたどる
            # 左からDP(結果はTDに入れている)
            ac = TD[i]
            for j in self.graph[i]:  # 元々の親要素も含めた全ての子要素を順番に
                TD[j] = ac  # 累積したものをTDに入れる
                ac = self.merge(ac, XX[j])  # マージする
            # リセットして右からDP(結果はacに入れている)
            ac = self.unit
            for j in self.graph[i][::-1]:  # 逆順に
                # TDに残っている左から累積した分とacにある右から累積した分をTDにマージ
                TD[j] = self.adj_td(self.merge(TD[j], ac), j, i)
                ac = self.merge(ac, XX[j])  # acの累積更新 # 逆向きにマージしていく
                # レコード 順向きのものME[j]と逆向きのものをマージする
                XX[j] = self.adj_fin(self.merge(ME[j], TD[j]), j)
        self.res = XX
Exemplo n.º 22
0
def deque_process(n):
    for i in range(1, n + 1):
        deque.append(i)

    while len(deque) != 1:
        a = deque.popleft()
        deque.rotate(-1)

    print(deque.popleft())
Exemplo n.º 23
0
 def append(self, item):
     """
     Append item.
     If RingBuffer is full, switch to «overfull» mode.
     """
     deque.append(self, item)
     if len(self) == self.size:
         #If RingBuffer is full, switch to «overfull» mode.
         self.append = self.overfull_append
Exemplo n.º 24
0
def bfs(queue):
  while len(queue):
    node = queue.popleft()
    process(node)
    
    if node.left:
      queue.append(node.left)
    if node.right:
      queue.append(node.right)
Exemplo n.º 25
0
 def emit(self, record):
     deque = self.deque
     with self:
         if record.name not in self.categories:
             self.categories.add(record.name)
             app_state.app.new_category.emit(record.name)
         deque.append(record)
         if len(deque) > self.max_records:
             deque.popleft()
     app_state.app.new_log.emit(record)
Exemplo n.º 26
0
def past_moving_average(deque, elem, n=moving_average_window_size):

    ## Just at start when we don't have enough data
    if (len(deque) < n):
        deque.append(elem)
        return elem

    deque.popleft()
    deque.append(elem)
    return sum(deque) / n
Exemplo n.º 27
0
def reciever():
    global message
    while True:
        msg = pickle.loads(client.recv(4096))

        if msg[0] == 10:
            print("Match match made with", msg[1])
            t = input("Accept?[y/n]").lower()
            client.send(pickle.dumps([9, t]))
        else:
            deque.append(msg)
Exemplo n.º 28
0
 def BFS(self, start_node):
     queue = deque()
     deque.append(queue, start_node)
     while queue:
         node = queue.popleft()
         for adjnode in self.vertexs[node].adjacent.keys():
             if self.vertexs[adjnode].color is 'White':
                 self.vertexs[adjnode].color = 'Grey'
                 deque.append(queue, adjnode)
         self.vertexs[node].color = 'Black'
         print node, self.vertexs[node]
Exemplo n.º 29
0
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
    # 维持从大到小的队列,保证deque[0]为窗口内最大值的索引
    from collections import deque
    deque, res = deque(), []
    for index, value in enumerate(nums):
        if deque and deque[0] <= index - k:
            deque.popleft()
        while deque and nums[deque[-1]] < value:
            deque.pop()
        deque.append(index)
        if index >= k - 1:
            res.append(nums[deque[0]])
    return res
 def levelOrder(self, root: TreeNode) -> List[List[int]]:
     if not root: return []
     deque, res = collections.deque([root]), []
     while deque:
         tmp = collections.deque()
         for _ in range(len(deque)):
             node = deque.popleft()
             if len(res)%2: tmp.appendleft(node.val)
             else: tmp.append(node.val)
             if node.left: deque.append(node.left)
             if node.right: deque.append(node.right)
         res.append(list(tmp))
     return res