'''
A GUI Application that lets you draw with your mouse on a canvas and predict
the digits using a Pre-Trained CNN model.
For training the model refer to the IPython notebook

'''
#libraries
import tkinter as tk
import tkinter.filedialog as filedialog
from PIL import ImageGrab ,ImageTk, Image
import numpy as np
import cv2
import win32gui
from keras.models import load_model

# loading the model
model = load_model(r'C:\Users\panka\Study\Machine Learning\Digit Recognition GUI\model.h5')

def predict_digit(filename):

    # opening the image and converting it fit for input in model
    image = cv2.imread(filename)
    grey = cv2.cvtColor(image.copy(), cv2.COLOR_BGR2GRAY)
    ret, th = cv2.threshold(grey.copy(), 75, 255, cv2.THRESH_BINARY_INV)
    contours, _ = cv2.findContours(th.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    for cnt in contours:
        x, y, w, h = cv2.boundingRect(cnt)
        # Create rectangle
        cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), thickness=2)
        digit = th[y:y + h, x:x + w]

        # Resizing that digit to (18, 18)
        resized_digit = cv2.resize(digit, (18, 18))

        # Padding the digit with 5 pixels of black color (zeros) in each side to
        #finally produce the image of (28, 28)
        padded_digit = np.pad(resized_digit, ((5, 5), (5, 5)), "constant", constant_values=0)

        # sending the padded digit to model and prediciting
        prediction = model.predict(padded_digit.reshape(1, 28, 28, 1))
        #writing prediciton on image
        data = "Pred = " + str(np.argmax(prediction))
        #print(data)
        font = cv2.FONT_HERSHEY_SIMPLEX
        fontScale = 0.5
        color = (0, 0, 0)
        thickness = 1
        cv2.putText(image, data, (x, y - 5), font, fontScale, color, thickness)
    #resizing & saving the final image
    image = cv2.resize(image,(800,600))
    cv2.imwrite('predict.png', image)

class App(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.lastx = self.lasty = None
        self.x = self.y = 0
        #self.geometry("820x690")
        self.resizable(0,0)
        #self.resizable(width = True, height = True)
        self.title("Handwriiten Digit Recognition GUI")

        # Creating elements
        self.canvas = tk.Canvas(self, width=800, height=600, bg="white", borderwidth=5)
        self.classify_btn = tk.Button(self, text="Recognise", command=self.classify_handwriting,
                                      bg='deep sky blue')
        self.classify_btn.config(font=('helvetica', 14, 'bold'))
        self.button_clear = tk.Button(self, text="Clear", command=self.clear_all,
                                      bg='deep sky blue')
        self.button_clear.config(font=('helvetica', 14, 'bold'))
        self.openfile = tk.Button(self, text="Open A File", command=self.open_file,
                                      bg='deep sky blue')
        self.openfile.config(font=('helvetica', 14, 'bold'))

        # Grid structure
        self.canvas.grid(row=0, column=0, pady=2, sticky=tk.W, columnspan=3)
        self.classify_btn.grid(row=1, column=0, pady=2, padx=2,columnspan=2)
        self.button_clear.grid(row=1, column=2, pady=2, padx =2,columnspan =2)
        self.openfile.grid(row=1, column=4, pady=2, padx =2)
        self.canvas.bind("<Button-1>", self.activate_event)

        img = Image.open("First.jpg")
        # PhotoImage class is used to add image to widgets, icons etc
        img = ImageTk.PhotoImage(img)

        # create a label
        panel = tk.Label(self, image = img)

        # set the image as img
        panel.image = img
        panel.grid(row=0, column=3,columnspan = 3)

    def clear_all(self):
        #clear button
        self.canvas.delete("all")
        #reset the output screen
        img = Image.open("First.jpg")

        # PhotoImage class is used to add image to widgets, icons etc
        img = ImageTk.PhotoImage(img)

        # create a label
        panel = tk.Label(self, image = img)

        # set the image as img
        panel.image = img
        panel.grid(row=0, column=3,columnspan = 3)
    def open_file(self):
        file_path = filedialog.askopenfilename()
        predict_digit(file_path)
        img = Image.open('predict.png')
        # PhotoImage class is used to add image to widgets, icons etc
        img = ImageTk.PhotoImage(img)
        panel = tk.Label(self, image = img)
        #   set the image as img
        panel.image = img
        panel.grid(row=0, column=3,columnspan = 3)

    def classify_handwriting(self):
        HWND = self.canvas.winfo_id()         # get the handle of the canvas
        rect = win32gui.GetWindowRect(HWND)   # get the coordinate of the canvas
        ImageGrab.grab(rect).save('test.png') # taking ss of canvas

        predict_digit("test.png")
        # opens the output image
        img = Image.open('predict.png')
        # PhotoImage class is used to add image to widgets, icons etc
        img = ImageTk.PhotoImage(img)

        panel = tk.Label(self, image = img)
        #   set the image as img
        panel.image = img
        panel.grid(row=0, column=3,columnspan = 3)

    def activate_event(self, event):
        self.canvas.bind('<B1-Motion>', self.draw_lines)
        self.lastx, self.lasty = event.x, event.y

    def draw_lines(self, event):
        self.x = event.x
        self.y = event.y
        self.canvas.create_line((self.lastx, self.lasty, self.x, self.y), width=8, fill='black',
                                capstyle=tk.ROUND, smooth=tk.TRUE, splinesteps=12)
        self.lastx, self.lasty = self.x, self.y

app = App()
tk.mainloop()


from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os

app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'crud.sqlite')
db = SQLAlchemy(app)
ma = Marshmallow(app)

class Receipt(db.Model):
    receipt_id = db.Column(db.Integer, primary_key=True)
    country = db.Column(db.String(80))
    price = db.Column(db.Float)
    vat = db.Column(db.Float)
    receipt_file = db.Column(db.LargeBinary)

    def __init__(self, country, price, vat, receipt_file):
        self.country = country
        self.price = price
        self.vat = vat
        self.receipt_file = receipt_file

class ReceiptSchema(ma.Schema):
    class Meta:
        # Fields to expose
        fields = ('country', 'price', 'vat', 'receipt_file')

receipt_schema = ReceiptSchema()
receipts_schema = ReceiptSchema(many=True)

# endpoint to create new
@app.route("/receipt", methods=["POST"])
def add_receipt():
    country = request.json['country']
    price = request.json['price']
    vat = request.json['vat']
    receipt_file = request.json['receipt_file']

    new_receipt = Receipt(country, price, vat, receipt_file)

    db.session.add(new_receipt)
    db.session.commit()

    return jsonify(new_receipt)

# endpoint to show all   OKKKK
@app.route("/receipt/list", methods=["GET"])
def get_receipt_list():
    all_receipt = Receipt.query.all()
    result = receipts_schema.dump(all_receipt)
    """
    return jsonify(receipt_list = result.data)
    IF WORK BELOW, TRY THIS ONE
    """
    return jsonify(result.data)

# endpoint to get by id OKKKK
@app.route("/receipt/<id>", methods=["GET"])
def receipt_detail(id):
    receipt = Receipt.query.get(id)
    return receipts_schema.jsonify(receipt)

# endpoint to update user
@app.route("/receipt/<id>", methods=["PATCH"])
def receipt_update(id):
    receipt = Receipt.query.get(id)
    country = request.json['country']
    price = request.json['price']
    vat = request.json['vat']
    receipt_file = request.json['receipt_file']

    receipt.country = country
    receipt.price = price
    receipt.vat = vat
    receipt.receipt_file = receipt_file

    db.session.commit()
    return receipt_schema.jsonify(receipt)

# endpoint to delete user
@app.route("/receipt/<id>", methods=["DELETE"])
def receipt_delete(id):
    receipt = Receipt.query.get(id)
    db.session.delete(receipt)
    db.session.commit()

    return receipt_schema.jsonify(receipt)

if __name__ == '__main__':
    app.run(debug=True)


from singly_linked_list_lib.singly_linked_list_node import SinglyLinkedListNode

class SinglyLinkedList(object):
    def __init__(self):
        self.head = None
        self.tail = None
        self.length = 0

    def is_empty(self):
        return self.length == 0

    def add_to_front(self, value):
        """
        O(1)
        """
        temp_node = self.head
        self.head = SinglyLinkedListNode(value)
        self.head.set_next_node(temp_node)
        self.length += 1
        if self.length == 1:
            self.tail = self.head

    def add_to_back(self, value):
        """
        O(1)
        """
        node = SinglyLinkedListNode(value)
        if self.is_empty():
            self.head = node
        else:
            self.tail.set_next_node(node)
        self.tail = node
        self.length += 1

    def add(self, value):
        """
        O(1)
        """
        self.add_to_back(value)

    def add_node(self, node):
        if self.is_empty():
            self.head = node
        else:
            self.tail.set_next_node(node)
        self.tail = node
        self.length += 1

    def remove_front(self):
        if not self.is_empty():
            self.head = self.head.get_next_node()
            self.length -= 1
            if self.length == 0:
                self.tail = None

    def remove_back(self):
        """
        O(n)
        """
        if not self.is_empty():
            if self.length == 1:
                self.tail = None
                self.head = None
            else:
                current = self.head
                while current.get_next_node() is not self.tail:
                    current = current.get_next_node()
                current.next_node = None
                self.tail = current
            self.length -= 1

    def remove(self, item):
        """
        O(n)
        :param item:
        :return:
        """
        if not self.is_empty():
            previous = None
            current_node = self.head
            while current_node is not None:
                if current_node.get_value() == item:
                    if previous is not None:
                        previous.set_next_node(current_node.get_next_node())
                        if current_node.get_next_node() is None:
                            self.tail = previous
                    else:
                        self.remove_front()
                    self.length -= 1
                    return True
                previous = current_node
                current_node = current_node.get_next_node()
        return False

    def clear(self):
        """
        O(1)
        :return:
        """
        self.head = None
        self.tail = None
        self.length = 0

    def enumerate(self):
        """
        O(n)
        :return:
        """
        current_node = self.head
        while current_node is not None:
            yield current_node
            current_node = current_node.get_next_node()

    def __str__(self):
        """
         O(n)
        """
        if not self.is_empty():
            buffer_array = []
            for node in self.enumerate():
                buffer_array.append(str(node))
                buffer_array.append(str('=>'))
            buffer_array.append('None')
            return ''.join(buffer_array)
        else:
            return 'This Linked List is empty!'


from beluga.visualization import BelugaPlot
from beluga.visualization.datasources import Dill
# plots = BelugaPlot('./data.dill',default_sol=-1,default_step=0)
mpbvp_ds = Dill('../../mpbvp/planarHypersonicWithHeatRate/data_1200.dill')
plots = BelugaPlot('./data_1200_2deg15km_ep4.dill',default_sol=-1,default_step=-1, renderer='matplotlib')

plots.add_plot().line('theta*180/3.14','h/1000',label='ICRM Solution')                    \
                .xlabel('Downrange (deg)').ylabel('h (km)')      \
                .title('Altitude vs. Downrange') \
                .line('theta*180/3.14','h/1000',label='MPBVP Solution', datasource=mpbvp_ds, step=-1, sol=-1) \

plots.add_plot().line('t','k*sqrt(rho0*exp(-h/H)/rn)*v**3/10000',label='ICRM Solution') \
                .line('t','k*sqrt(rho0*exp(-h/H)/rn)*v**3/10000',label='MPBVP Solution', datasource=mpbvp_ds, step=-1, sol=-1) \
                .xlabel('t (s)').ylabel('Heat-rate')      \
                .title('Heat-rate vs. Time')

# plots.add_plot().line('t','theta*180/3.14',label='ICRM Solution')                    \
#                 .line('t','theta*180/3.14',label='MPBVP Solution', datasource=mpbvp_ds, step=-1, sol=-1)\
#                 .line('t','theta*180/3.14',label='Unconstrained Solution', datasource=mpbvp_ds, step=0, sol=-1)\
#                 .xlabel('t (s)').ylabel('theta (degrees)')      \
#                 .title('Control history')
#
# plots.add_plot().line('t','lamY', label='ICRM Solution')                    \
#                 .line('t','lamY', label='MPBVP Solution', datasource=mpbvp_ds, step=-1, sol=-1)\
#                 .line('t','lamY', label='Unconstrained Solution', datasource=mpbvp_ds, step=0, sol=-1) \
#                 .xlabel('t (s)').ylabel('lamY')      \
#                 .title('lamY')

plots.render()


'''
In this project, you will visualize the feelings and language used in a set of
Tweets. This starter code loads the appropriate libraries and the Twitter data you'll
need!
'''

import json
from textblob import TextBlob
import matplotlib.pyplot as plt

#Get the JSON data
tweetFile = open("TwitterData/tweets_small.json", "r")
tweetData = json.load(tweetFile)
tweetFile.close()

# Continue your program below!
tweettext = []
tweetstring = ""
for tweet in tweetData:
    tweetstring += tweet['text']

for tweet in tweetData:
    tweettext.append(tweet['text'])
first = tweettext[10]
print(type(first))

print(tweetstring)
blob_polarity = []
for blob in tweettext:
    b = TextBlob(blob)
    blob_polarity.append(b.polarity)
avg = sum(blob_polarity)/len(blob_polarity)

blob_subjectivity = []
for blob in tweettext:
    blob_subjectivity.append(blob_subjectivity)
worddict = {}

tweetBlob = TextBlob(tweetstring)
word_dict = {}
for word in tweetBlob.words:
    word_dict[word.lower()] = tweetBlob.word_counts[word.lower()]
print(word_dict)
# Textblob sample:
tb = TextBlob("You are a brilliant computer scientist.")
print(tb.sentiment)

plt.hist(blob_polarity, bins=[-1, -0.5, 0.0, 0.5, 1])
plt.xlabel('Values')
plt.ylabel('Number of Items')
plt.title('Histogram of Numbers')
plt.axis([-1.1, 1.1, 0, 100])
plt.grid(True)
plt.show()


import numpy as np

def sigmoid(x):
    """
    Calculate sigmoid
    """
    return 1/(1+np.exp(-x))

learnrate = 0.5
x = np.array([1, 2])
y = np.array(0.5)

# Initial weights
w = np.array([0.5, -0.5])

# Calculate one gradient descent step for each weight
# Calculate output of neural network using Sigmoid and multiplying the values times the weights
nn_output = sigmoid(np.dot(x, w))

# Calculate error of neural network: Expected Output - Calculated output (y-yi)
error = y - nn_output

# We can calculate the Gradient using Sigmoid: sigmoid*(1-sigmoid)
# Gradient: f(h)(1−f(h))  or Sigmoid(1-Sigmoid)
# Change in weights: learnrate*error*gradient*input
# Calculate change in weights: [learnrate*error*f(h)(1−f(h))*X
del_w = [ learnrate * error * nn_output * (1 - nn_output) * 1,
          learnrate * error * nn_output * (1 - nn_output) * 2]

print('Neural Network output:')
print(nn_output)
print('Amount of Error:')
print(error)
print('Change in Weights:')
print(del_w)


def longest_alphabetical_substring_finder():
    string = input("enter string to find longest alphabetical substring> ")

    longest_so_far = [string[0],]  # keep track of longest alpha substring so far
    longest_overall = [string[0],]  # keep track of longest overall alphabetical substring

    for alpha_char in range(len(string) - 1):  # avoid range error since we scan one index ahead of current index
        if string[alpha_char + 1] >= string[alpha_char]:
            longest_so_far.append(string[alpha_char + 1])
            if len(longest_so_far) > len(longest_overall):
                longest_overall = longest_so_far
        else:
            longest_so_far = [string[alpha_char + 1],]

    longest_alphabetical_substring = ''.join(longest_overall)
    print("Longest substring in alphabetical order is: ", longest_alphabetical_substring)


import os
import time

name = "common"

def child():
    print("In Child of {}".format(name))
    print("In Child PID: {} PPID: {}".format(os.getpid(), os.getppid()))

    time.sleep(5)
    exit(3)

def parent(child_pid):
    print("In Parent ({}) The child is: {}".format(name, child_pid))
    print("In Parent PID: {} PPID: {}".format(os.getpid(), os.getppid()))
    r = os.wait()
    print(r)

pid = os.fork()
print(pid)
if pid == 0:
    child()
else:
    parent(pid)


#calss header
class _OUTSTANDING():
	def __init__(self,):
		self.name = "OUTSTANDING"
		self.definitions = [u'clearly very much better than what is usual: ', u'not yet paid, solved, or done: ']

		self.parents = []
		self.childen = []
		self.properties = []
		self.jsondata = {}

		self.specie = 'adjectives'

	def run(self, obj1, obj2):
		self.jsondata[obj2] = {}
		self.jsondata[obj2]['properties'] = self.name.lower()
		return self.jsondata


import labbox_ephys as le
import hither2 as hi
import numpy as np

def _list(x):
    if isinstance(x, np.ndarray):
        return x.tolist()
    return x

def store_sorting_in_database(*, recording, sorting, recording_id, group_id, sorting_name, sorter_name, sorting_params, runtime_info, channel_ids=None):
    sorting_id = f'{recording_id}::{group_id}::{sorting_name}'
    if channel_ids is None:
        channel_ids = recording.get_channel_ids()
    doc = dict(
        recording_id=recording_id,
        group_id=group_id,
        channel_ids=_list(channel_ids),
        recording=recording.object(),
        sorting=sorting.object(),
        sorting_name=sorting_name,
        sorter_name=sorter_name,
        sorting_id=sorting_id,
        unit_ids=_list(sorting.get_unit_ids()),
        runtime_info=runtime_info
    )
    le.dbcollection('sortings').replace_one(dict(sorting_id=sorting_id), doc, upsert=True)

def sort_recording_from_database(recording_id, sorter_name, sorting_params, sorting_name, group_ids=None, channel_ids=None):
    recording = le.load_recording(recording_id=recording_id)
    sorter = getattr(le.sorters, sorter_name)
    all_channel_groups = recording.get_channel_groups()
    all_channel_ids = recording.get_channel_ids()
    groups_for_channel = dict()
    for i in range(len(all_channel_ids)):
        groups_for_channel[all_channel_ids[i]] = all_channel_groups[i]
    all_group_ids = list(set(all_channel_groups))
    if group_ids is None:
        group_ids = all_group_ids
    else:
        for gid in group_ids:
            if gid not in all_group_ids:
                raise Exception(f'No group/shank in recording: {gid}')
    for group_id in group_ids:
        print(f'Sorting shank {group_id} using {sorter_name}')
        arg_shank = dict(group=group_id, recording=recording.object())
        if channel_ids is not None:
            channel_ids_shank = [ch for ch in channel_ids if groups_for_channel[ch] == group_id ]
        else:
            channel_ids_shank = None
        if channel_ids_shank is None or len(channel_ids_shank) > 0:
            if channel_ids_shank is not None:
                arg_shank = dict(channel_ids=channel_ids_shank, recording=arg_shank)
            recording_shank = le.LabboxEphysRecordingExtractor(arg_shank)
            recording_shank_obj = le.LabboxEphysRecordingExtractor.get_recording_object(recording=recording_shank)
            with hi.config(download_results=True):
                result_shank = sorter.run(
                    recording=recording_shank_obj,
                    **sorting_params
                )
            sorting_shank_obj = result_shank.wait()
            sorting_shank = le.LabboxEphysSortingExtractor(sorting_shank_obj)
            store_sorting_in_database(
                recording=recording_shank,
                sorting=sorting_shank,
                recording_id=recording_id,
                group_id=group_id,
                channel_ids=channel_ids_shank,
                sorting_name=sorting_name,
                sorter_name=sorter_name,
                sorting_params=sorting_params,
                runtime_info=result_shank.runtime_info()
            )


# ArtSystem (c) ArtGames101 2018
import sys, os, random, subprocess, time, webbrowser

IS_WINDOWS = os.name == "nt"
IS_MAC = sys.platform == "darwin"

def clear_screen():
    if IS_WINDOWS:
        os.system("cls")
    else:
        os.system("clear")

def user_choice():
    return input("\n>>> ").lower().strip()

def start():
    clear_screen()
    print("ArtSystem Safe Mode")
    subprocess.call((sys.executable, "su.py"))
    main()
def main():
    clear_screen()
    print("Administrator     | SafeMode\n"
          "================================")
    print("\n"
          "c. Command Prompt\n"
          "\n"
          "w. WebBrowser\n"
          "\n"
          "s. Security Options\n")
    choice = user_choice()
    if choice == "c":
        admin()
    if choice == "s":
        security()
    if choice == "w":
        web()
    else:
        main()

def web():
    clear_screen()
    print("Web Browser\n"
          "===============")
    print("1. Enter URL")
    print("\n"
          "0. Exit")
    choice = user_choice()
    if choice == "1":
        clear_screen()
        print("Enter URL")
        choice = user_choice()
        webbrowser.open(choice)
        print("Please Wait...")
        time.sleep(5)
        web()
    if choice == "0":
        main()
def admin():
    clear_screen()
    print("Administrative Console\n"
          "========================\n"
          "Type 'help' for help, Type 'exit' to Exit")
    choice = user_choice()
    if choice == "help":
        clear_screen()
        print("Administrative Console\n"
              "========================\n")
        print("\n"
              "***Commands***\n"
              "\n"
              "help   (Shows Help)\n"
              "stop   (Runs Stop Command)\n"
              "exit   (Exits Console)\n"
              "restrt (Restart ArtSystem)\n"
              "sysin  (See the System Info)\n")
        input("\n"
              "Enter")
        admin()
    if choice == "sysin":
        clear_screen()
        # Ping (str(round((t2-t1)*1000)
        input("WIP")
        admin()
        try:
            import psutil
            if IS_WINDOWS:
                operate = "Win"
            if IS_MAC:
                operate = "MAC"
            else:
                operate = "GNU/Linux"
            t1 = time.perf_counter()
            time.sleep(0.678)
            t2 = time.perf_counter()
            size = '{:.2f} MiB'.format(__import__('psutil').Process().memory_full_info().uss / 1024 ** 2)
            print("(A≈) System Information")
            print("\n"
                  "Version {}, {}\n"
                  "\n"
                  "ArtSystem Size : {}\n"
                  "Ping Time : {}\n"
                  "Running on : {}\n"
                  "\n"
                  "(c) ArtGames101".format(vr, version, size, (str(round((t2-t1)*1000))), operate))
            input("\n"
                  "Back")
            admin()
        except:
            if IS_WINDOWS:
                operate = "Win"
            if IS_MAC:
                operate = "MAC"
            else:
                operate = "GNU/Linux"
            t1 = time.perf_counter()
            time.sleep(0.678)
            t2 = time.perf_counter()
            print("(A≈) System Information")
            print("\n"
                  "Version {}, {}\n"
                  "\n"
                  "ArtSystem Size : Unknown\n"
                  "Ping Time : {}ms\n"
                  "Running on : {}\n"
                  "\n"
                  "(c) ArtGames101".format(vr, version, (str(round((t2-t1)*1000))), operate))
            input("\n"
                  "Back")
            admin()
    if choice == "restrt":
        subprocess.call((sys.executable, "safe.py"))
    if choice == "stop":
        clear_screen()
        print("Stopped all scripts")
        sys.exit()
    if choice == "exit":
        main()
    else:
        input("[ARTSYS] {}: command not found".format(choice))
        admin()

def security():
    clear_screen()
    print("System Status : Safe\n"
          "\n"
          "Enter")
    input(".")
    main()

start()