# import flask
#
# from keras_vggface import VGGFace
#
# app = flask.Flask(__name__)
#
#
#
# if __name__ == "__main__":
#     print(("* Loading Keras model and Flask starting server..."
#            "please wait until server has fully started"))
#     model = VGGFace(model='resnet50', include_top=False, input_shape=(224, 224, 3), pooling='avg')
#     model.summary()
#     app.run(host="0.0.0.0", port=60006,  debug=True, use_reloader=False)

import base64
import datetime
import io
import os
import sys

import numpy as np
from PIL import Image
from sqlalchemy import create_engine
from sqlalchemy.ext.automap import automap_base

# from sqlalchemy import Column, Integer, String, Float, ForeignKey
# from sqlalchemy.orm import relationship
from sqlalchemy.orm import sessionmaker

import base64
from io import BytesIO

month = 1
y = 2021

if int(month) >= 2 and int(month) <= 12:
    if len(str(int(month) - 1)) < 2:
        month_1 = '0' + str(int(month) - 1)
    else:
        month_1 = str(int(month) - 1)
    month_2 = str(int(month))
    year_1 = year
    year_2 = year
else:
    month_1 = '12'
    month_2 = '01'

start_date = datetime.datetime.strptime('26/' + month_1 + '/' + str(year), '%d/%m/%Y')
end_date = datetime.datetime.strptime('26/' + month_2 + '/' + str(year), '%d/%m/%Y')

for _date in (start_date + datetime.timedelta(n) for n in range((end_date - start_date).days)):
    rs_person_images = session_sql.query(Person_Images).filter(
        Person_Images.ID_PERSON == row_person.ID_PERSON, Person_Images.DATE == _date).all()
    json_person = {}
    json_person['date'] = _date.strftime('%Y-%m-%d')
    status_1, status_2, status_3, status_4 = '', '', '', ''
    if len(rs_person_images) == 4:
        for row_person_images in rs_person_images:
            if str(getattr(row_person_images, "CHECK_SESSION")) == "1":
                status_1 = str(getattr(row_person_images, "STATUS"))
            elif str(getattr(row_person_images, "CHECK_SESSION")) == "2":
                status_2 = str(getattr(row_person_images, "STATUS"))
            elif str(getattr(row_person_images, "CHECK_SESSION")) == "3":
                status_3 = str(getattr(row_person_images, "STATUS"))
            else:
                status_4 = str(getattr(row_person_images, "STATUS"))
        if str(status_1) == str(1):
            if str(status_2) == str(2):
                json_person['sa_status'] = True
                json_person['sa_checkin'] = '7:00',
                json_person['sa_checkout'] = '11:00',
            else:
                json_person['sa_status'] = True
                json_person['sa_checkin'] = '7:00',
                json_person['sa_checkout'] = '11:00',
        else:
            json_person['sa_status'] = False
            json_person['sa_checkin'] = "0:00",
            json_person['sa_checkout'] = "0:00",

        if str(status_3) == str(3):
            if str(status_4) == str(4):
                json_person['ch_status'] = True
                json_person['ch_checkin'] = '13:00',
                json_person['ch_checkout'] = "17:00",
            else:
                json_person['ch_status'] = True
                json_person['ch_checkin'] = '13:00',
                json_person['ch_checkout'] = '17:00',
        else:
            json_person['ch_status'] = False
            json_person['ch_checkin'] = "0:00",
            json_person['ch_checkout'] = "0:00",
    else:
        json_person['sa_status'] = False
        json_person['sa_checkin'] = "0:00",
        json_person['sa_checkout'] = "0:00",

        json_person['ch_status'] = False
        json_person['ch_checkin'] = "0:00",
        json_person['ch_checkout'] = "0:00",
    person_date_data.append(json_person)


# std
import os
import unittest

# lib
import confuse

# project
from src.notifier.smtp_notifier import SMTPNotifier
from .dummy_events import DummyEvents

class TestSMTPNotifier(unittest.TestCase):
    def setUp(self) -> None:
        sender = os.getenv("SMTP_SENDER")
        sender_name = os.getenv("SMTP_SENDER_NAME")
        recipient = os.getenv("SMTP_RECIPIENT")
        username_smtp = os.getenv("SMTP_USERNAME")
        password_smtp = os.getenv("SMTP_PASSWORD")
        host = os.getenv("SMTP_HOST")
        port: int = 587
        if os.getenv("SMTP_PORT"):
            port = int(os.environ["SMTP_PORT"])
        smtp_auth = True
        if os.getenv("SMTP_ENABLE_AUTH"):
            smtp_auth = os.environ["SMTP_ENABLE_AUTH"].lower() in ["true", "1", "yes"]
        self.assertIsNotNone(sender, "You must export SMTP_SENDER as env variable")
        self.assertIsNotNone(sender_name, "You must export SMTP_SENDER_NAME as env variable")
        self.assertIsNotNone(recipient, "You must export SMTP_RECIPIENT as env variable")
        self.assertIsNotNone(host, "You must export SMTP_HOST as env variable")

        self.config = confuse.Configuration("chiadog", __name__)
        self.config.set(
            {
                "enable": True,
                "daily_stats": True,
                "wallet_events": True,
                "decreasing_plot_events": True,
                "increasing_plot_events": True,
                "credentials": {
                    "sender": sender,
                    "sender_name": sender_name,
                    "recipient": recipient,
                    "enable_smtp_auth": smtp_auth,
                    "username_smtp": username_smtp,
                    "password_smtp": password_smtp,
                    "host": host,
                    "port": port,
                },
            }
        )

        self.notifier = SMTPNotifier(
            title_prefix="Test",
            config=self.config,
        )

    @unittest.skipUnless(os.getenv("SMTP_HOST"), "Run only if SMTP available")
    def testSTMPLowPriorityNotifications(self):
        success = self.notifier.send_events_to_user(events=DummyEvents.get_low_priority_events())
        self.assertTrue(success)

    @unittest.skipUnless(os.getenv("SMTP_HOST"), "Run only if SMTP available")
    def testSMTPNormalPriorityNotifications(self):
        success = self.notifier.send_events_to_user(events=DummyEvents.get_normal_priority_events())
        self.assertTrue(success)

    @unittest.skipUnless(os.getenv("SMTP_HOST"), "Run only if SMTP available")
    def testSTMPHighPriorityNotifications(self):
        success = self.notifier.send_events_to_user(events=DummyEvents.get_high_priority_events())
        self.assertTrue(success)


from django.contrib import admin
from django.urls import path, include
from .import views
app_name = 'home'

urlpatterns = [
    path('', views.home_view, name='home'),
    path('about', views.about_view, name='about'),
    path('portfolio', views.portfolio_view, name='portfolio'),
    path('price', views.price_view, name='price'),
    path('services', views.services_view, name='services'),
    path('contact', views.contact_view, name='contact'),
]


"""processdata.py: This file accept from command line arguments, reading in
a reference file and a file that contains reads, and then write in an
alignment file whose name is specified by the last argument.
The main purpose is to provide a certificate such that one can
quickly examine each read, followed by location index(indices).
Note that in this program, for the sake of simplicity, if a read
appears more than twice, only cound up to the second alignment."""

__author__      = "Carolyn (Chih-Hsuan) Kao"
__version__     = "2.7.12"
__email__       = "chkao831@stanford.edu"
__date__        = "Oct 3, 2019"

import sys
import time

if __name__ == "__main__":
    if len(sys.argv) != 4:
        print("Usage:")
        print("$ python3 processdata.py <ref_file> <reads_file> <align_file>")
        sys.exit(0)

#open the reference file and read it in (and strip the last whitespace)
with open(sys.argv[1], 'r') as ref:
	f_ref = ref.read()
	f_ref = f_ref.strip()
ref.close()
#create a list to store each read
readList = []
#open the read file and read it in (and strip each empty line btw reads)
with open(sys.argv[2], 'r') as f_read:
	for line in f_read:
		line = line.strip()
		readList.append(line)
f_read.close()

#open the alignment file to write
f_write = open(sys.argv[3], "w")
#initialize integer variables to keep track of actual alignments
aligns0 = 0
aligns1 = 0
aligns2 = 0
#before the start of actual alignment, record time
start = time.time()

#the outer loop is for iteration of each read
for i in range(len(readList)):
	#create integer variables to record if a certain read
	#has first alignment, and then if it has second one after that
	firstTime = 0
	secondTime = 0
	#firstly, upon reading in a read, write to file
	f_write.write(str(readList[i]))

	#for inner loop is for finding read recursively
	for j in range(len(f_ref)):
	    #if there is no first alignment (i.e. no alignment at all)
		if(f_ref.find(readList[i],j,len(f_ref)) == -1):
		    #write in -1 and increment count
			f_write.write(' '+'-1'+'\n')
			aligns0 = aligns0 + 1
			break
		#otherwise, if there is first alignment BUT no second one
		elif(f_ref.find(readList[i],
		(f_ref.find(readList[i],j,len(f_ref)))+1,len(f_ref)) == -1):
			firstTime = f_ref.find(readList[i],j,len(f_ref))
			#capture its index and write to file &  increment count
			f_write.write(' '+str(firstTime)+'\n')
			aligns1 = aligns1 + 1
			break
		#otherwise, if there is first alignment AND second one
		else:
		    #firstly capture its index of first appearance
		    #then capture its index of second appearance, write both
			firstTime = f_ref.find(readList[i],j,len(f_ref))
			secondTime = f_ref.find(readList[i],firstTime+1,len(f_ref))
			f_write.write(' '+str(firstTime)+' '+str(secondTime)+'\n')
			#increment count
			aligns2 = aligns2 + 1
			break
#close the alignment file
f_write.close()
#by the end of actual alignment, record time
end = time.time()

print("reference length: " + str(len(f_ref)))
print("number reads: " + str(len(readList)))
print("aligns 0: " + str(aligns0/len(readList)))
print("aligns 1: " + str(aligns1/len(readList)))
print("aligns 2: " + str(aligns2/len(readList)))
print("elapsed time: " + str(end-start))


from unittest.mock import Mock, patch

import boto3 as boto
import orjson
from botocore.stub import ANY, Stubber
from dateutil.parser import parse
from deepdiff import DeepDiff

from sync import TIME_FORMAT
from sync.awsemr import (
    create_prediction_for_cluster,
    get_cluster_report,
    get_project_cluster_report,
)
from sync.models import Response

@patch("sync.awsemr.get_cluster_report")
@patch("sync.awsemr.create_prediction")
def test_create_prediction(create_prediction, get_cluster_report):
    with open("tests/data/emr-cluster-report.json") as emr_cluster_report_fobj:
        get_cluster_report.return_value = Response(
            result=orjson.loads(emr_cluster_report_fobj.read())
        )

    prediction_id = "320554b0-3972-4b7c-9e41-c8efdbdc042c"
    create_prediction.return_value = Response(result=prediction_id)

    s3 = boto.client("s3")
    stubber = Stubber(s3)

    stubber.add_response(
        "list_objects_v2",
        {
            "Contents": [
                {
                    "Key": "29f4dded-70be-4344-b9b5-396c8c0481cf/2023-03-07T04:14:28Z/f84639ed-7a6a-4496-81e1-b5ba8fa8b6ce/eventlog/application_1678162862227_0001"
                }
            ]
        },
        {
            "Bucket": "my-emr-projects",
            "Prefix": "29f4dded-70be-4344-b9b5-396c8c0481cf/2023-03-07T04:14:28Z/f84639ed-7a6a-4496-81e1-b5ba8fa8b6ce/eventlog/",
        },
    )

    s3_mock = Mock(wraps=s3)

    # This method cannot be stubbed like list_objects_v2
    s3_mock.generate_presigned_url.return_value = (
        "https://my-emr-projects.s3.amazonaws.com/something/something"
    )

    with stubber, patch("boto3.client") as mock_client:
        mock_client.return_value = s3_mock
        response = create_prediction_for_cluster(
            get_cluster_report.return_value.result["Cluster"]["Id"]
        )

    assert prediction_id == response.result

def test_get_cluster_report():
    with open("tests/data/emr-cluster-report.json") as emr_cluster_report_fobj:
        emr_cluster_report = orjson.loads(emr_cluster_report_fobj.read())

    cluster_id = emr_cluster_report["Cluster"]["Id"]
    region = emr_cluster_report["Region"]

    emr = boto.client("emr")
    stubber = Stubber(emr)

    describe_response = {"Cluster": emr_cluster_report["Cluster"].copy()}
    del describe_response["Cluster"]["BootstrapActions"]
    del describe_response["Cluster"]["InstanceFleets"]

    stubber.add_response("describe_cluster", describe_response, {"ClusterId": cluster_id})
    stubber.add_response(
        "list_bootstrap_actions",
        {"BootstrapActions": emr_cluster_report["Cluster"]["BootstrapActions"]},
        {"ClusterId": cluster_id},
    )
    stubber.add_response(
        "list_instance_fleets",
        {"InstanceFleets": emr_cluster_report["Cluster"]["InstanceFleets"]},
        {"ClusterId": cluster_id},
    )
    stubber.add_response(
        "list_instances", {"Instances": emr_cluster_report["Instances"]}, {"ClusterId": cluster_id}
    )
    stubber.add_response(
        "list_steps", {"Steps": emr_cluster_report["Steps"]}, {"ClusterId": cluster_id}
    )

    with stubber, patch("boto3.client") as mock_client:
        mock_client.return_value = emr
        result = get_cluster_report(cluster_id, region).result

    assert not DeepDiff(emr_cluster_report, result)

@patch("sync.awsemr.get_cluster_report")
@patch("sync.awsemr.get_project")
def test_get_project_report(get_project, get_cluster_report):
    with open("tests/data/emr-cluster-report.json") as emr_cluster_report_fobj:
        cluster_report = orjson.loads(emr_cluster_report_fobj.read())
        get_cluster_report.return_value = Response(result=cluster_report)

    get_project.return_value = Response(
        result={
            "created_at": "2023-01-20T00:38:10Z",
            "updated_at": "2023-03-10T17:18:50Z",
            "id": "4f5fe783-df74-4d64-adad-a635d6319579",
            "name": "Data Insights",
            "description": "My first project",
            "cluster_log_url": "s3://megacorp-bucket/projects/emr",
            "prediction_preference": "balanced",
        }
    )

    s3 = boto.client("s3")
    s3_stubber = Stubber(s3)

    run_timestamp = parse("2023-03-07T04:14:28Z")
    last_modified = parse("2023-03-07T05:14:28Z")
    project_id = "4f5fe783-df74-4d64-adad-a635d6319579"
    run_id = "f84639ed-7a6a-4496-81e1-b5ba8fa8b6ce"
    run_prefix = f"projects/emr/{project_id}/{run_timestamp.strftime(TIME_FORMAT)}/{run_id}"
    event_log_key = f"{run_prefix}/eventlog/application_1678162862227_0001"
    bucket = "megacorp-bucket"

    s3_stubber.add_response(
        "list_objects_v2",
        {"Contents": [{"Key": event_log_key, "LastModified": last_modified}]},
        {
            "Bucket": bucket,
            "Prefix": f"projects/emr/{project_id}/",
        },
    )
    s3_stubber.add_response(
        "put_object",
        {
            "ETag": '"14fe4f49fffffffffff9afbaaaaaaaa9"',
            "ResponseMetadata": {
                "HTTPHeaders": {
                    "content-length": "0",
                    "date": "Wed, 09 Apr 2022 " "20:35:42 GMT",
                    "etag": '"14fe4f49fffffffffff9afbaaaaaaaa9"',
                    "server": "AmazonS3",
                },
                "HTTPStatusCode": 200,
                "HostId": "GEHrJmjk76Ug/clCVUwimbmIjTTb2S4kU0lLg3Ylj8GKrAIsv5+S7AFb2cRkCLd+mpptmxfubLM=",
                "RequestId": "A8FFFFFFF84C3A77",
                "RetryAttempts": 0,
            },
            "VersionId": "Dbc0gbLVEN4N5F4oz7Hhek0Xd82Mdgyo",
        },
        {"Body": ANY, "Bucket": bucket, "Key": f"{run_prefix}/emr-cluster-report.json"},
    )

    emr = boto.client("emr")
    emr_stubber = Stubber(emr)

    cluster_id = "j-14QV64S2PV1Y2"

    emr_stubber.add_response(
        "list_clusters",
        {
            "Clusters": [
                {"Id": cluster_id, "Status": {"StateChangeReason": {"Code": "ALL_STEPS_COMPLETED"}}}
            ]
        },
        {
            "CreatedBefore": last_modified,
            "CreatedAfter": run_timestamp,
            "ClusterStates": ["TERMINATED"],
        },
    )

    emr_stubber.add_response(
        "describe_cluster",
        {"Cluster": {"Id": cluster_id, "Tags": [{"Key": "sync:run-id", "Value": run_id}]}},
        {"ClusterId": cluster_id},
    )

    def client_patch(name, **kwargs):
        if name == "s3":
            return s3
        elif name == "emr":
            return emr

    with s3_stubber, emr_stubber, patch("boto3.client") as mock_client:
        mock_client.side_effect = client_patch
        result = get_project_cluster_report(project_id).result

    assert not DeepDiff(cluster_report, result[0])
    assert f"s3://{bucket}/{event_log_key}" == result[1]


from datetime import datetime

def timer(func_name: str):
    def decorate(function):
        def wrapper(*args, **kwargs):
            start = datetime.now()
            result = function(*args, **kwargs)
            end = datetime.now()
            print(
                "function execution time: {time.seconds}s, {time.microseconds}ms".format(
                    time=end - start
                )
            )
            return result
        return wrapper
    return decorate


import numpy as np
import pandas as pd
import torch
import torch.nn as nn
from torch.utils.data import Dataset
from sklearn.metrics import (
    balanced_accuracy_score,
    accuracy_score,
    precision_score,
    recall_score,
    f1_score,
    average_precision_score,
    roc_auc_score,
)
from collections import defaultdict

class TrainData(Dataset):
    def __init__(self, X_data, y_data):
        self.X_data = X_data
        self.y_data = y_data

    def __getitem__(self, index):
        return self.X_data[index], self.y_data[index]

    def __len__(self):
        return len(self.X_data)

class ValData(Dataset):
    def __init__(self, X_data, y_data):
        self.X_data = X_data
        self.y_data = y_data

    def __getitem__(self, index):
        return self.X_data[index], self.y_data[index]

    def __len__(self):
        return len(self.X_data)

class TestData(Dataset):
    def __init__(self, X_data):
        self.X_data = X_data

    def __getitem__(self, index):
        return self.X_data[index]

    def __len__(self):
        return len(self.X_data)

class BinaryClassification(nn.Module):
    def __init__(self):
        super().__init__()
        self.layer_1 = nn.Linear(134, 670)
        self.layer_2 = nn.Linear(670, 670)
        self.layer_out = nn.Linear(670, 1)

        self.relu = nn.ReLU()
        self.dropout = nn.Dropout(p=0.1)
        self.batchnorm1 = nn.BatchNorm1d(670)
        self.batchnorm2 = nn.BatchNorm1d(670)

    def forward(self, inputs):
        x = self.relu(self.layer_1(inputs))
        x = self.batchnorm1(x)
        x = self.relu(self.layer_2(x))
        x = self.batchnorm2(x)
        x = self.dropout(x)
        x = self.layer_out(x)

        return x

def avg_precision(y_pred, y_test):

    y_pred_prob = torch.sigmoid(y_pred)
    y_pred_prob = y_pred_prob.cpu().detach().numpy()
    avg_precision = average_precision_score(y_test, y_pred_prob)

    return avg_precision

def torchclf_eval_test(
    y_test: np.ndarray, test_pred_list: np.ndarray, test_pred_labels: np.ndarray,
) -> pd.DataFrame:
    """Computes PyTorch binary classifier scikit learn metrics from the test set
    and stores them in a DataFrame"""

    scores = defaultdict(list)
    scores["Classifier"].append("PyTorch Binary Classifier")

    for metric in [
        balanced_accuracy_score,
        accuracy_score,
        precision_score,
        recall_score,
        f1_score,
        average_precision_score,
        roc_auc_score,
    ]:

        score_name = (
            metric.__name__.replace("_", " ").replace("score", "").capitalize().strip()
        )
        if score_name in ["Average precision", "Roc auc"]:

            scores[score_name].append(metric(y_test, test_pred_list))

        else:
            scores[score_name].append(metric(y_test, test_pred_labels))

    score_df = pd.DataFrame(scores).set_index("Classifier")
    score_df = score_df.round(3)

    return score_df


import functools

from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect, get_object_or_404
from images.models import ImagePost
from .models import *

# Create your views here.

def home(request):
    if not request.user.is_authenticated():
        messages.add_message(request, messages.ERROR, "请登录或注册账号", extra_tags='login')
        return redirect('/')
    postss = query_posts(1)
    return render(request, 'timeline/timeline.html', {"posts": postss, "user": request.user.myuser})

def posts(request):
    try:
        page = int(request.GET['page'])
    except:
        page = 1
    try:
        name = request.GET['name']
    except:
        name = ""
    postss = query_posts(page, name)
    return render(request, 'timeline/card.html', {"posts": postss, "user": request.user.myuser})

def photos(request):
    return render(request, 'timeline/image-card.html', {"photos": range(10)})

def comments(request):
    """
    Use GET method containing 'post-id'(ImagePost id number)
    e.g. timeline/comments?post-id=123
    :return: comments list or 404
    """
    id = request.GET['post-id']
    image_post = get_object_or_404(ImagePost, id=id)
    comments = image_post.comments
    return render(request, 'timeline/comments.html', {'comments': comments, "post": image_post})

def add_comment(request):
    """
    Use POST method containing 'post-id'(ImagePost id number), 'content'(Comment Content)
    :return: comments list or 404
    """
    if request.user.is_authenticated():
        user = request.user.myuser
        id = request.POST['post-id']
        image_post = get_object_or_404(ImagePost, id=id)
        content = request.POST['content']

        comment = Comment(user=user, content=content, image_post=image_post)
        comment.save()

        comments = image_post.comments
        return render(request, 'timeline/comments.html', {'comments': comments, "post": image_post})
    else:
        messages.add_message(request, messages.ERROR, "请登录或注册账号", extra_tags='login')
        return redirect('/')

def like(request):
    """
    Use GET method containing 'post-id'(ImagePost id number)
    e.g. timeline/like?post-id=123
    """
    id = request.GET['post-id']
    image_post = get_object_or_404(ImagePost, id=id)
    user = request.user.myuser
    user.like_images.add(image_post)
    user.save()
    return HttpResponse("OK")

def unlike(request):
    """
    Use GET method containing 'post-id'(ImagePost id number)
    e.g. timeline/unlike?post-id=123
    """
    id = request.GET['post-id']
    image_post = get_object_or_404(ImagePost, id=id)
    user = request.user.myuser
    user.like_images.remove(image_post)
    user.save()
    return HttpResponse("OK")

def tags(request):
    id = request.GET['post-id']
    image_post = get_object_or_404(ImagePost, id=id)
    tags = image_post.tags

def query_posts(page, name=""):
    return ImagePost.objects.filter(is_private=False).filter(theme__name__icontains=name).order_by('-upload_time')[page*10-10:page*10]


# Question : Given an array consisting cost of toys. Given an integer K depicting the amount
# with you. Maximise the number of toys you can have with K amount.
#
# Question Type : Easy
# Used : Sort the given array of costs. Run a loop to over them while the sum is less than K.
#        Return the value of count.
# Complexity : O(n log n)

def maxToys(costs,K):
    costs.sort()
    sum = 0
    count = 0

    for cost in costs:
        sum += cost
        if sum <= K:
            count += 1
        else:
            break

    return count

if __name__ == "__main__":
    costs = [1, 12, 5, 111, 200, 1000, 10]
    K = 50
    print("Maximum toys that can be bought are:", maxToys(costs, K))


from django.utils.translation import activate
from django.shortcuts import render

from .models import Shool, Skill, Testimonial, Work
# Create your views here.

def index(request):
    shools = Shool.objects.all()
    skills = Skill.objects.all()
    testimonials = Testimonial.objects.all()
    works = Work.objects.all()
    for work in works:
        work.duties = work.duties.all(work)

    activate("pl")
    return render(request, 'index.html', {
        "shools": shools,
        "skills": skills,
        "testimonials": testimonials,
        "works": works
    })


#Problem 5
#2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
#What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

def find_smallest_multiple(n):
    current_number = 1
    while True:
        divisible = True
        for i in range(1, n):
            if current_number % i != 0:
                divisible = False
                break
        if divisible:
            return current_number
        current_number += 1

smallest_multiple = find_smallest_multiple(10)
print(smallest_multiple)


import time
import RPi.GPIO as GPIO
from sensor_library import Distance_Sensor
import random
import sys
sensor = Distance_Sensor()
distance_list = []

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

pwmFreq = 100

GPIO.setup(18, GPIO.OUT)                # PIN 12 ON BOARD
GPIO.setup(24, GPIO.OUT)                # PIN 18 ON BOARD
GPIO.setup(23, GPIO.OUT)                # PIN 16 ON BOARD
GPIO.setup(25, GPIO.OUT)                # PIN 22 ON BOARD
GPIO.setup(22, GPIO.OUT)                # PIN 15 ON BOARD
GPIO.setup(27, GPIO.OUT)                # PIN 13 ON BOARD
GPIO.setup(17, GPIO.OUT)                # PIN 11 ON BOARD

pwma = GPIO.PWM(18, pwmFreq)
pwmb = GPIO.PWM(17, pwmFreq)
pwma.start(100)
pwmb.start(100)

def runMotor(spd, direction = 0):       # direction = 0 = CW, direction = 1 = CCW

    GPIO.output(25, GPIO.HIGH)
    in1 = GPIO.HIGH
    in2 = GPIO.LOW

    if direction == 1:
        in1 = GPIO.LOW
        in2 = GPIO.HIGH

    GPIO.output(23, in1)
    GPIO.output(24, in2)
    pwma.ChangeDutyCycle(spd)

def motorStop():
    GPIO.output(25, GPIO.LOW)

def input_data():                                                                   # gathers a data point every 0.5 seconds, appends data to list and returns list
  value = sensor.distance()
  time.sleep(0.5)
  distance_list.append(value)

  return distance_list

def average_calc(distance_list):                                                    # if list contains less then 5 values return None

  if len(distance_list) < 5:
    return None

  else:                                                                             # when list has more than 5 values, divide by the length of the list and return average rounded to 2 decimal places
    average = sum(distance_list)/len(distance_list)
    rounded = round(average,2)
    return rounded

def display_average():

  for i in range(5):
      distance_list = input_data()                                                  # get a list with most recent value from distance sensor
  rounded = average_calc(distance_list)                                             # if list contains 5 items, find rounded average. Otherwise, return None
  print("Distance (raw)\tDistance (avg)")                                           # display distance values and status of output devices to shell
  print(str(distance_list[-1])+'\t\t'+str(rounded))
  distance_list.clear()
  return rounded

def runner(ans):
  avg = display_average()
  while True:
    try:
      while avg < 200:
        try:
          runMotor(ans)
          avg = display_average()
        except KeyboardInterrupt:
          motorStop()
          sys.exit(0)
      motorStop()
      avg = display_average()
    except KeyboardInterrupt:
      sys.exit(0)

def process(rounded):

    ans = input("Which fan speed would you like? (1, 2, 3, 4, increasing, or random)\n")
    if ans == "1":
        runner(25)

    elif ans == "2":
        runner(50)

    elif ans == "3":
        runner(75)

    elif ans == "4":
        runner(100)

    elif ans == "random":
      avg = display_average()
      while True:
        try:
          while avg < 200:
            try:
              runMotor(random.randrange(0, 100))
              avg = display_average()
            except KeyboardInterrupt:
              motorStop()
              sys.exit(0)
          motorStop()
          avg = display_average()
        except KeyboardInterrupt:
          sys.exit(0)

    elif ans == "increasing":
      avg = display_average()
      while True:
        try:
          while avg < 200:
            try:
              for i in range(100):
                runMotor(i)
                time.sleep(0.1)
              avg = display_average()
            except KeyboardInterrupt:
              motorStop()
              sys.exit(0)
          motorStop()
          avg = display_average()
        except KeyboardInterrupt:
          sys.exit(0)

    else:
        print("Please enter either 1, 2, 3, 4, increasing, or random\n")

while True:
  rounded = display_average()                                                    # find 5 most recent distance values and print their average

  while rounded > 200:                                                           # if there is nothing in front of the sensor initially, do nothing (keep on getting data and printing values)
      try:
        rounded = display_average()
      except KeyboardInterrupt:
        sys.exit(0)

  process(rounded)


from django.shortcuts import render
from django.shortcuts import render, redirect
from employee.forms import EmployeeForm, ProveedoresForm
from employee.models import Employee, Proveedores

def emp(request):
    if request.method == "POST":
        form = EmployeeForm(request.POST)
        if form.is_valid():
            try:
                form.save()
                return redirect('/show')
            except:
                pass
    else:
        form = EmployeeForm()
    return render(request,'index.html',{'form':form})

def show(request):
    employees = Employee.objects.all()
    return render(request,"show.html",{'employees':employees})

def menu(request):
    employees = Employee.objects.all()
    return render(request,"menu.html",{'employees':employees})

def edit(request, id):
    employee = Employee.objects.get(id=id)
    return render(request,'edit.html', {'employee':employee})

def update(request, id):
    employee = Employee.objects.get(id=id)
    form = EmployeeForm(request.POST, instance = employee)
    if form.is_valid():
        form.save()
        return redirect("/show")
    return render(request, 'edit.html', {'employee': employee})

def destroy(request, id):
    employee = Employee.objects.get(id=id)
    employee.delete()
    return redirect("/show")

# --------------------------------------------------------------------------
def emp2(request):
    if request.method == "POST":
        form = ProveedoresForm(request.POST)
        if form.is_valid():
            try:
                form.save()
                return redirect('/shp')
            except:
                pass
    else:
        form = ProveedoresForm()
    return render(request,'regpro.html',{'form':form})

def shp(request):
    proveedor = Proveedores.objects.all()
    return render(request,"shp.html",{'proveedoress':proveedor})

def edit2(request, id):
    proveedor = Proveedores.objects.get(id=id)
    return render(request,'edit2.html', {'proveedores':proveedor})

def update2(request, id):
    proveedore = Proveedores.objects.get(id=id)
    form = ProveedoresForm(request.POST, instance = proveedore)
    if form.is_valid():
        form.save()
        return redirect("/shp")
    return render(request, 'edit2.html', {'proveedores': proveedore})

def destroy2(request, id):
    proveedor = Proveedores.objects.get(id=id)
    proveedor.delete()
    return redirect("/shp")


import socket
import _thread as thread
import time
import sys

PORT = 6789
HOST = socket.gethostbyname('localhost')

message_buffer = [] # Message Buffer
index_buffer = []   # Index Buffer which will identify which user sent the message

new_user_list = []  #New User List Buffer

connection_list=[]  #All of the connection established
connection_bool=[]  #status of the connection

left_index=[]   #All of the thread_index no that has left the chat
left_index_bool=[]  #Status of announcing left members
username_list=[]    #All of the username joined in the chat

'''---------------------- Helper functions --------------------'''
def left_chat(this_index):  # Function to identify if "this_index" has left the chat
    global left_index
    for loc in left_index:
        if this_index==loc:
            return True
    return False

def broadcastAll(): # Function to broadcast all messages in the buffer to all users in the connection
    global message_buffer
    global index_buffer
    global connection_list

    iterator = 0    # Iterator to go through all of the index_buffer, one by one, correlated to the message buffer index
    for msg in message_buffer:  # For every message left in the message_buffer list
        conn_index=0    #Connection index
        if msg:
            msg = "<"+username_list[index_buffer[iterator]]+">: "+msg   # Append the nickname infront of the message
        for conn in connection_list:  # Iterate through all of the connection
            if not left_chat(conn_index):   # If this connection hasn't left the group chat
                if conn_index!=index_buffer[iterator]:
                    # Check if we need to send to this connection, i.e. if its the user that sent the "msg, no need to send"
                    if msg:
                        conn.send(msg.encode('utf-8'))
            conn_index+=1
        iterator+=1

    # Empty out all of the buffer and index
    message_buffer.clear()
    index_buffer.clear()

def broadcastAllNew(name):  # Function to broadcast "welcome message" to about a new member to all members connected in the chat
    global connection_list

    if name:
        name +=  " has just joined the chat!"
    conn_index = 0
    for conn in connection_list:    # Iterate through all connections
        if not left_chat(conn_index):   # check if this connection hasn't left the group chat
            if name:
                conn.send(name.encode('utf-8'))
        conn_index+=1

def left_broadcast_done():  # See if broadcasting of all of the members who have left is done
    global left_index
    global left_index_bool

    for i in range(len(left_index)):
        if not left_index_bool[i]:
            return False
    return True

def broadcastLeft(this_index):  # Broadcast that "this_index" user has left the chat to all of the members connected in the chat
    global username_list
    global connection_list

    left_username = username_list[this_index]
    message = left_username + " has left the chat!"
    conn_index = 0
    for conn in connection_list:
        if conn_index!= this_index and not left_chat(conn_index):
            conn.send(message.encode('utf-8'))
        conn_index+=1

'''----------------- Main Handlers here --------------------'''
def broadcast_handler():    # Broadcast_thread Function handler
    # this will be a function/thread that will be running all the time once this program starts
    global message_buffer
    global left_index_bool
    global left_index
    global new_user_list

    while True:
        while len(new_user_list)!=0:    # Check if any new members joined the chat, in the new_members buffer
            broadcastAllNew(new_user_list.pop(0))

        if len(message_buffer)>0:   # Check if there is any message left in the message buffer
            broadcastAll()

        if not left_broadcast_done():   # If not all of the members that have left's notice hasn't been broadcasted
            for i in range(len(left_index)):
                if left_index_bool[i] is False:  #If haven't broadcasted, then broadcast
                    broadcastLeft(left_index[i])
                    left_index_bool[i]=True

def handle_client(conn,loc_index):  # Client_threads function handler
    global message_buffer
    global index_buffer
    global left_index
    global left_index_bool
    global connection_bool
    global username_list
    global new_user_list

    loc_message = ''

    #Local Variables
    joined = False  # identify for new clients
    end_handler = False # boolean variable to end the thread

    while True:
        if end_handler or not connection_bool[loc_index]:   # End the infinite loop in this thread
            print(username_list[loc_index],'is exiting the group chat!')
            break

        try:
            loc_message = conn.recv(1024).decode('utf-8')   #Get the new message
            if joined:
                print ("Recevied message from ",username_list[loc_index], " saying ", loc_message)

            if loc_message == "exit":   # If client wants to exit the chat
                print(username_list[loc_index],'is exiting the group chat!')
                end_handler = True  # Make this infinite loop in this client to quit
                connection_bool[loc_index]=False    # Clarify that this connection has been closed
                left_index.append(loc_index)    # Append this client's index into the left_index list
                left_index_bool.append(False)   # Append that this client's left group chat message HAS NOT been broadcasted
                print('loc message:',loc_message,' index:',loc_index, ' end_handler:',end_handler)
                continue

            if not joined: # New member joined, append his name to the new member list buffer and continue
                username_list.append(loc_message)
                new_user_list.append(loc_message)
                joined=True
                continue

            if not end_handler: # As long as this infinite loop isn't ready to be closed yet
                message_buffer.append(loc_message)  # Append the message to the message buffer
                index_buffer.append(loc_index)      # Append the client_index to the index buffer
                time.sleep(0)
        except:
            continue

    # Close the connection in this thread and end the thread
    print('connection closed with ', username_list[loc_index])
    conn.shutdown(1)
    conn.close()
    sys.exit()

# Initialise the serverSocket
serverSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
serverSocket.bind((HOST,PORT))
serverSocket.listen()
print("Server has started listening...")

#Start a broadcasting_thread
thread.start_new_thread(broadcast_handler,())

thread_index = 0

while True:
    #Accepts the new connection and get its info
    connectionSocket, addr = serverSocket.accept()
    print('Connected by', addr[0],':',addr[1], " thread index: ",thread_index)

    #Some Connection info
    connection_list.append(connectionSocket)
    connection_bool.append(True)

    #Start the client thread
    thread.start_new_thread(handle_client,(connectionSocket,thread_index))

    #Increment the thread index
    thread_index+=1

serverSocket.close()


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Tweet',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('author_handle', models.CharField(max_length=15, verbose_name=b"twitter handle of this tweet's author")),
                ('is_retweet', models.BooleanField(default=False, verbose_name=b'is this a retweet?')),
                ('body', models.CharField(max_length=255, null=True, verbose_name=b'', blank=True)),
                ('date_published', models.DateTimeField(null=True, verbose_name=b'date published')),
            ],
        ),
        migrations.CreateModel(
            name='TweetFavorite',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('favorited_by_handle', models.CharField(max_length=15, verbose_name=b'twitter handle of person who favorited this tweet')),
                ('date_favorited', models.DateTimeField(null=True, verbose_name=b'date favorited')),
                ('tweet_id', models.ForeignKey(verbose_name=b'we vote tweet id', blank=True, to='twitter.Tweet', null=True)),
            ],
        ),
        migrations.CreateModel(
            name='TwitterUser',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('handle', models.CharField(unique=True, max_length=15, verbose_name=b'twitter handle')),
                ('fullname', models.CharField(max_length=80, null=True, verbose_name=b'full name of twitter user', blank=True)),
                ('is_group', models.BooleanField(default=False, verbose_name=b'is this a twitter group account')),
                ('user_url', models.URLField(null=True, verbose_name=b"url of user's website", blank=True)),
                ('bio_statement', models.CharField(max_length=255, null=True, verbose_name=b'bio for user', blank=True)),
                ('icon_url', models.URLField(null=True, verbose_name=b"url of user's profile icon", blank=True)),
            ],
        ),
        migrations.CreateModel(
            name='TwitterWhoFollowMe',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('handle_of_me', models.CharField(max_length=15, verbose_name=b"from this twitter handle's perspective...")),
                ('handle_that_follows_me', models.CharField(max_length=15, verbose_name=b"twitter handle of this tweet's author")),
            ],
        ),
        migrations.CreateModel(
            name='TwitterWhoIFollow',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('handle_of_me', models.CharField(max_length=15, verbose_name=b"from this twitter handle's perspective...")),
                ('handle_i_follow', models.CharField(max_length=15, verbose_name=b'twitter handle being followed')),
            ],
        ),
    ]


import sys

if len(sys.argv) != 3:
    raise Exception("Incorrect usage. Correct usage: python slie.py function-file params-file")

fFilename = str(sys.argv[1])
pFilename = str(sys.argv[2])
f = open(fFilename, 'r')
p = open(pFilename, 'r')

lines = p.readlines()
ranges = []
count = 0
oFilename = fFilename
for line in lines:
    if not line:
        raise Exception("Empty line found in filei: " + pFilename)

    words = line.split()
    if len(words) !=2:
        raise Exception("Only two values per row (hi and low) allowed in the params file")

    if count >=3:
            raise Exception("Only three rows, one for each direction, allowed in the params file")

    x = [0.,0.]
    x[0] = float(words[0])
    x[1] = float(words[1])
    ranges.append(x)
    oFilename += "_" + words[0] + "_" + words[1]
    count += 1

print(ranges)

lines = f.readlines()
data =[]
for line in lines:
    if not line:
        raise Exception("Empty line found in filei: " + fFilename)

    words = line.split()
    rowData = []
    for w in words:
        rowData.append(float(w))

    data.append(rowData)

N = len(data)
o = open(oFilename,'w')
for i in range(N):
    rowData = data[i]
    keep = True
    for j in range(3):
        if data[i][j] < ranges[j][0] or data[i][j] > ranges[j][1]:
            keep = False
            break

    if keep:
      M = len(rowData)
      for j in range(M):
        print(rowData[j], end = " ", file = o)

      print(file = o)

p.close()
f.close()
o.close()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar  4 11:25:57 2019

@author: Santosh,Sahil
"""
import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report

def sigmoid(t):
    return 1 / (1 + np.exp(-t))

def sigmoid_derivative(s):
    return s * (1 - s)

def softmax(z):
    exp_z = np.exp(z)
    softmax_scores = exp_z / np.sum(exp_z, axis=1, keepdims=True)
    return softmax_scores

def softmax_to_y(softmax_scores):
    return np.argmax(softmax_scores, axis=1)

def reLU(x):
    return x * (x > 0)

def reLU_derivative(x):
    return 1. * (x > 0)

def error_rate(y_pred, y_test):
    m = y_pred.shape[0]
    return np.sum(1 - (y_pred == y_test)) / m

def plot_decision_boundary(model, X, y):
    x1_array, x2_array = np.meshgrid(np.arange(-10, 10, 0.01), np.arange(-10, 10, 0.01))
    grid_coordinates = np.c_[x1_array.ravel(), x2_array.ravel()]
    Z = model.predict(grid_coordinates)
    Z = Z.reshape(x1_array.shape)
    plt.contourf(x1_array, x2_array, Z, cmap=plt.cm.bwr)
    plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.bwr)
    plt.show()

class NN(object):

    def __init__(self, input_dimension, output_dimension, nodes, alpha=0.1, num_epochs=1000):
        # weights
        self.input_weight = np.random.randn(input_dimension, nodes) / np.sqrt(input_dimension)
        self.hidden_weight = np.random.randn(nodes, output_dimension) / np.sqrt(nodes)

        # bias
        self.input_bias = np.zeros((1, nodes))
        self.output_bias = np.zeros((1, output_dimension))
        self.alpha = alpha
        self.epochs = num_epochs

    def hyperparameters(self, alpha, epochs):
        self.alpha = alpha
        self.epochs = epochs

    def forward_propagation(self, X):
        # dot product of X (input) and first set
        self.hidden = reLU(np.dot(X, self.input_weight) + self.input_bias)
        # dot product of hidden layer and second set
        self.output = softmax(np.dot(self.hidden, self.hidden_weight) + self.output_bias)
        return self.output

    def backward_propagation(self, X, y):
        d = X.shape[0]
        one_hot_y = np.zeros_like(self.output)
        for i in range(y.shape[0]):
            one_hot_y[i, y[i]] = 1

        self.o_error = self.output - one_hot_
        self.o_delta = self.o_error

        # error: how much hidden layer weights contributed to output error
        self.hid_error = self.o_delta.dot(self.hidden_weight.T)

        # applying derivative of reLu to hidden error
        self.hid_delta = self.hid_error * reLU_derivative(self.hidden)

        w2 = self.hidden.T.dot( self.o_delta) / d
        b2 = np.sum(self.o_delta, axis=0, keepdims=True) / d
        w1 = X.T.dot( self.hid_delta) / d
        b1 = np.sum(self.hid_delta, axis=0, keepdims=True) / d

        # Return updated gradients
        values = { "w1": w1,
                    "b1": b1,
                   "w2": w2,
                "b2": b2}
        return values

    # Updates the weights after calculating gradient in the self propagation step
    def update_weight(self, grads):
        self.input_bias -= self.alpha * grads["b1"]
        self.output_bias -= self.alpha * grads["b2"]
        self.input_weight -= self.alpha * grads["w1"]
        self.hidden_weight -= self.alpha * grads["w2"]

    # Computes the cross entropy between the actual and predicted values
    def compute_cost(self, o_z, y):
        m = y.shape[0]
        log_likelihood = -np.log(o_z[range(m), y])
        loss = np.sum(log_likelihood) / m
        return loss

    # Fits the neural network using the training dataset
    # Returns the training error for every 10th epoch
    def fit(self, X_train, y_train):
        train_error = [0.5]
        for i in range(self.epochs):
            output = self.forward_propagation(X_train)
            grads = self.backward_propagation(X=X_train, y=y_train)
            self.update_weight(grads)
            if (i % 10 == 0):
                # hot_y = softmax_to_y(output)
                train_error += [self.compute_cost(output, y_train)]
        return train_error

    # Fits the neural network using the training dataset,
    # calculates train as well as test error rate alongside
    def fit_test_train(self, X_train, y_train, X_test, y_test):
        train_error = []
        test_error = []
        for i in range(self.epochs):
            output_train = self.forward_propagation(X_train)
            grads = self.backward_propagation(X=X_train, y=y_train)
            self.update_weight(grads)
            if (i % 10 == 0):
                train_error += [self.compute_cost(output_train, y_train)]
                output_test = self.forward_propagation(X_test)
                test_error += [self.compute_cost(output_test, y_test)]
        error = [None] * 2
        error[0] = train_error
        error[1] = test_error
        return error

    def predict(self, X_test):
        output = self.forward_propagation(X_test)
        return softmax_to_y(output)

def k_fold(X, y, k, nn):
    X = np.array_split(X, k)
    y = np.array_split(y, k)

    test_error = [None] * k

    for i in range(k):
        b = 0
        for j in range(k):
            if j == i:
                X_test = X[i]
                y_test = y[i]
            else:
                if b == 0:
                    X_train = X[j]
                    y_train = y[j]
                    b += 1
                else:
                    X_train = np.concatenate([X_train, X[i]])
                    y_train = np.concatenate([y_train, y[i]])
        nn.fit(X_train, y_train)
        y_pred = nn.predict(X_test)
        test_error[i] = error_rate(y_pred, y_test)
    return np.sum(test_error) / (k + 1)

class regularizationL2(NN):

    def __init__(self, input_dimension, nodes, output_dimension, alpha=0.5, num_epochs=1000, reg_para=0.001):
        self.reg = reg_para
        super().__init__(input_dimension, nodes, output_dimension, alpha, num_epochs)

    def hyperparameter(self, alpha, num_epochs, reg_para):
        self.alpha = alpha
        self.num_epochs = num_epochs
        self.reg = reg_para

    def update_weight(self, grads):
        # Adding derivative of regularization term
        self.input_bias -= self.reg * self.input_bias
        self.output_bias -= self.reg * self.output_bias
        self.input_weight -= self.reg * self.input_weight
        self.hidden_weight -= self.reg * self.hidden_weight

        self.input_bias -= self.alpha * grads["b1"]
        self.output_bias -= self.alpha * grads["b2"]
        self.input_weight -= self.alpha * grads["w1"]
        self.hidden_weight -= self.alpha * grads["w2"]

def linear():
    X = np.genfromtxt('DATA/data_linearX.csv', delimiter=',')
    y = np.genfromtxt('DATA/data_lineary.csv', delimiter=',').astype(np.int64)
    plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.bwr)
    plt.show()

    X, X_test, y, y_test = train_test_split(X, y, test_size=0.2)
    input_dim = int(X.shape[1])
    output_dim = int(y.max() + 1)
    nodes = 10

    nn = NN(input_dim, nodes, output_dim, alpha=0.05, num_epochs=500)
    train_err = nn.fit(X, y)

    y_pred = nn.predict(X_test)

    err = error_rate(y_pred, y_test)
    print("Error in test set is ", err * 100, "%")

    plt.plot(train_err)
    plt.title("Cross Entropy with respect to Epochs")
    plt.xlabel("Number of Epochs (factor of 10)")
    plt.ylabel("Cross Entropy")
    plt.show()

    # Even though the cross entropy is not minimized,
    # our system is able to distinguish the red points from the blue points easily
    # Plotting decision boundary
    plot_decision_boundary(nn, X_test, y_test)

    # Confusion matrix
    print("Confusion Matrix \n")
    print(confusion_matrix(y_pred, y_test))
    print(classification_report(y_pred, y_test))

    X = np.genfromtxt('DATA/data_linearX.csv', delimiter=',')
    y = np.genfromtxt('DATA/data_lineary.csv', delimiter=',').astype(np.int64)
    test_error = k_fold(X, y, 5, nn)
    print("Average test error is :", test_error)

def non_linear():
    X = np.genfromtxt('DATA/data_nonlinearX.csv', delimiter=',')
    y = np.genfromtxt('DATA/data_nonlineary.csv', delimiter=',').astype(np.int64)
    plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.bwr)
    plt.show()
    X, X_test, y, y_test = train_test_split(X, y, test_size=0.2)
    input_dim = int(X.shape[1])
    output_dim = int(y.max() + 1)
    nodes = 30

    nn = NN(input_dim, nodes, output_dim, alpha=0.5, num_epochs=2500)
    train_err = nn.fit(X, y)

    y_pred = nn.predict(X_test)

    err = error_rate(y_pred, y_test)
    print("Error in test set is ", err * 100, "%")

    plt.plot(train_err)
    plt.title("Cross Entropy with respect to Epochs")
    plt.xlabel("Number of Epochs (factor of 10)")
    plt.ylabel("Cross Entropy")
    plt.show()

    # Even though the cross entropy is not minimized,
    # our system is able to distinguish the red points from the blue points easily
    # Plotting decision boundary
    plot_decision_boundary(nn, X_test, y_test)

    # Confusion matrix
    print("Confusion Matrix \n")
    print(confusion_matrix(y_pred, y_test))
    print(classification_report(y_pred, y_test))

    # Cross Validation score for the linear dataset
    X = np.genfromtxt('DATA/data_nonlinearX.csv', delimiter=',')
    y = np.genfromtxt('DATA/data_nonlineary.csv', delimiter=',').astype(np.int64)
    test_error = k_fold(X, y, 5, nn)
    print("Average test error is :", test_error)

    # Script for checking the test and train error
    X = np.genfromtxt('DATA/data_nonlinearX.csv', delimiter=',')
    y = np.genfromtxt('DATA/data_nonlineary.csv', delimiter=',').astype(np.int64)
    input_dim = int(X.shape[1])
    output_dim = int(y.max() + 1)

    nodes = 30

    nn = NN(input_dim, nodes, output_dim, alpha=0.05, num_epochs=500)
    X_train, X_test, y_train, y_test = train_test_split(X, y)
    err = nn.fit_test_train(X_train, y_train, X_test, y_test)

    train_err = err[0]
    test_err = err[1]

    plt.plot(train_err)
    plt.plot(test_err)
    plt.legend(('Train', 'Test'))
    plt.show()

def l2Regularization():
    X = np.genfromtxt('DATA/data_nonlinearX.csv', delimiter=',')
    y = np.genfromtxt('DATA/data_nonlineary.csv', delimiter=',').astype(np.int64)
    plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.bwr)
    plt.show()
    X, X_test, y, y_test = train_test_split(X, y, test_size=0.2)
    input_dim = int(X.shape[1])
    output_dim = int(y.max() + 1)
    nodes = 30
    nn = regularizationL2(input_dim, nodes, output_dim, alpha=0.1, num_epochs=2500)
    X_train, X_test, y_train, y_test = train_test_split(X, y)
    err = nn.fit_test_train(X_train, y_train, X_test, y_test)

    train_err = err[0]
    test_err = err[1]

    plt.plot(train_err)
    plt.plot(test_err)
    plt.show()

def digitTraining():
    X = np.genfromtxt('DATA/Digit_X_train.csv', delimiter=',')
    y = np.genfromtxt('DATA/Digit_y_train.csv', delimiter=',').astype(np.int64)
    input_dim = int(X.shape[1])
    output_dim = int(y.max() + 1)
    nodes = 30

    nn = NN(input_dim, nodes, output_dim, alpha=0.05, num_epochs=2500)
    train_err = nn.fit(X, y)
    train_err.pop(0)

    X_test = np.genfromtxt('DATA/Digit_X_test.csv', delimiter=',')
    y_test = np.genfromtxt('DATA/Digit_y_test.csv', delimiter=',').astype(np.int64)

    y_pred = nn.predict(X_test)

    err = error_rate(y_pred, y_test)
    print(err)

    plt.plot(train_err)
    # plt.plot(test_err)
    plt.show()

    nn = regularizationL2(input_dim, nodes, output_dim, alpha=0.1, num_epochs=2500)
    X_train, X_test, y_train, y_test = train_test_split(X, y)
    err = nn.fit_test_train(X_train, y_train, X_test, y_test)

    train_err = err[0]
    test_err = err[1]
    plt.plot(train_err)
    plt.plot(test_err)
    plt.show()

def main():
    print('Non-linear:\n')
    non_linear()
    print('Linear:\n')
    linear()
    print('Regularized:\n')
    l2Regularization()
    print('Digit:\n')
    digitTraining()

if __name__ == "__main__":
    main()


from matplotlib import pyplot as plt

#Se definen los valores obtenidos mediante solucion de la ec. dif
c1 = -3; c2 = 1
#se define el intervalo
x = [-2,-1,0,1,2]

#arreglo o lista donde se guardara los datos obtenidos en "y"
valores = []

#se crea encabezado de tabla
print("|\tx\t|\ty")

#se crea el iterable
for n in x:
    #sustitucion de valores en la ecuacion
    y = -3+(n)+(1/12)*n**(4)+(1/2)*n**(2)
    g = (str(y))
    g = (g[0:10])
    g = float(g)

    #se agregan los resultados de "y" en el arreglo o lista
    valores.append(g)

    #se imprime tabla
    print("|\t",n,"\t|",y)

print(valores)

#se crea grafica
plt.plot(x,valores,'c-o')
#etiqueta de ejes
plt.xlabel("eje X")
plt.ylabel("eje Y")
#titulo
plt.title(r'$y=-3+x+\frac{1}{12}x^{4}+\frac{1}{2}x^{2}$')
plt.grid(True)
plt.axhline(0,color='r',lw=1)
plt.axvline(0,color='r',lw=1)
plt.show()


# Hayoung Nam
# CH4 Sales Tax Calculator
# June 18 2020
# Create a program that uses a seperate module to calculates sales tax and total after tax

print ("Sales Tax Calculator")

def getItems ():

    print ()

    print ("ENTER ITEMS (ENTER 0 TO END)")

    print ()

    total = 0

    while True:

        cost = float (input ("Cost of item: "))

        if cost == 0:

            break

        total += cost

    return total

def calculations (total):

    """

    Calculates sales tax

    """

    rate = 6

    salesTax = (rate/100) * total

    totalwithTax = salesTax + total

    return salesTax, totalwithTax

def printResult(total):

    salesTax, totalwithTax = calculations (total)

    total = round (total, 2)

    salesTax = round (salesTax, 2)

    totalwithTax = round (totalwithTax, 2)

    print ("Total:\t", total)

    print ("Sales Tax: ", salesTax)

    print ("Total after tax: ", totalwithTax)

def main ():

    choice = "y"

    while choice.lower() == "y":

        total = getItems ()

        printResult(total)

        print()

        choice = input ("Again? (y/n) :")

    print ()

    print ("Thanks, bye!")

if __name__ == "__main__":

    main()


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

class product_class:
    def __init__(self,root):
        self.root = root
        self.root.geometry("1020x540+240+105")
        self.root.title("Product Master")
        self.root.config (bg="white")
        self.root.focus_force()
#===============================================================================================================================================
        self.var_product_id=StringVar()
        self.var_product_Name=StringVar()
        self.var_rate=StringVar()
#=================================================================================================================================================
        title=Label(self.root,text="Product Master",font=("arial",30,"bold")).place(x=0,y=0,relwidth=1,height=60)

        lbl_product_id=Label(self.root,text="Product ID",font=("Times New Roman",15),bg="pink").place(x=10,y=70,width=150,height=30)
        lbl_product_Name=Label(self.root,text="Product Name",font=("Times New Roman",15),bg="pink").place(x=10,y=120,width=150,height=30)
        lbl_rate=Label(self.root,text="Rate",font=("Times New Roman",15),bg="pink").place(x=10,y=170,width=150,height=30)

        txt_product_id=Entry(self.root,textvariable=self.var_product_id,font=("Times New Roman",15),bg="white").place(x=170,y=70,width=150,height=30)
        txt_product_name=Entry(self.root,textvariable=self.var_product_Name,font=("Times New Roman",15),bg="white").place(x=170,y=120,width=150,height=30)
        txt_rate=Entry(self.root,textvariable=self.var_rate,font=("Times New Roman",15),bg="white").place(x=170,y=170,width=150,height=30)

        btn_add=Button(self.root,text="Add",command=self.add,font=("arial",15),cursor="hand2").place(x=20,y=455,width=140,height=30)
        btn_update=Button(self.root,text="Update",command=self.update,font=("arial",15),cursor="hand2").place(x=170,y=455,width=140,height=30)
        btn_delete=Button(self.root,text="Delete",command=self.delete,font=("arial",15),cursor="hand2").place(x=20,y=495,width=140,height=30)
        btn_clear=Button(self.root,text="Clear",command=self.clear,font=("arial",15),cursor="hand2").place(x=170,y=495,width=140,height=30)
#=====================Tree View===============================================================================================================
        self.producttable=ttk.Treeview(self.root,columns=("product_ID","product_Name","Rate"))
        self.producttable.place(x=330,y=70,width=675,height=460)

        self.producttable.heading("product_ID",text="Product ID")
        self.producttable.heading("product_Name",text="Name")
        self.producttable.heading("Rate",text="Rate")
        self.producttable["show"]="headings"

        self.producttable.column("product_ID",width=80)
        self.producttable.column("product_Name",width=80)
        self.producttable.column("Rate",width=80)
        self.producttable.bind("<ButtonRelease-1>",self.get_data)

        self.show()

#============================================================================================================================================

    def add(self):
        con=sqlite3.connect(database=r'oms.db')
        cur = con.cursor()
        try:
            if self.var_product_id.get()=="" or self.var_product_Name.get()=="" or self.var_product_id.get()=="" or self.var_rate.get()=="":
                messagebox.showerror("Error","All fields required required",parent=self.root)
            elif self.var_rate.get().isnumeric()==False:
               messagebox.showerror("Error","Rate must contain numbers only",parent=self.root)
            elif int(self.var_rate.get())<=0:
                messagebox.showerror("Error","Rate should be greater than 0",parent=self.root)
            elif self.var_product_id.get().isnumeric()==False:
                messagebox.showerror("Error","Product ID must contain numbers only",parent=self.root)
            else:
                cur.execute("Select * from product where product_ID=?",(self.var_product_id.get(),))
                row=cur.fetchone()
                if row!=None:
                    messagebox.showerror("Error","The ID has been assigned, try different ID",parent=self.root)
                else:
                    cur.execute("Insert into product (product_ID,product_Name,Rate) values(?,Upper(?),?)",(self.var_product_id.get(),self.var_product_Name.get(),self.var_rate.get(),))
                    con.commit()
                    messagebox.showinfo("Success","Added Successfully",parent=self.root)
                    self.show()
                    self.clear()
        except Exception as ex:
            if str(ex)=="UNIQUE constraint failed: product.product_Name":
                messagebox.showerror("Error","Product Name already exists",parent=self.root)
            else:
                messagebox.showerror("Error",f"Error due to: {str(ex)}",parent=self.root)

    def update(self):
        con=sqlite3.connect(database=r'oms.db')
        cur = con.cursor()
        try:
            if self.var_product_id.get()=="":
                messagebox.showerror("Error","Product ID must be required",parent=self.root)
            elif int(self.var_rate.get())<=0:
                messagebox.showerror("Error","Rate should be greater than 0",parent=self.root)
            elif self.var_rate.get().isnumeric()==False:
                messagebox.showerror("Error","Rate must contain numbers only",parent=self.root)
            elif self.var_product_id.get().isnumeric()==False:
                messagebox.showerror("Error","Product ID must contain numbers only",parent=self.root)
            else:
                cur.execute("Select * from product where product_ID=?",(self.var_product_id.get(),))
                row=cur.fetchone()
                if row==None:
                    messagebox.showerror("Error","Invalid ID",parent=self.root)
                else:
                    cur.execute("Update product set product_Name=upper(?),Rate=? where product_ID=?",(self.var_product_Name.get(),self.var_rate.get(),self.var_product_id.get(),))
                    con.commit()
                    messagebox.showinfo("Success","Updated Successfully",parent=self.root)
                    self.show()
                    self.clear()

        except Exception as ex:
            if str(ex)=="UNIQUE constraint failed: product.product_Name":
                messagebox.showerror("Error","Product Name already exists",parent=self.root)
            else:
                messagebox.showerror("Error",f"Error due to: {str(ex)}",parent=self.root)

    def delete(self):
        con=sqlite3.connect(database=r'oms.db')
        cur = con.cursor()
        cur1 = con.cursor()
        try:
            cur1.execute("Select count(*) from order_det where product_Name=?",(self.var_product_Name.get(),))
            row1 = cur1.fetchone()
            if row1[0]>0:
                messagebox.showerror("Error","Product is in orders - Cannot delete")
            else:
                if self.var_product_id.get()=="":
                    messagebox.showerror("Error","Invalid Product ID",parent=self.root)
                else:
                    cur.execute("Select * from product where product_ID=?",(self.var_product_id.get(),))
                    row=cur.fetchone()
                    if row==None:
                        messagebox.showerror("Error","Invalid Product ID",parent=self.root)
                    else:
                        op=messagebox.askyesno("Confirm","Do you really want to delete?",parent=self.root)
                        if op==True:
                            cur.execute("delete from product where product_ID=?",(self.var_product_id.get(),))
                            con.commit()
                            messagebox.showinfo("Delete","Deleted Successfully",parent=self.root)
                            self.show()
                            self.clear()
        except Exception as ex:
            messagebox.showerror("Error",f"Error due to: {str(ex)}",parent=self.root)

    def clear(self):
        self.var_product_id.set("")
        self.var_product_Name.set("")
        self.var_rate.set("")
        self.show()

    def show(self):
        con=sqlite3.connect(database=r'oms.db')
        cur=con.cursor()
        try:
            cur.execute("select * from product")
            rows=cur.fetchall()
            self.producttable.delete(*self.producttable.get_children())
            for row in rows:
                self.producttable.insert('',END,values=row)

        except Exception as ex:
            messagebox.showerror("Error",f"Error due to: {str(ex)}",parent=self.root)

    def get_data(self,ev):
        f=self.producttable.focus()
        content=(self.producttable.item(f))
        row=content['values']
        #print(row)
        self.var_product_id.set(row[0])
        self.var_product_Name.set(row[1])
        self.var_rate.set(row[2])

if __name__=="__main__":
    root=Tk()
    obj=product_class(root)
    root.mainloop()


from django.urls import path
# from django.views.decorators.cache import cache_page

from .views import NarrativeListView, NarrativeView, SearchView, NarrativeListTag, SearchAllView

urlpatterns = [
    path('tag/<int:tid>/', NarrativeListTag.as_view(), name='tag-detail'),
    path('search/', SearchAllView.as_view(), name='search'),
    path('<slug:category>/search/', SearchView.as_view(), name='search-category'),
    path('<slug:category>/', NarrativeListView.as_view(), name='category-detail'),
    path('<slug:slug>/', NarrativeView.as_view(), name='narrative-detail'),
    path('<slug:category>/<slug:slug>/', NarrativeView.as_view(), name='narrative-detail'),
]


from os.path import dirname, join
from setuptools import setup, find_packages

with open(join(dirname(__file__), 'scrapy_httpcache/VERSION'), 'rb') as f:
    version = f.read().decode('ascii').strip()

setup(
    name='scrapy-httpcache',
    version=version,
    url='https://github.com/nyov/scrapy-httpcache',
    description='Scrapy extension to cache HTTP Requests and Responses',
    author='Scrapy developers',
    license='BSD',
    packages=find_packages(exclude=('tests', 'tests.*')),
    include_package_data=True,
    zip_safe=False,
    classifiers=[
        'Framework :: Scrapy',
        'Development Status :: 5 - Production/Stable',
        'Environment :: Console',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 3',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ],
    install_requires=[
        'Scrapy>=1.0.0',
        'six',
    ],
)


"""
练习
从客户端输入一个学生的id 姓名 年龄 分数
将其发送到服务端，有服务端写入到一个文件
每个信息占一行
数据传输使用udp套接字完成
                        服务端
"""
from socket import *
import struct

sockfd = socket(AF_INET, SOCK_DGRAM)
sockfd.bind(("0.0.0.0", 44474))
# 确定数据结构
st = struct.Struct("i32sif")
# 打开文件
fd = open("student.txt", "a+")
while True:
    data, addr = sockfd.recvfrom(1024)
    # 数据解析
    data = st.unpack(data)
    info = "%d %s %d %.2f\n" % (data[0],
                                data[1].decode(),
                                data[2],
                                data[3])
    fd.write(info)

fd.close()
sockfd.close()


#%%
import requests
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np

# %%
def get_round_value(year, mon, day):
    year = str(year)
    mon = str(mon).rjust(2, '0')
    day = str(day).rjust(2, '0')
    url = 'https://okbfex.kbstar.com/quics'
    params = {
    'chgCompId' : 'b028286',
    'baseCompId' : 'b028286',
    'page' : 'C015690',
    'cc' : 'b028286:b028286'
    }
    data = {
        '조회년월일':year+mon+day,
        '등록회차' : '1',
        'selDate' : year+mon+day,
        'strFocusBtn' : '조회',
        'year1' : year,
        'mon1' : mon,
        'day1' : day,
        'se_inqueryRound' : '1'
    }
    response = requests.post(url, params=params, data=data)
    soup = BeautifulSoup(response.content, 'html.parser')
    round_value = soup.find('option')['value']
    return round_value

# %%
def get_exchange_rate(year, mon, day, round_value):
    year = str(year)
    mon = str(mon).rjust(2, '0')
    day = str(day).rjust(2, '0')
    url = 'https://okbfex.kbstar.com/quics'
    params = {
    'chgCompId' : 'b028286',
    'baseCompId' : 'b028286',
    'page' : 'C015690',
    'cc' : 'b028286:b028286'
    }
    data = {
        '조회년월일':year+mon+day,
        '등록회차' : round_value,
        'selDate' : year+mon+day,
        'strFocusBtn' : '조회',
        'year1' : year,
        'mon1' : mon,
        'day1' : day,
        'se_inqueryRound' : round_value
    }
    response = requests.post(url, params=params, data=data)
    soup = BeautifulSoup(response.content, 'html.parser')
    try:
        aud = soup.select('#AllDsp1 > tr:nth-child(7) > td:nth-child(2)')[0].get_text()
        chf = soup.select('#AllDsp1 > tr:nth-child(5) > td:nth-child(2)')[0].get_text()
        cny = soup.select('#AllDsp1 > tr:nth-child(10) > td:nth-child(2)')[0].get_text()
        eur = soup.select('#AllDsp1 > tr:nth-child(3) > td:nth-child(2)')[0].get_text()
        hkd = soup.select('#AllDsp1 > tr:nth-child(9) > td:nth-child(2)')[0].get_text()
        jpy = soup.select('#AllDsp1 > tr:nth-child(2) > td:nth-child(2)')[0].get_text()
        usd = soup.select('#AllDsp1 > tr:nth-child(1) > td:nth-child(2)')[0].get_text()
    except:
        aud = np.nan
        chf = np.nan
        cny = np.nan
        eur = np.nan
        hkd = np.nan
        jpy = np.nan
        usd = np.nan
    result_dic = {
        'date' : year+mon+day,
        'AUD' : aud,
        'CHF' : chf,
        'CNY' : cny,
        'EUR' : eur,
        'HKD' : hkd,
        'JPY' : jpy,
        'USD' : usd
    }
    return result_dic

#%%
result_list = []
year = 2020
for mon in range(1, 4):
    for day in range(1, 32):
        round_value = get_round_value(year, mon, day)
        result_dic = get_exchange_rate(year, mon, day, round_value)
        result_list.append(result_dic)
        print(str(year)+str(mon).rjust(2, '0')+str(day).rjust(2, '0')+' 완료')
result_df = pd.DataFrame(result_list)
result_df.to_csv(r'c:\Users\ksfc\Downloads\kb_exchange_rate.csv', index=False)


#!/usr/bin/python3
"""Island Perimeter Problem
"""

# how to compute island perimeter?
# 1. iterate over the grid
# 2. if we find a 1, we check the 4 sides
# 3. if the side is 0 or the side is out of the grid, we add 1 to the perimeter
# 4. return the perimeter
def island_perimeter(grid):
    """Calculates the perimeter of the island described in grid

    Args:
        grid (list): 2d list of integers containing 0(water) or 1(land)
    Return:
        the perimeter of the island
    """
    perimeter = 0
    for i in range(len(grid)):
        for j in range(len(grid[i])):
            if grid[i][j] == 1:
                if i == 0 or grid[i - 1][j] == 0:
                    perimeter += 1
                if i == len(grid) - 1 or grid[i + 1][j] == 0:
                    perimeter += 1
                if j == 0 or grid[i][j - 1] == 0:
                    perimeter += 1
                if j == len(grid[i]) - 1 or grid[i][j + 1] == 0:
                    perimeter += 1

    return perimeter


from django.core.management.base import BaseCommand, CommandError
import pandas as pd
from pathlib import Path
from ...models import Product, Author, RarityType

class Command(BaseCommand):
    help = 'Populates the database with some initial data'

    def handle(self, *args, **options):

        print("Starting Acme NFT population script...")

        # ----------------------------- Load NFTs -----------------------------

        def get_rarity(price, stock, mean):

            index = price/stock

            normaliced_index = index / mean

            if normaliced_index < 0.5:
                return RarityType.common
            elif normaliced_index < 1:
                return RarityType.rare
            elif normaliced_index < 1.5:
                return RarityType.epic
            elif normaliced_index < 2:
                return RarityType.legendary
            elif normaliced_index >= 2:
                return RarityType.mythic

        path = Path(__file__).parent / "../../static/dataset/dataset.csv"

        datos = pd.read_csv(path, sep=",", header=0, names=["title", "name", "creator", "art_series", "price", "symbol", "type", "likes", "nsfw", "tokens", "year" , "rights", "royalty", "cid", "path"])

        mean_price_per_stock = (datos["price"]/datos["tokens"]).mean()

        for index, row in datos.iterrows():

            # Find or create the author
            try:
                author = Author.objects.get(name=row["creator"])
            except Author.DoesNotExist:
                author = Author(name=row["creator"])
                author.save()

            rarity = get_rarity(float(row["price"]), int(row["tokens"]), mean_price_per_stock)
            showcase = rarity == RarityType.mythic or rarity == RarityType.legendary
            # Create and save the product
            product = Product(name=row["name"], collection=row["title"], price=float(row["price"]), stock=int(row["tokens"]), image_url=row["path"].replace("./", ""), offer_price=None, rarity=rarity, author=author, showcase=showcase)
            product.save()

        print("Done! Your product database is now populated with some initial data.")


from RPi import GPIO
from time import sleep
import time
#import keyboard

# P - Power Pin, D - Directional Pin
motor1Dir = 2;
motor1PWM = 3;
clk1 = 14;
dt1 = 15;

motor2Dir = 17;
motor2PWM = 27;
clk2 = 23;
dt2 = 24;

motor3Dir = 9;
motor3PWM = 10;
clk3 = 8;
dt3 = 7;

motor4Dir = 5;
motor4PWM = 6;
clk4 = 20;
dt4 = 21;

GPIO.setmode(GPIO.BCM);

GPIO.setup(motor1PWM, GPIO.OUT);
GPIO.setup(motor1Dir, GPIO.OUT);
GPIO.setup(motor2PWM, GPIO.OUT);
GPIO.setup(motor2Dir, GPIO.OUT);
GPIO.setup(motor3PWM, GPIO.OUT);
GPIO.setup(motor3Dir, GPIO.OUT);
GPIO.setup(motor4PWM, GPIO.OUT);
GPIO.setup(motor4Dir, GPIO.OUT);

GPIO.setup(clk1, GPIO.IN, pull_up_down=GPIO.PUD_DOWN);
GPIO.setup(dt1, GPIO.IN, pull_up_down=GPIO.PUD_DOWN);
GPIO.setup(clk2, GPIO.IN, pull_up_down=GPIO.PUD_DOWN);
GPIO.setup(dt2, GPIO.IN, pull_up_down=GPIO.PUD_DOWN);
GPIO.setup(clk3, GPIO.IN, pull_up_down=GPIO.PUD_DOWN);
GPIO.setup(dt3, GPIO.IN, pull_up_down=GPIO.PUD_DOWN);
GPIO.setup(clk4, GPIO.IN, pull_up_down=GPIO.PUD_DOWN);
GPIO.setup(dt4, GPIO.IN, pull_up_down=GPIO.PUD_DOWN);

# Give full power to motor
GPIO.output(motor1PWM, GPIO.HIGH);
GPIO.output(motor1Dir, GPIO.HIGH);

GPIO.output(motor2PWM, GPIO.HIGH);
GPIO.output(motor2Dir, GPIO.HIGH);

GPIO.output(motor3PWM, GPIO.HIGH);
GPIO.output(motor3Dir, GPIO.HIGH);

GPIO.output(motor4PWM, GPIO.HIGH);
GPIO.output(motor4Dir, GPIO.HIGH);

global encoderVal, encoderPPM, storedTime, currTime, shaftRPM, gearboxRPM
storedTime = [-1, -1, -1, -1]
encoderVal = [0, 0, 0, 0]
encoderPPM = 11
shaftRPM = [0, 0, 0, 0]
gearboxRPM = [0, 0, 0, 0]

def encoderInit(channel):
	global encoderVal, encoderPPM, storedTime, currTime, shaftRPM, gearboxRPM
	encoderVal[0]=encoderVal[0]+1;
	currTime = time.time()
	#print("Pulse!")

	if storedTime[0] == -1:
		storedTime[0] = time.time()
	else:
		timeDiff = currTime - storedTime[0]
		storedTime[0] = currTime
		timeFactor = 60/timeDiff

		shaftRPM[0] = encoderVal[0]*timeFactor / encoderPPM;
		gearboxRPM[0] = shaftRPM[0]/40

		encoderVal[0] = 0

GPIO.add_event_detect(dt1,GPIO.RISING, callback=encoderInit)

interval = 1
try:
	while True:
		if shaftRPM[0] != 0 and gearboxRPM[0] != 0:
			print("Gearbox RPM:",gearboxRPM[0]," | Shaft RPM:",shaftRPM[0])

except KeyboardInterrupt:          # trap a CTRL+C keyboard interrupt
	GPIO.cleanup()                 # resets all GPIO ports used by this program


from django.urls import path,include
from . import views
from .views import *
from rest_framework_simplejwt.views import (
    TokenRefreshView,
)
from rest_framework import routers

router = routers.DefaultRouter()
router.register(r'products', ProductViewSet, basename='product')
router.register(r'cart', CartViewSet, basename='cart')

urlpatterns = [
    path('', views.getRoutes),
    path('register/', UserRegisterCreateAPIView.as_view(), name='apiregister'),
    path('token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
    path('mycart/<int:user_id>/', CartProductsViewSet.as_view(), name='mycart'),
    path('send_order_email/', sendEmail.as_view(), name='send_order_email'),

    path('', include(router.urls)),
]


"""

Main script for reading in images and parsing
out clusters based on passed in parameters

"""

#import the various cluster scripts
from cluster.geotag import parse_geotag_clusters
from cluster.color import parse_color_clusters
from cluster.date import parse_date_clusters
from cluster.tag import parse_tag_clusters

def parse_clusters(args, photos):
    """
    Parse out clusters based on the passed in arguments

    args: The parsin arguments to use
    photos: The photo array

    NOTE: args need to still be decided on
    """

    #here will have information to determine what kind of clusters are returned
    #for now just parses out geoTag information
    clusters = []

    #has additional information for geotag clustering
    if args is 'geotag':
        return parse_geotag_clusters(photos)
    elif args is 'color':
        clusters = parse_color_clusters(photos)
    elif args is'tag':
        clusters = parse_tag_clusters(photos)
    elif args is 'date':
        clusters = parse_date_clusters(photos)
    else:
        return None

    return clusters

if __name__ == "__main__":
    """
    for testing purposes
    """

    """
    image_arr = os.listdir(IMAGES_FOLDER)
    if image_arr[0].endswith('.jpg'):
        print True
    """
    parse_clusters(None)


from time import sleep
from os import get_terminal_size
from random import *
from colorama import *
from termcolor import *
from UIV1 import *

init()
print(Fore.BLUE + '')

# Initialize Player Class

class Player(object):
    base_health = 100
    base_damage = 3
    base_defense = 3
    base_regen_per_turn = 3
    base_magic_damage = 1
    base_mana = 10
    name = 'Gerald Lagley'
    inventory = {
    }
    room_number = '0'
    equipped = {
        'weapon': {
            'fist': {
                'name': 'Fist',
                'desc': 'Your fist, a very trusty weapon.',
                'value': 'You wouldn\'t sell your own body would you',
                'equippable': True,
                'type': 'weapon',
                'perks': {
                    'health': 0,
                    'damage': 3,
                    'defense': 0,
                    'magic_damage': 0,
                },
                'amount': 1,
            }
        },
        'armor': {
            'clothes': {
                'name': 'Clothes',
                'desc': 'A reliable set of cotton clothes. Not very strong but keeps you warm.',
                'value': 20,
                'equippable': True,
                'type': 'armor',
                'perks': {
                    'health': 0,
                    'damage': 0,
                    'defense': 3,
                    'magic_damage': 0,
                },
                'amount': 1,
            }
        },
        'ring': {
            'wedding ring': {
                'name': 'Wedding Ring',
                'desc': 'A ring given to you by your wife on your wedding day.',
                'value': 100,
                'equippable': True,
                'type': 'ring',
                'perks': {
                    'health': 2,
                    'damage': 2,
                    'defense': 2,
                    'magic_damage': 3,
                },
                'amount': 1,
            }
        },
        'amulet': {
            'silver locket': {
                'name': 'Silver Locket',
                'desc': 'A family heirloom containing pictures of your children.',
                'value': 75,
                'equippable': True,
                'type': 'amulet',
                'perks': {
                    'health': 1,
                    'damage': 1,
                    'defense': 0,
                    'magic_damage': 4,
                    'regen': 3,
                    'mana': 2,
                },
                'amount': 1,
            }
        }
    }
    current_weapon = 'fist'
    current_armor = 'clothes'
    current_ring = 'wedding ring'
    current_amulet = 'silver locket'
    gold = 500

    def __init__(self):
        self.room_number = '0'
        self.command = 'null'
        self.health = self.base_health
        self.damage = self.base_damage
        self.defense = self.base_defense
        self.magic_damage = self.base_magic_damage
        self.regen_per_turn = self.base_regen_per_turn
        self.regen_per_turn += self.equipped['amulet'][self.current_amulet]['perks']['regen']
        self.mana = self.base_mana
        self.room = room[self.room_number]
        self.min_damage = self.base_damage
        for i in self.equipped:
            for j in self.equipped[i]:
                try:
                    self.health += self.equipped[i][j]['perks']['health']
                    self.defense += self.equipped[i][j]['perks']['defense']
                    self.damage += self.equipped[i][j]['perks']['damage']
                    self.magic_damage += self.equipped[i][j]['perks']['magic_damage']
                    self.mana += self.equipped[i][j]['perks']['mana']
                    self.current_health = self.health
                    self.current_mana = self.mana
                    self.max_damage = self.damage
                    self.min_damage -= self.equipped[i][j]['perks']['damage']
                except KeyError:
                    print('I done goofed')

    def name_set(self):
        if input('Do you wish to set your name: ') == 'y' or 'Y':
            self.name = input('Please enter your name: ')
            print("Your name is " + self.name)
        else:
            print('Your name is ' + self.name)

    def move(self, direction):
        try:
            self.room_number = room[self.room_number]['directions'][direction.lower()]
            self.room = room[self.room_number]
            sleep(1)
            if self.room['environment'] == 'Temple':
                print('You walk forward through the white marble doorway and into the ' + room[self.room['directions'][direction.lower()]['name']])
            else:
                print('You move 1 room ' + direction)
        except KeyError:
            print('Please enter a valid direction')
            return False

    def examine(self, item):
        try:
            print('You look around and find a ' + room[self.room_number]['items'][item]['name'] + ' lying on the floor')
            print('The object is ' + room[self.room_number]['items'][item]['desc'])
            print('You ascertain its value to be roughly ' + str(room[self.room_number]['items'][item]['value']) + colored(' gold', 'yellow'))
        except KeyError:
            print('You look everywhere but fail to find a ' + str(item))

    def look(self):
        try:
            if room[self.room_number]['environment'] == 'Temple':
                print('A polished, marble plaque reads ' + room[self.room_number]['name'])
            else:
                print('Name: ' + room[self.room_number]['name'])
        except SyntaxError:
            print('Error: Syntax Error')
        print('You see ')
        for i in room[self.room_number]['items']:
            try:
                print(room[self.room_number]['items'][i]['name'])
            except KeyError:
                print('KeyError')

    def pickup(self, item):
        if item.lower() == 'all':
            conf = input('Do you want to pick up all of the items in this room: ')
            if conf.lower() == 'y' or conf.lower() == 'yes':
                for item in room[self.room_number]['items']:
                    try:
                        self.inventory[item] = room[self.room_number]['items'][item]
                        del room[self.room_number]['items'][item]
                    except KeyError:
                        print('You look everywhere but can\'t find anything to pick up.')
        elif item.lower() == 'gold':
            conf = input('Do you want to pick up the coins on the floor: ')
            if conf.lower() == 'y' or conf.lower() == 'yes':
                try:
                    self.gold += room[self.room_number]['gold']
                    room[self.room_number]['gold'] -= room[self.room_number]['gold']
                except KeyError:
                    if self.room['environment'] == 'Temple':
                        print('You look carefully around the gleaming marble room,', end='')
                        print('thoroughly checking every corner, but fail to find any coins.')
                    else:
                        print('You look everwhere but fail to find any coins (environment not defined)')
        else:
            conf = input('Do you want to pick up the ' + item.lower() + ': ')
            if conf.lower() == 'y' or conf.lower() == 'yes':
                try:
                    self.inventory[item] = room[self.room_number]['items'][item]
                    del room[self.room_number]['items'][item]
                except KeyError:
                    print('You look everywhere but can\'t find a ' + item.lower())
            else:
                print('You consider it, but decide not to pick up the ' + item.lower())

    def input(self, command):
        self.command = command
        if str(self.command) == 'move':
            self.move(input(colored('Please enter a direction: ', 'green')))
        elif str(self.command) == 'look':
            self.look()
        elif str(self.command) == 'pickup':
            print(colored('The items you can pick up are: ', 'green'))
            colored(self.list_items(), 'blue')
            self.pickup(input(colored('What do you want to pick up: ', 'green')))
        else:
            print('Derher')

    def list_items(self):
        for i in room[self.room_number]['items']:
            try:
                print(Fore.BLUE + room[self.room_number]['items'][i]['name'])
            except KeyError:
                print('KeyError')

    def stats(self):
        self.health = self.base_health
        self.defense = self.base_defense
        self.damage = self.base_damage
        self.magic_damage = self.base_magic_damage
        self.regen_per_turn = self.base_regen_per_turn
        self.regen_per_turn += self.equipped['amulet'][self.current_amulet]['perks']['regen']
        for i in self.equipped:
            for j in self.equipped[i]:
                try:
                    self.health += self.equipped[i][j]['perks']['health']
                    self.defense += self.equipped[i][j]['perks']['defense']
                    self.damage += self.equipped[i][j]['perks']['damage']
                    self.magic_damage += self.equipped[i][j]['perks']['magic_damage']
                except KeyError:
                    print('I done goofed')

    def equip(self, item):
        if item.lower() in self.inventory:
            item_type = self.inventory[item]['type']
            for i in self.equipped[item_type]:
                self.inventory[i] = self.equipped[item_type][i]
            self.equipped[item_type].clear()
            self.equipped[item_type][item] = self.inventory[item]
            del self.inventory[item]
            self.stats()
        else:
            print('You rummage through your bag but can\'t find a ' + item + '.')

# Initialize rooms

room = {
    '0': {
        'name': 'Temple Atrium',
        'items': {
            'wooden stick': {
                'name': 'Wooden Stick',
                'desc': 'a wooden stick, could be useful',
                'value': 0,
                'equippable': True,
                'type': 'weapon',
                'perks': {
                    'health': 0,
                    'damage': 6,
                    'defense': 0,
                    'magic_damage': 0,
                },
            },
        },
        'desc': 'Insert desc here',
        'entry_info': 'Insert desc here',
        'directions': {
            'n': '1000',
        },
        'environment': 'Temple',
        'hostile': False,
    },
    '1000': {
        'name': 'Temple Antechamber',
        'items': {

        },
        'desc': 'Insert desc here',
        'entry_info': 'Insert entry info here',
        'directions': {
            'n': '2000',
            'e': '1010',
            'w': '990',
            's': '0'
        },
        'environment': 'Temple',
        'hostile': True,
    },
    '2000': {
        'name': 'Temple Hallway',
        'items': {

        },
        'desc': 'Insert desc here',
        'entry_info': 'Insert entry info here',
        'directions': {

        },
    },
}

# Create player with Player() class

player = Player()


"""
This module represents the Producer.

Computer Systems Architecture Course
Assignment 1
March 2020
"""

from threading import Thread
from time import sleep

class Producer(Thread):
    """
    Class that represents a producer.
    """

    def __init__(self, products, marketplace, republish_wait_time, **kwargs):
        """
        Constructor.

        @type products: List()
        @param products: a list of products that the producer will produce

        @type marketplace: Marketplace
        @param marketplace: a reference to the marketplace

        @type republish_wait_time: Time
        @param republish_wait_time: the number of seconds that a producer must
        wait until the marketplace becomes available

        @type kwargs:
        @param kwargs: other arguments that are passed to the Thread's __init__()

        Other attributes
        type producer_id: Int
        param producer_id: the id of the producer
        """
        Thread.__init__(self, **kwargs)
        self.products = products
        self.marketplace = marketplace
        self.republish_wait_time = republish_wait_time
        self.producer_id = -1 # initial dummy value

    def run(self):
        # register the producer (get his id)
        self.producer_id = self.marketplace.register_producer()

        while 1:
            for product, quantity, produce_time in  self.products:
                # the amount that has been produced for the current product
                produced_quantity = 0
                # semaphore for checking if the current product has been produced but not published
                produced = False

                while produced_quantity < quantity:
                    # the semaphore is acquired here so that the producer
                    # can wait the production time
                    self.marketplace.producers_locks[self.producer_id].acquire()
                    if not produced:
                        sleep(produce_time)
                    published = self.marketplace.publish(self.producer_id, product)
                    self.marketplace.producers_locks[self.producer_id].release()

                    if published:
                        # the product has benn published, we can produce the next product
                        produced_quantity += 1
                        produced = False
                    else:
                        # the product has been produced, but not published
                        produced = True
                        sleep(self.republish_wait_time)