from __future__ import print_function

import pyaudio
import sys
import wave

from io import StringIO

import alsaaudio
import colorama
import pyaudio                          #
import numpy as np

from reedsolo import RSCodec, ReedSolomonError
from termcolor import cprint
from pyfiglet import figlet_format

HANDSHAKE_START_HZ = 4096
HANDSHAKE_END_HZ = 5120 + 1024

START_HZ = 1024
STEP_HZ = 256
BITS = 4

FEC_BYTES = 4

def stereo_to_mono(input_file, output_file):
    inp = wave.open(input_file, 'r')
    params = list(inp.getparams())
    params[0] = 1 # nchannels
    params[3] = 0 # nframes

    out = wave.open(output_file, 'w')
    out.setparams(tuple(params))

    frame_rate = inp.getframerate()
    frames = inp.readframes(inp.getnframes())
    data = np.fromstring(frames, dtype=np.int16)
    left = data[0::2]
    out.writeframes(left.tostring())

    inp.close()
    out.close()

def yield_chunks(input_file, interval):
    wav = wave.open(input_file)
    frame_rate = wav.getframerate()

    chunk_size = int(round(frame_rate * interval))
    printf(chunk_size)
    total_size = wav.getnframes()
    printf(total_size)
    while True:
        chunk = wav.readframes(chunk_size)
        if len(chunk) == 0:
            return

        yield frame_rate, np.fromstring(chunk, dtype=np.int16)

def dominant(frame_rate, chunk):
    w = np.fft.fft(chunk)
    freqs = np.fft.fftfreq(len(chunk))
    peak_coeff = np.argmax(np.abs(w))
    peak_freq = freqs[peak_coeff]
    return abs(peak_freq * frame_rate) # in Hz

def match(freq1, freq2):
    return abs(freq1 - freq2) < 20

def decode_bitchunks(chunk_bits, chunks):
    out_bytes = []

    next_read_chunk = 0
    next_read_bit = 0

    byte = 0
    bits_left = 8
    while next_read_chunk < len(chunks):
        can_fill = chunk_bits - next_read_bit
        to_fill = min(bits_left, can_fill)
        offset = chunk_bits - next_read_bit - to_fill
        byte <<= to_fill
        shifted = chunks[next_read_chunk] & (((1 << to_fill) - 1) << offset)
        byte |= shifted >> offset;
        bits_left -= to_fill
        next_read_bit += to_fill
        if bits_left <= 0:

            out_bytes.append(byte)
            byte = 0
            bits_left = 8

        if next_read_bit >= chunk_bits:
            next_read_chunk += 1
            next_read_bit -= chunk_bits

    return out_bytes

def decode_file(input_file, speed):
    wav = wave.open(input_file)
    if wav.getnchannels() == 2:
        mono = StringIO()
        stereo_to_mono(input_file, mono)

        mono.seek(0)
        input_file = mono
    wav.close()

    offset = 0
    for frame_rate, chunk in yield_chunks(input_file, speed / 2):
        dom = dominant(frame_rate, chunk)
        print("{} => {}".format(offset, dom))
        offset += 1

def extract_packet(freqs):
    freqs = freqs[::2]
    bit_chunks = [int(round((f - START_HZ) / STEP_HZ)) for f in freqs]
    bit_chunks = [c for c in bit_chunks[1:] if 0 <= c < (2 ** BITS)]
    # print(bit_chunks)
    # for a in bit_chunks :
    #     print(a)
    # b = bytearray(decode_bitchunks(BITS, bit_chunks))
    # print(b)
    return bytearray(decode_bitchunks(BITS, bit_chunks))

def out(output):
    # print(output)
    outputlist = []
    for byteOfOutput in output:
        tmp = format(byteOfOutput,'08b')
        frontOfTmp = tmp[:4]
        backOfTmp = tmp[4:]
        # print(frontOfTmp)
        # print(backOfTmp)
        outputlist.append(int(frontOfTmp,2))
        outputlist.append(int(backOfTmp,2))
        # print(outputlist)
    # b'x16/x32/a3 -> [1,6,3,2,10,3] 로 만들어줌.
    # print(outputlist)

    outfreqs = [ x * STEP_HZ + START_HZ  for x in outputlist]
    #주파수로 다시 래핑해주기.
    # print(outfreqs)

    p = pyaudio.PyAudio()
    stream = p.open(format=pyaudio.paFloat32,channels=1,rate=44100,output = True)
    # p = pyaudio.PyAudio()
    for freq in outfreqs:
        samples = (np.sin(2*np.pi*np.arange(44100*0.6)*freq/44100)).astype(np.float32)
        stream.write(samples)
        print("freq : " + str(freq))

def display(s):
    cprint(figlet_format(s.replace(' ', '   '), font='doom'), 'yellow')

def listen_linux(frame_rate=44100, interval=0.1):

    mic = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, device="default")
    mic.setchannels(1)
    mic.setrate(44100)
    mic.setformat(alsaaudio.PCM_FORMAT_S16_LE)
    num_frames = int(round((interval / 2) * frame_rate))
    mic.setperiodsize(num_frames)
    print("start...")

    in_packet = False
    packet = []

    while True:
        l, data = mic.read()
        if not l:
            continue

        chunk = np.fromstring(data, dtype=np.int16)
        dom = dominant(frame_rate, chunk)
        # print(dom)

        if in_packet and match(dom, HANDSHAKE_END_HZ):
            byte_stream = extract_packet(packet)
            # print(byte_stream)

            try:
                byte_stream = RSCodec(FEC_BYTES).decode(byte_stream)
                # print(byte_stream)
                # print(type(byte_stream))  # bytearray
                byte_stream = byte_stream.decode("utf-8")
                # print(type(byte_stream)) # '201502087 a' // string

                datas = byte_stream.split(); #list

                if "201502087" in datas:
                    datas.remove("201502087"); # remove 201502087 in list
                    # print(datas)
                    output = " ".join(datas) # output is str of removed datas(list) // string
                # print(output)
                    output = output.encode("utf-8")
                # print(output)
                    output = RSCodec(FEC_BYTES).encode(output) # output bytearray
                    #이제 이거를 소리로 바꾸면 끝.
                    out(output)

                    for data in datas:
                        display(data)
                    # 학번을 제외한 데이터들에 대해 디스플레이 해준다.
                    # display(datas)

            except ReedSolomonError as e:
                pass
                # print("{}: {}".format(e, byte_stream))

            packet = []
            in_packet = False
        elif in_packet:
            packet.append(dom)
        elif match(dom, HANDSHAKE_START_HZ):
            in_packet = True

if __name__ == '__main__':
    colorama.init(strip=not sys.stdout.isatty())

    #decode_file(sys.argv[1], float(sys.argv[2]))
    # with noalsaerr():
    #     p = pyaudio.PyAudio()
    #
    # volume = 0.5     # range [0.0, 1.0]
    # fs = 44100       # sampling rate, Hz, must be integer
    # duration = 1.0   # in seconds, may be float
    # f = 440.0        # sine frequency, Hz, may be float
    #
    # # generate samples, note conversion to float32 array
    # samples = (np.sin(2*np.pi*np.arange(fs*duration)*f/fs)).astype(np.float32)
    #
    # # for paFloat32 sample values must be in range [-1.0, 1.0]
    # stream = p.open(format=pyaudio.paFloat32,channels=1,rate=fs,output=True)
    #
    #             # play. May repeat with different volume values (if done interactively)
    # stream.write(volume*samples)
    listen_linux()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import argparse
import time
from datetime import datetime, timedelta
import pandas as pd
import yaml
import numpy as np
import logging

def run(args):
    target_path = args.path
    with open(args.config_file, encoding='utf8') as fd:
        config = yaml.safe_load(fd)

    # DualThrustStrategy
    # 1. config
    config['strategy']['DualThrustStrategy']['params']['G'] = 20

    # 2. data
    sname = 'dual_thrust'
    index = pd.date_range('1/1/2020', periods=100, freq='T')
    s1 = pd.Series(range(100), index=index)
    s1.name = 'price'
    s2 = pd.Series(range(100), index=index)
    s2.name = 'volume'
    df = pd.concat([s1, s2], axis=1)
    df.to_csv(f'{target_path}{sname}.csv', header=True, index=True)

    # save config
    with open(args.config_file, 'w') as file:
        yaml.dump(config, file)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Trading session preparation')
    parser.add_argument('--date', help='today')
    parser.add_argument('-f', '--config_file', dest='config_file', default='./config_live.yaml', help='config yaml file')
    parser.add_argument('-p', '--path', dest='path', default='./strategy/', help='data path')

    args = parser.parse_args()
    run(args)

    print('Dene session preparation. Ready to trade')


"""groups table

Revision ID: 8c697c377cc6
Revises: 299bf618451d
Create Date: 2019-05-05 11:21:15.611868

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '8c697c377cc6'
down_revision = '299bf618451d'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('group', sa.Column('group', sa.String(length=120), nullable=True))
    op.create_index(op.f('ix_group_group'), 'group', ['group'], unique=False)
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_index(op.f('ix_group_group'), table_name='group')
    op.drop_column('group', 'group')
    # ### end Alembic commands ###


"""
Created on Fri Jan 29 2020

"""

# IMPORTED LIBRARIES

import os
import datetime, time
import sys

import pandas
import numpy as np
import matplotlib.pyplot as plt

import serial
from serial.tools import list_ports

# MAIN PROGRAM

if __name__ == "__main__":

    listed_ports = list_ports.comports()

    print("COM Ports Connected: ")

    for port in listed_ports:
        print("{}".format(port))

    port_selected = input("Selected port: ")
    material = input("Target material (blood, fat, muscle): ")

    if port_selected != "":
        ser = serial.Serial(port = "COM{}".format(port_selected), baudrate = 9600, bytesize = 8)

        # this will store the line
        dataStream = []

        byteLine = []

        for i in range(100):
            for c in ser.read():
                byteLine.append(c)
                if c == '\n':
                    dataStream.append(byteLine)
                    print(byteLine)
                    byteLine = []

        np.savetxt("{}.csv".format(material), np.asarray(dataStream), delimiter=",")

        ser.close()


import secrets

NUMBER_OF_NETWORK_PARTICIPANTS = 1000
NUMBER_OF_BRANCHES = 3
MAX_HOPS = 8
MIN_HOPS = 5
MIN_UNIQUE_HOPS = 5

class Node():
	def __init__(self , id):
		self.publicKey = id
		self.neighborUD = False
		self.neighborDD = False
		self.neighborUI = False
		self.neighborDI = False
		self.branches = []
		for branch in range(0 , NUMBER_OF_BRANCHES):
			self.branches.append(False)

	def __str__(self):
		return str(self.publicKey)

	def __repr__(self):
		return str(self.publicKey)

def createNodes():
	nodes = []
	for i in range(0 , NUMBER_OF_NETWORK_PARTICIPANTS):
		nodes.append(Node(i))

	for i in range(0 , len(nodes)):
		if ((i + 1) > (NUMBER_OF_NETWORK_PARTICIPANTS - 1)):
			nodes[i].neighborUD = nodes[0]
		else:
			nodes[i].neighborUD = nodes[i + 1]
		if ((i - 1) < 0):
			nodes[i].neighborDD = nodes[(NUMBER_OF_NETWORK_PARTICIPANTS - 1)]
		else:
			nodes[i].neighborDD = nodes[i - 1]
		if ((nodes[i].neighborUD.publicKey + 1) > (NUMBER_OF_NETWORK_PARTICIPANTS - 1)):
			nodes[i].neighborUI = nodes[0]
		else:
			nodes[i].neighborUI = (nodes[i].neighborUD.publicKey + 1)
		if ((nodes[i].neighborDD.publicKey - 1) < 0):
			nodes[i].neighborDI = nodes[(NUMBER_OF_NETWORK_PARTICIPANTS - 1)]
		else:
			nodes[i].neighborDI = nodes[(nodes[i].neighborDD.publicKey - 1)]

	return nodes

def selectValidNode(node , nodes):
	counter = (NUMBER_OF_NETWORK_PARTICIPANTS * 10)
	while (True):
		selection = secrets.choice(nodes)
		if ((selection == node) or (selection == node.neighborUD) or (selection == node.neighborDD) or (selection == node.neighborUI) or (selection == node.neighborDI) or (selection in node.branches) or (all(selection.branches))):
			counter -= 1
			if (counter <= 0):
				for aNode in nodes:
					if (not((aNode == node) or (aNode == node.neighborUD) or (aNode == node.neighborDD) or (aNode == node.neighborUI) or (aNode == node.neighborDI) or (aNode in node.branches) or (all(selection.branches)))):
						return aNode
				return 'X'
		else:
			return selection

def establishBranches(nodes):
	for i in range(0 , len(nodes)):
		for branchNum in range(0 , NUMBER_OF_BRANCHES):
			if (not(nodes[i].branches[branchNum])):
				validNode = selectValidNode(nodes[i] , nodes)
				if (validNode == 'X'):
					nodes[i].branches[branchNum] = validNode
					continue
				for chosenNodeBranchCounter in range(0 , NUMBER_OF_BRANCHES):
					if (not(validNode.branches[chosenNodeBranchCounter])):
						nodes[nodes.index(validNode)].branches[chosenNodeBranchCounter] = nodes[i]
						break

				nodes[i].branches[branchNum] = validNode

	return nodes

def findPaths(nodes , printResults = False , returnResults = False):
	import time
	startTime = time.time()

	paths = []
	numHopsProcessed = 0
	numTimesEndNodeReached = 0
	numTimesEndNodeReachedWithinHopCount = 0
	numTimesHopCountExceeded = 0

	startingNode = secrets.choice(nodes)
	endingNode = secrets.choice(nodes)

	def recursivePathTraversal(node = startingNode , inheritedPath = []):
		nonlocal paths , numHopsProcessed , numTimesEndNodeReached , numTimesEndNodeReachedWithinHopCount , numTimesHopCountExceeded
		numHopsProcessed += 1

		if (node == 'X'):
			return

		currentPath = []
		for item in inheritedPath:
			currentPath.append(item)
		currentPath.append(node)

		if (node == endingNode):
			numTimesEndNodeReached += 1
			if ((len(currentPath) >= MIN_HOPS) and (len(currentPath) <= MAX_HOPS)):
				numTimesEndNodeReached += 1
				numTimesEndNodeReachedWithinHopCount += 1
				paths.append(currentPath)
				return

		if (len(currentPath) >= MAX_HOPS):
			numTimesHopCountExceeded += 1
			return

		if (not(node.neighborUD == currentPath[(len(currentPath) - 1)])):
			recursivePathTraversal(node.neighborUD , currentPath)
		if (not(node.neighborDD == currentPath[(len(currentPath) - 1)])):
			recursivePathTraversal(node.neighborDD , currentPath)
		for branchNum in range(0 , NUMBER_OF_BRANCHES):
			if (not(node.branches[branchNum] == currentPath[(len(currentPath) - 1)])):
				recursivePathTraversal(node.branches[branchNum] , currentPath)

	recursivePathTraversal()

	filteredPaths = []
	for path in paths:
		unique = set()
		for item in path:
			unique.add(item)
		if (len(unique) >= MIN_UNIQUE_HOPS):
			filteredPaths.append(path)

	endTime = time.time()

	if (printResults):
		print('Number of hops processed:' , numHopsProcessed)
		print('Number of valid paths found:' , len(filteredPaths))
		print('Number of times correct end node found:' , numTimesEndNodeReached)
		print('Number of times correct end node found within desired hop count:' , numTimesEndNodeReachedWithinHopCount)
		print('Number of times the max hop count was exceeded' , numTimesHopCountExceeded)
		print('It took' , (endTime - startTime) , 'seconds to process all of the possible paths.')

	if (returnResults):
		return numHopsProcessed , len(filteredPaths) , numTimesEndNodeReached , numTimesEndNodeReachedWithinHopCount , numTimesHopCountExceeded , (endTime - startTime)

def getAverageResults(iterations = 1000):
	counter = 0
	avgNumHopsProcessed = 0
	avgValidPaths = 0
	avgNumTimesEndNodeReached = 0
	avgNumTimesEndNodeReachedWithinHopCount = 0
	avgNumTimesHopCountExceeded = 0
	avgTime = 0
	for i in range(0 , iterations):
		numHopsProcessed , validPaths , numTimesEndNodeReached , numTimesEndNodeReachedWithinHopCount , numTimesHopCountExceeded , time = findPaths(establishBranches(createNodes()) , False , True)
		counter += 1
		avgNumHopsProcessed += numHopsProcessed
		avgValidPaths += validPaths
		avgNumTimesEndNodeReached += numTimesEndNodeReached
		avgNumTimesEndNodeReachedWithinHopCount += numTimesEndNodeReachedWithinHopCount
		avgNumTimesHopCountExceeded += numTimesHopCountExceeded
		avgTime += time

	print('Average number of hops processed:' , (avgNumHopsProcessed / counter))
	print('Average number of valid paths found:' , (avgValidPaths / counter))
	print('Average number of times correct end node found:' , (avgNumTimesEndNodeReached / counter))
	print('Average number of times correct end node found within desired hop count:' , (avgNumTimesEndNodeReachedWithinHopCount / counter))
	print('Average number of times the max hop count was exceeded' , (avgNumTimesHopCountExceeded / counter))
	print('It took' , (avgTime / counter) , 'seconds on average to process all of the possible paths.')

#findPaths(establishBranches(createNodes()) , True)
getAverageResults()


from .. import mesh
from .. import delaunay
from .. import geometry
import numpy as np
import collections

def init(
    outer_radius,
    curvature_radius,
    fn_hex_grid=10,
    ref="spherical_pixel_cap",
):
    cap = mesh.init()
    cap["vertices"] = geometry.grid.hexagonal.init_from_outer_radius(
        outer_radius=2.0 * outer_radius, ref="hex", fn=fn_hex_grid
    )

    for k in cap["vertices"]:
        cap["vertices"][k][2] = geometry.sphere.surface_height(
            x=cap["vertices"][k][0],
            y=cap["vertices"][k][1],
            curvature_radius=curvature_radius,
        )

    for k in cap["vertices"]:
        cap["vertex_normals"][k] = geometry.sphere.surface_normal(
            x=cap["vertices"][k][0],
            y=cap["vertices"][k][1],
            curvature_radius=curvature_radius,
        )

    mtl_key = ref
    cap["materials"][mtl_key] = collections.OrderedDict()

    all_grid_faces = delaunay.make_faces_xy(vertices=cap["vertices"], ref=ref)

    for fkey in all_grid_faces:
        vkey_a = all_grid_faces[fkey]["vertices"][0]
        vkey_b = all_grid_faces[fkey]["vertices"][1]
        vkey_c = all_grid_faces[fkey]["vertices"][2]

        va = cap["vertices"][vkey_a]
        vb = cap["vertices"][vkey_b]
        vc = cap["vertices"][vkey_c]

        ra = np.hypot(va[0], va[1])
        rb = np.hypot(vb[0], vb[1])
        rc = np.hypot(vc[0], vc[1])

        if ra <= outer_radius and rb <= outer_radius and rc <= outer_radius:
            cap["materials"][mtl_key][fkey] = all_grid_faces[fkey]
            cap["materials"][mtl_key][fkey]["vertex_normals"] = [
                vkey_a,
                vkey_b,
                vkey_c,
            ]

    return mesh.remove_unused_vertices_and_vertex_normals(mesh=cap)


from flask import Blueprint, render_template, flash, session, Flask

user = Blueprint('user', __name__, template_folder='../assets/templates/user', static_folder='../assets/static', url_prefix="/user")

from app import mysql

@user.route('/')
def test():
    test=mysql.query_db("select * from frappe.books")
    print(test)
    return render_template('user_dashboard.html')


import os

from hanspell.spell_checker import fix

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'

import tensorflow as tf

import data
import generative_model.model as ml
from generative_model.configs import DEFINES

tf.logging.set_verbosity(tf.logging.ERROR)
char2idx, idx2char, vocabulary_length = data.load_vocabulary()

while True:
    saved_answer = ''
    print("> 사용자 : ", end='')
    predic_input_enc, predic_input_enc_length = data.enc_processing([fix(input())], char2idx)
    predic_output_dec, predic_output_dec_length = data.dec_output_processing([""], char2idx)
    predic_target_dec = data.dec_target_processing([""], char2idx)
    classifier = tf.estimator.Estimator(
        model_fn=ml.Model,  # 모델 등록한다.
        model_dir=DEFINES.check_point_path,  # 체크포인트 위치 등록한다.
        params={  # 모델 쪽으로 파라메터 전달한다.
            'hidden_size': DEFINES.hidden_size,  # 가중치 크기 설정한다.
            'learning_rate': DEFINES.learning_rate,  # 학습율 설정한다.
            'vocabulary_length': vocabulary_length,  # 딕셔너리 크기를 설정한다.
            'embedding_size': DEFINES.embedding_size,  # 임베딩 크기를 설정한다.
            'max_sequence_length': DEFINES.max_sequence_length,
        })

    for i in range(25):
        if i > 0:
            predic_output_dec, predic_output_decLength = data.dec_output_processing([answer], char2idx)
            predic_target_dec = data.dec_target_processing([answer], char2idx)

        predictions = classifier.predict(
            input_fn=lambda: data.eval_input_fn(predic_input_enc, predic_output_dec, predic_target_dec, 1))

        answer = data.pred_next_string(predictions, idx2char)
        if len(answer) == len(saved_answer):
            break
        else:
            saved_answer = answer

    print("> 인공지능 : ", fix(answer))


try:
    import json
    import itertools
    import uuid
    import sys
    import requests
    from requests_futures.sessions import FuturesSession
    import os
    import datetime
    import pandas as pd
    from bs4 import BeautifulSoup
except Exception as e:
    print("Some Modules are Missings ")

class BaseUrl(object):
    def __init__(self, Query=''):
        self.url = "https://www.google.co.in/search?q=%s&source=lnms&tbm=isch"
        self.__query = Query
        self.baseurl = self.url % self.__query
        self.headers = {'User-Agent': "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36"}
        print(self.baseurl)

class WebCrawler(object):
    def __init__(self, Query, numberImage=100):
        self.maxImage = numberImage
        self.query = Query
        self.baseurl = BaseUrl(Query=self.query)

    def soup(self):
        response = requests.get(self.baseurl.baseurl, headers=self.baseurl.headers)
        return BeautifulSoup(response.text, 'html.parser')

    def getImageURl(self):

        if (self.maxImage >100):
            print("Number of Images cannot exceeds 100")
        else:
            soup = self.soup()
            image_elements = soup.find_all("div", {"class": "rg_meta"})
            metadata_dicts = (json.loads(e.text) for e in image_elements)
            link_type_records = ((d["ou"], d["ity"]) for d in metadata_dicts)
            return itertools.islice(link_type_records, self.maxImage)

class GoogleImageDownloader(object):
    def __init__(self, Query, numberImage=100):
        self.query = Query
        self.numofImage = numberImage
        self.crawler = WebCrawler(Query=self.query, numberImage=self.numofImage)

    def getUrls(self):
        data = self.crawler.getImageURl()
        data = [ (i, url) for i, (url, image_type) in enumerate(data) ]
        return data

    def saveCsv(self):
        data = self.getUrls()
        df = pd.DataFrame(data=data)
        df.to_csv("Result.csv")
        print("Saved on your Computer with Result.csv")

    def saveJson(self):
        data = self.getUrls()
        df = pd.DataFrame(data=data)
        df.to_json("Result.json")
        print("Saved on your Computer with Result.json")

    def downloadImages(self):

        data = self.getUrls()
        df = pd.DataFrame(data=data, columns=["No", "Url"])

        start = datetime.datetime.now()

        with FuturesSession() as sess:
            futures = [sess.get(url) for i, url in enumerate(df["Url"].to_list())]
            for i, url in enumerate(futures):

                print("Downloading Image {}".format(i))

                data = url.result().content

                cwd = os.getcwd()                           # get CWD
                folder = 'Images'                           # Create Folder Logs
                newPath = os.path.join(cwd, folder)         # change Path

                try:
                    """ try to create directory """
                    os.mkdir(newPath)                   # create Folder

                except Exception as e:

                    """ Directory already exists """

                    filename = "{}.jpg".format(i)
                    completePath = os.path.join(newPath, filename)

                    with open(completePath, "wb") as f:
                        f.write(data)

        end = datetime.datetime.now()
        print("Total Time : {}".format(end-start))

#
# if __name__ == "__main__":
#     image = GoogleImageDownloader(Query="Dog", numberImage=50)
#     image.saveCsv()         # saves all the URL in CSV File
#     image.saveJson()        # saves all the URL in JSON Format
#     image.downloadImages()  # Download all Images and stores inside the folder called Images


from datetime import datetime

from django.core.validators import MinValueValidator, MaxValueValidator
from django.db import models, transaction

# Create your models here.
from django.utils import timezone

class Company(models.Model):
    name = models.CharField(max_length=200, verbose_name="Company Name")
    balance = models.IntegerField(verbose_name="Company Account Balance", validators=[MinValueValidator(0)] )
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = "Companies"

class Employee(models.Model):
    name = models.CharField(max_length=50, verbose_name="Employee Name")
    surname = models.CharField(max_length=50, verbose_name="Employee Surname")
    company = models.ForeignKey(Company, verbose_name="Company", on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name + self.surname

class BudgetChoices(models.IntegerChoices):
    LOW = 300, 'Low $300'
    HIGH = 500, 'High $400'

class Card(models.Model):
    BUDGET_CHOICES = (
        (300, 'Low ( $300 )'),
        (500, 'High ( $500 )'),
    )
    employee = models.OneToOneField(Employee, related_name="card", verbose_name="Employee", on_delete=models.CASCADE)
    budget = models.IntegerField(default=BudgetChoices.LOW, choices=BudgetChoices.choices)
    balance = models.IntegerField(verbose_name="Card Balance", default=0, validators=[MinValueValidator(0)] )
    created_at = models.DateTimeField(auto_now_add=True)

    def save(self, *args, **kwargs):
        if not self.pk:
            budget_per_day = self.budget / 30
            created_day = datetime.now().day
            ## money is deposited for the remaining days until the end of the month
            self.balance = (31 - created_day) * budget_per_day
        super(Card, self).save(*args, **kwargs)

    def __str__(self):
        return f"{self.employee}'s card"

class Restaurant(models.Model):
    name = models.CharField(max_length=50, verbose_name= "Restaurant Name")
    created_at = models.DateTimeField(auto_now_add=True)
    balance = models.IntegerField(verbose_name="Restaurant Balance", default=0, validators=[MinValueValidator(0)] )

    def __str__(self):
        return self.name

class Transaction(models.Model):
    TRANSACTION_TYPE = (('top-up', 'Top-Up'), ('purchase', 'Purchase'))
    card = models.ForeignKey(Card, related_name="transactions", verbose_name="Card", on_delete=models.CASCADE)
    transaction_type = models.CharField(choices=TRANSACTION_TYPE, max_length=20, verbose_name="Transaction Type")

    amount = models.IntegerField(verbose_name="Amount", default=0)
    restaurant = models.ForeignKey(Restaurant, related_name="transactions", verbose_name="Restaurant", on_delete=models.CASCADE, null=True, blank=True)
    is_success = models.BooleanField(verbose_name="Was the transaction successful?", default=False)
    status_message = models.CharField(max_length=100, verbose_name="Status Message", default="-Status message goes here-")
    created_at = models.DateTimeField(auto_now_add=True)

    def save(self, *args, **kwargs):
        if not self.pk:
            card = self.card
            company = self.card.employee.company
            if self.transaction_type == "top-up":
                if card.budget > company.balance:
                    self.is_success=False
                    self.status_message = "Top-Up failed. I think the company went bankrupt :("
                else:
                    card.balance = card.budget
                    company.balance -= card.budget
                    self.is_success = True
                    self.status_message = "The card is fulled"
            elif self.transaction_type == "purchase":
                if self.amount > card.balance:
                    self.is_success = False
                    self.status_message = "Insufficient balance."
                else:
                    card.balance -= self.amount
                    self.restaurant.balance += self.amount
                    self.is_success = True
                    self.status_message = "Purchase successful."
                    self.restaurant.save()
            card.save()
            company.save()

        super(Transaction, self).save(*args, **kwargs)

    def __str__(self):
        return self.transaction_type

class Refund(models.Model):
    transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

    def save(self, *args, **kwargs):
        if not self.pk:
            with transaction.atomic():
                restaurant = self.transaction.restaurant
                restaurant.balance -= self.transaction.amount
                self.transaction.card.balance += self.transaction.amount
                restaurant.save()
                self.transaction.card.save()


from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
import pymorphy2
import regex as re
import nltk

import numpy as np
from PIL import Image, ImageChops, ImageEnhance
from numpy import array

import os
from joblib import load
np.random.seed(2)

class FakeDetection:
    def __init__(self,model):
        self.model = model
    def predict(self,sample):
        answer = self.model.predict(sample)
        return answer
    def preprocessing(self,data):
        pass

class TextFakeDetector(FakeDetection):
    def __init__(self,model,vectorizer_path):
        super().__init__(model)
        self.vectorizer=load(vectorizer_path)
        nltk.download('stopwords')
        nltk.download('punkt')
        self.stop_words = stopwords.words("russian")
        self.morph=pymorphy2.MorphAnalyzer(lang='ru')

    def predict(self, sample):
        answer = super().predict(self.preprocessing(sample))
        return answer[0]==1

    def preprocessing(self, data):
        clean_txt = []
        tokenized_sent = word_tokenize(data.lower().strip(),language="russian")
        tokenized_sent=[self.morph.parse(x)[0].normal_form for x in tokenized_sent if x not in self.stop_words and (re.sub(r'[^\w\s]', '', x)!='') and re.search(r'[0-9]+',x) is None and re.search(r'[_a]+',x) is None]
        clean_txt.append(' '.join(tokenized_sent))
        vectorized_txt = self.vectorizer.transform(clean_txt)
        return vectorized_txt

class ImageFakeDetector(FakeDetection):
    def __init__(self,model):
        super().__init__(model)
    def predict(self, sample):
        answer = super().predict(self.preprocessing(sample))
        i=np.argmax(answer[0])
        return i==1, answer[0][i] * 100
    def preprocessing(self, img):
        filename = './tmp/photo'
        resaved_filename = filename + '.resaved.jpg'
        im =img.convert('RGB')
        im.save(resaved_filename, 'JPEG', quality=90)
        resaved_im = Image.open(resaved_filename)
        ela_im = ImageChops.difference(im, resaved_im)
        extrema = ela_im.getextrema()
        max_diff = max([ex[1] for ex in extrema])
        if max_diff == 0:
            max_diff = 1
        scale = 255.0 / max_diff
        ela_im = ImageEnhance.Brightness(ela_im).enhance(scale)
        x = array(ela_im.resize((128, 128))).flatten() / 255.0
        X = np.array(x)
        X=X.reshape(-1, 128, 128, 3)
        os.remove(resaved_filename)
        return X


from ecoevo.entities.entity_manager import EntityManager
from ecoevo.entities.player import Player
from rich import print

if __name__ == "__main__":
    entity_manager = EntityManager()
    player0 = Player(persona='gold_digger', id=0, pos=(1, 1))
    player1 = Player(persona='hazelnut_farmer', id=1, pos=(2, 2))
    player2 = Player(persona='coral_collector', id=2, pos=(6, 3))
    player3 = Player(persona='sand_picker', id=3, pos=(2, 6))
    data = entity_manager.data
    entity_manager.reset_map([player0, player1, player2, player3])
    map = entity_manager.map
    # print(map)
    print(map.keys())

    old_pos = player1.pos
    print(player1.pos)
    print(map[player1.pos])
    entity_manager.execute(player1, (('move', 'up'), None, None))
    print(player1.pos)
    print(map[player1.pos])
    assert old_pos not in map, "Old pos still exists."


import numpy as np
import tensorflow.compat.v1 as tf
from sklearn import linear_model
import utils

class LinearRegression():
    def __init__(self, session, loss="l2", lammy=1, num_epochs=40, learning_rate=0.1, verbose=0):
        self.loss = loss
        self.lammy = lammy
        self.num_epochs = num_epochs
        self.verbose = verbose
        self.learning_rate = learning_rate
        self.w = None
        self.b = None
        self.session = session
        tf.disable_eager_execution()

    def fit(self, X, y):
        x_tf = tf.placeholder(tf.float32, shape=X.shape)
        y_tf = tf.placeholder(tf.float32, shape=y.shape)
        self.w = tf.get_variable("W", (X.shape[1], 1), tf.float32, tf.zeros_initializer())
        self.b = tf.get_variable("B", (1, 1), tf.float32, tf.zeros_initializer())
        cost = self.compute_cost(x_tf, y_tf)
        optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate).minimize(cost)
        init = tf.global_variables_initializer()
        self.session.run(init)
        last_cost = 0
        for epoch in range(self.num_epochs + 1):
            _, epoch_cost = self.session.run([optimizer, cost], feed_dict={x_tf: X, y_tf: y})
            if abs(epoch_cost - last_cost) < 1e-10:
                break
            last_cost = epoch_cost
            if self.verbose > 0:
                print("Cost after epoch %i: %f" % (epoch, epoch_cost))

    def predict(self, X):
        x = tf.placeholder(tf.float32, shape=X.shape)
        prediction = tf.add(tf.matmul(x, self.w), self.b)
        result = self.session.run(prediction, feed_dict={x: X})
        return result

    def compute_cost(self, X, y):
        result = tf.add(tf.matmul(X, self.w), self.b)
        rsq = tf.reduce_mean((result - y) ** 2)
        if self.loss == 'l2':
            return rsq + self.lammy * tf.reduce_sum(self.w ** 2) / 2
        else:
            return rsq + self.lammy * tf.reduce_sum(tf.abs(self.w))

if __name__ == '__main__':
    X_train, X_test, y_train, y_test = utils.preprocess_avocado()

    with tf.Session() as sess:
        model = LinearRegression(sess, verbose=1, loss='l1', learning_rate=0.01, num_epochs=500)
        model.fit(X_train, y_train)
        pred = model.predict(X_test)

    difference = np.mean(np.square(pred - np.array(y_test)))
    print("The test error is: ", difference)

    model = linear_model.LinearRegression()
    model.fit(X_train, y_train)
    pred = model.predict(X_test)
    difference = np.mean(np.square(pred - np.array(y_test)))
    print("The test error from sk-learn is: ", difference)


import base64
import subprocess
import time
from functools import cached_property

import requests

from helpers import print_message

class ImageUploadServiceBase:
    """Base Class for All Image Upload Services"""

    def __init__(self, configuration):
        self.configuration = configuration
        self.images_to_upload = []
        self.uploaded_images = []

    def _upload_single_image(self, filename, image_data):
        """
        Main Method to Upload a Single Images.

        All Child Classes May Implement The `_upload_single_image` Method
        Must return a image URL or None
        """
        return None

    def add(self, file_path, filename, image_data):
        self.images_to_upload.append(
            {
                'file_path': file_path,
                'filename': filename,
                'data': image_data
            }
        )

    def upload(self):
        """
        Main Method to Upload Images.

        Child Classes May Override The `upload` Method
        Must return a list of dictionaries

        [{
            'file_path': file_path,
            'filename': filename,
            'url': image_url
        }]
        """
        print_message('Upload Screenshots', message_type='group')

        for file in self.images_to_upload:
            filename = file['filename']
            image_url = self._upload_single_image(filename, file['data'])
            if image_url:
                self.uploaded_images.append(
                    {
                        'file_path': file['file_path'],
                        'filename': filename,
                        'url': image_url
                    }
                )
                # Sleep for 2 seconds after each successful image upload
                time.sleep(2)

        print_message('', message_type='endgroup')

        return self.uploaded_images

class ImgurImageUploadService(ImageUploadServiceBase):
    """Service to Upload Images to Imgur"""

    IMGUR_API_URL = 'https://api.imgur.com/3/upload'

    def _upload_single_image(self, filename, image_data):
        """Upload a Single Image to Imgur using Imgur API"""
        response = requests.post(
            self.IMGUR_API_URL,
            files={
                "image": image_data,
            },
            data={
                'name': filename
            }
        )

        data = response.json()

        if response.status_code == 200 and data['success']:
            link = data['data']['link']
            print_message(f'Image "{filename}" Uploaded to "{link}"')
            return link
        else:
            print_message(
                f'Failed to Upload Image "{filename}". '
                f'Status Code: {response.status_code}'
            )
            return None

class GitHubBranchImageUploadService(ImageUploadServiceBase):
    """Service to Upload Images to GitHub Branch"""

    GITHUB_API_URL = 'https://api.github.com'
    BRANCH_NAME = 'webpage-screenshot-action-branch'
    IMAGE_UPLOAD_DIRECTORY = 'webpage-screenshots'
    AUTHOR_NAME = 'github-actions[bot]'
    AUTHOR_EMAIL = 'github-actions[bot]@users.noreply.github.com'

    @cached_property
    def _request_headers(self):
        """Get headers for GitHub API request"""
        return {
            'Accept': 'application/vnd.github.v3+json',
            'authorization': f'Bearer {self.configuration.GITHUB_TOKEN}'
        }

    def _setup_git_branch(self):
        """Set Up Git Branch"""
        print_message('Setup GitHub Branch', message_type='group')
        subprocess.run(['git', 'config', 'user.name', self.AUTHOR_NAME])
        subprocess.run(['git', 'config', 'user.email', self.AUTHOR_EMAIL])

        subprocess.run(
            ['git', 'fetch', 'origin', '--prune', '--unshallow'],
        )

        remote_branches = subprocess.check_output(
            ['git', 'branch', '-r'],
        )

        if self.BRANCH_NAME not in str(remote_branches):
            subprocess.run(
                ['git', 'checkout', '-b', self.BRANCH_NAME]
            )
            subprocess.run(
                ['git', 'push', '-u', 'origin', self.BRANCH_NAME]
            )
        else:
            print_message(f'Branch "{self.BRANCH_NAME}" Already Exists')
        print_message('', message_type='endgroup')

    def _get_github_image_url(self, filename):
        """Get GitHub Image URL"""
        return (
            f'https://github.com/{self.configuration.GITHUB_REPOSITORY}/raw'
            f'/{self.BRANCH_NAME}/{self.IMAGE_UPLOAD_DIRECTORY}/{filename}'
        )

    def _upload_single_image(self, filename, image_data):
        url = (
            f'{self.GITHUB_API_URL}/repos/{self.configuration.GITHUB_REPOSITORY}'
            f'/contents/{self.IMAGE_UPLOAD_DIRECTORY}/{filename}'
        )
        data = {
            'message': (
                '[webpage-screenshot-action] Added Screenshots for '
                f'PR #{self.configuration.GITHUB_PULL_REQUEST_NUMBER}'
            ),
            'content': base64.b64encode(image_data).decode("utf-8"),
            'branch': self.BRANCH_NAME,
            'author': {
                'name': self.AUTHOR_NAME,
                'email': self.AUTHOR_EMAIL
            },
            'committer': {
                'name': self.AUTHOR_NAME,
                'email': self.AUTHOR_EMAIL
            }
        }

        response = requests.put(
            url,
            headers=self._request_headers,
            json=data
        )

        if response.status_code in [200, 201]:
            link = self._get_github_image_url(filename)
            print_message(f'Image "{filename}" Uploaded to "{link}"')
            return link
        else:
            # API should return 201, otherwise show error message
            msg = (
                f'Error while trying to upload "{filename}" to github. '
                'GitHub API returned error response for '
                f'{self.configuration.GITHUB_REPOSITORY},'
                f'status code: {response.status_code}'
            )
            print_message(msg, message_type='error')
            return None

    def upload(self):
        """Upload Images to a GitHub Branch"""
        if not self.images_to_upload:
            return []

        # Create a new branch
        self._setup_git_branch()

        return super().upload()


import pandas as pd
from sklearn.ensemble import RandomForestClassifier

def predict_by_rf(train_feature, train_label, test_feature):
    rf = RandomForestClassifier(n_estimators=200, n_jobs=10)
    rf.fit(train_feature, train_label)
    return rf.predict(test_feature)

def run():
    # The competition datafiles are in the directory ../input
    # Read competition data files:
    train_data = pd.read_csv("./input/train.csv")
    test_data = pd.read_csv("./input/test.csv")

    train_label, train_feature = train_data['label'], train_data.ix[:, 1:]
    predict_label = predict_by_rf(train_feature, train_label, test_data)

    # write to output
    with open("./output/submission.csv", "w") as f:
        f.write("ImageId,Label\n")
        for k, v in enumerate(predict_label):
            f.write("{},{}\n".format(k+1, v))

run()


# -*- coding: utf-8 -*-
"""
Created on Sun Jul  3 12:41:52 2022

@author: Mohammad
"""

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import time
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
from sklearn.model_selection import KFold
from sklearn.svm import LinearSVC
from sklearn.svm import SVC

data= pd.read_csv(r"C:\Users\Mohammad\Downloads\train.csv")
data=data.drop(["Genus" , "Species", "RecordID","MFCCs_ 1"], axis =1)
x_data=data.drop(["Family"],axis=1)
y_data=data["Family"]
y_data[y_data == "Leptodactylidae"] = 0
y_data[y_data == "Hylidae"] = 1
y_data[y_data == "Dendrobatidae"] = 2
y_data[y_data == "Bufonidae"] = 3
x_data=x_data.to_numpy()
y_data=y_data.to_numpy()
x_data=np.array(x_data, dtype=float)
y_data=np.array(y_data,dtype=float)
x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.3,random_state=3)

#A

start_time = time.time()
gnb = LinearSVC()
gnb=SVC(kernel='linear')
gnb.fit(x_train, y_train)
clock = time.time() - start_time
y_train_pred = gnb.predict(x_train)
acc_train = 100 * accuracy_score(y_train, y_train_pred)

y_test_pred = gnb.predict(x_test)
acc_test = 100 * accuracy_score(y_test, y_test_pred)
print('Training Time :', str(round(clock, 2)), 'Seconds')
print('Train Accuracy is:', str(round(acc_train, 2)), '%')
print('Test Accuracy is:',str(round(acc_test, 2)), '%')
print("Number of support vectors:",str(len(gnb.support_vectors_[:, :])))
plt.plot(acc_train,'r')
plt.plot(acc_test,'c')
plt.ylabel('Accuracy (%)')
plt.xlabel('Iteration')
plt.legend(['Train Accuracy', 'Test Accuracy'], loc='lower right')
plt.grid()
plt.title('Model Accuracy')
plt.show()

#B

C = np.asarray([ 0.001,0.01, 0.1, 1,5, 100])
x_train_v, x_val, y_train_v, y_val = train_test_split(x_train, y_train, test_size=0.3)
kf = KFold(n_splits=4, shuffle=True)
acc_train_c_list = []
acc_val_c_list = []
for c in C:
    acc_train_fold_list = []
    acc_val_fold_list = []
    for train_index, valid_index in kf.split(x_train):
        x_train_fold = x_train[train_index]
        y_train_fold = y_train[train_index]
        x_val_fold = x_train[valid_index]
        y_val_fold = y_train[valid_index]
        gnb = SVC(C=c, kernel='linear')
        gnb.fit(x_train_fold, y_train_fold.ravel())
        y_train_fold_pred = gnb.predict(x_train_fold)
        y_val_fold_pred = gnb.predict(x_val_fold)
        acc_train_fold = 100 * accuracy_score(y_train_fold, y_train_fold_pred)
        acc_val_fold = 100 * accuracy_score(y_val_fold, y_val_fold_pred)
        acc_train_fold_list.append(acc_train_fold)
        acc_val_fold_list.append(acc_val_fold)
    acc_train_c_list.append(sum(acc_train_fold_list) / len(acc_train_fold_list))
    acc_val_c_list.append(sum(acc_val_fold_list) / len(acc_val_fold_list))

acc_val_max = max(acc_val_c_list)
acc_val_max_index = acc_val_c_list. index(acc_val_max)
acc_train_max = acc_train_c_list[acc_val_max_index]
acc_val_max_c = C[acc_val_max_index]

print('---------------------')
print('C with Maximum Validation Accuracy :', acc_val_max_c)
print('Maximum Training Accuracy :', str(round(acc_train_max, 2)), '%')
print('Maximum Validation Accuracy :', str(round(acc_val_max, 2)), '%')
print('---------------------')

fig, ax = plt.subplots()
ax.plot(np.asarray(acc_val_c_list), label='Validation Accuracy')
ax.set_xticklabels(('-', '0.001', '0.01', '0.1', '1', '5', '100'))
ax.legend(loc='best')
plt.xlabel('C')
plt.ylabel('Accuracy')
plt.grid()

gnb = SVC(C=100, kernel='linear')
gnb.fit(x_train, y_train)
y_train_perd = gnb.predict(x_train)
y_test_perd = gnb.predict(x_test)
acc_train = 100 * accuracy_score(y_train, y_train_perd)
acc_train = 100 * accuracy_score(y_test, y_test_perd)

# Print Result

print('Train Accuracy :', str(round(acc_train, 2)), '%')
print('Number of Support Vectors :',len(gnb.support_vectors_))

#c

x_train_v, x_val, y_train_v, y_val = train_test_split(x_train, y_train, test_size=0.3)

Poly2_SVM = SVC(kernel='poly', degree=2)
Poly2_SVM.fit(x_train_v, y_train_v.ravel())
Poly3_SVM = SVC(kernel='poly', degree=3)
Poly3_SVM.fit(x_train_v, y_train_v.ravel())
Poly4_SVM = SVC(kernel='poly', degree=4)
Poly4_SVM.fit(x_train_v, y_train_v.ravel())
Poly5_SVM = SVC(kernel='poly', degree=5)
Poly5_SVM.fit(x_train_v, y_train_v.ravel())
RBF_SVM = SVC(kernel='rbf')
RBF_SVM.fit(x_train_v, y_train_v.ravel())

# For Poly2
y_val_poly2_pred = Poly2_SVM.predict(x_val)
acc_val_poly2 = 100 * accuracy_score(y_val, y_val_poly2_pred)
# For Poly3
y_val_poly3_pred = Poly3_SVM.predict(x_val)
acc_val_poly3 = 100 * accuracy_score(y_val, y_val_poly3_pred)
# For Poly4
y_val_poly4_pred = Poly4_SVM.predict(x_val)
acc_val_poly4 = 100 * accuracy_score(y_val, y_val_poly4_pred)
# For Poly5
y_val_poly5_pred = Poly5_SVM.predict(x_val)
acc_val_poly5 = 100 * accuracy_score(y_val, y_val_poly5_pred)
# For RBF
y_val_rbf_pred = RBF_SVM.predict(x_val)
acc_val_rbf = 100 * accuracy_score(y_val, y_val_rbf_pred)

print('---------------------')
print('Validation Accuracy for Poly2 Kernel :', str(round(acc_val_poly2, 2)), '%')
print('Number of Support Vectors for Poly2 Kernel :',len(Poly2_SVM.support_vectors_))
print('---------------------')
print('Validation Accuracy for Poly3 Kernel :', str(round(acc_val_poly3, 2)), '%')
print('Number of Support Vectors for Poly3 Kernel :',len(Poly3_SVM.support_vectors_))
print('---------------------')
print('Validation Accuracy for Poly4 Kernel :', str(round(acc_val_poly4, 2)), '%')
print('Number of Support Vectors for Poly4 Kernel :',len(Poly4_SVM.support_vectors_))
print('---------------------')
print('Validation Accuracy for Poly5 Kernel :', str(round(acc_val_poly5, 2)), '%')
print('Number of Support Vectors for Poly5 Kernel :',len(Poly5_SVM.support_vectors_))
print('---------------------')
print('Validation Accuracy for RBF Kernel :', str(round(acc_val_rbf, 2)), '%')
print('Number of Support Vectors for RBF Kernel :',len(RBF_SVM.support_vectors_))
print('---------------------')

#D

C = np.asarray([ 0.001,0.01, 0.1, 1,5, 100])

x_train_v, x_val, y_train_v, y_val = train_test_split(x_train, y_train, test_size=0.3)

acc_val_list = []
for c in C:
  RBF_SVM = SVC(C=c, kernel='rbf')
  RBF_SVM.fit(x_train_v, y_train_v)
  y_val_perd = RBF_SVM.predict(x_val)
  acc_val = 100 * accuracy_score(y_val, y_val_perd)
  acc_val_list.append(acc_val)

acc_val_max = max(acc_val_list)
acc_val_max_index = acc_val_list. index(acc_val_max)
acc_val_max_c = C[acc_val_max_index]

print('---------------------')
print('C with Maximum Validation Accuracy :', acc_val_max_c)
print('Maximum Validation Accuracy :', str(round(acc_val_max, 2)), '%')
print('---------------------')

fig, ax = plt.subplots()
ax.plot(np.asarray(acc_val_list), label='Validation Accuracy')
ax.set_xticklabels(('-', '0.001', '0.01', '0.1', '1', '5', '100'))
ax.legend(loc='lower right')
plt.xlabel('C')
plt.ylabel('Accuracy')
plt.title('Validation Accuracy of RBF SVM')
plt.grid()

RBF_SVM = SVC(C=0.001, kernel='rbf')
RBF_SVM.fit(x_train, y_train.ravel())
y_train_perd = RBF_SVM.predict(x_train)
y_test_perd = RBF_SVM.predict(x_test)
acc_train = 100 * accuracy_score(y_train, y_train_perd)
acc_test = 100 * accuracy_score(y_test, y_test_perd)

# Print Result
print('---------------------')
print('Train Accuracy :', str(round(acc_train, 2)), '%')
print('Test Accuracy :', str(round(acc_test, 2)), '%')
print('Number of Support Vectors :',len(RBF_SVM.support_vectors_))
# print('---------------------')

#E

C = np.asarray([ 0.001,0.01, 0.1, 1,5, 100])
kf = KFold(n_splits=4, shuffle=True)
acc_train_c_list = []
acc_val_c_list = []
for c in C:
    acc_train_fold_list = []
    acc_val_fold_list = []
    for train_index, valid_index in kf.split(x_train):
        x_train_fold = x_train[train_index]
        y_train_fold = y_train[train_index]
        x_val_fold = x_train[valid_index]
        y_val_fold = y_train[valid_index]
        gnb = SVC(C=c, kernel='rbf')
        gnb.fit(x_train_fold, y_train_fold.ravel())
        y_train_fold_pred = gnb.predict(x_train_fold)
        y_val_fold_pred = gnb.predict(x_val_fold)
        acc_train_fold = 100 * accuracy_score(y_train_fold, y_train_fold_pred)
        acc_val_fold = 100 * accuracy_score(y_val_fold, y_val_fold_pred)
        acc_train_fold_list.append(acc_train_fold)
        acc_val_fold_list.append(acc_val_fold)
    acc_train_c_list.append(sum(acc_train_fold_list) / len(acc_train_fold_list))
    acc_val_c_list.append(sum(acc_val_fold_list) / len(acc_val_fold_list))

acc_val_max = max(acc_val_c_list)
acc_val_max_index = acc_val_c_list. index(acc_val_max)
acc_train_max = acc_train_c_list[acc_val_max_index]
acc_val_max_c = C[acc_val_max_index]

print('---------------------')
print('C with Maximum Validation Accuracy :', acc_val_max_c)
print('Maximum Validation Accuracy :', str(round(acc_val_max, 2)), '%')
print('---------------------')

fig, ax = plt.subplots()
ax.plot(np.asarray(acc_val_c_list), label='Validation Accuracy')
ax.set_xticklabels(('-', '0.001', '0.01', '0.1', '1', '5', '100'))
ax.legend(loc='lower right')
plt.xlabel('C')
plt.ylabel('Accuracy')
plt.grid()