def draw(tab_arrive,temps_file,temp_system):
    dictio={}
    j=0
    for i in range(len(tab_arrive)):
        dictio2={}
        dictio2["t_arrive"]='{:.4f}'.format(tab_arrive[i])
        dictio2["t_file"]='{:.4f}'.format(temps_file[i])
        dictio2["t_service"]='{:.4f}'.format(tab_arrive[i]+temps_file[i])
        dictio2["t_depart"]='{:.4f}'.format(tab_arrive[i]+temp_system[i])
        j=i+1
        dictio[j]=dictio2


    master = Tk()

    tframe = Frame(master)
    tframe.pack()
    table = TableCanvas(tframe)

    table = TableCanvas(tframe, data=dictio)

    model = table.model
    model.importDict(dictio)
    table.sortTable(columnName="t_arrive")
    table.show()
    master.mainloop()
Beispiel #2
0
    def genRandomWebLogs(self):
        """
            Method for generating random web log data.
        """

        self.count += 1
        if self.randomWebLogsWindowOpenedFlag == False:

            self.randomWebLogsWindowOpenedFlag = True # set window opened
            global RandomWebLogsWindow

            def toggleFlag():
                self.randomWebLogsWindowOpenedFlag = False # set window closed
                RandomWebLogsWindow.destroy()

            RandomWebLogsWindow = tk.Toplevel(self)
            RandomWebLogsWindow.minsize(300, 500)
            RandomWebLogsWindow.geometry("300x500+100+100")
            RandomWebLogsWindow.title("Random web log data")
            RandomWebLogsWindow.config(bd=5)
            RandomWebLogsWindow.protocol("WM_DELETE_WINDOW", toggleFlag)

            x = sp.arange(1, 31 * 24) # 1 month of traffic data
            y = sp.array(200 * (sp.sin(2 * sp.pi * x / (7 * 24))), dtype=int)
            y += gamma.rvs(15, loc=0, scale=100, size=len(x))
            y += 2 * sp.exp(x / 100.0)
            y = sp.ma.array(y, mask=[y < 0])
            sp.savetxt(os.path.join("sample_data", "sample_web_traffic.tsv"), list(zip(x, y)), delimiter="\t", fmt="%s")
            model = TableModel() # create a new TableModel for table data
            table = TableCanvas(RandomWebLogsWindow, model=model, editable=False) # create a new TableCanvas for showing the table
            table.createTableFrame()
            tableData = {} # dictionary for storing table data
            for k, v in list(zip(x,y)):
                tableData[uuid.uuid4()] = {'Hour': str(k), 'Hits': str(v)}
            model.importDict(tableData)
            table.resizeColumn(0, 100)
            table.resizeColumn(1, 100)
            table.sortTable(columnName='Hour')
            table.redrawTable()

        else:
            RandomWebLogsWindow.deiconify()  
    def ratSightings(self):
        #call API for data
        r = requests.get(
            'http://ec2-54-174-96-216.compute-1.amazonaws.com:9000/showRecords'
        )
        rtext = r.text
        rawdata = json.loads(rtext)

        #create table & model
        self.ratSightingView = Toplevel()
        self.ratSightingView.title("List of recent rat sightings")

        self.rattable = Frame(self.ratSightingView)
        self.rattable.pack()

        model = TableModel()
        model.importDict(rawdata)

        #convert date column to datetime data type
        for x in range(len(rawdata)):
            datestr = model.getValueAt(x, 6)
            try:
                date = datetime.datetime.strptime(datestr,
                                                  '%m/%d/%Y %I:%M:%S %p')
                model.setValueAt(date.strftime('%Y/%m/%d %I:%M:%S %p'), x, 6)
            except:
                try:
                    dt = parser.parse(datestr)
                    model.setValueAt(date.strftime('%Y/%m/%d %I:%M:%S %p'), x,
                                     6)
                except:
                    pass
                pass

        #get data into table
        table = TableCanvas(self.rattable, model=model)
        table.createTableFrame()

        #sort by date
        table.sortTable(columnName='date')
        '''
Beispiel #4
0
    def __table__(self, master):
        try:
            if self.rule_win.state() == 'normal':
                pass
        except:
            data = {}
            colnums = ['Rule', 'Node', 'Question', 'Yes', 'No']
            rule_dict = self.df.ix[:, 'Rule':'No']

            for r in range(len(rule_dict.index)):
                plice = {}
                for c in range(len(rule_dict.columns)):
                    if rule_dict.iloc[r, c] == 'nan':
                        plice[rule_dict.columns[c]] = ' '
                    else:
                        plice[rule_dict.columns[c]] = rule_dict.iloc[r, c]
                data[str(r)] = plice

            self.rule_win = Toplevel(master)
            frame = Frame(self.rule_win)
            frame.pack()
            model = TableModel()

            for key in colnums:
                model.addColumn(key)  #sort the columns

            model.importDict(data)
            table = TableCanvas(frame,
                                model=model,
                                width=800,
                                height=500,
                                rowheight=20,
                                editable=False,
                                cellbackgr='#E3F6CE',
                                reverseorder=1,
                                rowselectedcolor='yellow')
            table.createTableFrame()
            table.sortTable(columnName='Rule')
Beispiel #5
0
    def findTweetSentiment(self):
        """
            Method for calculating the sentiment of each tweet.
        """

        if not os.path.isfile(self.TwitterKeysFile):
            tkMessageBox.showerror("ERROR", "Twitter API credentials not filled. Use the Set/Update Twitter Credentials button to do so.", parent = self.parent)
            return

        self.count += 1
        if self.tweetSentimentOpenedFlag == False:
            # set window opened
            self.tweetSentimentOpenedFlag = True

            # initialize window
            global TweetSentimentWindow
            def toggleFlag():
                self.tweetSentimentOpenedFlag = False
                TweetSentimentWindow.destroy()

            TweetSentimentWindow = tk.Toplevel(self)
            TweetSentimentWindow.minsize(600, 500)
            #TwitterKeysWindow.overrideredirect(True)
            TweetSentimentWindow.geometry("1000x500+100+100")
            TweetSentimentWindow.title("Tweet Sentiments (Zero values omitted)")
            TweetSentimentWindow.config(bd=5)
            TweetSentimentWindow.protocol("WM_DELETE_WINDOW", toggleFlag)

            # create a new TableModel for table data
            model = TableModel()

            # create a new TableCanvas for showing the table
            table = TableCanvas(TweetSentimentWindow, model=model,
                                 editable=False)
            table.createTableFrame()

            # dictionary for storing table data
            tableData = {}
            
            # calculate sentiments
            afinnfile = open(self.AFINNFile)
            scores = {} 
            for line in afinnfile:
                    term, score  = line.split("\t")  
                    scores[term] = int(score)  

            #print scores.items() 
            positive = 0.0
            negative = 0.0
            
            outfile = open(self.TwitterStreamFile)
            for line in outfile:
                    json_obj = json.loads(line)
                    sentiment = 0
                    try:            
                        text = json_obj['text'].decode('utf-8')
                        # clean the text
                        text = ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)","",text).split())
                        text = re.sub(r'^https?:\/\/.*[\r\n]*', '', text, flags=re.MULTILINE)
                        text = re.sub(r'RT', '', text, flags=re.MULTILINE)
                        #print text
                        text_list = text.split(' ')
                        for char in text_list:
                            if char in scores:
                                    sentiment += scores[char]

                        if sentiment != 0:
                            # add items to table data dictionary
                            tableData[uuid.uuid4()] = {'Tweet': text, 'Score': str(sentiment)}
                            if sentiment > 0:
                                positive += 1
                            elif sentiment < 0:
                                negative += 1
                            #print text + "   " + str(sentiment) + "\n\n"
                            
                    except:
                        #print "passed"
                        pass

            # calculate ratio            
            if positive > 0 and negative > 0:
                ratio = round(float(positive) / float(negative), 2)
                
            # insert and sort data in the table
            model.importDict(tableData)
            table.resizeColumn(0, 850)
            table.resizeColumn(1, 50)
            table.sortTable(columnName='Score')
            table.redrawTable()

            if positive > negative:
                extra = "The overall sentiment is POSITIVE."
            else:    
                extra = "The overall sentiment is NEGATIVE."
            
            # show info box about the overall result
            tkMessageBox.showinfo("Score Ratio", "The ratio of positive vs. negative tweets is " + str(ratio) + ". " + extra, parent = TweetSentimentWindow)
Beispiel #6
0
#(or we can create the model first and supply it as an argument to the table constructor):

data = {'rec1': {'col1': 99.88, 'col2': 108.79, 'label': 'rec1'},
'rec2': {'col1': 99.88, 'col2': 108.79, 'label': 'rec2'},
'rec3': {'col1':1.0, 'label':'rec3'},
'rec4': {'col1':2.0, 'label':'rec4'}
}

model = table.model
model.importDict(data) #can import from a dictionary to populate model
table.redrawTable()


#by column name
raw_input('Sort table by column name')
table.sortTable(columnName='label')

#by column index
raw_input('Sort table by column index')
table.sortTable(columnIndex=1) 

raw_input('Add automatic key row')
#add with automatic key
table.addRow()

raw_input('Add row with new key name')
#add with named key, other keyword arguments are interpreted as column values
keyname = 'rec5'
table.addRow(keyname, label='abc')

raw_input('Add column')
Beispiel #7
0
    def findTweetSentiment(self):
        """
            Method for calculating the sentiment of each tweet.
        """

        if not os.path.isfile(self.TwitterKeysFile):
            tkMessageBox.showerror(
                "ERROR",
                "Twitter API credentials not filled. Use the Set/Update Twitter Credentials button to do so.",
                parent=self.parent)
            return

        self.count += 1
        if self.tweetSentimentOpenedFlag == False:
            # set window opened
            self.tweetSentimentOpenedFlag = True

            # initialize window
            global TweetSentimentWindow

            def toggleFlag():
                self.tweetSentimentOpenedFlag = False
                TweetSentimentWindow.destroy()

            TweetSentimentWindow = tk.Toplevel(self)
            TweetSentimentWindow.minsize(600, 500)
            #TwitterKeysWindow.overrideredirect(True)
            TweetSentimentWindow.geometry("1000x500+100+100")
            TweetSentimentWindow.title(
                "Tweet Sentiments (Zero values omitted)")
            TweetSentimentWindow.config(bd=5)
            TweetSentimentWindow.protocol("WM_DELETE_WINDOW", toggleFlag)

            # create a new TableModel for table data
            model = TableModel()

            # create a new TableCanvas for showing the table
            table = TableCanvas(TweetSentimentWindow,
                                model=model,
                                editable=False)
            table.createTableFrame()

            # dictionary for storing table data
            tableData = {}

            # calculate sentiments
            afinnfile = open(self.AFINNFile)
            scores = {}
            for line in afinnfile:
                term, score = line.split("\t")
                scores[term] = int(score)

            #print scores.items()
            positive = 0.0
            negative = 0.0

            outfile = open(self.TwitterStreamFile)
            for line in outfile:
                json_obj = json.loads(line)
                sentiment = 0
                try:
                    text = json_obj['text'].decode('utf-8')
                    # clean the text
                    text = ' '.join(
                        re.sub(
                            "(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)",
                            "", text).split())
                    text = re.sub(r'^https?:\/\/.*[\r\n]*',
                                  '',
                                  text,
                                  flags=re.MULTILINE)
                    text = re.sub(r'RT', '', text, flags=re.MULTILINE)
                    #print text
                    text_list = text.split(' ')
                    for char in text_list:
                        if char in scores:
                            sentiment += scores[char]

                    if sentiment != 0:
                        # add items to table data dictionary
                        tableData[uuid.uuid4()] = {
                            'Tweet': text,
                            'Score': str(sentiment)
                        }
                        if sentiment > 0:
                            positive += 1
                        elif sentiment < 0:
                            negative += 1
                        #print text + "   " + str(sentiment) + "\n\n"

                except:
                    #print "passed"
                    pass

            # calculate ratio
            if positive > 0 and negative > 0:
                ratio = round(float(positive) / float(negative), 2)

            # insert and sort data in the table
            model.importDict(tableData)
            table.resizeColumn(0, 850)
            table.resizeColumn(1, 50)
            table.sortTable(columnName='Score')
            table.redrawTable()

            if positive > negative:
                extra = "The overall sentiment is POSITIVE."
            else:
                extra = "The overall sentiment is NEGATIVE."

            # show info box about the overall result
            tkMessageBox.showinfo(
                "Score Ratio",
                "The ratio of positive vs. negative tweets is " + str(ratio) +
                ". " + extra,
                parent=TweetSentimentWindow)
Beispiel #8
0
class MainWindow(object):
    def __init__(self, controller):
        self.controller = controller
        self.window = Tk()
        # self.window.geometry('1600x' + str(self.window.winfo_screenheight()))
        self.window.geometry(config.MAIN_WINDOW_DEFAULT_WIDTH + 'x' + config.MAIN_WINDOW_DEFAULT_HEIGHT)
        self.window.bind_all('<Key>', self.key)
        self.frame = Frame(self.window, width=200, height=200, bd=11)
        self.frame.pack(expand=True, fill=BOTH)
        self.label_value = StringVar()
        self.label_value.set('test')
        self.label = Label(self.frame, textvariable=self.label_value, anchor=NW, justify=CENTER, wraplength=398)
        # don't mix grid and pack
        self.label.grid(row=0)
        self.table = TableCanvas(self.frame, cols=0, rows=0, editable=False)

        self.table.parentframe.master.bind_all("<Control-j>", self.move_cursor_up)
        self.table.parentframe.master.bind_all("<Control-k>", self.move_cursor_down)
        self.table.parentframe.master.bind_all("<Control-l>", self.move_cursor_left)
        self.table.parentframe.master.bind_all("<Control-semicolon>", self.move_cursor_right)

        self.table.createTableFrame()

        self.sort_order = 0
        # self.window.mainloop()

    def key(self, event):
        if event.keysym == 'Escape':
            self.window.destroy()
            return
        elif event.keysym == 'Return':
            return
        else:
            # self.label_value.set(self.controller.query_builder.get_query_for_label())
            self.controller.key_pressed_event(event.keysym)
            return

    def set_data_to_table(self, dct, sortColumn=''):
        if not dct:
            return
        self.table.model.createEmptyModel()
        self.table.model.importDict(dct)
        self.table.sortTable(columnName=sortColumn)
        self.table.redrawTable()

    def sort_table(self, sortColumn):
        self.table.sortTable(columnName=sortColumn, reverse=self.sort_order)
        if self.sort_order == 0:
            self.sort_order = 1
        else:
            self.sort_order = 0

    def move_cursor_up(self, event):
        x,y = self.table.getCanvasPos(self.table.currentrow, 0)
        if x == None:
            return

        if self.table.currentrow == 0:
            return
        else:
            self.table.currentrow = self.table.currentrow -1

        self.draw_table_cursor()
        return

    def move_cursor_down(self, event):
        x,y = self.table.getCanvasPos(self.table.currentrow, 0)
        if x == None:
            return

        if self.table.currentrow >= self.table.rows-1:
            return
        else:
            self.table.currentrow = self.table.currentrow +1

        self.draw_table_cursor()
        return

    def move_cursor_left(self, event):
        x,y = self.table.getCanvasPos(self.table.currentrow, 0)
        if x == None:
            return

        self.table.currentcol  = self.table.currentcol -1

        self.draw_table_cursor()
        return

    def move_cursor_right(self, event):
        x,y = self.table.getCanvasPos(self.table.currentrow, 0)
        if x == None:
            return

        if self.table.currentcol >= self.table.cols-1:
            if self.table.currentrow < self.table.rows-1:
                self.table.currentcol = 0
                self.table.currentrow  = self.table.currentrow +1
            else:
                return
        else:
            self.table.currentcol  = self.table.currentcol +1

        self.draw_table_cursor()
        return

    def draw_table_cursor(self):
        self.table.drawSelectedRect(self.table.currentrow, self.table.currentcol)
        coltype = self.table.model.getColumnType(self.table.currentcol)
        if coltype == 'text' or coltype == 'number':
            self.table.delete('entry')
            self.table.drawCellEntry(self.table.currentrow, self.table.currentcol)