def detect(self, algorithm=2, threshold=1, method=1): """Detect Boundary """ self.get_diff_queue(method) self.threshold = adaptive_threshold.calc_threshold( self.diff_queue, threshold) boundary_queue = Queue() end = { 'prev_frame': self.diff_queue.size() - 1, 'next_frame': self.diff_queue.size() - 1, 'value': 0 } boundary_queue.enqueue(end) for diff in self.diff_queue.get(): # print("{}".format(diff['value'])) if (diff['value'] >= self.threshold): print("Shot Boundary Detected : {} - {}".format( diff['prev_frame'], diff['next_frame'])) boundary_queue.enqueue(diff) start = {'prev_frame': 0, 'next_frame': 0, 'value': 0} boundary_queue.enqueue(start) list_index = self.get_list_keyframes_index(boundary_queue, algorithm) list_shots = self.get_list_shots(boundary_queue) diffs = self.diff_queue.get() diffs.reverse() self.delete_dir_content(constants.IMAGES_DIR) self.delete_dir_content(constants.SHOTS_DIR) self.save_keyframes(list_index) self.save_shots(list_shots) return list_index, diffs, self.threshold
def Algorithm1(G, basesore, sourceList): n = 0 SG = nx.MultiGraph() simqueue = Queue() for i in range(len(sourceList)): simqueue.enqueue(sourceList[i]) # while(not(simqueue.empty())): while (n < 100 and simqueue.size() < 98): # print ("这次感染队列列表有个感染点") # print (simqueue.size()) sourceItem_ = simqueue.dequeue() SG.add_node(sourceItem_) for sourceNeightor in list(G.neighbors(sourceItem_)): if G.node[sourceNeightor]['Cn'] == 0: G.node[sourceNeightor]['Scn'] += G.nodes[sourceItem_]['Scn'] G.add_node(sourceNeightor, Cn=1) SG.add_node(sourceNeightor) SG.add_edge(sourceItem_, sourceNeightor) simqueue.enqueue(sourceNeightor) n += 1 #对所有n<V(就是分数达到阕值的节点感染)算是谣言的不同之处吧。更新。 for index in range(1, 35): if G.node[index]['Scn'] > basesore: G.add_node(index, Cn=1) return G, SG
def testWaitTime(numOfStudents, duration): numOfTasks = numOfStudents * 2 ## print(numOfTasks) printQueue = Queue() aPrinter = Printer(10) waitTimeList = [] for currentSecond in range(duration): if hasTask(numOfTasks, duration): timeStamp = currentSecond ## print(timeStamp) printQueue.enqueue(Task(timeStamp)) if not aPrinter.isBusy() and not printQueue.isEmpty(): currentTask = printQueue.dequeue() aPrinter.nextTask(currentTask) waitTimeList.append(currentSecond - currentTask.timeStamp) ## print('currentSecond', currentSecond) ## print('currentTask.timeStamp', currentTask.timeStamp) ## print('currentSecond - currentTask.timeStamp', currentSecond - currentTask.timeStamp) aPrinter.timeRemain = 60 / aPrinter.ppm * currentTask.pages ## print(aPrinter.ppm) ## print('pages: {}, timeRemain: {}'.format(currentTask.pages,aPrinter.timeRemain)) if aPrinter.isBusy(): ## print(currentSecond) aPrinter.tick() if aPrinter.timeRemain <= 0: aPrinter.currentTask = None return sum(waitTimeList) / len(waitTimeList)
def bfs(start, end): """ Breadth first search. Takes a start tile and end tile, and uses their neighbour list to traverse. Uses the LIFO queue in queues.py. :param start: Tile :param end: Tile :return: came_from, dictionary with all tiles, and where we came from (parent). success, True or False. If the algorithm found the end tile or not. has_been_next, list over tiles that has been considered as the next tile. """ frontier = Queue() frontier.add(start) came_from = {start: None} success = False has_been_next = [] while not frontier.empty(): current = frontier.pop() current.visit() if current == end: print("Breadth First Search, successful.") success = True break for next_tile in current.neighbours: if next_tile not in has_been_next: has_been_next.append(next_tile) if next_tile not in came_from: frontier.add(next_tile) came_from[next_tile] = current return came_from, success, has_been_next
def test_queues(self): q = Queue() for i in range(1,100): q.push(i) self.assertEqual(99,q.size()) self.assertEqual(1,q.peek()) self.assertEqual(1,q.pop())
def test_enqueue(self): q = Queue() q.enqueue('Python') assert list(q.items) == ['Python'] # Add another item q.enqueue('Java') assert list(q.items) == ['Python', 'Java']
def test(): from random import randint students = 10 taskPerStuUpTo = 2 pagesUpTo = 20 printPeriod = 1 * 60 * 60 aPrintQueue = Queue() aPrinter = Printer(speed = 12, printQueue = aPrintQueue, printPeriod = 3600) numOfTasks = 0 for i in range(students): numOfTasks += randint(0, taskPerStuUpTo) enterTimeList = [] for i in range(numOfTasks): enterTimeList.append(randint(0, printPeriod -1)) enterTimeList.sort() lastEndTime = 0 for enterTime in enterTimeList: aTask = Task(enterTime, randint(1,pagesUpTo), lastEndTime, aPrinter.speed) aPrintQueue.enqueue(aTask) lastEndTime = aTask.endTime() ## print(aPrintQueue.size()) totalWaitTime = 0 ## print(aPrinter.printQueue.size()) ## print('isEmpty',aPrinter.printQueue.isEmpty()) ## print(aPrinter.isBusy()) while aPrinter.isBusy(): ## print(aPrinter.isBusy()) ## print(totalWaitTime) totalWaitTime += aPrinter.printQueue.dequeue().taskLastTime() return totalWaitTime / numOfTasks
def __init__(self, dataStructure): super(interactiveDataStructures, self).__init__() # rich module elements pretty.install() traceback.install() self.console = Console() # Datastructure elements availableDataStrutuces = { 'DynamicArray': DynamicArray(), 'SingleLinkedList': SinglyLinkedList(), 'DoublyLinkedList': DoublyLinkedList(), 'Stack': Stack(), 'Queue': Queue(), 'PriorityQueue': PriorityQueue() } correspondingNodes = { 'DynamicArray': None, 'SingleLinkedList': ListNode(None), 'DoublyLinkedList': ListNode(None), 'Stack': StackNode(None), 'Queue': QueueNode(None), 'PriorityQueue': PQNode(None) } if dataStructure in availableDataStrutuces: self.dataStructure = availableDataStrutuces[dataStructure] self.DSNode = correspondingNodes[dataStructure] self.DSname = dataStructure interactiveDataStructures.prompt = text.Text(f'({dataStructure}) ', style="bold magenta") # doesn't quite work else: raise ValueError(f'Please choose one of the following available data structure: {availableDataStrutuces.keys()}')
def bfs(start_tile, end_tile): """ Breadth-first search algorithm :param start_tile: Tile object, start tile of board :param end_tile: Tile object, end tile of board :return: """ queue = Queue() queue.put(start_tile) came_from = {} came_from[start_tile] = None has_been_next_tile = [] while not queue.empty(): current_tile = queue.get() current_tile.visit() if current_tile == end_tile: break for next_tile in current_tile.neighbours: if next_tile not in has_been_next_tile: has_been_next_tile.append(next_tile) if next_tile not in came_from: queue.put(next_tile) came_from[next_tile] = current_tile current_tile.visit() return came_from, has_been_next_tile
async def consume(config): queue = Queue(id=config.q) loop = asyncio.get_running_loop() await init_redis(loop) while True: await consume_queue(queue)
def test_Queue(size): # Create the queue queue = Queue(size) # Fill up the queue for i in range(size): queue.enq(i) assert queue.peek() == 0 assert queue.is_empty() == False # Check the queue is full assert queue.is_full() # Check enqueuing throws an assert with pytest.raises(AssertionError): queue.enq(0) # Empty the queue, check the order is correct for i in range(size): assert queue.deq() == i assert queue.is_full() == False # Check the queue is empty assert queue.is_empty() # Check that dequeuing throws an assert with pytest.raises(IndexError): queue.deq()
def insertInBinaryTreeUsingLevelOrder(root, data): newNode = BinaryTree(data) if root is None: root = newNode return root q = Queue() q.enqueue(root) node = None while not q.isEmpty(): node = q.dequeue() # dequeue FIFO if data == node.get_data(): return root # basically level order, insert would be where there is no left if node.left is not None: q.enqueue(node.left) else: node.left = newNode return root # if left all filled, insert right if node.right is not None: q.enqueue(node.right) else: node.right = newNode return root
def test_dequeue(self): q = Queue() q.dequeue() q.enqueue('Python') q.enqueue('Java') result = q.dequeue() assert result == 'Python' assert list(q.items) == ['Java']
def __init__(self): # once pressed, and released; keys show up in this queue self._changes = Queue(24) self.key_pressed = '' self.debug = 0 # 0..2 self.last_event_time = utime.ticks_ms()
def queues(): queue = Queue() queue.enqueue(4) queue.enqueue(40) queue.enqueue(5) queue.enqueue(3) queue.enqueue(7) print(queue)
def make_queue(): queue = Queue() queue.enqueue(23) queue.enqueue(45) queue.enqueue(58) queue.enqueue(34) queue.enqueue(45) print(f"Queue: {queue.items}")
def josephus(nameList, count): q = Queue() for name in nameList: q.enqueue(name) while q.size() > 1: for j in range(count + 1): out = q.dequeue() if j != count: q.enqueue(out) return q.dequeue()
def broadTravel(t): q=Queue() q.put(t) while q.qsize()>0: tmp=q.get() print tmp.value if tmp.left is not None: q.put(tmp.left) if tmp.right is not None: q.put(tmp.right)
def levelOrder(self): if self.size > 0: queue = Queue() queue.enqueue(self.root) while not queue.isEmpty(): print(queue.front().data) queue.dequeue() pass pass
def test_length(self): q = Queue() assert q.length() == 0 q.enqueue('A') assert q.length() == 1 q.enqueue('B') assert q.length() == 2 q.dequeue() assert q.length() == 1 q.dequeue() assert q.length() == 0
def test_front(self): q = Queue() assert q.front() is None q.enqueue('A') assert q.front() == 'A' q.enqueue('B') assert q.front() == 'A' q.dequeue() assert q.front() == 'B' q.dequeue() assert q.front() is None
def breadth_first_search(self, starting_vert): to_visit = Queue() visited = set() to_visit.enqueue(starting_vert) visited.add(starting_vert) while to_visit.size() > 0: current_vert = to_visit.dequeue() for next_vert in current_vert.get_connections(): if next_vert not in visited: visited.add(next_vert) to_visit.enqueue(next_vert)
async def test_consumer_integration(redis): async def task(): return 1 queue = Queue(id='test_queue') job = Job(queue_id=queue.id, task=task) await EnqueueJobUseCase(job).execute() result = await ConsumeQueue(queue).execute() assert result == 1
def test_dequeue(self): q = Queue(['A', 'B', 'C']) assert q.dequeue() == 'A' assert q.length() == 2 assert q.dequeue() == 'B' assert q.length() == 1 assert q.dequeue() == 'C' assert q.length() == 0 assert q.is_empty() is True with self.assertRaises(ValueError): q.dequeue()
def simulate_test(): """ Simulate behavior of one client Returns ------- current_time : int How many se """ #Creating queues, a client, and enqueueing the client print('Utworzono kolejki!') q1 = Queue(queue_type=1) q2 = Queue(queue_type=2) q3 = Queue(queue_type=3) print('Utworzono klienta!') c1 = Client(1) print('Dołączam do kolejki') q1.enqueue(c1) # max time equals 9 hours max_time = 9 * 3600 # time spent on registering current_time = c1.register_time while current_time < max_time: if current_time + c1.selection_time + 1800 > max_time: print("I won't manage to play another game, quitting...") c1.set_type(3) # find best queue q3.enqueue(c1) # wait for your turn current_time += c1.signoff_time q3.dequeue() break selection_time = c1.selection_time print("I've chosen a game in {}!".format(manage_time(selection_time))) game_time = int(np.random.normal(1800, 900)) print("I played for {}!".format(manage_time(game_time))) current_time += selection_time + game_time print("Ending within {}".format(manage_time(current_time))) return current_time
def test_enqueue(self): q = Queue() q.enqueue('A') assert q.front() == 'A' assert q.length() == 1 q.enqueue('B') assert q.front() == 'A' assert q.length() == 2 q.enqueue('C') assert q.front() == 'A' assert q.length() == 3 assert q.is_empty() is False
def __init__(self, team1, team2, player_playing_first): self.players = [ team1.player1, team2.player1, team1.player2, team2.player2 ] # Init seats self.seats = Queue() for p in self.players: self.seats.enqueue(p) # Set player who plays first next while not self.seats.peek() == player_playing_first: self.get_next_player()
def are_connected(self, person1, person2): queue = Queue() seen = set() queue.enqueue(person1) while not queue.is_empty(): current = queue.dequeue() seen.add(current) print("current:", current) print("seen:", seen) if current is person2: return True for adjacent in current.adjacent: queue.enqueue(adjacent) return False
def sumInBinaryTreeLevelOrder(root): if root is None: return 0 q = Queue() q.enqueue(root) node = None sum = 0 while not q.isEmpty(): node = q.dequeue() # dequeue FIFO sum += node.get_data() if node.left is not None: q.enqueue(node.left) if node.right is not None: q.enqueue(node.right) return sum
def create_queues(queue_type, quantity): """ Create a list of list of Queues with given quantity Parameters ---------- queue_type : int [1, 2, 3] type of the queue quantity : int number of queues to return Returns ------- list a list of Queues """ return [Queue(queue_type) for _ in range(quantity)]