import sys
from PyQt5.QtWidgets import QMessageBox, QTabWidget
from PyQt5.QtGui import QIcon

class Transfero(QTabWidget):
    def __init__(self, name='Transfero', ax=300, ay=200, aw=1000, ah=500):
        super(Transfero, self).__init__()
        self.setWindowTitle(name)
        self.setGeometry(ax, ay, aw, ah)

        # set icon for window
        self.setWindowIcon(QIcon(':window_icon/WindowIcon/transfero.png'))

    # this method checks whether we unmounted FUSE system or not before actually leaving the program
    def closeEvent(self, e):
        # check if go-mtpfs is mounted, prevent closing window until unmounting system
        go_mtpfs_mounted = self.widget(0).Unmount.isEnabled()
        jmtpfs_mounted = self.widget(1).Unmount.isEnabled()
        mtpfs_mounted = self.widget(2).Unmount.isEnabled()

        if go_mtpfs_mounted:
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Information)
            msg.setWindowTitle('Warning')
            msg.setText('It seems you haven\'t unmounted one of the systems. Please, unmount system(s) and try again.')
            msg.setStandardButtons(QMessageBox.Ok)
            msg.exec_()

            e.ignore()

        elif jmtpfs_mounted:
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Information)
            msg.setWindowTitle('Warning')
            msg.setText('It seems you haven\'t unmounted one of the systems. Please, unmount system(s) and try again.')
            msg.setStandardButtons(QMessageBox.Ok)
            msg.exec_()

            e.ignore()

        elif mtpfs_mounted:
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Information)
            msg.setWindowTitle('Warning')
            msg.setText('It seems you haven\'t unmounted one of the systems. Please, unmount system(s) and try again.')
            msg.setStandardButtons(QMessageBox.Ok)
            msg.exec_()

            e.ignore()

        else:
            # close window
            e.accept()


#! python3
# prettifiedStopwatch.py - Expand the stopwatch project from this
#                          chapter so that it uses the rjust() and
#                          ljust() string methods to “prettify” the
#                          output.
# Adam Pellot

import pyperclip
import time

# Display the program's instructions.
print('''Press ENTER to begin. Afterward, press ENTER to "click" the stopwatch.
Press Ctrl-C to quit.''')
input()                    # Press Enter to begin.
print('Started.')
startTime = time.time()    # Get the first lap's start time.
lastTime = startTime
lapNum = 1

# Start tracking the lap times.
results = []
try:
    while True:
        input()
        lapTime = round(time.time() - lastTime, 2)
        totalTime = round(time.time() - startTime, 2)
        # "Prettified" variables for output.
        pLapNum = str(lapNum).rjust(2)
        pTotalTime = str(totalTime).rjust(6)
        pLapTime = str(lapTime).rjust(6)
        print('Lap #%s: %s (%s)' % (pLapNum, pTotalTime, pLapTime), end='')
        results.append('Lap #%s: %s (%s)' % (pLapNum, pTotalTime, pLapTime))
        lapNum += 1
        lastTime = time.time()  # Reset the last lap time.
except KeyboardInterrupt:
    # Handle the Ctrl-C exception to keep its error message from displaying.
    print('\nDone.')
    # Copy results to clipboard via pyperclip.
    pyperclip.copy('\n'.join(results))


# V1.2 Moving variables .distance and .prev over from inc_graphs.py
# V1.3 Updating for directed graphs

import math
# import inc_graphs as graphs

# g is the graph, t is a list of goal objects, and s is start location (string)
# goal objects have variables .name and .location, where .location is in the graph g
# t can be modified but not g or s
# return a dictionary indexed by goalNames storing the distances to each goal.
def simulPaths(g, t, s):
	# Dijkstra's Algorithm
	distance = {}
	prev = {} # store the paths if you want
	unvisited = []

	# initialize wrt graph g
	for n in g.nodeNames:
		distance[n] = math.inf
		prev[n] = ""
		unvisited.append(n)

	# distance is zero at the start
	distance[s] = 0
	# mandatory false prev value for prev[start]
	prev[s] = s
	# remove start node from unvisited nodes
	unvisited.remove(s)

	# r is the results dictionary
	r = {}
	for gol in t:
		r[gol.name] = math.inf

	# GraphNode object has .name and dictionary .adjList
	currentNode = g.nodes[s]

	# Important Case: goal node is at start node
	for gol in t:
		if(currentNode.name == gol.location):
			r[gol.name] = 0 # distance 0
			t.remove(gol)
			# Check for completion
			if(t == []):
				return r

	while(unvisited != []):
		# update distance for each adjacent node
		for x in list(currentNode.adjList.keys()):
			if(distance[currentNode.name] + g.weight(currentNode.name,x) < distance[x]):
				distance[x] = distance[currentNode.name] + g.weight(currentNode.name, x)
				prev[x] = currentNode.name

		#select the closest unvisited node
		minDist = math.inf
		candidate = "__SOUND__"
		for x in unvisited:
			if(distance[x] < minDist):
				candidate = x
				minDist = distance[x]

		# check for unselectability
		if(candidate == "__SOUND__"):
			print("ERROR: in file inc_shortest_paths.py  . . .")
			print("There is no path between the specified nodes.")
			quit()

		# visit the selected node
		unvisited.remove(candidate)
		currentNode = g.nodes[candidate]

		# check for completion
		# t stands for sinks, r is results.
		for gol in t:
			if(currentNode.name == gol.location):
				r[gol.name] = distance[gol.location]
				t.remove(gol)
				if(t == []):
					return r
	print("ERROR: in file inc_shortest_paths.py  . . .")
	print("All nodes have been visited.")
	quit()


__author__ = 'T90'
__version__ = '1.0.0'

import urllib2 as ulib
from BeautifulSoup import BeautifulSoup

def problem(n):
	url = "https://projecteuler.net/problem=" + str(n)
	u = ulib.urlopen(url)
	data = u.read()
	soup = BeautifulSoup(data)
	h2 = soup.find('h2')
	div = soup.find('div', attrs={'class': 'problem_content'})
	file = open("questions.html", "a")
	content = "

 Problem : " + str(n) + "
" + str(h2) + str(div)
	file.write(content)
	file.close()

for i in xrange(1, 480):
	problem(i)


import numpy

def sub_lines(matrix, ind_from: int, ind_what: int) -> list:
    """
    subtracts lines
    """
    matrix[ind_from] = list(map(lambda x, y: abs(x-y), matrix[ind_from], matrix[ind_what]))
    return matrix

def get_code_offset(matrix, ind_from: int, ind_what: int) -> list:
    """
    returns the distance between all lines
    """
    matrix[ind_from] = list(map(lambda x, y: abs(x-y), matrix[ind_from], matrix[ind_what]))
    return len(list(filter(lambda a: a !=1, matrix[ind_from])))

def should_sub(matrix, ind_from, leading_1_col) -> bool:
    """
    performs a check for the need to subtract a string
    """
    return matrix[ind_from][leading_1_col] == 1

def ref(arr) -> list:
    t = 0
    mass = []
    for i in arr:
        for j in arr:
            if i < j:
                t += 1
        mass.append(t)
        t = 0
    rez = [[]]*len(mass)
    for i in range(len(mass)):
        rez[mass[i]] = arr[i]
    return rez

def rref(matrix) -> list:
    for row_ind in range(len(matrix)):
        leading_1 = 0
        while matrix[row_ind][leading_1] != 1:
            leading_1 += 1
        for row_ind_1 in range(row_ind):
            if should_sub(matrix, row_ind_1, leading_1):
                matrix = sub_lines(matrix, row_ind_1, row_ind)
    return matrix

def prepare_matrix(matrix) -> list:
    """
    function which transforms matrix to binary type
    """
    for i in range(len(matrix)):
        matrix[i] = list(map(lambda x: x % 2, matrix[i]))
    return matrix

def prepare_vector(vec) -> list:
    return list(map(lambda x: x % 2, vec))

def mul_vector_by_matrix(vector, matrix) -> list:
    np_vec = numpy.array(vector)
    np_matrix = numpy.array(matrix)
    return (np_vec.dot(np_matrix)).tolist()

class LinearCode:
    def __init__(self, matrix) -> None:
        self.matrix = prepare_matrix(matrix)  # base matrix
        self.cols = len(matrix[0])  # number of cols
        self.rows = len(matrix)  # number of rows

    def s_ref(self) -> None:
        """
        transforms matrix to the upper-triangular form
        """
        t = 0
        mass = []
        for i in self.matrix:
            for j in self.matrix:
                if i < j:
                    t += 1
            mass.append(t)
        t = 0
        rez = [[]]*len(mass)
        for i in range(len(mass)):
            rez[mass[i]] = self.matrix[i]
        self.matrix = rez

    def s_rref(self) -> None:
        """
        transforms matrix to the reduced upper - triangular form
        """
        for row_ind in range(len(self.matrix)):
            leading_1 = 0
        while self.matrix[row_ind][leading_1] != 1:
            leading_1 += 1
        for row_ind_1 in range(row_ind):
            if should_sub(self.matrix, row_ind_1, leading_1):
                self.matrix = sub_lines(self.matrix, row_ind_1, row_ind)

    def get_leading_1s(self) -> list:
        """
        returns list of leadings cols
        """
        res = []
        for row_ind in range(len(self.matrix)):
            leading_1 = 0
            while self.matrix[row_ind][leading_1] != 1:
                leading_1 += 1
            res.append(leading_1)
        return res

    def f_ilya(self) -> list:
        """
        get X matrix
        """
        arr = self.get_leading_1s()
        print(arr)
        rez = []
        temp = [[]]*self.rows
        door = False
        for i in range(self.rows):
            for j in range(self.cols):
                for k in range(len(arr)):
                    if(arr[k] == j):
                        door = True
                        break
                    else:
                        continue
                if(door):
                    door = False
                    continue
                rez.append(self.matrix[i][j])
            temp[i] = rez
            rez = []
        return(temp)

    def get_check_matrix(self) -> list:
        """
        get H matrix
        """
        X = self.f_ilya()
        I = numpy.eye(len(X[0]), dtype=int).tolist()
        h = []
        leading_1 = self.get_leading_1s()
        cur_x = 0
        cur_i = 0
        for i in range(len(X)+len(I)):
            if i in leading_1:
                h.append(X[cur_x])
                cur_x +=1
            else:
                h.append(I[cur_i])
                cur_i += 1
            # h.append(X[i] if i in leading_1 else I[i])
        return h

    def get_min_code_offset(self) -> int:
        """
        returns the minimum distance between lines
        """
        res = []
        for row_ind in range(self.rows):
            for row_ind_1 in range(row_ind+1, self.rows):
                res.append(get_code_offset(self.matrix, row_ind, row_ind_1))
        return min(res)

    def __str__(self) -> str:
        print("number of cols: ", self.cols, " number of rows: ", self.rows)
        for i in range(self.rows - 1):
            print(self.matrix[i])
        return str(self.matrix[self.rows-1])

def main():
    # inp =  [[1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0],
    #         [0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1],
    #         [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1],
    #         [0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0],
    #         [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1]]

    inp =  [[5, 0, 3, 0, 0, 1, 0, 1, 0, 1, 0],
            [0, 0, 2, 1, 0, 1, 1, 0, 0, 1, 9],
            [0, 0, 4, 0, 1, 0, 0, 1, 0, 0, 3],
            [0, 0, 0, 2, 0, 0, 1, 0, 0, 1, 6],
            [0, 0, 0, 0, 4, 6, 0, 0, 1, 5, 1]]

    lc = LinearCode(inp)
    lc.s_ref()
    lc.s_rref()
    print(lc)
    # print(lc.get_leading_1s())
    # get_code_offset(lc.matrix, 0, 1)
    # print(i for i in lc.get_check_matrix())
    for i in lc.get_check_matrix():
        print(i)

    word_with_error = [1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0]
    word = [1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0]

    print(mul_vector_by_matrix(word, lc.get_check_matrix()))
    print(mul_vector_by_matrix(word_with_error, lc.get_check_matrix()))

    # print(lc.get_min_code_offset())

if __name__ == '__main__':
    main()


# for

# for waiting in range(10):
#     print("대기번호 : {}".format(waiting))

# starbucks = ["ironMan", "Thor", "Groot", "Yoda"]
# for customer in starbucks:
#     print("{0}님, 커피가 준비되었습니다.".format(customer))

# while
# customer = "Thor"
# index = 5
# while index >= 1:
#     print("{0}, 커피 레디. {1}번 남았다".format(customer, index))
#     index -= 1
#     if index == 0:
#         print("버렸다")

# customer = "IronMan"
# i = 1
# while True:                                   # 조건이 True인 동안에 반복하는 것이므로, 이는 무한반복문이 된다.
#     print("{0}, Ready. Called {1} times".format(customer, i))
#     i += 1

# continue & break

# absent = [2, 5]
# no_book = [8]
# for student in range(1, 11):
#     if student in absent:
#         continue                            # 이하 문장을 수행하지 않고, for 문을 다시 시작하게 한다.
#     elif student in no_book:
#         print("{0}, break it".format(student))
#         break                               # 이하 문장이 무엇이 오든 반복문을 끝낸다.
#     print("{0}, read it".format(student))
#
# # for 문의 활용
#
# student = [1, 2, 3, 4, 5]
# student = [i+10 for i in student]           # student 리스트의 내용마다 10을 더한 값을 i로 해서 다시 만든다
# print(student)
#
# students = ["ironman", "thor", "hulk"]
# # students = [len(i) for i in students]     # students의 값을 i에 넣고, i의 길이를 출력하여 리스트로 만든다.
# # print(students)
# students = [i.upper() for i in students]    # students의 값을 i에 넣고, 대문자로 변환하여 리스트로 만든다.
# print(students)

# 퀴즈
# 50명의 승객을 매칭할 수 있다. 다음의 조건을 만족할 수 있는 총 탑승 승객 수를 구하라
# 조건 1 : 운행 소요시간은 5분 ~ 50분 랜덤
# 조건 2 : 소요시간 5분 ~ 15분 사이인 승객만 매칭해야 한다.

from random import *

i = 0
# passenger = list(range(1, 51))
# for matching in passenger:
for pasngr in range(1, 51):
    tf_time = randrange(5, 51)
    if 5 <= tf_time <= 15:
        i += 1
        print(f"[O] {pasngr}번째, (소요시간 : {tf_time}분)")
    else:
        print(f"[ ] {pasngr}번째, (소요시간 : {tf_time}분)")

print(f"총 탑승 가능 : {i}명")


import logging

from aiogram.dispatcher.filters import Command, Text
from aiogram import types
from aiogram.types import CallbackQuery

from keyboards.inline.choice_buttons import choice, pear_keyboard
from keyboards.inline.callback_data import buy_callback
from loader import dp, bot

@dp.message_handler(Command("items"))
async def show_items(message: types.Message):
    await message.answer("На продажу у нас есть 2 товара: 5 груш и 5 яблок\n"
                         "Нажмите отмену, если нечего не нужно", reply_markup=choice)

@dp.callback_query_handler(buy_callback.filter(item_name="pear"))
async def buying_pear(call: CallbackQuery, callback_data: dict):
    await bot.answer_callback_query(callback_query_id=call.id, cache_time=60)
    # await call.answer(cache_time=60)

    quantity = callback_data.get("quantity")
    await call.message.answer(f"вы выбрали купить грушу.Всего {quantity}.Спасибо", reply_markup=pear_keyboard)

@dp.callback_query_handler(buy_callback.filter(item_name="apple"))
async def buying_pear(call: CallbackQuery, callback_data: dict):
    await bot.answer_callback_query(callback_query_id=call.id, cache_time=60)
    # await call.answer(cache_time=60)

    quantity = callback_data.get("quantity")
    await call.message.answer(f"Вы выбрали купить яблоко.Всего {quantity}.Спасибо", reply_markup=pear_keyboard)

@dp.callback_query_handler(text="cancel")
async def buying_pear(call: CallbackQuery):
    await call.answer("Отменили покупку", show_alert=True)


import os

BOT_TOKEN = os.getenv('BOT_TOKEN')
if not BOT_TOKEN:
    print('You have forgot to set BOT_TOKEN')
    quit()

HEROKU_APP_NAME = os.getenv('HEROKU_APP_NAME')

# webhook settings
WEBHOOK_HOST = f'https://{HEROKU_APP_NAME}.herokuapp.com'
WEBHOOK_PATH = f'/webhook/{BOT_TOKEN}'
WEBHOOK_URL = f'{WEBHOOK_HOST}{WEBHOOK_PATH}'

# webserver settings
WEBAPP_HOST = '0.0.0.0'
WEBAPP_PORT = int(os.getenv('PORT'))

WEBHOOK_SSL_CERT = 'webhook.cer'  # Путь к сертификату
WEBHOOK_SSL_PRIV = 'webhook.cer'  # Путь к приватному ключу


import threading

# 创建全局ThreadLocal对象
import time

local_school = threading.local()

class Student():
    def __init__(self, name):
        self.name = name

def process_student(name):
    std = Student(name)
    local_school.student = std   # 写操作
   # local_school.teacher = std
    do_task_1()
    time.sleep(5)
    do_task_2()

def do_task_1():
    std = local_school.student  # 读操作
    print("do_task_1", std.name)

def do_task_2():
    std = local_school.student   # 读操作
    print("do_task_2", std.name)

if __name__ == '__main__':
    '''
    全局变量local_school，每个线程对它都可以读写student属性，而且互不影响。可以把local_school看成是全局变量，
    但是每个属性如local_school.student都是线程的局部变量，可以任意读写互不干扰，也不用管理锁的问题

    一个threading.local变量虽然是全局变量，但是每个线程都只读写自己线程的独立副本，互不干扰。
    threading.local解决了参数在一个线程中各个函数之间互相传递的问题
    '''

    t1 = threading.Thread(target=process_student, args=("Curry",))
    t2 = threading.Thread(target=process_student, args=("大雄",))
    t1.start()
    t2.start()


# -*- coding: utf-8 -*-
"""
Created on Sun Feb 26 11:08:10 2023

@author: HP
"""

import numpy as np
import pickle
import streamlit as st
import warnings

warnings.filterwarnings("ignore")

loaded_model = pickle.load(open('trained_hd_model.sav','rb'))

def heartdisease_prediction(input_data):

    input_data_as_numpy_Array = np.array(input_data)

    input_reshaped = input_data_as_numpy_Array.reshape(1,-1)

    prediction = loaded_model.predict(input_reshaped)
    if(prediction[0]==0):
        return "The person does not have heart disease"
    else:
        return "The person has heart disease"

#input_data = (63,0,0,124,197,0,1,136,1,0.0,1,0,2)

def main():

    # giving a title
    st.title("Heart disease prediction web app")
    age = st.text_input("Enter age as number")
    sex = st.text_input("Enter gender (1-Male ,0-Female")
    cp  = st.text_input("Enter Chest pain type (0-3)")
    trestbps = st.text_input("Resting blood pressure")
    chol = st.text_input("Enter serum cholesterol in mg/dl")
    fbs = st.text_input("Enter fasting blood sugar")
    restecg = st.text_input("Resting electrocardiographic results")
    thalach = st.text_input("Maximum heart rate achieved")
    exang = st.text_input("Exercise induced angina (1-yes,0-no)")
    oldpeak = st.text_input("ST depression induced by exercise relative to rest")
    slope = st.text_input("slope of the peak exercise ST segment")
    ca = st.text_input("number of major vessels (0-3) colored by flourosopy")
    thal = st.text_input("thal: 0 = normal; 1 = fixed defect; 2 = reversable defect")

    # code for prediction
    diagnosis = ''

    # creating a button
    if st.button('HD Test Result'):
        diagnosis = heartdisease_prediction([age,sex,cp,trestbps,chol,fbs,restecg,thalach,exang,oldpeak,slope,ca,thalach])

    st.success(diagnosis)

if __name__ == '__main__':
    main()


from werkzeug.datastructures import ImmutableMultiDict
from slamd.materials.processing.models.liquid import Liquid, Composition
from slamd.materials.processing.models.material import Costs
from slamd.materials.processing.strategies.liquid_strategy import LiquidStrategy

def test_create_model_reads_all_properties_from_submitted_material():
    submitted_material = ImmutableMultiDict([('material_name', 'test liquid'),
                                             ('material_type', 'Liquid'),
                                             ('co2_footprint', '999.99'),
                                             ('costs', '888.88'),
                                             ('delivery_time', '77'),
                                             ('na2_si_o3', '12.3'),
                                             ('na_o_h', '23.4'),
                                             ('na2_si_o3_mol', '34.5'),
                                             ('na_o_h_mol', '45.6'),
                                             ('na2_o', '67.8'),
                                             ('si_o2', '78.9'),
                                             ('h2_o', '89.0'),
                                             ('na2_o_mol', '0.98'),
                                             ('si_o2_mol', '9.87'),
                                             ('h2_o_mol', '8.76'),
                                             ('submit', 'Save material')])
    model = LiquidStrategy.create_model(submitted_material)
    assert model.name == 'test liquid'
    assert model.type == 'Liquid'
    assert model.costs.co2_footprint == 999.99
    assert model.costs.costs == 888.88
    assert model.costs.delivery_time == 77
    assert model.composition.na2_si_o3 == 12.3
    assert model.composition.na_o_h == 23.4
    assert model.composition.na2_si_o3_mol == 34.5
    assert model.composition.na_o_h_mol == 45.6
    assert model.composition.na2_o == 67.8
    assert model.composition.si_o2 == 78.9
    assert model.composition.h2_o == 89.0
    assert model.composition.na2_o_mol == 0.98
    assert model.composition.si_o2_mol == 9.87
    assert model.composition.h2_o_mol == 8.76

def test_gather_composition_properties_adds_all_properties():
    composition = Composition(
        na2_si_o3=12.3,
        na2_si_o3_mol=34.5,
        na_o_h=23.4,
        na_o_h_mol=45.6,
        na2_o=67.8,
        na2_o_mol=0.98,
        si_o2=78.9,
        si_o2_mol=9.87,
        h2_o=89.0,
        h2_o_mol=8.76,
    )
    liquid = Liquid(
        name='test liquid',
        type='Liquid',
        costs=Costs(),
        additional_properties=[],
        composition=composition
    )

    result = LiquidStrategy.gather_composition_information(liquid)
    assert result == ['Na₂SiO₃ (m%): 12.3, ',
                      'Na₂SiO₃ (mol%): 34.5, ',
                      'NaOH (m%): 23.4, ',
                      'NaOH (mol%): 45.6, ',
                      'Na₂O (m%): 67.8, ',
                      'Na₂O (mol%): 0.98, ',
                      'SiO₂ (m%): 78.9, ',
                      'SiO₂ (mol%): 9.87, ',
                      'H₂O (m%): 89.0, ',
                      'H₂O (mol%): 8.76, ']

def test_convert_to_multidict_adds_all_properties():
    composition = Composition(
        na2_si_o3=12.3,
        na_o_h=23.4,
        na2_si_o3_mol=34.5,
        na_o_h_mol=45.6,
        na2_o=67.8,
        si_o2=78.9,
        h2_o=89.0,
        na2_o_mol=0.98,
        si_o2_mol=9.87,
        h2_o_mol=8.76,
    )
    liquid = Liquid(
        name='test liquid',
        type='Liquid',
        costs=Costs(),
        additional_properties=[],
        composition=composition
    )

    multidict = LiquidStrategy.convert_to_multidict(liquid)
    assert multidict['material_name'] == 'test liquid'
    assert multidict['material_type'] == 'Liquid'
    assert multidict['na2_si_o3'] == '12.3'
    assert multidict['na_o_h'] == '23.4'
    assert multidict['na2_si_o3_mol'] == '34.5'
    assert multidict['na_o_h_mol'] == '45.6'
    assert multidict['na2_o'] == '67.8'
    assert multidict['si_o2'] == '78.9'
    assert multidict['h2_o'] == '89.0'
    assert multidict['na2_o_mol'] == '0.98'
    assert multidict['si_o2_mol'] == '9.87'
    assert multidict['h2_o_mol'] == '8.76'


import os
import random
import urllib.request
import hjson
import pandas as pd
import matplotlib.colors as colors
import beartype
import warnings
from .m2l_enums import Datatype, VerboseLevel

class Config(object):
    """Object that represents a sub-project. It is defined by some source data,
    a region of interest (bounding box or polygon) and some execution flags.
    """

    def __init__(self, map_data, verbose_level=VerboseLevel.ALL):
        self.project_path = None
        self.bbox_3d = {
            "minx": 0,
            "maxx": 1000,
            "miny": 0,
            "maxy": 1000,
            "base": -10000,
            "top": 1200,
        }
        self.polygon = None
        self.step_out = 0.1
        self.dtm_crs = "EPSG:4326"
        self.project_crs = None

        # TODO: Need to add check for map_data and verbose_level types
        self.map_data = map_data
        self.verbose_level = verbose_level

        # Set default run flags
        self.run_flags = {
            "aus": True,
            "deposits": "Fe,Cu,Au,NONE",
            "dtb": "",
            "dtb_null": -2147483648,
            "cover_dip": 10,
            "cover_spacing": 5000,
            "orientation_decimate": 1,
            "contact_decimate": 5,
            "intrusion_mode": 0,
            "interpolation_spacing": 500,
            "misorientation": 30,
            "interpolation_scheme": "scipy_rbf",
            "fault_decimate": 5,
            "min_fault_length": 5000,
            "fault_dip": 90,
            "fault_orientation_clusters": 2,
            "fault_length_clusters": 2,
            "pluton_dip": 45,
            "pluton_form": "domes",
            "min_pluton_area": 10000000,
            "dist_buffer": 10,
            "contact_dip": -999,
            "contact_orientation_decimate": 5,
            "null_scheme": "null",
            "thickness_buffer": 5000,
            "max_thickness_allowed": 10000,
            "fold_decimate": 5,
            "fat_step": 750,
            "close_dip": -999,
            "use_interpolations": True,
            "use_fat": True,
            "use_roi_clip": False,
            "roi_clip_path": "",
            "drift_prefix": [],
            "ignore_codes": [],
            "fault_fault_weight": 3,
            "fault_weight": 1,
            "formation_weight": 7,
            "formation_formation_weight": 9,
            "fault_formation_weight": 5,
            "map2graph": False,
            "granular_map2graph": False,
        }

    @beartype.beartype
    def update(
        self,
        project_path: str,
        bbox_3d,
        polygon,
        step_out,
        dtm_crs,
        project_crs,
        metadata_filename: str = "",
        clut_path: str = "",
        run_flags=dict(),
    ):
        self.project_path = project_path
        self.graph_path = os.path.join(project_path, "graph")
        self.tmp_path = os.path.join(project_path, "tmp")
        self.output_path = os.path.join(project_path, "output")

        # filenames for WKT format (map2graph requirement)
        self.fault_filename_wkt = os.path.join(project_path, "tmp", "faults.csv")
        # self.fault_output_file_csv = os.path.join(project_path,'output',"faults.csv")
        self.structure_filename_wkt = os.path.join(project_path, "tmp", "structure.csv")
        self.geology_filename_wkt = os.path.join(project_path, "tmp", "geology.csv")
        self.mindep_filename_wkt = os.path.join(project_path, "tmp", "mindep.csv")

        self.strat_graph_filename = os.path.join(
            project_path, "graph", "graph_strat_NONE.gml"
        )
        # self.dtm_filename = os.path.join(project_path,"dtm", 'dtm.tif')
        # self.dtm_reproj_filename = os.path.join(project_path,"dtm", 'dtm_rp.tif')
        self.clut_path = clut_path

        if isinstance(run_flags, dict):
            for key in run_flags:
                if key not in self.run_flags:
                    warnings.warn(f"config run_flags key {key} is not a valid option")
            self.run_flags.update(run_flags)
            # TODO: Add sanity checks for run_flags updated from user
            if self.run_flags["interpolation_spacing"] < 0:
                self.run_flags["interpolation_spacing"] = -self.run_flags[
                    "interpolation_spacing"
                ]
            self.run_flags["orientation_decimate"] = max(
                self.run_flags["orientation_decimate"], 1
            )
            self.run_flags["contact_decimate"] = max(
                self.run_flags["contact_decimate"], 1
            )
            self.run_flags["fault_decimate"] = max(self.run_flags["fault_decimate"], 1)
            self.run_flags["contact_orientation_decimate"] = max(
                self.run_flags["contact_orientation_decimate"], 1
            )
            self.run_flags["fold_decimate"] = max(self.run_flags["fold_decimate"], 1)
        else:
            print(
                "run_flags must be a dictionary, setting config run flags to the defaults."
            )

        self.bbox_3d = bbox_3d
        self.bbox = tuple(
            [bbox_3d["minx"], bbox_3d["miny"], bbox_3d["maxx"], bbox_3d["maxy"]]
        )

        # Recalculate height and width from bbox and interpolation_spacing
        self.width = (
            int((self.bbox[2] - self.bbox[0]) / self.run_flags["interpolation_spacing"])
            + 1
        )
        self.height = (
            int((self.bbox[3] - self.bbox[1]) / self.run_flags["interpolation_spacing"])
            + 1
        )
        self.polygon = polygon
        self.step_out = step_out

        self.dtm_crs = dtm_crs
        self.project_crs = project_crs

        self.read_metadata(metadata_filename)
        self.create_cmap()

    @beartype.beartype
    def read_metadata(self, filename: str):
        """
        Helper function that turns json and hjson files into usable configuration dictionaries.

        Args:
            filename (string) : Path or url to metadata file
        """
        if filename == "" and self.map_data.get_map_data(Datatype.GEOLOGY) is not None:
            metadata_error = "When using your own local files or remote data, pass the path or url to a valid metadata file (.json or .hjson) that describes your input column names.\n"
            metadata_error += "You can find an example config here https://gist.github.com/yohanderose/a127c29cb88529f049a5bafc881bb1a0"
            raise ValueError(metadata_error)

        # Load in dictionary that describes the column names
        try:
            if filename.startswith("http"):
                with urllib.request.urlopen(filename) as raw_data:
                    self.c_l = hjson.load(raw_data)
                    if self.state is not None:
                        # Check for if remote sources are given as local files, state won't exist
                        if self.state == "SA":
                            for key in self.c_l.keys():
                                try:
                                    self.c_l[key] = self.c_l[key].lower()
                                except Exception:
                                    pass
            else:
                with open(filename) as raw_data:
                    self.c_l = hjson.load(raw_data)
        except Exception as e:
            self.errorState = str(e)
        self.check_for_reserved_codes_and_labels()

    def check_for_reserved_codes_and_labels(self):
        reserved_labels_structure = {
            "d": "DIP",
            "dd": "DIPDIR",
            "sf": "STRUCTURE_TYPE",
            "ds": "DESCRIPTION",
            "bo": "POLARITY",
            "gi": "STRUCTURE_POINT_ID",
        }
        reserved_labels_geology = {
            "g": "GROUP",
            "u": "CODE",
            "g2": "GROUP2",
            "c": "UNIT_NAME",
            "r1": "ROCKTYPE1",
            "r2": "ROCKTYPE2",
            "min": "MIN_AGE",
            "max": "MAX_AGE",
            "o": "GEOMETRY_OBJECT_ID",
        }
        reserved_labels_fault = {
            "n": "NAME",
            "f": "FEATURE",
            "fdip": "DIP",
            "fdipdir": "DIPDIR",
            "fdipest": "DIP_ESTIMATE",
            "o": "GEOMETRY_OBJECT_ID",
        }

        for label in reserved_labels_structure.keys():
            if (
                self.c_l[label] in reserved_labels_structure.values()
                and not self.c_l[label] == reserved_labels_structure[label]
            ):
                raise ValueError(
                    f"Metadata label '{label}' uses reserved keyword {self.c_l[label]} from structure dataframes, please rename this column to something else."
                )
        for label in reserved_labels_geology.keys():
            if (
                self.c_l[label] in reserved_labels_geology.values()
                and not self.c_l[label] == reserved_labels_geology[label]
            ):
                raise ValueError(
                    f"Metadata label '{label}' uses reserved keyword {self.c_l[label]} from geology dataframes, please rename this column to something else."
                )
        for label in reserved_labels_fault.keys():
            if (
                self.c_l[label] in reserved_labels_fault.values()
                and not self.c_l[label] == reserved_labels_fault[label]
            ):
                raise ValueError(
                    f"Metadata label '{label}' uses reserved keyword {self.c_l[label]} from fault dataframes, please rename this column to something else."
                )

    # TODO: Make it more obvious when formations are not found and random colours are assigned
    def create_cmap(self):
        # Make colours consistent from map to model
        formations = sorted(
            [
                formation.replace(" ", "_").replace("-", "_")
                for formation in list(
                    set(
                        self.map_data.get_map_data(Datatype.GEOLOGY)[
                            "UNIT_NAME"
                        ].to_numpy()
                    )
                )
            ]
        )
        temp_colours = [""] * len(formations)
        self.colour_dict = dict(zip(formations, temp_colours))
        try:
            # Try to retrieve the clut reference
            colour_ref = pd.read_csv(self.clut_path)
            for formation in formations:
                key = formation.replace("-", "_")
                colour = None
                try:
                    colour = colour_ref[colour_ref["code"] == key]["colour"].to_numpy()[
                        0
                    ]
                except Exception:
                    try:
                        colour = colour_ref[colour_ref["UNITNAME"] == key][
                            "colour"
                        ].to_numpy()[0]
                    except Exception:
                        print(
                            "formation "
                            + formation
                            + " does not have a colour reference"
                        )
                        colour = "#%02X%02X%02X" % (
                            random.randint(0, 255),
                            random.randint(0, 255),
                            random.randint(0, 255),
                        )

                self.colour_dict[formation] = colour
                # print(key, colour)

        except Exception:
            # Otherwise, just append a random set
            self.clut_path = ""
            random_colours = [
                "#%02X%02X%02X"
                % (
                    random.randint(0, 255),
                    random.randint(0, 255),
                    random.randint(0, 255),
                )
                for i in range(len(formations))
            ]
            i = 0
            for key in self.colour_dict.keys():
                self.colour_dict[key] = random_colours[i]
                i = i + 1

        self.cmap = colors.ListedColormap(self.colour_dict.values(), name="geol_key")

    @beartype.beartype
    def save_cmap(self, workflow: dict):
        """Create a colourmap for the model using the colour code"""
        all_sorts = pd.read_csv(os.path.join(self.tmp_path, "all_sorts_clean.csv"))

        if workflow["cover_map"]:
            self.colour_dict["cover"] = "#FFFFC0"
            self.colour_dict["cover_up"] = "#FFFFC0"
        colours = []
        newKeys = [key.replace("-", "_") for key in self.colour_dict.keys()]
        newColourDict = dict(zip(newKeys, list(self.colour_dict.values())))
        for code in all_sorts["code"]:
            # colours.append([self.colour_dict[code]])
            code = code.replace("-", "_")
            colours.append([newColourDict[code]])
        data = colours
        expected_extra_cols = pd.DataFrame(columns=["colour"], data=data)
        all_sorts = pd.concat([all_sorts, expected_extra_cols], axis=1)
        all_sorts.to_csv(
            os.path.join(self.tmp_path, "all_sorts_clean.csv"), ",", index=None
        )


import requests
import argparse
from time import sleep
from json import dumps, loads
from kafka import KafkaProducer
from datetime import datetime

# get argument parser
parser = argparse.ArgumentParser(description='Short sample app')
parser.add_argument('bootstrap_servers', type=str, action="store_true")
args = parser.parse_args()

bootstrap_servers = args.bootstrap_servers.split(',')

# connect to kafka as a producer
producer = KafkaProducer(bootstrap_servers=bootstrap_servers,
                         value_serializer=lambda x:
                         dumps(x).encode('utf-8'))

# list of crypto currencies we are interested in
crypto_coins = ['BTC', 'ETH', 'XRP', 'BCH', 'LTC', 'EOS', 'XLM', 'LINK', 'DASH', 'XTZ']

# go on a never-ending loop
while True:
    # loop over every coin we are interested in
    for coin in crypto_coins:
        # format the url for the api to get a OK response
        url = 'https://api.coinbase.com/v2/prices/{}-USD/sell'.format(coin)
        usd_value = loads(requests.get(url).text)['data']['amount']
        time_now = datetime.now().strftime('%d-%m-%Y %H:%M:%S')
        # prepare the value and timestamp for sending to kafka
        data = {'timestamp': time_now, 'usd_value': usd_value}
        # send data to kafka
        producer.send(coin, value=data)
        # a small sleep to not overwhelm the API
        sleep(1)
    # wait 30 seconds till we send the next update
    sleep(30)


from __future__ import print_function, division

import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
import torch.backends.cudnn as cudnn
import numpy as np
import torchvision
from torchvision import datasets, models, transforms
from torch.utils.tensorboard import SummaryWriter
import matplotlib.pyplot as plt
import time
import os
import copy

from PIL import Image
import re

cudnn.benchmark = True
plt.ion()   # interactive mode

class PlantAssessmentDataset(torch.utils.data.Dataset):
    def __init__(self, root, transforms):
        self.root = root
        self.transforms = transforms
        # load all image files, sorting them to
        # ensure that they are aligned
        self.imgs = list(sorted(os.listdir(root)))
        with open('challenge_anno.txt') as f:
            self.score_labels_txt = f.readlines()

    def __getitem__(self, idx):
        # load images and masks
        img_path = os.path.join(self.root, self.imgs[idx])
        img = Image.open(img_path).convert("RGB")

        # get the plant health label
        health_score = [re.search('\t(.*)\n', x).group(1) for x in self.score_labels_txt if self.imgs[idx] in x]
        #health_score = torch.tensor(int(health_score[0]), dtype=torch.int64)
        health_score = torch.tensor(int(health_score[0]), dtype=torch.float32)

        if self.transforms is not None:
            img = self.transforms(img)

        return img, health_score

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

# Data augmentation and normalization for training
# Just normalization for validation
data_transforms = {
    'train': transforms.Compose([
        transforms.Resize(344),
        transforms.RandomRotation(degrees=180, fill=255),
        transforms.RandomResizedCrop(344, scale=(0.80, 1)),
        transforms.CenterCrop(224),
        transforms.RandomHorizontalFlip(),
        transforms.RandomVerticalFlip(),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ]),
    'val': transforms.Compose([
        transforms.Resize(344),
        transforms.CenterCrop(224),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ]),
    'test': transforms.Compose([
            transforms.Resize(344),
            transforms.CenterCrop(224),
            transforms.ToTensor(),
            transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
        ]),
}

if __name__ == "__main__":

    folds = ['fold1', 'fold2', 'fold3', 'fold4', 'fold5']
    for fold in folds:
        print('\nFOLD: %s\n' % fold)

        for num_trial in range(1, 6):

            # log metrics to tensorboard
            with SummaryWriter() as writer:
                writer = SummaryWriter('runs_resnet18/' + fold + '/trial' + str(num_trial))

                data_dir = os.path.join('data_folds', fold)
                image_datasets = {x: PlantAssessmentDataset(os.path.join(data_dir, x),
                                                          data_transforms[x])
                                  for x in ['train', 'val', 'test']}
                dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=8,
                                                             shuffle=True, num_workers=0)
                              for x in ['train', 'val', 'test']}
                dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'val', 'test']}

                device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

                ######################################################################
                # Visualize a few images
                # ^^^^^^^^^^^^^^^^^^^^^^
                # Let's visualize a few training images so as to understand the data
                # augmentations.

                def imshow(inp, title=None):
                    """Display image for Tensor."""
                    inp = inp.numpy().transpose((1, 2, 0))
                    mean = np.array([0.485, 0.456, 0.406])
                    std = np.array([0.229, 0.224, 0.225])
                    inp = std * inp + mean
                    inp = np.clip(inp, 0, 1)
                    plt.imshow(inp)
                    if title is not None:
                        plt.title(title)
                    plt.pause(0.001)  # pause a bit so that plots are updated

                # Get a batch of training data
                #inputs, health_scores = next(iter(dataloaders['train']))

                # Make a grid from batch
                #out = torchvision.utils.make_grid(inputs)

                #imshow(out, title=[x.item() for x in health_scores])

                def train_model(model, criterion, optimizer, scheduler, num_epochs=25):
                    since = time.time()

                    best_model_wts = copy.deepcopy(model.state_dict())
                    best_min_loss = 10000000

                    for epoch in range(num_epochs):
                        print(f'Epoch {epoch}/{num_epochs - 1}')
                        print('-' * 10)

                        # Each epoch has a training and validation phase
                        for phase in ['train', 'val']:
                            if phase == 'train':
                                model.train()  # Set model to training mode
                            else:
                                model.eval()   # Set model to evaluate mode

                            running_loss = 0.0
                            #running_corrects = 0

                            # Iterate over data.
                            for inputs, health_scores in dataloaders[phase]:
                                inputs = inputs.to(device)
                                #health_scores = health_scores.to(device)
                                health_scores = torch.unsqueeze(health_scores, dim=1).to(device)

                                # zero the parameter gradients
                                optimizer.zero_grad()

                                # forward
                                # track history if only in train
                                with torch.set_grad_enabled(phase == 'train'):
                                    outputs = model(inputs)
                                    loss = criterion(outputs, health_scores)
                                    # log loss to tensorboard
                                    writer.add_scalar(phase + "_loss", loss, epoch)

                                    # backward + optimize only if in training phase
                                    if phase == 'train':
                                        loss.backward()
                                        optimizer.step()

                                # statistics
                                running_loss += loss.item() * inputs.size(0)
                                #running_corrects += torch.sum(preds == labels.data)
                            if phase == 'train':
                                scheduler.step()

                            epoch_loss = running_loss / dataset_sizes[phase]
                            #epoch_acc = running_corrects.double() / dataset_sizes[phase]

                            print(f'{phase} Loss: {epoch_loss:.4f}')

                            # deep copy the model
                            if phase == 'val' and epoch_loss < best_min_loss:
                                best_min_loss = epoch_loss
                                best_model_wts = copy.deepcopy(model.state_dict())

                        print()

                    # test phase
                    model.eval()  # Set model to evaluate mode
                    test_running_loss = 0
                    for inputs, health_scores in dataloaders['test']:
                        inputs = inputs.to(device)
                        #health_scores = health_scores.to(device)
                        health_scores = torch.unsqueeze(health_scores, dim=1).to(device)

                        # zero the parameter gradients
                        optimizer.zero_grad()

                        with torch.set_grad_enabled(phase == 'train'):
                            outputs = model(inputs)
                            loss = criterion(outputs, health_scores)

                        # statistics
                        test_running_loss += loss.item() * inputs.size(0)
                    test_loss = test_running_loss / dataset_sizes['test']

                    time_elapsed = time.time() - since
                    print(f'Training complete in {time_elapsed // 60:.0f}m {time_elapsed % 60:.0f}s')
                    print(f'Best val Loss: {best_min_loss:4f}')
                    print(f'TEST Loss: {test_loss:.4f}')
                    writer.add_text('TEST Loss', str(test_loss), num_epochs)

                    writer.add_hparams({'optimizer': 'SGD', 'epochs': num_epochs, 'lr': optimizer.defaults['lr'], 'momentum': optimizer.defaults['momentum'],
                                        'step_size': scheduler.step_size, 'gamma': scheduler.gamma, 'bs': 8, 'loss_function': 'L1Loss'},
                                      {'best_val_loss': best_min_loss, 'best_test_loss': test_loss})

                    writer.flush()

                    # load best model weights
                    model.load_state_dict(best_model_wts)
                    return model

            ######################################################################
            # Visualizing the model predictions
            # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
            #
            # Generic function to display predictions for a few images
            #

            def visualize_model(model, split_name, num_images=12):
                was_training = model.training
                model.eval()
                images_so_far = 0
                fig = plt.figure()

                with torch.no_grad():
                    for i, (inputs, labels) in enumerate(dataloaders[split_name]):
                        inputs = inputs.to(device)
                        labels = labels.to(device)

                        outputs = model(inputs)
                        outputs = torch.squeeze(outputs)
                        #_, preds = torch.max(outputs, 1)

                        for j in range(inputs.size()[0]):
                            images_so_far += 1
                            ax = plt.subplot(num_images//2, 2, images_so_far)
                            ax.axis('off')
                            ax.set_title(f'HR: {int(labels[j])} Predicted: {outputs[j]}')
                            imshow(inputs.cpu().data[j])

                            if images_so_far == num_images:
                                model.train(mode=was_training)
                                return
                    model.train(mode=was_training)

            ######################################################################
            # Finetuning the ConvNet
            # ----------------------
            #
            # Load a pretrained model and reset final fully connected layer.
            #

            model_ft = models.resnet18(weights='IMAGENET1K_V1')
            num_ftrs = model_ft.fc.in_features
            # Here the size of each output sample is set to 1.
            #model_ft.fc = nn.Linear(num_ftrs, 100)
            #model_ft.classifier[1] = nn.Linear(num_ftrs, 1,  bias=True)
            """model_ft.fc = nn.Sequential(
                                    nn.Dropout(p=0.4, inplace=True),
                                    nn.Linear(num_ftrs, 1024,  bias=True),
                                    nn.Dropout(p=0.4, inplace=True),
                                    nn.Linear(1024, 512,  bias=True),
                                    nn.Dropout(p=0.4, inplace=True),
                                    nn.Linear(512, 256,  bias=True),
                                    nn.Dropout(p=0.4, inplace=True),
                                    nn.Linear(256, 128,  bias=True),
                                    nn.Dropout(p=0.4, inplace=True),
                                    nn.Linear(128, 64,  bias=True),
                                    nn.Dropout(p=0.4, inplace=True),
                                    nn.Linear(64, 32,  bias=True),
                                    nn.Dropout(p=0.4, inplace=True),
                                    nn.Linear(32, 1,  bias=True),
            )"""
            model_ft.fc = nn.Sequential(
                                    nn.Dropout(p=0.4, inplace=True),
                                    nn.Linear(num_ftrs, 256,  bias=True),
                                    nn.Dropout(p=0.4, inplace=True),
                                    nn.Linear(256, 128,  bias=True),
                                    nn.Dropout(p=0.4, inplace=True),
                                    nn.Linear(128, 64,  bias=True),
                                    nn.Dropout(p=0.4, inplace=True),
                                    nn.Linear(64, 32,  bias=True),
                                    nn.Dropout(p=0.4, inplace=True),
                                    nn.Linear(32, 1,  bias=True),
            )

            model_ft = model_ft.to(device)

            #criterion = nn.MSELoss()
            criterion = nn.L1Loss()

            # Observe that all parameters are being optimized
            optimizer_ft = optim.SGD(model_ft.parameters(), lr=0.0005, momentum=0.9)

            # Decay LR by a factor of 0.5 every 4 epochs
            exp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=4, gamma=0.5)

            model_ft = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler,
                                   num_epochs=25)

            # store best model for each fold
            torch.save(model_ft.state_dict(), os.path.join('runs_resnet18/', fold + '/trial' + str(num_trial), 'model_resnet18_bestvalloss.pth'))

            writer.flush()
            writer.close()

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

            #visualize_model(model_ft, 'val')
            #visualize_model(model_ft, 'test')

            plt.ioff()
            plt.show()


from rest_framework import viewsets, status
from rest_framework.authentication import TokenAuthentication
from rest_framework.response import Response
from .models import Question, Answer
from .serializers import QuestionSerializer, AnswerSerializer, UserSerializer
from rest_framework.decorators import action
from django.contrib.auth.models import User
from rest_framework.permissions import IsAuthenticated, AllowAny

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = (AllowAny,)
class QuestionViewSet(viewsets.ModelViewSet):
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer
    authentication_classes = (TokenAuthentication, )
    permission_classes = (AllowAny,)

    @action(detail=True, methods=['POST'])
    def rate_question(self, request, pk=None):
        if "stars" in request.data:
            question = Question.objects.get(id=pk)
            stars = request.data["stars"]
            #user = request.user
            user = User.objects.get(id=1)
            print("question: ", user.username)

            response = {"message": "it is working"}
            return Response(response, status=status.HTTP_202_ACCEPTED)
        else:
            response = {"message": "Please provide a star rating"}
            return Response(response, status=status.HTTP_400_BAD_REQUEST)
class AnswerViewSet(viewsets.ModelViewSet):
    queryset = Answer.objects.all()
    serializer_class = AnswerSerializer


#https://www.acmicpc.net/problem/2562

max=0
line=0
for i in range(9):
    x=int(input())
    if x>max:
        max=x
        line=i
print(max)
print(line+1)


import pyautogui
import pyscreeze
import time
import configparser
import datetime
import PyWinMouse

pyautogui.PAUSE = 0.2
pyautogui.FAILSAFE = False

#on set up la config
config = configparser.ConfigParser()
config.read("config.ini")

playButtonPixelPos = pyautogui.Point(x=eval(config["DEFAULT"]["playButtonPixelPos"])[0], y=eval(config["DEFAULT"]["playButtonPixelPos"])[1])
playButtonPixelRGB = eval(config["DEFAULT"]["playButtonPixelRGB"])
inBetweenSettingsButtonPixelPos1 = pyautogui.Point(x=eval(config["DEFAULT"]["inBetweenSettingsButtonPixelPos1"])[0], y=eval(config["DEFAULT"]["inBetweenSettingsButtonPixelPos1"])[1])
inBetweenSettingsButtonPixelRGB1 = eval(config["DEFAULT"]["inBetweenSettingsButtonPixelRGB1"])
inBetweenSettingsButtonPixelPos2 = pyautogui.Point(x=eval(config["DEFAULT"]["inBetweenSettingsButtonPixelPos2"])[0], y=eval(config["DEFAULT"]["inBetweenSettingsButtonPixelPos2"])[1])
inBetweenSettingsButtonPixelRGB2 = eval(config["DEFAULT"]["inBetweenSettingsButtonPixelRGB2"])
concedeButtonPos = pyautogui.Point(x=eval(config["DEFAULT"]["concedeButtonPos"])[0], y=eval(config["DEFAULT"]["concedeButtonPos"])[1])
concedeButtonRGB = eval(config["DEFAULT"]["concedeButtonRGB"])
inMatchSettingsButtonPixelPos1 = pyautogui.Point(x=eval(config["DEFAULT"]["inMatchSettingsButtonPixelPos1"])[0], y=eval(config["DEFAULT"]["inMatchSettingsButtonPixelPos1"])[1])
inMatchSettingsButtonPixelRGB1 = eval(config["DEFAULT"]["inMatchSettingsButtonPixelRGB1"])
inMatchSettingsButtonPixelPos2 = pyautogui.Point(x=eval(config["DEFAULT"]["inMatchSettingsButtonPixelPos2"])[0], y=eval(config["DEFAULT"]["inMatchSettingsButtonPixelPos2"])[1])
inMatchSettingsButtonPixelRGB2 = eval(config["DEFAULT"]["inMatchSettingsButtonPixelRGB2"])

class quickgrab:
    def __init__(self):
        self.isRunning = False
        self.timeBeforeConcede = 0
        self.mouse = PyWinMouse.Mouse()

    def startTheScript(self):
        count = 0
        while True:
            time.sleep(0.5)
            count += 1

            if not self.isRunning:
                print("pause")
                while not self.isRunning:
                    one = 1

            if(self.areWeInMainScreen()):
                self.goToPixAndClick(playButtonPixelPos)
                print("We are in MainScreen")

            if(self.areWeInBetweenMatchScreen()):
                time.sleep(self.timeBeforeConcede)
                self.goToPixAndClick(inBetweenSettingsButtonPixelPos1)
                print("We are in Between Matches")

            if(self.areWeInConcedeMenu()):
                self.goToPixAndClick(concedeButtonPos)
                print("We are in Concede Menu")

            if (self.areWeInMatchScreen()):
                time.sleep(self.timeBeforeConcede)
                self.goToPixAndClick(inBetweenSettingsButtonPixelPos1)
                print("We are in Match Screen")

            if count > 15:
                self.goToPixAndClick(pyautogui.Point(x=10, y=10))
                count = 0

    def getPosIn3Secs(self):
        time.sleep(3)
        return pyautogui.position()

    def getColorIn3Secs(selfself):
        time.sleep(3)
        return pyautogui.pixel(pyautogui.position().x, pyautogui.position().y)

    def getPosNow(self):
        return pyautogui.position()

    def getColorNow(self):
        return pyautogui.pixel(pyautogui.position().x, pyautogui.position().y)

    def click(self):
        self.mouse.left_down()
        time.sleep(0.2)
        self.mouse.left_up()

    def goToImgAndClick(self, path):
        try:
            Pix = pyautogui.locateCenterOnScreen(path)
            pyautogui.moveTo(Pix.x, Pix.y, 0)
            self.click()
        except pyscreeze.ImageNotFoundException:
            print("image non trouvee")

    def goToPixAndClick(self, Pix):
        pyautogui.moveTo(Pix.x, Pix.y, 0)
        self.click()

    def printMyPosInXSecs(self):
        time.sleep(3)
        print(pyautogui.position())

    def printMyRGB(self):
        print(pyautogui.pixel(inBetweenSettingsButtonPixelPos1.x, inBetweenSettingsButtonPixelPos1.y))

    def areWeInMainScreen(self):
        if pyautogui.pixel(playButtonPixelPos.x, playButtonPixelPos.y) == playButtonPixelRGB:
            return True
        else:
            return False

    def areWeInBetweenMatchScreen(self):
        if pyautogui.pixelMatchesColor(inBetweenSettingsButtonPixelPos1.x, inBetweenSettingsButtonPixelPos1.y, inBetweenSettingsButtonPixelRGB1)\
                or pyautogui.pixelMatchesColor(inBetweenSettingsButtonPixelPos2.x, inBetweenSettingsButtonPixelPos2.y, inBetweenSettingsButtonPixelRGB2):
                return True
        else:
            return False

    def areWeInConcedeMenu(self):
        if pyautogui.pixelMatchesColor(concedeButtonPos.x, concedeButtonPos.y, concedeButtonRGB):
            return True
        else:
            return False

    def areWeInMatchScreen(self):
        if pyautogui.pixelMatchesColor(inMatchSettingsButtonPixelPos1.x, inMatchSettingsButtonPixelPos1.y, inMatchSettingsButtonPixelRGB1)\
                or pyautogui.pixelMatchesColor(inMatchSettingsButtonPixelPos2.x, inMatchSettingsButtonPixelPos2.y, inMatchSettingsButtonPixelRGB2):
            return True
        else:
            return False


#pip install cx_Oraacle

import cx_Oracle

conn = cx_Oracle.connect('scott','tiger','localhost:1521/XE')
cursor = conn.cursor()
cursor.execute("select * from emp where deptno = 10")

# print(cursor)

# for item in cursor:
#     while True:
#         job = input('직업을 입력하세요 >>> ').upper()
#         if job in item[2]:
#             print(item[1])
#             break
#         else:
#             print('직업을 정확히 입력해주세요.')

for item in cursor:
    print(item[1],item[5])
# for item in cursor:
#     print(item[1])

conn.close()


"""
    Creates a RectRegion class that inherits from Region (see region.py)
    that represent a rectangular region in the symmetric basis.
"""
import numpy as np
import matplotlib.pyplot as plt

from .rect_region import RectRegion
from .utils import transform_sym

class SymRegion(RectRegion):
    """
        Rectangular region.

        Defined by x_lim and y_lim, coordinates in the symmetric basis.
        Hence, it uses all the same splitting functions as the RectRegion,
        but different plotting rules.
    """
    def __init__(self, x_lim, y_lim, canonical_plot=True):
        super(SymRegion, self).__init__(x_lim, y_lim)
        self.canonical_plot = canonical_plot

    def plot_bounds(self, *argv, **kwargs):
        """Plots the bounds of the region."""
        polygon = np.array([[max(0, self.x_lim[0]), self.y_lim[0]],
                            [self.x_lim[1], self.y_lim[0]],
                            [self.x_lim[1], self.y_lim[1]],
                            [max(0, self.x_lim[0]), self.y_lim[1]]])
        last_point = polygon[-1]
        for x, y in polygon:
            self.__plot_sym_line([last_point[0], x],
                                 [last_point[1], y], *argv, **kwargs)
            last_point = [x, y]

    def plot_patch(self, *argv, **kwargs):
        """Plots the patch defined by the region."""
        polygon = np.array([[max(0, self.x_lim[0]), self.y_lim[0]],
                            [self.x_lim[1], self.y_lim[0]],
                            [self.x_lim[1], self.y_lim[1]],
                            [max(0, self.x_lim[0]), self.y_lim[1]]])
        self.__plot_sym_polygon(polygon, *argv, **kwargs)

    def plot_coord_split(self, cut_val, cut_dim, *argv, **kwargs):
        """Plots the line defined by cut_val and cut_dim."""
        if cut_dim == 0:
            # Plot on x-y/2
            if self.x_lim[0] <= cut_val <= self.x_lim[1]:
                pts = np.array([[cut_val]*2, self.y_lim])
            else:
                return None
        else:
            if self.y_lim[0] <= cut_val <= self.y_lim[1]:
                if self.x_lim[0] <= 0 <= self.x_lim[1]:
                    x_lim_l1 = [0, np.max(self.x_lim)]
                    pts = np.array([x_lim_l1, [cut_val]*2])
                else:
                    x_lim_min = np.min(np.abs(self.x_lim))
                    x_lim_max = np.max(np.abs(self.x_lim))
                    pts = np.array([[x_lim_min, x_lim_max], [cut_val]*2])
            else:
                return None

        self.__plot_sym_line(pts[0], pts[1], *argv, **kwargs)
        return None

    # --------------- Protected interface ---------------

    def _gen_sub(self, x_lim, y_lim):
        """Generates a sub region, parameterized in the symmetric basis."""
        return SymRegion(x_lim, y_lim, self.canonical_plot)

    # --------------- Private interface ---------------

    def __plot_sym_line(self, xs, ys, *argv, **kwargs):
        if self.canonical_plot:
            x1, y1 = transform_sym(xs[0], ys[0])
            x2, y2 = transform_sym(xs[1], ys[1])
        else:
            x1, y1 = xs[0], ys[0]
            x2, y2 = xs[1], ys[1]
        plt.plot([x1, x2], [y1, y2], *argv, **kwargs)
        if self.canonical_plot:
            x1, y1 = transform_sym(-xs[0], ys[0])
            x2, y2 = transform_sym(-xs[1], ys[1])
        else:
            x1, y1 = -xs[0], ys[0]
            x2, y2 = -xs[1], ys[1]
        plt.plot([x1, x2], [y1, y2], *argv, **kwargs)

    def __plot_sym_polygon(self, polygon, *argv, **kwargs):
        if self.canonical_plot:
            tr_polygon = np.array([transform_sym(x, xp) for x, xp in polygon])
        else:
            tr_polygon = polygon
        plt.gca().fill(tr_polygon[:, 0], tr_polygon[:, 1], *argv, **kwargs)
        polygon[:, 0] = - polygon[:, 0]
        if self.canonical_plot:
            polygon = np.array([transform_sym(x, xp) for x, xp in polygon])
        plt.gca().fill(polygon[:, 0], polygon[:, 1], *argv, **kwargs)


# 문제 327쪽
# https://www.acmicpc.net/problem/3190

# 보드의 크기
n = int(input())
graph = [ [0] * (n+1) for _ in range(n+1) ]

# 사과의 개수
k = int(input())
# 사과 위치 표시
for _ in range(k):
  a,b = map(int,input().split())
  graph[a][b] = 1

# 회전 개수
L = int(input())
# 회전 정보 기록
info = []
for _ in range(L):
  x, c = input().split()
  info.append((int(x),c))

# 동남서북 ( 처음에 오른쪽(동쪽) 보고 있음 )
dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]

# 회전
def turn(direction, c):
  if c == 'L':
    direction = (direction -1)%4
  else:
    direction = (direction +1)%4
  return direction

def simulate():
  x,y = 1, 1 # 머리 위치
  # 존재하는 곳 2로 표시
  graph[x][y] = 2
  direction = 0
  # 위치 정보 표시
  q = [ (x,y) ]
  time = 0
  index = 0
  while True:
    nx = x + dx[direction]
    ny = y + dy[direction]
    # 벽이 아니고 뱀이 존재하지 않음
    if 1 <= nx and nx <= n and 1 <= ny and ny <= n and graph[nx][ny] != 2 :
      # 사과가 없을 때, 머리 앞으로 이동 꼬리도 앞으로 이동
      if graph[nx][ny] == 0 :
        graph[nx][ny] = 2
        q.append((nx,ny))
        px, py = q.pop(0)
        graph[px][py] = 0
    # 사과가 있을 때 머리만 앞으로 이동
      if graph[nx][ny] == 1:
        graph[nx][ny] = 2
        q.append((nx,ny))
    # 벽에 부딪혔을 때
    else:
      time += 1
      break
    x = nx
    y = ny
    time += 1
    # 회전해야될 때
    if index < len(info) and time == info[index][0] :
      direction = turn(direction,info[index][1])
      index += 1

  return time

print(simulate())

[이것이 취업을 위한 코딩테스트다] 정리/3. 알고리즘 유형별 기출문제/12. 구현/11. 뱀.py


from sklearn.model_selection import TimeSeriesSplit

class Dataset:
    def __init__(self, train_df, n_splits):
        self._train_data = train_df
        self._n_splits = n_splits

    def train(self, model):
        target_col = 'depth_to_groundwater'
        X = self._train_data.loc[:, self._train_data.columns != target_col]
        X = X.rename(columns={'date': 'ds'})
        y = self._train_data.loc[:, self._train_data.columns == target_col]
        y.columns = ['y']
        cv = TimeSeriesSplit(n_splits=self._n_splits)
        for train_index, val_index in cv.split(X):
            X_train, X_val = X.iloc[train_index], X.iloc[val_index]
            y_train, y_val = y.iloc[train_index], y.iloc[val_index]
            model.train(
                X_train=X_train, y_train=y_train, X_val=X_val, y_val=y_val)

    def get_validation_data(self, model):
        target_col = 'depth_to_groundwater'
        y = self._train_data.loc[:, self._train_data.columns == target_col]
        y.columns = ['y']
        cv = TimeSeriesSplit(n_splits=self._n_splits)
        y_vals = []
        for train_index, val_index in cv.split(y):
            y_train, y_val = y.iloc[train_index], y.iloc[val_index]
            y_vals.append(y_val)
        return model.get_validation_data(y_vals=y_vals)


T = int(input())

for test_case in range(T):
    result = 0
    N, K = map(int, input().split())
    N_list = []
    for i in range(12):
        N_list.append(i+1)

    for i in range(1<<12):
        temp_list = []
        temp_sum = 0
        for j in range(12):
            if i&(1<<j):
                temp_list.append(N_list[j])

        for j in temp_list:
            temp_sum += j

        if temp_sum == K and len(temp_list) == N:
            result += 1

    print("#{0} {1}".format(test_case+1, result))


# Taking numbers from the user

num_1 = input("Enter 1st number: ")
num_2 = input("Enter 2nd number: ")
swap = num_1    # Swapping the values
num_1 = num_2
num_2 = swap

# Displaying values after swapping

print(f"After swapping:\n1st number: {num_1}")
print(f"2nd number: {num_2}")


# Serialization is the process of converting a data structure or object into a sequence of bits
# so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
# Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work.
# You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.
#
# For example, you may serialize the following tree
#
#     1
#    / \
#   2   3
#      / \
#     4   5
#
# as "[1,2,3,null,null,4,5]", just the same as how LeetCode OJ serializes
# a binary tree. You do not necessarily need to follow this format, so
# please be creative and come up with different approaches yourself.

class Codec:
    splitter = ','
    nullStr = 'NULL'

    def serialize(self, root):
        """Encodes a tree to a single string.

        :type root: TreeNode
        :rtype: str
        """
        def build_list(node, ln):
            if node is None:
                ln.append(self.nullStr)
                return
            # pre-order traversal
            ln.append(str(node.val))
            build_list(node.left, ln)
            build_list(node.right, ln)

        list_node = []
        build_list(root, list_node)
        return self.splitter.join(list_node)

    def deserialize(self, data):
        """Decodes your encoded data to tree.

        :type data: str
        :rtype: TreeNode
        """
        def createTree(list_node):
            try:
                nval = list_node.pop()
            except IndexError:
                return

            if nval == self.nullStr:
                return None

            node = TreeNode(nval)
            node.left = createTree(list_node_val)
            node.right = createTree(list_node_val)
            return node

        list_node_val = data.split(self.splitter)
        list_node_val.reverse()
        root = createTree(list_node_val)
        return root


import os
import random
import shutil
import string
import unittest
import uuid

import pandas as pd

import constants
from grade_helper_ops.compile_grade_report import compile_grade_report

class TestCompileGradeReport(unittest.TestCase):

    def test_compile_grade_report_all_students_graded(self):
        path = os.path.join("test_lab")
        students_amt = 10
        if not os.path.exists(path):
            os.makedirs(path, exist_ok=True)
        column_names = ["First name", "Surname", "ID number", "Grade", "Feedback"]
        for i in range(students_amt):
            row_values = [''.join(random.choices(string.ascii_uppercase, k=i)),
                          ''.join(random.choices(string.ascii_uppercase, k=i)), uuid.uuid4(), f"{i}", "Try harder!"]
            student_path = os.path.join(path, f"student_{i}")
            os.makedirs(student_path, exist_ok=True)
            csv_path = os.path.join(student_path, constants.CSV_FILE_NAME)

            csv_data = {}
            for row, col in zip(row_values, column_names):
                csv_data[col] = [row]
            data_frame = pd.DataFrame(csv_data)
            data_frame.to_csv(csv_path, columns=column_names)

        response = compile_grade_report(os.listdir(path), path, os.path.join(path, constants.FINAL_GRADE_REPORT_PATH),
                                        column_names)
        self.assertFalse(response["error"])
        shutil.rmtree(path)

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


from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
import json
from collections import OrderedDict
import string
from prettytable import PrettyTable

# Define words we do not want to show in frequent list
def unwanted():
    unwanted = list(stopwords.words('english'))
    unwanted += list(string.punctuation)
    unwanted += ['https', 'http', '...', '…',"''",'``','iphone', 'Iphone', 'iphone7', 'Iphone7',"'s"]
    return unwanted

# Find the most frequent n words in tweets json data
def frequent_words(data, n):
    unwanted_words = unwanted()
    counts = dict() # {"word1": 253, "word2": 13}
    for tweet in data:
        if "text" in tweet.keys() and tweet["lang"]=="en":
            sentence = tweet["text"]
            words = word_tokenize(sentence)
            for word in words:
                if word.lower() not in unwanted_words:
                    counts[word] = counts.get(word, 0)+1
    sorted_counts = sorted(counts.items(), key=lambda t: t[1], reverse = True)
    with open("frequency.txt", 'w', encoding='utf-8') as f:
        f.write(str(sorted_counts[:n]))
    return sorted_counts[:n]

# Find tweets retweeted more than n times
def popular_tweet(statuses, n):
    popular = []
    for tweet in statuses:
        if "retweet_count" in tweet.keys() and tweet["retweet_count"] > n:
            popular.append(tweet)
    return popular

# Find tweets with an overall retweeted numbers more than n times
def popular_retweeted_count(statuses, n):
    popular = {}
    for tweet in statuses:
        if "retweeted_status" in tweet.keys() and len(tweet["retweeted_status"])!=0 and tweet["lang"] == "en" \
            and "retweet_count" in tweet["retweeted_status"].keys():
                if tweet["retweeted_status"]["retweet_count"] > n and "text" in tweet.keys() and len(tweet["text"])!=0:
                    if tweet["text"] not in popular.values():
                        popular[tweet["retweeted_status"]["retweet_count"]] = tweet["text"]
    sorted_popular = sorted(popular.items(), key=lambda t: t[0], reverse = True)
    return sorted_popular

tweets_all = load_data("combined_all.json")
frequent_words_tweets_all = frequent_words(tweets_all, 30)

# print out results as table
pt_word_frequency = PrettyTable(field_names = ['Words', 'Frequency'])
[pt_word_frequency.add_row(row) for row in frequent_words_tweets_all]
print(pt_word_frequency)

# find tweets with an overall retweeted number greater than 5000
popular_retweeted_count = popular_retweeted_count(content, 5000)
for tweet in sorted(popular_retweeted_count, reverse=True):
    print("retweeted_number: ", tweet[0], "\t","tweet_text: ", tweet[1])


import re
from tlds import tlds

EYES = r'[\#:;Xx8]'
HAT = r'[<>~]?'
NOSE = r'[\'-o\*]?'
MOUTH_F = r'[\[\]\|\)\(\/\\DSspPQ><xoO\*]'
MOUTH_B = r'[\[\]\|\)\(\/\\DSsqQ><xoO\*]'
TEAR = r'\'?'

class Tokenizer(object):

    SPLITTER = re.compile(
        '((?:' + ')|(?:'.join([

            # Emoticons
            HAT + EYES + TEAR + NOSE + MOUTH_F,   # <:'-(
            MOUTH_B + NOSE + TEAR + EYES + HAT,   # )-':>
            r'[oO\^\*][_.oOv][oO\^\*]',  # o_O

            # Whitespace
            r'\s+',

            # Elipsis
            r'\.\.+'

            # Contractions
            #r"\w+n't",
            #r"\w+'ll",
            #r"\w+'ve",
            #r"\w+'re",
            #r"\w+'d",
            #r"\w+'s",
            #r"I'm",
            #r"y'all",
            r"\w+'\w+",
            r"\w+n'",
            r"o'\w*",
            r"ol'",
            r"'tis",
            r"'twas",

            # Punctuation
            r'[?!,.;:"\'\(\)\]\[]',

            # Hyperlinks
            r'https?\://\w+(?:\.\w+)+(?:/\S+)*/?',
            r'(?:\w+\.)+(?:' + '|'.join(tlds) + ')(?:/\S+)*/?(?:\s|$)',

        ]) + '))')

    ALL_WHITE = re.compile(r'\s*$')

    def split(self, text):
        return [
            s.lower() for s in self.SPLITTER.split(text)
            if not self.ALL_WHITE.match(s)
        ]


from StyleALAE.losses import *

# --------------------- DISTRIBUTED TRAINING ---------------------------------------------- #
# How to train using distributed https://www.tensorflow.org/tutorials/distribute/custom_training
# There appears to be issues with multi-gpu training. Instead of training inside model.fit method,
# this instead attempts to wrap each training step with @tf.function...
# https://www.tensorflow.org/guide/distributed_training#examples_and_tutorials
# -------------------------------#

def create_discriminator_training_step(model, batch_size):

    @tf.function
    def discriminator_train_step(batch):
        # Step I - Update Discriminator  #
        # -------------------------------#

        # Random mini-batch from data set
        x_real, noise, constant = batch

        # samples from prior N(0, 1)
        z = K.random_normal((batch_size, model.z_dim))
        # generate fake images
        x_fake = model.generator([z, noise, constant])

        # Compute loss and apply gradients
        with tf.GradientTape() as tape:

            fake_pred = model.discriminator(x_fake)

            real_pred = model.discriminator(x_real)

            loss_d = discriminator_logistic_non_saturating(real_pred, fake_pred)

            # Add the R1 term
            if model.γ > 0:

                x_real = model.real_as_tensor(x_real) #tf.Variable(x_real, dtype=tf.float32)
                with tf.GradientTape() as r1_tape:
                    r1_tape.watch(x_real)
                    # 1. Get the discriminator output for real images
                    pred = model.discriminator(x_real)

                # 2. Calculate the gradients w.r.t to the real images.
                grads = r1_tape.gradient(pred, [x_real])[0]

                # 3. Calculate the squared norm of the gradients
                r1_penalty = tf.nn.compute_average_loss(K.sum(K.square(grads), axis=[1, 2, 3]))
                loss_d += model.γ / 2 * r1_penalty

        gradients = tape.gradient(loss_d, model.θ_E + model.θ_D)
        model.optimizer_d.apply_gradients(zip(gradients, model.θ_E + model.θ_D))

        return loss_d

    return discriminator_train_step

def create_generator_training_step(model, batch_size):
    @tf.function
    def generator_train_step(batch):
        # ----------------------------#
        #  Step II - Update Generator #
        # ----------------------------#
        x_real, noise, constant = batch
        # samples from prior N(0, 1)
        z = K.random_normal((batch_size, model.z_dim))
        # Compute loss and apply gradients
        with tf.GradientTape() as tape:
            fake_pred = model.discriminator(model.generator([z, noise, constant]))

            loss_g = generator_logistic_non_saturating(fake_pred)

        gradients = tape.gradient(loss_g, model.θ_F + model.θ_G)
        model.optimizer_g.apply_gradients(zip(gradients, model.θ_F + model.θ_G))

        return loss_g

    return generator_train_step

def create_reciprocal_training_step(model, batch_size):
    @tf.function
    def reciprocal_train_step(batch):
        # ------------------------------#
        #  Step III - Update Reciprocal #
        # ------------------------------#
        x_real, noise, constant = batch
        # samples from prior N(0, 1)
        z = K.random_normal((batch_size, model.z_dim))
        # Get w
        w = model.F(z)
        # Compute loss and apply gradients
        with tf.GradientTape() as tape:
            w_pred = model.reciprocal([w, noise, constant])

            loss_r = l2(w, w_pred)

        gradients = tape.gradient(loss_r, model.θ_G + model.θ_E)
        model.optimizer_r.apply_gradients(zip(gradients, model.θ_G + model.θ_E))

        return loss_r

    return reciprocal_train_step

def create_distributed_train_step(train_step, strategy):
    @tf.function
    def distributed_train_step(dataset_inputs):
        per_replica_losses = strategy.run(train_step, args=(dataset_inputs,))
        return strategy.reduce(tf.distribute.ReduceOp.MEAN, per_replica_losses, axis=None)
    return distributed_train_step


def money():
    lst = sorted(list(map(int, input().split())))
    if len(set(lst)) == 1:
        return lst[0] * 5000 + 50000
    if len(set(lst)) == 2:
        if lst[1] == lst[2]:
            return lst[1] * 1000 + 10000
        else:
            return (lst[1] + lst[2]) * 500 + 2000

    for i in range(3):
        if lst[i] == lst[i+1]:
            return 1000 + lst[i] * 100
    return lst[-1] * 100

N = int(input())

print(max(money() for i in range(N)))

'''
1. 강사님은 함수로 구현.
2. 나는 계속 max 값을 업데이트 하는 형식으로 진행했는데,
    반환값을 모두 받아서 그 중 max 값으로 출력함.
'''

02_알고리즘/python/BOJ/01_기본/2_예외/2484_주사위네개_2.py


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 18 08:35:20 2019

@author: pickering
"""

import numpy as np
import scipy as sp
import matplotlib.pyplot as plt

plt.rc('text', usetex=True)
plt.rc('font', family='sans-serif')

h = 6.626E-34
c = 3E8
temp = 5777
k = 1.38E-23

plt.close('all')

sun_spectra = np.loadtxt('../data_files_for_figures/sun_black_body.txt')
wavelength_sun = np.loadtxt('../data_files_for_figures/sun_wavelengths.txt')
wavelength_nm = np.linspace(0,5000,500)
wavelength_m = wavelength_nm/1E9
frequency = c/wavelength_m
planck = (2*h*(c**2)/(wavelength_m**5))*(1/(np.exp((h*c)/(wavelength_m*k*temp))-1))

rayleigh = 2*c*k*temp/(wavelength_m**4)

plt.figure()
plt.plot(wavelength_nm, planck/1E13, label=r"Planck's Law")
plt.plot(wavelength_nm, rayleigh/1E13, label=r'Rayleigh-Jeans Law')
plt.plot(wavelength_sun, sun_spectra*1.25, linestyle="-", alpha=0.5, label=r'Solar Spectral Radiance')
plt.ylim(0,3)
plt.xlim(0,3000)
plt.xlabel(r'Wavelength [nm]')
plt.ylabel(r'Spectral Radiance [a.u.]')
plt.legend()

plt.savefig('../final_figures/black_body.png',dpi=400,bbox_inches='tight')


'''Circular Singly Linked List '''

class Node():

    def __init__(self,data):

        self.data = data
        self.next = None

class LinkedList():

    def __init__(self):

        self.head = None

    def insertBegin(self,data):

        newNode = Node(data)

        if self.head == None:

            self.head = newNode
            newNode.next = self.head

        else:

            current = self.head
            while current.next != self.head:
                current = current.next

            newNode.next = self.head
            current.next = newNode
            self.head = newNode

    def insertEnd(self,data):

        newNode = Node(data)

        if self.head == None:

            self.head = newNode
            self.head.next = self.head

        else:

            current = self.head

            while current.next != self.head:

                current = current.next

            newNode.next = self.head
            current.next = newNode

    def length(self):

        if self.head == None:

            return 0

        else:

            current = self.head
            count = 1
            while current.next != self.head:

                current = current.next
                count +=1

            return count

    def insertAt(self,index,data):

        newNode = Node(data)

        if index < self.length():

            if index == 0:

                self.insertBegin(data)

            elif index == self.length()-1:

                self.insertEnd(data)

            else:

                prevNode = self.head
                pos = index-1

                while pos != 0:

                    prevNode = prevNode.next
                    pos -=1

                nextNode = prevNode.next
                newNode.next = nextNode
                prevNode.next = newNode

        else:

            print("Index Outof Range")

    def deleteElement(self,element):

        if self.head.data == element:

            temp = self.head
            self.head = temp.next

            current = self.head

            while current.next != temp:

                current = current.next

            current.next = self.head
            return

        else:

            temp = self.head
            current = self.head

            while current.next != temp:

                if current.next.data == element:

                    current.next = current.next.next
                    return

                current = current.next

            print("Element Not Found")

    def showForward(self):

        if self.head == None:

            print("Empty LinkedList")

        else:

            current = self.head

            while current.next != self.head:

                print(current.data,end=",")

                current = current.next

            print(current.data,end=" ")

if __name__ == "__main__":

    a = LinkedList()
    a.insertBegin(4)
    a.insertBegin(3)
    a.insertBegin(1)
    a.insertEnd(5)
    a.insertEnd(6)
    a.insertAt(0,0)
    a.insertAt(2,2)
    a.insertAt(6,7)
    a.showForward()
    a.deleteElement(9)
    a.showForward()


import cv2
import numpy as np
import argparse
import tensorflow as tf

class JudgeFashion:
    def __init__(
        self,
        img_size=640,
        model_path="./trained_model_v1.tflite",
        use_gpu=False,
        w="./yolov3.weights",
        cfg="./yolo.cfg",
    ):
        self.w = w
        self.cfg = cfg

        self.self.IMG_SIZE = self.IMG_SIZE
        self.tflite_interpreter = tf.lite.Interpreter(model_path=args.model_path)

        self.tflite_interpreter.allocate_tensors()
        self.input_details = self.tflite_interpreter.get_input_details()
        self.output_details = self.tflite_interpreter.get_output_details()
        self.input_shape = self.input_details[0]["shape"]
        self.net = cv2.dnn.readNet(self.w, self.cfg)

        if use_gpu:
            net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
            net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)

    def get_output_layers(self, net):
        layer_names = net.getLayerNames()
        output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
        return output_layers

    def fix_img_size(self, im, desired_size=640):
        old_size = im.shape[:2]  # old_size is in (height, width) format

        ratio = float(desired_size) / max(old_size)
        new_size = tuple([int(x * ratio) for x in old_size])

        # new_size should be in (width, height) format

        im = cv2.resize(im, (new_size[1], new_size[0]))

        delta_w = desired_size - new_size[1]
        delta_h = desired_size - new_size[0]
        top, bottom = delta_h // 2, delta_h - (delta_h // 2)
        left, right = delta_w // 2, delta_w - (delta_w // 2)

        color = [0, 0, 0]
        new_im = cv2.copyMakeBorder(
            im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color
        )

        return new_im

    def getYoloPredictions(self, frame, YOLO_NET):
        class_ids = []
        confidences = []
        boxes = []
        blob = cv2.dnn.blobFromImage(
            frame, 0.00392, (416, 416), (0, 0, 0), True, crop=False
        )
        YOLO_NET.setInput(blob)
        outs = YOLO_NET.forward(get_output_layers(YOLO_NET))
        width = frame.shape[1]
        height = frame.shape[0]

        for out in outs:
            for detection in out:
                scores = detection[5:]
                class_id = np.argmax(scores)
                confidence = scores[class_id]
                if confidence > 0.5:
                    center_x = int(detection[0] * width)
                    center_y = int(detection[1] * height)
                    w = int(detection[2] * width)
                    h = int(detection[3] * height)
                    x = center_x - w / 2
                    y = center_y - h / 2
                    class_ids.append(class_id)
                    confidences.append(float(confidence))
                    boxes.append([x, y, w, h])

            indices = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
            return indices, boxes, class_ids

    def crop_out_person(self, img, YOLO_NET=net):
        img = fix_img_size(img, self.IMG_SIZE)
        predictions, boxes, labels = getYoloPredictions(img, YOLO_NET)
        person_bboxes = []
        for currentPrediction in predictions:
            currentPrediction = currentPrediction[0]
            if labels[currentPrediction] != 0:
                continue

            box = boxes[currentPrediction]
            x = box[0]
            y = box[1]
            w = box[2]
            h = box[3]
            label = str(labels[currentPrediction])
            person_bboxes.append([x, y, w, h])

        return person_bboxes

    def get_fashion_results(self, image):
        bboxes = crop_out_person(image)

        for bbox in bboxes:
            x, y, w, h = bbox

            person_croped = image[y : y + h, x : x + w, :]
            fix_sized_img = fix_img_size(person_croped, self.IMG_SIZE)
            self.tflite_interpreter.set_tensor(
                self.input_details[0]["index"], fix_sized_img
            )
            self.tflite_interpreter.invoke()

            results = np.squeeze(
                self.tflite_interpreter.get_tensor(self.output_details[0]["index"])
            )
            return results


import logging

logger = logging.getLogger(__name__)

def validate_item(item: dict):
    """Validate Item data and return dict of data.

    Args:
        item (dict): Feed Item dict

    Returns:
        dict: masked item dict
    """
    try:
        required_item_keys = ['title', 'author',
                              'summary', 'link', 'published']
        if not item.keys() in required_item_keys:
            logger.warning('Invalid item keys')
            return False, 'Invalid item keys'

        cleaned_data = {
            'title': item['title'],
            'author': item['author'],
            'summary': item['summary'],
            'link': item['link'],
            'rights': item['rights'],
            'publication_date': item['published']
        }
        return True, cleaned_data
    except Exception:
        logger.exception('Invalid item data')
        return False, 'Invalid item data'


import logging

_logger = logging.getLogger(__name__)
_logger.setLevel(logging.DEBUG)

def logged_query(cr, query, args=None):
    if args is None:
        args = ()
    args = tuple(args) if type(args) == list else args
    cr.execute(query, args)
    _logger.debug('Running %s', query % args)
    _logger.debug('%s rows affected', cr.rowcount)
    return cr.rowcount

def rename_module(cr):
    old_names = ['acsone_hr_contract']
    new_name = 'hr_contract_signature'
    query = ("UPDATE ir_model_data SET module = %s "
             "WHERE module in %s ")
    logged_query(cr, query, (new_name, tuple(old_names)))
    query = ("UPDATE ir_module_module_dependency SET name = %s "
             "WHERE name in %s")
    logged_query(cr, query, (new_name, tuple(old_names)))


import goody

def read_fa(file : open) -> {str:{str:str}}:
    list = []
    dict = {}
    dict2 = {}
    kk = ''
    for n in file:
        list.append(n.strip().split(';'))
    for k in list:
        for i in range(1,len(k),2):
            dict2.update({k[i:i+2][0]:k[i:i+2][1]})
        dict[k[0]] = dict2.copy()
        dict2.clear()
    return dict

def fa_as_str(fa : {str:{str:str}}) -> str:
    s = []
    b = ""
    fa = sorted(fa.items(), key= lambda x:x[0])
    for ll in fa:
        s = [(key, value) for key, value in ll[1].items() ]
        s.sort(key= lambda x:x[0])
        b += "  " + str(ll[0]) + " transitions: " + str(s) +"\n"
        s.clear()
    return b

def process(fa : {str:{str:str}}, state : str, inputs : [str]) -> [None]:
    list = []
    list2 = []
    list.append(state)
    counter = 0
    cc = state
    if 'x' in inputs:
        inputs.remove('x')
        list2.append(('x', None))
    while counter < len(inputs):
        for n in fa:
            if cc == n:
                list.append((inputs[counter], fa[cc][inputs[counter]]))
                if counter != (len(inputs) - 1):
                    cc = fa[cc][inputs[counter]]
                counter += 1
    if len(list2) == 1:
        list.append(list2[0])
    return list

def interpret(fa_result : [None]) -> str:
    list = []
    n = ""
    n += "Start state = " + str(fa_result[0]) + "\n"
    counter = 0
    fa_result.remove(fa_result[0])
    while counter < len(fa_result):
        for j in fa_result:
            if j[0] == 'x':
                n += "  Input = " + j[0] + '; ' + "illegal input: simulation terminated" + '\n'
                counter += 1
                list.append('1')
            else:
                n += "  Input = " + j[0] + '; ' + "new state = " + j[1] + '\n'
                counter += 1
    if len(list) == 1:
        n+= "Stop state = " + 'None' + '\n'
    else:
        n+= "Stop state = " + fa_result[len(fa_result) - 1][1] + '\n'
    return n

if __name__ == '__main__':
    # Write script here

    # For running batch self-tests
    print()
    import driver
    driver.default_file_name = "bsc3.txt"
#     driver.default_show_traceback = True
#     driver.default_show_exception = True
#     driver.default_show_exception_message = True
    driver.driver()


import subprocess
import os, sys
import time

def listdir_abspath(d):
    return [os.path.abspath(os.path.join(d, f)) for f in os.listdir(d)]

class yolo3(object):
    filenames = None
    procs = None
    fw = None
    fr = None
    df = None
    def __init__(self, *args, **kwargs):
        procs = kwargs['procs']
        self.fw = [ open('tmpout'+str(i)+'.log', 'w') for i in range(procs) ]
        self.procs = [ subprocess.Popen(['./darknet', 'detect', 'cfg/yolov3.cfg', 'yolov3.weights'],
            stdin=subprocess.PIPE, stdout=self.fw[i], stderr=self.fw[i], cwd='../yolo-v3/')
            for i in range(procs) ]
        time.sleep(max(5, procs/3*2))  # let darknet load weigths
        self.fr = [ open('tmpout'+str(i)+'.log', 'r+')  for i in range(procs) ]
        [ f.truncate(0) for f in self.fr ]
        [ f.truncate(0) for f in self.fw ]

    def split_task(self):
        names = []
        for n in self.filenames:
            if n.rsplit('.', 1)[1] in ['jpg', 'png']:
                names.append(n)
        self.filenames = sorted(names)
        # construct dictionary of image uniqnames
        self.df = dict.fromkeys([ n.split('/')[-1] for n in self.filenames ])
        # padding to align
        self.filenames += self.filenames[-1:] * \
            (len(self.procs) - len(self.filenames) % len(self.procs))
        assert(len(self.filenames) % len(self.procs)==0)
        n = len(self.filenames)//len(self.procs)
        self.filenames = [ self.filenames[i:i+n] for i in range(0, len(self.filenames), n) ]
        assert(len(self.filenames)==len(self.procs))

    def run_all(self):
        for i in range(len(self.filenames[0])):
            t = time.time()
            for p in range(len(self.procs)):
                self.recognize(p, i) # assumed to take long (>20 seconds)
            if(i>0):
                # no results to analyze in first loop
                self.text_analyzer(i-1)
                # logically at the end of the loop
            time.sleep(20) # after 20 seconds, start checking results
            while(min([len(f.readlines()) for f in self.fr])<2):
                [f.seek(0) for f in self.fr]
                time.sleep(1) # check every 1 second for results
            print('group {} takes time {}'.format(i+1, time.time()-t))
        self.text_analyzer(len(self.filenames[0])-1)

    def text_analyzer(self, group):
        # this function needs to run in <1 second
        [f.seek(0) for f in self.fr]
        for p in range(len(self.fr)):
            uniqname = self.filenames[p][group].rsplit('/', 1)[1]
            assert(uniqname in self.df)
            result = self.analyze_yolo_output(self.fr[p].readlines())
            self.fw[p].truncate(0)
            # put results in dataframe
            if self.df[uniqname] == 1:
                pass
            else:
                self.df[uniqname] = result
        self.write_progress()

    def write_progress(self, all=False, file=None):
        if file is None:
            file = 'progress.log'
        p = open(file, 'w')
        for k, v in self.df.items():
            if v is not None:
                p.writelines(str(k) + ',' + str(v[0]) + ',' + str(v[1]) + '\n')
            elif all:
                p.writelines(str(k) + ', \n')
        p.close()

    def analyze_yolo_output(self, lines):
        assert(len(lines)>=2)
        assert(lines.pop(-1)=='Enter Image Path: ')
        lines.pop(0)
        for i in range(len(lines)):
            obj,acc = lines[i].split(sep=':', maxsplit=1)
            if obj == 'traffic light':
                return (1, int(acc.split('%')[0]))
            elif obj == 'stop sign':
                return (2, int(acc.split('%')[0]))
        return (0, 0)

    def recognize(self, p, n):
        self.procs[p].stdin.write((self.filenames[p][n]+'\n').encode('utf-8'))
        self.procs[p].stdin.flush()

if __name__ == '__main__':
    y = yolo3(procs=16)
    y.filenames = listdir_abspath('../yolo-v3/data/street/')
    y.split_task()
    y.run_all()


import numpy as np
import scipy as sp
import scipy.fftpack
import pandas as pd
from datetime import datetime
import random
import matplotlib.pyplot as plt
from common import process_merchant_avg_cents_hour_of_day, make_df

first_day = datetime(2033, 1, 1)
last_day = datetime(2034, 12, 31)

df = make_df()
by_merchant = df.groupby("merchant")

df_churned_merchants = pd.read_pickle("churned_merchants.pkl")
print(df_churned_merchants[0:20])

def get_threshold(transactions):
    from skimage.filters import threshold_otsu, threshold_local
    transactions = np.row_stack(( transactions, np.ones(transactions.shape)))
    thresh = threshold_otsu(transactions)
    binary = transactions > thresh
    return thresh

def threshold_transactions(transactions, threshold):
    transactions[transactions <= threshold] = 0
    return transactions

def get_boolean_transactions(transactions, threshold):
    bool_array = transactions > threshold
    bool_array[-1] = True
    return bool_array

def plot_merchant(t_days, transactions, id_merchant):
    fig, ax = plt.subplots()
    ax.plot(t_days , transactions, '.-')
    plt.xlabel("Days")
    plt.ylabel("Transaction Amount (cents)")
    plt.title("Transactions of Merchant {}".format(hex(id_merchant)[2:]))

def plot_merchant_bool(t_days, transactions, bool_transactions, id_merchant):
    f, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
    ax1.plot(t_days , transactions, '.-')
    ax2.plot(t_days, bool_transactions)
    ax2.set_xlabel("Days")
    ax1.set_ylabel("Transaction Amount (cents)")
    ax1.set_title("Transactions of Merchant {}".format(hex(id_merchant)[2:]))
    ax2.set_title("Are There Sales Today?")
    ax2.set_ylabel("Yes (1) / No (0)")

def process_merchant_to_time_series(single_merchant):
    id_merchant = single_merchant['merchant'].iloc[0]
    df_end = pd.DataFrame([[last_day, id_merchant, 0]], columns=['time', 'merchant', 'cents'])
    df_beg = pd.DataFrame([[first_day, id_merchant, 0]], columns=['time', 'merchant', 'cents'])
    single_merchant = single_merchant.append([df_beg, df_end], ignore_index=True)

    # Resample the dataframe
    single_merchant = single_merchant.set_index(['time'])

    df_hourly = pd.DataFrame()
    df_hourly['cents'] = single_merchant['cents'].resample('1D').count()
    df_hourly.insert(1, "merchant", id_merchant)
    df_hourly = df_hourly.reset_index('time')

    transactions = df_hourly['cents'].to_numpy()
    first_of_year = datetime( df.agg({"time": "min"})[0].year, 1, 1 )
    t = df_hourly['time'] - first_of_year
    t_secs = t.dt.total_seconds().to_numpy()
    t_days = t_secs / (3600 * 24)
    return t_days, transactions

id_merchant = int(653416108)
single_merchant = by_merchant.get_group(id_merchant)
churned_merchant = df_churned_merchants.set_index("merchant").loc[id_merchant]
print(churned_merchant)
t_days, transactions = process_merchant_to_time_series(single_merchant)

threshold = get_threshold(transactions)
thresholded_transactions = threshold_transactions(transactions, threshold)
bool_transactions = get_boolean_transactions(transactions, threshold)
i_non_zero = np.nonzero(bool_transactions)
i_diff_non_zero = np.diff(i_non_zero[0])

plot_merchant_bool(t_days[0:-1], transactions[0:-1], bool_transactions[0:-1], id_merchant)
plt.show()


from dateutil import tz
from dateutil.parser import parse

ET = tz.gettz('US/Eastern')
CT = tz.gettz('US/Central')
MT = tz.gettz('US/Mountain')
PT = tz.gettz('US/Pacific')

us_tzinfos = {  'CST': CT, 'CDT' : CT,
                'EST': ET, 'EDT' : ET,
                'MST': MT, 'MDT' : MT,
                'PST': PT, 'PDT' : PT}

dt_est = parse('2014-01-02 04:00:00 EST', tzinfos=us_tzinfos)
dt_pst = parse('2016-03-11 16:00:00 PST', tzinfos=us_tzinfos)

print(dt_est)
print(dt_pst)