<commit_before>__author__ = 'LukaAvbreht,SamoKralj'
from tkinter import *
from igra import *

class tkmlin():
    def __init__(self,master):
        self.master = master
        self.master.minsize(width=900, height=700)
        self.bg = 'LemonChiffon'

        self.igra = Igra()

        #tuki si bos lahko zbiru kako barva tvoja polja
        self.barva1 = 'Black'
        self.barva2 = 'White'

        #igralca ki igrata igro
        self.ime_igralec1 = 'Črni'
        self.ime_igralec2 = 'Beli'

        #igralca
        self.igralec_beli = Igralec(self, self.barva1)
        self.igralec_crni = Igralec(self, self.barva2)

        #kdo je na potezi
        self.na_potezi = None

        #Igralnaself.plosca
        self.plosca = Canvas(master, width=700, height=700, bg=self.bg)
        self.plosca.grid(row=1, column=0, rowspan=7, columnspan=7, sticky=N+S+E+W)

        #Slovar ki ima za kljuce id gumbov in jih poveze z poljem v igri
        self.id_polje = dict()

        #crte za igralno plosco
        self.plosca.create_rectangle(50, 50, 650, 650)
        self.plosca.create_rectangle(150, 150, 550, 550)
        self.plosca.create_rectangle(250, 250, 450, 450)

        self.plosca.create_line(350, 50, 350, 250)
        self.plosca.create_line(350, 450, 350, 650)
        self.plosca.create_line(50, 350, 250, 350)
        self.plosca.create_line(450, 350, 650, 350)

        # generira gumbke na polju in jim da svoj id
        for i in range(7):
            for j in range(7):
                if self.igra.plosca[j][i]==None:
                    x =self.plosca.create_oval((100*j+50)-25, (100*i+50)-25, (100*j+50)+25, (100*i+50)+25, outline=self.bg)
                    self.id_polje[x] = (i,j)
        print(self.id_polje)

        self.plosca.bind("<Button-1>", self.klik)

        self.textbox = StringVar(master, value='Na potezi je {}.'.format(self.ime_igralec1))
        Label(self.master, textvariable=self.textbox, font=("Helvetica", 20)).grid(row=0, column=0, columnspan=7)

        #stanja za igro
        self.DEFCON = 0
        #DEFCON 0 : nič, čakamo da začnemo igro
        #DEFCON 1 : Igralec na potezi naj izbere polje
        #DEFCON 2 : Igralec na potezi naj izbere drugo polje
        #DEFCON 3 : Igralec na potezi naj izbere zeton, ki ga bo odstranil

        #generira gumbe ki niso povezani z igro
        gumb_novaigra = Button(master, text="Nova igra", command= self.newgame)
        gumb_novaigra.grid(row=0, column=9, sticky=N+W+E+S)

        gumbtest =  Button(master, text="TEST", command= self.test)
        gumbtest.grid(row=0, column=10, sticky=N+W+E+S)

    #trol
    def test(self):
        if self.DEFCON == 0:
            for i in self.id_polje:
                self.plosca.itemconfig(i,fill=self.barva1)
            self.textbox.set('Na potezi je {}.'.format(self.ime_igralec2))
            self.DEFCON = 1
        else:
            for i in self.id_polje:
                self.plosca.itemconfig(i,fill=self.barva2)
            self.textbox.set('Na potezi je {}.'.format(self.ime_igralec1))
            self.DEFCON = 0

    def klik(self,event):
        """Funkcija ki vrne id polja, na katerega je pritisnil uporabnik"""
        x = event.x
        y = event.y
        kam = self.plosca.find_overlapping(x-25, y-25, x+25, y+25)
        for id in kam:
            if id in self.id_polje:
                if self.DEFCON == 0:
                    self.textbox.set("Klikni gumb NOVA IGRA")
                elif self.DEFCON == 1:
                    self.na_potezi.prvi_klik = id
                    self.na_potezi.uporabnikova_poteza()
                    if self.na_potezi == self.igralec_beli:
                        self.na_potezi = self.igralec_crni
                    else:
                        self.na_potezi = self.igralec_beli
                elif self.DEFCON == 2:
                    pass
                elif self.DEFCON == 3:
                    pass
                else:
                    pass

    def newgame(self):
        self.igra = Igra()
        for i in self.id_polje:
            self.plosca.itemconfig(i, fill=None)
        self.na_potezi = self.igralec_crni
        self.textbox.set('Na potezi je {}.'.format(self.ime_igralec1))
        self.DEFCON = 1

    def poteza(self, i, j, a=False, b=False): #najprej pogleda v keri fazi smo, pol pa nardi v odvisnosti od tega potezo
        # ce smo v fazi 0 potem je prvi klik le postavljanje kamncka
        # ce smo v drugi fazi usaka poteza zahteva 2 klika
        if self.igra.faza == 0:
            self.klik0
        elif self.igra.faza == 1:
            self.klik1

    def zacni_igro(self, IGRALEC_BELI, IGRALEC_CRNI):
        self.igra = Igra()
        self.igralec_beli = IGRALEC_BELI
        self.igralec_crni = IGRALEC_CRNI

class Igralec():
    """cloveski igralec"""
    def __init__(self, tkmlin, barva):
        """Shrani klike igralca in doloci igralno polje kjer igralec igra igro"""
        self.gui = tkmlin
        self.prvi_klik = None
        self.drugi_klik = None
        self.tretji_klik = None
        self.barva = barva

    def ponastavi(self):
        """resetira igrelcevo potezo na nevtralno pozicijo"""
        self.prvi_klik = None
        self.drugi_klik = None
        self.tretji_klik = None

    def uporabnikova_poteza(self):
        """Metoda ki naredi potezo (preveri njeno veljavnost in naroci igralni plosci da jo zapise v igralno polje)"""
        if self.gui.igra.faza == 0:
            self.gui.plosca.itemconfig(self.prvi_klik, fill = self.barva)
        else:
            pass
        # tuki bos meu odvisno od tega u keri fazi si potezo in ti bo preverju ce jo lahko izvede in od tebe zahtevu
        # klike, ko bos kilke izvedu se bo pa poteza zapisala u igro

if __name__ == "__main__":
    root = Tk()
    root.wm_title('Nine Men\'s Morris')
    root.resizable(width=FALSE, height=FALSE)
    okno = tkmlin(root)
    root.mainloop()
<commit_msg>Povezal fazo 1 z logiko igre<commit_after>__author__ = 'LukaAvbreht,SamoKralj'
from tkinter import *
from igra import *

class tkmlin():
    def __init__(self,master):
        self.master = master
        self.master.minsize(width=900, height=700)
        self.bg = 'LemonChiffon'

        self.igra = Igra()

        #tuki si bos lahko zbiru kako barva tvoja polja
        self.barva1 = 'Black'
        self.barva2 = 'White'

        #igralca ki igrata igro
        self.ime_igralec1 = 'Črni'
        self.ime_igralec2 = 'Beli'

        #igralca
        self.igralec_beli = Igralec(self, self.barva1)
        self.igralec_crni = Igralec(self, self.barva2)

        #kdo je na potezi
        self.na_potezi = None

        #Igralnaself.plosca
        self.plosca = Canvas(master, width=700, height=700, bg=self.bg)
        self.plosca.grid(row=1, column=0, rowspan=7, columnspan=7, sticky=N+S+E+W)

        #Slovar ki ima za kljuce id gumbov in jih poveze z poljem v igri
        self.id_polje = dict()

        #crte za igralno plosco
        self.plosca.create_rectangle(50, 50, 650, 650)
        self.plosca.create_rectangle(150, 150, 550, 550)
        self.plosca.create_rectangle(250, 250, 450, 450)

        self.plosca.create_line(350, 50, 350, 250)
        self.plosca.create_line(350, 450, 350, 650)
        self.plosca.create_line(50, 350, 250, 350)
        self.plosca.create_line(450, 350, 650, 350)

        # generira gumbke na polju in jim da svoj id
        for i in range(7):
            for j in range(7):
                if self.igra.plosca[j][i]==None:
                    x =self.plosca.create_oval((100*j+50)-25, (100*i+50)-25, (100*j+50)+25, (100*i+50)+25, outline=self.bg)
                    self.id_polje[x] = (i,j)
        print(self.id_polje)

        self.plosca.bind("<Button-1>", self.klik)

        self.textbox = StringVar(master, value='Pozdravljeni!')
        Label(self.master, textvariable=self.textbox, font=("Helvetica", 20)).grid(row=0, column=0, columnspan=7)

        #stanja za igro
        self.DEFCON = 0
        #DEFCON 0 : nič, čakamo da začnemo igro
        #DEFCON 1 : Igralec na potezi naj izbere polje
        #DEFCON 2 : Igralec na potezi naj izbere drugo polje
        #DEFCON 3 : Igralec na potezi naj izbere zeton, ki ga bo odstranil

        #generira gumbe ki niso povezani z igro
        gumb_novaigra = Button(master, text="Nova igra", command= self.newgame)
        gumb_novaigra.grid(row=0, column=9, sticky=N+W+E+S)

        gumbtest =  Button(master, text="TEST", command= self.test)
        gumbtest.grid(row=0, column=10, sticky=N+W+E+S)

    #trol
    def test(self):
        if self.DEFCON == 0:
            for i in self.id_polje:
                self.plosca.itemconfig(i,fill=self.barva1)
            self.textbox.set('Na potezi je {}.'.format(self.ime_igralec2))
            self.DEFCON = 1
        else:
            for i in self.id_polje:
                self.plosca.itemconfig(i,fill=self.barva2)
            self.textbox.set('Na potezi je {}.'.format(self.ime_igralec1))
            self.DEFCON = 0

    def klik(self,event):
        """Funkcija ki vrne id polja, na katerega je pritisnil uporabnik"""
        x = event.x
        y = event.y
        kam = self.plosca.find_overlapping(x-25, y-25, x+25, y+25)
        for id in kam:
            if id in self.id_polje:
                if self.DEFCON == 0:
                    self.textbox.set("Klikni gumb NOVA IGRA")
                elif self.DEFCON == 1:
                    self.na_potezi.prvi_klik = id
                    poteza = self.na_potezi.uporabnikova_poteza()
                    if poteza:
                        #Če je bila izvedena poteza igralca, zamenjaj kdo je na potezi
                        if self.na_potezi == self.igralec_beli:
                            self.na_potezi = self.igralec_crni
                        else:
                            self.na_potezi = self.igralec_beli
                elif self.DEFCON == 2:
                    pass
                elif self.DEFCON == 3:
                    pass
                else:
                    pass

    def newgame(self):
        self.igra = Igra()
        for i in self.id_polje:
            self.plosca.itemconfig(i, fill=None)
        self.na_potezi = self.igralec_crni
        self.textbox.set('Na potezi je {}.'.format(self.ime_igralec1))
        self.DEFCON = 1

    def poteza(self, i, j, a=False, b=False): #najprej pogleda v keri fazi smo, pol pa nardi v odvisnosti od tega potezo
        # ce smo v fazi 0 potem je prvi klik le postavljanje kamncka
        # ce smo v drugi fazi usaka poteza zahteva 2 klika
        if self.igra.faza == 0:
            self.klik0
        elif self.igra.faza == 1:
            self.klik1

    def izvedi_potezo(self, id, i, j):
        self.plosca.itemconfig(id, fill = self.na_potezi.barva)
        self.igra.poteza(i,j)

class Igralec():
    """cloveski igralec"""
    def __init__(self, tkmlin, barva):
        """Shrani klike igralca in doloci igralno polje kjer igralec igra igro"""
        self.gui = tkmlin
        self.prvi_klik = None
        self.drugi_klik = None
        self.tretji_klik = None
        self.barva = barva

    def ponastavi(self):
        """resetira igrelcevo potezo na nevtralno pozicijo"""
        self.prvi_klik = None
        self.drugi_klik = None
        self.tretji_klik = None

    def uporabnikova_poteza(self):
        """Metoda ki naredi potezo (preveri njeno veljavnost in naroci igralni plosci da jo zapise v igralno polje)"""
        if self.gui.igra.faza == 0:
            koord_1 = self.gui.id_polje[self.prvi_klik][0]
            koord_2 = self.gui.id_polje[self.prvi_klik][1]
            if self.gui.igra.je_veljavna(koord_1, koord_2):
                self.gui.izvedi_potezo(self.prvi_klik, koord_1, koord_2)
                return True
            else:
                return False
        else:
            pass
        # tuki bos meu odvisno od tega u keri fazi si potezo in ti bo preverju ce jo lahko izvede in od tebe zahtevu
        # klike, ko bos kilke izvedu se bo pa poteza zapisala u igro

if __name__ == "__main__":
    root = Tk()
    root.wm_title('Nine Men\'s Morris')
    root.resizable(width=FALSE, height=FALSE)
    okno = tkmlin(root)
    root.mainloop()
<|endoftext|>


<commit_before>from Piece import Piece, Pawn, Rook, Knight, Bishop, Queen, King

class Move(object):
    """Contains all the move methods"""
    def __init__(self):
        pass

    def set_new_game(self):
        """
        Initializes pieces for a new chess game.
        Uses two for loops and if/else statements to set the pieces.
        """
        board = []
        A, B, C, D, E, F, G, H = range(8), range(8), range(8), range(8), range(8), range(8), range(8), range(8) # Feels unpythonic but can't do A = B = C = ... = range(8) since lists are mutable
        board.extend([A, B, C, D, E, F, G, H])

        for row in xrange(8):
            for col in xrange(8):
                if col == 1:
                    board[row][col] = Pawn(False, 'White')

                elif col == 6:
                    board[row][col] = Pawn(False, 'Black')

                elif col in range(2,7):
                    board[row][col] = Piece(True, 'NA')

                elif col == 0:
                    if row == 0 or row == 7:
                        board[row][col] = Rook(False, 'White')

                    elif row == 1 or row == 6:
                        board[row][col] = Knight(False, 'White')

                    elif row == 2 or row == 5:
                        board[row][col] = Bishop(False, 'White')

                    elif row == 3:
                        board[row][col] = Queen(False, 'White')

                    else:
                        board[row][col] = King(False, 'White')

                else:
                    if row == 0 or row == 7:
                        board[row][col] = Rook(False, 'Black')

                    elif row == 1 or row == 6:
                        board[row][col] = Knight(False, 'Black')

                    elif row == 2 or row == 5:
                        board[row][col] = Bishop(False, 'Black')

                    elif row == 3:
                        board[row][col] = Queen(False, 'Black')

                    else:
                        board[row][col] = King(False, 'Black')

        return board

    def get_move(self):
        """
        Prompts user for desired move. Only using numerical coordinates for now.
        Stores from and to coordinates in tuples. Returns a tuple of these tuples."
        Input is basic now, eg. 12 is parsed as (1, 2)
        """
        piece_from = tuple(i for i in raw_input("From?"))
        piece_to = tuple(i for i in raw_input("To?"))

        print "Moving from {0} to {1}".format(piece_from, piece_to)
        return (piece_from, piece_to)

    def move(self, piece_from, piece_to):
        """Rudimentary move function for now"""
        self.main_board[piece_to[0]][piece_to[1]] = self.main_board[piece_from[0]][piece_from[1]]  # Moves piece
        self.main_board[piece_from[0]][piece_from[1]] = Piece(True, 'NA')  # Makes old location empty

    def alphanum_to_cartesian(self, piece_from, piece_to):
        """
        Converts board coordinate input--eg. 'A5' to cartesian coordinates.
        Takes the two movement tuples, converts, then returns a single tuple
        """
        pass
<commit_msg>Wrote alphanum_to_cartesian() method<commit_after>from Piece import Piece, Pawn, Rook, Knight, Bishop, Queen, King

class Move(object):
    """Contains all the move methods"""
    def __init__(self):
        pass

    def set_new_game(self):
        """
        Initializes pieces for a new chess game.
        Uses two for loops and if/else statements to set the pieces.
        """
        board = []
        A, B, C, D, E, F, G, H = range(8), range(8), range(8), range(8), range(8), range(8), range(8), range(8) # Feels unpythonic but can't do A = B = C = ... = range(8) since lists are mutable
        board.extend([A, B, C, D, E, F, G, H])

        for row in xrange(8):
            for col in xrange(8):
                if col == 1:
                    board[row][col] = Pawn(False, 'White')

                elif col == 6:
                    board[row][col] = Pawn(False, 'Black')

                elif col in range(2,7):
                    board[row][col] = Piece(True, 'NA')

                elif col == 0:
                    if row == 0 or row == 7:
                        board[row][col] = Rook(False, 'White')

                    elif row == 1 or row == 6:
                        board[row][col] = Knight(False, 'White')

                    elif row == 2 or row == 5:
                        board[row][col] = Bishop(False, 'White')

                    elif row == 3:
                        board[row][col] = Queen(False, 'White')

                    else:
                        board[row][col] = King(False, 'White')

                else:
                    if row == 0 or row == 7:
                        board[row][col] = Rook(False, 'Black')

                    elif row == 1 or row == 6:
                        board[row][col] = Knight(False, 'Black')

                    elif row == 2 or row == 5:
                        board[row][col] = Bishop(False, 'Black')

                    elif row == 3:
                        board[row][col] = Queen(False, 'Black')

                    else:
                        board[row][col] = King(False, 'Black')

        return board

    def get_move(self):
        """
        Prompts user for desired move. Only using numerical coordinates for now.
        Stores from and to coordinates in tuples. Returns a tuple of these tuples."
        Input is basic now, eg. 12 is parsed as (1, 2)
        """
        piece_from = tuple(i for i in raw_input("From?"))
        piece_to = tuple(i for i in raw_input("To?"))

        print "Moving from {0} to {1}".format(piece_from, piece_to)
        return (piece_from, piece_to)

    def move(self, piece_from, piece_to):
        """Rudimentary move function for now"""
        self.main_board[piece_to[0]][piece_to[1]] = self.main_board[piece_from[0]][piece_from[1]]  # Moves piece
        self.main_board[piece_from[0]][piece_from[1]] = Piece(True, 'NA')  # Makes old location empty

    def alphanum_to_cartesian(self, piece_from, piece_to):
        """
        Converts board coordinate input--eg. 'A5' to cartesian coordinates.
        Takes the two movement tuples, converts, then returns a single tuple
        """
        atoi = {
            'A' : 0
            'B' : 1
            'C' : 2
            'D' : 3
            'E' : 4
            'F' : 5
            'G' : 6
            'H' : 7
        }

        piece_from = (atoi[piece_from[0]], int(piece_from[1]) - 1)  # -1 since counting starts from 0 not 1
        piece_to = (atoi[piece_to[0]], int(piece_to[1]) - 1)

        return (piece_from, piece_to)
<|endoftext|>


<commit_before>from Piece import Piece, Pawn, Rook, Knight, Bishop, Queen, King

class Move(object):
    """Contains all the move methods"""
    def __init__(self):
        pass

    def set_new_game(self):
        """
        Initializes pieces for a new chess game.
        Uses two for loops and if/else statements to set the pieces.
        """
        board = []
        A, B, C, D, E, F, G, H = range(8), range(8), range(8), range(8), range(8), range(8), range(8), range(8) # Feels unpythonic but can't do A = B = C = ... = range(8) since lists are mutable
        board.extend([A, B, C, D, E, F, G, H])

        for row in xrange(8):
            for col in xrange(8):
                if col == 1:
                    board[row][col] = Pawn(False, 'White')

                elif col == 6:
                    board[row][col] = Pawn(False, 'Black')

                elif col in range(2,7):
                    board[row][col] = Piece(True, 'N/A')

                elif col == 0:
                    if row == 0 or row == 7:
                        board[row][col] = Rook(False, 'White')

                    elif row == 1 or row == 6:
                        board[row][col] = Knight(False, 'White')

                    elif row == 2 or row == 5:
                        board[row][col] = Bishop(False, 'White')

                    elif row == 3:
                        board[row][col] = Queen(False, 'White')

                    else:
                        board[row][col] = King(False, 'White')

                else:
                    if row == 0 or row == 7:
                        board[row][col] = Rook(False, 'Black')

                    elif row == 1 or row == 6:
                        board[row][col] = Knight(False, 'Black')

                    elif row == 2 or row == 5:
                        board[row][col] = Bishop(False, 'Black')

                    elif row == 3:
                        board[row][col] = Queen(False, 'Black')

                    else:
                        board[row][col] = King(False, 'Black')

        return board

    def get_move(self):
        """
        Prompts user for desired move. Only using numerical coordinates for now.
        Stores from and to coordinates in tuples. Returns a tuple of these tuples."
        Input is basic now, eg. 12 is parsed as (1, 2)
        """
        piece_from = tuple(int(i) for i in raw_input("From?"))
        piece_to = tuple(int(i) for i in raw_input("To?"))

        print "Moving from {0} to {1}".format(piece_from, piece_to)
        return (piece_from, piece_to)

    #def move(piece_from, piece_to):
    #    """Rudimentary move function for now"""

<commit_msg>Added a move() method to Move. Tested to see if the method could access main_board array from the Board class<commit_after>from Piece import Piece, Pawn, Rook, Knight, Bishop, Queen, King

class Move(object):
    """Contains all the move methods"""
    def __init__(self):
        pass

    def set_new_game(self):
        """
        Initializes pieces for a new chess game.
        Uses two for loops and if/else statements to set the pieces.
        """
        board = []
        A, B, C, D, E, F, G, H = range(8), range(8), range(8), range(8), range(8), range(8), range(8), range(8) # Feels unpythonic but can't do A = B = C = ... = range(8) since lists are mutable
        board.extend([A, B, C, D, E, F, G, H])

        for row in xrange(8):
            for col in xrange(8):
                if col == 1:
                    board[row][col] = Pawn(False, 'White')

                elif col == 6:
                    board[row][col] = Pawn(False, 'Black')

                elif col in range(2,7):
                    board[row][col] = Piece(True, 'N/A')

                elif col == 0:
                    if row == 0 or row == 7:
                        board[row][col] = Rook(False, 'White')

                    elif row == 1 or row == 6:
                        board[row][col] = Knight(False, 'White')

                    elif row == 2 or row == 5:
                        board[row][col] = Bishop(False, 'White')

                    elif row == 3:
                        board[row][col] = Queen(False, 'White')

                    else:
                        board[row][col] = King(False, 'White')

                else:
                    if row == 0 or row == 7:
                        board[row][col] = Rook(False, 'Black')

                    elif row == 1 or row == 6:
                        board[row][col] = Knight(False, 'Black')

                    elif row == 2 or row == 5:
                        board[row][col] = Bishop(False, 'Black')

                    elif row == 3:
                        board[row][col] = Queen(False, 'Black')

                    else:
                        board[row][col] = King(False, 'Black')

        return board

    def get_move(self):
        """
        Prompts user for desired move. Only using numerical coordinates for now.
        Stores from and to coordinates in tuples. Returns a tuple of these tuples."
        Input is basic now, eg. 12 is parsed as (1, 2)
        """
        piece_from = tuple(int(i) for i in raw_input("From?"))
        piece_to = tuple(int(i) for i in raw_input("To?"))

        print "Moving from {0} to {1}".format(piece_from, piece_to)
        return (piece_from, piece_to)

    def move(self, piece_from, piece_to):
        """Rudimentary move function for now"""
        temp = self.main_board[0][0]
        self.main_board[0][0] = self.main_board[0][1]
        self.main_board[0][1] = temp

<|endoftext|>


<commit_before>from flask import (
    Markup,
    abort,
    flash,
    redirect,
    render_template,
    request,
    session,
    url_for,
)
from flask_login import current_user

from app import login_manager
from app.main import main
from app.main.forms import LoginForm
from app.models.user import InvitedUser, User

@main.route('/sign-in', methods=(['GET', 'POST']))
def sign_in():
    if current_user and current_user.is_authenticated:
        return redirect(url_for('main.show_accounts_or_dashboard'))

    form = LoginForm()

    if form.validate_on_submit():

        user = User.from_email_address_and_password_or_none(
            form.email_address.data, form.password.data
        )

        if user and user.state == 'pending':
            return redirect(url_for('main.resend_email_verification'))

        if user and session.get('invited_user'):
            invited_user = InvitedUser.from_session()
            if user.email_address.lower() != invited_user.email_address.lower():
                flash("You can't accept an invite for another person.")
                session.pop('invited_user', None)
                abort(403)
            else:
                invited_user.accept_invite()
        if user and user.sign_in():
            if user.sms_auth:
                return redirect(url_for('.two_factor', next=request.args.get('next')))
            if user.email_auth:
                return redirect(url_for('.two_factor_email_sent'))

        # Vague error message for login in case of user not known, locked, inactive or password not verified
        flash(Markup(
            (
                "The email address or password you entered is incorrect."
                " Forgot your password?"
            ).format(password_reset=url_for('.forgot_password'))
        ))

    other_device = current_user.logged_in_elsewhere()
    return render_template(
        'views/signin.html',
        form=form,
        again=bool(request.args.get('next')),
        other_device=other_device
    )

@login_manager.unauthorized_handler
def sign_in_again():
    return redirect(
        url_for('main.sign_in', next=request.path)
    )
<commit_msg>Replace can't with cannot<commit_after>from flask import (
    Markup,
    abort,
    flash,
    redirect,
    render_template,
    request,
    session,
    url_for,
)
from flask_login import current_user

from app import login_manager
from app.main import main
from app.main.forms import LoginForm
from app.models.user import InvitedUser, User

@main.route('/sign-in', methods=(['GET', 'POST']))
def sign_in():
    if current_user and current_user.is_authenticated:
        return redirect(url_for('main.show_accounts_or_dashboard'))

    form = LoginForm()

    if form.validate_on_submit():

        user = User.from_email_address_and_password_or_none(
            form.email_address.data, form.password.data
        )

        if user and user.state == 'pending':
            return redirect(url_for('main.resend_email_verification'))

        if user and session.get('invited_user'):
            invited_user = InvitedUser.from_session()
            if user.email_address.lower() != invited_user.email_address.lower():
                flash("You cannot accept an invite for another person.")
                session.pop('invited_user', None)
                abort(403)
            else:
                invited_user.accept_invite()
        if user and user.sign_in():
            if user.sms_auth:
                return redirect(url_for('.two_factor', next=request.args.get('next')))
            if user.email_auth:
                return redirect(url_for('.two_factor_email_sent'))

        # Vague error message for login in case of user not known, locked, inactive or password not verified
        flash(Markup(
            (
                "The email address or password you entered is incorrect."
                " Forgot your password?"
            ).format(password_reset=url_for('.forgot_password'))
        ))

    other_device = current_user.logged_in_elsewhere()
    return render_template(
        'views/signin.html',
        form=form,
        again=bool(request.args.get('next')),
        other_device=other_device
    )

@login_manager.unauthorized_handler
def sign_in_again():
    return redirect(
        url_for('main.sign_in', next=request.path)
    )
<|endoftext|>


<commit_before>__author__ = 'Tyler Long'
__version__ = '0.4.3'<commit_msg>Bump version to 0.4.4<commit_after>__author__ = 'Tyler Long'
__version__ = '0.4.4'
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

"""
quickavro
~~~~~~~~~~~~

quickavro is a library for working with the avro file format.

:copyright: (c) 2016 by Chris Marshall.
:license: Apache 2.0, see LICENSE for more details.

"""

__title__ = 'quickavro'
__version__ = '0.1.19'
__authors__ = ['Chris Marshall']
__license__ = 'Apache 2.0'
__all__ = ['BinaryEncoder', 'Enum', 'FileReader', 'FileWriter']

from .constants import (
    DEFAULT_SYNC_INTERVAL,
    HEADER_SCHEMA
)
from .errors import (
    CodecNotSupported,
    InvalidSchemaError
)
from .encoder import BinaryEncoder, Enum
from .reader import FileReader
from .writer import FileWriter
<commit_msg>Increment version<commit_after># -*- coding: utf-8 -*-

"""
quickavro
~~~~~~~~~~~~

quickavro is a library for working with the avro file format.

:copyright: (c) 2016 by Chris Marshall.
:license: Apache 2.0, see LICENSE for more details.

"""

__title__ = 'quickavro'
__version__ = '0.1.20'
__authors__ = ['Chris Marshall']
__license__ = 'Apache 2.0'
__all__ = ['BinaryEncoder', 'Enum', 'FileReader', 'FileWriter']

from .constants import (
    DEFAULT_SYNC_INTERVAL,
    HEADER_SCHEMA
)
from .errors import (
    CodecNotSupported,
    InvalidSchemaError
)
from .encoder import BinaryEncoder, Enum
from .reader import FileReader
from .writer import FileWriter
<|endoftext|>


<commit_before>from collections import OrderedDict
from datetime import datetime

from flask import url_for
from flask_login import current_user

from app import db
from app.models.base_model import BaseEntity
from app.models.activity import Activity
from app.models.user import User
from app.models.mollie import Transaction
from app.models.page import PageRevision, Page
from app.utils.google import send_email
from app.utils.page import PageAPI

def export_form_data(r):
    import re
    return re.sub(r'%[0-9A-F]{2}', '', r.data)

class CustomForm(db.Model, BaseEntity):
    """Custom form model.

    A custom form is a form on which users can register themselves
    (see CustomFormResult) and can be bound to activities.
    """

    __tablename__ = 'custom_form'

    owner_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    name = db.Column(db.String(256))
    origin = db.Column(db.String(4096))
    html = db.Column(db.UnicodeText())
    msg_success = db.Column(db.String(2048))
    max_attendants = db.Column(db.Integer)
    introductions = db.Column(db.Integer)
    price = db.Column(db.Float, default=0)
    owner = db.relationship('User', backref=db.backref('custom_forms',
                                                       lazy='dynamic'))
    terms = db.Column(db.String(4096))

    archived = db.Column(db.Boolean)
    requires_direct_payment = db.Column(db.Boolean, default=False,
                                        nullable=False)

    exports = \
        OrderedDict([('user_id', {
            'label': 'Gebruiker ID',
            'export': lambda r: r.owner_id,
            'on_by_default': False,
        }), ('user_email', {
            'label': 'Gebruiker email',
            'export': lambda r: r.owner.email,
            'on_by_default': True,
        }), ('user_name', {
            'label': 'Gebruiker naam',
            'export': lambda r: '%s %s' % (r.owner.first_name,
                                           r.owner.last_name),
            'on_by_default': True,
        }), ('date', {
            'label': 'Inschrijfdatum',
            'export': lambda r: r.created,
            'on_by_default': False,
        }), ('has_paid', {
            'label': 'Heeft betaald',
            'export': lambda r: r.has_paid,
            'on_by_default': True,
        }), ('form', {
            'label': 'Form resultaat',
            'export': export_form_data,
            'on_by_default': False,
        })])

    def __init__(self, owner_id=None, name="", origin="", html="",
                 msg_success="", max_attendants=150, introductions=0,
                 terms=""):
        self.owner_id = owner_id
        self.name = name
        self.origin = origin
        self.html = html
        self.msg_success = msg_success
        self.max_attendants = max_attendants
        self.introductions = introductions
        self.terms = terms
        self.archived = False

    def has_activity(self):
        return (self.activities.count() > 0)

    def get_closest_activity(self):
        return (self.activities
                .order_by(Activity.modified.desc())
                .first())

    def submittable_by(self, user=current_user):
        # Test if the form is accessable through an activity.
        if self.has_activity() and user.is_authenticated:
            return True

        # Query all the page's this form is attached to.
        pages = Page.query.join(PageRevision, CustomForm)\
            .filter(Page.id == PageRevision.page_id)\
            .filter(PageRevision.custom_form_id == self.id).all()

        # Test if we are allowed to read on any on these pages.
        if any([PageAPI.can_read(page) for page in pages]):
            return True

        return False

    def is_archived(self):
        latest_activity = (self.activities.order_by(Activity.end_time.desc())
                           .first())

        return self.archived or (latest_activity and
                                 datetime.now() > latest_activity.end_time)

    @property
    def attendants(self):
        return sum(entry.introductions + 1 for entry in
                   self.custom_form_results.all())

    @classmethod
    def aslist(cls, current=None):
        lst = [
            ('Gevolgde formulieren', cls.qry_followed().all()),
            ('Actieve formulieren', cls.qry_active().all()),
        ]

        if current is not None:
            cf = cls.query.get(current)

            if cf is not None and cf.is_archived():
                lst.append(('Gearchiveerd geselecteerd formulier', [cf]))

        return lst

    @classmethod
    def qry_followed(cls):
        return (
            cls.query
            .outerjoin(Activity, cls.id == Activity.form_id)
            .filter(CustomFormFollower.query
                    .filter(cls.id == CustomFormFollower.form_id,
                            CustomFormFollower.owner_id == current_user.id)
                    .exists(),
                    db.or_(cls.archived == False, cls.archived == None),
                    db.or_(Activity.id == None,
                           db.and_(Activity.id != None,
                                   db.func.now() < Activity.end_time)))
            .order_by(cls.modified.desc()))  # noqa

    @classmethod
    def qry_active(cls):
        return (
            cls.query
            .outerjoin(Activity, cls.id == Activity.form_id)
            .filter(
                db.not_(CustomFormFollower.query
                        .filter(cls.id == CustomFormFollower.form_id,
                                CustomFormFollower.owner_id == current_user.id)
                        .exists()),
                db.or_(cls.archived == False, cls.archived == None),
                db.or_(Activity.id == None,
                       db.and_(Activity.id != None,
                               db.func.now() < Activity.end_time)))
            .order_by(cls.modified.desc()))  # noqa

    @classmethod
    def qry_archived(cls):
        return (
            cls.query
            .outerjoin(Activity, cls.id == Activity.form_id)
            .filter(
                db.or_(cls.archived == True,
                       db.and_(Activity.id != None,
                               db.func.now() >= Activity.end_time)))
            .order_by(cls.modified.desc()))  # noqa

    @staticmethod
    def update_payment(transaction_id, paid):
        transaction = (Transaction.query
                       .filter(Transaction.id == transaction_id)
                       .first())
        if transaction.form_result:
            transaction.form_result.has_paid = paid
            db.session.commit()

class CustomFormResult(db.Model, BaseEntity):
    """Custom form results model.

    The custom form results are the registrations of users on custom forms.
    """

    __tablename__ = 'custom_form_result'

    owner_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    form_id = db.Column(db.Integer, db.ForeignKey('custom_form.id'))
    data = db.Column(db.String(4096))
    has_paid = db.Column(db.Boolean)
    introductions = db.Column(db.Integer)

    owner = db.relationship('User', backref=db.backref('custom_form_results',
                                                       lazy='dynamic'))
    form = db.relationship('CustomForm',
                           backref=db.backref('custom_form_results',
                                              lazy='dynamic'))

    def __init__(self, owner_id=None, form_id=None, data="", has_paid=False,
                 introductions=0, price=0.0):
        self.owner_id = owner_id
        self.form_id = form_id
        self.data = data
        self.has_paid = has_paid
        self.introductions = introductions
        self.price = price
        self.notify_followers()

    def __repr__(self):
        return "<FormResult owner:%s has_paid:%s>" % (self.owner.first_name,
                                                      self.has_paid)

    def notify_followers(self):
        form_url = url_for('custom_form.view_single', form_id=self.form_id,
                           _external=True)
        followers = CustomFormFollower.query\
            .filter(CustomFormFollower.form_id == self.form_id)
        owner = User.query.get(self.owner_id)
        form = CustomForm.query.get(self.form_id)
        for follower in followers:
            send_email(to=follower.owner.email,
                       subject='Formulier ingevuld',
                       email_template='email/form.html',
                       sender='via',
                       user=follower.owner,
                       form_url=form_url,
                       owner=owner.first_name + " " + owner.last_name,
                       form=form.name)

class CustomFormFollower(db.Model, BaseEntity):
    __tablename__ = 'custom_form_follower'

    prints = ('owner_id', 'form_id')

    owner_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    form_id = db.Column(db.Integer)

    owner = db.relationship(
        'User', backref=db.backref('custom_forms_following', lazy='dynamic'))

    def __init__(self, owner_id=None, form_id=None):
        self.owner_id = owner_id
        self.form_id = form_id
<commit_msg>Added introductions to export<commit_after>from collections import OrderedDict
from datetime import datetime

from flask import url_for
from flask_login import current_user

from app import db
from app.models.base_model import BaseEntity
from app.models.activity import Activity
from app.models.user import User
from app.models.mollie import Transaction
from app.models.page import PageRevision, Page
from app.utils.google import send_email
from app.utils.page import PageAPI

def export_form_data(r):
    import re
    return re.sub(r'%[0-9A-F]{2}', '', r.data)

class CustomForm(db.Model, BaseEntity):
    """Custom form model.

    A custom form is a form on which users can register themselves
    (see CustomFormResult) and can be bound to activities.
    """

    __tablename__ = 'custom_form'

    owner_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    name = db.Column(db.String(256))
    origin = db.Column(db.String(4096))
    html = db.Column(db.UnicodeText())
    msg_success = db.Column(db.String(2048))
    max_attendants = db.Column(db.Integer)
    introductions = db.Column(db.Integer)
    price = db.Column(db.Float, default=0)
    owner = db.relationship('User', backref=db.backref('custom_forms',
                                                       lazy='dynamic'))
    terms = db.Column(db.String(4096))

    archived = db.Column(db.Boolean)
    requires_direct_payment = db.Column(db.Boolean, default=False,
                                        nullable=False)

    exports = \
        OrderedDict([('user_id', {
            'label': 'Gebruiker ID',
            'export': lambda r: r.owner_id,
            'on_by_default': False,
        }), ('user_email', {
            'label': 'Gebruiker email',
            'export': lambda r: r.owner.email,
            'on_by_default': True,
        }), ('user_name', {
            'label': 'Gebruiker naam',
            'export': lambda r: '%s %s' % (r.owner.first_name,
                                           r.owner.last_name),
            'on_by_default': True,
        }), ('date', {
            'label': 'Inschrijfdatum',
            'export': lambda r: r.created,
            'on_by_default': False,
        }), ('has_paid', {
            'label': 'Heeft betaald',
            'export': lambda r: r.has_paid,
            'on_by_default': True,
        }), ('form', {
            'label': 'Form resultaat',
            'export': export_form_data,
            'on_by_default': False,
        }), ('introductions', {
            'label': 'Introducees',
            'export': lambda r: r.introductions,
            'on_by_default': True,
        })])

    def __init__(self, owner_id=None, name="", origin="", html="",
                 msg_success="", max_attendants=150, introductions=0,
                 terms=""):
        self.owner_id = owner_id
        self.name = name
        self.origin = origin
        self.html = html
        self.msg_success = msg_success
        self.max_attendants = max_attendants
        self.introductions = introductions
        self.terms = terms
        self.archived = False

    def has_activity(self):
        return (self.activities.count() > 0)

    def get_closest_activity(self):
        return (self.activities
                .order_by(Activity.modified.desc())
                .first())

    def submittable_by(self, user=current_user):
        # Test if the form is accessable through an activity.
        if self.has_activity() and user.is_authenticated:
            return True

        # Query all the page's this form is attached to.
        pages = Page.query.join(PageRevision, CustomForm)\
            .filter(Page.id == PageRevision.page_id)\
            .filter(PageRevision.custom_form_id == self.id).all()

        # Test if we are allowed to read on any on these pages.
        if any([PageAPI.can_read(page) for page in pages]):
            return True

        return False

    def is_archived(self):
        latest_activity = (self.activities.order_by(Activity.end_time.desc())
                           .first())

        return self.archived or (latest_activity and
                                 datetime.now() > latest_activity.end_time)

    @property
    def attendants(self):
        return sum(entry.introductions + 1 for entry in
                   self.custom_form_results.all())

    @classmethod
    def aslist(cls, current=None):
        lst = [
            ('Gevolgde formulieren', cls.qry_followed().all()),
            ('Actieve formulieren', cls.qry_active().all()),
        ]

        if current is not None:
            cf = cls.query.get(current)

            if cf is not None and cf.is_archived():
                lst.append(('Gearchiveerd geselecteerd formulier', [cf]))

        return lst

    @classmethod
    def qry_followed(cls):
        return (
            cls.query
            .outerjoin(Activity, cls.id == Activity.form_id)
            .filter(CustomFormFollower.query
                    .filter(cls.id == CustomFormFollower.form_id,
                            CustomFormFollower.owner_id == current_user.id)
                    .exists(),
                    db.or_(cls.archived == False, cls.archived == None),
                    db.or_(Activity.id == None,
                           db.and_(Activity.id != None,
                                   db.func.now() < Activity.end_time)))
            .order_by(cls.modified.desc()))  # noqa

    @classmethod
    def qry_active(cls):
        return (
            cls.query
            .outerjoin(Activity, cls.id == Activity.form_id)
            .filter(
                db.not_(CustomFormFollower.query
                        .filter(cls.id == CustomFormFollower.form_id,
                                CustomFormFollower.owner_id == current_user.id)
                        .exists()),
                db.or_(cls.archived == False, cls.archived == None),
                db.or_(Activity.id == None,
                       db.and_(Activity.id != None,
                               db.func.now() < Activity.end_time)))
            .order_by(cls.modified.desc()))  # noqa

    @classmethod
    def qry_archived(cls):
        return (
            cls.query
            .outerjoin(Activity, cls.id == Activity.form_id)
            .filter(
                db.or_(cls.archived == True,
                       db.and_(Activity.id != None,
                               db.func.now() >= Activity.end_time)))
            .order_by(cls.modified.desc()))  # noqa

    @staticmethod
    def update_payment(transaction_id, paid):
        transaction = (Transaction.query
                       .filter(Transaction.id == transaction_id)
                       .first())
        if transaction.form_result:
            transaction.form_result.has_paid = paid
            db.session.commit()

class CustomFormResult(db.Model, BaseEntity):
    """Custom form results model.

    The custom form results are the registrations of users on custom forms.
    """

    __tablename__ = 'custom_form_result'

    owner_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    form_id = db.Column(db.Integer, db.ForeignKey('custom_form.id'))
    data = db.Column(db.String(4096))
    has_paid = db.Column(db.Boolean)
    introductions = db.Column(db.Integer)

    owner = db.relationship('User', backref=db.backref('custom_form_results',
                                                       lazy='dynamic'))
    form = db.relationship('CustomForm',
                           backref=db.backref('custom_form_results',
                                              lazy='dynamic'))

    def __init__(self, owner_id=None, form_id=None, data="", has_paid=False,
                 introductions=0, price=0.0):
        self.owner_id = owner_id
        self.form_id = form_id
        self.data = data
        self.has_paid = has_paid
        self.introductions = introductions
        self.price = price
        self.notify_followers()

    def __repr__(self):
        return "<FormResult owner:%s has_paid:%s>" % (self.owner.first_name,
                                                      self.has_paid)

    def notify_followers(self):
        form_url = url_for('custom_form.view_single', form_id=self.form_id,
                           _external=True)
        followers = CustomFormFollower.query\
            .filter(CustomFormFollower.form_id == self.form_id)
        owner = User.query.get(self.owner_id)
        form = CustomForm.query.get(self.form_id)
        for follower in followers:
            send_email(to=follower.owner.email,
                       subject='Formulier ingevuld',
                       email_template='email/form.html',
                       sender='via',
                       user=follower.owner,
                       form_url=form_url,
                       owner=owner.first_name + " " + owner.last_name,
                       form=form.name)

class CustomFormFollower(db.Model, BaseEntity):
    __tablename__ = 'custom_form_follower'

    prints = ('owner_id', 'form_id')

    owner_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    form_id = db.Column(db.Integer)

    owner = db.relationship(
        'User', backref=db.backref('custom_forms_following', lazy='dynamic'))

    def __init__(self, owner_id=None, form_id=None):
        self.owner_id = owner_id
        self.form_id = form_id
<|endoftext|>


<commit_before>#! /usr/bin/env python
# -*- encoding: utf-8 -*-

"""
Measures your typing speed in words per minute (WPM).

This file is part of the wpm software.
Copyright 2017, 2018 Christian Stigen Larsen

Distributed under the GNU Affero General Public License (AGPL) v3 or later. See
the file LICENSE.txt for the full license text. This software makes use of open
source software.

The quotes database is *not* covered by the AGPL!
"""

__author__ = "Christian Stigen Larsen"
__copyright__ = "Copyright 2017, 2018 Christian Stigen Larsen"
__license__ = "GNU AGPL v3 or later"
__version__ = "1.50.1"
<commit_msg>Bumps to v1.50.2<commit_after>#! /usr/bin/env python
# -*- encoding: utf-8 -*-

"""
Measures your typing speed in words per minute (WPM).

This file is part of the wpm software.
Copyright 2017, 2018 Christian Stigen Larsen

Distributed under the GNU Affero General Public License (AGPL) v3 or later. See
the file LICENSE.txt for the full license text. This software makes use of open
source software.

The quotes database is *not* covered by the AGPL!
"""

__author__ = "Christian Stigen Larsen"
__copyright__ = "Copyright 2017, 2018 Christian Stigen Larsen"
__license__ = "GNU AGPL v3 or later"
__version__ = "1.50.2"
<|endoftext|>


<commit_before>#!/usr/bin/env python

import requests
import sys

from argparse import ArgumentParser
from ConfigParser import ConfigParser
from datetime import datetime, timedelta

# The URL is hard coded. I'm comfortable doing this since it's unlikely that
# the URL will change without resulting in an API change that will require
# changes to this script.
_URL = 'http://otx.alienvault.com/api/v1/pulses/subscribed'

# Bro Intel file header format
_HEADER = "#fields\tindicator\tindicator_type\tmeta.source\tmeta.url\tmeta.do_notice\n"

# Mapping of OTXv2 Indicator types to Bro Intel types, additionally,
# identifies unsupported intel types to prevent errors in Bro.
_MAP = {
    "IPv4": "Intel::ADDR",
    "IPv6": "Intel::ADDR",
    "domain": "Intel::DOMAIN",
    "hostname": "Intel::DOMAIN",
    "email": "Intel::EMAIL",
    "URL": "Intel::URL",
    "URI": "Intel::URL",
    "FileHash-MD5": "Intel::FILE_HASH",
    "FileHash-SHA1": "Intel::FILE_HASH",
    "FileHash-SHA256": "Intel::FILE_HASH",
}

def _get(key, mtime, limit=20, next_request=''):
    '''
    Retrieves a result set from the OTXv2 API using the restrictions of
    mtime as a date restriction.
    '''

    headers = {'X-OTX-API-KEY': key}
    params = {'limit': limit, 'modified_since': mtime}
    if next_request == '':
        r = requests.get(_URL, headers=headers, params=params)
    else:
        r = requests.get(next_request, headers=headers)

    # Depending on the response code, return the valid response.
    if r.status_code == 200:
        return r.json()
    if r.status_code == 403:
        print("An invalid API key was specified.")
        sys.exit(1)
    if r.status_code == 400:
        print("An invalid request was made.")
        sys.exit(1)

def iter_pulses(key, mtime, limit=20):
    '''
    Creates an iterator that steps through Pulses since mtime using key.
    '''

    # Populate an initial result set, after this the API will generate the next
    # request in the loop for every iteration.
    initial_results = _get(key, mtime, limit)
    for result in initial_results['results']:
        yield result

    next_request = initial_results['next']
    while next_request:
        json_data = _get(key, mtime, next_request=next_request)
        for result in json_data['results']:
            yield result
        next_request = json_data['next']

def map_indicator_type(indicator_type):
    '''
    Maps an OTXv2 indicator type to a Bro Intel Framework type.
    '''

    return _MAP.get(indicator_type)

def main():
    '''Retrieve intel from OTXv2 API.'''

    parser = ArgumentParser(description='AlienVault OTXv2 Bro Client')
    parser.add_argument('-c', '--config',
                        help='configuration file path',
                        default='bro-otx.conf')
    args = parser.parse_args()

    config = ConfigParser()
    config.read(args.config)
    key = config.get('otx', 'api_key')
    days = int(config.get('otx', 'days_of_history'))
    outfile = config.get('otx', 'outfile')
    do_notice = config.get('otx', 'do_notice')

    mtime = (datetime.now() - timedelta(days=days)).isoformat()

    with open(outfile, 'wb') as f:
        f.write(_HEADER)
        for pulse in iter_pulses(key, mtime):
            # Intel description for notices
            description = 'AlienVault OTXv2 - %s ID: %s Author: %s' % (
                                pulse[u'name'],
                                pulse[u'id'],
                                pulse[u'author_name'])
            # A lot of care has to go into creating this description.
            # Tabs are removed to prevent Bro from throwing errors.
            # Unicode is also dropped to prevent errors.
            description = description.replace('\t', ' ')
            description = description.encode('ascii', 'replace')
            for indicator in pulse[u'indicators']:
                bro_type = map_indicator_type(indicator[u'type'])
                if bro_type is None:
                    continue
                try:
                    url = pulse[u'references'][0]
                except IndexError:
                    url = 'https://otx.alienvault.com'
                fields = [indicator[u'indicator'],
                    bro_type,
                    description,
                    url,
                    do_notice + '\n']
                f.write('\t'.join(fields))

if __name__ == '__main__':
    main()
<commit_msg>Fixed an issue (#4) where Bro would output an error due to the fact that the intel file is written in place.<commit_after>#!/usr/bin/env python

import requests
import sys
import os

from argparse import ArgumentParser
from ConfigParser import ConfigParser
from datetime import datetime, timedelta

# The URL is hard coded. I'm comfortable doing this since it's unlikely that
# the URL will change without resulting in an API change that will require
# changes to this script.
_URL = 'http://otx.alienvault.com/api/v1/pulses/subscribed'

# Bro Intel file header format
_HEADER = "#fields\tindicator\tindicator_type\tmeta.source\tmeta.url\tmeta.do_notice\n"

# Mapping of OTXv2 Indicator types to Bro Intel types, additionally,
# identifies unsupported intel types to prevent errors in Bro.
_MAP = {
    "IPv4": "Intel::ADDR",
    "IPv6": "Intel::ADDR",
    "domain": "Intel::DOMAIN",
    "hostname": "Intel::DOMAIN",
    "email": "Intel::EMAIL",
    "URL": "Intel::URL",
    "URI": "Intel::URL",
    "FileHash-MD5": "Intel::FILE_HASH",
    "FileHash-SHA1": "Intel::FILE_HASH",
    "FileHash-SHA256": "Intel::FILE_HASH",
}

def _get(key, mtime, limit=20, next_request=''):
    '''
    Retrieves a result set from the OTXv2 API using the restrictions of
    mtime as a date restriction.
    '''

    headers = {'X-OTX-API-KEY': key}
    params = {'limit': limit, 'modified_since': mtime}
    if next_request == '':
        r = requests.get(_URL, headers=headers, params=params)
    else:
        r = requests.get(next_request, headers=headers)

    # Depending on the response code, return the valid response.
    if r.status_code == 200:
        return r.json()
    if r.status_code == 403:
        print("An invalid API key was specified.")
        sys.exit(1)
    if r.status_code == 400:
        print("An invalid request was made.")
        sys.exit(1)

def iter_pulses(key, mtime, limit=20):
    '''
    Creates an iterator that steps through Pulses since mtime using key.
    '''

    # Populate an initial result set, after this the API will generate the next
    # request in the loop for every iteration.
    initial_results = _get(key, mtime, limit)
    for result in initial_results['results']:
        yield result

    next_request = initial_results['next']
    while next_request:
        json_data = _get(key, mtime, next_request=next_request)
        for result in json_data['results']:
            yield result
        next_request = json_data['next']

def map_indicator_type(indicator_type):
    '''
    Maps an OTXv2 indicator type to a Bro Intel Framework type.
    '''

    return _MAP.get(indicator_type)

def main():
    '''Retrieve intel from OTXv2 API.'''

    parser = ArgumentParser(description='AlienVault OTXv2 Bro Client')
    parser.add_argument('-c', '--config',
                        help='configuration file path',
                        default='bro-otx.conf')
    args = parser.parse_args()

    config = ConfigParser()
    config.read(args.config)
    key = config.get('otx', 'api_key')
    days = int(config.get('otx', 'days_of_history'))
    outfile = config.get('otx', 'outfile')
    do_notice = config.get('otx', 'do_notice')

    mtime = (datetime.now() - timedelta(days=days)).isoformat()

    with open(outfile + '.tmp', 'wb') as f:
        f.write(_HEADER)
        for pulse in iter_pulses(key, mtime):
            # Intel description for notices
            description = 'AlienVault OTXv2 - %s ID: %s Author: %s' % (
                                pulse[u'name'],
                                pulse[u'id'],
                                pulse[u'author_name'])
            # A lot of care has to go into creating this description.
            # Tabs are removed to prevent Bro from throwing errors.
            # Unicode is also dropped to prevent errors.
            description = description.replace('\t', ' ')
            description = description.encode('ascii', 'replace')
            for indicator in pulse[u'indicators']:
                bro_type = map_indicator_type(indicator[u'type'])
                if bro_type is None:
                    continue
                try:
                    url = pulse[u'references'][0]
                except IndexError:
                    url = 'https://otx.alienvault.com'
                fields = [indicator[u'indicator'],
                    bro_type,
                    description,
                    url,
                    do_notice + '\n']
                f.write('\t'.join(fields))

	os.rename(outfile + '.tmp', outfile)

if __name__ == '__main__':
    main()
<|endoftext|>


<commit_before>"""
    wtforms.form
    ~~~~~~~~~~~~

    TODO

    :copyright: 2007 by James Crasta, Thomas Johansson.
    :license: MIT, see LICENSE.txt for details.
"""
from wtforms.validators import ValidationError
import types

class Form(object):
    def __init__(self, formdata=None, obj=None, prefix='', idprefix='', **kwargs):
        if prefix:
            prefix += '_'
        self._idprefix = idprefix

        # populate data from form and optional instance and defaults
        self.errors = {}
        self._fields = {}
        has_formdata = bool(formdata)
        for name in dir(self.__class__):
            f = getattr(self.__class__, name, None)
	    if isinstance(f, types.UnboundMethodType):
	    	f = f.im_func
            if name.startswith('_') or not getattr(f, '_formfield', False):
                continue

            form_name = prefix + name
            self._fields[name] = field = f(name=form_name, form=self)
            setattr(self, name, field)

            if name in kwargs:
                field.process_data(kwargs[name], has_formdata)
            if hasattr(obj, name):
                field.process_data(getattr(obj, name), has_formdata)
            if has_formdata and form_name in formdata:
                field.process_formdata(formdata.getlist(form_name))

    def __iter__(self):
        for field in self._fields.itervalues():
            yield field

    def validate(self):
        success = True
        for name, field in self._fields.iteritems():
            field.errors = []
            validators = list(field.validators)
            validators.append(field._validate)
            inline_validator = getattr(self.__class__, '_validate_%s' % name, None)
            if inline_validator is not None:
                validators.append(inline_validator)
            for validator in validators:
                try:
                    validator(self, field)
                except ValidationError, e:
                    field.errors.append(e.message)
            if field.errors:
                success = False
                self.errors[name] = field.errors
        return success

    def _get_data(self):
        data = {}
        for name, val in self._fields.iteritems():
            data[name] = val.data
        return data
    data = property(_get_data)

    def auto_populate(self, model):
        """
        Automatically copy our converted form values into the model object.

        This can be very dangerous if not used properly, so make sure to only use
        this in forms with proper validators and the right attributes.
        """
        for name, val in self._fields.iteritems():
            setattr(model, name, val.data)
<commit_msg>Make validation work without error on python 2.4/2.5.  Also make ValueError allowed as a validation error. Refs #2, fixes #11<commit_after>"""
    wtforms.form
    ~~~~~~~~~~~~

    TODO

    :copyright: 2007 by James Crasta, Thomas Johansson.
    :license: MIT, see LICENSE.txt for details.
"""
from wtforms.validators import ValidationError
import types

class Form(object):
    def __init__(self, formdata=None, obj=None, prefix='', idprefix='', **kwargs):
        if prefix:
            prefix += '_'
        self._idprefix = idprefix

        # populate data from form and optional instance and defaults
        self.errors = {}
        self._fields = {}
        has_formdata = bool(formdata)
        for name in dir(self.__class__):
            f = getattr(self.__class__, name, None)
	    if isinstance(f, types.UnboundMethodType):
	    	f = f.im_func
            if name.startswith('_') or not getattr(f, '_formfield', False):
                continue

            form_name = prefix + name
            self._fields[name] = field = f(name=form_name, form=self)
            setattr(self, name, field)

            if name in kwargs:
                field.process_data(kwargs[name], has_formdata)
            if hasattr(obj, name):
                field.process_data(getattr(obj, name), has_formdata)
            if has_formdata and form_name in formdata:
                field.process_formdata(formdata.getlist(form_name))

    def __iter__(self):
        for field in self._fields.itervalues():
            yield field

    def validate(self):
        success = True
        for name, field in self._fields.iteritems():
            field.errors = []
            validators = list(field.validators)
            validators.append(field._validate)
            inline_validator = getattr(self.__class__, '_validate_%s' % name, None)
            if inline_validator is not None:
                validators.append(inline_validator)
            for validator in validators:
                try:
                    validator(self, field)
                except ValueError, e:
                    field.errors.append(e.args[0])
            if field.errors:
                success = False
                self.errors[name] = field.errors
        return success

    def _get_data(self):
        data = {}
        for name, val in self._fields.iteritems():
            data[name] = val.data
        return data
    data = property(_get_data)

    def auto_populate(self, model):
        """
        Automatically copy our converted form values into the model object.

        This can be very dangerous if not used properly, so make sure to only use
        this in forms with proper validators and the right attributes.
        """
        for name, val in self._fields.iteritems():
            setattr(model, name, val.data)
<|endoftext|>


<commit_before>from typing import List

import usb.core
import usb.util
import threading
from treehopper.api.HardwarePwmManager import HardwarePwmManager
from treehopper.api.HardwareSpi import HardwareSpi
from treehopper.api.HardwareUart import HardwareUart
from treehopper.utils.EventHandler import EventHandler
from treehopper.api.Pin import Pin
from treehopper.api.HardwarePwm import HardwarePwm
from treehopper.api.HardwareI2c import HardwareI2c
from treehopper.api.DeviceCommands import DeviceCommands
from treehopper.api.SoftPwmManager import SoftPwmManager

class TreehopperUsb:
    """Core object for communicating with Treehopper USB boards"""

    def __init__(self, dev: usb.core.Device):
        self._pin_listener_thread = threading.Thread(target=self._pin_listener)
        self._dev = dev
        self._comms_lock = threading.Lock()

        self._pin_report_endpoint = 0x81
        self._peripheral_response_endpoint = 0x82
        self._pin_config_endpoint = 0x01
        self._peripheral_config_endpoint = 0x02

        self.pins = []  # type: List[Pin]
        for i in range(20):
            self.pins.append(Pin(self, i))

        self.pins[0].name = "Pin 0 (SCK)"
        self.pins[1].name = "Pin 1 (MISO)"
        self.pins[2].name = "Pin 2 (MOSI)"
        self.pins[3].name = "Pin 3 (SDA)"
        self.pins[4].name = "Pin 4 (SCL)"
        self.pins[5].name = "Pin 5 (TX)"
        self.pins[6].name = "Pin 6 (RX)"
        self.pins[7].name = "Pin 7 (PWM1)"
        self.pins[8].name = "Pin 8 (PWM2)"
        self.pins[9].name = "Pin 9 (PWM3)"

        self.uart = HardwareUart(self)
        self.i2c = HardwareI2c(self)
        self.spi = HardwareSpi(self)
        self.hardware_pwm_manager = HardwarePwmManager(self)
        self._soft_pwm_manager = SoftPwmManager(self)
        self.pwm1 = HardwarePwm(self.pins[7])
        self.pwm2 = HardwarePwm(self.pins[8])
        self.pwm3 = HardwarePwm(self.pins[9])

        self._led = False
        self._connected = False
        self._pin_report_received = EventHandler(self)

    def connect(self):
        """Connect to the board.

        Calling this method will connect to the board and start the pin listener update thread. Repeated calls
        to this method are ignored."""
        if self._connected:
            return

        self._dev.set_configuration()
        self._connected = True
        self._pin_listener_thread.start()

    def disconnect(self):
        """Disconnect from the board.

        This method disconnects from the board and stops the pin listener update thread. Repeated calls to this
        method are ignored."""
        if not self._connected:
            return

        self._connected = False
        self._pin_listener_thread.join()
        usb.util.dispose_resources(self._dev)

    def _pin_listener(self):
        while self._connected:
            try:
                data = self._dev.read(self._pin_report_endpoint, 41, 1000)
                i = 1
                if data[0] == 0x02:
                    for pin in self.pins:
                        pin._update_value(data[i], data[i+1])
                        i += 2
            except:
                pass
        return

    def _send_pin_config(self, data: List[int]):
        self._dev.write(self._pin_config_endpoint, data)

    def _send_peripheral_config_packet(self, data: List[int]):
        self._dev.write(self._peripheral_config_endpoint, data)

    def _receive_comms_response_packet(self, num_bytes_to_read: int) -> List[int]:
        return self._dev.read(self._peripheral_response_endpoint, num_bytes_to_read)

    @property
    def led(self) -> bool:
        """
        [Property] Gets or sets the state of the LED.
        :return: the state of the LED
        """
        return self._led

    @led.setter
    def led(self, val: bool):
        """
        [Property] Gets or sets the state of the LED.
        :param val: the new state of the LED
        """
        self._led = val
        data = [DeviceCommands.LedConfig, self._led]
        self._dev.write(self._peripheral_config_endpoint, data)

    @property
    def connected(self):
        """[Property] Gets whether the board is connected."""
        return self._connected
<commit_msg>Add docs + serial/name/reboot functions<commit_after>from time import sleep
from typing import List

import usb.core
import usb.util
import threading

from treehopper.api.HardwarePwmManager import HardwarePwmManager
from treehopper.api.HardwareSpi import HardwareSpi
from treehopper.api.HardwareUart import HardwareUart
from treehopper.utils.EventHandler import EventHandler
from treehopper.api.Pin import Pin
from treehopper.api.HardwarePwm import HardwarePwm
from treehopper.api.HardwareI2c import HardwareI2c
from treehopper.api.DeviceCommands import DeviceCommands
from treehopper.api.SoftPwmManager import SoftPwmManager

class TreehopperUsb:
    """
    The core class for communicating with Treehopper USB boards.

    This class represents a Treehopper board. You'll access all the pins, peripherals, and board functions through
    this object, which will automatically create all peripheral instances for you.

    Warning:
        Do not attempt to create a TreehopperUsb instance manually; always obtain references to boards from the
        treehopper.api.find_boards() function.

    Examples:
        >>> board = find_boards()[0]        # Get the first board.
        >>> board.connect()                 # Be sure to connect before doing anything else.
        >>> board.led = True                # Turn on the board's LED.
        >>> imu = Mpu9250.probe(board.i2c)  # Connect an MPU9250 9-DoF IMU to the I2C interface on the board.
        >>> print(imu.accelerometer)        # Print the acceleration reading from the sensor.
        '[0.95, 0.01, 0.03]'
        >>> board.disconnect()              # Disconnect from the board when finished.

    Attributes:
        pins (list[DigitalPin]): Collection of pins that belong to this board (List[Pin.Pin]).
        spi (HardwareSpi): The SPI peripheral (HardwareSpi.HardwareSpi).
        i2c (HardwareI2c): The I2C peripheral (HardwareI2c.HardwareI2c).
        uart (HardwareUart): The UART peripheral (HardwareUart.HardwareUart).
        pwm1 (HardwarePwm): The PWM1 peripheral (HardwarePwm.HardwarePwm).
        pwm2 (HardwarePwm): The PWM2 peripheral (HardwarePwm.HardwarePwm).
        pwm3 (HardwarePwm): The PWM3 peripheral (HardwarePwm.HardwarePwm).
        hardware_pwm_manager (HardwarePwmManager): The hardware PWM manager (HardwarePwmManager.HardwarePwmManager).

    """
    def __init__(self, dev: usb.core.Device):
        self._pin_listener_thread = threading.Thread(target=self._pin_listener)
        self._dev = dev
        self._comms_lock = threading.Lock()

        self._pin_report_endpoint = 0x81
        self._peripheral_response_endpoint = 0x82
        self._pin_config_endpoint = 0x01
        self._peripheral_config_endpoint = 0x02

        self.pins = []  # type: List[Pin]

        for i in range(20):
            self.pins.append(Pin(self, i))

        self.pins[0].name = "Pin 0 (SCK)"
        self.pins[1].name = "Pin 1 (MISO)"
        self.pins[2].name = "Pin 2 (MOSI)"
        self.pins[3].name = "Pin 3 (SDA)"
        self.pins[4].name = "Pin 4 (SCL)"
        self.pins[5].name = "Pin 5 (TX)"
        self.pins[6].name = "Pin 6 (RX)"
        self.pins[7].name = "Pin 7 (PWM1)"
        self.pins[8].name = "Pin 8 (PWM2)"
        self.pins[9].name = "Pin 9 (PWM3)"

        self.spi = HardwareSpi(self)
        self.i2c = HardwareI2c(self)
        self.uart = HardwareUart(self)

        self.pwm1 = HardwarePwm(self.pins[7])
        self.pwm2 = HardwarePwm(self.pins[8])
        self.pwm3 = HardwarePwm(self.pins[9])

        self.hardware_pwm_manager = HardwarePwmManager(self)
        self._soft_pwm_manager = SoftPwmManager(self)

        self._led = False
        self._connected = False
        self._pin_report_received = EventHandler(self)

    def connect(self):
        """
        Connect to the board.

        Calling this method will connect to the board and start the pin listener update thread. Repeated calls
        to this method are ignored.

        Warning:
            You must connect to the board before performing any operations (other than querying the name()
            or serial_number() of the board).

        Returns:
            None

        """
        if self._connected:
            return

        self._dev.set_configuration()
        self._connected = True
        self._pin_listener_thread.start()

    def disconnect(self):
        """Disconnect from the board.

        This method disconnects from the board and stops the pin listener update thread. Repeated calls to this
        method are ignored."""
        if not self._connected:
            return

        self._connected = False
        self._pin_listener_thread.join()
        usb.util.dispose_resources(self._dev)

    def reboot(self):
        """
        Reboots the board.

        Calling this method will automatically call the disconnect() method, and no further communication will
        be possible until the board is reopened.

        Returns:
            None
        """
        self._send_peripheral_config_packet([DeviceCommands.Reboot])
        self.disconnect()

    def reboot_into_bootloader(self):
        """
        Reboots the board into bootloader mode.

        Calling this method will automatically call the disconnect() method, and no further communication will
        be possible. You can load new firmware onto the board once in bootloader mode, or if you wish to
        return to normal operation, replug the board to reset it.

        Returns:
            None
        """
        self._send_peripheral_config_packet([DeviceCommands.EnterBootloader])
        self.disconnect()

    def update_serial_number(self, serial_number: str):
        """
        Update the serial number on the device.

        While the new serial number is immediately available from the SerialNumber property, the changes
        will not take effect in other applications until the device is reset. This can be done by calling
        reboot().

        Args:
            serial_number (str): a 60-character (or fewer) string containing the new serial number

        Returns:
            None

        Examples:
        >>> board = find_boards()[0]                 # Get the first board.
        >>> board.connect()                          # Be sure to connect before doing anything else.
        >>> board.update_serial_number("a3bY392")    # Change the serial number.
        >>> board.reboot()                           # Reboot the board so the OS picks up the changes.
        """
        length = len(serial_number)
        if length > 60:
            raise RuntimeError("String must be 60 characters or less")

        data_to_send = [DeviceCommands.FirmwareUpdateSerial, length] + list(serial_number.encode())
        self._send_peripheral_config_packet(data_to_send)
        sleep(0.1)

    def update_device_name(self, device_name: str):
        """
        Update the device name on the device.

        While the new serial number is immediately available from the SerialNumber property, the changes
        will not take effect in other applications until the device is reset. This can be done by calling
        reboot().

        Note:
            Microsoft Windows caches the device name in the registry when it is first attached to the board, so even
            if you change the device name with this function, you won't see the new device name --- even after
            replugging the board. To force Windows to update the registry with the new name, make sure to change the
            serial number, too (see update_serial_number()).

        Args:
            device_name (str): a 60-character (or fewer) string containing the new device name.

        Returns:
            None

        Examples:
        >>> board = find_boards()[0]                 # Get the first board.
        >>> board.connect()                          # Be sure to connect before doing anything else.
        >>> board.update_device_name("Acme Widget")  # Update the device name.
        >>> board.update_serial_number("a3bY392")    # Change the serial number to force Windows refresh.
        >>> board.reboot()                           # Reboot the board so the OS picks up the changes.

        """
        length = len(device_name)
        if length > 60:
            raise RuntimeError("String must be 60 characters or less")

        data_to_send = [DeviceCommands.FirmwareUpdateName, length] + list(device_name.encode())
        self._send_peripheral_config_packet(data_to_send)
        sleep(0.1)

    @property
    def serial_number(self):
        """
        [Property] Gets the serial number of the board.

        This property is available to read even without connecting to the board. If you wish to change the serial number,
        use update_serial_number().

        Note:
            While you do not need to connect() to the board before querying its serial number, you will not be able
            to retrieve the serial number of a board to which another application is connected.

            Treehopper's Python USB backend calls into LibUSB, which doesn't support querying the OS for device info,
            so LibUSB implicitly connects to the board, queries the string descriptor, and disconnects. Since
            concurrent operation isn't supported by LibUSB, this operation will error if the board is already open.

        Returns:
            str: The serial number.

        """
        return self._dev.serial_number

    @property
    def name(self):
        """
        [Property] Gets the device name of the board.

        This property is available to read even without connecting to the board. If you wish to change the device name,
        use update_device_name().

        Note:
            While you do not need to connect() to the board before querying its device name, you will not be able
            to retrieve the device name of a board to which another application is connected.

            Treehopper's Python USB backend calls into LibUSB, which doesn't support querying the OS for device info,
            so LibUSB implicitly connects to the board, queries the string descriptor, and disconnects. Since
            concurrent operation isn't supported by LibUSB, this operation will error if the board is already open.

        Returns:
            str: The device name.

        """
        return self._dev.product

    def _pin_listener(self):
        while self._connected:
            try:
                data = self._dev.read(self._pin_report_endpoint, 41, 1000)
                i = 1
                if data[0] == 0x02:
                    for pin in self.pins:
                        pin._update_value(data[i], data[i+1])
                        i += 2
            except:
                pass
        return

    def _send_pin_config(self, data: List[int]):
        self._dev.write(self._pin_config_endpoint, data)

    def _send_peripheral_config_packet(self, data: List[int]):
        self._dev.write(self._peripheral_config_endpoint, data)

    def _receive_comms_response_packet(self, num_bytes_to_read: int) -> List[int]:
        return self._dev.read(self._peripheral_response_endpoint, num_bytes_to_read)

    @property
    def led(self) -> bool:
        """
        [Property] Gets the state of the LED.

        Returns:
            bool: The current state of the LED.

        """
        return self._led

    @led.setter
    def led(self, val: bool) -> None:
        """
        [Property] Sets the state of the LED.

        Args:
            val (bool): The new state of the LED.

        Returns:
            None
        """
        self._led = val
        data = [DeviceCommands.LedConfig, self._led]
        self._dev.write(self._peripheral_config_endpoint, data)

    @property
    def connected(self):
        """
        [Property] Gets whether the board is connected.

        Returns:
            bool: Whether the board is connected

        Note:
            The board will automatically disconnect if an unrecoverable error is encountered (which includes a disconnect),
            so this is a useful property to consult to determine if a board is physically attached to a computer.
        """
        return self._connected
<|endoftext|>


<commit_before>import clr
import os

dll_path = os.path.dirname(os.path.abspath(__file__)) + r'..\bin\CSWhiteLibrary.dll'
clr.AddReference(dll_path)

from CSWhiteLibrary import Keywords
WHITE_LIB = Keywords()

class WhiteLibrary(object):

    def launch_application(self, sut):
        '''
        Launch windows application
        | Arguments | Usage | (M)andatory / (O)ptional |
        | sut | application under testing | M |
        '''
        WHITE_LIB.launch_application(sut)

    def attach_window(self, window):
        '''
        Attach to window in application
        | Arguments | Usage | (M)andatory / (O)ptional |
        | window | window to attach | M |
        '''
        WHITE_LIB.attach_window(window)

    def close_application(self):
        '''
        Close application
        | No arguments |
        '''
        WHITE_LIB.close_application()

    def set_logging_level(self, level):
        '''
        Set log level
        | Arguments | Usage | (M)andatory / (O)ptional |
        | level | log level (info / debug / warn) | M |
        '''
        WHITE_LIB.set_log_level(level)

    def input_text_to_textbox(self, locator, text):
        '''
        Write text to textbox
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        | text | inserted string | M |
        '''
        WHITE_LIB.input_text_textbox(locator, text)

    def set_slider_value(self, locator, double):
        '''
        Write slider to value double
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        | double | inserted value (must be between scale) | M |
        '''
        WHITE_LIB.set_slider(locator, double)

    def verify_slider_value(self, locator, expected):
        '''
        Verify slider value
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        | actual | expected double | M |
        '''
        actual = WHITE_LIB.verify_slider(locator)
        verify_value(expected, actual)

    def verify_progressbar_value(self, locator, expected):
        '''
        Verify progressbar value
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        | actual | expected double | M |
        '''
        actual = WHITE_LIB.verify_progressbar(locator)
        verify_value(expected, actual)

    def verify_text_in_textbox(self, locator, expected):
        '''
        Verify text in textbox
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        | actual | expected text | M |
        '''
        actual = WHITE_LIB.verify_text_textbox(locator)
        verify_value(expected, actual)

    def verify_label(self, locator, expected):
        '''
        Verify text in label
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        | actual | expected text | M |
        '''
        actual = WHITE_LIB.verify_label(locator)
        verify_value(expected, actual)

    def select_combobox_value(self, locator, value):
        '''
        Select combobox value
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        | value | selected value | M |
        '''
        WHITE_LIB.select_combobox_value(locator, value)

    def select_listbox_value(self, locator, value):
        '''
        Select listbox value
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        | value | selected value | M |
        '''
        WHITE_LIB.select_listbox_value(locator, value)

    def toggle_check_box(self, locator):
        '''
        Toggle check box
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        '''
        WHITE_LIB.toggle_check_box(locator)

    def select_combobox_index(self, locator, index):
        '''
        Select combobox index
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        | index | combobox index | M |
        '''
        WHITE_LIB.select_combobox_index(locator, int(index))

    def verify_combobox_item(self, locator, expected):
        '''
        Verify combobox selected value
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        | actual | expected value | M |
        '''
        actual = WHITE_LIB.verify_combobox_item(locator)
        verify_value(expected, actual)

    def verify_button(self, locator, expected):
        '''
        Verify text in button
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        | actual | expected text | M |
        '''
        actual = WHITE_LIB.verify_button(locator)
        verify_value(expected, actual)

    def click_button(self, locator):
        '''
        Click button
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        '''
        WHITE_LIB.click_button(locator)

    def verify_radio_button(self, locator, expected):
        '''
        Verify value of radio button
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        | actual | expected value | M |
        '''
        actual = WHITE_LIB.verify_radio_button(locator)
        verify_value(expected, actual)

    def verify_check_box(self, locator, expected):
        '''
        Verify value of check box
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        | actual | expected value | M |
        '''
        actual = WHITE_LIB.verify_check_box(locator)
        verify_value(expected, actual)

    def select_radio_button(self, locator):
        '''
        Click button
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        '''
        WHITE_LIB.select_radio_button(locator)

    def verify_menu(self, locator, expected):
        '''
        Verify menu item exists
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        | expected | expected text in value | M |
        '''
        actual = WHITE_LIB.verify_menu(locator)
        verify_value(expected, actual)

    def click_menu_button(self, locator):
        '''
        Click menu button
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        '''
        WHITE_LIB.click_menu_button(locator)

    def select_modal_window(self, locator):
        '''
        Select modal window by title
        | Arguments | Usage | (M)andatory / (O)ptional |
        | Title | Modal window title | M |
        '''
        WHITE_LIB.select_modal_window(locator)

    def select_tab_page(self, locator, title):
        """ Selects a tab page. """
        WHITE_LIB.selectTabPage(locator, title)

    def select_tree_node(self, locator, *node_path):
        """ Selects a tree node. """
        WHITE_LIB.selectTreeNode(locator, node_path)

    def expand_tree_node(self, locator, *node_path):
        """ Expands a tree node. """
        WHITE_LIB.expandTreeNode(locator, node_path)

    def double_click_tree_node(self, locator, *node_path):
        """ Double-clicks a tree node. """
        WHITE_LIB.doubleClickTreeNode(locator, node_path)

    def right_click_tree_node(self, locator, *node_path):
        """ Right-clicks a tree node. """
        WHITE_LIB.rightClickTreeNode(locator, node_path)

def verify_value(expected, actual):
    if expected != actual:
        raise AssertionError("Correct value not found: %s != %s" % (expected, actual))<commit_msg>Still<commit_after>import clr
import os

dll_path = os.path.dirname(os.path.abspath(__file__)) + r'\..\bin\CSWhiteLibrary.dll'
clr.AddReference(dll_path)

from CSWhiteLibrary import Keywords
WHITE_LIB = Keywords()

class WhiteLibrary(object):

    def launch_application(self, sut):
        '''
        Launch windows application
        | Arguments | Usage | (M)andatory / (O)ptional |
        | sut | application under testing | M |
        '''
        WHITE_LIB.launch_application(sut)

    def attach_window(self, window):
        '''
        Attach to window in application
        | Arguments | Usage | (M)andatory / (O)ptional |
        | window | window to attach | M |
        '''
        WHITE_LIB.attach_window(window)

    def close_application(self):
        '''
        Close application
        | No arguments |
        '''
        WHITE_LIB.close_application()

    def set_logging_level(self, level):
        '''
        Set log level
        | Arguments | Usage | (M)andatory / (O)ptional |
        | level | log level (info / debug / warn) | M |
        '''
        WHITE_LIB.set_log_level(level)

    def input_text_to_textbox(self, locator, text):
        '''
        Write text to textbox
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        | text | inserted string | M |
        '''
        WHITE_LIB.input_text_textbox(locator, text)

    def set_slider_value(self, locator, double):
        '''
        Write slider to value double
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        | double | inserted value (must be between scale) | M |
        '''
        WHITE_LIB.set_slider(locator, double)

    def verify_slider_value(self, locator, expected):
        '''
        Verify slider value
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        | actual | expected double | M |
        '''
        actual = WHITE_LIB.verify_slider(locator)
        verify_value(expected, actual)

    def verify_progressbar_value(self, locator, expected):
        '''
        Verify progressbar value
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        | actual | expected double | M |
        '''
        actual = WHITE_LIB.verify_progressbar(locator)
        verify_value(expected, actual)

    def verify_text_in_textbox(self, locator, expected):
        '''
        Verify text in textbox
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        | actual | expected text | M |
        '''
        actual = WHITE_LIB.verify_text_textbox(locator)
        verify_value(expected, actual)

    def verify_label(self, locator, expected):
        '''
        Verify text in label
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        | actual | expected text | M |
        '''
        actual = WHITE_LIB.verify_label(locator)
        verify_value(expected, actual)

    def select_combobox_value(self, locator, value):
        '''
        Select combobox value
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        | value | selected value | M |
        '''
        WHITE_LIB.select_combobox_value(locator, value)

    def select_listbox_value(self, locator, value):
        '''
        Select listbox value
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        | value | selected value | M |
        '''
        WHITE_LIB.select_listbox_value(locator, value)

    def toggle_check_box(self, locator):
        '''
        Toggle check box
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        '''
        WHITE_LIB.toggle_check_box(locator)

    def select_combobox_index(self, locator, index):
        '''
        Select combobox index
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        | index | combobox index | M |
        '''
        WHITE_LIB.select_combobox_index(locator, int(index))

    def verify_combobox_item(self, locator, expected):
        '''
        Verify combobox selected value
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        | actual | expected value | M |
        '''
        actual = WHITE_LIB.verify_combobox_item(locator)
        verify_value(expected, actual)

    def verify_button(self, locator, expected):
        '''
        Verify text in button
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        | actual | expected text | M |
        '''
        actual = WHITE_LIB.verify_button(locator)
        verify_value(expected, actual)

    def click_button(self, locator):
        '''
        Click button
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        '''
        WHITE_LIB.click_button(locator)

    def verify_radio_button(self, locator, expected):
        '''
        Verify value of radio button
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        | actual | expected value | M |
        '''
        actual = WHITE_LIB.verify_radio_button(locator)
        verify_value(expected, actual)

    def verify_check_box(self, locator, expected):
        '''
        Verify value of check box
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        | actual | expected value | M |
        '''
        actual = WHITE_LIB.verify_check_box(locator)
        verify_value(expected, actual)

    def select_radio_button(self, locator):
        '''
        Click button
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        '''
        WHITE_LIB.select_radio_button(locator)

    def verify_menu(self, locator, expected):
        '''
        Verify menu item exists
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        | expected | expected text in value | M |
        '''
        actual = WHITE_LIB.verify_menu(locator)
        verify_value(expected, actual)

    def click_menu_button(self, locator):
        '''
        Click menu button
        | Arguments | Usage | (M)andatory / (O)ptional |
        | locator | element id | M |
        '''
        WHITE_LIB.click_menu_button(locator)

    def select_modal_window(self, locator):
        '''
        Select modal window by title
        | Arguments | Usage | (M)andatory / (O)ptional |
        | Title | Modal window title | M |
        '''
        WHITE_LIB.select_modal_window(locator)

    def select_tab_page(self, locator, title):
        """ Selects a tab page. """
        WHITE_LIB.selectTabPage(locator, title)

    def select_tree_node(self, locator, *node_path):
        """ Selects a tree node. """
        WHITE_LIB.selectTreeNode(locator, node_path)

    def expand_tree_node(self, locator, *node_path):
        """ Expands a tree node. """
        WHITE_LIB.expandTreeNode(locator, node_path)

    def double_click_tree_node(self, locator, *node_path):
        """ Double-clicks a tree node. """
        WHITE_LIB.doubleClickTreeNode(locator, node_path)

    def right_click_tree_node(self, locator, *node_path):
        """ Right-clicks a tree node. """
        WHITE_LIB.rightClickTreeNode(locator, node_path)

def verify_value(expected, actual):
    if expected != actual:
        raise AssertionError("Correct value not found: %s != %s" % (expected, actual))<|endoftext|>