from app.database.model_actions import save, delete
from app.database.model import Stock, Maintainer

class StockMaintainerDbController:

  @classmethod
  def add_stock_maintainer(cls, **kwargs):
    stock = Stock.query.get(kwargs['stock_id'])
    maintainer = Maintainer.query.get(kwargs['maintainer_id'])
    stock.maintainers.append(maintainer)
    save(stock)

  @classmethod
  def remove_stock_maintainer(cls, **kwargs):
    stock = Stock.query.get(kwargs['stock_id'])
    maintainer = Maintainer.query.get(kwargs['maintainer_id'])
    stock.maintainers.remove(maintainer)
    save(stock)


import matplotlib.pyplot as plt

import numpy
import theano
from theano import function, tensor
from pylearn2.utils import sharedX
from pylearn2.linear.conv2d import Conv2D
from pylearn2.space import Conv2DSpace, VectorSpace

def get_layer_normalizer(kernel_shape, threshold):
    normalizer = LayerNormalization(kernel_shape, threshold)
    return normalizer.run

class LayerNormalization():

    def __init__(self, kernel_shape=9, threshold=1e-4):
        self.kernel_shape = kernel_shape
        self.threshold= threshold
        self._normalization_function = None

    def run(self, p):

        if not self._normalization_function:
            img_shape = p.shape
            self._normalization_function = subtractive_divisive_lcn(p, img_shape, self.kernel_shape, self.threshold)

        return self._normalization_function(p)

def subtractive_divisive_lcn(input, img_shape, kernel_shape, threshold=1e-4):
    """
    Yann LeCun's local contrast normalization

    Original code in Theano by: Guillaume Desjardins

    Parameters
    ----------
    input : C01B
    img_shape : wxh
    kernel_shape : 9
    threshold : WRITEME
    """
    input = input.reshape((input.shape[0], input.shape[1], input.shape[2], 1))
    X = tensor.matrix(dtype=input.dtype)
    X = X.reshape((len(input), img_shape[0], img_shape[1], 1))

    filter_shape = (1, 1, kernel_shape, kernel_shape)
    filters = sharedX(gaussian_filter(kernel_shape).reshape(filter_shape))

    input_space = Conv2DSpace(shape=img_shape, num_channels=1)
    transformer = Conv2D(filters=filters, batch_size=len(input),
                         input_space=input_space,
                         border_mode='full')
    convout = transformer.lmul(X)

    # For each pixel, remove mean of 9x9 neighborhood
    mid = int(numpy.floor(kernel_shape / 2.))
    centered_X = X - convout[:, mid:-mid, mid:-mid, :]

    # Scale down norm of 9x9 patch if norm is bigger than 1
    transformer = Conv2D(filters=filters,
                         batch_size=len(input),
                         input_space=input_space,
                         border_mode='full')
    sum_sqr_XX = transformer.lmul(X ** 2)

    denom = tensor.sqrt(sum_sqr_XX[:, mid:-mid, mid:-mid, :])
    divisor = denom
    #per_img_mean = denom.mean(axis=[1, 2])
    #divisor = tensor.largest(per_img_mean.dimshuffle(0, 'x', 'x', 1), denom)
    divisor = tensor.maximum(divisor, threshold)

    new_X = centered_X / divisor
    new_X = tensor.flatten(new_X, outdim=3)

    f = function([X], new_X)
    return f

def gaussian_filter(kernel_shape):
    """
    .. todo::

        WRITEME

    Parameters
    ----------
    kernel_shape : WRITEME
    """
    x = numpy.zeros((kernel_shape, kernel_shape),
                    dtype=theano.config.floatX)

    def gauss(x, y, sigma=2.0):
        Z = 2 * numpy.pi * sigma**2
        return 1. / Z * numpy.exp(-(x**2 + y**2) / (2. * sigma**2))

    mid = numpy.floor(kernel_shape / 2.)
    for i in xrange(0, kernel_shape):
        for j in xrange(0, kernel_shape):
            x[i, j] = gauss(i - mid, j - mid)

    return x / numpy.sum(x)


import logging
from datetime import datetime, timedelta

from heapq import heappush, heappop, heapify
from flask import request, jsonify;
from codeitsuisse import app;

logger = logging.getLogger(__name__)

# """
# def flight(sorted_flights, lengthRun):
#     for counter, flight in enumerate(sorted_flights):
#         if(counter >= lengthRun):
#             before = datetime.strptime(sorted_flights[counter-lengthRun]["Time"], "%H%M")
#             after = datetime.strptime(sorted_flights[counter]["Time"], "%H%M")
#             if after < before + timedelta(seconds=int(reservedTime)):
#                  sorted_flights[counter]["Time"] = (before + timedelta(seconds=int(reservedTime))).strftime("%H%M")
#         flight["Runway"] = runways[counter%lengthRun]
#     return sorted_flights
# """
# @app.route('/airtrafficcontroller', methods=['POST'])
# def airtraffic():
#     data = request.get_json()
#     print("data sent for evaluation {}".format(data))
#
#     flights = data.get("Flights")
#     numOfFlights = len(flights)
#     sorted_flights = sorted(flights, key=lambda kv: (kv["Time"], kv["PlaneId"]))
#     reservedTime = data.get("Static").get("ReserveTime")
#
#     if "Runways" in data.get("Static").keys():
#         runways = data.get("Static").get("Runways")
#         sorted_runways = sorted(runways)
#         lengthRun = len(sorted_runways)
#
#         for flight in sorted_flights:
#             if(flight.get("Distressed", False)):
#                 flight.pop("Distressed")
#                 reserved_flight = flight
#                 sorted_flights.remove(flight)
#                 sorted_flights.insert(0, reserved_flight)
#                 for counter, flight in enumerate(sorted_flights):
#                     if(counter >= lengthRun):
#                         before = datetime.strptime(sorted_flights[counter-lengthRun]["Time"], "%H%M")
#                         after = datetime.strptime(sorted_flights[counter]["Time"], "%H%M")
#                         if after < before + timedelta(seconds=int(reservedTime)):
#                              sorted_flights[counter]["Time"] = (before + timedelta(seconds=int(reservedTime))).strftime("%H%M")
#                     flight["Runway"] = runways[counter%lengthRun]
#                 results = {"Flights" : sorted_flights}
#                 return jsonify(results)
#
#         for counter, flight in enumerate(sorted_flights):
#             if(counter >= lengthRun):
#                 for i in range(lengthRun):
#                     before = datetime.strptime(sorted_flights[counter-i-lengthRun]["Time"], "%H%M")
#                     after = datetime.strptime(sorted_flights[counter]["Time"], "%H%M")
#                     if after > before + timedelta(seconds=int(reservedTime)):
#                          sorted_flights[counter]["Time"] = (before + timedelta(seconds=int(reservedTime))).strftime("%H%M")
#                     flight["Runway"] = runways[counter%lengthRun]
#
#                 if after < before + timedelta(seconds=int(reservedTime)):
#                      sorted_flights[counter]["Time"] = (before + timedelta(seconds=int(reservedTime))).strftime("%H%M")
#             else:
#                 flight["Runway"] = sorted_runways[counter%lengthRun]
#
#     else:
#         for i in range(1, numOfFlights):
#             before = datetime.strptime(sorted_flights[i-1]["Time"], "%H%M")
#             after = datetime.strptime(sorted_flights[i]["Time"], "%H%M")
#             if after < before + timedelta(seconds=int(reservedTime)):
#                  sorted_flights[i]["Time"] = (before + timedelta(seconds=int(reservedTime))).strftime("%H%M")
#
#     print("My result :{}".format(sorted_flights))
#     results = {"Flights" : sorted_flights}
#     return jsonify(results)

def cmp_to_key(mycmp):
    'Convert a cmp= function into a key= function'
    class K:
        def __init__(self, obj, *args):
            self.obj = obj
        def __lt__(self, other):
            return mycmp(self.obj, other.obj) < 0
        def __gt__(self, other):
            return mycmp(self.obj, other.obj) > 0
        def __eq__(self, other):
            return mycmp(self.obj, other.obj) == 0
        def __le__(self, other):
            return mycmp(self.obj, other.obj) <= 0
        def __ge__(self, other):
            return mycmp(self.obj, other.obj) >= 0
        def __ne__(self, other):
            return mycmp(self.obj, other.obj) != 0
    return K

def cmp(x, y):
    print('fuck', x, y)
    if x['Distressed'] != y['Distressed']:
        return x['Distressed']
    if x['Time'] != y['Time']:
        print(x['Time'], y['Time'], x['Time'] < y['Time'])
        return x['Time'] < y['Time']
    return x['PlaneId'] < y['PlaneId']

@app.route('/airtrafficcontroller', methods=['POST'])
def air():
    data = request.get_json()
    print("data sent for evaluation {}".format(data))

    flights = data['Flights']
    for i in range(len(flights)):
        flights[i]['Time'] = datetime(1, 1, 1, int(flights[i]['Time']) // 100, int(flights[i]['Time']) % 100, 0)
        if 'Distressed' not in flights[i]:
            flights[i]['Distressed'] = 1
        elif flights[i]['Distressed'] == 'true':
            flights[i]['Distressed'] = 0
        else:
            flights[i]['Distressed'] = 1
    reserve = int(data['Static']['ReserveTime'])

    flights = sorted(flights, key=lambda k: (k['Distressed'], k['Time'], k['PlaneId']))
    print(flights)
    if 'Runways' in data['Static']:
        runways = data['Static']['Runways']
        times = {}

        for i in range(len(runways)):
            times[runways[i]] = datetime(1,1,1,0,0,0)

        response = []
        for flight in flights:
            #time, runway = heappop (runways)
            rw = ''

            flightTime = flight['Time']
            for i in times:
                print(times[i], flightTime)
                if times[i] <= flightTime:
                    if rw == '' or rw > i:
                        rw = i
            if rw == '':
                for i in times:
                    if rw == '' or rw > i:
                        rw = i
            time = times[rw]
            time = max(time, flightTime)
            response.append({'PlaneId': flight['PlaneId'], 'Time': time.strftime("%H%M"), 'Runway': rw})
            time = time + timedelta(0, reserve)
            times[rw] = time

            print('Response: {}'.format(response))
            #heappush(runways, (time, runway))
        return jsonify(Flights=response)
    else:
        response = []
        time = datetime(1,1,1,0,0,0)
        for flight in flights:
            flightTime = flight['Time']
            time = max(time, flightTime)
            response.append({'PlaneId': flight['PlaneId'], 'Time': time.strftime("%H%M")})
            time = time + timedelta(0, reserve)
        return jsonify(Flights=response)


r,c,n = map(int,input().split())
grid = [[x for x in input()] for _ in range(r)]

def bomberMan(n, grid):
    dx = [1,0,-1,0]
    dy = [0,1,0,-1]

    if n == 1:
        return grid
    if n%2 == 0:
        temp = ['O'*c for _ in range(r)]
        return temp

    temp = [[['O' for _ in range(c)] for _ in range(r)] for _ in range(2)]

    for t in range(2):
        for i in range(r):
            for j in range(c):
                if grid[i][j] == 'O':
                    temp[t][i][j] = '.'
                else:
                    for d in range(4):
                        if 0<=i+dx[d]<r and 0<=j+dy[d]<c:
                            if grid[i+dx[d]][j+dy[d]] == 'O':
                                temp[t][i][j] = '.'
                                break
        grid = temp[t]

    for i in range(r):
        temp[0][i] = ''.join(temp[0][i])

    for i in range(r):
        temp[1][i] = ''.join(temp[1][i])

    if (n-3)%4==0:
        return temp[0]
    else:
        return temp[1]

result = bomberMan(n, grid)


import csv
from sklearn.preprocessing import LabelEncoder
from flask import Flask,render_template,request,redirect,url_for,flash
import numpy as np
import mysql.connector
import cv2,os
import pandas as pd
from PIL import Image
import datetime
import time
import math
import pickle
app=Flask(__name__)
app.config['SECRET_KEY']='attendance system'
mydb = mysql.connector.connect(host="localhost", user="root", passwd="", database="smart_attendance")
cursor = mydb.cursor()
@app.route('/')
def index():
    return render_template('index.html')
@app.route('/collection')
def collection():
    return render_template('collection.html')
@app.route('/about')
def about():
    return render_template('about.html')
@app.route('/services')
def services():
    return render_template('services.html')
@app.route('/blog')
def blog():
    return render_template('blog.html')
@app.route('/contact')
def contact():
    return render_template('contact.html')
@app.route('/single')
def single():
    return render_template('single.html')

@app.route("/addback", methods=['POST','GET'])
def addback():
    if request.method=='POST':
        Id=request.form['rno']
        name=request.form['name']
        print(type(Id))
        print(type(name))
        if not Id:
           flash("Please enter roll number properly ","warning")
           return render_template('collection.html')

        elif not name:
            flash("Please enter your name properly ", "warning")
            return render_template('collection.html')

        # elif (Id.isalpha() and name.isalpha()):
        cam = cv2.VideoCapture(0)
        harcascadePath = "Haarcascade/haarcascade_frontalface_default.xml"
        detector = cv2.CascadeClassifier(harcascadePath)
        sampleNum = 0
        df = pd.read_csv("Student_Details/StudentDetails.csv")
        val = df.Id.values
        if Id in str(val):
            flash("Roll already exists", "danger")
            return render_template("index.html")

        else:
            while (True):
                ret, img = cam.read()
                gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
                faces = detector.detectMultiScale(gray, 1.3, 5)
                for (x, y, w, h) in faces:
                    cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
                        # incrementing sample number
                    sampleNum = sampleNum + 1
                        # saving the captured face in the dataset folder TrainingImage
                    cv2.imwrite("TrainingImage/ " + name + "." + Id + '.' + str(
                            sampleNum) + ".jpg", gray[y:y + h, x:x + w])
                        # display the frame

                else:
                    cv2.imshow('frame', img)
                    # wait for 100 miliseconds
                if cv2.waitKey(100) & 0xFF == ord('q'):
                    break
                    # break if the sample number is morethan 100
                elif sampleNum > 100:
                        break
        cam.release()
        cv2.destroyAllWindows()
        # res = "Roll Number : " + Id + " Name : " + name
        row = [Id, name]
        with open('Student_Details/StudentDetails.csv', 'a+') as csvFile:
            writer = csv.writer(csvFile)
            writer.writerow(row)
        csvFile.close()
        flash("Captured images successfully!!","success")
        return render_template("collection.html")

    return render_template("collection.html")
@app.route('/training')
def training():
    le = LabelEncoder()
    faces, Id = getImagesAndLabels("TrainingImage")
    Id = le.fit_transform(Id)
    output = open('label_encoder.pkl', 'wb')
    pickle.dump(le, output)
    output.close()
    recognizer = cv2.face.LBPHFaceRecognizer_create()
    recognizer.train(faces, np.array(Id))
    recognizer.save(r"Trained_Model\Trainner.yml")

    flash("Model Trained Successfully", "success")
    return render_template('index.html')

def getImagesAndLabels(path):
    imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
    faces = []
    Ids = []
    for imagePath in imagePaths:
        pilImage = Image.open(imagePath).convert('L')
        imageNp = np.array(pilImage, 'uint8')
        Id = str(os.path.split(imagePath)[-1].split(".")[1])
        faces.append(imageNp)
        Ids.append(Id)
    return faces, Ids

@app.route('/prediction')
def prediction():
    recognizer = cv2.face.LBPHFaceRecognizer_create()  # cv2.createLBPHFaceRecognizer()
    recognizer.read(r"Trained_Model\Trainner.yml")
    harcascadePath = r"Haarcascade\haarcascade_frontalface_default.xml"
    faceCascade = cv2.CascadeClassifier(harcascadePath);
    df = pd.read_csv(r"Student_Details\StudentDetails.csv")
    cam = cv2.VideoCapture(0)
    # print(df)
    font = cv2.FONT_HERSHEY_SIMPLEX
    col_names = ['First Name', 'Last Name']
    pkl_file = open('label_encoder.pkl', 'rb')
    le = pickle.load(pkl_file)
    pkl_file.close()
    det=0
    while True:
        ret, im = cam.read()
        gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
        faces = faceCascade.detectMultiScale(gray, 1.2, 5)
        for (x, y, w, h) in faces:
            cv2.rectangle(im, (x, y), (x + w, y + h), (225, 0, 0), 2)
            Id, conf = recognizer.predict(gray[y:y + h, x:x + w])
            # print(conf)
            if (conf < 50):
                det += 1
                tt = le.inverse_transform([Id])
                # print(type(tt))
                tt = tt[0]
                rno=str(tt)
                # print(rno)
                print(det)
                if det==40:
                    ts = time.time()
                    date = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d')
                    timeStamp = datetime.datetime.fromtimestamp(ts).strftime('%H:%M')
                    in_time = int(timeStamp.split(':')[0]) * 60
                    # in_time=400
                    print(in_time)
                    sql = "select count(*) from attendance where rno='%s' and date1='%s'" % (rno, date)
                    z = pd.read_sql_query(sql, mydb)
                    count = z.values[0][0]
                    if 600 >= in_time:# Befor 10
                        print("hhhhhhhhhh")
                        if count == 0:
                            status='Early Coming'
                            sql = "insert into attendance(rno,in_time,in_status,date1) values(%s,%s,%s,%s)"
                            val = (rno, timeStamp, status, date)
                            cursor.execute(sql, val)
                            mydb.commit()
                        else:
                            sql = "select in_time from attendance where rno='%s' and date1='%s'" % (rno, date)
                            result = pd.read_sql_query(sql, mydb)
                            in_time1 = result.values[0][0]
                            in_min = int(in_time1.split(':')[0]) * 60
                            in_min = in_min + int(in_time1.split(':')[1])
                            timeStamp.split(':')
                            out_min = int(timeStamp.split(':')[0]) * 60
                            out_min = out_min + int(timeStamp.split(':')[1])
                            work_time = out_min - in_min
                            work_time1 = math.floor(work_time / 60)
                            work_time2 = work_time % 60
                            w_full = str(work_time1) + ':' + str(work_time2)
                            s = "Early Out"
                            sq = "update attendance set out_time='%s',out_status='%s',overall_time='%s' where rno='%s' and date1='%s'" % (
                            timeStamp, s, w_full, rno, date)
                            cursor.execute(sq)
                            mydb.commit()
                    elif 600 < in_time and 720 >= in_time: #after 10-12
                        print("ddddddddddd")
                        if count == 0:
                            status = 'Late Coming'
                            sql= "insert into attendance(rno,in_time,in_status,date1) values(%s,%s,%s,%s)"
                            val = (rno, timeStamp, status, date)
                            cursor.execute(sql, val)
                            mydb.commit()
                        else:
                            sql = "select in_time from attendance where rno='%s' and date1='%s'" % (rno, date)
                            result = pd.read_sql_query(sql, mydb)
                            in_time1 = result.values[0][0]
                            in_min = int(in_time1.split(':')[0]) * 60
                            in_min = in_min + int(in_time1.split(':')[1])
                            timeStamp.split(':')
                            out_min = int(timeStamp.split(':')[0]) * 60
                            out_min = out_min + int(timeStamp.split(':')[1])
                            work_time = out_min - in_min
                            work_time1 = math.floor(work_time / 60)
                            work_time2 = work_time % 60
                            w_full = str(work_time1) + ':' + str(work_time2)
                            s = "Early Out"
                            sq = "update attendance set out_time='%s',out_status='%s',overall_time='%s' where rno='%s' and date1='%s'" % (
                                timeStamp, s, w_full, rno, date)
                            cursor.execute(sq)
                            mydb.commit()

                    elif 720 <= in_time and 960 >= in_time:#12-4
                        print("lllllllllllllllll")
                        # sql="select count(*) from attendance where rno='%s' and date1='%s'"%(rno,date)
                        # x=pd.read_sql_query(sql,mydb)
                        # count=x.values[0][0]
                        if count==0:
                            print("kkkkkkkkkkkkkkk")
                            status = 'Afternoon Come'
                            sql = "insert into attendance(rno,in_time,in_status,date1) values(%s,%s,%s,%s)"
                            val = (rno, timeStamp, status, date)
                            cursor.execute(sql, val)
                            mydb.commit()
                        else:
                            sql = "select in_time from attendance where rno='%s' and date1='%s'" % (rno, date)
                            result = pd.read_sql_query(sql, mydb)
                            in_time1 = result.values[0][0]
                            in_min = int(in_time1.split(':')[0]) * 60
                            in_min = in_min + int(in_time1.split(':')[1])
                            timeStamp.split(':')
                            out_min = int(timeStamp.split(':')[0]) * 60
                            out_min = out_min + int(timeStamp.split(':')[1])
                            work_time = out_min - in_min
                            work_time1 = math.floor(work_time / 60)
                            work_time2 = work_time % 60
                            w_full = str(work_time1) + ':' + str(work_time2)
                            print("uuuuuuuuuuuuuuuuuu")
                            s="Early Out"
                            sq = "update attendance set out_time='%s',out_status='%s',overall_time='%s' where rno='%s' and date1='%s'" % (
                                timeStamp, s, w_full, rno, date)
                            cursor.execute(sq)
                            mydb.commit()
                    else:#after 4
                        sql = "select in_time from attendance where rno='%s' and date1='%s'" % (rno, date)
                        result = pd.read_sql_query(sql, mydb)
                        in_time1 = result.values[0][0]
                        in_min = int(in_time1.split(':')[0]) * 60
                        in_min = in_min + int(in_time1.split(':')[1])
                        timeStamp.split(':')
                        out_min = int(timeStamp.split(':')[0]) * 60
                        out_min = out_min + int(timeStamp.split(':')[1])
                        work_time = out_min - in_min
                        work_time1 = math.floor(work_time / 60)
                        work_time2 = work_time % 60
                        w_full = str(work_time1) + ':' + str(work_time2)
                        print("aaaaaaaaaaaaaaaa")
                        s = "Perfect Out"
                        sq = "update attendance set out_time='%s',out_status='%s',overall_time='%s' where rno='%s' and date1='%s'" % (
                            timeStamp, s, w_full, rno, date)
                        cursor.execute(sq)
                        mydb.commit()
                    det=0

            else:
                Id = 'Unknown'
                tt = str(Id)
                print(tt)
            if (conf > 55):
                noOfFile = len(os.listdir("ImageUnknown")) + 1
                cv2.imwrite(r"ImageUnknown\Image" + str(noOfFile) + ".jpg", im[y:y + h, x:x + w])
            # print("tt:",str(tt))
            # print("x:", str(x))
            # print("y:", str(y))
            # print("font:", str(font))
            cv2.putText(im, str(tt), (x, y + h), font, 1, (255, 255, 255), 2)
        cv2.imshow('im', im)
        if (cv2.waitKey(1) == ord('q')):
            break
    cam.release()
    cv2.destroyAllWindows()
    flash("Attendance taken","success")
    return render_template('index.html')

@app.route('/viewdata', methods=['POST','GET'])
def viewdata():
    if request.method=='POST':
        rno=request.form['rno']
    sql="select * from attendance where rno='%s' "%(rno)
    x=pd.read_sql_query(sql,mydb)
    x=x.drop(['id','rno'], axis=1)
    return render_template('single.html',row_val=x.values.tolist())

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


import serial
import io

import time

class SerialClass():
    #  PUBLIC STUFF--------------------
    #  BOOLEAN cardID_available
    #  BOOLEAN commandResponse_available
    #  BOOLEAN alive_available
    #  string getcardID()
    #  string get_command_response()
    #  boolean get_alive()
    #  null  attempt_to_get_readings()
    #  null  close()

    def __init__(self):
        #self.ser = serial.Serial('/dev/tty.usbserial', 9600,timeout=1)
        self.ser = serial.Serial('/dev/ttyUSB0', 9600)  ### read() will return bad data if the baudrate is incorrect
        #self.ser.baudrate = 115200
        #self.ser = serial.Serial('COM4', 9600)
        self.global_partial_line="";
        self.cardID_available=False
        self.commandResponse_available=False
        self.alive_available=False
        self.commandResponse="";

    def readln(self):  ### looks for a \n linefeed. removes a single line from the serial buffer. returns that line that it
        # removed.  if it does not find a line, returns an empty string, and the que  will be empty. If there are
        # more lines in the que, nothing is done with them until this function is called again.  This function has to
        #  be called often enough to keep the que from overflowing.
        #  if the que becomes empty,  saves the partial line  for use later
        #   and returns an empty string.
        #  also will return an empty string if there is a \n with no other characters on the input.
        out_line=self.global_partial_line  # each time this routine is entered, initialize the output to the temp store
        while self.ser.in_waiting: # do this over and over again until there is nothing waiting
            c=self.ser.read()   # by defult, reads one byte
            c=str(c.decode("utf-8")) # input is a byte string, different than a string, so must be decoded into a string.
            if  c == '\n':  # string-string comparison here.  Python alows compare of different types, always will fail on equality.
                self.global_partial_line="";  # reset temp storag
                return(out_line)  # returns the line, que is not empty, partial line is reset to empty string
            else :
              out_line += c
              self.global_partial_line += c
        # serial buffer is empty here and a newline is not found
        return ""
    def parse_line(self,instr):
        if instr[0]=="*":
            #print ("alive")
            self.alive_available=True;
        else:
            par_tuple=instr.partition(" ")  # part before, space, and part after . if no equal, returns str and two empty strings
            if par_tuple[1]  == "" and par_tuple[2] == "":
                print('comment=',instr)
            elif  par_tuple[0]=="+++":
                #print("In SERIAL: response to command")
                ##par_tuple=par_tuple[2].partition(" ") # get part after, now part after is " A 6  534"
                self.commandResponse=par_tuple[2].strip()
                self.commandResponse_available=True  # be sure to put this after the previous line, not before

            elif  par_tuple[0] == "===":
                #print( " card read") # part after is "cardsreadnum facility-cardnumber "
                par_tuple=par_tuple[2].partition(" ") # get part after, now part after is "facility-cardnumber"
                #print("After reading this many cards");print(par_tuple[0])
                par_tuple=par_tuple[2].partition("-") # now part after is cardnumber
                #print("facilty number=",par_tuple[0],"card number=", par_tuple[2])
                self.cardID=par_tuple[2].strip();
                self.cardID_available=True;
            else:
                print("In SerialConnection: unusual message received:  ",instr)

    def attempt_to_get_readings(self):  #  removes all the lines from the serial buffer. parses those lines, looking for data.
        # if it finds data, then fills the global data array with the data.  is finished when the entire serial buffer is empty.
        # repeatadly calls readline until the serial buffer is empty.
        #print("quelength=",working_inque.qsize())
        while self.ser.in_waiting:
                      cd= self.readln()  # remove a single line from the serial buffer. Returns a line or a empty string
                      if cd != "":
                        pt=self.parse_line(cd)  # the tuple that comes back has a TRUE if the line was a full one with data in it.

    def get_cardID(self):
        if self.cardID_available==True:
            self.cardID_available=False;
            return self.cardID
        else:
            return NULL

    def get_command_response(self):
        if self.commandResponse_available==True:
            self.commandResponse_available=False;
            return self.commandResponse
        else:
            return NULL

    def get_alive(self):
        if self.alive_available==True:
            self.alive_available=False;
            return True
        else:
            return False
    def send_command(self,instr):
        #print("IN SERIAL: command sent to arduino:"+instr)
        self.ser.write(instr.encode());

    def send_imp_request(self):
        self.send_command("+++ imp \r\n")
    def relay_mainpowerOFF(self):
        s=    ("+++ write "+str(MAINPOWER_RELAY_PIN)+" 1 \r\n")
        self.send_command(s);
    def relay_mainpowerON(self) :
        self.send_command("+++ write "+str(MAINPOWER_RELAY_PIN)+" 0 \r\n");
    def close(self):
        return serial.Serial.close(self.ser)

if  __name__ == "__main__":
    print('HI there')
    s=SerialClass()
    sio = io.TextIOWrapper(io.BufferedRWPair(s.ser,s.ser))
    sio.write(("hello\n"))
    sio.flush() # it is buffering. required to get the data out *now*
    #resp=sio.readline()
    #print(">>"+resp)
    i=0; j=300; k=450;
    while True:
        s.attempt_to_get_readings();
        if s.cardID_available:
            print("cardID=",s.get_cardID())
        if s.commandResponse_available:
            inp=s.get_command_response();
            print("command response=",inp)
        if s.alive_available:
            print("alive=",s.get_alive())
        i=i+1;  j=j+1; k=k+1;
        if i>500:
            i=0
            s.relay_mainpowerOFF()
        if j>500:
            j=0
            s.relay_mainpowerON()
        if k>500:
            k=0
            s.send_imp_request()

        time.sleep(.01)
    s.close()


# -*- coding: utf-8 -*-

from importlib import abc, util, import_module
import logging
import os
import subprocess
import sys
from pathlib import Path

try:
    import pybind11
except ModuleNotFoundError:
    logging.warning("Package 'pybind11' could not be loaded, binding modules "
                    "will not be available")

__all__ = ["CppBase"]

BUILD_DIR = "_build"
CMAKE_LISTS = "CMakeLists.txt"

class BindingException(Exception):
    """
    Exception to be raised if the cpp binding raises.
    """
    pass

class CppBase:
    """
    Mix-in class for modules written in C++.

    This class uses pybind and cmake to automatically compile and link the
    provided sources and load them as an python module.

    Args:
        :module_path: Path to directory that contains the sources.
        :module_name: Name of the module
        :binding_source: cpp file including the binding definition
        :additional_sources: List of additional cpp files to compile into module
        :additional_lib: dict with key 'lib name' and additional lines for the
          CMakeLists
        :additional_compile_defs: list with compiler definitions

    Warn:
        `additional_sources` will be added to the compilation unit.
        *Every other file* is ignored by this routine so far.

    """

    def __init__(self,
                 module_path=None,
                 module_name=None,
                 binding_source=None,
                 additional_sources=None,
                 binding_class_name=None,
                 additional_lib=None,
                 additional_compile_defs=None):
        self._logger = logging.getLogger(self.__class__.__name__)

        # adapt to os-specific extensions
        if os.name == 'nt':
            self.sfx = '.pyd'
        else:
            self.sfx = '.so'

        if module_name is None:
            message = "Instantiation of binding class without module_name is not allowed!"
            self._logger.error(message)
            raise BindingException(message)
        self.module_name = module_name

        if module_path is None:
            message = "Instantiation of binding class without module_path is not allowed!"
            self._logger.error(message)
            raise BindingException(message)

        if binding_source is None:
            if binding_class_name is not None:
                binding_source = binding_class_name + ".cpp"
                module_source = module_name + ".cpp"
                additional_sources = additional_sources.append(module_source) if additional_sources else [module_source]
                self._logger.warn("Use of binding_class_name is deprecated. Please migrate to binding_source")
            else:
                message = "Instantiation of binding class without binding_source is not allowed!"
                self._logger.error(message)
                raise BindingException(message)

        self.module_path = Path(module_path).resolve()
        self.build_path = self.module_path / BUILD_DIR
        self.sources = [binding_source] if additional_sources is None else [*additional_sources, binding_source]

        self.additional_lib = None
        if additional_lib is not None:
            assert (isinstance(additional_lib, dict))
            self.additional_lib = additional_lib

        self.additional_compile_defs = None
        if additional_compile_defs is not None:
            assert (isinstance(additional_compile_defs, list))
            self.additional_compile_defs = additional_compile_defs

        if self.create_binding_config():
            self.build_binding()
            if os.name == 'nt' and 'GCC' not in sys.version:
                libPath = (self.build_path / 'Release' / self.module_name)
            else:
                libPath = (self.build_path / self.module_name)
            ModuleFinder().register(self.module_name,
                                    libPath.with_suffix(self.sfx))
            self.bindings = self.load()

    def create_binding_config(self):
        # check if folder exists
        if not self.module_path.is_dir():
            self._logger.error("Config folder '{}' does not exist."
                               "".format(self.module_path))
            return False

        if not self.build_path.is_dir():
            self.build_path.mkdir()

        for src in self.sources:
            if not (self.module_path / src).is_file():
                self._logger.error("Source file '{}' could not be found in the "
                                   "given module path '{}'."
                                   "".format(src,
                                             self.module_path))
                return False

        if not (self.build_path / CMAKE_LISTS).is_file():
            self._logger.info("CMakeLists.txt not found in module build dir.")
            self._logger.info("Generating new CMake config.")
            self.create_cmake_lists()

        config_changed = self.update_binding_config()
        if config_changed:
            self.build_config()

        return True

    def create_cmake_lists(self):
        """
        Create the stub of a `CMakeLists.txt` .

        Returns:
        """
        c_make_lists = """
cmake_minimum_required(VERSION 3.15)
project(Bindings)

find_package(Python REQUIRED COMPONENTS Interpreter Development)

find_package(pybind11 CONFIG REQUIRED PATHS ${{Python_SITELIB}})
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY .)
set(PYTHON_MODULE_EXTENSION "{}")
""".format(self.sfx)

        with open(self.build_path / CMAKE_LISTS, "w") as f:
            f.write(c_make_lists)

    def update_binding_config(self):
        """
        Add the module config to the cmake lists.

        Returns:
            bool: True if build config has been changed and cmake has to be
            rerun.
        """
        cmake_line = "\ninclude({}.cmake)\n".format(self.module_name)
        config_line = "\npybind11_add_module({} SHARED {})\n".format(
            self.module_name,
            " ".join([Path(os.path.relpath(self.module_path / src, self.build_path)).as_posix() for src in self.sources]),
        )
        if self.additional_lib:
            for value in self.additional_lib.values():
                config_line += value
            config_line += "\ntarget_link_libraries({} PRIVATE {})\n".format(
                self.module_name,
                " ".join(self.additional_lib.keys()),
            )
        if self.additional_compile_defs:
            config_line += "\nadd_compile_definitions("
            for value in self.additional_compile_defs:
                config_line += value + " "
            config_line += ")\n"

        ret = False
        with open(self.build_path / "{}.cmake".format(self.module_name), 'w+') as f:
            if config_line not in f.read():
                f.write(config_line)
                ret = True

        with open(self.build_path / CMAKE_LISTS, "r+") as f:
            if cmake_line not in f.read():
                self._logger.info("Appending build info for '{}'".format(self.module_name))
                f.write(cmake_line)
                ret = True

        return ret

    def build_config(self):
        # generate config
        if os.name == 'nt' and 'GCC' not in sys.version:
            cmd = ['cmake', '-A', 'x64', '-S', '.', '-B', '.']
        else:
            cmd = ['cmake', '.']
        result = subprocess.run(cmd, cwd=self.build_path)

        if result.returncode != 0:
            message = "Generation of binding config failed."
            self._logger.error(message)
            raise BindingException(message)

    def build_binding(self):
        # build
        if os.name == 'nt' and 'GCC' not in sys.version:
            cmd = ['cmake', '--build', '.', '--config', 'Release', '--target', self.module_name]
        else:
            cmd = ['cmake', '--build', '.', '-t', self.module_name]
        result = subprocess.run(cmd, cwd=self.build_path)

        if result.returncode != 0:
            message = "Build failed!"
            self._logger.error(message)
            raise BindingException(message)

    def load(self):
        if self.module_name in sys.modules:
            del sys.modules[self.module_name]
        return import_module(self.module_name)

class ModuleFinder(abc.MetaPathFinder):
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(ModuleFinder, cls).__new__(cls)
            cls._instance.path_map = dict()
            sys.meta_path.insert(0, cls._instance)
        return cls._instance

    def register(self, name, path):
        if name in self.path_map.keys():
            return
        self.path_map[name] = path

    def find_spec(self, name, path, target=None):
        if not name in self.path_map:
            return None
        return util.spec_from_file_location(name, self.path_map[name])


#!/usr/bin/env python

#ROS_NAMESPACE=stereo_vision rosrun stereo_image_proc stereo_image_proc

import rospy
import sys
from sensor_msgs.msg import CameraInfo, Image
from std_msgs.msg import String
from camera_info_manager import CameraInfoManager
from cv_bridge import CvBridge, CvBridgeError
import time
import threading

import tf

from arducam_manager import ArducamManager
from led_manager import LEDManager
from stereo_vision_ros.srv import ChangeModality, ChangeModalityResponse

CAMERA_NAME = 'stereo_vision_camera'

class StereoVisionNode:

    def __init__(self):
        # fps related variable
        self.timeFpsStart = time.time()
        self.timeFpsNow = time.time()
        self.seqFps = 0

        self.flagLowFPS = False

        rospy.init_node('{}_node'.format(CAMERA_NAME), argv=sys.argv)

        self.config_file = rospy.get_param('~config_file',
                                           '../camera_config_files/OV5647_MIPI_2Lane_RAW8_8b_2592x1944_AB.cfg')
        self.calibration_left = rospy.get_param('~calibration_left', '')
        self.calibration_right = rospy.get_param('~calibration_right', '')

        self.cim_left = CameraInfoManager(cname="left",
                                          url='file://' + self.calibration_left,
                                          namespace="left")
        self.cim_right = CameraInfoManager(cname="right",
                                           url='file://' + self.calibration_right,
                                           namespace="right")

        self.cim_left.loadCameraInfo()  # Needs to be called before getter!
        self.camera_info_left = self.cim_left.getCameraInfo()
        self.camera_info_left.header.frame_id = "left_frame"

        self.cim_right.loadCameraInfo()  # Needs to be called before getter!
        self.camera_info_right = self.cim_right.getCameraInfo()
        self.camera_info_right.header.frame_id = "right_frame"

        self.stereo_cam = ArducamManager(self.config_file)
        self.bridge = CvBridge()

        self.image_publisher_right = rospy.Publisher("right/image_raw", Image,
                                                     queue_size=1)
        self.image_publisher_left = rospy.Publisher("left/image_raw", Image,
                                                    queue_size=1)
        self.camera_publisher_right = rospy.Publisher("right/camera_info", CameraInfo,
                                                      queue_size=1)
        self.camera_publisher_left = rospy.Publisher("left/camera_info", CameraInfo,
                                                     queue_size=1)

        self.modality_publisher = rospy.Publisher("modality", String, queue_size=1)
        self.service_change_modality = rospy.Service('change_modality', ChangeModality, self.change_modality)

        self.seq = 0
        self.stereo_cam.startCapture()

        self.checkCameraStatusThread = threading.Thread(target=self.checkCameraStatus)
        self.checkCameraStatusThreadRunning = True
        self.checkCameraStatusThread.start()

        self.ledManager = LEDManager()

    def readImages(self, br):
        # Read image from camera
        img_right, img_left = self.stereo_cam.readImages()

        if img_left is not None and img_right is not None:
            timeNow = rospy.Time.now()
            self.publishImage(self.image_publisher_left,
                              self.camera_publisher_left,
                              img_left,
                              self.camera_info_left,
                              self.seq,
                              timeNow)

            self.publishImage(self.image_publisher_right,
                              self.camera_publisher_right,
                              img_right,
                              self.camera_info_right,
                              self.seq,
                              timeNow)
            #transformation bidon
            br.sendTransform((5.0, 5.0, 5.0),
                             (0.0, 0.0, 0.0, 1.0),
                             rospy.Time.now(),
                             "stereo_vision_frame",
                             "world")
            self.seq += 1

    def publishImage(self, img_publisher, info_publisher, image, info, seq, timeNow):
        image_msg = self.bridge.cv2_to_imgmsg(image, encoding="bgr8")

        # Add timestamp and sequence number (empty by default)
        image_msg.header.stamp = timeNow
        image_msg.header.seq = seq
        image_msg.header.frame_id = "stereo_vision_frame"
        img_publisher.publish(image_msg)

        camera_msg = info
        camera_msg.header = image_msg.header  # Copy header from image message
        info_publisher.publish(camera_msg)

    def checkCameraStatus(self):
        while self.checkCameraStatusThreadRunning:
            self.timeFpsNow = time.time()
            if self.timeFpsNow - self.timeFpsStart >= 3:  # print every second
                fps = (self.seq - self.seqFps) / 3
                if fps == 0:
                    rospy.logerr("No data received from camera!")
                elif fps < 5:
                    rospy.logwarn("FPS is lower than 5...")
                    if not self.flagLowFPS: self.flagLowFPS = True
                elif self.flagLowFPS:
                    rospy.loginfo("FPS back to normal")
                    self.flagLowFPS = False

                self.seqFps = self.seq
                self.timeFpsStart = self.timeFpsNow

        self.checkCameraStatusThreadRunning = False

    def closeNode(self):
        self.checkCameraStatusThreadRunning = False
        self.checkCameraStatusThread.join()
        self.stereo_cam.shutdown()
        self.ledManager.shutdown()

    def startTouch(self):
        self.stereo_cam.startTouch()
        self.ledManager.startTouch()

    def startVision(self):
        self.stereo_cam.startVision()
        self.ledManager.startVision()

    def change_modality(self, request):
        result = True
        if request.modality == "touch":
            rospy.loginfo("Modality changed to TOUCH")
            self.startTouch()
            self.modality_publisher.publish("touch")
        elif request.modality == "vision":
            rospy.loginfo("Modality changed to VISION")
            self.startVision()
            self.modality_publisher.publish("vision")
        else:
            rospy.logwarn("Modality change error: " + request.modality + " is not recognised" )
            result = False
        return ChangeModalityResponse(result)

def main():
    stereoNode = StereoVisionNode()

    br = tf.TransformBroadcaster()
    while not rospy.is_shutdown():
        stereoNode.readImages(br)

    stereoNode.closeNode()

if __name__ == '__main__':
    main()


import requests
import hashlib
import subprocess
import os

def STEP1():

    # Send GET message to download the file
    file_url = 'http://download.videolan.org/pub/videolan/vlc/3.0.17.4/win64/vlc-3.0.17.4-win64.exe.sha256'
    resp_msg = requests.get(file_url)
    # Check whether the download was successful
    if resp_msg.status_code == requests.codes.ok:
    # Extract binary file content from response message body

        file_content = resp_msg.content
        x = file_content.split()
        # Print the hash value
        return x[0]

def STEP2():

    # Send GET message to download the file
    file_url = 'http://download.videolan.org/pub/videolan/vlc/3.0.17.4/win64/vlc-3.0.17.4-win64.exe'
    resp_msg = requests.get(file_url)
    # Check whether the download was successful
    if resp_msg.status_code == requests.codes.ok:
    # Extract binary file content from response message body

        file_content = resp_msg.content

        # Print the hash value
        return file_content

def STEP3(file_content, x):

    # Calculate SHA-256 hash value
    image_hash = hashlib.sha256(file_content).hexdigest()

    print(x, image_hash)
    a = x.decode("utf-8")
    if a == image_hash:
        print("Both files are same")
        print(f"Hash: {a}")

    else:
        print("Files are different!")

def STEP4(file_content):

    # Save the binary file to disk
    with open(r'C:\Users\Owner\Desktop\SEMESTER4\Scripting\COMP593-Lab6\Result.exe', 'wb') as file:
        file.write(file_content)
        print("File has been saved to disk")

def STEP5():

    installer_path = r'C:\Users\Owner\Desktop\SEMESTER4\Scripting\COMP593-Lab6\Result.exe'
    subprocess.run([installer_path, '/L=1033', '/S'])

    print("File is executed and is run silently")
    return installer_path

def STEP6(installer_path):

    os.remove(installer_path)
    print("File has been removed as requested")

def main():
    x = STEP1()
    file_content = STEP2()
    STEP3(file_content, x)
    STEP4(file_content)
    installer_path = STEP5()
    STEP6(installer_path)
main()


"""
Project 3 - Sudoku Solver
BB&N 2018-19 Advanced Topics in Computer Science
Sudoku.java - source file to solve sudoku puzzles.
See the Powerschool for guidelines and advice.

Name:
Date: October 2018
"""

def is_valid(puzzle, row, column, number):
    # Boolean function that determines if it is allowed to place a number in
    # the given position [row, column]
    if(row <= 2):
        row_section = [0,1,2]
    elif(row >= 6):
        row_section = [6,7,8]
    else:
        row_section = [3,4,5]

    if(column <= 2):
        column_section = slice(0,3,1)
    elif(column >= 6):
        column_section = slice(6,9,1)
    else:
        column_section = slice(3,6,1)

    section_of_puzzle = [puzzle[x][column_section] for x in row_section]
    section_contains = any(number in x for x in section_of_puzzle)

    entire_row = puzzle[row:row+1]
    row_contains = number in entire_row

    entie_column = [puzzle[x:x+1][column:column+1] for x in range(8)]
    column_contains = any(number in x for x in entie_column)

    if(section_contains or row_contains or column_contains):
        return False
    else:
        return True

def solve(puzzle, row, column):
    # Function that should be recursively called to solve the sudoku puzzle.
    # This function should return a boolean that says whether the puzzle can be
    # solved using the current configuration

    return False

def main():
    # Open the file and read it into a 9x9 list
    filename = "s3.txt" # change this to read other puzzle files
    with open(filename, "r") as file:
        puzzle = []
        for line in file:
            line = [int(x) for x in line.strip().split(" ")]
            puzzle.append(line)

    print("Original puzzle ("+filename+")")
    print_puzzle(puzzle) # print unsolved puzzle

    print(str(is_valid(puzzle,2,0,3 ) ) )

##############################
###### HELPER FUNCTIONS ######
##############################
def check_answer(puzzle, filename):
    filename = filename.split(".")
    filename = filename[0]+"_solution.txt"
    try:
        with open(filename, "r") as file:
            puzzle_sol = []
            for line in file:
                line = [int(x) for x in line.strip().split(" ")]
                puzzle_sol.append(line)
            for r in range(len(puzzle_sol)):
                for c in range(len(puzzle_sol[r])):
                    if puzzle[r][c] != puzzle_sol[r][c]:
                        return False
            return True
    except:
        return None

def print_puzzle(puzzle):
    # helper function to print puzzle cleanly
    for i in puzzle:
        for j in i:
            print(str(j) + " ",end="")
        print()

main()


"""
734. Sentence Similarity
Given two sentences words1, words2 (each represented as an array of strings), and a list of similar word pairs pairs, determine if two sentences are similar.

For example, "great acting skills" and "fine drama talent" are similar, if the similar word pairs are pairs = [["great", "fine"], ["acting","drama"], ["skills","talent"]].

Note that the similarity relation is not transitive. For example, if "great" and "fine" are similar, and "fine" and "good" are similar, "great" and "good" are not necessarily similar.

However, similarity is symmetric. For example, "great" and "fine" being similar is the same as "fine" and "great" being similar.

Also, a word is always similar with itself. For example, the sentences words1 = ["great"], words2 = ["great"], pairs = [] are similar, even though there are no specified similar word pairs.

Finally, sentences can only be similar if they have the same number of words. So a sentence like words1 = ["great"] can never be similar to words2 = ["doubleplus","good"].

Note:

The length of words1 and words2 will not exceed 1000.
The length of pairs will not exceed 2000.
The length of each pairs[i] will be 2.
The length of each words[i] and pairs[i][j] will be in the range [1, 20].
"""

# Time complexity: O(N+P)
# Space complexity: O(P)
class Solution:
    def areSentencesSimilar(self, words1: [str], words2: [str], pairs: [[str]]) -> bool:
        if len(words1) != len(words2):
            return False
        elif not words1:
            return True

        similar_words = {}
        for p, q in pairs:
            if p not in similar_words:
                similar_words[p] = {q}
            else:
                similar_words[p].add(q)
            if q not in similar_words:
                similar_words[q] = {p}
            else:
                similar_words[q].add(p)

        for i in range(len(words1)):
            if words1[i] != words2[i]:
                if words1[i] not in similar_words or words2[i] not in similar_words[words1[i]]:
                    return False
        return True


from vpython import *
import csv
import sys
from time import sleep

# Only need to pip install vpythpn

if len(sys.argv) == 2:
    filename = f'sequences/{sys.argv[1]}.csv'
else:
    filename = 'sequences/moving-rotating-rainbow.csv'

# Setup the canvas and the view
# By the way, this library has terrible documentation
scene = canvas(width=600, height=780, center=vector(0,1.5,0))
framerate = 60

# Open the file with the coordinates of lights, and setup the spheres
lights = []
with open('coords_2021.csv','r',encoding='utf-8-sig') as f:
    reader = csv.reader(f)

    for row in reader:
        # Read coordinates
        x,y,z = [float(x.strip()) for x in row]

        # Display a white light
        light = sphere(pos=vector(x,z,y), radius=0.03, shininess=0)

        lights.append(light)

# Open the animation file and process it
print('Loading animation...')
animation = []

with open(filename,'r',encoding='utf-8') as f:
    reader = csv.reader(f)
    total_frames = 0

    next(reader) # skip the header
    for row in reader:
        total_frames += 1
        colors = []
        for i in range(500):
            r = int(row[i*3 +1])/255
            g = int(row[i*3 +2])/255
            b = int(row[i*3 +3])/255
            colors.append(vector(r,g,b))
        animation.append(colors)

# Loop the animation
print('Playing animation...')
while True:
    for frame in range(total_frames):
        for l in range(500):
            lights[l].color = animation[frame][l]
        sleep(1/framerate)


import socket
import pickle
from time import sleep
from components.carro import Carro

class ConectionTCP:
    def __init__(self, ip: str, port: int):
        self.ip = ip
        self.port = port
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def connect(self):
        self.sock.connect((self.ip, self.port))

    def send(self, data):
        self.sock.send(data.encode())

    def receive(self):
        return self.sock.recv(2048).decode()

    def enviar_dados(
            self,
            lista_carro: list[Carro],
    ):
        while True:
            if len(lista_carro) > 0:
                try:
                    num_carros_andar_1 = len(list(filter(
                        lambda carro: carro.datatime_saida == None and carro.posicao_vaga[0] == "A", lista_carro
                    )))
                    num_carros_andar_2 = len(list(filter(
                        lambda carro: carro.datatime_saida == None and carro.posicao_vaga[0] == "B", lista_carro
                    )))
                except:
                    pass
                ultimo_carro = list(filter(
                    lambda carro: carro.datatime_saida != None, lista_carro
                ))
                if len(ultimo_carro) > 0:
                    ultimo_carro = ultimo_carro[-1].to_dict()
                else:
                    ultimo_carro = None
            else:
                ultimo_carro = None
                num_carros_andar_1 = 0
                num_carros_andar_2 = 0
            dados = {
                "num_carros_andar_1": num_carros_andar_1,
                "num_carros_andar_2": num_carros_andar_2,
                "ultimo_carro": ultimo_carro,
            }
            try:
                data_serializada = pickle.dumps(dados)
                self.sock.send(data_serializada)
            except:
                self.reconectar()
            sleep(1)

    def receive_dict(self):
        return self.sock.recv(2048)

    def close(self):
        self.sock.close()

    def aguardar_conexao(self):
        self.sock.listen(1)
        self.conexao, self.endereco = self.sock.accept()

    def reconectar(self):
        try:
            self.sock.connect((self.ip, self.port))
        except:
            sleep(5)


# -*- coding: utf-8 -*-
import logging
from copy import copy, deepcopy

from eaglet.decorator import param_required
from eaglet.core import api_resource
from business import model as business_model
from db.mall import models as mall_models

from business.mall.image_group.image import Image
from business.mall.corporation_factory import CorporationFactory

class ImageGroup(business_model.Model):
	"""
	图片分组
	"""
	__slots__ = (
		'id',
		'name',
		'created_at',
	)

	def __init__(self, model=None):
		business_model.Model.__init__(self)

		self.context['db_model'] = model
		if model:
			self._init_slot_from_model(model)

	@staticmethod
	@param_required(['db_model'])
	def from_model(args):
		return ImageGroup(args['db_model'])

	@property
	def images(self):
		"""
		获取image group中的Image对象集合
		"""
		image_models = mall_models.Image.select().dj_where(group_id=self.id)
		images = []
		for image_model in image_models:
			images.append(Image.from_model(image_model))

		return images

	def add_image(self, corp, image):
		"""
		向image group中添加一个image
		"""
		mall_models.Image.create(
			owner = corp.id,
			group = self.id,
			url = image['path'],
			title = '',
			width = image['width'],
			height = image['height']
		)

	def update(self, params):
		"""
		更新image group
		"""
		corp = CorporationFactory.get()
		mall_models.Image.delete().dj_where(owner_id=corp.id, group_id=self.id).execute()

		if 'name' in params:
			#更新name
			mall_models.ImageGroup.update(name=params['name']).dj_where(owner_id=corp.id, id=self.id).execute()

		if 'images' in params:
			#更新images
			for image in params['images']:
				self.add_image(corp, image)

	@staticmethod
	def create(corp, name, images):
		image_group_model = mall_models.ImageGroup.create(
			owner = corp.id,
			name = name
		)

		image_group = ImageGroup.from_model({
			'db_model': image_group_model
		})

		for image in images:
			image_group.add_image(corp, image)

		return image_group


import os

from sequana.lazy import pandas as pd
from sequana.modules_report.base_module import SequanaBaseModule

from sequana import TRF

from sequana.lazy import pylab

from sequana.utils.datatables_js import DataTable
from sequana.utils.df2html import df2html

__all__ = ["TRFModule"]

class TRFModule(SequanaBaseModule):
    """Report dedicated to TRF file"""

    def __init__(self, trf_input, output_filename=None):
        super().__init__()

        self.trf = TRF(trf_input)
        self.title = "TRF Report"
        self.create_report_content()
        self.create_html(output_filename)

    def create_report_content(self):
        self.sections = list()
        self.add_info()
        self.add_table()
        self.add_images_section()

    def add_info(self):

        html = "<br>".join(self.trf.__repr__().split("\n"))

        self.sections.append({"name": "Information", "anchor": "info", "content": html})

    def add_table(self):

        datatable = DataTable(self.trf.df, "result", index=True)
        datatable.datatable.datatable_options = {
            "scrollX": "300px",
            "pageLength": 15,
            "scrollCollapse": "true",
            "dom": "tBifp",
            "paging": "true",
            "buttons": ["copy", "csv"],
        }
        js = datatable.create_javascript_function()
        html_tab = datatable.create_datatable(float_format="%.3g")

        html = ""
        html += "{} {}".format(html_tab, js)

        self.sections.append(
            {"name": "TRF results", "anchor": "results", "content": html}
        )

    def add_images_section(self):
        style = "width:65%"
        import pylab

        pylab.ioff()

        def plotter1(filename):
            pylab.clf()
            self.trf.hist_entropy()
            pylab.savefig(filename)

        html1 = self.create_embedded_png(plotter1, "filename", style=style)

        def plotter2(filename):
            pylab.clf()
            self.trf.hist_period_size()
            pylab.savefig(filename)

        html2 = self.create_embedded_png(plotter2, "filename", style=style)

        self.sections.append(
            {"name": "Image", "anchor": "table", "content": html1 + html2}
        )


#!C:\Python\Python

def word_reverse(str):
    tempWord = ''
    words = []

    for s in str:
        if s == ' ' and tempWord != ' ':
            words.append(tempWord)
            tempWord = ''
        else:
            tempWord += s
    if tempWord != ' ':
        words.append(tempWord)

    print("before:", str)

    str = " ".join(words[::-1])
    print("after:", str)

word_reverse(" I am a child")
exit()

# using recursion
def recursion(str):
    if len(str) == 0:
        return str
    else:
        return recursion(str[1:]) + str[0]

# using loop
def loop(str):
    newStr=''
    for i in str:
        newStr = i + newStr
    return newStr

# using extended slice syntax
def slice(str):
    str = str[::-1]
    return str

# using function reversed()
def reverse(str):
    str = "".join(reversed(str))
    return str

myStrA = "geeksforgeeeks"
#print(recursion(myStrA))
#print(loop(myStrA))
#print(slice(myStrA))
#print(reverse(myStrA))
print(reversed(myStrA))

Python/98_授课/Algorithm development/01_String/10_How do you reverse words in a given sentence 2 methods/word_reverse.py


from utils.errorResponse import create_error_with_status
import constants

from werkzeug.wrappers import Request, Response
import requests
import json

class AuthMiddleware:
    def __init__(self, app, base_app, logger):
        self.app = app
        self.base = base_app
        self.logger = logger

    def __call__(self, environ, start_response):
        request = Request(environ, shallow=True)
        if request.method in ["POST", "DELETE", "PUT", "PATCH"]:
            self.logger.info("Auth request")
            auth_url = self.base.config["AUTH_SERVICE_URI"] + "/validate"
            self.logger.debug(auth_url)
            if "accessToken" not in request.headers:
                self.logger.warn("No token for auth")
                res = Response(json.dumps(create_error_with_status(0, "No token detected")), mimetype="application/json",
                               status=constants.common_responses["No auth"])
                return res(environ, start_response)

            auth = requests.post(auth_url, json={"token": request.headers["accessToken"]})

            self.logger.debug(str(auth.status_code) + str(auth.content))
            auth_status = auth.json()["status"]

            if auth_status != constants.statuses["tokens"]["accessOk"]:
                auth_error = auth.json()["error"]
                self.logger.warn("Access token is not OK")
                res = Response(json.dumps(create_error_with_status(0, auth_error)), mimetype="application/json",
                               status=constants.common_responses["No auth"])
                return res(environ, start_response)
            auth_email = auth.json()["value"]["email"]
            environ["user_email"] = auth_email

        return self.app(environ, start_response)


import tkinter as tk
import protocol
import random
from tkinter import messagebox

class App(tk.Frame):
    upper_text = None

    interface_frm = None
    interface_ip_field = None
    interface_ip = None
    interface_port_field = None
    interface_port = None
    interface_connect_bttn = None

    connection_frm = None
    client_list = None
    popup = None

    e91_params_frm = None
    length_field = None
    length = None
    seed_field = None
    seed = None
    run_bttn = None

    results_frm = None
    key_field = None
    delta_s_field = None

    server_socket = None
    role = None
    client_addr_list = None
    client_addr = None

    def __init__(self, master):
        super().__init__(master)
        self.grid()

        self.upper_text = tk.Label(text="CONNECTION SETTINGS")
        self.upper_text.grid(column=0, row=0, sticky=tk.W)

        self.interface_frm = tk.Frame()
        self.interface_frm.grid(column=0, row=1, sticky=tk.W)

        tk.Label(master=self.interface_frm, text="Interface-IP: ").grid(column=0, row=0, sticky=tk.W)
        self.interface_ip_field = tk.Entry(master=self.interface_frm)
        self.interface_ip_field.grid(column=1, row=0, sticky=tk.W)
        self.interface_ip = tk.StringVar()
        self.interface_ip_field["textvariable"] = self.interface_ip

        tk.Label(master=self.interface_frm, text="Interface-Port: ").grid(column=2, row=0, sticky=tk.W)
        self.interface_port_field = tk.Entry(master=self.interface_frm)
        self.interface_port_field.grid(column=3, row=0, sticky=tk.W)
        self.interface_port = tk.IntVar()
        self.interface_port_field["textvariable"] = self.interface_port

        self.connect_bttn = tk.Button(text="connect", command=self.connect_to_interface)
        self.connect_bttn.grid(column=0, row=2, sticky=tk.W)

    def connect_to_interface(self):
        self.server_socket, own_addr = protocol.q_establish_connection((self.interface_ip.get(),
                                                                        self.interface_port.get(),))
        self.upper_text.config(text="SELECT PARTNER")
        self.connect_bttn.destroy()
        self.interface_frm.destroy()
        self.connection_frm = tk.Frame()
        self.connection_frm.grid(column=0, row=1, sticky=tk.W)
        tk.Label(master=self.connection_frm, text=f"your IP: {own_addr[0]}:{own_addr[1]}").grid(column=0, row=0)
        self.client_list = tk.Listbox(master=self.connection_frm, selectmode=tk.SINGLE)
        self.client_list.grid(column=0, row=1, sticky=tk.W)
        button_frm = tk.Frame(master=self.connection_frm)
        button_frm.grid(column=0, row=2)
        tk.Button(master=button_frm, text="update", command=self.update_users).\
            grid(column=0, row=0, sticky=tk.W)
        tk.Button(master=button_frm, text="choose", command=self.choose_user).\
            grid(column=1, row=0, sticky=tk.E)

    def update_users(self):
        self.client_addr_list, connection_req = protocol.q_update(self.server_socket)
        if connection_req is not None:
            popup = tk.Toplevel(self.master)
            popup.geometry("300x200+200+200")
            tk.Label(popup, text=f"{connection_req[0]}:{connection_req[1]} want to communicate.").pack(fill=tk.BOTH)

            def accept(app):
                app.role = False
                app.client_addr = connection_req
                app.draw_parameter_screen()
                protocol.q_accept_user(app.server_socket, True)
                popup.destroy()

            def refuse(app):
                protocol.q_accept_user(app.server_socket, app.client_addr, False)
                popup.destroy()

            tk.Button(popup, text="accept", command=lambda: accept(self)).pack(side=tk.LEFT, fill=tk.BOTH)
            tk.Button(popup, text="refuse", command=lambda: refuse(self)).pack(side=tk.RIGHT, fill=tk.BOTH)

        else:
            self.client_list.delete(0, tk.END)
            for i in range(len(self.client_addr_list)):
                self.client_list.insert(i, f"{self.client_addr_list[i][0]}:{self.client_addr_list[i][1]}")

    def choose_user(self):
        if len(self.client_list.curselection()) != 0:
            addr = self.client_addr_list[self.client_list.curselection()[0]]
            if protocol.q_choose_user(self.server_socket, addr):
                self.role = True
                self.client_addr = addr
                self.draw_parameter_screen()
            else:
                messagebox.showinfo(title="Connection Refused", message="The chosen client has refused the connection")

    def draw_parameter_screen(self):
        self.connection_frm.destroy()
        self.upper_text.config(text="E91 PARAMETERS")
        self.e91_params_frm = tk.Frame()
        self.e91_params_frm.grid(column=0, row=1, sticky=tk.W)

        tk.Label(master=self.e91_params_frm, text="Bitstring length: ").grid(column=0, row=0, sticky=tk.W)
        self.length_field = tk.Entry(master=self.e91_params_frm)
        self.length_field.grid(column=1, row=0, sticky=tk.W)
        self.length = tk.IntVar()
        self.length_field["textvariable"] = self.length

        tk.Label(master=self.e91_params_frm, text="Seed: ").grid(column=0, row=1, sticky=tk.W)
        self.seed_field = tk.Entry(master=self.e91_params_frm)
        self.seed_field.grid(column=1, row=1, sticky=tk.W)
        self.seed = tk.IntVar()
        self.seed_field["textvariable"] = self.seed

        self.run_bttn = tk.Button(text="run", command=self.run)
        self.run_bttn.grid(column=0, row=2, sticky=tk.W)

    def run(self):
        self.e91_params_frm.destroy()
        self.run_bttn.destroy()
        self.upper_text.config(text="running...")
        delta_s, key = protocol.e91protocol(self.length.get(), self.seed.get(), random,
                                            self.server_socket, self.role, self.client_addr)

        self.upper_text.config(text="RESLUTS")
        self.results_frm = tk.Frame()
        self.results_frm.grid(column=0, row=1, sticky=tk.W)

        tk.Label(master=self.results_frm, text="key: ").grid(column=0, row=0)
        self.key_field = tk.Entry(master=self.results_frm)
        self.key_field.grid(column=1, row=0)
        self.key_field["textvariable"] = key

        tk.Label(master=self.results_frm, text="delta s: ").grid(column=0, row=1)
        self.delta_s_field = tk.Entry(master=self.results_frm)
        self.delta_s_field.grid(column=1, row=1)
        self.delta_s_field["textvariable"] = delta_s

root = tk.Tk()
root.geometry("700x500+40+50")
root.title("E91 protocol client")
myapp = App(root)

if __name__ == '__main__':
    myapp.mainloop()


#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
import sys

def get_backup(country, data_touple, path_to_data='results/'):
    """
    Returns the load in MWh.
    """
    # -- Unpacking the touple --
    names = ['constraint', 'flowscheme', 'alpha', 'gamma', 'beta']
    data = dict(zip(names, data_touple))

    countries = ['AT', 'FI', 'NL', 'BA', 'FR', 'NO', 'BE', 'GB', 'PL', 'BG',
                 'GR', 'PT', 'CH', 'HR', 'RO', 'CZ', 'HU', 'RS', 'DE', 'IE',
                 'SE', 'DK', 'IT', 'SI', 'ES', 'LU', 'SK', 'EE', 'LV', 'LT']
    country_dict = dict(zip(countries, list(range(len(countries)))))

    return np.load(path_to_data +
                   '{constraint}_{flowscheme}_a{alpha:.2f}_g{gamma:.2f}_b{beta:.2f}_N.npz'\
                   .format(**data))['balancing'][country_dict[country]]

def get_load(country, path_to_data='data/'):
    """
    Returns the load in MWh.
    """
    return np.load(path_to_data + 'ISET_country_' + country + '.npz')['L']*1000

def quantile(quantile, dataset):
    """
    Docstring for quantile.
    """
    return np.sort(dataset)[int(round(quantile*len(dataset)))]

def time_between_extreme_events(timeseries, q=0.99, ignore_hours=0):
    """
    Finds the waiting times between extreme events in a timeseries.

    Parameters
    ----------
    timeseries:
    The timeseries we want to analyze.

    q:
    The quantile with which we want to quantify the extreme events.
    I.e. only event rarer than q are used in the analysis.

    ignore_hours:
    The number of hours we want to ignore, if the waiting time
    is smaller than.

    Return
    ------
    np.diff(extreme_events):
    The difference between extreme events that are farther
    apart than ignore_hours.
    """
    q = quantile(q, timeseries)
    # find the hours that contain extreme events
    extreme_events = np.arange(len(timeseries))[timeseries > q]
    if ignore_hours == 0:
        return np.diff(extreme_events)
    elif ignore_hours > 0:
        extreme_events_ignore = np.zeros(len(extreme_events), dtype=bool)
        extreme_events_ignore[0] = True # We always want to include the first extreme event
        # counter used to see when we exceed the number of ignored hours
        counter = 0
        for index, dif in enumerate(np.diff(extreme_events)):
            counter += dif
            if counter > ignore_hours:
                # index + 1 works because index ranges from
                # 0 to length(extreme_events) - 1
                extreme_events_ignore[index + 1] = True
                # reset the counter
                counter = 0
        # return the waiting times between the hours that contain extreme
        # events and that are also more than ignore_hours apart.
        return np.diff(extreme_events[extreme_events_ignore])
    elif ignore_hours < 0:
        print('ignore_hours must be positive. Try again.')

if __name__ == '__main__':
    data_touple = ('c', 's', 0.80, 1.00, 1.00)
    DK_backup = get_backup('DK', data_touple, path_to_data='./')
    DK_load = get_load('DK', path_to_data='/home/simon/Dropbox/Root/Data/ISET/')
    evs = time_between_extreme_events(DK_backup, ignore_hours=0)
    evs_in_weeks = evs/float(24*30)
    hist, bin_edges = np.histogram(evs_in_weeks, bins=500, normed=True)
    bins = 0.5*(bin_edges[:-1] + bin_edges[1:])
    hist = hist*np.diff(bins)[0]
    plt.plot(bins, hist)
    plt.show()

    from scipy.optimize import curve_fit
    from scipy.misc import factorial

    def poisson(k, lamb):
        return (lamb**k/factorial(k))*np.exp(-lamb)

    def log_factorial(n):
        n = int(n)
        return np.sum(np.log(np.arange(n) + 1))

    def log_poisson(x, a, b):
        return a*x + b

    ydata = np.log(hist) + np.asarray([log_factorial(n) for n in bins])
    xdata = bins[~np.isnan(ydata)]
    ydata = ydata[~np.isnan(ydata)]
    xdata = xdata[~np.isinf(ydata)]
    ydata = ydata[~np.isinf(ydata)]
    ydata = ydata[xdata > 0]
    xdata = xdata[xdata > 0]
    plt.plot(xdata, ydata, label='data', linewidth=2)

    param, pcov = curve_fit(log_poisson, xdata, ydata)
    a = param[0]
    b = param[1]
    print('lambda = {}'.format(-b))
    plt.plot(xdata, log_poisson(xdata, a, b), 'r', label='log_poisson fit')
    plt.legend(loc=2)
    plt.show()

    x_plot = np.arange(max(bins) + 1)
    plt.plot(bins, hist, 'b.')
    plt.plot(x_plot, poisson(x_plot, -b),  'r-')
    plt.show()


import os
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

# segmentare binara
#INPUT_PATH = r'E:\an_4_LICENTA\Scripturi_24mar\Scripturi\core\results\UNET_binar_brats_2D_FULLDATASET_lr=10^(-4)CONSTANT_AugumentareFLIP,ZOOM_de_la_inceput_Gibbsringingremoved_Squeeze&Extract_8b_SIGMOIDA_32_64_128_256_lr=10^(-4)_normalizaresimpla_bil0.9369.txt'
# dreapta (jos)
INPUT_PATH = r'E:\an_4_LICENTA\Workspace\Scripturi\core\results\wt1.txt' # cu augumentare
# stanga (jos)
#INPUT_PATH = r'E:\an_4_LICENTA\Workspace\Scripturi\core\results\UNET_binar_brats_2D_Gibbsringingremoved_Squeeze&Extract_biassfieldremoved2D_8b_SIGMOIDA_32_64_128_256_lr=10^(-4)_normalizaresimpla_bilinear_0.9316.txt' #
#INPUT_PATH = r'E:\an_4_LICENTA\Workspace\Scripturi\core\results\UNET_RESNET_HYBRID_1_number_of_blocks_3.txt' # OVERFIT SAU ZGOMOT?

# segmentare multiclasa
#INPUT_PATH = r'E:\an_4_LICENTA\Workspace\Scripturi\core_semantic\results_semantic\ABSOLUTE_FULL_DTS__unet_semantic_brats_2D_v3_COPIE_sigmaoida_fcost_dice_Vlad_weights_batch_gibbsremove_eph61.txt'
#INPUT_PATH = r'E:\an_4_LICENTA\Workspace\Scripturi\core_semantic\results_semantic\delazero.txt'
#INPUT_PATH = r'E:\an_4_LICENTA\Workspace\Scripturi\core_semantic\results_semantic\transferLR_gibbsoptimization_1.txt'

INPUT_PATH1 = r'E:\an_4_LICENTA\Workspace\Scripturi\core_semantic\results_semantic\delazero.txt'
INPUT_PATH2 = r'E:\an_4_LICENTA\Workspace\Scripturi\core_semantic\results_semantic\UNET_binar_brats_2D_FULLDATASET_lr=10^(-4)CONSTANT_Augumentare_FLIP,ZOOM_GAUSS_de_la_inceput_Gibbsringingremoved_Squeeze&Extract_biassfieldremoved2D_8b_SIGMOIDA_32_64_128_256_lr=10^(-4)_normalizaresimpla_bil.txt'

INPUT_PATH1 = r'E:\an_4_LICENTA\Workspace\Scripturi\core\results\wt1.txt'
INPUT_PATH2 = r'E:\an_4_LICENTA\Workspace\Scripturi\core\results\UNET_binar_brats_2D_Gibbsringingremoved_Squeeze&Extract_biassfieldremoved2D_8b_SIGMOIDA_32_64_128_256_lr=10^(-4)_normalizaresimpla_bilinear_0.9316.txt' #

def extract_data(INPUT_PATH):

    A = [] # lista cu atribute, adica cu metricile
    # = [] # de fapt nu prea am nevoie de x
    Y = [] # va fi omlista de liste. fiecare lista contine scorurile, de-a lungul axei timpului

    with open(INPUT_PATH, 'r') as file:
        text = file.read()

    lines = text.splitlines()

    for line in lines:
        line_sep_by_coma = line.split(',')
        for element in line_sep_by_coma:
            if len(element.split(':')) == 2:
                attribute, value = element.split(':')
                attribute, value = attribute.strip(), value.strip()
                # se trateaza cazul in care nu se regaseste inca acest atrinut inlista cu atribute
                if attribute not in A:
                    A.append(attribute)
                if len(Y) <= A.index(attribute):
                    Y.append([])
                Y[A.index(attribute)].append(float(value))
    return A, Y

#print(Y)
#print(len(Y))

def generate_2_overlaped_graphs(INPUT_PATH1, INPUT_PATH2):
    A1, Y1 = extract_data(INPUT_PATH1)
    A2, Y2 = extract_data(INPUT_PATH2)
    for y1, y2 in zip(Y1, Y2):
        plt.figure()
        print(y1)
        plt.plot([i for i in range(1, len(y1)+1)], list(y1), label='cu augmentare')
        plt.plot([i for i in range(1, len(y2)+1)], list(y2), label='fără augmentare')
        plt.xlabel('Număr de epoci')
        #plt.ylabel('Valoarea funcției de cost')
        plt.ylabel('Dice - Validare')
        plt.legend(loc='upper right', fontsize=12)
        #plt.legend(loc='lower right', fontsize=12)
        plt.show()

def generate_one_graph(INPUT_PATH):
    A, Y = extract_data(INPUT_PATH)
    for y in Y:
        plt.figure()
        print(y)
        plt.plot([i for i in range(1, len(y)+1)], list(y))
        plt.show()

def generate_graph_binara_val_vs_train_dice(INPUT_PATH):
    A, Y = extract_data(INPUT_PATH)
    plt.figure()
    train_dice = []
    for i in Y[0]:
        train_dice.append(1-i)
    plt.plot([i for i in range(1, len(train_dice)+1)], list(train_dice), label='F1-antrenare')
    plt.plot([i for i in range(1, len(Y[2])+1)], list(Y[2]), label='F1-validare')
    plt.xlabel('Număr de epoci')
    plt.ylabel('Dice')
    plt.legend(loc='lower left', fontsize=12)
    plt.show()

#################################

# Geenrate one graph
#generate_one_graph(INPUT_PATH)

# Generate 2 graphs
generate_2_overlaped_graphs(INPUT_PATH1, INPUT_PATH2)

# Genereaza grafic pentru train dice vs val dice - ca sa se vada overfitul
#generate_graph_binara_val_vs_train_dice(INPUT_PATH)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
from io import open
import os.path as osp
from setuptools import setup
from setuptools.command.install import install

HERE = osp.abspath(osp.dirname(__file__))
sys.path.insert(0, HERE)
from pibooth_oled_display import pibooth_oled_display as plugin

def main():
    setup(
        name="pibooth_oled_display",
        version=plugin.__version__,
        description=plugin.__doc__,
        long_description=open(osp.join(HERE, 'README.rst'), encoding='utf-8').read(),
        long_description_content_type='text/x-rst',
        classifiers=[
            'Development Status :: 5 - Production/Stable',
            'Environment :: Plugins',
            'Intended Audience :: Developers',
            'Intended Audience :: End Users/Desktop',
            'License :: OSI Approved :: GNU Affero General Public License v3',
            'Natural Language :: English',
            'Operating System :: POSIX :: Linux',
            'Programming Language :: Python :: 3.6',
            'Programming Language :: Python :: 3.7',
            'Programming Language :: Python :: 3.8',
            'Programming Language :: Python :: 3.9',
            'Topic :: Multimedia :: Graphics :: Capture :: Digital Camera',
        ],
        author="Kenneth Nicholas Jørgensen",
        url="https://github.com/DJ-Dingo/pibooth-oled-display",
        download_url="https://github.com/DJ-Dingo/pibooth-oled-display/archive/{}.tar.gz".format(plugin.__version__),
        license='GPLv3',
        platforms=['unix', 'linux'],
        keywords=[
            'raspberry pi',
            'camera',
            'raspberry pi camera',
            'photobooth',
            'selfiecam',
            'pygame',
            'pil',
            'pillow',
            'pibooth',
            'pibooth plugin',
            'oled display',
            'luma.oled',
            'oled'
        ],
        python_requires=">=3.6",
        install_requires=[
            'pibooth>=2.0.3',
            'luma.oled>=3.12.0',
            'setuptools'
        ],
        include_package_data=True,
        packages=['pibooth_oled_display', 'pibooth_oled_display.oled_display'],
        package_data={
            'pibooth_oled_display.oled_display': ['logo/*', 'fonts/*', 'default/*', '*.py', '*.rst',
                                                  'states/capture/*',
                                                  'states/choose/*',
                                                  'states/failure/*',
                                                  'states/finished/*',
                                                  'states/layout/*',
                                                  'states/preview/*',
                                                  'states/printer/*',
                                                  'states/processing/*']
        },
        options={
            'bdist_wheel': {'universal': True}
        },
        zip_safe=False,
        entry_points={'pibooth': ["pibooth_oled_display = pibooth_oled_display.pibooth_oled_display"]},
    )

if __name__ == '__main__':
    main()


import sys
import importlib
from collections import defaultdict

class Loader():
    def __init__(self, moduleType, subModRef, hostPackage):
        self.moduleType = moduleType.lower()
        self.subModRef = subModRef
        self.hostPackage = hostPackage
        self.moduleKeyMap = {}

    def fetchModule(self, moduleKey):
        mod = self.moduleKeyMap.get(moduleKey, None)
        if mod is None:
            mod = self.loadModule(moduleKey)

        return mod

    def moduleName(self, moduleKey):
        return "{0}.{1}".format(self.subModRef, moduleKey)

    def loadModule(self, moduleKey):
        moduleName = self.moduleName(moduleKey)
        if moduleName in sys.modules:
            return Module(moduleKey, sys.modules[moduleName], self)

        m = importlib.import_module(moduleName, package=self.hostPackage)
        return self._regModule(moduleKey, m)

    def unloadModule(self, moduleKey):
        self.moduleKeyMap.pop(moduleKey)
        moduleName = self.moduleName(moduleKey)
        if moduleName not in sys.modules:
            return

        Module(moduleKey, sys.modules[moduleName], self).callIfExist("unloaded")
        del sys.modules[moduleName]

    def reloadModule(self, moduleKey):
        moduleName = self.moduleName(moduleKey)
        if moduleName in sys.modules:
            m = sys.modules[moduleName]
            Module(moduleKey, m, self).callIfExist("unloaded")
            m = importlib.reload(m)
            mod = self._regModule(moduleKey, m)
        else:
            mod = self.loadModule(moduleKey)

        return mod

    def _regModule(self, moduleKey, m):
        mod = Module(moduleKey, m, self)
        mod.callIfExist("loaded")
        self.moduleKeyMap[moduleKey] = mod
        return mod

    def unloadAllModules(self):
        for k in self.moduleKeyMap.keys():
            self.unloadModule(k)

class Module:
    def __init__(self, moduleKey, mod, loader):
        self.moduleKey = moduleKey
        self.mod = mod
        self.loader = loader

    def objByBaseType(self, baseType):
        return self.objDictByBaseType([baseType]).get(baseType, [])

    def objDictByBaseType(self, baseTypes):
        objDict = defaultdict(list)
        for type_name in dir(self.mod):
            try:
                t = self.mod.__dict__[type_name]
                if not t.__bases__:
                    continue

                for baseType in baseTypes:
                    if type_name == baseType.__name__:
                        continue

                    if issubclass(t, baseType):
                        objDict[baseType].append(t)

            except AttributeError:
                pass

        return objDict

    def callIfExist(self, interface, *args, **kwds):
        interface = self._normName(interface)
        if interface in self.mod.__dict__:
            self.mod.__dict__[interface](*args, **kwds)

    def call(self, interface, *args, **kwds):
        interface = self._normName(interface)
        self.mod.__dict__[interface](*args, **kwds)

    def _normName(self, name):
        return "{0}_{1}".format(self.loader.moduleType, name)


import json
import math
import time
import csv
import graphviz
import numpy as np
import pandas as pd
from io import BytesIO
from sklearn import svm
from sklearn import tree
from sklearn import metrics
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split

# Count the number of values occurrence in dictionary
# Input type: dic. Example: price_data.values()
# Output type: dic
def count_values(value):
	result = {}
	for i in value:
		result[i] = result.get(i, 0) + 1
	return result

# Take the hour out from created column
# Input type: dic. Example: data.get("created", "")
# Output type: list
def extrac_hour(data):
	time = []
	hour = []
	values = data.values()
	for i in values:
		time.append(i.split(' ')[1])
	for i in time:
		hour.append(i.split(':')[0])
	return hour

# Count the same address and use the index in the list for the category
# Input type: data -> train data or test data, column -> column name, df -> train data frame or test data frame
# Output type: list
def calculate_address_category(data, column, df):
	address = data.get(column, '')
	count = count_values(address.values())

	# After count, put all the address into list
	# get a list of distinct addresses
	# Ex: ['Suffolk Street', 'Thompson Street' ...]
	address_collection = []
	for key, value in count.items():
		address_collection.append(key)

	# Get the address from data frame and
	# compare to address_collection to get the
	# index and the index is the category
	# Ex: [0, 1, 2, 1, 0, 500 ...]
	address_category = []
	for i in df[column]:
		address_category.append(address_collection.index(i))

	return address_category

def listToString(s):
	# initialize an empty string
	str1 = ""
	# traverse in the string
	for ele in s:
		str1 += " "
		str1 += ele
	# return string
	return str1

def count_feature_number(feature_names):
	def f2(s):
		result_list = []
		for ele in feature_names:
			if ele in s:
				result_list.append(1)
			else:
				result_list.append(0)
		return result_list
	result = f2
	return result

def count_feature(data):
	corpus = data['features'].values
	with open("decision_tree_text_features.txt", "r") as f:
		feature_names = f.read().splitlines()

	for i in range(len(feature_names)):
		feature_names[i] = feature_names[i].capitalize()

	count_f = count_feature_number(feature_names)
	feature_result = list(map(count_f, corpus))

	count_feature = []
	for i in feature_result:
		count_feature.append(i[0])
	return count_feature

def x_ysquare(data,value):
	square = []
	for i in data:
		square.append((i-value)**2)
	return square
def distance(data1,data2):
	f_distance = []
	for x in range(len(data1)):
		f_distance.append(math.sqrt(data1[x]+data2[x]))
	return f_distance

def decision_tree():
	print ("Running Decision Tree...\n")
	with open('test.json') as json_file:
		test_data = json.load(json_file)

	with open('train.json') as json_file:
		data = json.load(json_file)

		data_frame = pd.DataFrame(data)
		test_data_frame = pd.DataFrame(test_data)

		# Count the number of photos in the training set
		count_photo = []
		for i in data_frame['photos']:
			count_photo.append(len(i))
		# Count the number of photos in the test set
		count_test_photo = []
		for i in test_data_frame['photos']:
			count_test_photo.append(len(i))
		# Append the data as columns into data_frame
		data_frame['count_photos'] = count_photo
		test_data_frame['count_photos'] = count_test_photo

		# Append the address as columns into data_frame
		data_frame['address_category'] = calculate_address_category(data, 'display_address', data_frame)
		test_data_frame['address_category'] = calculate_address_category(test_data, 'display_address', test_data_frame)

		# Extracting hour and append them into data frame
		hour = extrac_hour(data.get("created", ""))
		test_hour = extrac_hour(test_data.get("created", ""))
		data_frame['hour'] = hour
		test_data_frame['hour'] = test_hour

		# Append the features word counting as columns into data_frame
		data_frame['count_feature'] = count_feature(data_frame)
		test_data_frame['count_feature'] = count_feature(test_data_frame)

		# Get the target and features
		target_values = data_frame['interest_level'].values.reshape(-1, 1)
		features = ['price', 'address_category', 'hour', 'latitude', 'longitude', 'bathrooms', 'count_photos', 'count_feature']

		# Set up the classifier
		clf = DecisionTreeClassifier(min_samples_split=5, max_depth=6)
		# Using cross_val_score to calculate the score of the training set
		score = cross_val_score(clf, data_frame[features], target_values, cv=10)

		print ("The score of the training set is: \n", score)
		print ("Mean of score: ", score.mean())
		print ("Accuracy: %0.2f (+/- %0.2f)" % (score.mean(), score.std() * 2))

		# Train the model
		clf.fit(data_frame[features], target_values)

		# Get the predict probability of test set
		predict = clf.predict_proba(test_data_frame[features])

		# Put the prediction into data frame with listing id
		# Export it to csv file for submitting to Kaggle
		result = pd.DataFrame({"listing_id": test_data_frame["listing_id"].values, "high": predict[:, 0], "medium": predict[:, 2], "low": predict[:, 1]})
		result.to_csv('decision_tree_result.csv', index=False)
		print ("\nFile: decision_tree_result.csv generated.")
		# Draw the decision tree into pdf
		dot_data = tree.export_graphviz(clf, out_file=None,
										filled=True, rounded=True,
										special_characters=True)
		graph = graphviz.Source(dot_data)
		graph.render("Decision Tree")
		print ("\nFile: Decision Tree.pdf generated.")

def SVM():
	print ('\nRunning SVM...\n')
	#open tain.jason
	with open('train.json') as json_file:
		data = json.load(json_file)
		data_frame = pd.DataFrame(data)

		print ("Extracting features from text...\n")

		corpus = data_frame['features'].values
		with open("text_features.txt", "r") as f:
			feature_names = f.read().splitlines()

		for i in range(len(feature_names)):
			feature_names[i] = feature_names[i].capitalize()

		# print(corpus)
		# print(feature_names)
		count_f = count_feature_number(feature_names)
		result = list(map(count_f, corpus))
		# print(result)

		myfeatures = result
		mytarget = data_frame['interest_level'].values
		# X_train, X_test, y_train, y_test = train_test_split(myfeatures, mytarget, test_size = 0.2)
		clf = svm.SVC(kernel = 'linear')
		clf.fit(myfeatures, mytarget)
		y_pred = clf.predict(myfeatures)
		print(y_pred)

		print("Accuracy:",metrics.accuracy_score(mytarget, y_pred))

		#start cross validation by k-fold
		from sklearn.model_selection import KFold # import KFold
		X = np.array(result) # create an array
		y = np.array(mytarget) # Create another array
		kf = KFold(n_splits=5) # Define the split - into 2 folds
		kf.get_n_splits(myfeatures) # returns the number of splitting iterations in the cross-validator
		clf2 = svm.SVC(kernel='linear',probability=True) # Linear Kernel
		scores = []
		proba = []
		for train_index, test_index in kf.split(X):
			X_train, X_test = X[train_index], X[test_index]
			y_train, y_test = y[train_index], y[test_index]
			#Create a svm Classifier

			#Train the model using the training sets
			clf2.fit(X_train, y_train)

			#Predict the response for test dataset
			y_pred = clf2.predict(X_test)
			scores.append(metrics.accuracy_score(y_test, y_pred))

			y_prob = clf2.predict_proba(myfeatures)
			proba.append(y_prob)
		print("done")

	#test the model by test data
	with open('test.json') as json_file:
		data_test = json.load(json_file)
		data_frame_test = pd.DataFrame(data_test)

		corpus_test = data_frame_test['features'].values
		with open("text_features.txt", "r") as f:
			feature_names_test = f.read().splitlines()

		for i in range(len(feature_names_test)):
			feature_names_test[i] = feature_names_test[i].capitalize()

		# print(corpus)
		# print(feature_names)
		count_f_test = count_feature_number(feature_names_test)
		result_test = list(map(count_f_test, corpus_test))

		myfeatures_test = result_test
		y_pred_test = clf2.predict(myfeatures_test)

		y_prob_test = clf2.predict_proba(myfeatures_test)

		y_prob_test2 = y_prob_test
		#y_prob_test
		y_prob_test = []
		for i in range(len(y_prob_test2)):
			temp = []
			temp.append(y_prob_test2[i][0])
			temp.append(y_prob_test2[i][2])
			temp.append(y_prob_test2[i][1])
			y_prob_test.append(temp)

		listing_ids_test = list(data_frame_test['listing_id'].values)
		i_test = 0
		output_test = []
		for i in range(len(y_prob_test)):
			temp_test = []
			temp_test.append(listing_ids_test[i])

			temp_test.extend(y_prob_test[i])
			output_test.append(temp_test)
			i_test = i_test + 1

		with open('SVM_result.csv', 'w', newline='') as mycsvfile:
			thedatawriter = csv.writer(mycsvfile, delimiter=',', lineterminator = '\n')
			thedatawriter.writerows(output_test)
		with open('SVM_result.csv',newline='') as f:
			r = csv.reader(f)
			data = [line for line in r]
		with open('SVM_result.csv','w',newline='') as f:
			w = csv.writer(f)
			w.writerow(['listing_id', 'high', 'medium', 'low'])
			w.writerows(data)

def logistic_regression():
	print ("\nRunning Logistic Regression...\n")
	with open('test.json') as json_file:
		test_data = json.load(json_file)

	with open('train.json') as json_file:
		data = json.load(json_file)

		data_frame = pd.DataFrame(data)
		test_data_frame = pd.DataFrame(test_data)

		city_latitude = 40.730610
		city_longitude = -73.935242

		x_square = x_ysquare(data_frame['latitude'],city_latitude)
		y_square = x_ysquare(data_frame['longitude'],city_longitude)

		x_square_test = x_ysquare(test_data_frame['latitude'],city_latitude)
		y_square_test = x_ysquare(test_data_frame['longitude'],city_longitude)

		# print (max(calculate_address_category(data, 'display_address', data_frame)))

		data_frame['address_category'] = calculate_address_category(data, 'display_address', data_frame)
		test_data_frame['address_category'] = calculate_address_category(test_data, 'display_address', test_data_frame)

		data_frame['center_distance'] = distance(x_square,y_square)
		test_data_frame['center_distance'] = distance(x_square_test,y_square_test)

		hour = extrac_hour(data.get("created", ""))
		test_hour = extrac_hour(test_data.get("created", ""))
		data_frame['hour'] = hour
		test_data_frame['hour'] = test_hour

		target_values = data_frame["interest_level"].values.ravel()
		features = ['price', 'address_category', 'hour', 'latitude', 'longitude', 'bathrooms','center_distance']
		# kf = KFold(n_splits=10)

		lr = LogisticRegression(multi_class ='multinomial', max_iter=5000)
		lr.fit(data_frame[features], target_values)

		score = cross_val_score(lr, data_frame[features], target_values, cv=10)

		print (score)
		print (score.mean())

		print("=================")

		accuracy = cross_val_score(lr, data_frame[features], target_values, cv=10,scoring='balanced_accuracy')
		print(accuracy)
		print (accuracy.mean())

		predict = lr.predict_proba(test_data_frame[features])

		result = pd.DataFrame({"listing_id": test_data_frame["listing_id"].values, "high": predict[:, 0], "medium": predict[:, 2], "low": predict[:, 1]})
		result.to_csv('logistic_regression_result.csv', index=False)

if __name__ == "__main__":
	decision_tree()
	logistic_regression()
	SVM()