from __future__ import print_function

import json
import boto3
import re
from urllib.request import urlopen
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

comprehendClient = boto3.client('comprehend')
s3Client = boto3.client('s3')

def lambda_handler(event, context):
    print("Received event: " + json.dumps(event, indent=2))

    asins = event['asins']
    reviewOutput = {}
    for asin in asins:
        asinData = {}
        reviewIndex = 0;
        url = "https://www.amazon.com/product-reviews/" + asin + "?pageNumber=2"
        response = urlopen(url)
        responseData = response.read()

        reviews = re.findall(r'(.*?)', str(responseData))

        asinReviews=[]
        for review in reviews:
            reviewCleaned = re.sub('([0-9]{2}&#[0-9]{2}|
|\\\\x..|\\\\|&#([0-9]){2})','',review)
            asinReviews.append(reviewCleaned)

        reviewOutput[asin] = asinReviews

    #print(reviewOutput)

    dataFrame = []

    for asin in asins:
        reviewList = reviewOutput[asin]

        comprehendOutput = comprehendClient.batch_detect_sentiment(TextList=reviewList, LanguageCode='en')
        nlpResponseResultList = comprehendOutput['ResultList']

        for nlpResponse in nlpResponseResultList:
            score = nlpResponse['SentimentScore']

            recordType = [asin,
                    score['Positive'], score['Negative'], score['Positive']-score['Negative'],
                    score['Neutral'], score['Mixed'], score['Neutral']-score['Mixed'],
                    nlpResponse['Sentiment']
                ]
            dataFrame.append(recordType)

    df = pd.DataFrame(dataFrame, columns=['ASIN','Pos','Neg', 'PosNeg', 'Neu', 'Mix', 'NeuMix', 'Sentiment'])
    asin0 = df.loc[(df["ASIN"] == asins[0])]
    asin1 = df.loc[(df["ASIN"] == asins[1])]

    bucketName = event['bucket']

    plt.figure()
    ax = plt.scatter(x=asin0["PosNeg"], y=asin0["NeuMix"], s=(1-asin0["Mix"])*1000, alpha=0.2, color='orchid', label=asins[0])
    ax = plt.scatter(x=asin1["PosNeg"], y=asin1["NeuMix"], s=(1-asin1["Mix"])*1000, alpha=0.2, color='orange', label=asins[1])
    plt.xlabel("Negavtive-to-Positive sentiment")
    plt.ylabel("Mixed-to-Neutral sentiment")
    plt.legend(loc=3,markerscale=0.5)
    plt.savefig('/tmp/scatter.png')
    s3Client.upload_file('/tmp/scatter.png', bucketName , 'scatter.png')

    plt.figure()
    sizes, labels, colors = pie_chart(asins[0], df)
    plt.pie(sizes, labels=labels, colors=colors, startangle=90, autopct='%1.1f%%')
    plt.axis('equal')
    plt.title(asins[0])
    plt.savefig('/tmp/pie1.png')
    s3Client.upload_file('/tmp/pie1.png', bucketName, 'pie1.png')

    plt.figure()
    sizes, labels, colors = pie_chart(asins[1], df)
    plt.pie(sizes, labels=labels, colors=colors, startangle=90, autopct='%1.1f%%')
    plt.axis('equal')
    plt.title(asins[1])
    plt.savefig('/tmp/pie2.png')
    s3Client.upload_file('/tmp/pie2.png', bucketName, 'pie2.png')

    return dataFrame

def pie_chart(asin, df):
    pos0 = df[(df["ASIN"]==asin) & (df["Sentiment"]=="POSITIVE")].count()[0]
    neg0 = df[(df["ASIN"]==asin) & (df["Sentiment"]=="NEGATIVE")].count()[0]
    mix0 = df[(df["ASIN"]==asin) & (df["Sentiment"]=="NEUTRAL")].count()[0]
    neu0 = df[(df["ASIN"]==asin) & (df["Sentiment"]=="MIXED")].count()[0]

    sizes = []
    labels = []
    colors = []
    if pos0 > 0:
        sizes.append(pos0)
        labels.append("Positive")
        colors.append("yellowgreen")
    if neu0 > 0:
        sizes.append(neu0)
        labels.append("Neutral")
        colors.append("lightskyblue")
    if mix0 > 0:
        sizes.append(mix0)
        labels.append("Mixed")
        colors.append("gold")
    if neg0 > 0:
        sizes.append(neg0)
        labels.append("Negative")
        colors.append("lightcoral")
    return sizes, labels, colors


import sys, pickle, numpy as np
from data import Vocab

gloveFile = sys.argv[1]
path_to_vocab = sys.argv[2]
save_file = sys.argv[3]
emb_dim = int(sys.argv[4])

vocab = Vocab('../data/vocab', 50000)

#https://stackoverflow.com/questions/37793118/load-pretrained-glove-vectors-in-python
def loadGloveModel(gloveFile):
    print("Loading Glove Model")
    with open(gloveFile,'r') as f:
        model = {}
        for line in f:
            splitLine = line.split()
            word = splitLine[0]
            embedding = np.array([float(val) for val in splitLine[1:]])
            model[word] = embedding
        print("Done.",len(model)," words loaded!")
        return model

if __name__ == "__main__":

    glove300_encodings = loadGloveModel(gloveFile)
    matrix = np.zeros((len(vocab._word_to_id) , emb_dim), dtype=np.float32)

    print("Glove matrices loaded, producing embedding matrix")

    for element in vocab._word_to_id:
        if element in glove300_encodings:
            matrix[vocab._word_to_id[element]] = glove300_encodings[element] + matrix[vocab._word_to_id[element]]

    print("Embedding matrices successfully created")

    with open(save_file, "wb") as file:
        pickle.dump(matrix, file)

    print("Embedding matrices successfully saved using pickle")


import os
import stat
import unittest
from pathlib import PurePath
from configparser import MissingSectionHeaderError

from src.app_config import ConfigHandler
from src.app_config import AccessConfigError
from src.app_config import BackupConfigError
from src.app_config import RebuildConfigError
from src.app_config import NameConfigError
from src.app_config import CopyConfigError

class TestConfigHandler(unittest.TestCase):
    @classmethod
    def setUpClass(cls) -> None:
        pass

    def setUp(self) -> None:
        self.example_config = 'example_config.ini'
        self.config_name = 'config.ini'
        self.fixtures = 'tests/fixtures'
        self.test = ConfigHandler()

    def tearDown(self) -> None:
        del self.example_config
        del self.config_name
        del self.fixtures
        del self.test

    def test_set_configparser(self):
        self.test._set_configparser(name=self.config_name,
                                    directory=None)
        result = self.test._config.sections()
        self.assertEqual(result[0], "MQTT")
        self.assertEqual(result[1], "CORE")
        self.assertEqual(result[2], "LOG")

    def test__str__(self):
        self.assertRegex(str(self.test),
                         'Config:')

    def test__repr__(self):
        result = repr(self.test)
        self.assertRegex(result,
                         "ConfigHandler")
        self.assertRegex(result,
                         self.config_name)

    def test_copy_string(self):
        source = self.test._search_config(name=self.example_config,
                                          directory=None)
        destination = self.test._search_config(name=self.config_name,
                                               directory=self.fixtures)
        result = self.test._copy_string(src=source,
                                        dst=destination)
        self.assertEqual(result, "Copied string success")

    def test_wrong_copy_string(self):
        source = self.test._search_config(name=self.example_config,
                                          directory=None)
        destination = self.test._search_config(name=self.config_name,
                                               directory=self.fixtures)
        # Change mode to not read, not write, not execute to all users
        os.chmod(destination, stat.S_ENFMT)
        self.assertRaises(CopyConfigError,
                          self.test._copy_string,
                          src=source,
                          dst=destination)
        os.chmod(destination, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)

    def test_search_config(self):
        full_path = self.test._search_config(self.config_name,
                                             None)
        result = PurePath(full_path)
        self.assertIsInstance(result, (str, PurePath))
        self.assertEqual(result.parts[-1], self.config_name)

    def test_wrong_search_config(self):
        self.assertRaises(NameConfigError,
                          self.test._set_configparser,
                          name=self.example_config,
                          directory=self.fixtures)

    def test_backup_file(self):
        result = self.test._backup_config_file()
        self.assertIsInstance(result, tuple)
        self.assertIsInstance(result[0], str)
        self.assertIsInstance(result[1], PurePath)
        self.assertRegex(result[0], "Backup config.ini to:")
        # delete created backup file
        os.remove(result[1])

    def test_wrong_backup_file(self):
        self.test.root_directory = self.fixtures
        destination = self.test._search_config(name=self.config_name,
                                               directory=self.fixtures)
        # Change mode to not read, not write, not execute to all users
        os.chmod(destination, stat.S_ENFMT)
        self.assertRaises(BackupConfigError,
                          self.test._backup_config_file)
        # Change mode to read, write, execute to all users
        os.chmod(destination, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)

    def test_validate(self):
        result = self.test._to_dict()
        self.assertIsInstance(result, dict)
        self.assertEqual(result['id'], "1234")
        self.assertEqual(result['type'], 'channel')
        self.assertEqual(result['name'], 'Канал')
        self.assertEqual(result['level'], '0')

    def test_rebuild_config(self):
        result = self.test._rebuild_config()
        self.assertEqual(result, 'Config rebuild success')

    def test_wrong_rebuild_config(self):
        destination = self.test._search_config(name=self.config_name,
                                               directory=self.fixtures)
        # Change mode to not read, not write, not execute to all users
        os.chmod(destination, stat.S_ENFMT)
        self.assertRaises(RebuildConfigError,
                          self.test._rebuild_config)
        # Change mode to read, write, execute to all users
        os.chmod(destination, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)

    def test_get_root_directory(self):
        directory = self.test.root_directory
        self.assertEqual(directory, None)

    def test_set_root_directory(self):
        self.test.root_directory = self.fixtures
        result = PurePath(self.test.file_path)
        self.assertEqual(result.parts[-1], self.config_name)
        self.assertEqual(result.parts[-2], 'fixtures')
        self.assertEqual(result.parts[-3], 'tests')

    def test_get_config_name(self):
        result = self.test.config_name
        self.assertEqual(result, self.config_name)

    def test_set_config_name(self):
        result = self.test.config_name = 'example_config.ini'
        self.assertEqual(result, 'example_config.ini')

    def test_read(self):
        result = self.test.read()
        self.assertEqual(result.id, "1234")
        self.assertEqual(result.type, 'channel')
        self.assertEqual(result.name, 'Канал')
        self.assertEqual(result.level, '0')

    def test_wrong_read(self):
        self.test.root_directory = self.fixtures

        def result(name):
            self.test.config_name = name
            return self.test.config_name

        self.assertRaises(MissingSectionHeaderError,
                          result,
                          'wrong_config.ini')

    def test_write_without_backup(self):
        self.test.root_directory = self.fixtures
        result = self.test.write(section='database',
                                 key="url",
                                 value="www.test.ru",
                                 backup=False)
        self.assertEqual(result[0], 'Completed')
        self.assertEqual(result[1], None)
        # rebuild config.ini to tests
        self.test._rebuild_config()

    def test_write_with_backup(self):
        self.test.root_directory = self.fixtures
        result = self.test.write(section='database',
                                 key="url",
                                 value="www.test.ru",
                                 backup=True)
        self.assertEqual(result[0], 'Completed')
        self.assertRegex(PurePath(result[1]).parts[-1],
                         'config.ini.BAK+')
        # rebuild config.ini to tests
        self.test._rebuild_config()
        # delete created backup file
        os.remove(result[1])

    def test_write_with_access_error(self):
        self.test.root_directory = self.fixtures
        self.test.config_name = self.config_name
        destination = self.test._search_config(name=self.config_name,
                                               directory=self.fixtures)
        # Change mode to not read, not write, not execute to all users
        os.chmod(destination, stat.S_ENFMT)
        self.assertRaises(AccessConfigError,
                          self.test.write,
                          section='database',
                          key="url",
                          value="www.test.ru",
                          backup=False)
        # Change mode to read, write, execute to all users
        os.chmod(destination, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
        # rebuild config.ini to tests
        self.test._rebuild_config()


import time
from sklearn.decomposition import PCA
import leafly.search_for_words as sfw
import leafly.nlp_funcs as nl
import leafly.data_preprocess as dp
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
import plotly.graph_objs as go
import plotly.plotly as py
from plotly.graph_objs import XAxis, YAxis, ZAxis, Layout, Scene
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
from sklearn.metrics import silhouette_score

df, prod_review_df = sfw.load_data()

tfvect, vect_words, review_vects = nl.lemmatize_tfidf(prod_review_df, max_features=1000, ngram_range=(1, 2))
pca_r= PCA(n_components=200)
review_pca = pca_r.fit_transform(review_vects)

num_kmeans = 15
kmeanses = []
scores = []
sil_scores = []
start = time.time()
for i in range(2, num_kmeans):
    km = KMeans(n_clusters=i, n_jobs=-1, random_state=42)
    kmeanses.append(km)
    km.fit(review_pca)
    scores.append(-km.score(review_pca)) # withi-cluster sum of squares
    labels = km.labels_
    sil_scores.append(silhouette_score(review_vects, labels, metric='euclidean'))

endTime = time.time()
print('took', endTime - start, 'seconds')

data = go.Scatter(
        x=list(range(2, num_kmeans)),
        y=scores,
        mode='markers',
        marker=dict(
            size=12,
            line=dict(
                color='rgba(217, 217, 217, 0.14)',
                width=0.5
            ),
            opacity=0.8
        )
    )

layout = Layout(
    title='kmeans plot strains',
    scene=Scene(
        xaxis=XAxis(title='number of KMeans clusters'),
        yaxis=YAxis(title='sum of squared distances from datapoints to cluster centers')
    )
)

py.plot([data], layout=layout, filename='kmeans-scatter', world_readable=True)

# look at silhouette_score
sil_scores = []
for km in kmeanses:
    labels = km.labels_
    sil_scores.append(silhouette_score(review_vects, labels, metric='euclidean'))

# shit...looks like 2 clusters is best, with 200 or full tfidf
plt.scatter(list(range(2, num_kmeans)), sil_scores)
plt.show()

# adapted from plotly and SO
# http://stackoverflow.com/questions/26941135/show-legend-and-label-axes-in-plotly-3d-scatter-plots
cur_km = kmeanses[1]
traces = []
for i in range(3):
    x, y, z = review_pca[cur_km.labels_ == i, 0], review_pca[cur_km.labels_ == i, 1], review_pca[cur_km.labels_ == i, 3]
    traces.append(go.Scatter3d(
        x=x,
        y=y,
        z=z,
        mode='markers',
        marker=dict(
            size=6,
#             line=dict(
#                 color='rgba(217, 217, 217, 0.14)',
#                 width=0.2
#             ),
            opacity=0.5
        ),
        name='cluster ' + str(i)
    ))

layout = Layout(
    title='3 KMeans clusters of strains',
    scene=Scene(
        xaxis=XAxis(title='PCA Dimension 1'),
        yaxis=YAxis(title='PCA Dimension 2'),
        zaxis=ZAxis(title='PCA Dimension 3')
    )
)

fig = go.Figure(data=traces, layout=layout)
py.plot(fig, filename='3 KMeans clusters of strains', world_readable=True)

# lets find top grams in each group
vect_words = np.array(tfvect.get_feature_names())
groups = []
for i in range(3):
    names = prod_review_df[cur_km.labels_ == i]['product']
    groups.append(prod_review_df[cur_km.labels_ == i])
    words = review_vects[cur_km.labels_ == i, :]
    avg_vects = words.mean(axis=0)
    idx = np.argsort(avg_vects)[::-1]
    print('group', i)
    print(list(zip(avg_vects[idx][:10], vect_words[idx][:10])))
    print('')
    print('')

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

num_kmeans = 15
kmeanses = []
scores = []
start = time.time()
for i in range(2, num_kmeans):
    km = KMeans(n_clusters=i, n_jobs=-1, random_state=42)
    kmeanses.append(km)
    km.fit(review_vects)
    scores.append(-km.score(review_vects)) # withi-cluster sum of squares

endTime = time.time()
print('took', endTime - start, 'seconds')

data = go.Scatter(
        x=list(range(2, num_kmeans)),
        y=scores,
        mode='markers',
        marker=dict(
            size=12,
            line=dict(
                color='rgba(217, 217, 217, 0.14)',
                width=0.5
            ),
            opacity=0.8
        )
    )

layout = Layout(
    title='kmeans plot strains',
    scene=Scene(
        xaxis=XAxis(title='number of KMeans clusters'),
        yaxis=YAxis(title='sum of squared distances from datapoints to cluster centers')
    )
)

py.plot([data], layout=layout, filename='kmeans-scatter', world_readable=True)

# look at silhouette_score
sil_scores = []
for km in kmeanses:
    labels = km.labels_
    sil_scores.append(silhouette_score(review_vects, labels, metric='euclidean'))

# shit...looks like 2 clusters is best, with 200 or full tfidf
plt.scatter(list(range(2, num_kmeans)), sil_scores)
plt.show()

# lets look at the clusters
# adapted from plotly and SO
# http://stackoverflow.com/questions/26941135/show-legend-and-label-axes-in-plotly-3d-scatter-plots
cur_km = kmeanses[8]
traces = []
for i in range(10):
    x, y, z = bio_PCA_sc[cur_km.labels_ == i, 0], bio_PCA_sc[cur_km.labels_ == i, 1], bio_PCA_sc[cur_km.labels_ == i, 3]
    traces.append(go.Scatter3d(
        x=x,
        y=y,
        z=z,
        mode='markers',
        marker=dict(
            size=6,
#             line=dict(
#                 color='rgba(217, 217, 217, 0.14)',
#                 width=0.2
#             ),
            opacity=0.5
        ),
        name='cluster ' + str(i)
    ))

layout = Layout(
    title='10 KMeans clusters of MBMS raw biomass',
    scene=Scene(
        xaxis=XAxis(title='PCA Dimension 1'),
        yaxis=YAxis(title='PCA Dimension 2'),
        zaxis=ZAxis(title='PCA Dimension 3')
    )
)

fig = go.Figure(data=traces, layout=layout)
py.plot(fig, filename='2 kmeans clusters of strains', world_readable=True)

km2 = kmeanses[0]
labels = km2.labels_
group0 = prod_review_df[labels == 0]
group1 = prod_review_df[labels == 1]
tfvect0, vect_words0, review_vects0 = nl.lemmatize_tfidf(group0, max_features=200)

# lets try clustering within a cluster and see how it looks
num_kmeans = 50
kmeanses0 = []
scores0 = []
start = time.time()
for i in range(2, num_kmeans):
    km = KMeans(n_clusters=i, n_jobs=-1, random_state=42)
    kmeanses0.append(km)
    km.fit(review_vects0)
    scores0.append(-km.score(review_vects)) # withi-cluster sum of squares

endTime = time.time()
print('took', endTime - start, 'seconds')

# look at silhouette_score
sil_scores0 = []
for km in kmeanses0:
    labels = km.labels_
    sil_scores0.append(silhouette_score(review_vects0, labels, metric='euclidean'))

# 15 clusters looks best
f = plt.figure()
ax = f.add_subplot(1, 1, 1)
ax.scatter(list(range(2, num_kmeans)), sil_scores0)
ax.set_title('group0 clusters')
plt.show()

# now the second cluster
tfvect1, vect_words1, review_vects1 = nl.lemmatize_tfidf(group1, max_features=200)

num_kmeans = 50
kmeanses1 = []
scores1 = []
start = time.time()
for i in range(2, num_kmeans):
    km = KMeans(n_clusters=i, n_jobs=-1, random_state=42)
    kmeanses1.append(km)
    km.fit(review_vects1)
    scores1.append(-km.score(review_vects)) # withi-cluster sum of squares

endTime = time.time()
print('took', endTime - start, 'seconds')

# look at silhouette_score
sil_scores1 = []
for km in kmeanses1:
    labels = km.labels_
    sil_scores1.append(silhouette_score(review_vects1, labels, metric='euclidean'))

# 7 clusters looks best for this one
f = plt.figure()
ax = f.add_subplot(1, 1, 1)
ax.scatter(list(range(2, num_kmeans)), sil_scores1)
ax.set_title('group1 clusters')
plt.show()


from psycopg2._psycopg import connection

from entity.item import Item

class ItemRepository:
    db: connection

    def __init__(self, db: connection):
        self.db = db

    def create_item(self, item: Item):
        query = "INSERT INTO item (id, value) VALUES (%s, %s)"
        curr = self.db.cursor()

        try:
            curr.execute(query=query, vars=(item.id, item.value))
            self.db.commit()
        except Exception as err:
            self.db.rollback()
            raise err

    def get_item_by_id(self, id):
        query = "SELECT id, value FROM item WHERE id = %s"
        curr = self.db.cursor()

        try:
            curr.execute(query=query, vars=(id))
            data = curr.fetchone()
            return Item(data[0], data[1])
        except Exception as err:
            self.db.rollback()
            raise err


# -*- coding: utf-8 -*-
import simplejson, urllib
import time
import datetime
import os
import pickle

def request_date(date):
	day_by_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
	old_date = [int(i) for i in date.split('-')]
	now_date = datetime.datetime.now()
	now_date = [now_date.year, now_date.month, now_date.day]
	if now_date[0] == old_date[0]:
		day_distance = sum(day_by_month[(old_date[1] - 1):(now_date[1] - 1)]) - old_date[2] + now_date[2]
	else:
		day_distance = sum(day_by_month[(old_date[1] - 1):12]) - old_date[2]
		day_distance += sum(day_by_month[0:(now_date[1] - 1)]) + now_date[2]
	now_date[2] = now_date[2] - day_distance % 7
	if now_date[2] < 0:
		now_date[2] += day_by_month[(now_date[1] - 1)]
		now_date[1] -= 1
	if now_date[1] == 0:
		now_date[1] = 12
		now_date[0] -= 1
	connect_1 = '-'
	connect_2 = '-'
	if now_date[1] < 10:
		connect_1 = '-0'
	if now_date[2] < 10:
		connect_2 = '-0'
	new_date = str(now_date[0]) + connect_1 + str(now_date[1]) + connect_2 + str(now_date[2])
	return new_date

def rail_station():
	# detail refer this link: http://ptx.transportdata.tw/MOTC/Swagger/#!/CityBusApi/CityBusApi_StopOfRoute
	url = "http://ptx.transportdata.tw/MOTC/v2/Rail/TRA/Station?$format=JSON"
	result = simplejson.load(urllib.urlopen(url))
	# result= simplejson.load(requests.get(url).text)
	# stations: stations[station_id][station_name and position]
	stations = {}
	for row in result:
		station_id = row["StationID"]
		if station_id == '4102':
			continue
		station_name = row["StationName"]["En"]
		lon = float(row["StationPosition"]["PositionLon"])
		lat = float(row["StationPosition"]["PositionLat"])
		stations[station_id] = {}
		stations[station_id]['name'] = station_name
		stations[station_id]['position'] = (lon, lat)
	return stations

def HSR_station():
	# detail refer this link: http://ptx.transportdata.tw/MOTC/Swagger/#!/CityBusApi/CityBusApi_StopOfRoute
	url = "http://ptx.transportdata.tw/MOTC/v2/Rail/THSR/Station?$format=JSON"
	result = simplejson.load(urllib.urlopen(url))
	# stations: stations[station_id][station_name and position]
	stations = {}
	for row in result:
		station_id = row["StationID"]
		station_name = row["StationName"]["En"]
		lon = float(row["StationPosition"]["PositionLon"])
		lat = float(row["StationPosition"]["PositionLat"])
		stations[station_id] = {}
		stations[station_id]['name'] = station_name
		stations[station_id]['position'] = (lon, lat)

	return stations

def datetime2unixtime(time_info, date_info):
	unix_time = int(time.mktime(time.strptime('%s %s:00' % (date_info, time_info), '%Y-%m-%d %H:%M:%S')))
	return unix_time

def HSR_travel_time(date):
	# date = YY-MM-DD
	date = request_date(date)
	station_url = "http://ptx.transportdata.tw/MOTC/v2/Rail/THSR/Station?$format=JSON"
	result = simplejson.load(urllib.urlopen(station_url))
	all_stations = set()
	for row in result:
		all_stations.add(row["StationID"])

	travel_time = {}
	travel_during_time = {}
	for dep_station in all_stations:
		travel_time[dep_station] = {}
		travel_during_time[dep_station] = {}
		for arr_station in all_stations:
			if dep_station != arr_station:
				travel_time[dep_station][arr_station] = []
				travel_during_time[dep_station][arr_station] = 0
				timetable_url = "http://ptx.transportdata.tw/MOTC/v2/Rail/THSR/DailyTimetable/OD/%s/to/%s/%s?$format=JSON" % (
				dep_station, arr_station, date)
				result = simplejson.load(urllib.urlopen(timetable_url))
				for row in result:
					train_no = row["DailyTrainInfo"]["TrainNo"]
					depart_time = datetime2unixtime(row["OriginStopTime"]["DepartureTime"], date)
					arrival_time = datetime2unixtime(row["DestinationStopTime"]["ArrivalTime"], date)
					travel_time[dep_station][arr_station].append([train_no, depart_time, arrival_time])
					travel_during_time[dep_station][arr_station] = int(arrival_time) - int(depart_time)
	return (travel_time, travel_during_time)

def rail_travel_time(date):
	# date = YY-MM-DD
	date = request_date(date)
	station_url = "http://ptx.transportdata.tw/MOTC/v2/Rail/TRA/Station?$format=JSON"
	result = simplejson.load(urllib.urlopen(station_url))
	all_stations = set()
	for row in result:
		all_stations.add(row["StationID"])

	travel_time = {}
	travel_during_time = {}
	for dep_station in all_stations:
		travel_time[dep_station] = {}
		travel_during_time[dep_station] = {}
		for arr_station in all_stations:
			if dep_station != arr_station:
				travel_time[dep_station][arr_station] = []
				travel_during_time[dep_station][arr_station] = 0
				timetable_url = "http://ptx.transportdata.tw/MOTC/v2/Rail/TRA/DailyTimetable/OD/%s/to/%s/%s?$format=JSON" % (
					dep_station, arr_station, date)
				result = simplejson.load(urllib.urlopen(timetable_url))
				for row in result:
					train_no = row["DailyTrainInfo"]["TrainNo"]
					depart_time = datetime2unixtime(row["OriginStopTime"]["DepartureTime"], date)
					arrival_time = datetime2unixtime(row["DestinationStopTime"]["ArrivalTime"], date)
					travel_time[dep_station][arr_station].append([train_no, depart_time, arrival_time])
					travel_during_time[dep_station][arr_station] = int(arrival_time) - int(depart_time)
	return (travel_time, travel_during_time)

def bus_route(city):
	# detail refer this link: http://ptx.transportdata.tw/MOTC/Swagger/#!/CityBusApi/CityBusApi_StopOfRoute
	url = "http://ptx.transportdata.tw/MOTC/v2/Bus/StopOfRoute/City/%s?$format=JSON"%(city)
	result= simplejson.load(urllib.urlopen(url))
	route_dict = {}
	for row in result:
		name = row['RouteUID']
		direction = row['Direction']
		sequence = []
		for stop in row['Stops']:
			sequence.append([stop['StopSequence'],stop['StopUID'],stop['StopPosition']['PositionLon'],stop['StopPosition']['PositionLat']])
		route_dict[name+"_"+str(direction)] = sequence

	return route_dict

def bus_SpeedDis(city,update_frequency=5):
	date = datetime.datetime.now().strftime('%Y-%m-%d')
	bus = {}
	pre = -1
	while 1:

		if (datetime.datetime.now().strftime('%Y-%m-%d') != date):
			speed = SpeedDistribution(bus)
			pickle.dump(speed,open("%s_SpeedDis_%s.pkl"%(city,date),"wb"))
			bus = {}
			pre = int(datetime.datetime.now().strftime('%H'))
			date = datetime.datetime.now().strftime('%Y-%m-%d')

		try:
			url = "http://ptx.transportdata.tw/MOTC/v2/Bus/RealTimeByFrequency/City/%s?$format=JSON"%(city)
			result= simplejson.load(urllib.urlopen(url))
		except:
			continue

		for row in result:
			try:
				routeID = row['RouteUID']
				direction = row['Direction']
				platenum = row['PlateNumb']
				lat,lon = row['BusPosition']["PositionLat"],row['BusPosition']["PositionLon"]
				t = row["GPSTime"]

				if str(routeID) + "_" + str(direction) not in bus.keys():
					bus[str(routeID) + "_" + str(direction)] = {}

				if platenum not in bus[str(routeID) + "_" + str(direction)].keys():
					bus[str(routeID) + "_" + str(direction)][platenum] = []
				bus[str(routeID) + "_" + str(direction)][platenum].append( [lat,lon,t] )
			except:
				continue

		time.sleep(60*update_frequency)

def SpeedDistribution(bus_real_record):
	SpeedDis = {}
	for bus_name in bus_real_record.keys():
		#print "Bus Route:",bus_name
		count = [0]*24
		total = [0]*24
		for bus_num in bus_real_record[bus_name].keys():
			#print "Car Number:",bus_num
			for row in bus_real_record[bus_name][bus_num]:
				hour = int(row[3].split("T")[1].split(":")[0])
				total[hour] = total[hour] + row[2]
				count[hour] = count[hour] + 1
		average = [0] * 24
		for i in range(0,24,1):
			if (total[i] != 0.0) & (count[i] != 0):
				average[i] = total[i]/count[i]

		SpeedDis[bus_name] = average
	return SpeedDis

def TimeTable(schedule,time_threshold):
	date_schedule = {}

	for bus_num in schedule.keys():

		if bus_num not in date_schedule.keys():
			date_schedule[bus_num] = {}

		for stop in schedule[bus_num].keys():

			if stop not in date_schedule[bus_num].keys():
				date_schedule[bus_num][stop] = []

			if len(schedule[bus_num][stop]) > 0:
				pre = schedule[bus_num][stop][0]
				for time in schedule[bus_num][stop][1:]:
					if abs(time-pre) > time_threshold*60:
						date_schedule[bus_num][stop].append(pre)
					pre = time
				date_schedule[bus_num][stop].append(schedule[bus_num][stop][-1])

	return date_schedule

def bus_schedule(city,time_threshold=5,update_frequency=5):
	date = datetime.datetime.now().strftime('%Y-%m-%d')
	pre = -1
	schedule = {}
	while 1:
		try:
			url = "http://ptx.transportdata.tw/MOTC/v2/Bus/EstimatedTimeOfArrival/City/%s?$format=JSON"%(city)
			result= simplejson.load(urllib.urlopen(url))
			unix_time = int(time.mktime(time.strptime(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S')))
		except:
			continue

		if (datetime.datetime.now().strftime('%Y-%m-%d') != date):
			schedule = TimeTable(schedule,time_threshold)
			pickle.dump(schedule,open("schedule_%s_%s.pkl"%(city,date),"wb"))
			schedule = {}
			pre = int(datetime.datetime.now().strftime('%H'))
			date = datetime.datetime.now().strftime('%Y-%m-%d')

		for row in result:
			try:
				stopUID = row['StopUID']
				RouteID = row['RouteUID']
				direction = row['Direction']

				if str(RouteID)+"_"+str(direction)  not in schedule.keys():
						schedule[str(RouteID)+"_"+str(direction)] = {}

				if stopUID not in schedule[str(RouteID)+"_"+str(direction)].keys():
						schedule[str(RouteID)+"_"+str(direction)][stopUID] = []

				EsTime= int(row['EstimateTime'])
				arr_time = unix_time + EsTime
				schedule[str(RouteID)+"_"+str(direction)][stopUID].append(arr_time)
			except:
				continue
		time.sleep(update_frequency*60)


from datetime import datetime as dt
def valDate(input):
    try:
        dateobject=dt.strptime(input,'%d/%m/%y')
        return True
    except ValueError:
        return False
date=input("Enter you birthday date->dd/mm/yy:")
a=valDate(date)
if a==True:
    print("Happy birthday...")
else:
    print("Best wishes for your birthday in advance..")


#!/usr/bin/env python3
import json
import random
import traceback

import eccodes
import requests

from ecmwf.opendata import Client

client = Client()

done = set()

with open("done.txt") as f:
    for url in f:
        url = url.rstrip()
        done.add(url)

ok = open("done.txt", "a")
fail = open("fail.txt", "a")

with open("index.txt") as f:
    for url in f:
        url = url.rstrip()
        if url in done:
            print(url, "DONE")
            continue
        print(url)
        # if "mmsf" in url:
        #     continue
        r = requests.get(url)
        r.raise_for_status()

        try:
            lines = []
            for line in r.text.splitlines():
                line = json.loads(line)
                lines.append(line)

            random.shuffle(lines)

            for i, line in enumerate(lines):
                if i > 20:
                    break
                line["target"] = "data"
                client.retrieve(line)
                with open("data", "rb") as g:
                    h = eccodes.codes_new_from_file(g, eccodes.CODES_PRODUCT_GRIB)
                    try:
                        for k, v in line.items():
                            if k in ["target", "_length", "_offset"]:
                                continue

                            if k == "param":
                                k = "shortName"
                            w = eccodes.codes_get_string(h, k)
                            assert v == w, (v, w)
                    finally:
                        eccodes.codes_release(h)

            print(url, file=ok)
        except Exception as e:
            print(traceback.format_exc())
            print(url, e, file=fail)


import jax
from typing import Any, Callable, Sequence, Optional
from jax import lax, random, numpy as jnp
import flax
from flax.core import freeze, unfreeze
from flax import linen as nn

# We create one dense layer instance (taking 'features' parameter as input)
model = nn.Dense(features=5)
key1, key2 = random.split(random.PRNGKey(0))
x = random.normal(key1, (10,)) # Dummy input
params = model.init(key2, x) # Initialization call
jax.tree_map(lambda x: x.shape, params) # Checking output shapes
model.apply(params, x)

# Set problem dimensions.
n_samples = 20
x_dim = 10
y_dim = 5

# Generate random ground truth W and b.
key = random.PRNGKey(0)
k1, k2 = random.split(key)
W = random.normal(k1, (x_dim, y_dim))
b = random.normal(k2, (y_dim,))
# Store the parameters in a pytree.
true_params = freeze({'params': {'bias': b, 'kernel': W}})

# Generate samples with additional noise.
key_sample, key_noise = random.split(k1)
x_samples = random.normal(key_sample, (n_samples, x_dim))
y_samples = jnp.dot(x_samples, W) + b + 0.1 * random.normal(key_noise,(n_samples, y_dim))
print('x shape:', x_samples.shape, '; y shape:', y_samples.shape)

# Same as JAX version but using model.apply().
def mse(params, x_batched, y_batched):
  # Define the squared loss for a single pair (x,y)
  def squared_error(x, y):
    pred = model.apply(params, x)
    return jnp.inner(y-pred, y-pred) / 2.0
  # Vectorize the previous to compute the average of the loss on all samples.
  return jnp.mean(jax.vmap(squared_error)(x_batched,y_batched), axis=0)

learning_rate = 0.3  # Gradient step size.
print('Loss for "true" W,b: ', mse(true_params, x_samples, y_samples))
loss_grad_fn = jax.value_and_grad(mse)

@jax.jit
def update_params(params, learning_rate, grads):
  params = jax.tree_multimap(
      lambda p, g: p - learning_rate * g, params, grads)
  return params

for i in range(101):
  # Perform one gradient update.
  loss_val, grads = loss_grad_fn(params, x_samples, y_samples)
  params = update_params(params, learning_rate, grads)
  if i % 10 == 0:
    print(f'Loss step {i}: ', loss_val)

import optax
tx = optax.sgd(learning_rate=0.001)
opt_state = tx.init(params)
loss_grad_fn = jax.value_and_grad(mse)

for i in range(101):
  loss_val, grads = loss_grad_fn(params, x_samples, y_samples)
  updates, opt_state = tx.update(grads, opt_state)
  params = optax.apply_updates(params, updates)
  if i % 10 == 0:
    print('Loss step {}: '.format(i), loss_val)


from setuptools import setup, find_packages
import pathlib
import pkg_resources

version = "0.0.1"

with open('README.md', encoding='utf-8') as readme_file:
    readme = readme_file.read()

with pathlib.Path('requirements.txt').open() as requirements_txt:
    requirements = [
        str(requirement) for requirement in pkg_resources.parse_requirements(requirements_txt)
    ]

setup(name='stringmethod',
      version=version,
      description=(
          """Implementation of string method to compute the minimum energy path between
          two points in a multidimensional energy landscape."""
      ),
      long_description=readme,
      long_description_content_type='text/markdown',
      author='Akash Pallath',
      author_email='apallath@seas.upenn.edu',
      url='https://github.com/apallath/stringmethod',
      python_requires='>=3.6',
      install_requires=requirements,
      packages=find_packages())


#coding=UTF-8
# 用户如果没有登录，是不能访问，有关用户信息界面的
from  django.http.response import HttpResponseRedirect
import  re

from django.middleware.gzip import GZipMiddleware

class UserAuth():
    def __init__(self,get_response):
        self.get_response=get_response
    def __call__(self, request):
        path =  request.path
        if  re.match('^/user/.+',path):
            if request.session.get('user')==None:
                return HttpResponseRedirect('/user')
        response = self.get_response(request)

        return response

# 管理权限，普通的员工，经理，admin，


import json
import os

from transformers import AutoConfig
from utils import MODEL_CONFIG_DIR

model_name_list = [
    'Salesforce/codet5-small',          # XXXX
    'Salesforce/codet5-base',           # XXXX
    "mrm8488/bert2bert_shared-spanish-finetuned-summarization"   # XXXX
]

config_list = []
for model_id, model_name in enumerate(model_name_list):
    config = AutoConfig.from_pretrained(model_name)
    model_name = model_name.replace('/', '_')
    save_path = os.path.join(MODEL_CONFIG_DIR, model_name)
    config.save_pretrained(save_path)
    config_list.append(config)


"""Tests for :mod:`~.fastapi_app`
"""

import random
import unittest

from fastapi.testclient import TestClient
from fastapi_app import app
from fastapi_app.constants import (CLASSIC_FIZZBUZZ_PREFIX, N_ARGS_NAME,
                                   SEP_ARGS_NAME, STREAM_PATH)
from fizzbuzz_lib import classic_fizzbuzz_as_text

class TestFastAPIApp(unittest.TestCase):
    """Unittest class to test :mod:`~.fastapi_app`"""

    def setUp(self) -> None:
        self._seps = [' ', ', ', '; ']
        random.seed()

    def test_classic_fizzbuzz(self):
        """Tests classic FizzBuzz web services
        """
        with TestClient(app) as client:
            for i in range(100):
                with self.subTest(i=i):
                    sep = random.choice(self._seps)
                    stream = random.choice([STREAM_PATH, ''])
                    r = client.get(f'/{CLASSIC_FIZZBUZZ_PREFIX}/{stream}',
                                   params={N_ARGS_NAME: i, SEP_ARGS_NAME: sep})
                    self.assertEqual(r.status_code, 200)
                    self.assertEqual(r.text, classic_fizzbuzz_as_text(i, sep))


import openpyxl as xl
wb=xl.load_workbook("C://exceldata//openexcel.xlsx")
# sheet1=wb['Sheet1']
# sheet2=wb['Sheet2']
sheet3=wb['Sheet3']
# print(sheet1.max_row)
# print(sheet1.max_column)
# print(sheet1.cell(1,1).value)
# sheet1.cell(10,10).value="hcl"
# sheet2.cell(5,1).value='=sum(A1:A4)'
# wb.save("C://exceldata//openexcel.xlsx")
excel_data=[]
# for i in range(1,6):
#     excel_data.append(sheet1.cell(i,3).value)
# print(excel_data)
for i in range(1,4):
    first = []
    for j in range(1,5):
        first.append(sheet3.cell(j,i).value)
    excel_data.append(first)
print(excel_data)


#!/usr/bin/env python
# py2/3 compatibility
from __future__ import (absolute_import, division,
                        print_function, unicode_literals)
from future import standard_library
standard_library.install_aliases()
from builtins import *
import sys

import rospy
import math
import numpy as np
import tf
import geometry_msgs.msg
from geometry_msgs.msg import Quaternion
# from future.builtins import input
from tf.transformations import *
import os, rospkg
import yaml

if __name__ == '__main__':
    rospy.init_node('tf_recorder')
    set_transform = rospy.get_param('/calibrate_origin', default=False)
    rospack = rospkg.RosPack()
    listener = tf.TransformListener()
    br = tf.TransformBroadcaster()

    rate = rospy.Rate(150.0)

    while not rospy.is_shutdown():
        if set_transform:
            try:
                (trans,rot) = listener.lookupTransform('/kinect2_link', '/aruco_marker_frame', rospy.Time(0))
            except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException):
                continue
            print(trans, rot)
            key = input("Press Enter to continue..., f to finish")
            if key == "f":
                set_transform = False
                trans = np.asarray(trans) + [0, 0.02, 0]
                trans = trans + [0.161/2.0, 0.161/2.0, 0]
                q = quaternion_from_euler(-math.pi / 2.0, -math.pi / 2.0, 0)
                rot = quaternion_multiply(rot, q)
                print(trans, rot)
                data = {'ref_frame': '/kinect2_link', 'origin_trans': trans.tolist(), 'origin_rot': rot.tolist()}
                with open(os.path.join(rospack.get_path("ropi_tangible_surface"), "config", "desktop_config.yaml"), 'w') as outfile:
                    yaml.dump(data, outfile)
        else:
            with open(os.path.join(rospack.get_path("ropi_tangible_surface"), "config", "desktop_config.yaml")) as f:
                loaded_data = yaml.load(f)
            br.sendTransform(loaded_data.get('origin_trans'), loaded_data.get('origin_rot'), rospy.Time.now(),"table_origin", loaded_data.get('ref_frame'))

        rate.sleep()


import argparse
parser = argparse.ArgumentParser()
parser.add_argument('title')
parser.add_argument('author')
args = parser.parse_args()

import pygame, os
import yaml

pygame.init()
info = pygame.display.Info()
width, height = info.current_w, info.current_h
screen = pygame.display.set_mode((width, height), pygame.FULLSCREEN)

pygame.font.init()
myfont = pygame.font.SysFont('Comic Sans MS', 220)
title = myfont.render(args.title, False, pygame.Color('black'))
myfont = pygame.font.SysFont('Comic Sans MS', 120)
author = myfont.render(args.author, False, pygame.Color('black'))

for _ in range(8):
    screen.fill(pygame.Color('white'))
    screen.blit(title, (width//2 - title.get_width()//2, 300))
    if author.get_width() > width:
        screen.blit(author, (0, 600))
    else:
        screen.blit(author, (width//2 - author.get_width()//2, 600))
    pygame.display.flip()
    pygame.time.wait(1000)

pygame.quit()


from django import template
from myCookbook import views
from datetime import datetime

register = template.Library()

def newIngredients(ingredients):
    newIngredients =[]
    newIngredients = ingredients.split(":")
    newIngredients = views.grouper(3,newIngredients)

    return newIngredients

register.filter('newIngredients', newIngredients)

def newInstructions(instructions):
    print(instructions)
    newInstructions = instructions.replace(';',',').split(':')
    print(newInstructions)
    return newInstructions

register.filter('newInstructions',newInstructions)

def convertDate(value):
    return value.date()
register.filter('convertDate',convertDate)


import unittest

from mock import MagicMock, Mock

from robot.ai.state.charge_state import ChargeState
from robot.ai.state.move_to_charge_station_state import MoveToChargeStationState

class TestMoveToChargeStationState(unittest.TestCase):
    called_times = 0

    def one_false(self, *args):
        if self.called_times == 0:
            self.called_times += 1
            return False
        else:
            return True

    def setUp(self):
        self.controller = Mock()
        self.movement_controller = Mock()
        self.pathfinding = Mock()
        self.move_to_charge_station_state = MoveToChargeStationState(self.controller, self.movement_controller)
        self.pathfinding.calculate_dijkstra_path = MagicMock()
        self.treasure_position = Mock(Y=0)
        self.pathfinding.calculate_dijkstra_path.return_value = [[], self.treasure_position]
        self.controller.pathfinding = self.pathfinding
        self.controller.position = {"x": 0, "y": 0, "w": 0}

    def test_calls_next_state_at_the_end(self):
        self.move_to_charge_station_state.has_arrived = MagicMock()
        self.move_to_charge_station_state.has_arrived.return_value = True

        self.move_to_charge_station_state.handle()

        self.controller.set_state.assert_called_with(ChargeState)
        self.controller.activate.assert_called_with()

    def test_calls_move_if_not_arrived(self):
        self.movement_controller.is_at_position = self.one_false
        self.move_to_charge_station_state.handle()
        self.movement_controller.move.assert_called_once_with(self.move_to_charge_station_state.charge_station_position,
                                                              self.move_to_charge_station_state.waypoints,
                                                              self.controller.position)

    def test_should_face_top_wall(self):
        self.movement_controller.is_at_position = self.one_false
        self.move_to_charge_station_state.handle()
        self.movement_controller.face_wall.assert_called_once_with('top', self.controller.position)


import matplotlib.pyplot as plt
import numpy as np

plt.show(block = False)

def visualizeAgentEnvironment(data):
    #Create coordinates
    plt.clf()
    plt.axes().set_aspect('equal')
    x_coords = []
    y_coords = []
    step=0.5
    for row in range(len(data)):
        for col in range(len(data[row])):
            x_coords = np.append(x_coords,col+step)
            y_coords = np.append(y_coords,row+step)

    #Grass
    colors = [[0.,0.,0.]]
    area = (30 * 1.5)**2  # 0 to 15 point radii
    for row in reversed(range(len(data))):
        for col in range(len(data[row])):
            amount_of_grass = data[row][col][0]
            color = [0.915,0.915,0.915]
            if amount_of_grass>0.:
                color = [0.9-amount_of_grass,0.8,0.9-amount_of_grass]
            colors = np.vstack([colors,color])

    colors = np.delete(colors, 0, 0)

    plt.scatter(x_coords, y_coords, s=area, marker='s', c=colors, alpha=1)
    plt.xticks(np.arange(0, len(data[0])+1, 1.0))
    plt.yticks(np.arange(0, len(data[0])+1, 1.0))

    #Agents
    colors = [[0.,0.,0.,0.]]
    area = (30 * 0.5)**2  # 0 to 15 point radii
    k=0
    for row in reversed(range(len(data))):
        for col in range(len(data[row])):
            agent = data[row][col][1]
            fullness = data[row][col][2]
            current_color = [1.,1.,1.,0.] #no agent
            if agent==1: #fox
                current_color = [1.,0.,0.,1.]
            if agent==1 or agent==2:
                plt.gca().annotate(str(fullness),
                                xy=(x_coords[k]+0.1,y_coords[k]+0.2), xycoords='data')
            if agent==2: #rabbit
                current_color = [0.,0.,1.,1.]

            colors = np.vstack([colors,current_color])
            k+=1

    colors = np.delete(colors, 0, 0)

    plt.scatter(x_coords, y_coords, s=area, marker='s', c=colors)
    plt.xticks(np.arange(0, len(data[0])+1, 1.0))
    plt.yticks(np.arange(0, len(data[0])+1, 1.0))

    plt.show(block = False)
    plt.pause(0.001)

if __name__ == "__main__":
    data  = [[[0.1,0.,5. ],[0.9,0.,5.],[0.,2.,5.],[0.6,0.,5.],[0.9,0.,5.]],
           [[0.2,0.,5. ],[0.7,0.,5.],[0.,0.,5.],[0. ,0.,5.],[0.9,0.,5.]],
           [[0.7,1.,5. ],[0. ,0.,5.],[0.,2.,5.],[0.3,0.,5.],[0. ,1.,5.]],
           [[0.9,1.,5. ],[0.5,1.,5.],[0.,0.,5.],[0.4,0.,5.],[0.2,0.,5.]],
           [[0.9,0.,5. ],[0.8,0.,5.],[0.,0.,5.],[0.9,0.,5.],[0.5,0.,5.]]]
    visualizeAgentEnvironment(data)


import io
import folium
import tempfile

from folium.features import DivIcon
from PIL import Image
from shapely.geometry import Point, mapping, shape

with tempfile.TemporaryDirectory(dir="/tmp") as tempdir:
    map_path = "{}/map.html".format(tempdir)
    image_path = "{}/image.png".format(tempdir)

    # Create map
    map = folium.Map([-23.682567,-46.666548], zoom_start=14, tiles="cartodbpositron")

    # Marker my location
    folium.Marker([-23.682567,-46.666548] ).add_to(map)

    focos = [
      [ -46.636548, -23.682567 ],
      [ -46.666548, -23.712567 ],
      [ -46.696548, -23.682567 ],
      [ -46.666548, -23.652567 ],
    ]

    for f in focos:
        folium.Marker(
            location=[f[1], f[0]],
            icon=folium.Icon(color="red",icon="fire"),
        ).add_to(map)

        folium.map.Marker([f[1], f[0]],
            icon=DivIcon(
                icon_size=(150,36),
                icon_anchor=(0,0),
                html='
%s
' % '2021-07-20T16:24:00+00:00',
            )
        ).add_to(map)

    # Buffer Location area
    patch = Point(-46.666548, -23.682567).buffer(0.02)
    geojson = mapping(patch)
    folium.GeoJson(geojson).add_to(map)

    # Save map
    map.save("map_path.html")

    # Convert map to PNG
    img_data = map._to_png(5)
    img = Image.open(io.BytesIO(img_data))
    img.save("image.png")


import unittest
import sqlite3
from project_code import database_connection
from project_code.error_class import NotAlpha, NotAlphaTwo, Yesno, Dateformat

class MyTestCase(unittest.TestCase):

    def test_createcontact(self):
        conn = sqlite3.connect('Conactdatabase.db')
        contact = ('01/02/19', 'Yes', 'Email', 'Carrie', '', 'Spoke with Carrie about burden study', 'Kelly')
        expected = "<class 'sqlite3.DatabaseError'>"
        actual = database_connection.create_contact(conn, contact)
        self.assertEqual(actual, expected)

    def test_invalid_staff(self):
        with self.assertRaises(Exception):
            NotAlphaTwo(None, "Your entry for person contacted must be alphabetic")

    def test_invalid_client(self):
        with self.assertRaises(Exception):
            NotAlpha('1', '01/01/19', 'Yes', 'Email', 123, 'EID12345', 'Hi', 'Kelly')

    def test_invalid_contactmade(self):
        with self.assertRaises(Exception):
            Yesno('01/01/19', '2', 'Email', 'Carrie', 'EID12345', 'Hi', 'Kelly')

    def test_invalid_date(self):
        with self.assertRaises(Exception):
            Dateformat('01/01/2019', 'Yes', 'Email', 'Carrie', 'EID12345', 'Hi', 'Kelly')

if __name__ == '__main__':
    unittest.main()


import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.animation as animation

x = np.linspace(-10,10,100)
y = np.linspace(-10,10,100)
z = np.array([[0 for i in range(100)]for j in range(100)])
for i in range(x.shape[0]):
    for j in range(y.shape[0]):
        z[i,j] = x[i]*x[i] + y[j]*y[j]

figure = plt.figure()
ax = Axes3D(figure)
X,Y = np.meshgrid(x,y)
ax.plot_surface(X,Y,z,rstride=1,cstride=1,cmap='rainbow')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.show()

f1= plt.figure()
plt.xlim(-10,10)
plt.ylim(-10,10)
levs = np.logspace(0,3,30)
Contour = plt.contour(X,Y,z)
plt.clabel(Contour,fontsize=10)

iteration = 1500
x_ini = -7.86
y_ini = 8.63
alpha = 0.001
#plt.scatter(x_ini,y_ini,marker='x',c='red',linewidths=3)
x = x_ini
y = y_ini

xx = []
yy = []
xx.append(x_ini)
yy.append(y_ini)
for i in range(iteration):
    x = x - alpha * 2 * x
    y = y - alpha * 2 * y
    if i%100 == 0:
        xx.append(x)
        yy.append(y)

xx = np.array(xx)
yy = np.array(yy)

def update_points(num):
    point_ani.set_data(xx[num], yy[num])
    text_pt.set_position((xx[num], yy[num]))
    text_pt.set_text("x=%.3f, y=%.3f"%(xx[num], yy[num]))
    return point_ani,text_pt

point_ani, = plt.plot(xx[0], yy[0], "r+")

text_pt = plt.text(0,0,'',fontsize=10)
# 开始制作动画
ani = animation.FuncAnimation(f1, update_points, np.arange(xx.shape[0]), interval=300, blit=True)

plt.xlabel('x')
plt.ylabel('y')
plt.title('contour and the tendency')
ani.save(r'./test.gif', writer='pillow', fps=5)

plt.show()


from pathlib import Path
import os
# import imageio
import matplotlib.pyplot as plt
from matplotlib.pyplot import cla
import networkx as nx
import signal
import abc
from multiprocessing import Pool,Manager,Process
import numpy as np

def autoPlot(data,y=None,continues=False,seed=2020,area=None,svfile=None,axis='on',dpi=80,size=10,alpha=0.7):
    plt.figure(figsize=(4, 4),dpi=dpi)
    if type(y)==np.ndarray:
        y=y.reshape(-1)

    if y is None:
        ax = plt.subplot(111)
        ax.scatter(data[:,0], data[:,1],s=size,alpha=alpha)
        if axis=='off':
            for key, spine in ax.spines.items(): # 取消边框
                spine.set_visible(False)
            plt.axis('off')
        if svfile is not None:
            plt.savefig(svfile,bbox_inches = 'tight',pad_inches = 0.02)
        plt.show()
        return

    if continues:
        if data.shape[1]==2:
            ax = plt.subplot(111)
            ax.scatter(data[:,0], data[:,1],c=y,s=size,alpha=alpha)

        if data.shape[1]==3:
            ax = plt.subplot(111, projection='3d')
            ax.scatter(data[:,0], data[:,1], data[:,2],c=y,s=size,alpha=alpha)

        for key, spine in ax.spines.items(): # 取消边框
            spine.set_visible(False)
        plt.axis('equal')
        if axis=='off':
            plt.axis('off')
        if svfile is not None:
            plt.savefig(svfile,bbox_inches = 'tight',pad_inches = 0.02)
        plt.show()

    if not continues:
        colors=['C{}'.format(i) for i in range(max(y)+1)]
        random.seed(seed)
        random.shuffle(colors)
        colors={i:colors[i] for i in range(max(y)+1)}
        colors[-1]='gray'
        colors[-2]='red'
        hashColor=lambda y:[colors[one] for one in y]
        noise_mask=(y==-1)

        if data.shape[1]==2:
            ax = plt.subplot(111)
            if area is None:
                ax.scatter(data[~noise_mask][:,0], data[~noise_mask][:,1],c=hashColor(y[~noise_mask]),s=size,alpha=alpha)
                ax.scatter(data[noise_mask][:,0], data[noise_mask][:,1],c=hashColor(y[noise_mask]),alpha=0.1,s=size)
            else:
                ax.scatter(data[~noise_mask][:,0], data[~noise_mask][:,1],c=hashColor(y[~noise_mask]), s=25 * area[~noise_mask].astype(np.float64) ** 3, alpha=0.5)
                ax.scatter(data[noise_mask][:,0], data[noise_mask][:,1],c=hashColor(y[noise_mask]), s=area[noise_mask].astype(np.float64), alpha=0.1)
            plt.axis('equal')

        if data.shape[1]==3:
            ax = plt.subplot(111, projection='3d')
            ax.scatter(data[~noise_mask][:,0], data[~noise_mask][:,1], data[~noise_mask][:,2],c=hashColor(y[~noise_mask]),s=size)
            ax.scatter(data[noise_mask][:,0], data[noise_mask][:,1], data[noise_mask][:,2],c=hashColor(y[noise_mask]),alpha=0.1,s=size)

        if axis=='off':
            # plt.axis('off')
            plt.xticks([])
            plt.yticks([])
            if data.shape[1]==3:
                ax.set_zticks([])

            for key, spine in ax.spines.items(): # 取消边框
                spine.set_visible(False)

        if svfile is not None:
            plt.savefig(svfile,bbox_inches = 'tight',pad_inches = 0.02)
        plt.show()

# def autoPlot(data,y=None,continues=False,seed=2020,area=None):
#     plt.figure(figsize=(4, 4))
#     if type(y)==np.ndarray:
#         y=y.reshape(-1)

#     if y is None:
#         ax = plt.subplot(111)
#         ax.scatter(data[:,0], data[:,1])
#         plt.axis('equal')
#         plt.show()
#         return

#     if continues:
#         if data.shape[1]==2:
#             ax = plt.subplot(111)
#             ax.scatter(data[:,0], data[:,1],c=y)

#         if data.shape[1]==3:
#             ax = plt.subplot(111, projection='3d')
#             ax.scatter(data[:,0], data[:,1], data[:,2],c=y)

#         plt.axis('equal')
#         plt.show()

#     if not continues:
#         colors=['C{}'.format(i) for i in range(max(y)+1)]
#         random.seed(seed)
#         random.shuffle(colors)
#         colors={i:colors[i] for i in range(max(y)+1)}
#         colors[-1]='gray'
#         hashColor=lambda y:[colors[one] for one in y]
#         noise_mask=(y==-1)

#         if data.shape[1]==2:
#             ax = plt.subplot(111)
#             if area is None:
#                 ax.scatter(data[~noise_mask][:,0], data[~noise_mask][:,1],c=hashColor(y[~noise_mask]))
#                 ax.scatter(data[noise_mask][:,0], data[noise_mask][:,1],c=hashColor(y[noise_mask]),alpha=0.1)
#             else:
#                 ax.scatter(data[~noise_mask][:,0], data[~noise_mask][:,1],c=hashColor(y[~noise_mask]), s=25 * area[~noise_mask].astype(np.float64) ** 3, alpha=0.5)
#                 ax.scatter(data[noise_mask][:,0], data[noise_mask][:,1],c=hashColor(y[noise_mask]), s=area[noise_mask].astype(np.float64), alpha=0.1)
#             plt.axis('equal')

#         if data.shape[1]==3:
#             ax = plt.subplot(111, projection='3d')
#             ax.scatter(data[~noise_mask][:,0], data[~noise_mask][:,1], data[~noise_mask][:,2],c=hashColor(y[~noise_mask]))
#             ax.scatter(data[noise_mask][:,0], data[noise_mask][:,1], data[noise_mask][:,2],c=hashColor(y[noise_mask]),alpha=0.1)

#         plt.show()

import plotly.graph_objects as go
import plotly.express as px
named_colors=px.colors.qualitative.Light24

def autoPlotly(X,labels):

    hovertexts=[str(label) for label in labels]

    fig = go.Figure(data=go.Scatter(
        x = X[:,0], # non-uniform distribution
        y = X[:,1], # zoom to see more points at the center
        mode='markers',
        marker=dict(
            color=[named_colors[int(i)%24] for i in labels],
            line_width=1
        ),
        hoverinfo = 'text',
        hovertext = hovertexts,
    ))

    fig.update_layout(
        width = 500,
        height = 500,
        title = "",
        xaxis = dict(
          range=[-2,2],  # sets the range of xaxis
          constrain="domain",  # meanwhile compresses the xaxis by decreasing its "domain"
        ),
        yaxis = dict(
          scaleanchor = "x",
          scaleratio = 1,
        ),
    )

    fig.show()

processes=[]

def term(sig_num, addtion):
    print('terminate process {}'.format(os.getpid()))
    try:
        print('the processes is {}'.format(processes) )
        for p in processes:
            print('process {} terminate'.format(p.pid))
            p.terminate()
            # os.kill(p.pid, signal.SIGKILL)
    except Exception as e:
        print(str(e))

class GIFPloter():
    def __init__(self,root):
        self.root=root

    @abc.abstractmethod
    def callback(self,task,pid,Process_state):
        # TODO 此处增加画图操作
        Process_state[str(pid)]=True

    def run(self,pnum,tasks,Y):
        signal.signal(signal.SIGTERM, term)

        ###############################多线程处理##########################
        Process_state=Manager().dict({str(i):True for i in range(pnum)})
        idx=0
        pid=1
        while idx<len(tasks):
            self.callback(tasks[idx],Y,pid,Process_state)
            #查询是否有可用线程
            for pid in range(pnum):
                if Process_state[str(pid)]==True:
                    Process_state[str(pid)]=False #占用当前线程
                    p=Process(target=self.callback,args=(tasks[idx],Y,pid,Process_state))
                    print( '{}'.format(idx) )
                    idx+=1
                    p.start()
                    processes.append(p)
                    break

        for p in processes:
            p.join()

    def SaveGIF(self,name,fps=1):
        pass
        # path = self.root
        # gif_images_path = os.listdir(path+'/')

        # gif_images_path=[img for img in gif_images_path if img[-4:]=='.png']
        # gif_images_path=sorted(gif_images_path,key=lambda x:int(x[:-4]))
        # gif_images = []
        # for i, path_ in enumerate(gif_images_path):
        #     print(path_)
        #     if '.png' in path_:
        #         if i % 1 == 0:
        #             gif_images.append(imageio.imread(path+'/'+path_))

        # imageio.mimsave(path+'/'+"{}.gif".format(name), gif_images, fps=fps)

class Visualization(GIFPloter):
    def __init__(self,root,seed=2020):
        super(Visualization,self).__init__(root)
        self.color_list=['C{}'.format(i) for i in range(1,21)]
        random.seed(seed)
        random.shuffle(self.color_list)
        self.Cnum=len(self.color_list)

    def callback(self,task,Y,pid,Process_state):
        X, root, B_mask ,idx=task
        root=Y

        colors=np.array(['gray']*root.shape[0])
        for rt in list(set(root)):
            selected=np.nonzero(root==rt)[0].tolist()
            colors[selected]=self.color_list[int(rt%self.Cnum)]

        colors[np.nonzero(B_mask)]='gray'
        plt.figure(figsize=(4,4))
        B_mask=(colors=='gray')
        plt.scatter(X[~B_mask,0],X[~B_mask,1],c=colors[~B_mask])
        plt.scatter(X[B_mask,0],X[B_mask,1],c=colors[B_mask],alpha=0.1)
        plt.title('{}'.format(idx))
        plt.axis('equal')
        plt.xticks([])
        plt.yticks([])

        path=Path(self.root)
        path.mkdir(exist_ok=True,parents=True)
        plt.savefig(path/('{}.png'.format(idx)))
        plt.close()

        Process_state[str(pid)]=True

import random
class PaperGraph:
    def __init__(self) -> None:
        pass

    @classmethod
    def show_manifolds(self,manifolds,X_extend,seed=2020):
        NC=len(manifolds)
        color_list=['gray']
        color_add=['C{}'.format(i) for i in range(NC)]
        color_add.remove('C7')
        random.seed(seed)
        random.shuffle(color_add)
        color_list=color_list+color_add

        fig=plt.figure(figsize=(4, 4))
        for i in range(NC):
            points=X_extend[manifolds[i].pID,:-2]
            centers=np.mean(points,axis=0)
            plt.scatter(points[:,0],points[:,1],c=color_list[i])
            plt.text(centers[0],centers[1],str(i))

        _=plt.axis('equal')

    @classmethod
    def show_clusters(self,X,Y,fileroot=None,fileidx=1000,title=None):
        C=int(np.max(Y))+1
        colors={-1:'gray'}
        colors.update({i:'C{}'.format(i) for i in range(C)})
        plt.figure(figsize=(4, 4))
        for c in range(-1,C):
            mask= (Y==c)
            if np.sum(mask) >0 :
                plt.scatter(X[mask][:,0],X[mask][:,1],c=colors[c])
        plt.axis('equal')

        if title:
            plt.title(title)
        if fileroot:
            for i in range(15):
                plt.savefig(Path(fileroot.format(fileidx+i)))
        # plt.show()

    @classmethod
    def show_local_clusters(self,X,V,seed=2020):
        Ks=list(V.keys())
        Vs=list(V.values())

        colors=['C{}'.format(i) for i in range(len(Ks))]
        random.seed(seed)
        random.shuffle(colors)
        plt.figure(figsize=(4, 4))
        for c in range(len(Vs)):
            if Ks[c]==-1:
                plt.scatter(X[Vs[c],0],X[Vs[c],1],c='gray',alpha=0.3)
            else:
                plt.scatter(X[Vs[c],0],X[Vs[c],1],c=colors[c])
                # plt.text(X[Vs[c],0].mean(),X[Vs[c],1].mean(),'{:.0f}'.format(c))
        plt.axis('equal')
        plt.show()

    @classmethod
    def show_topo_graph(self,V,E,X=None,fileroot=None,fileidx=1000):
        plt.figure(figsize=(4, 4))
        G = nx.Graph()
        G.add_nodes_from(V.keys())
        for e in E:
            if E[e]>0:
                G.add_edge(e[0],e[1],weight=E[e])
        if -1 in G.nodes():
            G.remove_node(-1)
        pos={}
        if X is None:
            pos = nx.kamada_kawai_layout(G)
        else:
            for i in V.keys():
                pos[i]=X[V[i]].mean(axis=0)

        nx.draw_networkx(G,pos,with_labels=False,node_size =50)
        edge_labels = nx.get_edge_attributes(G, 'weight')
        edge_labels={key:'{:.2f}'.format(val) for key,val in edge_labels.items()}
        nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
        plt.axis('equal')

        if fileroot:
            for i in range(5):
                plt.savefig(Path(fileroot.format(fileidx+i)))


import collections

def solution(n, computers):
    answer = 0
    graph = collections.defaultdict(list)
    for i in range(len(computers)):
        for j in range(len(computers)):
            if i == j:
                continue
            if computers[i][j] == 1:
                graph[i].append(j)

    def network(computer):
        if check[computer]:
            return
        check[computer] = True
        while graph[computer]:
            network(graph[computer].pop())

    check = [False]*n
    for computer in range(n):
        if check[computer]:
            continue
        network(computer)
        answer += 1

    return answer


import sqlite3
from tkinter import *
from tkinter import ttk
from tkinter import messagebox

import addbook
import addmember
import givebook

con = sqlite3.connect("library.sqlite")
cur = con.cursor()

class Main(object):
    def __init__(self, master):
        self.master = master

        def display_statistics(evt):
            count_books = cur.execute("SELECT count(book_id) FROM books").fetchall()
            count_members = cur.execute("SELECT count(member_id) FROM members").fetchall()
            count_taken = cur.execute("SELECT count(book_status) FROM books WHERE book_status=1").fetchall()
            print(count_books)
            self.lbl_book_count.config(text='Total : ' + str(count_books[0][0]) + " Books in Library")
            self.lbl_member_count.config(text='Total members : ' + str(count_members[0][0]))
            self.lbl_taken_count.config(text='Total taken : ' + str(count_taken[0][0]))
            display_books(self)

        def display_books(self):
            books = cur.execute("SELECT * FROM books").fetchall()
            count = 0
            self.list_books.delete(0, END)
            for book in books:
                print(book)
                self.list_books.insert(count, str(book[0]) + "-" + str(book[1]))
                count += 1

            def book_info(evt):
                value = str(self.list_books.get(self.list_books.curselection()))
                id = value.split('-')[0]
                book = cur.execute("SELECT * FROM books WHERE book_id=?", (id,))
                book_info = book.fetchall()
                print(book_info)

                self.list_details.delete(0, 'end')
                self.list_details.insert(0, "Book Name : " + book_info[0][1])
                self.list_details.insert(1, "Author : " + book_info[0][2])
                self.list_details.insert(2, "Page : " + book_info[0][3])
                self.list_details.insert(3, "Language : " + book_info[0][4])

                if book_info[0][5] == 0:
                    self.list_details.insert(4, "Status : Available")
                else:
                    self.list_details.insert(4, "Status : Not Available")

            def double_click(evt):
                global given_id
                value = str(self.list_books.get(self.list_books.curselection()))
                print(value)
                given_id = value.split('-')[0]
                give_book = GiveBook()

            self.list_books.bind("<<ListboxSelect>>", book_info)
            self.tabs.bind("<<NotebookTabChanged>>", display_statistics)
            # self.tabs.bind("<ButtonRelease-1>", display_books)
            # self.list_books.bind("<Double-Button-1>", double_click)

        # ================== Frames =====================
        mainframe = Frame(self.master)
        mainframe.pack()
        # top frame
        top_frame = Frame(mainframe, width=1350, height=70, bg='#f8f8f8', padx=20, relief=SUNKEN, borderwidth=2)
        top_frame.pack(sid=TOP, fill=X)
        # center frame
        center_frame = Frame(mainframe, width=1350, height=680, relief=RIDGE, bg="#e0f0f0")
        center_frame.pack(sid=TOP)
        # center left frame
        center_left_frame = Frame(center_frame, width=900, height=700, bg="#e0f0f0", borderwidth=2, relief="sunken")
        center_left_frame.pack(side='left')
        # center right frame
        center_right_frame = Frame(center_frame, width=450, height=700, bg="#e0f0f0", borderwidth=2, relief="sunken")
        center_right_frame.pack()

        # Search bar
        search_bar = LabelFrame(center_right_frame, width=440, height=175, text='Search Box', bg='#9bc9ff')
        search_bar.pack(fill=BOTH)
        self.lbl_search = Label(search_bar, text='Search : ', font='arial 12 bold', bg='#9bc9ff', fg='white')
        self.lbl_search.grid(row=0, column=0, padx=20, pady=10)
        self.search_entry = Entry(search_bar, width=30, bd=10)
        self.search_entry.grid(row=0, column=1, columnspan=3, padx=10, pady=10)
        self.btn_search = Button(search_bar, text='Search', font='arial 12', bg='#fcc324', fg='white',
                                 command=self.search_book)
        self.btn_search.grid(row=0, column=4, padx=20, pady=10)

        # list bar
        list_bar = LabelFrame(center_right_frame, width=400, height=175, text='List Box', bg='#fcc324')
        list_bar.pack(fill=BOTH)
        lbl_list = Label(list_bar, text='Sort By', font='times 16 bold', fg='#2488ff', bg='#fcc324')
        lbl_list.grid(row=0, column=2)

        self.list_choice = IntVar()
        rb1 = Radiobutton(list_bar, text='All Books', var=self.list_choice, value="1", bg='#fcc324')
        rb2 = Radiobutton(list_bar, text='In Library', var=self.list_choice, value="2", bg='#fcc324')
        rb3 = Radiobutton(list_bar, text='Borrowed Books', var=self.list_choice, value="3", bg='#fcc324')
        rb1.grid(row=1, column=0)
        rb2.grid(row=1, column=1)
        rb3.grid(row=1, column=2)

        btn_list = Button(list_bar, text='List Books', bg='#2488ff', fg='white', font='arial 12', command=self.list_books)
        btn_list.grid(row=1, column=3, padx=40, pady=10)

        # title and image
        image_bar = Frame(center_right_frame, width=440, height=350)
        image_bar.pack(fill=BOTH)
        self.title_right = Label(image_bar, text='Welcome to our Library', font='arial 16 bold')
        self.title_right.grid(row=0)
        self.image_library = PhotoImage(file='./icons/library.png')
        self.lbl_img = Label(image_bar, image=self.image_library)
        self.lbl_img.grid(row=1)

        # ==================================== ToolBar ======================

        # add book
        self.icon_book = PhotoImage(file='./icons/add_book.png')
        self.btn_book = Button(top_frame, text='Add Book', image=self.icon_book, compound=LEFT,
                               font='arial, 12 bold', command=self.add_book)
        self.btn_book.pack(sid=LEFT, padx=10)

        # add member method
        self.icon_member = PhotoImage(file='./icons/users.png')
        self.btn_member = Button(top_frame, text="Add Member", image=self.icon_member, compound="left",
                                 font='arial 12 bold', padx=10, command=self.add_member)
        self.btn_member.pack(side=LEFT)

        # give book
        self.icon_give = PhotoImage(file='./icons/givebook.png')
        self.btn_give = Button(top_frame, text="Give Book", image=self.icon_give, compound="left",
                               font='arial 12 bold', padx=10, command=self.give_book)
        self.btn_give.pack(side='left')

        # ===================== Tabs ==========================
        # ====================== Tab1 ===================
        self.tabs = ttk.Notebook(center_left_frame, width=900, height=660)
        self.tabs.pack()
        self.tab1_icon = PhotoImage(file='./icons/books.png')
        self.tab2_icon = PhotoImage(file='./icons/members.png')
        self.tab1 = ttk.Frame(self.tabs)
        self.tab2 = ttk.Frame(self.tabs)
        self.tabs.add(self.tab1, text='Library Management', image=self.tab1_icon, compound='left')
        self.tabs.add(self.tab2, text='Statistics', image=self.tab2_icon, compound='left')

        # ============== list books ==================
        self.list_books = Listbox(self.tab1, width=40, height=30, bd=5, font='times 12 bold')
        self.scroll = Scrollbar(self.tab1, orient=VERTICAL)
        self.list_books.grid(row=0, column=0, padx=(10, 0), pady=20, sticky=N)
        self.scroll.config(command=self.list_books.yview)
        self.list_books.config(yscrollcommand=self.scroll.set)
        self.scroll.grid(row=0, column=0, sticky=N + S + E)

        # list details'
        self.list_details = Listbox(self.tab1, width=80, height=30, bd=5, font='times 12 bold')
        self.list_details.grid(row=0, column=1, padx=(10, 0), pady=10, sticky=N)

        # ================================ Tab 2 =======================
        # Statistics
        self.lbl_book_count = Label(self.tab2, text="dfsghh", pady=20, font='verdana 14 bold')
        self.lbl_book_count.grid(row=0)
        self.lbl_member_count = Label(self.tab2, text="tye5t", pady=20, font='verdana 14 bold')
        self.lbl_member_count.grid(row=1, sticky=W)
        self.lbl_taken_count = Label(self.tab2, text="ye5yyy", pady=20, font='verdana 14 bold')
        self.lbl_taken_count.grid(row=2, sticky=W)

        # functions
        display_books(self)

        display_statistics(self)

    def add_book(self):
        add = addbook.Addbook()

    def add_member(self):
        member = addmember.Addmember()

    def search_book(self):
        value = self.search_entry.get()
        search = cur.execute("SELECT * FROM books WHERE book_name LIKE ?", ('%' + value + "%",)).fetchall()
        print(search)
        self.list_books.delete(0, 'end')
        count = 0
        for book in search:
            self.list_books.insert(count, str(book[0]) + "-" + str(book[1]))
            count += 1

    def list_books(self):
        value = self.list_choice.get()
        if value == 1:
            all_books = cur.execute("SELECT * FROM books").fetchall()
            self.list_books.delete(0, 'end')

            count = 0
            for book in all_books:
                self.list_books.insert(count, str(book[0]) + "-" + str(book[1]))
                count += 1
        elif value == 2:
            book_in_library = cur.execute("SELECT * FROM books WHERE book_status = ?", (0, )).fetchall()
            self.list_books.delete(0, 'end')

            count = 0
            for book in book_in_library:
                self.list_books.insert(count, str(book[0]) + "-" + str(book[1]))
                count += 1
        else:
            taken_book = cur.execute("SELECT * FROM books WHERE book_status = ?", (1, )).fetchall()
            self.list_books.delete(0, 'end')

            count = 0
            for book in taken_book:
                self.list_books.insert(count, str(book[0]) + "-" + str(book[1]))
                count += 1

    def give_book(self):
        give_book = givebook.GiveBook()

class GiveBook(Toplevel):
    def __init__(self):
        Toplevel.__init__(self)
        self.geometry('650x700+550+20')
        self.title("Lend Book")
        self.resizable(False, False)
        global given_id
        self.book_id = int (given_id)

        query = "SELECT * FROM books "
        books = cur.execute(query).fetchall()
        book_list = []
        for book in books:
            book_list.append(str(book[0]) + "-" + str(book[1]))

        query2 = "SELECT * FROM members"
        members = cur.execute(query2)
        member_list = []
        for member in members:
            member_list.append(str(member[0]) + "-" + str(member[1]))

        # ============= Frames ==================

        # Top Frame
        self.top_frame = Frame(self, height=150, bg='white')
        self.top_frame.pack(fill=X)

        # Bottom Frame
        self.bottom_frame = Frame(self, height=600, bg='#fcc324')
        self.bottom_frame.pack(fill=X)

        # heading, image
        self.top_image = PhotoImage(file='./icons/addbook.png')
        top_image_lbl = Label(self.top_frame, image=self.top_image, bg='white')
        top_image_lbl.place(x=120, y=10)
        heading = Label(self.top_frame, text='   Lend a Book   ', font='arial 22 bold', fg='#003f8a', bg='white')
        heading.place(x=290, y=60)

        # ============= Entry and Label =================
        # book combo box
        self.book_name = StringVar()
        self.lbl_name = Label(self.bottom_frame, text='Book : ', font='arial 15 bold', fg='white', bg='#fcc324')
        self.lbl_name.place(x=40, y=40)
        self.combo_name = ttk.Combobox(self.bottom_frame, textvariable=self.book_name, width=40)
        self.combo_name['values'] = book_list
        self.combo_name.current(self.book_id-1)
        self.combo_name.place(x=150, y=45)

        # member combo box
        self.member_name = StringVar()
        self.lbl_member = Label(self.bottom_frame, text='Member : ', font='arial 15 bold', fg='white', bg='#fcc324')
        self.lbl_member.place(x=40, y=80)
        self.combo_member = ttk.Combobox(self.bottom_frame, textvariable=self.member_name, width=40)
        self.combo_member['values'] = member_list
        self.combo_member.place(x=150, y=85)

        # Button
        button = Button(self.bottom_frame, text="Lend Book", command=self.lend_book)
        button.place(x=270, y=120)

    def lend_book(self):
        book_name = self.book_name.get()
        member_name = self.member_name.get()

        if book_name and member_name != "":
            try:
                query = "INSERT INTO 'borrows' (bbook_id, bmember_id) values(?,?) "
                cur.execute(query, (book_name, member_name))
                con.commit()
                messagebox.showinfo("Success", "Successfully added to database!", icon='info')
                cur.execute("UPDATE books SET book_status=? where book_id=?", (1, self.book_id))
                con.commit()
            except:
                messagebox.showerror("Error", "Can't add to database!", icon='warning')
        else:
            messagebox.showerror("Error", "Fields can't be empty!", icon='warning')

def main():
    root = Tk()
    app = Main(root)
    root.title("Library Management System")
    root.geometry("1350x750")
    root.iconbitmap('./icons/icon.ico')
    root.mainloop()

if __name__ == "__main__":
    main()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
Speed = 0.3

import ImportantFunctions as IF
import datetime
import serial
from PIL import ImageTk
from PIL import Image
import PIL
import tkinter.font
import tkinter.messagebox
import tkinter.filedialog
import tkinter as tk
import imutils
import cv2 as cv2
import math

import keyboard
from uvctypes import *
import time
import cv2
cap = cv2.VideoCapture(2)

import numpy as np
try:
    from queue import Queue
except ImportError:
    from Queue import Queue
import platform
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')
BUF_SIZE = 2
q = Queue(BUF_SIZE)

import serial
SerialData = serial.Serial("/dev/ttyACM0", 9600, timeout = 0.2)
###SerialData = serial.Serial("com10", 9600, timeout = 0.2)
SerialData.setDTR(False)
time.sleep(1)
SerialData.flushInput()
SerialData.setDTR(True)

def Send(SerialData, character, Description):
    SerialData.write(bytes(character, "utf-8"))
    print("ARDUINO SEND: ", Description)

def SendWait(SerialData, character, timeout, Description):
    SerialData.write(bytes(character, "utf-8"))
    reading = SerialData.read().decode("utf-8")
    ST = time.time()
    while True:
        if reading != "":
            break
        if time.time() - ST > timeout:
            break
    print("ARDUINO SEND: ", Description)

import datetime

def days_since_jan1(year_start_timestamp):
    year_start = datetime.datetime.fromtimestamp(year_start_timestamp)
    jan1 = datetime.date(year_start.year, 1, 1)
    year_start_date = year_start.date()
    days_since_jan1 = (year_start_date - jan1).days + 1

    if is_leap_year(year_start.year) and year_start_date > datetime.date(year_start.year, 2, 28):
        days_since_jan1 += 1

    return days_since_jan1

def is_leap_year(year):
    if year % 4 != 0:
        return False
    elif year % 100 != 0:
        return True
    elif year % 400 != 0:
        return False
    else:
        return True

def is_odd(number):
    return number % 2 != 0

def is_even(number):
    return number % 2 == 0

def py_frame_callback(frame, userptr):

    array_pointer = cast(frame.contents.data, POINTER(
        c_uint16 * (frame.contents.width * frame.contents.height)))
    data = np.frombuffer(
        array_pointer.contents, dtype=np.dtype(np.uint16)
    ).reshape(
        frame.contents.height, frame.contents.width
    )  # no copy

    # data = np.fromiter(
    #   frame.contents.data, dtype=np.dtype(np.uint8), count=frame.contents.data_bytes
    # ).reshape(
    #   frame.contents.height, frame.contents.width, 2
    # ) # copy

    if frame.contents.data_bytes != (2 * frame.contents.width * frame.contents.height):
        return

    if not q.full():
        q.put(data)

PTR_PY_FRAME_CALLBACK = CFUNCTYPE(
    None, POINTER(uvc_frame), c_void_p)(py_frame_callback)

def ktof(val):
    return (1.8 * ktoc(val) + 32.0)

def ktoc(val):
    return (val - 27315) / 100.0

def raw_to_8bit(data):
    cv2.normalize(data, data, 0, 65535, cv2.NORM_MINMAX)
    np.right_shift(data, 8, data)
    return cv2.cvtColor(np.uint8(data), cv2.COLOR_GRAY2RGB)

def display_temperature(img, val_k, loc, color):
    val = ktof(val_k)
    cv2.putText(img, "{0:.1f} degF".format(val), loc,
                cv2.FONT_HERSHEY_SIMPLEX, 0.75, color, 2)
    x, y = loc
    cv2.line(img, (x - 2, y), (x + 2, y), color, 1)
    cv2.line(img, (x, y - 2), (x, y + 2), color, 1)

ctx = POINTER(uvc_context)()
dev = POINTER(uvc_device)()
devh = POINTER(uvc_device_handle)()
ctrl = uvc_stream_ctrl()

res = libuvc.uvc_init(byref(ctx), 0)
if res < 0:
    print("uvc_init error")
    exit(1)

try:
    res = libuvc.uvc_find_device(ctx, byref(dev), PT_USB_VID, PT_USB_PID, 0)
    print(PT_USB_VID, PT_USB_PID)
    if res < 0:
        print("uvc_find_device error")
        exit(1)
except:
    libuvc.uvc_exit(ctx)

try:
    res = libuvc.uvc_open(dev, byref(devh))
    if res < 0:
        print("uvc_open error")
        exit(1)

    print("device opened!")

    print_device_info(devh)
    print_device_formats(devh)

    frame_formats = uvc_get_frame_formats_by_guid(devh, VS_FMT_GUID_Y16)
    if len(frame_formats) == 0:
        print("device does not support Y16")
        exit(1)

    libuvc.uvc_get_stream_ctrl_format_size(devh, byref(ctrl), UVC_FRAME_FORMAT_Y16,
                                           frame_formats[0].wWidth, frame_formats[0].wHeight, int(
        1e7 / frame_formats[0].dwDefaultFrameInterval)
    )

    res = libuvc.uvc_start_streaming(
        devh, byref(ctrl), PTR_PY_FRAME_CALLBACK, None, 0)
    if res < 0:
        print("uvc_start_streaming failed: {0}".format(res))
        exit(1)
except:
    libuvc.uvc_unref_device(dev)

root = tk.Tk()  # Main Root
root.attributes('-fullscreen', True)
# root.state('normal')
root.configure(background='white')
subFont1 = tkinter.font.Font(family='Segoe UI', size=20, weight="bold")
subFont2 = tkinter.font.Font(family='Segoe UI', size=11, weight="bold")

threshold_value = 90
area_required = 270
box_size = 30
box_size2 = 40
OrigRGBCamWidth = 1920
RGBCamWidthCrop = 480
CropX1RGB,CropX2RGB,CropY1RGB,CropY2RGB = 0,OrigRGBCamWidth-RGBCamWidthCrop,0,1080

RequiredCounter1 = 10
RequiredCounter2 = 15
RequiredCounter = RequiredCounter1
CurrentTemp1 = 24
CurrentTemp2 = 24
def MainLoop():
    global threshold_value
    global area_required
    global box_size
    global box_size2
    global CropX1RGB,CropX2RGB,CropY1RGB,CropY2RGB, PrevCount2, FalseCounter, ACU1_Op, ACU2_Op
    global OrigRGBCamWidth, RGBCamWidthCrop
    font = cv2.FONT_HERSHEY_SIMPLEX

    data = q.get(True, 500)
    # print(len(data),len(data[0]))
    data = cv2.resize(data[:, :], (240, 180))
    temperature = data / 100 - 273.15
    min_temp = 33
    max_temp = 37.5
    temp_norm = math.e ** ((temperature - min_temp) / (max_temp - min_temp))
    temp_norm = temp_norm * 255 / math.e
    temp_norm = np.clip(temp_norm, 0, 255)
    temp_norm = temp_norm.astype(np.uint8)

    min_temp2 = 28
    max_temp2 = 35
    temp_norm2 = math.e ** ((temperature - min_temp2) / (max_temp2 - min_temp2))
    temp_norm2 = temp_norm2 * 255 / math.e
    temp_norm2 = np.clip(temp_norm2, 0, 255)
    temp_norm2 = temp_norm2.astype(np.uint8)

    min_temp_fnd = round(np.amin(temperature), 2)
    max_temp_fnd = round(np.amax(temperature), 2)

    threshold_value = threshold_value_Entry.get()
    if threshold_value:
        try:
            threshold_value = int(threshold_value)
        except:
            threshold_value = 0
    else:
        threshold_value = 0

    try:
        threshold_value_temp = threshold_value*math.e/255
        threshold_value_temp = math.log(threshold_value_temp)/math.log(math.e)
        threshold_value_temp = threshold_value_temp*(max_temp - min_temp)
        threshold_value_temp = round(threshold_value_temp + min_temp,2)
    except:
        threshold_value_temp = 0

    area_required = area_required_Entry.get()
    if area_required:
        try:
            area_required = int(area_required)
        except:
            area_required = 0
    else:
        area_required = 0

    # print(threshold_value_temp)
    threshold_value_label.configure(text="Threshold Value: (Approx: " +str(threshold_value_temp)+ ")")
    _, temp_thresh = cv2.threshold(temp_norm, threshold_value, 255, cv2.THRESH_BINARY)
    kernel = np.ones((5, 5), np.uint8)

    cv2.imwrite("Video1.png", temp_thresh)

    new_img = cv2.imread("Video1.png")
    height, width = new_img.shape[:2]

    rows = new_img.shape[0]
    cols = new_img.shape[1]

    box_size = box1_Entry.get()
    if box_size:
        try:
            box_size = int(box_size)
        except:
            box_size = 1
    else:
        box_size = 1

    box_size2 = box2_Entry.get()
    if box_size2:
        try:
            box_size2 = int(box_size2)
        except:
            box_size2 = 1
    else:
        box_size2 = 1

    for i in range(0, width, box_size2):
        cv2.line(new_img, (i, 0), (i, height), (0, 0, 255), 1)

    for i in range(0, height, box_size):
        cv2.line(new_img, (0, i), (width, i), (0, 0, 255), 1)

    Count = 0
    logics = []
    for i in range(0, rows, box_size):
        for j in range(0, cols, box_size2):
            grid = temp_thresh[i:i+box_size, j:j+box_size2]
            grid2 = temp_norm[i:i+box_size, j:j+box_size2]
            ave = round(np.average(grid2))/255
            ave = ave*math.e
            ave = math.log(ave) / math.log(math.e)
            ave = ave * (max_temp - min_temp)
            ave = ave + min_temp
            ave = round(ave, 2)
            white_pixels = np.sum(grid == 255)
            if white_pixels > area_required:
                cv2.rectangle(new_img, (j, i), (j+box_size2, i+box_size), (0, 255, 0), 1)
                Count = Count + 1
                # cv2.putText(new_img, str(Count), (j, i+7), font, 0.35, (0, 255, 0), 1, cv2.LINE_AA)
                logics.append(True)
            else:
                logics.append(False)

    color_map = cv2.COLORMAP_JET
    temp_normed = cv2.normalize(temperature, None, 0, 255, cv2.NORM_MINMAX, dtype=cv2.CV_8U)
    temp_colored = cv2.applyColorMap(temp_norm2, color_map)

    while True:
        try:
            # RGB_CamImg = cv2.imread("downloaded.png")
            _,RGB_CamImg = cap.read()
            RGB_CamImg = RGB_CamImg[int(RGBCamWidthCrop/2):int(OrigRGBCamWidth-RGBCamWidthCrop/2), 0:1080]
            Max = OrigRGBCamWidth-RGBCamWidthCrop
            Maxy = 1080
            if CropX1RGB < 0:
                CropX1RGB = 0
            if CropX2RGB > Max:
                CropX2RGB = Max
            if CropY1RGB < 0:
                CropY1RGB = 0
            if CropY2RGB > Maxy:
                CropY2RGB = Maxy
            # print(CropX1RGB, CropX2RGB, CropY1RGB, CropY2RGB)
            # print(RGB_CamImg.shape)
            RGB_CamImg = RGB_CamImg[CropY1RGB:CropY2RGB, CropX1RGB:CropX2RGB]
            RGB_CamImg = cv2.resize(RGB_CamImg,(240,180))
            a=RGB_CamImg #Pang save lang, para safe

            gray = cv2.cvtColor(a, cv2.COLOR_BGR2GRAY)

            faces = faceCascade.detectMultiScale(
                gray,
                scaleFactor=1.1,
                minNeighbors=5,
                minSize=(30, 30),
                flags=cv2.CASCADE_SCALE_IMAGE
            )
            # print(faces)
            Centers = []
            for (x, y, w, h) in faces:
                # cv2.rectangle(a, (x, y), (x+w, y+h), (0, 255, 0), 2)
                Centers.append((x+int(w/2),y+int(h/2)))
            # print(Centers)
            break
        except:
            print("error")
    Count2 = 0
    itera = 0
    for i in range(0, rows, box_size):
        for j in range(0, cols, box_size2):
            cv2.rectangle(RGB_CamImg, (j, i), (j+box_size2, i+box_size), (0, 0, 255), 1)
            if FindCenterOn(j, i, box_size2, box_size, Centers) and logics[itera] == True:
                cv2.rectangle(RGB_CamImg, (j, i), (j+box_size2, i+box_size), (0, 255, 0), 1)
                cv2.circle(RGB_CamImg,FindCenter(j, i, box_size2, box_size, Centers),5,(0,255,0),-1,cv2.LINE_AA)
                Count2 = Count2 + 1
                cv2.putText(RGB_CamImg, str(Count2), (j, i+7), font, 0.35, (0, 255, 0), 1, cv2.LINE_AA)

            elif FindCenterOn(j, i, box_size2, box_size, Centers):
                cv2.rectangle(RGB_CamImg, (j, i), (j+box_size2, i+box_size), (255, 0, 0), 1)
                cv2.circle(RGB_CamImg,FindCenter(j, i, box_size2, box_size, Centers),5,(0,255,0),-1,cv2.LINE_AA)
                Count2 = Count2 + 1
                cv2.putText(RGB_CamImg, str(Count2), (j, i+7), font, 0.35, (0, 255, 0), 1, cv2.LINE_AA)
            elif logics[itera] == True:
                cv2.rectangle(RGB_CamImg, (j, i), (j+box_size2, i+box_size), (255, 0, 0), 1)
                Count2 = Count2 + 1
                cv2.putText(RGB_CamImg, str(Count2), (j, i+7), font, 0.35, (0, 255, 0), 1, cv2.LINE_AA)
            itera = itera + 1

            # if white_pixels > area_required:
            #     cv2.rectangle(new_img, (j, i), (j+box_size2, i+box_size), (0, 255, 0), 1)
            #     Count2 = Count2 + 1
            #     font = cv2.FONT_HERSHEY_SIMPLEX
            #     cv2.putText(new_img, str(Count), (j, i+7), font, 0.35, (0, 255, 0), 1, cv2.LINE_AA)

    if People_Entry.get().isdecimal():
        Count2 = int(People_Entry.get())
        # print("Manual People: ",People_Entry.get())
    global TrueCounter, RequiredCounter, RequiredCounter1, RequiredCounter2,Speed

    try:
        if PrevCount2 == Count2:
            TrueCounter = TrueCounter + Speed
            FalseCounter = 0
        else:
            FalseCounter = FalseCounter + Speed
            if FalseCounter > 5:
                PrevCount2 = Count2
                TrueCounter = 0
                FalseCounter = 0
    except:
        TrueCounter = 0
        FalseCounter = 0
        PrevCount2 = Count2
        pass

    global CurrentTemp1,CurrentTemp2,DesiredTemp1,DesiredTemp2
    Applied = ""
    if TrueCounter > RequiredCounter:
        TrueCounter = 0
        RequiredCounter = RequiredCounter2
        CurrentTemp1 = int(Current1_label.get())
        CurrentTemp2 = int(Current2_label.get())
        DateInteger = days_since_jan1(time.time()) #Leap year is considered ;)
        print("date: ", DateInteger)
        if is_odd(DateInteger): #DAY 1,3,5,7...
            if Count2 >= 35:
                if Count2 <= 20:
                    DesiredTemp1 = 23
                else:
                    DesiredTemp1 = 25
                DesiredTemp2 = 25 ##Supplementary
            else:
                if Count2 <= 20:
                    DesiredTemp1 = 23
                else:
                    DesiredTemp1 = 25
                DesiredTemp2 = 100 ##Supplementary (100 means OFF)

        if is_even(DateInteger): #DAY 2,4,6,8...
            if Count2 >= 35:
                if Count2 <= 20:
                    DesiredTemp2 = 23
                else:
                    DesiredTemp2 = 25
                DesiredTemp1 = 25 ##Supplementary
            else:
                if Count2 <= 20:
                    DesiredTemp2 = 23
                else:
                    DesiredTemp2 = 25
                DesiredTemp1 = 100 ##Supplementary (100 means OFF)

        ApplyTemp()
        Current1_label.delete(0,tk.END)
        Current2_label.delete(0,tk.END)
        if DesiredTemp1 > 50:
            Current1_label.configure(foreground="red")
        else:
            Current1_label.configure(foreground="black")

        if DesiredTemp2 > 50:
            Current2_label.configure(foreground="red")
        else:
            Current2_label.configure(foreground="black")

        Current1_label.insert(tk.END, str(CurrentTemp1))
        Current2_label.insert(tk.END, str(CurrentTemp2))
        Applied = " Applied"

    seconds = int(TrueCounter)   # replace with your desired number of seconds

    # Calculate the number of minutes and seconds
    minutes, seconds = divmod(seconds, 60)

    # Format the output string with leading zeros
    output_string = '{:02d}:{:02d}'.format(minutes, seconds)

    pips_value_label.configure(text="People (approx.): " + str(Count2) + " (" + str(output_string) + Applied +")")
    min_value_label.configure(text="Min Temp: " + str(min_temp_fnd) + " C")
    max_value_label.configure(text="Max Temp: " + str(max_temp_fnd) + " C")

    cv2.imwrite("Video1A.png", new_img)
    cv2.imwrite("Video2A.png", temp_colored)
    try:
        cv2.imwrite("Video3A.png", RGB_CamImg)
    except:
        pass
    IF.tkShow(Video1, "Video1A.png", 1)
    IF.tkShow(Video2, "Video2A.png", 1)
    IF.tkShow(Video3, "Video3A.png", 1)
    root.after(5, MainLoop)

def FindCenterOn(j, i, box_size_2, box_size, centers):
    for center in centers:
        if (j <= center[0] <= j+box_size_2) and (i <= center[1] <= i+box_size):
            return True
    return False

def FindCenter(j, i, box_size_2, box_size, centers):
    for center in centers:
        if (j <= center[0] <= j+box_size_2) and (i <= center[1] <= i+box_size):
            return center
    return False

def ApplyTemp():
    global CurrentTemp1,CurrentTemp2,DesiredTemp1,DesiredTemp2, ACU1_Op, ACU2_Op
    Diff1 = DesiredTemp1 - int(CurrentTemp1)
    if abs(Diff1) < 50:
        if ACU1_Op == False:
            ACU1_Op = True
            Send(SerialData,"A","ACU1 ON"); time.sleep(1)
            #send enable
        for i in range(abs(Diff1)):
            if Diff1 > 0:
                Send(SerialData,"C","ACU1 TempDown"); time.sleep(1)
                CurrentTemp1 = CurrentTemp1 - 1
            else:
                Send(SerialData,"B","ACU1 TempUp"); time.sleep(1)
                CurrentTemp1 = CurrentTemp1 + 1
    else:
        if ACU1_Op == True:
            ACU1_Op = False
            Send(SerialData,"A","ACU1 OFF"); time.sleep(1)
            #send disable
    print(DesiredTemp2, CurrentTemp2)
    Diff2 = DesiredTemp2 - int(CurrentTemp2)
    if abs(Diff2) < 50:
        if ACU2_Op == False:
            ACU2_Op = True
            Send(SerialData,"D","ACU2 ON"); time.sleep(1)
            #send enable
        for i in range(abs(Diff2)):
            if Diff1 > 0:
                Send(SerialData,"F","ACU2 TempDown"); time.sleep(1)
                CurrentTemp2 = CurrentTemp2 - 1
            else:
                Send(SerialData,"E","ACU2 TempUp"); time.sleep(1)
                CurrentTemp2 = CurrentTemp2 + 1
    else:
        if ACU2_Op == True:
            ACU2_Op = False
            Send(SerialData,"D","ACU2 OFF"); time.sleep(0.5)
            #send disable

GUI1 = tk.Frame(root)
GUI1.pack()

IF.Create_White_Screen("bg1.png", root.winfo_screenwidth(),
                       root.winfo_screenheight())
Background = tk.Label(GUI1, text='', font=subFont1, bg='white', bd=0)
Background.pack()
IF.tkShow(Background, "bg1.png", 1)

Video1 = tk.Label(GUI1, font=subFont1, bg='white')
Video1.place(x=10, y=10)

Video2 = tk.Label(GUI1, font=subFont1, bg='white')
Video2.place(x=300, y=10)

Video3 = tk.Label(GUI1, font=subFont1, bg='white')
Video3.place(x=300, y=270)

max_value_label = tk.Label(GUI1, font=subFont2, bg='white', height=1, text="Max Temp: ")
max_value_label.place(x=10, y=220)

min_value_label = tk.Label(GUI1, font=subFont2, bg='white', height=1, text="Min Temp: ")
min_value_label.place(x=10, y=240)

pips_value_label = tk.Label(GUI1, font=subFont2, bg='white', height=1, text="People: ")
pips_value_label.place(x=10, y=260)

threshold_value_label = tk.Label(GUI1, font=subFont2, bg='white', height=1, text="Threshold Value")
threshold_value_label.place(x=10, y=300)

threshold_value_Entry = tk.Entry(GUI1, font=subFont2, bg='white',width=5)
threshold_value_Entry.place(x=10, y=320)
threshold_value_Entry.insert(0, threshold_value)

area_required_label = tk.Label(GUI1, font=subFont2, bg='white', height=1, text="Required Area: (max is 30x30=900)")
area_required_label.place(x=10, y=340)

area_required_Entry = tk.Entry(GUI1, font=subFont2, bg='white',width=5)
area_required_Entry.place(x=10, y=360)
area_required_Entry.insert(0, area_required)

box1_label = tk.Label(GUI1, font=subFont2, bg='white', height=1, text="y: ")
box1_label.place(x=10, y=400)

box1_Entry = tk.Entry(GUI1, font=subFont2, bg='white',width=5)
box1_Entry.place(x=40, y=400)
box1_Entry.insert(0, box_size)

box2_label = tk.Label(GUI1, font=subFont2, bg='white', height=1, text="x: ")
box2_label.place(x=10, y=380)

box2_Entry = tk.Entry(GUI1, font=subFont2, bg='white',width=5)
box2_Entry.place(x=40, y=380)
box2_Entry.insert(0, box_size2)

People_Entry = tk.Entry(GUI1, font=subFont2, bg='white',width=5)
People_Entry.place(x=500, y=10)

Counter_label = tk.Label(GUI1, font=subFont2, bg='white', height=1, text="Timer: ")
Counter_label.place(x=40, y=420)

Current_label = tk.Label(GUI1, font=subFont2, bg='white', height=1, text="Current: ")
Current_label.place(x=10, y=420)

Desired_label = tk.Label(GUI1, font=subFont2, bg='white', height=1, text="Desired: ")
Desired_label.place(x=10, y=440)

f = open("CurrentTemp1.txt", "r+")
CurrentTemp1 = f.read()
f.close()
ACU1_Op = False
Current1_label = tk.Entry(GUI1, font=subFont2, bg='white',width=5)
Current1_label.place(x=100, y=420)
Current1_label.insert(tk.END, str(CurrentTemp1))

f = open("CurrentTemp2.txt", "r+")
CurrentTemp2 = f.read()
f.close()
ACU2_Op = False
Current2_label = tk.Entry(GUI1, font=subFont2, bg='white',width=5)
Current2_label.place(x=150, y=420)
Current2_label.insert(tk.END, str(CurrentTemp2))

def key_input(event):
    global CropX1RGB,CropX2RGB,CropY1RGB,CropY2RGB, Speed
    key_press = event.char
    if key_press.lower() == 'a':
        CropX1RGB = CropX1RGB - 10
    elif key_press.lower() == 's':
        CropX1RGB = CropX1RGB + 10
    elif key_press.lower() == 'd':
        CropX2RGB = CropX2RGB - 10
    elif key_press.lower() == 'f':
        CropX2RGB = CropX2RGB + 10

    if key_press.lower() == 't':
        CropY1RGB = CropY1RGB - 10
    elif key_press.lower() == 'g':
        CropY1RGB = CropY1RGB + 10
    elif key_press.lower() == 'h':
        CropY2RGB = CropY2RGB - 10
    elif key_press.lower() == 'n':
        CropY2RGB = CropY2RGB + 10

    if key_press.lower() == 'q':
        Speed = Speed - 0.1
    elif key_press.lower() == 'w':
        Speed = Speed + 0.1

root.bind("<KeyPress>", key_input)

root.after(5, MainLoop)
root.mainloop()

libuvc.uvc_stop_streaming(devh)
libuvc.uvc_unref_device(dev)
libuvc.uvc_exit(ctx)