Esempio n. 1
0
    def __init__ (self, pusher_stream="pox"):
        core.addListeners(self)
        core.openflow.addListeners(self)
        self.stream = pusher_stream

        self.stopStatsThread = Event()
        self.syncThread = TimerThread(self.stopStatsThread, request_stats, STAT_SAMPLING_PERIOD)
        self.syncThread.start()
Esempio n. 2
0
 def new_game(self):
     self.timer_thread.stop_thread()
     self.timer_text.set("time: 00:00")
     self.round_number = 0
     self.guess_history = []
     self.l.delete(0, END)
     self.answer_number = self.create_number()
     del self.timer_thread
     self.timer_thread = TimerThread(self.update_time)
     self.timer_thread.start()
     self.input_number.set('')
Esempio n. 3
0
class GuessGame():
    top = tk.Tk()
    btn_width = 5
    btn_borderwidth = 5
    ft = font.Font(size=15)
    element_column = 5
    l = None
    input = None
    answer_number = None
    round_number = 0
    guess_history = []
    timer_label = None
    timer_text = StringVar()
    timer_thread = None
    end_round = 10
    leader_board = LeaderBoard()
    current_second = 0

    def __init__(self):
        self.answer_number = self.create_number()
        # 開始Timer thread 物件
        self.timer_thread = TimerThread(self.update_time)
        self.current_second = 0
        self.input_number = StringVar()

    # 產生隨機不重複的4位數
    def create_number(self):
        num = str(randint(0, 9))
        while num == "0":
            num = str(randint(0, 9))
        while True:
            number = str(randint(0, 9))
            if str(number) not in num:
                num += number
            if len(num) == 4:
                return num

    def show_number_window(self):
        self.l.insert('end', "Answer: {}".format(self.answer_number))
        self.l.yview(END)

    def exit_game(self):
        self.top.destroy()

    '''
        新遊戲開始會重設所有必要參數
        如果遊戲輸了,則顯示信息。
    '''

    def new_game(self):
        self.timer_thread.stop_thread()
        self.timer_text.set("time: 00:00")
        self.round_number = 0
        self.guess_history = []
        self.l.delete(0, END)
        self.answer_number = self.create_number()
        del self.timer_thread
        self.timer_thread = TimerThread(self.update_time)
        self.timer_thread.start()
        self.input_number.set('')

    def lose_game(self, time=0, rounds=0, message="You lose!"):
        d = MyDialog(self.top, self, message, self.leader_board, rounds, time)
        self.top.wait_window(d.top)

    # 將秒數轉換為分鐘與秒,並更新計時器的label
    def update_time(self, time):
        second = time % 60
        minute = int(time / 60)
        self.current_second = time
        self.timer_text.set("time: {:02d}:{:02d}".format(minute, second))

    def run_game(self):
        guess_num = str(self.input.get())
        if guess_num == "":
            return
        has_error = False
        '''
            檢測error 並推送到List 上
        '''
        if len(guess_num) != 4:
            self.l.insert(
                'end',
                "{}   Invalid input!!! (length error) ".format(guess_num))
            has_error = True
        if len(set(guess_num)) != len(guess_num):
            self.l.insert(
                'end',
                "{}   Invalid input!!! (character repeat) ".format(guess_num))
            has_error = True
        if guess_num.isdigit() is False:
            self.l.insert(
                'end',
                "{}   Invalid input!!! (character error) ".format(guess_num))
            has_error = True
        if guess_num in self.guess_history:
            self.l.insert(
                'end', "{}   You guess this number before try again!!!".format(
                    guess_num))
            has_error = True
        '''
            如果沒有錯誤就執行這一小段
        '''
        if has_error is False:
            self.round_number += 1
            count = [0, 0]
            if guess_num == self.answer_number:
                self.l.insert('end',
                              "{}   You guess it right!!".format(guess_num))
                self.l.insert('end', "{}".format(self.timer_text.get()))
                self.l.yview(END)
                self.timer_thread.stop_thread()
                self.lose_game(self.current_second,
                               self.round_number,
                               message="You win!")
                return
            '''
                 計算判斷數字的重複與重疊數
            '''
            for c, character in enumerate(list(guess_num)):
                for g, character2 in enumerate(list(self.answer_number)):
                    if g == c and character == character2:
                        count[0] += 1
                    elif character == character2:
                        count[1] += 1
            self.l.insert(
                'end', "Round{} {} {}A{}B".format(self.round_number, guess_num,
                                                  count[0], count[1]))
            self.guess_history.append(guess_num)
            if self.round_number >= self.end_round:
                self.l.insert(
                    'end', "You lose! Answer: {}".format(self.answer_number))
                self.timer_thread.stop_thread()
                self.lose_game()
        self.input.delete(0, END)
        self.l.yview(END)

    '''

    '''

    def create_ui(self):
        frame = Frame(self.top)
        frame.pack()
        self.timer_label = Label(frame,
                                 text="time: 00:00",
                                 textvariable=self.timer_text)
        self.timer_label.pack()
        title = Label(frame, text="Welcome to Number Game")
        title.pack()
        self.input = Entry(frame, textvariable=self.input_number, bd=1)
        self.input.pack()
        Button(frame, text="Run", font=self.ft, command=self.run_game).pack()
        self.l = Listbox(frame, height=20, width=100)
        self.l.pack()
        Button(frame,
               text="Show Answer",
               borderwidth=self.btn_borderwidth,
               font=self.ft,
               command=self.show_number_window).pack()
        Button(frame,
               text="New Game",
               borderwidth=self.btn_borderwidth,
               font=self.ft,
               command=self.new_game).pack()
        Button(frame,
               text="Exit",
               borderwidth=self.btn_borderwidth,
               font=self.ft,
               command=self.exit_game).pack()

        self.l.yview(END)

        self.timer_thread.start()
        return self.top
Esempio n. 4
0
 def __init__(self):
     self.answer_number = self.create_number()
     # 開始Timer thread 物件
     self.timer_thread = TimerThread(self.update_time)
     self.current_second = 0
     self.input_number = StringVar()
class NetworkStats(object):
    def __init__(self, pusher_stream="pox"):
        core.addListeners(self)
        core.openflow.addListeners(self)
        self.stream = pusher_stream

        self.stopStatsThread = Event()
        self.syncThread = TimerThread(self.stopStatsThread, request_stats,
                                      STAT_SAMPLING_PERIOD)
        self.syncThread.start()

    def _handle_GoingDownEvent(self, event):
        # Stop the sync thread
        self.stopStatsThread.set()

    def _handle_FlowStatsReceived(self, event):

        flows = []

        total_bytes = 0
        total_flows = 0
        total_packets = 0
        dpid = dpidToStr(event.connection.dpid)

        for stats in event.stats:

            flows.append(
                FlowStatsMessage(
                    dpid,
                    stats.byte_count,
                    stats.packet_count,
                    ethernet_source=stats.match.dl_src,
                    ethernet_dest=stats.match.dl_dst,
                    ip_source=stats.match.nw_src,
                    ip_dest=stats.match.nw_dst,
                    ip_protocol=stats.match.nw_proto,
                    tcp_source=stats.match.tp_src,
                    tcp_dest=stats.match.tp_dst))

            total_bytes += stats.byte_count
            total_packets += stats.packet_count
            total_flows += 1

        message = AllFlowStatsForSwitchMessage(dpid, total_bytes,
                                               total_packets, total_flows)
        send(message, self.stream)

    def _handle_PortStatsReceived(self, event):
        stats = of_json.flow_stats_to_list(event.stats)

        ports = []

        for port in stats:

            ports.append(
                PortStatsMessage(
                    rx_packets=port["rx_packets"],
                    tx_packets=port["tx_packets"],
                    rx_bytes=port["rx_bytes"],
                    tx_bytes=port["tx_bytes"],
                    port_no=port["port_no"]))

        message = SwitchStatsMessage(dpidToStr(event.connection.dpid), ports)
        send(message, self.stream)
Esempio n. 6
0
 def schedule_timer(self, plug, time):
     stop_event = Event()
     TimerThread(stop_event, time, plug).start()
     self.timer_events.append(stop_event)
Esempio n. 7
0
class NetworkStats(object):

    def __init__ (self, pusher_stream="pox"):
        core.addListeners(self)
        core.openflow.addListeners(self)
        self.stream = pusher_stream

        self.stopStatsThread = Event()
        self.syncThread = TimerThread(self.stopStatsThread, request_stats, STAT_SAMPLING_PERIOD)
        self.syncThread.start()

    def _handle_GoingDownEvent(self, event):
        # Stop the sync thread
        self.stopStatsThread.set()

    def _handle_FlowStatsReceived (self, event) :

        flows = []

        total_bytes = 0
        total_flows = 0
        total_packets = 0
        dpid = dpidToStr(event.connection.dpid)

        for stats in event.stats:

            flows.append(FlowStatsMessage(
                dpid,
                stats.byte_count,
                stats.packet_count,
                ethernet_source=stats.match.dl_src,
                ethernet_dest=stats.match.dl_dst,
                ip_source=stats.match.nw_src,
                ip_dest=stats.match.nw_dst,
                ip_protocol=stats.match.nw_proto,
                tcp_source=stats.match.tp_src,
                tcp_dest=stats.match.tp_dst
            ))

            total_bytes += stats.byte_count
            total_packets += stats.packet_count
            total_flows += 1

        message = AllFlowStatsForSwitchMessage(dpid, total_bytes, total_packets, total_flows)
        send(message, self.stream)


    def _handle_PortStatsReceived (self, event) :
        stats = of_json.flow_stats_to_list(event.stats)

        ports = []

        for port in stats:

            ports.append(PortStatsMessage(
                rx_packets=port["rx_packets"],
                tx_packets=port["tx_packets"],
                rx_bytes=port["rx_bytes"],
                tx_bytes=port["tx_bytes"],
                port_no=port["port_no"]
            ))

        message = SwitchStatsMessage(dpidToStr(event.connection.dpid), ports)
        send(message, self.stream)
Esempio n. 8
0
monkey.patch_all()
import logging
import os
from flask import Flask, jsonify, request
from raft.cluster import Cluster
from timer_thread import TimerThread

logging.basicConfig(format='%(asctime)s - %(levelname)s: %(message)s',
                    datefmt='%H:%M:%S',
                    level=logging.INFO)

NODE_ID = int(os.environ.get('NODE_ID'))
cluster = Cluster()
node = cluster[NODE_ID]
timer_thread = TimerThread(NODE_ID)


def create_app():
    raft = Flask(__name__)
    timer_thread.start()
    return raft


app = create_app()


@app.route('/raft/vote', methods=['POST'])
def request_vote():
    vote_request = request.get_json()
    result = timer_thread.vote(json.loads(vote_request))
Esempio n. 9
0
 def timer(self, timer):
     timer_thread = TimerThread(timer)
     timer_thread.start()