Example #1
0
def main():
    my = Queue()
    while 1:
        command = input("Add, Serve, or Exit:")
        if command == "Add":
            print("%s"%my.size())
            if my.size() > 2:
                print ("You cannot add more people, the lineup is full!")
            else:
                name = input("enter the name of the person to add:")
                my.queue(name)
        
        if command == "Serve":
            if my.is_empty():
                print("the lineup is already empty")
            else:
                print("%s has beed served"%my.dequeue())
        if command == "Exit":
            import sys
            sys.exit(0)
    def normalize_graph(self,
                        graph: nx.DiGraph,
                        verbose: bool = False) -> nx.DiGraph:
        graph = graph.copy()

        unvisited_nodes = Queue()
        unvisited_nodes.queue = deque(graph.nodes.keys())

        # init: dependencies parsing & POS
        for node_id in unvisited_nodes.queue:
            node = graph.nodes[node_id]
            prepare_node(self.parser, node)

        # decomposition rules
        def run_rules(node_id, is_use_preserved=True):
            is_decomposed = False
            for rule in self.rules:
                preserved_tokens = None
                if is_use_preserved:
                    # todo: preserved words just for no-operational?
                    preserved_tokens = self._preserved_tokens  #if (not isinstance(rule, op_norm_rules.OperationDecomposeRule)) else None
                decomposed, added_nodes_ids = rule.decompose(
                    node_id, graph, preserved_tokens=preserved_tokens)
                if decomposed:
                    for id in added_nodes_ids:
                        unvisited_nodes.put(id)
                    is_decomposed = True
                    if verbose:
                        copy = graph.copy()
                        self._update_labels_from_doc(graph=copy)
                        _logger.info(
                            f"{rule}{' -reserved' if is_use_preserved else ''} (node: {node_id})\t{Decomposition.from_graph(graph=copy).to_string()}"
                        )
            return is_decomposed

        while not unvisited_nodes.empty():
            node_id = unvisited_nodes.get()
            run_rules(node_id, is_use_preserved=True)
            run_rules(node_id, is_use_preserved=False)

        # update "label" from "doc" if needed
        self._update_labels_from_doc(graph=graph)

        # re-order operation chain
        self.reorder_operations(graph)

        # re-order graph alphabetically
        self.reorder(graph)

        # todo: reorder args: intersection, union, ... args order
        return graph
Example #3
0
    def breadth_first(self):
        """A breadth-first traversal of the binary search tree."""
        nodes = Queue()
        if self.head:
            nodes.queue(self.head)

        while(nodes.size()):
            node = nodes.dequeue()
            if node.left:
                nodes.queue(node.left)
            if node.right:
                nodes.queue(node.right)

            yield node.value
Example #4
0
def action(args):
    # Check the factor
    assert args.factor is not None, "Augmentation Factor can't be None"
    assert args.factor >= 1, "Augmentation Factor can't be less than 1"
    # Check the workers
    assert args.workers is not None, "Workers can't be None"
    assert args.workers >= 1, "Workers can't be less than 1"
    # Check the Input path
    print(os.path.abspath(args.input_dataset))
    assert os.path.exists(args.input_dataset), "Input path doesn't exist"
    assert os.path.isdir(args.input_dataset), "Input path must be a folder"
    # Check the Output path
    assert not os.path.exists(args.output), "Output path already exist"

    # Take the arguments params.
    augmentation_factor: int = args.factor

    path_input: str = args.input_dataset
    path_output: str = args.output

    # Set the max workers
    max_workers = args.workers * 5

    # Get the list of images
    images = get_images_paths(path=path_input)

    # Create the queue of jobs and the progress object
    queue_images = Queue()
    queue_images.queue = deque(images)
    progress = tqdm(total=queue_images.qsize(),
                    position=0,
                    desc="Executing...")

    # Create the ThreadPoolExecutor and and submit the jobs.
    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        for i in range(max_workers):
            executor.submit(execute_augmentation, queue_images, progress,
                            path_output, augmentation_factor)

    # Shutdown the executor waiting till the jobs are done
    executor.shutdown(wait=True)
Example #5
0
    def run(self):
        output = []
        q = Queue()
        node = self.head
        q.queue((node, 0))
        while (q.is_empty()):
            node, level = q.dqueue()
            if node.left:
                q.queue((node.left, level + 1))
            if node.right:
                q.queue((node.right, level + 1))

            output.append((node.data, level))

        return output
Example #6
0
def create_simple_queue(initial_items):
    queue = Queue()
    queue.queue = deque(initial_items)
    queue.unfinished_tasks = len(queue.queue)
    return queue
Example #7
0
import sys
from queue import Queue
from collections import deque

sys.setrecursionlimit(10**6)
readline, write = (sys.stdin.readline, sys.stdout.write)

n = int(readline())
graph = [[] for _ in range(n + 1)]
for _ in range(n - 1):
    frm, to = [int(i) for i in readline().split()]
    graph[frm].append(to)
    graph[to].append(frm)
order = Queue()
order.queue = deque([int(i) for i in readline().split()])
vst = [False] * (n + 1)


def print_zero_and_exit():
    write("0")
    exit(0)


def trace(now_node):
    next_nodes = set()
    for next_node in graph[now_node]:
        if vst[next_node]:
            continue
        vst[next_node] = True
        next_nodes.add(next_node)
    while next_nodes:
Example #8
0
def play_recursive_game(deck1, deck2):
    round = 1
    prev_hands_1 = []
    prev_hands_2 = []

    while deck1.qsize() > 0 and deck2.qsize() > 0:
        # print("\n \n")
        # print(f"Playing round {round}")
        round += 1
        # print(f"Player 1 deck: {deck1.queue}")
        # print(f"Player 2 deck: {deck2.queue}")
        card1 = deck1.get()
        card2 = deck2.get()
        # print(f"Player 1 plays: {card1}")
        # print(f"Player 2 plays: {card2}")
        winner = 0
        for hand in prev_hands_1:
            if hand == deck1.queue:
                # win player 1
                print("Hand identical for player 1, player 1 wins")
                winner = 1
                break


        for hand in prev_hands_2:
            if hand == deck2.queue:
                # win player 1
                # print("Hand identical for player 2, player 1 wins")
                winner = 1
                break

        if winner == 0:
            prev_hands_1.append(deck1.queue.copy())
            prev_hands_2.append(deck2.queue.copy())
        else:
            deck1.put(card1)
            deck1.put(card2)
            continue


        if deck1.qsize() >= card1 and deck2.qsize() >= card2:
            # print("Playing sub-game to determine winner!")
            deck1_copy = Queue()
            deck2_copy = Queue()
            deck1_copy.queue = deck1.queue.copy()
            deck2_copy.queue = deck2.queue.copy()
            _, _, winner = play_recursive_game(deck1_copy, deck2_copy)
        elif card1 > card2:
            # print("Player 1 wins!")
            winner = 1

        else:
            # print("Player 2 wins!")
            winner = 2

        if winner == 1:
            deck1.put(card1)
            deck1.put(card2)
        else:
            deck2.put(card2)
            deck2.put(card1)

    if deck1.qsize() > 0:
        return deck1, deck2, 1
    else:
        return deck1, deck2, 2
def load_queue(l):
    q = Queue()
    q.queue = q.queue.__class__(l)
    return q
Example #10
0
def regexToPost(regExpPreConverted):
    """ Converts an infix regular expression to postfix """

    regExp = insertConcats(regExpPreConverted)
    regExp.reverse()  # top of stack at end of list

    outputQueue = Queue()
    opStack = []
    ops = [CONCAT_MARKER, ord("|"), ord("?"), ord("*"), ord("+")]
    prec = {
        CONCAT_MARKER: 1,
        ord("|"): 0,
        ord("?"): 2,
        ord("*"): 2,
        ord("+"): 2,
        ord("("): -1,
        ord("{"): 1.5
    }
    escapes = {
        97: 7,
        34: 34,
        102: 12,
        39: 39,
        98: 8,
        110: 10,
        114: 13,
        116: 9,
        118: 11,
        92: 92
    }

    while regExp:
        token = regExp.pop()

        if token == ord("\\"):
            nextToken = regExp.pop()

            # Check for character classes, otherwise escape the character
            if nextToken == ord("w"):
                regExp += [93, 95, 57, 45, 48, 122, 45, 97, 90, 45, 65, 91]

            elif nextToken == ord("s"):
                regExp += [93, 12, 10, 13, 9, 32, 91]

            elif nextToken == ord("d"):
                regExp += [93, 57, 45, 48, 91]

            elif nextToken == ord("W"):
                regExp += [93, 95, 57, 45, 48, 122, 45, 97, 90, 45, 65, 94, 91]

            elif nextToken == ord("S"):
                regExp += [93, 12, 10, 13, 9, 32, 94, 91]

            elif nextToken == ord("D"):
                regExp += [93, 57, 45, 48, 94, 91]

            else:
                # TODO: parsing of octal and hex characters
                outputQueue.put(ord("\\"))
                outputQueue.put(escapes.get(nextToken, nextToken))

        elif token in ops:  # doesn't treat like a single unit
            while opStack and prec[opStack[-1]] >= prec[token]:
                outputQueue.put(opStack.pop())
            opStack.append(token)

        elif token == ord("("):
            try:
                if regExp[-1] == ord(")"):
                    regExp.pop()
                    outputQueue.put(EPS_MARKER)
                elif regExp[-1] == ord("?"):
                    try:
                        if (regExp[-2], regExp[-3],
                                regExp[-4]) == (CONCAT_MARKER, ord("i"),
                                                ord(")")):
                            outputQueue.put(CASE_INSENSITIVE)
                            regExp.pop()  # 1
                            regExp.pop()  # ?
                            regExp.pop()  # i
                            regExp.pop()  # )
                            regExp.pop()  # 1
                        else:
                            opStack.append(token)
                    except IndexError:
                        opStack.append(token)
                else:
                    opStack.append(token)
            except IndexError:
                raise ReSyntaxError("Mismatched left paren")

        elif token == ord(")"):
            try:
                while opStack[-1] != ord("("):
                    outputQueue.put(opStack.pop())
                opStack.pop()
            except IndexError:
                raise ReSyntaxError("Misatched right paren")

        elif token == ord("{"):
            while opStack and prec[opStack[-1]] >= prec[token]:
                outputQueue.put(opStack.pop())
            outputQueue.put(ord("{"))

            #  Collect the rest of the repetition count
            n = 0
            while True:

                nextToken = regExp.pop()
                if nextToken >= 48 and nextToken <= 57:
                    n = n * 10 + nextToken - 48
                elif nextToken == ord(","):
                    outputQueue.put(-n)  # A horrible hack...
                    n = 0
                    outputQueue.put(nextToken)
                elif nextToken == ord("}"):
                    if n != 0:
                        outputQueue.put(-n)
                    outputQueue.put(nextToken)
                    break

        elif token == ord("["):
            outputQueue.put(token)
            # Parse into rpn
            hyphenFound = False
            while True:
                try:
                    nextToken = regExp.pop()

                    # TODO: Should be able to parse literal "]"
                    if nextToken == ord("-"):
                        hyphenFound = True

                    elif nextToken == ord("]"):
                        if hyphenFound:
                            outputQueue.put(ord("-"))
                        outputQueue.put(nextToken)
                        break

                    elif nextToken == ord("\\"):
                        try:
                            #  TODO: Create negative character classes inside character classes
                            escapedCharacter = regExp.pop()
                            if escapedCharacter == ord("]"):
                                outputQueue.put(
                                    ESCAPED_SQUARE
                                )  # Will be dealt with when building character classes
                            elif escapedCharacter == ord("w"):
                                regExp += [
                                    95, 57, 45, 48, 122, 45, 97, 90, 45, 65
                                ]
                            elif escapedCharacter == ord("s"):
                                regExp += [12, 10, 13, 9, 32]
                            elif escapedCharacter == ord("d"):
                                regExp += [57, 45, 48]
                            else:
                                outputQueue.put(
                                    escapes.get(escapedCharacter,
                                                escapedCharacter))

                        except IndexError:
                            raise ReSyntaxError(
                                "Inappropriate escaped bracket")

                    else:
                        outputQueue.put(nextToken)
                        if hyphenFound:
                            outputQueue.put(ord("-"))
                            hyphenFound = False
                except IndexError:
                    raise ReSyntaxError("Mismatched [")

        else:
            outputQueue.put(token)

    while opStack:
        outputQueue.put(opStack.pop())

    output = outputQueue.queue()
    output.reverse()
    return output  # Python views the top of the stack
Example #11
0
class TicTacToe:
    def __init__(self):
        self.__grid = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]
        self.__player = 1
        self.__turn = 0
        self.__history = Queue(9)

    def get_player(self):
        return self.__player

    def get_turn(self):
        return self.__turn

    def get_box(self, line, column):
        return self.__grid[line][column]

    def reset_grid(self):
        self.__grid = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]

    def reset_player(self):
        self.__player = 1

    def change_player(self):
        if self.__player == 1:
            self.__player = 2
        else:
            self.__player = 1

    def play(self, line, column):
        """verifies if the player's line and column can be placed in the grid"""
        if line > 3 or line < 1 or column > 3 or column < 1:
            return False
        if self.__grid[line - 1][column - 1] != '-':
            return False
        if self.__player == 1:
            self.__grid[line - 1][column - 1] = 'X'
        else:
            self.__grid[line - 1][column - 1] = 'O'
        self.__turn += 1
        Move = CMove()
        Move.set_Move(self.__player, line, column)
        self.__history.queue(Move)
        return True

    def end_condition(self):
        """win conditions"""
        for i in range(3):
            if self.__grid[i][0] == self.__grid[i][1] == self.__grid[i][
                    2] != '-':
                return True
        for i in range(3):
            if self.__grid[0][i] == self.__grid[1][i] == self.__grid[2][
                    i] != '-':
                return True
        if self.__grid[0][0] == self.__grid[1][1] == self.__grid[2][2] != '-':
            return True
        if self.__grid[0][2] == self.__grid[1][1] == self.__grid[2][0] != '-':
            return True
        return False

    def replay(self):
        """replay the game"""
        actual_move = self.__history.dequeue()
        self.play(actual_move.get_line(), actual_move.get_column())
Example #12
0
# -*- coding:utf-8 -*-
"""---------------------- 
    author: Rainbow
    time: 2018/03/28/21/9:05 PM
    Description:
    
    ----------------------"""
import requests
from bs4 import BeautifulSoup
import threading
import time
from queue import Queue

_DATA = []
FILE_LOCK = threading.Lock()
SHARE_Q = Queue.queue()  # 构造一个不限制大小的队列
_WORKING_THREAD_NUM = 3


class MyThread(threading.Thread):
    def __init__(self, func):
        super(MyThread, self).__init__()  # 调用父类的构造函数
        self.func = func  # 传入线程函数逻辑

    def run(self):
        self.func()


def get_page(url):
    try:
        my_page = requests.get(url).text