import streamlit as st
import numpy as np
import cv2
import pandas as pd

# ********************

def main():
    st.title('Recognition App')
    st.sidebar.title('Parameters')
    st.sidebar.markdown('Choose Parameters')
    st.subheader('Choose What You want to Identify')
    a = st.selectbox("Choose Option", ("Face", "Smile", "Eyes"))

    if a == 'Face':
        b = st.sidebar.button(
            'Capture Images For Face Recognition 🧔', key='capface')
        if b:
            face_model = cv2.CascadeClassifier(
                'C:/Users/kevka/Documents/Streamlit/HaarCascadeFace.xml')
            cap = cv2.VideoCapture(0)
            while True:
                status, photo = cap.read()
                face_cor = face_model.detectMultiScale(photo)
                if len(face_cor) == 0:
                    pass
                else:
                    x1 = face_cor[0][0]
                    y1 = face_cor[0][1]
                    x2 = x1+face_cor[0][2]
                    y2 = y1+face_cor[0][3]
                    photo = cv2.rectangle(
                        photo, (x1, y1), (x2, y2), [0, 255, 0])
                    cv2.putText(photo, "Hey Kevin", (250, 450),
                                cv2.FONT_HERSHEY_COMPLEX, 1, (0, 255, 0), 2)
                    cv2.imshow('Look At You', photo)
                    if cv2.waitKey(10) == 13:
                        break
            cv2.destroyAllWindows()
            cap.release()
        st.sidebar.markdown('To Stop, Press Enter')

    if a == 'Smile':
        c = st.sidebar.button(
            'Capture Images For Smile Recognition 😁', key='capnose')
        if c:
            smile_model = cv2.CascadeClassifier(
                'C:/Users/kevka/Documents/Streamlit/HaarCascadeSmile.xml')
            cap = cv2.VideoCapture(0)
            while True:
                status, photos = cap.read()
                smile_cor = smile_model.detectMultiScale(photos)
                if len(smile_cor) == 0:
                    pass
                else:
                    x1 = smile_cor[0][0]
                    y1 = smile_cor[0][1]
                    x2 = x1+smile_cor[0][2]
                    y2 = y1+smile_cor[0][3]
                    photos = cv2.rectangle(
                        photos, (x1, y1), (x2, y2), [0, 255, 0])
                    cv2.putText(photos, "Hey Kevin's Smile", (250, 450),
                                cv2.FONT_HERSHEY_COMPLEX, 1, (0, 255, 0), 2)
                    cv2.imshow('Look At Your Smile', photos)
                    if cv2.waitKey(10) == 13:
                        break
            cv2.destroyAllWindows()
            cap.release()
        st.sidebar.markdown('To Stop, Press Enter')

    if a == 'Eyes':
        d = st.sidebar.button(
            'Capture Images For Eyes Recognition 👀', key='capeyes')
        if d:
            eyes_model = cv2.CascadeClassifier(
                'C:/Users/kevka/Documents/Streamlit/HaarCascadeEyes.xml')
            cap = cv2.VideoCapture(0)
            while True:
                status, photoe = cap.read()
                eyes_cor = eyes_model.detectMultiScale(photoe)
                if len(eyes_cor) == 0:
                    pass
                else:
                    x1 = eyes_cor[0][0]
                    y1 = eyes_cor[0][1]
                    x2 = x1+eyes_cor[0][2]
                    y2 = y1+eyes_cor[0][3]
                    photoe = cv2.rectangle(
                        photoe, (x1, y1), (x2, y2), [0, 255, 0])
                    cv2.putText(photoe, "Hey Kevin's Eyes", (250, 450),
                                cv2.FONT_HERSHEY_TRIPLEX, 1, (0, 255, 0), 2)
                    cv2.imshow('Look At Your Eyes', photoe)
                    if cv2.waitKey(10) == 13:
                        break
            cv2.destroyAllWindows()
            cap.release()
        st.sidebar.markdown('To Stop, Press Enter')

if __name__ == '__main__':
    main()


from .AICNet import SSC_RGBD_AICNet
import torch.nn as nn
import torch
from .MLP import LocalDecoder
from collections import OrderedDict
from .DDRNet import SSC_RGBD_DDRNet
import os
import torch.nn.functional as F
import numpy as np
class RichSSC(nn.Module):
    def __init__(self, cls=12, basic_module="aic", mlp_layers=5, pretrain_encode=None, use_cls=True, args=None):
        super(RichSSC, self).__init__()
        if basic_module == "aic":
            self.encoding = SSC_RGBD_AICNet()
            out_feature = 256
        elif basic_module == "ddr":
            self.encoding = SSC_RGBD_DDRNet()
            out_feature = 320
        else:
            raise NotImplementedError
        self.use_cls = use_cls
        if use_cls:
            out_feature = out_feature + cls

        self.decoding = LocalDecoder(cls=cls, c_dim=out_feature, n_blocks=mlp_layers)

        self.pretrain_encode = pretrain_encode
        if pretrain_encode is not None:
            self.load_pretrain(args)

    def load_pretrain(self, args=None):
        if os.path.exists(self.pretrain_encode):
            param = torch.load(self.pretrain_encode)
            new_state_dict = OrderedDict()
            for k, v in param["state_dict"].items():
                if k[:7] == "module.":
                    if args.dataset == "nyu": # uncareful to accidently pacakged DDRNet and AICNet in "embedding" when training on NYU dataset
                        name = k[17: ]
                    else:
                        name = k[7:]
                    new_state_dict[name] = v
                else:
                    if args.dataset == "nyu": # uncareful to accidently pacakged DDRNet and AICNet in "embedding" when training on NYU dataset
                        k = k[10: ]
                    new_state_dict[k] = v
            self.encoding.load_state_dict(new_state_dict, strict=True)

    def fx(self, p, c):
        p_nor = p[:, :, None, None].float()

        cf = F.grid_sample(c, p_nor, padding_mode='border', align_corners=True, mode="bilinear").squeeze(
            -1).squeeze(-1)
        return cf.transpose(1, 2)

    def decoding_split_mode(self, test_points, c_feature, batch_test=102400):
        num_points = test_points.shape[1]
        iters = int(num_points / batch_test)
        pred = []
        with torch.no_grad():
            for i in range(iters):
                points = test_points[:, i * batch_test:(i + 1) * batch_test, :]
                out = self.decoding(points, self.fx(points, c_feature))
                pred.append(out)

            if iters * batch_test < num_points:
                points = test_points[:, iters * batch_test:, :]
                out = self.decoding(points, self.fx(points, c_feature))
                pred.append(out)
        return torch.cat(pred, dim=1)

    def forward_test(self, query_points, c_feature, sample_mode="center"):
        if sample_mode == 'center':
            b, pn, c = query_points.shape
            if pn < 102400:
                return self.decoding(query_points, self.fx(query_points, c_feature))
            else:
                return self.decoding_split_mode(query_points, c_feature)
        elif sample_mode == "vote":
            b, pn, en, c = query_points.shape
            query_points = query_points.reshape((b, -1, c))
            if pn * en <= 102400:
                query_condition = self.fx(query_points, c_feature)
                out = self.decoding(query_points, query_condition)
            else:
                out = self.decoding_split_mode(query_points, c_feature)

            out = out.cpu().detach().numpy()
            prediction = out.reshape((b, pn, en, -1))
            prediction = np.argmax(prediction, axis=3).reshape((b * pn, en))
            new_pred = []
            for i in range(len(prediction)):
                '''
                label = np.argmax(np.bincount(prediction[i]))
                one_hot = np.zeros(12)
                one_hot[label] = 1
                new_pred.append(one_hot)

                    isFloor = np.count_nonzero(np.where(pred==2)) > 0
                    isCeil = np.count_nonzero(np.where(pred==1)) > 0
                    if isFloor:
                        one_hot[2] = 1
                    elif isCeil:
                        one_hot[1] = 1
                    else:
                '''

                pred = prediction[i] # [en] stores each point's class label

                empty_space_point_num = en - np.count_nonzero(pred)
                if empty_space_point_num > en * 0.6:
                    one_hot = np.zeros(12)
                    one_hot[0] = 1
                else:
                    one_hot = np.zeros(12)
                    label = np.argmax(np.bincount(pred[np.where(pred!=0)]))
                    one_hot[label] = 1
                new_pred.append(one_hot)
            new_pred = np.array(new_pred)
            new_pred = torch.from_numpy(new_pred).reshape((b, pn, -1)).cuda()
            return new_pred

            #out = out.reshape((b, pn, en, -1))
            #out = out.sum(dim=2)

        elif sample_mode == "avg":
            b, pn, en, c = query_points.shape
            query_points = query_points.reshape((b, -1, c))
            query_condition = self.fx(query_points, c_feature)
            query_condition = query_condition.reshape((b, pn, en, -1))
            query_condition = query_condition.mean(dim=2)

            query_points = query_points.reshape((b, pn, en, -1))
            query_points = query_points.mean(dim=2)
            try:
                out = self.decoding(query_points, query_condition)
            except:
                out = self.decoding_split_mode(query_points, query_condition)
            return out

    def forward(self, x_depth=None, x_rgb=None, p=None, query_points=None, return_en_res=False, isTest=False, sample_mode="center"):
        feature, pre_cls_score = self.encoding(x_depth=x_depth, x_rgb=x_rgb, p=p)
        if self.use_cls:
            c_feature = torch.cat([feature, pre_cls_score], dim=1)
        else:
            c_feature = feature

        if isTest:
            out = self.forward_test(query_points, c_feature, sample_mode=sample_mode)
        else:
            out = self.decoding(query_points, self.fx(query_points, c_feature))
        if return_en_res:
            return out, pre_cls_score
        else:
            return out

    def get_trainable_parameters(self, lr_decode=1e-4, finetune_encode=False, lr_encode=1e-4):
        params = [
            {"params": self.decoding.parameters(), "lr": lr_decode}
        ]
        if finetune_encode:
            params.append({
                "params": self.encoding.parameters(), "lr": lr_encode
            })
        else:
            for k, v in self.encoding.named_parameters():
                v.requires_grad = False

        return params


from bs4 import BeautifulSoup
import requests
url = "http://www.saramin.co.kr/zf_user/jobs/list/job-category?exp_cd=1&edu_min=8&edu_max=11&cat_cd=404&panel_type=&search_optional_item=y&search_done=y&panel_count=y"
url2= "http://www.saramin.co.kr/zf_user/jobs/list/job-category?exp_cd=1&edu_min=8&edu_max=11&cat_cd=407&panel_type=&search_optional_item=y&search_done=y&panel_count=y"
url3= "http://www.saramin.co.kr/zf_user/jobs/list/job-category?cat_cd=404%2C407&exp_cd=1&edu_min=8&edu_max=11&panel_type=&search_optional_item=y&search_done=y&panel_count=y"
response = requests.get(url)
html = BeautifulSoup(response.text,'html.parser')

'''
company = html.select('.part_top')
for com in company:
    name = com.select_one('.company_name')
    rec = com.select_one('.recruit_name')
    cond  = com.select_one('.list_recruit_condition')
    print(f'{name.text} :: {rec.text} -{cond.text}')
    break
'''
company_list = html.select('ul.product_list li')
for com in company_list:
    company_info_url =f"http://www.saramin.co.kr{com.select_one('a')['href']}"
    idx = company_info_url.split('=')[-1]
    company_info_url = 'http://www.saramin.co.kr/zf_user/jobs/relay/view-ajax'
    company_info_param = { 'rec_idx':idx }
    company_response = requests.post(company_info_url, params = company_info_param)
    company_html = BeautifulSoup(company_response.text,'html.parser')
    company_title = company_html.select_one('.company_name').text
    print(company_title.strip())
    break
#사람인 나머지 데이터 파싱 !?
#다음 웹툰 일요일 첫번째 웹툰 상세페이지 크롤링


from typing import Tuple

import albumentations as A

__all__ = ["CoarseDropout"]

class CoarseDropout(A.CoarseDropout):
    def _keypoint_in_hole(self, keypoint: Tuple, hole: Tuple) -> bool:
        x1, y1, x2, y2 = hole
        x, y = keypoint[:2]
        return x1 <= x < x2 and y1 <= y < y2

    def apply_to_keypoints(self, keypoints, holes=(), **params):
        for hole in holes:
            remaining_keypoints = []
            for kp in keypoints:
                if not self._keypoint_in_hole(kp, hole):
                    remaining_keypoints.append(kp)
            keypoints = remaining_keypoints
        return keypoints

def main():
    from matplotlib import pyplot as plt
    import cv2
    import numpy as np

    t = A.Compose(
        [CoarseDropout(p=1, min_width=32, min_height=32, max_width=128, max_height=128)],
        keypoint_params=A.KeypointParams(format="xy", label_fields=["labels"]),
    )

    # image = np.zeros((256, 256, 3), dtype=np.uint8)
    image = cv2.imread("lena.png")[..., ::-1].copy()
    # image[::10, :] = 255
    # image[::35, :] = 255
    # image[::51, :] = 255
    # image[:, ::11] = 255
    # image[:, ::24] = 255
    # image[:, ::45] = 255

    kpts = []
    for x in range(20, 512, 20):
        for y in range(20, 512, 20):
            kpts.append((x, y))

    for k in kpts:
        image = cv2.circle(image, k, radius=3, color=(0, 200, 0), thickness=2, lineType=cv2.LINE_AA)

    data = t(image=image, keypoints=kpts, labels=np.zeros(len(kpts)))
    print(kpts)
    print(data["keypoints"])

    for k in data["keypoints"]:
        data["image"] = cv2.circle(
            data["image"],
            tuple(map(int, k[:2])),
            radius=2,
            color=(200, 0, 200),
            thickness=2,
            lineType=cv2.LINE_AA,
        )

    f, ax = plt.subplots(2, 1, figsize=(6, 12))
    ax[0].imshow(image)
    ax[1].imshow(data["image"])
    f.tight_layout()
    f.show()

if __name__ == "__main__":
    main()


import math

tax_percent = 0
income = int(input())

tax_ranges = [
    (0, 15527, 0),
    (15528, 42707, 0.15),
    (42708, 132406, 0.25),
    (132407, math.inf, 0.28)
    ]

percent = next(tax_percent for min_income, max_income, tax_percent in tax_ranges if min_income <= income <= max_income)

calculated_tax = income * percent
display_percent = 100 * percent

print("The tax for {} is {}%. That is {} dollars!".format(income, (round(display_percent)), round(calculated_tax)))


import pandas as pd

# Define chunk size for reading large files
chunk_size = 10000  # Adjust this based on your system's memory

# Define file paths
file1 = 'descriptors2.csv'
file2 = 'filtered_descriptors.csv'
output_file = 'combined_descriptors.csv'

# Read the first file entirely
df1 = pd.read_csv(file1, header=None, chunksize=chunk_size)
df_combined = pd.concat(df1, ignore_index=True)

# Function to filter rows based on ID condition
def filter_rows(df_chunk):
    return df_chunk[df_chunk.iloc[:, 0] > 12858]

# Read the second file in chunks and filter
df2 = pd.read_csv(file2, header=None, chunksize=chunk_size)
filtered_chunks = [filter_rows(chunk) for chunk in df2]

# Combine filtered data from the second file
df_filtered = pd.concat(filtered_chunks, ignore_index=True)

# Combine both dataframes
final_df = pd.concat([df_combined, df_filtered], ignore_index=True)

# Save the combined dataframe to a new CSV file
final_df.to_csv(output_file, index=False, header=False)


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

def matrix_composed_history(history):
    fig = plt.figure(figsize=plt.figaspect(0.5))
    ax = fig.add_subplot(211, projection='3d')
    ax_two = fig.add_subplot(212, projection='3d')

    a_one = [x for x in history if x[1] == 0]
    a_two = [x for x in history if x[1] == 1]

    surf1 = ax.plot_trisurf([s1[0][0][0] for s1 in a_one], [s2[0][0][1] for s2 in a_one], [g[2] for g in a_one],
                            cmap=plt.cm.jet)
    surf2 = ax_two.plot_trisurf([s1[0][1][0] for s1 in a_two], [s2[0][1][1] for s2 in a_two], [g[2] for g in a_two],
                                cmap=plt.cm.jet)

    ax.set_xlabel('State 1')
    ax.set_ylabel('State 2')
    ax.set_zlabel('Reward')
    ax.set_title("Action 1")

    ax_two.set_xlabel('State 1')
    ax_two.set_ylabel('State 2')
    ax_two.set_zlabel('Reward')
    ax_two.set_title("Action 2")

    fig.colorbar(surf1, ax=ax)
    fig.colorbar(surf2, ax=ax_two)

    plt.show()


#!/usr/bin/env python2
import auxiliar as ax
import math

def perplexity(entropy):
	return 2 ** entropy

def freq_count(corpus_dict):
	n_gram_sum = 0
	for word, word_freq in corpus_dict.iteritems():
		n_gram_sum += word_freq
	return n_gram_sum

# P(x)
def prob_x(uni_gram_list, freq_x):
	dict_prob_x = {}
	for word, word_freq in uni_gram_list.iteritems():
		dict_prob_x[word] = 1.0 * (word_freq) / freq_x
	return dict_prob_x

def uni_entropy(uni_gram_prob_dict):
	H = 0
	for word, word_prob in uni_gram_prob_dict.iteritems():
		H += word_prob * math.log(word_prob, 2)
	return -1 * H

# P(y|x)
def prob_yx(bi_gram_list, uni_gram_list):
	dict_prob_yx = {}
	for bi_word, bi_word_freq in bi_gram_list.iteritems():
		dict_prob_yx[bi_word] = 1.0 * bi_word_freq / uni_gram_list[bi_word[0]]
	return dict_prob_yx

def bi_entropy(bi_gram_prob_list, uni_gram_prob_list):
	H = 0
	for word, word_prob in bi_gram_prob_list.iteritems():
		H += uni_gram_prob_list[word[0]] * word_prob * math.log(word_prob, 2)
	return -1 * H

# P(z|xy)
def prob_zxy(tri_gram_list, bi_gram_list):
	dict_prob_zxy ={}
	for (x,y,z) , tri_word_freq in tri_gram_list.iteritems():
		dict_prob_zxy[x,y,z] = 1.0 * tri_word_freq / bi_gram_list[x,y]
	return dict_prob_zxy

def tri_entropy(tri_gram_prob_list, bi_gram_prob_list, uni_gram_prob_list):
	H = 0
	for (x,y,z), word_prob in tri_gram_prob_list.iteritems():
		H += uni_gram_prob_list[x] * bi_gram_prob_list[x,y] * word_prob * math.log(word_prob, 2)
	return -1 * H

def entropy(word_list, flag = 0):
	if flag == 0:
		U,B,T = ax.countNgrams(word_list, 0)
	else:
		U,B,T = word_list

	freq_uni = freq_count(U)
	uni_prob = prob_x(U, freq_uni)
	h_uni_gram = uni_entropy(uni_prob)

	bi_prob = prob_yx(B, U)
	h_bi_gram =  bi_entropy(bi_prob, uni_prob)

	tri_prob = prob_zxy(T, B)
	h_tri_gram = tri_entropy(tri_prob, bi_prob, uni_prob)

	return (h_uni_gram, h_bi_gram, h_tri_gram)

def smooth(tagged_list, prime = 0):
	brown_words = remove_tags(tagged_list)

	if prime == 0:
		return brown_words

	if prime == 1:
		x_prime = remove_words(tagged_list)
		U,B,T = ax.countNgrams(x_prime, 0)
		word_tag_dict = word_tag(tagged_list)

		Uy,By,Ty = ax.countNgrams(brown_words, 0)
		bigram_dict = prime_bigram(By, word_tag_dict)

		trigram_dict = prime_trigram(Ty, word_tag_dict)

		full_data =  [U,bigram_dict,trigram_dict]
		return entropy(full_data, 1)

	x_prime = remove_words(tagged_list)
	word_tag_dict = word_tag(tagged_list)
	U,B,T = ax.countNgrams(x_prime, 0)
	Uy,By,Ty = ax.countNgrams(brown_words, 0)
	xy_bigram_dict = xy_prime_bigram(By, word_tag_dict)
	xy_trigram_dict = xy_prime_trigram(Ty, word_tag_dict)
	full_data =  [U,xy_bigram_dict,xy_trigram_dict]
	return entropy(full_data, 1)

def remove_words(tagged_list):
	tags = []
	for words,tag in tagged_list:
		tags.append(tag)
	return tags

def remove_tags(tagged_list):
	words = []
	for word,tags in tagged_list:
		words.append(word)
	return words

# ['adv', 'noun', 'adp', 'pron', 'det', 'num', '.', 'prt', 'verb', 'x', 'conj', 'adj']
def word_tag(tagged_list):
	word_tag_dict = {}
	for word,tag in tagged_list:
		word_tag_dict[word] = tag
	return word_tag_dict

def prime_bigram(bigram_list, word_tag_dict):
	x_prime_bi = {}
	for word,count in bigram_list.iteritems():
		bi_key = (word_tag_dict[word[0]],word[1])
		if bi_key not in x_prime_bi:
			x_prime_bi[bi_key] = count
		else:
			x_prime_bi[bi_key] += count
	return x_prime_bi

def prime_trigram(trigram_list, word_tag_dict):
	x_prime_tri = {}
	for word,count in trigram_list.iteritems():
		tri_key = (word_tag_dict[word[0]],word[1],word[2])
		if tri_key not in x_prime_tri:
			x_prime_tri[tri_key] = count
		else:
			x_prime_tri[tri_key] += count
	return x_prime_tri

def xy_prime_bigram(bigram_list, word_tag_dict):
	xy_prime_bi = {}
	for word,count in bigram_list.iteritems():
		bi_key = (word_tag_dict[word[0]],word_tag_dict[word[1]])
		if bi_key not in xy_prime_bi:
			xy_prime_bi[bi_key] = count
		else:
			xy_prime_bi[bi_key] += count
	return xy_prime_bi

def xy_prime_trigram(trigram_list, word_tag_dict):
	xy_prime_tri = {}
	for word,count in trigram_list.iteritems():
		tri_key = (word_tag_dict[word[0]],word_tag_dict[word[1]],word[2])
		if tri_key not in xy_prime_tri:
			xy_prime_tri[tri_key] = count
		else:
			xy_prime_tri[tri_key] += count
	return xy_prime_tri


import csv

############   FOR CAR & TRUCK   ###########

# Open the input CSV file and the output CSV file
with open(r'D:\\ITS-2023\\Scenario\\5. Right - Copy.csv', 'r') as f_in:
    # Create CSV reader and writer objects
    reader = csv.DictReader(f_in)
    reader1 = csv.DictReader(f_in)
    reader2 = csv.DictReader(f_in)
    reader3 = csv.DictReader(f_in)
    reader4 = csv.DictReader(f_in)
    reader5 = csv.DictReader(f_in)
    s = set()

    total_time = 1160            #always change its value to final time
    updated_total_time = total_time - 60
    tme = (updated_total_time // 5) + 2

    j_truck = [0] * int(tme)
    k_truck = [0] * int(tme)
    l_truck = [0] * int(tme)
    ma_truck = [0] * int(tme)
    n_truck = [0] * int(tme)
    o_truck = [0] * int(tme)

    j_car = [0] * int(tme)
    k_car = [0] * int(tme)
    l_car = [0] * int(tme)
    ma_car = [0] * int(tme)
    n_car = [0] * int(tme)
    o_car = [0] * int(tme)

    m = [[]for _ in range(tme)]
    init_time = 0
    end_time = 60
    Velocity = []
    total_size = tme
    ranges = []
    increment = 60
    start = 0

    for _ in range(total_size):
        end = start + increment
        ranges.append((start, end))
        start += 5
    string_column_name = 'class'
    # for row in reader:
    #     # while float(row['vehicle_insertion_time']) < end_time:
    #     for start, end in ranges:
    #         if start < (float(row['T at D=20m'])) < end:
    #             # print(row[string_column_name])
    #             if(row[string_column_name]=='Car'):
    #                 j_car[start // 5] += 1
    #             else:
    #                 j_truck[start // 5] += 1

    # print("hi")
    # f_in.seek(0)
    # for row in reader1:
    #     # while float(row['vehicle_insertion_time']) < end_time:
    #     for start, end in ranges:
    #         if start < (float(row['T at D=50m'])) < end:
    #             if(row[string_column_name]=='Car'):
    #                 k_car[start // 5] += 1
    #             else:
    #                 k_truck[start // 5] += 1

    f_in.seek(0)
    for row in reader2:
        # while float(row['vehicle_insertion_time']) < end_time:
        for start, end in ranges:
            if start < (float(row['T at D=100m'])) < end:
                if(row[string_column_name]=='Car'):
                    l_car[start // 5] += 1
                else:
                    l_truck[start // 5] += 1

    f_in.seek(0)
    for row in reader3:
    # while float(row['vehicle_insertion_time']) < end_time:
        for start, end in ranges:
            if start < (float(row['T at D=200m'])) < end:
                if(row[string_column_name]=='Car'):
                    ma_car[start // 5] += 1
                else:
                    ma_truck[start // 5] += 1

    f_in.seek(0)
    for row in reader4:
    # while float(row['vehicle_insertion_time']) < end_time:
        for start, end in ranges:
            if start < (float(row['T at D=300m'])) < end:
                if(row[string_column_name]=='Car'):
                    n_car[start // 5] += 1
                else:
                    n_truck[start // 5] += 1

    f_in.seek(0)
    for row in reader5:
    # while float(row['vehicle_insertion_time']) < end_time:
        for start, end in ranges:
            if start < (float(row['T at D=400m'])) < end:
                if(row[string_column_name]=='Car'):
                    o_car[start // 5] += 1
                else:
                    o_truck[start // 5] += 1

    # print(l)
    rows_car = zip(ranges, j_car,k_car,l_car,ma_car,n_car,o_car)
    rows_truck = zip(ranges, j_truck,k_truck,l_truck,ma_truck,n_truck,o_truck)

    with open(r'D:\ITS-2023\Scenario\D_Veh_Flow_Car-5_Right.csv', 'w', newline='') as f_out:
        writer = csv.writer(f_out)
        writer.writerow(['Interval', 't@D=20m', 't@D=50m','t@D=100m' , 't@D=200m', 't@D=300m', 't@D=400m'])  # Write header row
        writer.writerows(rows_car)

    with open(r'D:\ITS-2023\Scenario\D_Veh_Flow_Truck-5_Right.csv', 'w', newline='') as f_out:
        writer = csv.writer(f_out)
        writer.writerow(['Interval', 't@D=20m', 't@D=50m','t@D=100m' , 't@D=200m', 't@D=300m', 't@D=400m'])  # Write header row
        writer.writerows(rows_truck)


'''
Galavantria
created by SentientDragon5
started March 2019
Art credit to
 - scratch.com users gamerkeep & ninja545
 - FangTrooper56
'''
import pyglet; import keyboard; import time
clock = 0
#window init
winW = 600; winH = 600
window = pyglet.window.Window(winW + 300,winH)
window.set_caption('Gallivantria')
window.set_icon(pyglet.image.load('n_16x16.png'), pyglet.image.load('n_32x32.png'))
invisible = pyglet.image.load('invisible.png')
#tile init
tileW = 20 ; tileH =20
tile = {}
for info in ['.','a','d','e','f','g','k','l','p','q','r','s','w','x']:
    tile[info] = pyglet.image.load(''.join(['t_',info,'.png']))
ren = pyglet.sprite.Sprite(tile['s'], x=60, y=60)
ren.update(None,None,None,None,float(1/3),float(1/3))
#objects init
objectkey = {}
for info in ['b','bd','bd','bd2','br','bo','bs','c','ch','f0','f1','f2','fs','gt','lt','mt','ps','s','sb','lb','st','sg','sy','t','v','vf','w']:
    objectkey[info] = pyglet.image.load(''.join(['o_',info,'.png']))
objRen = pyglet.sprite.Sprite(objectkey['b'], x=40, y=40)
objRen.update(None,None,None,None,float(0.4),float(0.4))
#inventory init
inventoryBG = pyglet.image.load('bg_inventory.png')
itemBorder = pyglet.image.load('bg_border.png')
itemBorderActive = pyglet.image.load('bg_border_active.png')
itemRen = pyglet.sprite.Sprite(itemBorder, x=60, y=60)
itemRen.update(None,None,None,None,float(1),float(1))
itemImage = {}
for info in ['leatherBag','sword','eyeOfTheSea','helm','breastplate','boots','cheese','ore','sværd']:
    itemImage[info] = pyglet.image.load(''.join(['i_',info,'.png']))
#action window init
door = pyglet.image.load('w_door.png')
action = pyglet.sprite.Sprite(door, x=200, y=200)
action.update(None,None,None,None,float(2),float(2))
#player init
skins = ['d']
skinNum = 0 #change number to change default skin 0 ~ original, 1 ~ dress girl, 2 ~ wizard
playerSkin = skins[skinNum]
playerImage = {}
for character in skins:
    for direction in ['d','l','r','u']:
        for tick in ['0','1','2','3']:
            playerImage[''.join([character,direction,tick])] = pyglet.image.load(''.join(['c_',character,direction,tick,'.png']))
player = pyglet.sprite.Sprite(playerImage[''.join([playerSkin,'d','0'])], x=40, y=40)
player.update(None,None,None,None,float(0.45),float(0.45))
gx = 0 ; gy = 0
#read player data
houseA = '3h0'
house = {}
house['3h0'] = ''
defaultMap = '2'#'defaultMap'
islands = {}
islands[0] = '2'
islands[1] = '3'
islands[2] = '4'
playerData = {}
save_key = ['world','x','y','storage','active0','active1','item0','item1','item2','item3','armour0','armour1','armour2']
inventoryKey = ['storage','active0','active1','item0','item1','item2','item3','armour0','armour1','armour2']
def readPlayer():
    global playerData, save_key, gx, gy, globalWorld
    with open(''.join(['s_save_',playerSkin,'.txt']), 'r') as file:
        Count = 0
        for lineStr in file:
            line = (lineStr.split(' '))
            for char in line:
                if char == '\n':
                    continue
                else:
                    playerData[save_key[Count]] = char
                    Count += 1
    gx = int(playerData['x']) ; gy = int(playerData['y'])
    globalWorld = playerData['world']
readPlayer()
#read Chest
chest_save_key = ['item0','item1','item2','item3','item4','item5','item6','item7',]
chests = {}
with open('s_chest.txt', 'r') as file:
    Count = 0
    for lineStr in file:
        line = (lineStr.split(' '))
        for char in line:
            if char == '\n':
                continue
            else:
                chests[chest_save_key[Count]] = char
                Count += 1
#read & render island data
colorIndex = {}
collisions = {}
def renWorBg(world):
    collisions.clear()
    colorIndex.clear()
    with open(''.join(['m_',world,'.txt']), 'r') as file:
        x = 0 ; y = 580
        for lineStr in file:
            line = (lineStr.split(' '))
            for char in line:
                if char == '\n':
                    continue
                else:
                    colorIndex[(x,y)] = char
                x += tileW
            y -= tileH
            x = 0
    for y in range(0,winH,20):
        for x in range(0,winW,20):
            colorInfo = colorIndex[(x,y)]
            ren.set_position(x,y)
            if colorInfo == 'w':
                collisions[(x,y)] = True
            elif colorInfo == '.':
                collisions[(x,y)] = True
            ren.image = tile[colorInfo]
            ren.draw()
#read & render island data
objects = {}
acessLoc = {'3h0':'empty','4h0':'empty','4h1':'empty','4h2':'empty','4h3':'empty','4h4':'empty','chest':'empty','boat':'empty'}
fireCount = 0
def edgeCollisions():
    for a in range(-20,580,20):
        collisions[(-20,a)] = True
        collisions[(a,-20)] = True
        collisions[(580,a)] = True
        collisions[(a,580)] = True
    for a in range(0,600,20):
        collisions[(0,a)] = True
        collisions[(a,0)] = True
        collisions[(600,a)] = True
        collisions[(a,600)] = True
def renObjects(world,height):
    global clock, gy, fireCount, acessLoc
    def makeHouse(num):
        pass
    objects.clear()
    with open(''.join(['mo_',world,'.txt']), 'r') as file:
        for lineStr in file:
            line = (lineStr.split(' '))
            objects[line[0]] = line[1]
            line.clear()
    for item in objects:
        texture = objects[item]
        a = item.split('(')
        b = a[1].split(')')
        c = b[0].split(',')
        if texture == 's':
            objRen.image = objectkey[texture]
            objRen.set_position(int(c[0]),int(c[1]) + 20)
        else:
            objRen.set_position(int(c[0]),int(c[1]))
        if texture == 'f':
            if fireCount >= 3:
                fireCount = 0
            objRen.image = objectkey[''.join(['f',str(fireCount)])]
        elif texture == 's':
            objRen.image = objectkey[texture]
        elif texture == 'mt':
            objRen.image = objectkey[texture]
        elif texture == 'sb.0':
            l = texture.split('.')
            objRen.image = objectkey[l[0]]
            for sby in [0,20]:
                for sbx in [0,20,40,60,80]:
                    collisions[(int(c[0]) + sbx,int(c[1]) + sby)] = True
            acessLoc[''.join(['3h',str(l[1])])] = (int(c[0]) + 40,int(c[1]) - 20)
        elif texture == 'sb.1':
            l = texture.split('.')
            objRen.image = objectkey[l[0]]
            for sby in [0,20]:
                for sbx in [0,20,40,60,80]:
                    collisions[(int(c[0]) + sbx,int(c[1]) + sby)] = True
            acessLoc[''.join(['4h',str(l[1])])] = (int(c[0]) + 40,int(c[1]) - 20)
        elif texture == 'sb.2':
            l = texture.split('.')
            objRen.image = objectkey[l[0]]
            for sby in [0,20]:
                for sbx in [0,20,40,60,80]:
                    collisions[(int(c[0]) + sbx,int(c[1]) + sby)] = True
            acessLoc[''.join(['4h',str(l[1])])] = (int(c[0]) + 40,int(c[1]) - 20)
        elif texture == 'sb.3':
            l = texture.split('.')
            objRen.image = objectkey[l[0]]
            for sby in [0,20]:
                for sbx in [0,20,40,60,80]:
                    collisions[(int(c[0]) + sbx,int(c[1]) + sby)] = True
            acessLoc[''.join(['4h',str(l[1])])] = (int(c[0]) + 40,int(c[1]) - 20)
        elif texture == 'sb.4':
            l = texture.split('.')
            objRen.image = objectkey[l[0]]
            for sby in [0,20]:
                for sbx in [0,20,40,60,80]:
                    collisions[(int(c[0]) + sbx,int(c[1]) + sby)] = True
            acessLoc[''.join(['4h',str(l[1])])] = (int(c[0]) + 40,int(c[1]) - 20)
        elif texture == 'lb.0':
            l = texture.split('.')
            objRen.image = objectkey[l[0]]
            for sby in [0,20,40,60]:
                for sbx in [0,20,40,60,80,100,120]:
                    collisions[(int(c[0]) + sbx,int(c[1]) + sby)] = True
            acessLoc[''.join(['4h',str(l[1])])] = (int(c[0]) + 60,int(c[1]) - 20)
        elif texture == 'bo':
            objRen.image = objectkey[texture]
            for sby in [0]:
                for sbx in [0,20,40]:
                    collisions[(int(c[0]) + sbx,int(c[1]) + sby)] = True
            acessLoc['boat'] = (int(c[0]) + 20,int(c[1]) + 20)
        elif texture == 'fs':
            objRen.image = objectkey[texture]
            for bdy in [0,20]:
                for bdx in [0,20,40]:
                    collisions[(int(c[0]) + bdx,int(c[1]) + bdy)] = True
        elif texture == 'bd':
            objRen.image = objectkey[texture]
            for bdy in [0,20]:
                for bdx in [0,20]:
                    collisions[(int(c[0]) + bdx,int(c[1]) + bdy)] = True
        elif texture == 'bd2':
            objRen.image = objectkey[texture]
            for bdy in [0,20]:
                for bdx in [0,20]:
                    collisions[(int(c[0]) + bdx,int(c[1]) + bdy)] = True
        elif texture == 'ps':
            objRen.image = objectkey[texture]
            for bdy in [0,20]:
                for bdx in [0,20]:
                    collisions[(int(c[0]) + bdx,int(c[1]) + bdy)] = True
        elif texture == 'lt':
            objRen.image = objectkey[texture]
            for bdy in [0,20]:
                for bdx in [20,40]:
                    collisions[(int(c[0]) + bdx,int(c[1]) + bdy)] = True
        elif texture == 'gt':
            objRen.image = objectkey[texture]
            for bdy in [20,40]:
                for bdx in [40,60]:
                    collisions[(int(c[0]) + bdx,int(c[1]) + bdy)] = True
        elif texture == 'bs':
            objRen.image = objectkey[texture]
            for bdy in [0]:
                for bdx in [0,20,40,60,80,100]:
                    collisions[(int(c[0]) + bdx,int(c[1]) + bdy)] = True
        elif texture == 'c':
            objRen.image = objectkey[texture]
            collisions[(int(c[0]),int(c[1]))] = True
            acessLoc['chest'] = (int(c[0]),int(c[1]) - 20)
        else:
            objRen.image = objectkey[texture]
            collisions[(int(c[0]),int(c[1]))] = True
        if height == 'above':
            if int(c[1]) >= gy:
                objRen.draw()
        else:
            if int(c[1]) < gy:
                objRen.draw()
    fireCount += 1
playerticking = 0
lastd = 'd'
active = {}
def clearActive():
    for key in inventoryKey:
        active[key] = False
clearActive()
def switch(one,two):
    global active
    oldone = playerData[one]
    oldtwo = playerData[two]
    playerData[one] = oldtwo
    playerData[two] = oldone
def inventoryEdit():
    if keyboard.is_pressed('q'):
        pass
def drawInventory(playerImage):
    global gx, gy, acessLoc, active
    def checkActive(catagory,num):
        if active[''.join([catagory,str(num)])] == True:
            itemRen.update(None,None,None,None,float(1/4),float(1/4))
            itemRen.image = itemBorderActive
        else:
            itemRen.update(None,None,None,None,float(1/2),float(1/2))
            itemRen.image = itemBorder
        itemRen.draw()
    #draw Background
    itemRen.update(None,None,None,None,float(1),float(1))
    itemRen.image = inventoryBG
    itemRen.set_position(600,0)
    itemRen.draw()
    itemLoc = {}
    for y in [520]:
        for x in [793]:
            itemRen.set_position(x,y)
            checkActive('storage','')
            itemLoc['storagex'] = x + 10 ; itemLoc['storagey'] = y + 10
    itemNum = 0
    catagory = 'item'
    for y in [450,380]:
        for x in [760,830]:
            itemRen.set_position(x,y)
            checkActive(catagory,itemNum)
            itemLoc[''.join([catagory,str(itemNum),'x'])] = x + 10 ; itemLoc[''.join([catagory,str(itemNum),'y'])] = y + 10
            itemNum += 1
    itemNum = 0
    catagory = 'armour'
    for y in [500,430,360]:
        for x in [690]:
            itemRen.set_position(x,y)
            checkActive(catagory,itemNum)
            itemLoc[''.join([catagory,str(itemNum),'x'])] = x + 10 ; itemLoc[''.join([catagory,str(itemNum),'y'])] = y + 10
            itemNum += 1
    itemNum = 0
    catagory = 'active'
    for y in [290]:
        for x in [650,800]:
            itemRen.set_position(x,y)
            checkActive(catagory,itemNum)
            itemLoc[''.join([catagory,str(itemNum),'x'])] = x + 10 ; itemLoc[''.join([catagory,str(itemNum),'y'])] = y + 10
            itemNum += 1
    itemRen.update(None,None,None,None,float(1.2),float(1.2))
    itemRen.image = pyglet.image.load(''.join(['c_',playerSkin,'d0.png']))
    itemRen.set_position(610,410)
    itemRen.draw()
    #draw Items
    for item in save_key:
        if item == 'world':
            drawItem = False
            playerData['x'] = gx
            continue
        elif item == 'x':
            drawItem = False
            playerData['x'] = gx
            continue
        elif item == 'y':
            drawItem = False
            playerData['y'] = gy
            continue
        if playerData[item] == 'empty':
            drawItem = False
        else:
            itemRen.image = itemImage[str(playerData[item])]
            itemRen.set_position(itemLoc[''.join([item,'x'])],itemLoc[''.join([item,'y'])])
            itemRen.update(None,None,None,None,float(0.75),float(0.75))
            itemRen.draw()
    action.image = invisible
    action.update(None,None,None,None,float(2),float(2))
    if globalWorld == '2':
        if (gx, gy) == acessLoc['boat']:
            ptext('press E to go to another island',670,20,10)
            action.image = objectkey['bo']
            action.update(None,None,None,None,float(1.2),float(1.2))
            action.set_position(650,50)
    if globalWorld == '3':
        if (gx, gy) == acessLoc['3h0']:
            ptext('press E to enter the house',670,20,10)
            action.image = door
            action.set_position(700,50)
        if (gx, gy) == acessLoc['boat']:
            ptext('press E to go to another island',670,20,10)
            action.image = objectkey['bo']
            action.update(None,None,None,None,float(1.2),float(1.2))
            action.set_position(650,50)
        if (gx, gy) == acessLoc['chest']:
            itemRen.update(None,None,None,None,float(1/2),float(1/2))
            itemRen.image = itemBorder
            itemLoc = {}
            itemNum = 0
            for y in [10,80,150,220]:
                for x in [760,830]:
                    itemRen.set_position(x,y)
                    itemRen.draw()
                    itemLoc[''.join(['item',str(itemNum),'x'])] = x + 10 ; itemLoc[''.join(['item',str(itemNum),'y'])] = y + 10
                    itemNum += 1
            #draw Chest Items
            for item in chest_save_key:
                if chests[item] == 'empty':
                    drawItem = False
                else:
                    itemRen.image = itemImage[str(chests[item])]
                    itemRen.set_position(itemLoc[''.join([item,'x'])],itemLoc[''.join([item,'y'])])
                    itemRen.update(None,None,None,None,float(0.75),float(0.75))
                    itemRen.draw()
            action.update(None,None,None,None,float(1.5),float(1.5))
            ptext('click to switch\nthe boxes',630,70,10)
            action.image = objectkey['c']
            action.set_position(630,120)
    if globalWorld == '4':
        if (gx, gy) == acessLoc['4h0']:
            ptext('press E to enter the house',670,20,10)
            action.image = door
            action.set_position(700,50)
        if (gx, gy) == acessLoc['4h1']:
            ptext('press E to enter the house',670,20,10)
            action.image = door
            action.set_position(700,50)
        if (gx, gy) == acessLoc['4h2']:
            ptext('press E to enter the house',670,20,10)
            action.image = door
            action.set_position(700,50)
        if (gx, gy) == acessLoc['4h3']:
            ptext('press E to enter the house',670,20,10)
            action.image = door
            action.set_position(700,50)
        if (gx, gy) == acessLoc['4h4']:
            ptext('press E to enter the house',670,20,10)
            action.image = door
            action.set_position(700,50)
        if (gx, gy) == acessLoc['boat']:
            ptext('press E to go to another island',670,20,10)
            action.image = objectkey['bo']
            action.update(None,None,None,None,float(1.2),float(1.2))
            action.set_position(650,50)
islandCount = 0
islandLoc = {}
islandLoc['2'] = (260,360)
islandLoc['3'] = (500,60)
islandLoc['4'] = (100,80)
def executeAction(actionType):
    global gx, gy, globalWorld, exitTox, exitToy, playerSkin, lastd, islandCount, islands, islandLoc, acessLoc
    tempx = gx
    tempy = gy
    if actionType == 'h':
        if globalWorld == houseA:
            globalWorld = '3'
            edgeCollisions()
            fireCount = 0
            gx = exitTox
            gy = exitToy
            animateStep(False,'d',playerSkin) ; lastd = 'd'
        if (tempx,tempy) == acessLoc['3h0']:
            if globalWorld == '3':
                print(globalWorld)
                globalWorld = houseA
                edgeCollisions()
                exitTox = gx ; exitToy = gy
                gx = 300 ; gy = 120#enter house location
                animateStep(False,'u',playerSkin) ; lastd = 'u'

        if globalWorld == '4h0':
            globalWorld = '4'
            edgeCollisions()
            fireCount = 0
            gx = exitTox
            gy = exitToy
            animateStep(False,'d',playerSkin) ; lastd = 'd'
        if globalWorld == '4h1':
            globalWorld = '4'
            edgeCollisions()
            fireCount = 0
            gx = exitTox
            gy = exitToy
            animateStep(False,'d',playerSkin) ; lastd = 'd'
        if globalWorld == '4h2':
            globalWorld = '4'
            edgeCollisions()
            fireCount = 0
            gx = exitTox
            gy = exitToy
            animateStep(False,'d',playerSkin) ; lastd = 'd'
        if globalWorld == '4h3':
            globalWorld = '4'
            edgeCollisions()
            fireCount = 0
            gx = exitTox
            gy = exitToy
            animateStep(False,'d',playerSkin) ; lastd = 'd'
        if globalWorld == '4h4':
            globalWorld = '4'
            edgeCollisions()
            fireCount = 0
            gx = exitTox
            gy = exitToy
            animateStep(False,'d',playerSkin) ; lastd = 'd'

        if (tempx,tempy) == acessLoc['4h0']:
            if globalWorld == '4':
                print(globalWorld)
                globalWorld = '4h0'
                edgeCollisions()
                exitTox = gx ; exitToy = gy
                gx = 300 ; gy = 200#enter house location
                animateStep(False,'u',playerSkin) ; lastd = 'u'
        if (tempx,tempy) == acessLoc['4h1']:
            if globalWorld == '4':
                print(globalWorld)
                globalWorld = '4h1'
                edgeCollisions()
                exitTox = gx ; exitToy = gy
                gx = 300 ; gy = 200
                animateStep(False,'u',playerSkin) ; lastd = 'u'
        if (tempx,tempy) == acessLoc['4h2']:
            if globalWorld == '4':
                print(globalWorld)
                globalWorld = '4h2'
                edgeCollisions()
                exitTox = gx ; exitToy = gy
                gx = 300 ; gy = 200
                animateStep(False,'u',playerSkin) ; lastd = 'u'
        if (tempx,tempy) == acessLoc['4h3']:
            if globalWorld == '4':
                print(globalWorld)
                globalWorld = '4h3'
                edgeCollisions()
                exitTox = gx ; exitToy = gy
                gx = 300 ; gy = 200
                animateStep(False,'u',playerSkin) ; lastd = 'u'
        if (tempx,tempy) == acessLoc['4h4']:
            if globalWorld == '4':
                print(globalWorld)
                globalWorld = '4h4'
                edgeCollisions()
                exitTox = gx ; exitToy = gy
                gx = 300 ; gy = 200
                animateStep(False,'u',playerSkin) ; lastd = 'u'

    if actionType == 'b':
        if acessLoc['boat'] == (gx,gy):
            islandCount += 1
            if islandCount == 3:
                islandCount = 0
            globalWorld = islands[islandCount]
            print(islandLoc[islands[islandCount]])
            locStr = str(islandLoc[islands[islandCount]])
            a = locStr.split('(')
            b = a[1].split(')')
            c = b[0].split(',')
            gx = int(c[0])
            gy = int(c[1])
#player
exitTox = gx ; exitToy = gy
def animateStep(bAnimate,direction,image):
    global playerticking,lastd
    if bAnimate == True:
        playerticking += 1
        if playerticking == 4:
            playerticking = 0
        lastd = direction
    else:
        playerticking = 0
    player.image = playerImage[''.join([image,direction,str(playerticking)])]
pressedLast = True
mode = 'play'
activeNum = 9
switchTemp = ''
def runPlayer(image):
    global gx, gy, mode, globalWorld, pressedLast, activeNum, switchTemp, skins, skinNum, playerSkin, exitTox, exitToy, gmessage
    reversex = 0 ; reversey = 0
    keypress = False ; drawChest = False
    if keyboard.is_pressed('q'):#mode switch
        activeNum = 0
        switchTemp = ''
        if mode == 'play':
            mode = 'inventory'
        elif mode == 'inventory':
            mode = 'play'
            clearActive()
        print(mode)
    if keyboard.is_pressed('r'):
        ptext(' INSTRUCTIONS:/npress W to move up\npress A to move left\npress S to move down\npress D to move right\npress E to enter buildings\n   or enter boats\npress Q to edit inventory',680,240,20)
    if mode == 'play':
        if keyboard.is_pressed('w'):#move up
            gy += 20
            animateStep(True,'u',image)
            reversey = -20
            keypress = True; pressedLast = True
        elif keyboard.is_pressed('a'):#move left
            gx -= 20
            animateStep(True,'l',image)
            reversex = 20
            keypress = True ; pressedLast = True
        elif keyboard.is_pressed('s'):#move down
            gy -= 20
            animateStep(True,'d',image)
            reversey = 20
            keypress = True ; pressedLast = True
        elif keyboard.is_pressed('d'):#move right
            gx += 20
            animateStep(True,'r',image)
            reversex = -20
            keypress = True ; pressedLast = True
        elif keyboard.is_pressed('e'):#enter house
            pressedLast = False
            executeAction('h')
            executeAction('b')
            '''
        elif keyboard.is_pressed('q'):#change player
            pressedLast = False
            skinNum += 1
            if skinNum >= (len(skins)+ 1):
                skinNum = 0
            playerSkin = skins[skinNum]
            readPlayer()'''
        elif keyboard.is_pressed('enter'):#function 1
            print('function 1')
        elif keyboard.is_pressed('shift'):#function 2
            print('function 2')
        else:
            animateStep(False,lastd,image)
            keypress = False
    if mode == 'inventory':
        if keyboard.is_pressed('w'):
            clearActive()
            activeNum += 1
        if keyboard.is_pressed('s'):
            clearActive()
            activeNum -= 1
        if activeNum > 9:
            activeNum = 0
        if activeNum < 0:
            activeNum = 9
        active[inventoryKey[activeNum]] = True
        if switchTemp == '':
            ptext('press W and S to scroll\npress ENTER to select',680,240,20)
            if keyboard.is_pressed('enter'):#select
                switchTemp = activeNum
        elif not (switchTemp == ''):
            active[inventoryKey[int(switchTemp)]] = True
            if keyboard.is_pressed('enter'):#switch
                switch(str(inventoryKey[activeNum]),str(inventoryKey[int(switchTemp)]))
                switchTemp = ''
                clearActive()
    #ren Inventory (chest)
    if (gx,gy) in collisions:
        gx += reversex ; gy += reversey
        animateStep(False,lastd,image)
    playerData['world'] = globalWorld
    if keypress == True:
        print(gx,gy)
        Savefile = open(''.join(['s_save_',playerSkin,'.txt']),'w')
        writeList = []
        for info in save_key:
            writeList.append(str(playerData[info]))
            writeList.append(' \n')
        del writeList[-1]
        Savefile.write(str(''.join(writeList)))
        Savefile.close()
def ptext(info,x,y,size):
    lines = info.split('\n')
    yOffset = 0
    for line in lines:
        text = pyglet.text.Label(line, font_name='Arial', font_size=10,x=x, y=(y + yOffset))
        text.draw()
        yOffset -= size * 1.5
#rerender
def update(dt):
    global clock,gx,gy,playerSkin,globalWorld, textx, texty, textinfo
    #drawChest = False
    window.clear()
    drawInventory(playerSkin)
    runPlayer(playerSkin)
    renWorBg(globalWorld)
    renObjects(globalWorld,'above')
    player.set_position(gx,gy)
    player.draw()
    renObjects(globalWorld,'below')
    action.draw()
    clock += 1
def main():
    pyglet.clock.schedule_interval(update, 0.05)
    pyglet.app.run()
main()
exit()


#!/usr/bin/python3

"""Program which auto-connects to USB serial devices.

This program waits for the device to be connected and when the device is
disconnected, then it will go back to waiting for a device to once again
be connected.

"""

from __future__ import print_function

import select
import pyudev
import serial
import sys
import os
import tty
import termios
import traceback
import syslog
import argparse
import time
from collections import namedtuple

EXIT_CHAR = 0
def set_exit_char(exit_char):
    global EXIT_CHAR
    EXIT_CHAR = ord(exit_char) - ord('@')

set_exit_char('X')  # Control-X

class Logger(object):

    def __init__(self, log_file=None):
        self._log_file = log_file
        self._line = b''

    def log(self, log_bytes):
        if not self._log_file:
            return

        for char in log_bytes:
            char = bytes([char])
            if char == b'\r':
                continue
            if len(self._line) == 0:
                self._line += self.timestamp()
            self._line += char
            if char == b'\n':
                self._log_file.write(self._line)
                self._line = b''

    def print(self, log_str, end='\n'):
        # print accepts a string, but assumes it's ascii-only
        log_str += end
        sys.__stdout__.write(log_str)
        if self._log_file:
            self.log(log_str.encode('ascii'))

    def timestamp(self):
        curr_time = round(time.time(), 4)
        time_str = time.strftime('%H:%M:%S', time.localtime(curr_time))
        time_str += '{:.4f}: '.format(curr_time - int(curr_time))[1:]
        return time_str.encode('ascii')

    def char(self, prefix, c):
        self.print( "%s.Read '%c' 0x%02x\r" % (prefix, chr(c) if c >= 0x20 and c < 0x7f else '?', c))

def is_usb_serial(device, args=None):
    """Checks device to see if its a USB Serial device.

    The caller already filters on the subsystem being 'tty'.

    If serial_num or vendor is provided, then it will further check to
    see if the serial number and vendor of the device also matches.
    """
    prop = device.properties
    if 'ID_VENDOR' not in prop:
        return False
    if not args is None:
        if args.port and args.port not in device.device_node:
            return False
        if args.vendor:
            if 'ID_VENDOR' not in prop:
              return False
            if not prop['ID_VENDOR'].startswith(args.vendor):
              return False
        if args.serial:
            if 'ID_SERIAL_SHORT' not in prop:
                return False
            if prop['ID_SERIAL_SHORT'] != args.serial:
                return False
        if args.intf:
            if 'ID_USB_INTERFACE_NUM' not in prop:
                return False
            if prop['ID_USB_INTERFACE_NUM'] != args.intf:
                return False
    return True

def extra_info(device):
    #for x in device:
    #    print(x, device[x])
    output = ''
    prop = device.properties
    if 'ID_VENDOR_ID' in prop:
        output = ' {}:{}'.format(prop['ID_VENDOR_ID'], prop['ID_MODEL_ID'])
    extra_items = []
    if 'ID_VENDOR' in prop:
        extra_items.append("vendor '%s'" % prop['ID_VENDOR'])
    if 'ID_SERIAL_SHORT' in prop:
        extra_items.append("serial '%s'" % prop['ID_SERIAL_SHORT'])
    if 'ID_USB_INTERFACE_NUM' in prop:
        extra_items.append('intf {}'.format(prop['ID_USB_INTERFACE_NUM']))
    if extra_items:
        output += ' with '
        output += ' '.join(extra_items)
    return output

def usb_serial_mon(monitor, device, baud=115200, debug=False, echo=False):
    """Monitors the serial port from a given USB serial device.

    This function open the USB serial port associated with device, and
    will read characters from it and send to stdout. It will also read
    characters from stdin and send them to the device.

    This function returns when the deivce disconnects (or is
    disconnected).

    """
    port_name = device.device_node
    log.print('USB Serial device%s connected @%s\r' % (
              extra_info(device), port_name))
    log.print('Use Control-%c to exit.\r' % chr(EXIT_CHAR + ord('@')))

    if device.properties['ID_VENDOR'].startswith('Synthetos'):
        echo = True

    epoll = select.epoll()
    epoll.register(monitor.fileno(), select.POLLIN)

    try:
        serial_port = serial.Serial(port=port_name,
                                    baudrate=baud,
                                    timeout=0.001,
                                    bytesize=serial.EIGHTBITS,
                                    parity=serial.PARITY_NONE,
                                    stopbits=serial.STOPBITS_ONE,
                                    xonxoff=False,
                                    rtscts=False,
                                    dsrdtr=False)
    except serial.serialutil.SerialException:
        log.print("Unable to open port '%s'\r" % port_name)
        return

    serial_fd = serial_port.fileno()
    tty.setraw(serial_fd)
    new_settings = termios.tcgetattr(serial_fd)
    new_settings[6][termios.VTIME] = 0
    new_settings[6][termios.VMIN] = 1
    termios.tcsetattr(serial_fd, termios.TCSANOW, new_settings)

    epoll.register(serial_port.fileno(), select.POLLIN)
    epoll.register(sys.stdin.fileno(), select.POLLIN)

    while True:
        events = epoll.poll()
        for fileno, _ in events:
            if fileno == monitor.fileno():
                dev = monitor.poll()
                if (dev.device_node != port_name or
                        dev.action != 'remove'):
                    continue
                log.print('USB Serial device @%s disconnected.\r' % port_name)
                log.print('\r')
                serial_port.close()
                return
            if fileno == serial_port.fileno():
                try:
                    data = serial_port.read(256)
                except serial.serialutil.SerialException:
                    log.print('USB Serial device @%s disconnected.\r' % port_name)
                    log.print('\r')
                    serial_port.close()
                    return
                if debug:
                    for x in data:
                        log.char("Serial", x)
                pos = 0
                while True:
                    nl_pos = data.find(b'\n', pos)
                    if nl_pos < 0:
                        break
                    if nl_pos > 0 and data[nl_pos-1:nl_pos] == b'\r':
                        # already have \r before \n - just leave things be
                        pos = nl_pos + 1
                        continue
                    data = data[:nl_pos] + b'\r' + data[nl_pos:]
                    pos = nl_pos + 2
                sys.stdout.write(data)
                sys.stdout.flush()
                log.log(data)
            if fileno == sys.stdin.fileno():
                data = os.read(fileno, 1)
                if len(data) == 0:
                    continue
                if debug:
                    for x in data:
                        log.char("stdin", x)
                if data[0] == EXIT_CHAR:
                    raise KeyboardInterrupt
                if echo:
                    sys.stdout.write(data)
                    if data[0:1] == b'\r':
                        sys.stdout.write(b'\n')
                    sys.stdout.flush()
                if data[0:1] == b'\n':
                    serial_port.write(b'\r')
                else:
                    serial_port.write(data)
                time.sleep(0.002)

def main():
    """The main program."""

    default_baud = 115200
    parser = argparse.ArgumentParser(
        prog="usb-ser-mon.py",
        usage="%(prog)s [options] [command]",
        description="Monitor serial output from USB Serial devices",
        epilog="Press Control-%c to quit" % chr(EXIT_CHAR + ord('@'))
    )
    parser.add_argument(
        "-p", "--port",
        dest="port",
        action="store",
        help="Set the port to connect to",
        default=None
    )
    parser.add_argument(
        "-b", "--baud",
        dest="baud",
        action="store",
        type=int,
        help="Set the baudrate used (default = %d)" % default_baud,
        default=default_baud
    )
    parser.add_argument(
        "-d", "--debug",
        dest="debug",
        action="store_true",
        help="Turn on debugging",
        default=False
    )
    parser.add_argument(
        "-e", "--echo",
        dest="echo",
        action="store_true",
        help="Turn on local echo",
        default=False
    )
    parser.add_argument(
        "-i", "--intf",
        dest="intf",
        help="Connect to USB serial device with a given interface",
        default=None
    )
    parser.add_argument(
        "-l", "--list",
        dest="list",
        action="store_true",
        help="List USB Serial devices currently connected"
    )
    parser.add_argument(
        "-s", "--serial",
        dest="serial",
        help="Connect to USB Serial device with a given serial number",
        default=None
    )
    parser.add_argument(
        "--log",
        dest="log",
        default="usb-ser-mon.log",
        help="Log the session to a file."
    )
    parser.add_argument(
        "-n", "--vendor",
        dest="vendor",
        help="Connect to USB Serial device with a given vendor",
        default=None
    )
    parser.add_argument(
        "-v", "--verbose",
        dest="verbose",
        action="store_true",
        help="Turn on verbose messages",
        default=False
    )
    parser.add_argument(
        "-y",
        dest="ctrl_y_exit",
        action="store_true",
        help="Use Control-Y to exit rather than Control-X",
        default=False
    )
    args = parser.parse_args(sys.argv[1:])
    sys.stdout = sys.stdout.buffer

    global log
    log = Logger(open(args.log, "wb"))

    if args.verbose:
        log.print('pyudev version = %s' % pyudev.__version__)
        log.print('echo = %d' % args.echo)

    if args.ctrl_y_exit:
        set_exit_char('Y')

    context = pyudev.Context()
    context.log_priority = syslog.LOG_NOTICE

    if args.list:
        detected = False
        for device in context.list_devices(subsystem='tty'):
            if is_usb_serial(device, args):
                log.print('USB Serial Device%s found @%s\r' % (
                          extra_info(device), device.device_node))
                detected = True
        if not detected:
            log.print('No USB Serial devices detected.\r')
        return

    stdin_fd = sys.stdin.fileno()
    old_settings = termios.tcgetattr(stdin_fd)
    try:
        # Make some changes to stdin. We want to turn off canonical
        # processing  (so that ^H gets sent to the device), turn off echo,
        # and make it unbuffered.
        tty.setraw(stdin_fd)
        new_settings = termios.tcgetattr(stdin_fd)
        new_settings[3] &= ~(termios.ICANON | termios.ECHO)
        new_settings[6][termios.VTIME] = 0
        new_settings[6][termios.VMIN] = 1
        termios.tcsetattr(stdin_fd, termios.TCSANOW, new_settings)

        monitor = pyudev.Monitor.from_netlink(context)
        monitor.start()
        monitor.filter_by('tty')

        # Check to see if the USB Serial device is already present.
        for device in context.list_devices(subsystem='tty'):
            if is_usb_serial(device, args):
                usb_serial_mon(monitor, device, baud=args.baud,
                        debug=args.debug, echo=args.echo)

        # Otherwise wait for the teensy device to connect
        while True:
            dev = namedtuple('Device', ['properties'])({})
            if args.serial:
                dev.properties['ID_SERIAL_SHORT'] = args.serial
            if args.vendor:
                dev.properties['ID_VENDOR'] = args.vendor
            log.print('Waiting for USB Serial Device%s ...\r' % extra_info(dev))
            epoll = select.epoll()
            epoll.register(monitor.fileno(), select.POLLIN)
            epoll.register(sys.stdin.fileno(), select.POLLIN)
            while True:
                events = epoll.poll()
                for fileno, _ in events:
                    if fileno == monitor.fileno():
                        device = monitor.poll()
                        if device.action != 'add':
                            continue
                        if is_usb_serial(device, args):
                            usb_serial_mon(monitor, device, baud=args.baud,
                                debug=args.debug, echo=args.echo)
                            break
                    if fileno == sys.stdin.fileno():
                        data = os.read(fileno, 1)
                        if data[0] == EXIT_CHAR:
                            raise KeyboardInterrupt
    except KeyboardInterrupt:
        log.print('\r')
    except Exception:
        traceback.print_exc()
    # Restore stdin back to its old settings
    termios.tcsetattr(stdin_fd, termios.TCSANOW, old_settings)

if __name__ == "__main__":
    main()


from pathlib import Path

from click.testing import CliRunner

from zenml.cli.base import clean, init
from zenml.constants import CONFIG_FILE_NAME, REPOSITORY_DIRECTORY_NAME
from zenml.utils import yaml_utils
from zenml.utils.io_utils import get_global_config_directory

def test_init_creates_zen_folder(tmp_path: Path) -> None:
    """Check that init command creates a .zen folder."""
    runner = CliRunner()
    runner.invoke(init, ["--path", str(tmp_path)])
    assert (tmp_path / REPOSITORY_DIRECTORY_NAME).exists()

def test_clean_user_config(clean_workspace) -> None:
    global_zen_config_yaml = (
        Path(get_global_config_directory()) / CONFIG_FILE_NAME
    )
    assert global_zen_config_yaml.exists()
    yaml_contents = yaml_utils.read_yaml(str(global_zen_config_yaml))
    user_id = yaml_contents["user_id"]
    analytics_opt_in = yaml_contents["analytics_opt_in"]
    version = yaml_contents["version"]
    runner = CliRunner()
    runner.invoke(clean, ["--yes", True])
    new_yaml_contents = yaml_utils.read_yaml(str(global_zen_config_yaml))
    assert user_id == new_yaml_contents["user_id"]
    assert analytics_opt_in == new_yaml_contents["analytics_opt_in"]
    assert version == new_yaml_contents["version"]


"""Media Player platform for eversolo."""
from __future__ import annotations

import datetime as dt

from homeassistant.components.media_player import (
    MediaPlayerDeviceClass,
    MediaPlayerEntity,
    MediaPlayerEntityFeature,
    MediaPlayerState,
)

from .const import DOMAIN, LOGGER
from .coordinator import EversoloDataUpdateCoordinator
from .entity import EversoloEntity

SUPPORT_FEATURES = (
    MediaPlayerEntityFeature.TURN_OFF
    | MediaPlayerEntityFeature.SELECT_SOURCE
    | MediaPlayerEntityFeature.PLAY
    | MediaPlayerEntityFeature.PAUSE
    | MediaPlayerEntityFeature.VOLUME_SET
    | MediaPlayerEntityFeature.VOLUME_MUTE
    | MediaPlayerEntityFeature.VOLUME_STEP
    | MediaPlayerEntityFeature.PREVIOUS_TRACK
    | MediaPlayerEntityFeature.NEXT_TRACK
    | MediaPlayerEntityFeature.SEEK
)

async def async_setup_entry(hass, entry, async_add_devices):
    """Set up the Media Player platform."""
    coordinator = hass.data[DOMAIN][entry.entry_id]

    async_add_devices([EversoloMediaPlayer(coordinator, entry)])

class EversoloMediaPlayer(EversoloEntity, MediaPlayerEntity):
    """Eversolo Media Player."""

    def __init__(self, coordinator: EversoloDataUpdateCoordinator, config_entry):
        """Initialize the Media Player."""
        super().__init__(coordinator)
        self._attr_device_class = MediaPlayerDeviceClass.RECEIVER
        self._attr_supported_features = SUPPORT_FEATURES
        self._attr_unique_id = f"{coordinator.config_entry.entry_id}_media_player"
        self._config_entry = config_entry
        self._name = "Eversolo"
        self._state = None

    @property
    def name(self):
        """Return name."""
        return self._name

    @property
    def state(self):
        """Return Media Player state."""
        music_control_state = self.coordinator.data.get("music_control_state", None)

        if music_control_state is None:
            self._state = None
            return self._state

        state = int(music_control_state.get("state", -1))

        if state == 0:
            self._state = MediaPlayerState.IDLE
        elif state == 3:
            self._state = MediaPlayerState.PLAYING
            self._attr_media_position_updated_at = dt.datetime.now()
        elif state == 4:
            self._state = MediaPlayerState.PAUSED
        else:
            LOGGER.debug("Unknown state: %s", state)
            self._state = None

        return self._state

    @property
    def device_info(self):
        """Return Media Player device info."""
        return {}

    @property
    def volume_level(self):
        """Volume level of the Media Player in range 0..1."""
        music_control_state = self.coordinator.data.get("music_control_state", None)

        if music_control_state is None:
            return None

        current_volume = music_control_state.get("volumeData", {}).get(
            "currenttVolume", None
        )
        max_volume = music_control_state.get("volumeData", {}).get("maxVolume", None)

        if current_volume is None or max_volume is None:
            LOGGER.debug(
                "Current volume or max volume invalid in music control state: %s",
                music_control_state,
            )
            return None

        return float(current_volume) / float(max_volume)

    @property
    def is_volume_muted(self):
        """Return muted state."""
        music_control_state = self.coordinator.data.get("music_control_state", None)

        if music_control_state is None:
            return None

        return music_control_state.get("volumeData", {}).get("isMute", None)

    @property
    def source(self):
        """Return the current input source."""
        input_output_state = self.coordinator.data.get("input_output_state", None)

        if input_output_state is None:
            return None

        sources = self.coordinator.data.get("input_output_state", {}).get(
            "transformed_sources", None
        )

        if sources is None:
            return None

        input_index = input_output_state.get("inputIndex", -1)
        if input_index < 0 or input_index >= len(sources):
            LOGGER.debug("Input index %s is out of range", input_index)
            return None

        return list(sources.values())[input_index]

    @property
    def source_list(self):
        """List of available input sources."""
        # NoneType object has no values
        sources = self.coordinator.data.get("input_output_state", {}).get(
            "transformed_sources", None
        )

        if sources is None:
            return None

        return list(sources.values())

    @property
    def media_title(self):
        """Title of current playing media."""
        music_control_state = self.coordinator.data.get("music_control_state", None)

        if music_control_state is None:
            return None

        play_type = music_control_state.get("playType", None)

        # Bluetooth or Spotify Connect
        if play_type == 4 or play_type == 6:
            return (
                music_control_state.get("everSoloPlayInfo", {})
                .get("everSoloPlayAudioInfo", {})
                .get("songName", None)
            )

        # Internal Player
        if play_type == 5:
            return music_control_state.get("playingMusic", {}).get("title", None)

        return None

    @property
    def media_artist(self):
        """Artist of current playing media."""
        music_control_state = self.coordinator.data.get("music_control_state", None)

        if music_control_state is None:
            return None

        play_type = music_control_state.get("playType", None)

        # Bluetooth or Spotify Connect
        if play_type == 4 or play_type == 6:
            return (
                music_control_state.get("everSoloPlayInfo", {})
                .get("everSoloPlayAudioInfo", {})
                .get("artistName", None)
            )

        # Internal Player
        if play_type == 5:
            return music_control_state.get("playingMusic", {}).get("artist", None)

        return None

    @property
    def media_album_name(self):
        """Album of current playing media."""
        music_control_state = self.coordinator.data.get("music_control_state", None)

        if music_control_state is None:
            return None

        play_type = music_control_state.get("playType", None)

        # Bluetooth or Spotify Connect
        if play_type == 4 or play_type == 6:
            return (
                music_control_state.get("everSoloPlayInfo", {})
                .get("everSoloPlayAudioInfo", {})
                .get("albumName", None)
            )

        # Internal Player
        if play_type == 5:
            return music_control_state.get("playingMusic", {}).get("album", None)

        return None

    @property
    def media_image_url(self):
        """Image url of current playing media."""
        music_control_state = self.coordinator.data.get("music_control_state", None)

        if music_control_state is None:
            return None

        play_type = music_control_state.get("playType", None)

        # Bluetooth or Spotify Connect
        if play_type == 6:
            album_url = music_control_state.get("everSoloPlayInfo", {}).get(
                "icon", None
            )

            if album_url is None or album_url == "":
                return None

            if not album_url.startswith("http"):
                album_url = self.coordinator.client.create_image_url_by_path(album_url)

            return album_url

        # Internal Player
        if play_type == 5:
            song_id = music_control_state.get("playingMusic", {}).get("id", None)
            if song_id is not None:
                return self.coordinator.client.create_image_url_by_song_id(song_id)

        return None

    @property
    def media_duration(self):
        """Duration of current playing media in seconds."""
        music_control_state = self.coordinator.data.get("music_control_state", None)

        if music_control_state is None:
            return None

        duration = music_control_state.get("duration", None)

        if duration is None or duration == 0:
            return None

        return duration / 1000

    @property
    def media_position(self):
        """Position of current playing media in seconds."""
        music_control_state = self.coordinator.data.get("music_control_state", None)

        if music_control_state is None:
            return None

        position = music_control_state.get("position", None)

        if position is None or position == 0:
            return None

        return position / 1000

    async def async_media_seek(self, position: float):
        """Seek the media to a specific location."""
        await self.coordinator.client.async_seek_time(round(position * 1000))
        await self.coordinator.async_request_refresh()

    async def async_turn_off(self):
        """Turn off Media Player."""
        await self.coordinator.client.async_trigger_power_off()
        await self.coordinator.async_request_refresh()

    async def async_set_volume_level(self, volume: float) -> None:
        """Set volume level, range 0..1."""
        music_control_state = self.coordinator.data.get("music_control_state", None)

        if music_control_state is None:
            return

        converted_volume = round(
            volume * int(music_control_state.get("volumeData", {}).get("maxVolume", 0))
        )
        await self.coordinator.client.async_set_volume(converted_volume)
        await self.coordinator.async_request_refresh()

    async def async_volume_up(self):
        """Volume up the Media Player."""
        await self.coordinator.client.async_volume_up()
        await self.coordinator.async_request_refresh()

    async def async_volume_down(self):
        """Volume down Media Player."""
        await self.coordinator.client.async_volume_down()
        await self.coordinator.async_request_refresh()

    async def async_mute_volume(self, mute):
        """Send mute command."""
        await self.coordinator.client.async_mute()
        await self.coordinator.async_request_refresh()

    async def async_select_source(self, source):
        """Set the input source."""
        sources = self.coordinator.data.get("input_output_state", {}).get(
            "transformed_sources", None
        )

        if sources is None:
            return

        try:
            index, tag = next(
                (index, key)
                for index, key in enumerate(sources)
                if sources[key] == source or key == source
            )
        except StopIteration:
            raise ValueError(f"Source {source} not found")

        await self.coordinator.client.async_set_input(index, tag)

    async def async_media_play_pause(self):
        """Simulate play pause Media Player."""
        await self.coordinator.client.async_toggle_play_pause()
        await self.coordinator.async_request_refresh()

    async def async_media_play(self):
        """Send play command."""
        if self._state is not MediaPlayerState.PLAYING:
            await self.coordinator.client.async_toggle_play_pause()
            await self.coordinator.async_request_refresh()

    async def async_media_pause(self):
        """Send pause command."""
        if self._state is MediaPlayerState.PLAYING:
            await self.coordinator.client.async_toggle_play_pause()
            await self.coordinator.async_request_refresh()

    async def async_media_next_track(self):
        """Send next track command."""
        await self.coordinator.client.async_next_title()
        await self.coordinator.async_request_refresh()

    async def async_media_previous_track(self):
        """Send the previous track command."""
        await self.coordinator.client.async_previous_title()
        await self.coordinator.async_request_refresh()


from django.shortcuts import render
from django.http import HttpResponse, HttpResponseNotFound, JsonResponse
from django.conf import settings
from django.core.files.storage import FileSystemStorage
import time
import os.path
from . import steg as lsbsteg
from . import filesteg as lsbfilesteg

UPLOAD_ROOT = os.path.dirname(os.path.realpath(__name__))

# Create your views here.

def index(request):
    return render(request, 'index.html', {})

def encode(request):
    return render(request, 'encode.html', {})

def process_encoding_data(request):
    if request.method == 'POST' and request.FILES['coverimage']:
        coverimage = upload_file(request.FILES['coverimage'])
        if request.POST.get('istextsteg'):
            message = request.POST.get('message')
            stegImage = encode_image_text_steg(message, coverimage)
            return JsonResponse(status=200, data={'status': 'true', 'location': '../' + stegImage})

        else:
            textstegfile = upload_file(request.FILES['textfile'])
            stegImage = encode_image_text_file_steg(textstegfile, coverimage)
            return JsonResponse(status=200, data={'status': 'true', 'location': '../' + stegImage})
    if request.method == 'GET':
        return HttpResponseNotFound('
Not Allowed
')

def encode_image_text_steg(message, coverimg):
    if message == '':
        message = 'no text found'
    if coverimg is not None:
        newImg = lsbsteg.encodeLSB(message, UPLOAD_ROOT + coverimg)
        if not newImg is None:
            return newImg
        else:
            return

def encode_image_text_file_steg(textfile, coverimg):
    if coverimg is not None and textfile is not None:
        newImg = lsbfilesteg.encodeLSB(UPLOAD_ROOT + textfile, UPLOAD_ROOT + coverimg)
        if not newImg is None:
            return newImg
        else:
            return

def decode(request):
    return render(request, 'decode.html', {})

def process_decoding_data(request):
    if request.method == 'POST' and request.FILES['stegimage']:
        steg_image = upload_file(request.FILES['stegimage'])
        if request.POST.get('istextsteg'):
            messageDecoded = decode_text_from_image(steg_image)
            return JsonResponse(status=200, data={'status': 'true', 'message': messageDecoded})

        else:
            textfile = decode_textfile_from_image(steg_image)
            return JsonResponse(status=200, data={'status': 'true', 'location': '../' + textfile})
    if request.method == 'GET':
        return HttpResponseNotFound('
Not Allowed
')

def decode_text_from_image(steg_image):
    if steg_image is not None:
        message_decoded = lsbsteg.decodeLSB(UPLOAD_ROOT + steg_image)
        if not message_decoded is None:
            return message_decoded
        else:
            return

def decode_textfile_from_image(steg_image):
    textFile = lsbfilesteg.decodeLSB(UPLOAD_ROOT + steg_image)
    if not textFile is None:
        return textFile
    else:
        return

def upload_file(my_file):
    if my_file is not None:
        fs = FileSystemStorage()
        extension = os.path.splitext(my_file.name)[1]
        filename = fs.save(time_in_millisecond() + extension, my_file)
        uploaded_file_url = fs.url(filename)
        return uploaded_file_url
    else:
        return None

def time_in_millisecond():
    millis = int(round(time.time() * 1000))
    return str(millis)


import re
from django.contrib.sites import requests

__author__ = 'Travis'

def analysis(tweet_list):

    #links to NLP sentiment analysis at http://text-processing.com/demo/sentiment/
    url = 'http://text-processing.com/api/sentiment/'
    payload = {'text':tweet_list}
    response = requests.post(url, data=payload)
    return_string = response.content
    numbers = re.findall('\d+(\.\d{1,5})', return_string)
    neg_int = float(numbers[0])

    # "neutral int" is another number returned by the API
    # but is unused for this app
    # neutral_int = float(numbers[1])
    pos_int = float(numbers[2])

    if pos_int > neg_int:
        label = "POSITIVE"
    else:
        label = "NEGATIVE"

    neg_int = str(int(neg_int*100)) + "%"
    # neutral_int = str(int(neutral_int*100)) + "%"
    pos_int = str(int(pos_int*100)) + "%"
    analysis_results = {'neg_int':neg_int,'label':label, 'pos_int':pos_int}

    return analysis_results

# def dictionary():
#
#     apiUrl = 'http://api.wordnik.com/v4'
#     apiKey = 'YOUR API KEY HERE'
#     client = swagger.ApiClient(apiKey, apiUrl)
#
#     wordApi = WordApi.WordApi(client)
#     example = wordApi.getTopExample('irony')
#     dict_data = {'example_text':example.text}
#
#     return dict_data

    # https://github.com/wordnik/wordnik-python


import sys
move_encoding = {"A":"Rock", "B":"Paper", "C":"Scissors",
 "X":"Rock", "Y":"Paper", "Z":"Scissors"}

beats = {"Rock": "Scissors", "Paper": "Rock", "Scissors": "Paper"}
points_for_choice = {"Rock": 1, "Paper": 2, "Scissors": 3}

def points_for_outcome(opponent, mine):
    if opponent == mine:
        return 3
    elif beats[mine] == opponent:
        return 6
    else:
        return 0

with open(sys.argv[1], "rt") as fd:
    accum = 0
    for line in fd:
        line = line.strip().replace(" ", "")
        opponent, mine = [move_encoding[x] for x in line]
        accum += points_for_choice[mine] + points_for_outcome(opponent, mine)
print(accum)


from typing import List, Any
from random import random
import math
import numpy as np
from sklearn.decomposition import PCA
from math import sqrt

d = 50

def CalcDistant(vec1, vec2):
    vec = np.multiply(np.array(vec1 - vec2), np.array(vec1 - vec2))
    return vec.sum()

#text is a tokenized list of words
def vectorization(text, embed):
    vec = np.zeros((1, d))
    num = 0;
    unknown = 0
    for i in text:
        if i in embed:
            vec += embed[i]
    return vec/np.linalg.norm(vec)

# preprocessing: lowering and splitting
def preprocessing(text):
    text = text.lower()
    stripped_text = ''

    for c in text:
        if ((not c.isalnum()) and (c != ' ') and (len(c.encode(encoding='utf_8')) == 1)):
            stripped_text = stripped_text + ' ' + c + ' '
        else:
            stripped_text += c
    return stripped_text

#tokenization: getting stuff together
def tokenization(text):
    q = text.split(' ')
    while ('' in q):
        q.remove('')
    while ('>' in q):
        q.remove('>')
    while ('<' in q):
        q.remove('<')
    return q

def init_params(layer_sizes,activation):
    d = {}
    for i in range(len(layer_sizes) - 1):
        if ((activation == "sigmoid")|(activation == "tanh")):
            #Xavier
            w = np.random.randn((layer_sizes[i]+1)*layer_sizes[i+1]) * sqrt(1.0/(layer_sizes[i]+1)*layer_sizes[i+1])
            w = np.reshape(w, (layer_sizes[i]+1, layer_sizes[i+1]))
            d[i] = w
        else:
            #He
            w = np.random.randn((layer_sizes[i]+1)*layer_sizes[i+1]) * sqrt(2.0/(layer_sizes[i]+1)*layer_sizes[i+1])
            w = np.reshape(w, (layer_sizes[i]+1, layer_sizes[i+1]))
            d[i] = w

    #last layer
    if ((activation == "sigmoid")|(activation == "tanh")):
            #Xavier
        w = np.random.randn((layer_sizes[-1]+1)*2) * sqrt(1.0/(2*(layer_sizes[-1]+1)))
        w = np.reshape(w, (layer_sizes[-1]+1, 2))
        d[len(layer_sizes) - 1] = w
    else:
            #He
        w = np.random.randn((layer_sizes[-1]+1)*2) * sqrt(2.0/(2*(layer_sizes[-1]+1)))
        w = np.reshape(w, (layer_sizes[-1]+1, 2))
        d[len(layer_sizes) - 1] = w
    return d

def tanh(weight, x): #X is a matrix, weight is a matrix - return matrix
    b = np.dot(x, weight)
    b = 1 + np.exp(-2*b.T)
    return np.array(2/b) - 1

def relu(weight, x): #X is a matrix, weight is a matrix  - return matrix
    b = np.dot(x, weight)
    return np.maximum(b.T, 0)

def sigmoid(weight, x): #X is a matrix, weight is a matrix - return matrix
    b = np.dot(x, weight)
    b = 1 + np.exp(-b.T)
    return np.array(1/b).T

def fully_connected(a_prev, W, activation):
    a_prev = np.insert(a_prev, 0, np.ones(a_prev.shape[0]), 1)
    if (activation == "sigmoid"):
        layer_out = sigmoid (W, a_prev)
    elif (activation == "tanh"):
        layer_out = tanh (W, a_prev)
    elif (activation == "relu"):
        layer_out = relu (W, a_prev)
    else:
        #linear
        layer_out = np.dot(a_prev, W)
        layer_out = layer_out

    return layer_out.T, a_prev, W

def ffnn(X, params, activation):
    cash = []
    for i in params:
        X, tmpcash1, tmpcash2 = fully_connected(X, params[i], activation)
        cash.append (tmpcash1)
        cash.append (tmpcash2)
    X = np.exp(X - np.amax(X, axis = 0))
    X = (X.T/X.sum(axis = 1)).T #softmax
    cash.append (X)
    return X, cash

def softmax_crossentropy(ZL, Y):
    Y = np.array(Y)
    log_likelihood = -np.log(np.dot(ZL.T, Y))
    loss = np.sum(log_likelihood) / len(Y)
    math_expect = np.sum(np.dot(ZL.T, Y))
    return loss

def fully_connected_backward(dA, cache, activation):
    if (activation == "sigmoid"):
        derivative = cache[2]*(1-cache[2])
    elif (activation == "tanh"):
        derivative = 1 - cache[2]*cache[2]
    elif (activation == "relu"):
        derivative = np.maximum(cache[2], 0)
    else:
        #linear
        derivative = cache[2]
    if (dA.shape[1] == derivative.shape[0]):
        tmp = np.dot(dA,derivative)
    else:
        tmp = np.dot(dA.T,derivative)
    check_gradients(activation, cache[2], derivative)
    DZ = np.dot (cache[3], dA.T)*derivative.T
    DW = np.dot(cache[0].T, DZ.T)
    return np.delete(DZ.T, (0), axis = 1), DW

def ffnn_backward(dZL, caches, activation):
    d_param = {}
    dA = dZL
    d_param[-int(len(caches)/2)] = dA
    d_param[int(len(caches)/2)] = np.dot(caches[len(caches) - 4].T,dA)
    for i in range (int(len(caches)) - 4, 0, -2):
        d_param[- int(i/2) - 1], d_param[int(i/2) + 1] = fully_connected_backward(dA, caches[i-2:i+3], activation)
        dA = d_param[- int(i/2) - 1]
    #positive/2 - DZ
    #negative/2 - DW
    return d_param

def softmax_crossentropy_backward(cache):
    dZL = cache[len(cache) - 2] - cache[len(cache) - 1] # ^Y - Y
    return np.array(dZL)

def check_gradients (activation, x, grad):
    h = 0.00001
    if (activation == "sigmoid"):
        correct = (1/(1 + np.exp(-(x + h).T)) - 1/(1 + np.exp(-(x - h).T)))/(2*h)
    elif (activation == "tanh"):
        correct = (2/(1 + np.exp(-2*(x + h).T)) - 2/(1 + np.exp(-2*(x - h).T)))/(2*h)
    elif (activation == "relu"):
        correct = (np.maximum(x + h, 0) - np.maximum(x - h, 0))/(2*h)
    else:
        #linear
        correct = 1
    print ("error = ", np.sum(abs(correct - grad.T).sum(axis = 0)/correct.shape[1]))
    return

def gd_step(params,grads,learning_rate, alpha):
    alpha = 0.0001
    for i in range (len(params)):
        if (params[i].shape[1] != grads[i+2].shape[1]):
            params[i] = params[i] - np.delete(learning_rate*grads[i+2], (0), axis=1) + alpha*params[i]
        else:
            params[i] = params[i] - learning_rate*grads[i+2] + alpha*params[i]
    return params

def train_ffnn(Xtrain, Ytrain, Xdev, Ydev, layer_sizes, learning_rate, num_epochs, batch_size):
    Xtrain -= Xtrain.mean(axis = 0)
    Xtrain /= Xtrain.std(axis = 0)
    X = np.zeros((Ytrain.shape[0], Ytrain.shape[1]))
    print(Ytrain)
    dict_weights = init_params(layer_sizes,"tanh")
    cur_batch = 0
    alpha = 0.001
    for i in range (num_epochs):
        if ((i == 500)|(i == 700)|i == 900):
            learning_rate /= 2
            alpha /= 2
        if (cur_batch + batch_size > Xtrain.shape[0]):
            cur_batch = 0

        #X[cur_batch:cur_batch + batch_size], cache = ffnn(np.insert(Xtrain[cur_batch:cur_batch + batch_size], 0, np.ones(batch_size), 1), dict_weights,"tanh")
        X[cur_batch:cur_batch + batch_size], cache = ffnn(Xtrain[cur_batch:cur_batch + batch_size], dict_weights,"tanh")
        cache.append(np.array(Ytrain[cur_batch:cur_batch + batch_size]))

        print (i, "] precision = ", np.sum(abs((X[cur_batch:cur_batch + batch_size]-Ytrain[cur_batch:cur_batch + batch_size]))/(2*batch_size)))

        dict_grads = ffnn_backward(softmax_crossentropy_backward(cache),cache,"tanh")
        #for i in (dict_grads.keys()):

        dict_weights = gd_step(dict_weights, dict_grads, learning_rate, alpha)
        cur_batch += batch_size

    return dict_weights

def train(
        train_texts: List[str],
        train_labels: List[str],
        pretrain_params: Any = None) -> Any:

    embeddings = {}
    f = open('glove.6B.50d.txt','r')
    for line in f:
        k = line.index(' ')
        embeddings[line[:k]] = np.fromstring(line[k:], sep = ' ')
    matr = np.ones((1, d))

    doc_amount = len(train_texts) # amount of documents in train sample
    y_labels = []
    for i in range(doc_amount):
        new_text = tokenization(preprocessing(train_texts[i]))
        matr = np.append(matr, vectorization(new_text, embeddings), axis=0)

        if (train_labels[i] == 'neg'):
            y_labels = y_labels + [[0, 1]]
        else:
            y_labels = y_labels + [[1, 0]]

    matr = np.delete(matr, (0), axis=0)
    learning_rate = 0.01
    num_epochs = 1200
    batch_size = 5000
    layer_sizes = [d, 200, 100]
    dict_weights = train_ffnn(matr, np.array(y_labels), layer_sizes, learning_rate, num_epochs, batch_size)

    return {'weights': dict_weights, 'embeddings':embeddings}

def classify(texts: List[str], params: Any) -> List[str]:

    embeddings = params['embeddings']
    dict_weights = params['weights']

    doc_amount = len(texts) # amount of documents in train sample
    matr = np.ones((1, d))
    for i in range(doc_amount):
        new_text = tokenization(preprocessing(texts[i]))
        matr = np.append(matr, vectorization(new_text, embeddings), axis=0)

    matr = np.delete(matr, (0), axis=0)
    print("matr shape ", matr.shape)
    X, cache = ffnn(matr, dict_weights, "tanh")

    texts_labels = []
    print (X.shape)
    for i in range(X.shape[0]):
        if (X[i][0] > X[i][1]):
            texts_labels.append('pos')
        else:
            texts_labels.append('neg')
    return texts_labels


import numpy as np
import numpy.linalg as nplg
import scipy.linalg as sclg
from functional import cost_function,gradient,hessian
from modCholDec import modDec
from utilities import unvec

"""
Implemetation of the modified newton method for cost function minimization

"""

def rec(P0, D,W, conv):
    """
    Use the modified newton method to reconstruct the point configuration that
    generate D
    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
    Parameters:
        P0: initial guess, is an (d,n) matrix, where d is the embedding
            dimension and n is the nuber of points
        D: measured (n,n) EDM
        W: (n,n) Mask matrix corresponding to D
        conv: convergence rate
    Returns:
        (d,n) matrix containing the estimated configuration that generates D
    """

    first = 1.#first term of convergence condition
    second = 0.#second term of convergence condition
    P = P0#initial guess
    iter = 0#iter counter

    #starting the cycle
    while first> second:
        #store the old configuration
        POld = P

        #compute hessian and gradient
        G = gradient(P,D,W)
        H = hessian(P,D,W)

        #compute LS via modified cholewsky decomposition
        S,L = modDec(H)

        #find the upgrade term by solving the systems
        epsII = sclg.solve_triangular(L,-G)
        epsI  = nplg.solve(S,epsII)
        eps   = sclg.solve_triangular(L,epsI)
        term = unvec(eps, np.shape(P0))

        #update the guess
        P = P + (2**-iter)*term
        iter +=1

        #update convergence terms
        first = abs(cost_function(P,D,W)-cost_function(POld,D,W))
        second = conv*nplg.norm(P-POld, ord = 2)

    return P