def input_int_list():
    return list(map(int, input().strip().split()))

number_of_shoes = int(input())
shoe_sizes = input_int_list()
number_of_customers = int(input())

customers = []
for i in range(number_of_customers):
    size, price = input_int_list()
    customers.append((size, price))

money_sum = 0
for c in customers:
    if c[0] in shoe_sizes:
        money_sum += c[1]
        shoe_sizes.remove(c[0])

print(money_sum)


from herd import Herd
from fleet import Fleet

class Battlefield:

    def __init__(self):
        self.fleet = Fleet()
        self.herd = Herd()

# Begins the game set up and starts it. Built in replayability
    def run_game(self):
        game_start = self.display_welcome()
        if game_start:
            play_again = "1"
            while play_again == "1":
                self.herd.create_herd()
                self.fleet.create_fleet()
                self.display_winners(self.battle())
                play_again = input("\nDo you wish to play again? 1: Yes 2: No \nPlayer: ")

 # Start Menu for Players
    def display_welcome(self):
        game_start = input('''
        \nROBOTS VS DINOSAURS
        \nPress 1 to begin!
        \nPlayer:  ''')
        if game_start == "1":
            return True
        else:
            return False

# Controls the battle sequence for players and ends it upon victory condition met.
    def battle(self):
        game_continue = True
        while game_continue:
            game_continue = self.dino_turn(self.show_dino_options(), self.show_dino_opponent_options())
            if game_continue == False:
                return "Dinosaurs"
            game_continue = self.robo_turn(self.show_robo_options(), self.show_robo_opponent_options())
            if game_continue == False:
                return "Robots"

# Dinosaurs turn and victory condition check
    def dino_turn(self, dinosaur, robot):
        self.herd.dinosaurs[dinosaur].attack(self.fleet.robots[robot])
        for robo in self.fleet.robots:
            if robo.alive == True:
                return True
        return False

# Robots turn and victory condition check
    def robo_turn(self, robot, dinosaur):
        self.fleet.robots[robot].attack(self.herd.dinosaurs[dinosaur])
        for dino in self.herd.dinosaurs:
            if dino.alive == True:
                return True
        return False

##############Refactor Needed Below########################
# Robot character selection, also prevents players from picking a destroyed robot
    def show_robo_options(self):
        invalid_choice = True
        while invalid_choice:
            player_choice = int(input(f'''
            \nPick your robot!
            \n1: {self.fleet.robots[0].name} HP: {self.fleet.robots[0].health}
            \n2: {self.fleet.robots[1].name} HP: {self.fleet.robots[1].health}
            \n3: {self.fleet.robots[2].name} HP: {self.fleet.robots[2].health}
            \nPlayer: ''')) - 1
            if self.fleet.robots[player_choice].alive:
                return player_choice
            elif self.fleet.robots[player_choice].alive == False:
                print(f"{self.fleet.robots[player_choice].name} is already destroyed! Pick another Soldier Commander!")
            else:
                print("Invalid input try again.")

# Dino character selection, also prevents players from picking a dead dino
    def show_dino_options(self):
        invalid_choice = True
        while invalid_choice:
            player_choice = int(input(f'''
            \nPick your dinosaur!
            \n1: {self.herd.dinosaurs[0].name} HP: {self.herd.dinosaurs[0].health}
            \n2: {self.herd.dinosaurs[1].name} HP: {self.herd.dinosaurs[1].health}
            \n3: {self.herd.dinosaurs[2].name} HP: {self.herd.dinosaurs[2].health}
            \nPlayer: ''')) - 1
            if self.herd.dinosaurs[player_choice].alive:
                return player_choice
            elif self.herd.dinosaurs[player_choice].alive == False:
                print(f"{self.herd.dinosaurs[player_choice].name} is already dead! Pick another Dinosaur Alpha!")
            else:
                print("Invalid input try again.")

# Dino Target selection, also prevents players from picking a destroyed target
    def show_dino_opponent_options(self):
        invalid_target = True
        while invalid_target:
            player_target = int(input(f'''
            \nPick your dinosaur's attack target!
            \n1: {self.fleet.robots[0].name} HP: {self.fleet.robots[0].health}
            \n2: {self.fleet.robots[1].name} HP: {self.fleet.robots[1].health}
            \n3: {self.fleet.robots[2].name} HP: {self.fleet.robots[2].health}
            \nPlayer: ''')) - 1
            if self.fleet.robots[player_target].alive:
                return player_target
            elif self.fleet.robots[player_target].alive == False:
                print(f"{self.fleet.robots[player_target].name} is already destroyed! Pick another target Alpha!")
            else:
                print("Invalid input try again.")

# Robo Target selection, also prevents players from picking a dead target
    def show_robo_opponent_options(self):
        invalid_target = True
        while invalid_target:
            player_target = int(input(f'''
            \nPick your robot's attack target!
            \n1: {self.herd.dinosaurs[0].name} HP: {self.herd.dinosaurs[0].health}
            \n2: {self.herd.dinosaurs[1].name} HP: {self.herd.dinosaurs[1].health}
            \n3: {self.herd.dinosaurs[2].name} HP: {self.herd.dinosaurs[2].health}
            \nPlayer: ''')) - 1
            if self.herd.dinosaurs[player_target].alive:
                return player_target
            elif self.herd.dinosaurs[player_target].alive == False:
                print(f"{self.herd.dinosaurs[player_target].name} is already dead! Pick another target Commander!")
            else:
                print("Invalid input try again.")
###############Refactor Needed Above#################################

# When victory conditions are met, will display the winner for the player.
    def display_winners(self, winners):
        if winners == "Dinosaurs":
            print("\nDinosaurs have trampled and dismantled the robot invasion. Skynet does not go online.")
        elif winners == "Robots":
            print("\nSkynet Online. Robots have managed to vaporize the dinosaurs making them extinct Commander... Again.")


from flask import Flask, request, jsonify, json
from flask_api import status
from jinja2._compat import izip
from datetime import datetime
from flask_cors import CORS, cross_origin
from flaskext.mysql import MySQL
from flask import Blueprint
from flask_restplus import Api, Resource, fields
import requests

app = Flask(__name__)
cors = CORS(app)
mysql = MySQL()
product_rating = Blueprint('product_rating_api', __name__)
api = Api(product_rating, version='1.0', title='MyElsa API',
    description='MyElsa API')
name_space = api.namespace('ProductRating', description='Product Rating')

'''app.config['MYSQL_DATABASE_USER'] = 'creamson_langlab'
app.config['MYSQL_DATABASE_PASSWORD'] = 'Langlab@123'
app.config['MYSQL_DATABASE_DB'] = 'creamson_logindb'
app.config['MYSQL_DATABASE_HOST'] = 'creamsonservices.com'
'''

app.config['MYSQL_DATABASE_USER'] = 'admin'
app.config['MYSQL_DATABASE_PASSWORD'] = 'cbdHoRPQPRfTdC0uSPLt'
app.config['MYSQL_DATABASE_DB'] = 'creamson_logindb'
app.config['MYSQL_DATABASE_HOST'] = 'myelsa.cdcuaa7mp0jm.us-east-2.rds.amazonaws.com'

mysql.init_app(app)

app.config['CORS_HEADERS'] = 'Content-Type'

rating_post = api.model('rating_post', {
	"user_id":fields.Integer(required=True),
	"status":fields.String(),
	"rating":fields.Integer(),
	"product_code":fields.String(required=True)})

@name_space.route("/rateProductPost")
class rateProductPost(Resource):
	@name_space.expect(rating_post)
	def post(self):
		details = request.get_json()
		connection = mysql.connect()
		cursor = connection.cursor()
		user_id = details['user_id']
		fav_status = details['status']
		product_code = details['product_code']
		rating = details['rating']

		cursor.execute("""SELECT `id` FROM `product_rating` WHERE
			`user_id` = %s and `product_code` = %s""",(user_id,product_code))

		idx = cursor.fetchone()
		# print(idx)
		if idx:
			idx = idx[0]
		else:
			idx = None

		if idx == None:
			product_rating_insert_query = ("""INSERT INTO `product_rating`(`user_id`, `product_code`,
				`rating`, `status`) VALUES(%s,%s,%s,%s)""")
			product_rating_data = (user_id,product_code,rating,fav_status)
			cursor.execute(product_rating_insert_query,product_rating_data)
			connection.commit()
			details['rating_id'] = cursor.lastrowid

			cursor.execute("""SELECT avg(`rating`),COUNT(`product_code`) FROM product_rating
					WHERE product_code = %s GROUP BY product_code""",(product_code))

			rating_data = cursor.fetchall()
			if rating_data:
				avg_rating = rating_data[0][0]
				noofrating = rating_data[0][1]
				avg_rating = 4.5
				noofrating = 12 + noofrating
				if noofrating < 20:
					avg_rating = 4.5
				if noofrating > 20:
					avg_rating = round((rating_data[0][0]),2)

			details['noofrating'] = noofrating
			details['avg_rating'] = avg_rating

			return ({"attributes": {
		    				"status_desc": "Product Rating Details.",
		    				"status": "success"
		    				},
		    				"responseList":{"RatingDtls":details}}), status.HTTP_200_OK

		else:
			# update_url = 'http://127.0.0.1:5000/product_rating/ProductRating/rateProductUpdate'
			update_url = 'http://ec2-18-191-221-235.us-east-2.compute.amazonaws.com/product_rating/ProductRating/rateProductUpdate'
			update_data = details
			headers = {'Content-type':'application/json', 'Accept':'application/json'}
			rating_put_res = requests.put(update_url, data=json.dumps(update_data),headers=headers)
			res = rating_put_res.json()
			print(res)
			return res

		connection.commit()
		cursor.close()

@name_space.route("/rateProductUpdate")
class rateProductUpdate(Resource):
	@name_space.expect(rating_post)
	def put(self):
		details = request.get_json()
		connection = mysql.connect()
		cursor = connection.cursor()
		user_id = details['user_id']
		fav_status = details['status']
		product_code = details['product_code']
		rating = details['rating']
		print(user_id,product_code)
		cursor.execute("""SELECT `id`,`rating`,`status` FROM `product_rating` WHERE
			`user_id` = %s and `product_code` = %s""",(user_id,product_code))

		idx = cursor.fetchall()
		# print(idx)
		if idx:
			rating_id = idx[0][0]
			cursor.execute("""SELECT avg(`rating`),COUNT(`product_code`) FROM product_rating
					WHERE product_code = %s GROUP BY product_code""",(product_code))

			rating_data = cursor.fetchall()
			if rating_data:
				avg_rating = rating_data[0][0]
				noofrating = rating_data[0][1]
				avg_rating = 4.5
				noofrating = 12 + noofrating
				if noofrating < 20:
					avg_rating = 4.5
				if noofrating > 20:
					avg_rating = round((rating_data[0][0]),2)

			details['noofrating'] = noofrating
			details['avg_rating'] = avg_rating
		if rating and not fav_status:
			update_rating_query = ("""UPDATE `product_rating` SET `rating`= %s
				WHERE id = %s""")
			update_rating_data = (rating,rating_id)
			cursor.execute(update_rating_query,update_rating_data)
		elif fav_status and not rating:
			update_rating_query = ("""UPDATE `product_rating` SET `status`= %s
				WHERE id = %s""")
			update_rating_data = (fav_status,rating_id)
			cursor.execute(update_rating_query,update_rating_data)

		elif fav_status and rating:
			update_rating_query = ("""UPDATE `product_rating` SET `rating`= %s,`status`= %s
				WHERE id = %s""")
			update_rating_data = (rating,fav_status,rating_id)
			cursor.execute(update_rating_query,update_rating_data)
		else:
			user_rating = idx[0][1]
			user_fav_status = idx[0][2]
			update_rating_query = ("""UPDATE `product_rating` SET `rating`= %s ,`status`= %s
				WHERE id = %s""")
			update_rating_data = (user_rating,user_fav_status,rating_id)
			cursor.execute(update_rating_query,update_rating_data)

		connection.commit()
		details['rating_id'] = rating_id
		cursor.close()
		return ({"attributes": {
		    				"status_desc": "Product Rating Details.",
		    				"status": "success"
		    				},
		    				"responseList":{"RatingDtls":details}}), status.HTTP_200_OK

@name_space.route("/getProductRatingAndLike/<int:user_id>/<string:product_code>")
class rateProductUpdate(Resource):
	def get(self,user_id,product_code):
		connection = mysql.connect()
		cursor = connection.cursor()
		details = {"avg_rating":4.5,
					"noofrating":12,
					"likes_count":0,
					"dislike_count":0,
					"user_rating":"",
					"user_vote":""}
		try:

			cursor.execute("""SELECT id FROM product_rating
				WHERE product_code = %s""",(product_code))

			idx = cursor.fetchone()
			if idx:
				idx = idx[0]

			if idx:
				cursor.execute("""SELECT avg(`rating`),COUNT(`product_code`) FROM product_rating
					WHERE product_code = %s GROUP BY product_code""",(product_code))

				rating_data = cursor.fetchall()
				if rating_data:
					avg_rating = rating_data[0][0]
					noofrating = rating_data[0][1]
					avg_rating = 4.5
					noofrating = 12 + noofrating
					if noofrating < 20:
						avg_rating = 4.5
					if noofrating > 20:
						avg_rating = round((rating_data[0][0]),2)
				else:
					avg_rating = 0
					noofrating = 0

				cursor.execute("""SELECT COUNT(status) FROM product_rating WHERE
					product_code = %s and status = 'l' GROUP BY product_code""",(product_code))

				like_data = cursor.fetchone()
				if like_data:
					likes_count = like_data[0]
				else:
					likes_count = 0

				cursor.execute("""SELECT COUNT(status) FROM product_rating WHERE
					product_code = %s and status = 'd' GROUP BY product_code""",(product_code))

				dislike_data = cursor.fetchone()
				if dislike_data:
					dislike_count = dislike_data[0]
				else:
					dislike_count = 0

				cursor.execute("""SELECT `rating`,`status` FROM product_rating WHERE
					product_code = %s and `user_id` = %s""",(product_code,user_id))

				user_data = cursor.fetchall()
				if user_data:
					user_rating = user_data[0][0]
					user_vote = user_data[0][1]
				else:
					user_rating = 0
					user_vote = ""
				# print(user_data)
				details = {"avg_rating":avg_rating,
					"noofrating":noofrating,
					"likes_count":likes_count,
					"dislike_count":dislike_count,
					"user_rating":user_rating,
					"user_vote":user_vote}

		except:
			pass

		return ({"attributes": {
		    				"status_desc": "Product Rating Details.",
		    				"status": "success"
		    				},
		    				"responseList":details}), status.HTTP_200_OK

if __name__ == '__main__':
	app.run(host='0.0.0.0',debug=True)


# coding: utf-8
from django.conf.urls import patterns, url

from esperancanordeste.catalog.views import (ProductListView,
                                             ProductCategoryListView,
                                             ProductDetailListView)

urlpatterns = patterns(
    'esperancanordeste.catalog.views',
    url(r'^$', ProductListView.as_view(), name='home'),
    url(r'^(?P<category_slug>[-\w]+)/$',
        ProductCategoryListView.as_view(),
        name='category_list'),
    url(r'^(?P<category_slug>[-\w]+)/(?P<slug>[-\w]+)/$',
        ProductDetailListView.as_view(),
        name='product_detail'),
)


# This is a scanner that takes a string of raw input and returns a sentence
# that is composed of a list of tuples with the (TOKEN, WORD) pairings.
# If a word isn't part of the lexicon, then it returns the WORD with
# TOKEN set to error.

def scan(sentence=[]):
    direction=['north', 'south', 'east', 'west']
    verb=['go', 'stop', 'kill', 'eat']
    stop=['the', 'in', 'of', 'from', 'at', 'it']
    noun=['door', 'bear', 'princess', 'cabinet']
    # Empty list to store result
    result=[]
    # Takes input and separates it into words in a list
    words = sentence.split()
    # Converts each word in the list to lower case
    words = [element.lower() for element in words]

    for item in words:
        if item  in direction:
            direction_word=('direction',item)
#                print "Will print direction_word"
#                print direction_word
            result.append(direction_word)
        elif item in verb:
            verb_word=('verb',item)
            result.append(verb_word)
        elif item in stop:
            stop_word=('stop', item)
            result.append(stop_word)
        elif item in noun:
            noun_word=('noun', item)
            result.append(noun_word)
        else:
            error_word=('error',item)
            result.append(error_word)

    return result


def is_simple(n):
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True

def digits_sum(n):
    summ = 0
    for i in range(len(n)):
        summ += int(n[i])
    return summ

for i in range(100):
    st = '>' + '0' * 39 + 'static' * i + '2' * 39
    while '>static' in st or '>2' in st or '>0' in st:
        if '>static' in st:
            st = st.replace('>static', '22>', 1)
        if '>2' in st:
            st = st.replace('>2', '2>', 1)
        if '>0' in st:
            st = st.replace('>0', 'static>', 1)
    st = st.replace('>', '')
    if is_simple(digits_sum(st)):
        print(i)
        print(digits_sum(st))
        break


import cv2
import numpy as np
import datetime as dt
import math

#horrible estimate
def checkYAxis(y):
    if 100<y<240:
        return 1
    if 240<y<326:
        return 2
    if 326<y<400:
        return 3
    if 400<y<490:
        return 4
    if 490<y<530:
        return 5
    if 530<y<620:
        return 6

def checkLed(xval, yval, med, img, r):

    if img[xval, yval-med] == 1 and yval-med !=0:

        #print('a')
        #print(r)
        r += 1
        return checkLed(xval, yval-med, med, img, r)

    return r

'''
read the immage and apply gray filter
'''
img = cv2.imread('Clipboard02.bmp')
cv2.imshow("image", img)
cv2.waitKey(0)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

'''
apply gaussian blur to the gray image
'''
gray_blur = cv2.GaussianBlur(gray, (15, 15), 0)
cv2.imshow("gas", gray_blur)
cv2.waitKey(0)

'''
binarize the image with 200 threshold
thresh1 is the binarized image
'''
ret,thresh1 = cv2.threshold(gray_blur,200,255,cv2.THRESH_BINARY)
cv2.imshow("gas", thresh1)
cv2.waitKey(0)

'''
compute the closing using a 3x3 kernel
'''

kernel = np.ones((3,3), np.uint8)
closing = cv2.morphologyEx(thresh1, cv2.MORPH_CLOSE,kernel,iterations=4)
cv2.imshow("gas4", closing)
cv2.waitKey(0)

'''
we'll work on a copy of the processed image
'''
cont_img = closing.copy()

'''
find the contours
'''
im2,ctrs, hier = cv2.findContours(cont_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

#sorted_ctrs = sorted(ctrs, key=lambda ctr: cv2.boundingRect(ctr)[0] + cv2.boundingRect(ctr)[1] * img.shape[1] ) (left to right top to bottom)

'''
sort the contours from left to right
'''
sorted_ctrs = sorted(ctrs, key=lambda ctr: cv2.boundingRect(ctr)[0])
centroids = []
on_leds = []
y_values = []

for i, ctr in enumerate(sorted_ctrs):
    # Get bounding box
    x, y, w, h = cv2.boundingRect(ctr)

    #Centroids coordinates
    M = cv2.moments(ctr)
    cY = int(M["m10"] / M["m00"])
    cX = int(M["m01"] / M["m00"])
    centroids.append((cX,cY))

    #save Y values for sorting
    y_values.append(cY)

    #test = checkYAxis(cY)
    #on_leds.append(test)

    #cv2.drawContours(img, [ctr], -1, (0, 255, 0), 2)
    #cv2.rectangle(img,(x,y),( x + w, y + h ),(90,0,255),2)
    #cv2.putText(img, str(test), (x - 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.65, (0, 255, 0), 2)

print("y axis values: ")
print(y_values)
m = []
med = 0

#compute the average value for all the y axis values
if len(y_values) > 1:
    for i in range(0, len(y_values)-1):
        m.append(y_values[i+1]-y_values[i])
    for elem in m:
        med += elem
    med /= len(m)

leds = open('leds2.txt', 'w')
#go through contours again and draw bounding rectangles and the sequence numbers for each rectangle
for i, ctr in enumerate(sorted_ctrs):
    # Get bounding box
    x, y, w, h = cv2.boundingRect(ctr)
    M = cv2.moments(ctr)
    cY = int(M["m10"] / M["m00"])
    cX = int(M["m01"] / M["m00"])
    cv2.rectangle(img,(x,y),( x + w, y + h ),(90,0,255),2)

    if len(y_values) == 1:
        cv2.putText(img, "1", (x - 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.65, (0, 255, 0), 2)
        leds.write("led 1 is on ")
    else:
        test = checkLed(cX, cY, med, cont_img, 1)
        on_leds.append(test)
        cv2.putText(img, str(test), (x - 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.65, (0, 255, 0), 2)

leds.write("On leds: ")
leds.write(str(on_leds))
leds.close()

cv2.imshow('marked areas',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
print("Centroids:")
print (centroids)
print ("Number of Contours -> %d "%len(ctrs))
print("on leds:")
print (on_leds)
'''
TODO: iterate through Y values of centroids
and find median value of (c2 - c1) (c3-c2)...
use that as the estimate for which led is open
'''

# define the list of boundaries
# Convert to HSV colorspace
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

#Yellow
lower_yellow = np.array([20, 100, 100], dtype=np.uint8)
upper_yellow = np.array([40, 255, 255], dtype=np.uint8)
mask = cv2.inRange(hsv, lower_yellow, upper_yellow)

output = cv2.bitwise_and(img, img, mask = mask)
cv2.imshow("images",output)
cv2.waitKey(0)

'''
output = cv2.connectedComponents(cont_img, 4, cv2.CV_32S)

num_labels = output[0]
labels = output[1]

cnts = cv2.findContours(cont_img, cv2.RETR_EXTERNAL,
	cv2.CHAIN_APPROX_SIMPLE)
cnts = contours.sort_contours(cnts)[0]

# Map components labels to hue val
label_hue = np.uint8(179*labels/np.max(labels))
blank_ch = 255*np.ones_like(label_hue)
labeled_img = cv2.merge([label_hue, blank_ch, blank_ch])

#cvt to bgr display
labeled_img = cv2.cvtColor(labeled_img, cv2.COLOR_HSV2BGR)

#set bg label to black
labeled_img[label_hue==0] = 0
cv2.imshow("labeled", labeled_img)
cv2.waitKey(0)
'''


###
## * << Haru Free PDF Library 2.0.0 >> -- character_map.c
## *
## * Copyright (c) 1999-2006 Takeshi Kanno <takeshi_kanno@est.hi-ho.ne.jp>
## *
## * Permission to use, copy, modify, distribute and sell this software
## * and its documentation for any purpose is hereby granted without fee,
## * provided that the above copyright notice appear in all copies and
## * that both that copyright notice and this permission notice appear
## * in supporting documentation.
## * It is provided "as is" without express or implied warranty.
## *
## * usage character_map <encoding-name> <low-range-from> <low-range-to>
## *              <high-range-from> <high-range-to>
## * ex. character_map 90ms-RKSJ-V 0x80 0x
## *
##

## port to python by Li Jun
## http://groups.google.com/group/pythoncia

import os, sys

from ctypes import *
up=2
def setlibpath(up):
    import sys
    path=os.path.normpath(os.path.split(os.path.realpath(__file__))[0]+'\..'*up)
    if path not in sys.path:
        sys.path.append(path)

setlibpath(up)

from haru import *
from haru.c_func import *
from haru.hpdf_errorcode import *

@HPDF_Error_Handler(None, HPDF_UINT, HPDF_UINT, c_void_p)
def error_handler (error_no, detail_no, user_data):
    global pdf
    printf ("ERROR: %s, detail_no=%u\n", error_detail[error_no],
                detail_no)
    HPDF_Free (pdf)
    sys.exit(1)

def draw_page(pdf, page, title_font, font, h_byte, l_byte):
    PAGE_WIDTH = 420
    CELL_HEIGHT = 20
    CELL_WIDTH = 20

    l_byte = int(l_byte / 16) * 16
    h_count = 16 - (l_byte / 16)
    page_height = 40 + 40 + (h_count + 1) * CELL_HEIGHT

    HPDF_Page_SetHeight (page, page_height)
    HPDF_Page_SetWidth (page, PAGE_WIDTH)

    HPDF_Page_SetFontAndSize (page, title_font, 10)

    ypos = h_count + 1
    while True:
        y = (ypos) * CELL_HEIGHT + 40

        HPDF_Page_MoveTo (page, 40, y)
        HPDF_Page_LineTo (page, 380, y)
        HPDF_Page_Stroke (page)
        if (ypos < h_count):
            buf=[None,None]

            buf[0] = 16 - ypos - 1
            if (buf[0] < 10):
                buf[0] += ord('0')
            else:
                buf[0] += (ord('A') - 10)
            buf[1] = 0
            buf=[i % 256 for i in buf]      #because buf is unsigned char *

            w = HPDF_Page_TextWidth (page, buf)
            HPDF_Page_BeginText (page)
            HPDF_Page_MoveTextPos (page, 40 + (20 - w) / 2, y + 5)
            HPDF_Page_ShowText (page, buf)
            HPDF_Page_EndText (page)

        if (ypos == 0):
            break

        ypos-=1

    for xpos in range(18):
        y = (h_count + 1) * CELL_HEIGHT + 40
        x = xpos * CELL_WIDTH + 40

        HPDF_Page_MoveTo (page, x, 40)
        HPDF_Page_LineTo (page, x, y)
        HPDF_Page_Stroke (page)

        if (xpos > 0 and xpos <= 16):
            buf=[None,None]

            buf[0] = xpos - 1
            if (buf[0] < 10):
                buf[0] += ord('0')
            else:
                buf[0] += (ord('A') - 10)
            buf[1] = 0
            buf=[i % 256 for i in buf]      #because buf is unsigned char *

            w = HPDF_Page_TextWidth(page, buf)
            HPDF_Page_BeginText(page)
            HPDF_Page_MoveTextPos(page, x + (20 - w) / 2,
                        h_count * CELL_HEIGHT + 45)
            HPDF_Page_ShowText(page, buf)
            HPDF_Page_EndText(page)

    HPDF_Page_SetFontAndSize (page, font, 15)

    ypos = h_count
    while True:
        y = (ypos - 1) * CELL_HEIGHT + 45

        for xpos in range(16):
            buf=[None for i in range(3)]

            x = xpos * CELL_WIDTH + 40 + CELL_WIDTH

            buf[0] = h_byte
            buf[1] = (16 - ypos) * 16 + xpos
            buf[2] = 0x00
            buf=[i % 256 for i in buf]      #because buf is unsigned char *

            w = HPDF_Page_TextWidth(page, buf)
            if (w > 0):
                HPDF_Page_BeginText(page)
                HPDF_Page_MoveTextPos(page, x + (20 - w) / 2, y)
                HPDF_Page_ShowText(page, buf)
                HPDF_Page_EndText(page)

        if (ypos == 0):
            break

        ypos-=1

def main ():
    global  pdf

    flg=[HPDF_UINT16(0) for i in range(256)]

    fname=os.path.realpath(sys.argv[0])
    fname=fname[:fname.rfind('.')]+'.pdf'

    if (len(sys.argv) < 3):
        printf ("usage: character_map <encoding-name> <font-name>\n")
        printf ('for example, character_map.py GBK-EUC-H SimHei,Bold')
        return 1

    pdf = HPDF_New (error_handler, NULL)
    if (not pdf):
        printf ("error: cannot create PdfDoc object\n")
        return 1

    # configure pdf-document (showing outline, compression enabled)
    HPDF_SetPageMode(pdf, HPDF_PAGE_MODE_USE_OUTLINE)
    HPDF_SetCompressionMode (pdf, HPDF_COMP_ALL)
    HPDF_SetPagesConfiguration (pdf, 10)

    HPDF_UseJPEncodings (pdf)
    HPDF_UseJPFonts (pdf)
    HPDF_UseKREncodings (pdf)
    HPDF_UseKRFonts (pdf)
    HPDF_UseCNSEncodings (pdf)
    HPDF_UseCNSFonts (pdf)
    HPDF_UseCNTEncodings (pdf)
    HPDF_UseCNTFonts (pdf)

    encoder = HPDF_GetEncoder (pdf, sys.argv[1])
    if (HPDF_Encoder_GetType (encoder) != HPDF_ENCODER_TYPE_DOUBLE_BYTE):
        printf ("error: %s is not cmap-encoder\n", sys.argv[1])
        HPDF_Free (pdf)
        return 1

    font = HPDF_GetFont (pdf, sys.argv[2], sys.argv[1])

    min_l = 255
    min_h = 256
    max_l = 0
    max_h = 0

    for i in range(256):
        for j in range(20, 256):
            buf=[None, None ,None]
            code = i * 256 + j

            buf[0] = i
            buf[1] = j
            buf[2] = 0

            btype = HPDF_Encoder_GetByteType (encoder, buf, 0)
            unicode = HPDF_Encoder_GetUnicode (encoder, code)

            if (btype == HPDF_BYTE_TYPE_LEAD and
                    unicode != 0x25A1):
                if (min_l > j):
                    min_l = j

                if (max_l < j):
                    max_l = j

                if (min_h > i):
                    min_h = i

                if (max_h < i):
                    max_h = i

                flg[i] = 1

    printf ("min_h=%04X max_h=%04X min_l=%04X max_l=%04X\n",
            min_h, max_h, min_l, max_l)

    # create outline root.
    root = HPDF_CreateOutline (pdf, NULL, sys.argv[1], NULL)
    HPDF_Outline_SetOpened (root, HPDF_TRUE)

    for i in range(256):
        if (flg[i]):
            page = HPDF_AddPage (pdf)
            title_font = HPDF_GetFont (pdf, "Helvetica", NULL)

            buf="0x%04X-0x%04X" %(
                                  (i * 256 + min_l),
                                  (i * 256 + max_l)
                                 )

            outline = HPDF_CreateOutline (pdf, root, buf, NULL)
            dst = HPDF_Page_CreateDestination (page)
            HPDF_Outline_SetDestination(outline, dst)

            draw_page (pdf, page, title_font, font, i, min_l)

            buf="%s (%s) 0x%04X-0x%04X" %(
                        sys.argv[1],
                        sys.argv[2],
                        (i * 256 + min_l),
                        (i * 256 + max_l)
                        )
            HPDF_Page_SetFontAndSize (page, title_font, 10)
            HPDF_Page_BeginText (page)
            HPDF_Page_MoveTextPos (page, 40, HPDF_Page_GetHeight (page) - 35)
            HPDF_Page_ShowText (page, buf)
            HPDF_Page_EndText (page)

    HPDF_SaveToFile (pdf, fname)
    HPDF_Free (pdf)

    return 0

main()


from flask import Flask, request, render_template
import random
from expansions import expand

app = Flask(__name__, static_url_path="")

@app.route("/", methods=["POST", "GET"])
def render_name():
    themes = []
    expression = ""
    name = ""

    if len(request.values.get("expression", "").strip()) > 0:
        expression = request.values.get("expression")
        name = expand(expression)

    else:
        themes = request.values.getlist("theme")
        if not isinstance(themes, list):
            themes = ["buzzword"]

        buzz_patterns = []
        dict_patterns = []

        for theme in themes:
            buzz_patterns.append("{prefix}{%s|few}" % theme)
            buzz_patterns.append("{%s|few}{suffix}" % theme)
            buzz_patterns.append("{%s|several}" % theme)
            dict_patterns.append("{dict %s|several}" % theme)

        if random.random() > .7:
            pattern = random.choice(dict_patterns)
        else:
            pattern = random.choice(buzz_patterns)

        name = expand(pattern)

    return render_template("index.html", name=name, themes=themes, expression=expression)

if __name__ == "__main__":
    app.run()


import asyncio
import timeit
from concurrent.futures import ProcessPoolExecutor
from concurrent.futures import ThreadPoolExecutor

import aiohttp
import requests

class AsyncioPractice:

    def _fetch(self, url):
        response = requests.get(url)
        assert response.status_code == 200

    def processpool_fetch_all(self, urls):
        with ProcessPoolExecutor(max_workers=5) as executor:
            [executor.submit(self._fetch, url) for url in urls]

    def threadpool_fetch_all(self, urls):
        with ThreadPoolExecutor(max_workers=5) as executor:
            [executor.submit(self._fetch, url) for url in urls]

    def block_fetch_all(self, urls):
        [self._fetch(url) for url in urls]

    async def async_fetch(self, session, url):
        with aiohttp.Timeout(10):
            print('start:', url)
            async with session.get(url) as response:
                print('get urls:', url)
                assert response.status == 200

    async def async_fetch_all(self, session, urls):
        fetches = [asyncio.Task(self.async_fetch(session, url)) for url in urls]
        await asyncio.gather(*fetches)

if __name__ == '__main__':
    INPUT_URLS = [
        'http://b.ssut.me',
        'https://google.com',
        'https://apple.com',
        'https://ubit.info',
        'https://github.com/ssut'
    ]
    ASYNCIO_PRACTICE = AsyncioPractice()
    START = timeit.default_timer()
    LOOP = asyncio.get_event_loop()
    with aiohttp.ClientSession(loop=LOOP) as client_session:
        LOOP.run_until_complete(ASYNCIO_PRACTICE.async_fetch_all(client_session, INPUT_URLS))
    print(timeit.default_timer() - START)


# Project, Part 1, Uninformed Search

from networkx import nx
# import matplotlib.pyplot as plt
from queue import PriorityQueue
import time

# MAX_CARDS = 1

def load_data():
    G = nx.Graph()
    with open("input.txt", "r") as f:
        for line in f.readlines():
            G.add_edge(*tuple(map(int, line.split())))

    return G

def exposed_graph(G, node):
    H = nx.Graph()
    for i in node:
        H.add_edges_from([(i, n) for n in G.neighbors(i)])

    return H

def path_cost(G, node):
    population = G.number_of_nodes()

    cost = 0
    unexposed_people = G.copy()
    for i, person in enumerate(node):
        n_exposed = G.number_of_nodes() - unexposed_people.number_of_nodes()
        n_given_card = i

        new_exposed_people = unexposed_people.neighbors(person)
        new_exposed = len(new_exposed_people)

        adoption_probability = max(.1, 1 - 1 / (n_exposed + n_given_card)) if n_exposed + n_given_card != 0 else .1
        cost += population - 1 - new_exposed * adoption_probability

        unexposed_people.remove_nodes_from(new_exposed_people)
        unexposed_people.remove_node(person)

    return cost

def card_candidates(G, node):
    H = exposed_graph(G, node)
    I = G.copy()
    I.remove_nodes_from(H)
    return I.nodes()

def goal_test(G, node, max_cards, candidates=None):
    if len(node) == max_cards:
        return True

    if candidates is None:
        candidates = card_candidates(G, node)
    return len(candidates) == 0

# running in about T(n, c) = .009 * n^(c - 1) where n of friendships and c is the number of cards given out
def uniform_cost_search(G, num_cards):
    frontier = PriorityQueue()

    count = 0
    frontier.put((0, []))
    while "pigs" != "fly":
        if frontier.empty():
            raise Exception("Not solution found")

        cost, node = frontier.get()

        candidates = card_candidates(G, node)
        if goal_test(G, node, num_cards, candidates):
            print("Nodes expanded: " + str(count))
            return node

        count += 1
        for candidate in candidates:
            child = node[:] + [candidate]
            frontier.put((path_cost(G, child), child))

def main():
    print("running project.part1.uninformed_search")

    G = load_data()
    for i in range(1, 4):
        start = time.time()

        solution = uniform_cost_search(G, i)

        print(solution)
        print("Time: " + str(time.time() - start))
        print()

if __name__ == '__main__':
    main()


"""
Checksum builder.
"""

from httpx import Response

from .models import CheckSumsData, CheckSumsFile

class CheckSumDataBuilder:
    """
    Class to build the CheckSumsData object
    from the response of the checksums API.
    """

    _response: Response

    def __init__(self, response: Response) -> None:
        self._response = response

    def build(self) -> CheckSumsData:
        """
        Build the CheckSumsData object.
        """
        _checksums = CheckSumsData()
        _raw_data = self._response.text.split("\n")

        for _raw_line in _raw_data:
            _line = _raw_line.strip()

            if _line == "":
                continue

            _line_split = _line.split("  ")
            _checksum = CheckSumsFile(filename=_line_split[1], checksum=_line_split[0])
            _checksums.checksum_by_filename[_checksum.filename] = _checksum

        return _checksums


import sys

import numpy as np
import pygame
from pygame.locals import (K_ESCAPE, K_RETURN, K_SPACE, KEYDOWN,
                           MOUSEBUTTONDOWN, MOUSEMOTION, QUIT)

pygame.init()
font = pygame.font.SysFont('Verdana', 30)
bg = (40, 40, 40)
lines = (70, 70, 70)
white = (255, 255, 255)

in_play_button = lambda x, y: 120 >= x >= 9 and 645 >= y >= 605
in_clear_button = lambda x, y: 257 >= x >= 135 and 645 >= y >= 605
in_step_button = lambda x, y: 388 >= x >= 275 and 645 >= y >= 605

class Button:
    __slots__ = ([
        'main_text', 'second_text', 'main_color', 'select_color', 'pos'
    ])

    def __init__(self,
                 main_text: str = '',
                 second_text: str = '',
                 main_color: tuple = (0, 100, 0),
                 select_color: tuple = (0, 255, 0),
                 pos: tuple = (0, 0)):
        self.main_text = main_text
        self.second_text = second_text
        self.main_color = main_color
        self.select_color = select_color
        self.pos = pos

    def __call__(self, text: bool = True, color: bool = True):
        if text:
            _text = self.main_text
        else:
            _text = self.second_text
        if color:
            _color = self.main_color
        else:
            _color = self.select_color

        return font.render(_text, True, white, _color)

class GameOfLife():

    def __init__(self):

        self.width = 1200
        self.height = 600
        self.square_size = 10

        self.rc = int(self.height / self.square_size)
        self.cc = int(self.width / self.square_size)

        self.game_board = np.zeros((self.rc, self.cc))

        # Buttons
        self.play_button = Button(' Start  ', ' Pause ', (0, 100, 0),
                                  (0, 255, 0), (10, 605))
        self.clear_button = Button('  Clear  ', '', (100, 0, 0), (255, 0, 0),
                                   (135, 605))
        self.step_button = Button('  Step  ', '', (0, 100, 0), (0, 255, 0),
                                  (275, 605))

        pygame.init()
        pygame.display.set_caption('Game of Life!!')
        self.screen = pygame.display.set_mode((self.width, self.height + 60))
        self.clock = pygame.time.Clock()
        self.update_game = False

    def __call__(self, update_game: bool = False):

        state = np.copy(self.game_board)

        for row in range(self.rc):
            for col in range(self.cc):
                if update_game:
                    life_cells = \
                        state[(row - 1) % self.rc, (col - 1) % self.cc] + \
                        state[(row - 1) % self.rc, col % self.cc] + \
                        state[(row - 1) % self.rc, (col + 1) % self.cc] + \
                        state[ row % self.rc, (col - 1) % self.cc] + \
                        state[ row % self.rc, (col + 1) % self.cc] + \
                        state[(row + 1) % self.rc, (col - 1) % self.cc] + \
                        state[(row + 1) % self.rc, col % self.cc] + \
                        state[(row + 1) % self.rc, (col + 1) % self.cc]

                    # Rules
                    if self.game_board[row, col] == 0 and life_cells == 3:
                        self.game_board[row, col] = 1

                    elif self.game_board[row, col] == 1 and (life_cells > 3 or
                                                             life_cells < 2):
                        self.game_board[row, col] = 0

                # Draw cells
                if self.game_board[row, col] == 0:
                    pygame.draw.rect(
                        self.screen, lines,
                        (col * self.square_size, row * self.square_size,
                         self.square_size, self.square_size), 1)
                else:
                    pygame.draw.rect(
                        self.screen, white,
                        (col * self.square_size, row * self.square_size,
                         self.square_size, self.square_size), 0)

    def quit_game(self):
        pygame.quit()
        sys.exit()

    def switch_update(self):
        self.update_game = not self.update_game
        self.pb = self.play_button(not self.update_game, True)

    def clear_screen(self):
        self.game_board = np.zeros((self.rc, self.cc))
        if self.update_game:
            self.switch_update()

    def events(self):
        for event in pygame.event.get():

            # Close game
            if event.type == QUIT:
                self.quit_game()

            elif event.type == KEYDOWN:
                keys = pygame.key.get_pressed()

                if keys[K_ESCAPE]:
                    self.quit_game()
                elif keys[K_SPACE]:
                    self.switch_update()
                elif keys[K_RETURN]:
                    self(True)

            elif event.type == MOUSEMOTION:
                x_pos, y_pos = pygame.mouse.get_pos()

                self.pb = self.play_button(not self.update_game,
                                           not in_play_button(x_pos, y_pos))
                self.cb = self.clear_button(True,
                                            not in_clear_button(x_pos, y_pos))
                self.sb = self.step_button(True,
                                           not in_step_button(x_pos, y_pos))

            clicks = pygame.mouse.get_pressed()
            if sum(clicks) == 0:
                continue
            x_pos, y_pos = pygame.mouse.get_pos()

            x_cell = int(np.floor(x_pos / self.square_size))
            y_cell = int(np.floor(y_pos / self.square_size))

            if clicks == (1, 0, 0):

                if in_play_button(x_pos, y_pos):
                    self.switch_update()
                elif in_clear_button(x_pos, y_pos):
                    self.clear_screen()
                elif in_step_button(x_pos, y_pos):
                    self(True)
                elif y_cell < self.rc:
                    self.game_board[y_cell, x_cell] = 1

            elif clicks == (0, 0, 1):

                if y_cell < self.rc:
                    self.game_board[y_cell, x_cell] = 0

        self.screen.blit(self.pb, self.play_button.pos)
        self.screen.blit(self.cb, self.clear_button.pos)
        self.screen.blit(self.sb, self.step_button.pos)

if __name__ == '__main__':
    game = GameOfLife()
    while True:
        game.clock.tick(15)
        game.screen.fill(bg)
        game.events()
        game(game.update_game)
        pygame.display.flip()


a1 = int(input('輸入首項:'))
r = int(input('輸入公比:'))
n = int(input('輸入項數:'))
sum1 = 0
for i in range(n):
    ax = a1 * r ** i
    sum1 += ax
    print(ax,"i:",i,end=" ")
print("=>",sum1)

def getAn(n):
    if n == 1:
        return a1
    else:
        return getAn(n-1) * r

def getSn(n):
    if n == 1:
        return a1
    else:
        an = getAn(n)
        return getSn(n-1) + an
print(getSn(n))


height = int(input("Whats your height in cm? "))
credits = int(input("How much credits you have? "))

# if height >= 137 and credits >= 10:
#   print("Enjoy the ride!")
# elif credits >= 10 and height < 137:
#   print("You are not tall enough to ride.")
# elif height >= 137 and credits < 10:
#   print("You don't have enough credits.")
# else:
#   print("You are not tall enough and dont have credits!")

#bonus

is_rolercoaster_open = True
is_tall_enough = height >= 137
have_credits = credits >= 10

if is_rolercoaster_open and is_tall_enough and have_credits:
  print("Enjoy you ride!")
elif not is_tall_enough or not have_credits:
  print("You dont meet the requirements!")
else:
  print("The rolercoaster is closed!")


"""
https://www.youtube.com/watch?v=kWiCuklohdY&t=3s

나도코딩
파이썬 코딩 무료 강의 (기본편) - 6시간 뒤면 여러분도 개발자가 될 수 있어요 [나도코딩]

2022-07-13 02:28:36 ~ 02:37:49
2022-07-14 02:37:50 ~ 02:58:58
"""

# 7-1 함수

def open_account():
    print("새로운 계좌가 생성되었습니다.")

open_account()

# 7-2 전달값과 반환값
# 예제 1 : 입금

def deposit(balance, money):  # 입금
    print("입금이 완료되었습니다. 잔액은 {0}원입니다.".format(balance + money))
    return balance + money

balance = 0
balance = deposit(balance, 1000)
print(balance)

# 예제 2 : 출금

def withdraw(balance, money):  # 출금
    if balance >= money:  # 잔액이 출금하려는 금액과 같거나 많으면
        print("출금이 완료되었습니다. 잔액은 {0}원입니다.".format(balance - money))
        return balance - money
    else:
        print("출금이 불가합니다. 잔액은 {0}원입니다.".format(balance))
        return balance

balance = 0
balance = deposit(balance, 2000)
balance = withdraw(balance, 1000)
print(balance)
'''
입금이 완료되었습니다. 잔액은 2000원입니다.
출금이 완료되었습니다. 잔액은 1000원입니다.
1000
'''
balance = 0
balance = deposit(balance, 2000)
balance = withdraw(balance, 3000)
print(balance)
'''
입금이 완료되었습니다. 잔액은 2000원입니다.
출금이 불가합니다. 잔액은 2000원입니다.
2000
'''

# 예제 3 : 야간 출금, 수수료

def withdraw_night(balance, money):  # 저녁에 출금
    commission = 100  # 수수료 100원
    return commission, balance - money - commission

balance = 0
balance = deposit(balance, 1000)
commission, balance = withdraw_night(balance, 500)
print('수수료는 {0}원이며, 잔액은 {1}원입니다.'.format(commission, balance))
'''
입금이 완료되었습니다. 잔액은 1000원입니다.
수수료는 100원이며, 잔액은 400원입니다.
'''

# 7-3 기본값

def profile(name, age, main_lang):
    print("이름 : {0}\t나이 : {1}\t주 사용 언어 : {2}"\
          .format(name, age, main_lang))

profile("Edwin", 20, "Python")
profile("Jose", 25, "Java")
'''
이름 : Edwin	나이 : 20	주 사용 언어 : Python
이름 : Jose	나이 : 25	주 사용 언어 : Java
'''

# 같은 학교 같은 학년 같은 반 같은 수업

def profile(name, age=17, main_lang="Python"):  # 기본 값 설정
    print("이름 : {0}\t나이 : {1}\t주 사용 언어 : {2}"\
          .format(name, age, main_lang))

profile("Edwin")
profile("Jose")
'''
기본값으로 나이와 주 사용 언어를 설정해두었기 때문에,
이름만 기입하면 기본값을 그대로 출력해주는 것을 확인 할 수 있음

출력 결과 :
이름 : Edwin	나이 : 17	주 사용 언어 : Python
이름 : Jose	나이 : 17	주 사용 언어 : Python
'''

# 7-4 키워드값

def profile(name, age, main_lang):
    print(name, age, main_lang)

profile(name="Edwin", main_lang="Python", age=20)
profile(main_lang="Java", age=25, name="Jose")
'''
순서를 다르게 입력해도, 키워드에 맞춰 값을 기입함으로써
함수에 정의한 순서대로 값을 반환해 주는 것을 확인 할 수 있음.

출력 결과 :
Edwin 20 Python
Jose 25 Java
'''

# 7-5 가변인자

def proflie(name, age, *language):
    print("이름 : {0}\t나이: {1}\t".format(name, age), end=" ")
    for lang in language:
        print(lang, end=" ")
    print()

# 개인별로 익힌 언어의 갯수가 다를 수 있으므로,
# def proflie(name, age, lang1, lang2, lang3 ... 이렇게 일일이 기입하는 것 보다
# *language로 지정하고 for문을 사용하는 것이 합리적

proflie("Louis", 20, "Python", "Java", "C", "C++", "C#", "JavaScript")
# 이름 : Louis	나이: 20	 Python Java C C++ C# JavaScript

proflie("Lisbeth", 25, "Kotlin", "Swift")
# 이름 : Lisbeth	나이: 25	 Kotlin Swift

# 7-6 지역변수와 전역변수

gun = 10

# 방법 1
def checkpoint(soldiers):  # 경계근무
    global gun  # 전역 공간에 있는 gun 사용 : 함수 내에서가 아니라 전체에 사용 가능
    gun = gun - soldiers
    print("남은 총 : {0}".format(gun))

print("전체 총 : {0}".format(gun))
checkpoint(2)
'''
전체 총 : 10
남은 총 : 8
'''

# 방법 2 : 방법 1처럼 전역변수를 쓸 수도 있지만
# 나중에 코드 관리가 힘들기 때문에 이렇게 하는 것이 낫다고 함.
def checkpoint_ret(gun, soldiers):
    gun = gun - soldiers
    print("남은 총 : {0}".format(gun))
    return gun

print("전체 총 : {0}".format(gun))
gun = checkpoint_ret(gun, 2)
'''
전체 총 : 10
남은 총 : 8
'''

# 7-7 퀴즈 #6

'''
Quiz)  표준 체중을 구하는 프로그램을 작성하시오

* 표준 체중 : 각 개인의 키에 적당한 체중

(성별에 따른 공식)
남자 : 키(m) x 키(m) x 22
여자 : 키(m) x 키(m) x 21

조건 1 : 표준 체중은 별도의 함수 내에서 계산
             * 함수명 : std_weight
             * 전달값 : 키(height), 성별(gender)
조건 2 : 표준 체중은 소수점 둘째자리까지 표시

(출력 예제)
키 175cm 남자의 표준 체중은 67.38kg입니다.
'''

def std_weight(height, gender):

    if gender == "남자":
        return height * height * 22
    else:
         return height * height * 21

height = 175
gender = "남자"
weight = round(std_weight(height / 100, gender), 2)
print("키 {0}cm {1}의 표준 체중은 {2}kg입니다. ".format(height, gender, weight))


def get_quant(char, linhas):
    count = 0
    for l in linhas:
        count += l.count(char)
    return count

def win(player, linhas):
    for l in linhas:
        if l.count(player) == 3:
            return True
    for i in range(0,3):
        if linhas[0][i] == player and linhas[0][i] == linhas[1][i] and linhas[1][i] == linhas[2][i]:
            return True
    if linhas[1][1] == player:
        if linhas[0][0] == linhas[1][1] and linhas[1][1] == linhas[2][2]:
            return True
        if linhas[0][2] == linhas[1][1] and linhas[1][1] == linhas[2][0]:
            return True
    return False

def valid_board(linhas):
    xq = get_quant('X', linhas)
    oq = get_quant('O', linhas)
    if xq - oq < 0 or xq - oq > 1:
        return False
    if win('O', linhas) and xq != oq:
        return False
    if win('X', linhas) and xq == oq:
        return False
    return True

if __name__ == '__main__':
    n = int(input().strip())
    for i in range(0, n):
        l1 = input().strip()
        while not l1:
            l1 = input().strip()
        l2 = input().strip()
        l3 = input().strip()
        if valid_board([l1,l2,l3]):
            print('yes')
        else:
            print('no')


''' Agents: stop/random/shortest/seq2seq  '''

import json
import os
import sys
import numpy as np
import random
import time
import math

import torch
import torch.nn as nn
import torch.distributions as D
from torch.autograd import Variable
from torch import optim
import torch.nn.functional as F

import utils
from env import R2RBatch
from utils import padding_idx
from param import args
from collections import defaultdict

import scipy.stats

class BaseAgent(object):
    ''' Base class for an R2R agent to generate and save trajectories. '''

    def __init__(self, env, results_path):
        self.env = env
        self.results_path = results_path
        random.seed(args.seed)
        self.results = {}
        self.losses = [] # For learning agents
        self.IL_losses = []
        self.WeTA_losses = []
        self.RL_losses = []
        self.WaTA_losses = []

    def write_results(self):
        output = [{'inst_idx': k, 'trajectory': v} for k, v in self.results.iteritems()]
        with open(self.results_path, 'w') as f:
            json.dump(output, f)

    def rollout(self):
        ''' Return a list of dicts containing instr_id:'xx', path:[(viewpointId, heading_rad, elevation_rad)]  '''
        raise NotImplementedError

    @staticmethod
    def get_agent(name):
        return globals()[name+"Agent"]

    def test(self):
        self.env.reset_epoch()
        self.losses = []
        self.WeTA_losses = []
        self.RL_losses = []
        self.WaTA_losses = []
        self.IL_losses = []

        self.results = {}
        # We rely on env showing the entire batch before repeating anything
        #print 'Testing %s' % self.__class__.__name__
        looped = False
        while True:
            for traj in self.rollout():
                if traj['inst_idx'] in self.results:
                    looped = True
                else:
                    self.results[traj['inst_idx']] = traj['path']
            if looped:
                break

class AskOracle(object):
    def __init__(self):
        self.uncertain_threshold = args.uncertain_threshold
        self.DONT_ASK = 0
        self.ASK = 1

    def isUncertain(self, agent_dist):
        uniform = [1. / len(agent_dist)] * len(agent_dist)
        entropy_gap = scipy.stats.entropy(uniform) - scipy.stats.entropy(agent_dist)
        if entropy_gap < self.uncertain_threshold - 1e-9:
            return self.ASK, 'uncertain '
        else:
            return self.DONT_ASK, ''

    def __call__(self, agent_dist, last_distance, cur_distance):
        finalreason = ""
        ask_1, ask_reason_1 = self.isUncertain(agent_dist)
        if ask_1 == 1:
            finalreason += ask_reason_1

        if last_distance - cur_distance <= 0: # no progress
            ask_2 = 1
            ask_reason_2 = 'no progress'
        else:
            ask_2 = 0
            ask_reason_2 = ''

        if ask_2 == 1:
            finalreason += ask_reason_2

        finalask = 1 if (ask_1 or ask_2) else 0

        return finalask, finalreason

class SCoA_Agent(BaseAgent):
    ''' An agent based on an LSTM seq2seq model with attention. '''

    # For now, the agent can't pick which forward move to make - just the one in the middle
    model_actions = ['left', 'right', 'up', 'down', 'forward', '<end>', '<start>', '<ignore>']
    env_actions = {
      "left": ([0],[-1], [0]), # left
      "right": ([0], [1], [0]), # right
      "up": ([0], [0], [1]), # up
      "down": ([0], [0],[-1]), # down
      "forward": ([1], [0], [0]), # forward
      "<end>": ([0], [0], [0]), # <end>
      "<start>": ([0], [0], [0]), # <start>
      "<ignore>": ([0], [0], [0])  # <ignore>
    }
    feedback_options = ['teacher', 'argmax', 'sample']

    def __init__(self, env, results_path, encoder, decoder, critic, WeTA, episode_len=20, visable=False, path_type='planner_path'):
        super(SCoA_Agent, self).__init__(env, results_path)
        self.feature_size = 2048
        self.encoder = encoder
        self.decoder = decoder

        self.critic = critic
        self.WeTA = WeTA

        self.episode_len = episode_len
        self.losses = []
        self.IL_losses = []
        self.criterion = nn.CrossEntropyLoss(ignore_index=args.ignoreid, size_average=False)

        self.WeTA_criterion = nn.CrossEntropyLoss(size_average=False)
        self.WeTA_losses = []

        self.RL_losses = []
        self.WaTA_losses = []

        self.logs = defaultdict(list)

    @staticmethod
    def n_inputs():
        return len(SCoA_Agent.model_actions)

    @staticmethod
    def n_outputs():
        return len(SCoA_Agent.model_actions)-2 # Model doesn't output start or ignore

    # prepare candidate length and feature(bs, max_candidate_leng, 2048+4)
    def _candidate_variable(self, obs):
        candidate_leng = [len(ob['candidate']) + 1 for ob in obs]       # +1 is for the end
        candidate_feat = np.zeros((len(obs), max(candidate_leng), self.feature_size + args.angle_feat_size), dtype=np.float32)
        # Note: The candidate_feat at len(ob['candidate']) is the feature for the END
        # which is zero in my implementation
        for i, ob in enumerate(obs):
            for j, c in enumerate(ob['candidate']):
                candidate_feat[i, j, :] = c['feature']                         # Image feat
        return torch.from_numpy(candidate_feat).cuda(), candidate_leng

    # get angle feature, image feature, candidate feature, candidate leng
    def get_input_feat(self, obs):
        input_a_t = np.zeros((len(obs), args.angle_feat_size), np.float32)
        for i, ob in enumerate(obs):
            input_a_t[i] = utils.angle_feature(ob['heading'], ob['elevation'])
        input_a_t = torch.from_numpy(input_a_t).cuda()

        f_t = self._feature_variable(obs)      # Image features from obs
        candidate_feat, candidate_leng = self._candidate_variable(obs)

        # input_a_t: shape(bs, angle_feat_size)
        # f_t: shape(bs, 36, 2048)
        # candidate_feat: shape(bs, max_candidate_leng, 2048+4)
        # candidate_leng: shape(bs, 1)
        return input_a_t, f_t, candidate_feat, candidate_leng

    def _feature_variable(self, obs):
        ''' Extract precomputed features into variable. '''
        features = np.empty((len(obs), args.num_view, self.feature_size + args.angle_feat_size), dtype=np.float32)
        # feature_size = obs[0]['feature'].shape[0]
        # features = np.empty((len(obs), self.feature_size), dtype=np.float32)
        for i,ob in enumerate(obs):
            features[i,:] = ob['feature']
        return Variable(torch.from_numpy(features), requires_grad=False).cuda()

    def get_nav_feature_variable(self, obs):
        features = np.empty((len(obs), 5, args.num_view, self.feature_size), dtype=np.float32)
        for i, ob in enumerate(obs):
            features[i, :] = ob['nav_history_feature']
        return Variable(torch.from_numpy(features), requires_grad=False).cuda()

    def _teacher_action(self, obs, ended):
        """
        Extract teacher actions into variable.
        :param obs: The observation.
        :param ended: Whether the action seq is ended
        :return:
        """
        a = np.zeros(len(obs), dtype=np.int64)
        for i, ob in enumerate(obs):
            if ended[i]:                                            # Just ignore this index
                a[i] = args.ignoreid
            else:
                for k, candidate in enumerate(ob['candidate']):
                    if candidate['viewpointId'] == ob['teacher']:   # Next view point
                        a[i] = k
                        break
                else:   # Stop here
                    try:
                        assert ob['teacher'] == ob['viewpoint']         # The teacher action should be "STAY HERE"
                    except:
                        import pdb; pdb.set_trace()
                    a[i] = len(ob['candidate'])
        return torch.from_numpy(a).cuda()

    def make_equiv_action(self, a_t, perm_obs, perm_idx=None, traj=None):
        """
        Interface between Panoramic view and Egocentric view
        It will convert the action panoramic view action a_t to equivalent egocentric view actions for the simulator
        """
        def take_action(i, idx, name):
            if type(name) is int:       # Go to the next view
                self.env.env.sims[idx].makeAction([name], [0], [0])
            else:                       # Adjust
                self.env.env.sims[idx].makeAction(*self.env_actions[name])
            state = self.env.env.sims[idx].getState()[0]
            if traj is not None:
                traj[i]['path'].append((state.location.viewpointId, state.heading, state.elevation))

        if perm_idx is None:
            perm_idx = range(len(perm_obs))
        for i, idx in enumerate(perm_idx):
            action = a_t[i]
            if action != -1:            # -1 is the <stop> action
                select_candidate = perm_obs[i]['candidate'][action]
                src_point = perm_obs[i]['viewIndex']
                trg_point = select_candidate['pointId']
                src_level = (src_point ) // 12   # The point idx started from 0
                trg_level = (trg_point ) // 12
                while src_level < trg_level:    # Tune up
                    take_action(i, idx, 'up')
                    src_level += 1
                while src_level > trg_level:    # Tune down
                    take_action(i, idx, 'down')
                    src_level -= 1
                while self.env.env.sims[idx].getState()[0].viewIndex != trg_point:    # Turn right until the target
                    take_action(i, idx, 'right')
                assert select_candidate['viewpointId'] == \
                       self.env.env.sims[idx].getState()[0].navigableLocations[select_candidate['idx']].viewpointId
                take_action(i, idx, select_candidate['idx'])

    def update_ctx(self, ctx, h_t, c_t, ans_ctx, ans_h_t, ans_c_t, predict_WeTA):
        predict_WeTA = predict_WeTA.unsqueeze(-1) # (bs, 1)

        ctx = ctx + predict_WeTA * ans_ctx
        h_t = h_t + predict_WeTA * ans_h_t
        c_t = c_t + predict_WeTA * ans_c_t

        return ctx, h_t, c_t

    def getangle_feature(self, obs):
        ''' Extract precomputed features into variable. '''
        features = np.empty((len(obs), self.feature_size + args.angle_feat_size), dtype=np.float32)
        for i,ob in enumerate(obs):
            features[i,:] = ob['feature'][ob['viewIndex']]
        return Variable(torch.from_numpy(features), requires_grad=False).cuda()

    def rollout(self, iter=None, train_RL=True):

        obs = np.array(self.env.reset())
        batch_size = len(obs)

        # Record starting point
        traj = [{
            'inst_idx': ob['inst_idx'],
            'path': [(ob['viewpoint'], ob['heading'], ob['elevation'])]
        } for ob in obs]

        # Init the reward shaping
        last_dist = np.zeros(batch_size, np.float32)
        for i, ob in enumerate(obs):   # The init distance from the view point to the target
            last_dist[i] = ob['distance']

        # ctx: shape(bs, 1, 512)
        # h_t: shape(bs, 512)
        # c_t: shape(bs, 512)
        # tar_enc: shape(bs, 1, 512)
        ctx, h_t, c_t, tar_enc = self.encoder(obs, cur_img=None, next_img=None, tar_enc=None, encoder_target=True)

        # Initialization the tracking state
        ended = np.array([False] * batch_size) # Indices match permuation of the model, not env

        # For test result submission
        visited = [set() for _ in obs]

        # Init the logs
        rewards = []
        hidden_states = []
        policy_log_probs = []
        masks = []
        entropys = []

        # Do a sequence rollout and calculate the loss
        self.loss = 0
        self.IL_loss = 0
        self.WeTA_loss = 0
        self.RL_loss = 0
        self.WaTA_loss = 0

        h1 = h_t
        for t in range(self.episode_len):
            input_a_t, f_t, candidate_feat, candidate_leng = self.get_input_feat(obs)

            WeTA_logit, predict_WeTA = self.WeTA(h_t)  # (bs, )

            cur_imgfeature = self._feature_variable(obs)

            next_vp_imgfeature = np.array([ob['next_vp_imgfeature'] for ob in obs])
            next_vp_imgfeature = Variable(torch.from_numpy(next_vp_imgfeature), requires_grad=False).cuda()

            WaTA_loss, ans_ctx, ans_h_t, ans_c_t = \
                    self.encoder(obs=obs, cur_img=cur_imgfeature, next_img=next_vp_imgfeature, tar_enc=tar_enc)
            # udpate ctx, h_t, c_t
            ctx, h_t, c_t = self.update_ctx(ctx, h_t, c_t, ans_ctx, ans_h_t, ans_c_t, predict_WeTA)

            # add env dropout
            noise = self.decoder.drop_env(torch.ones(self.feature_size).cuda())
            candidate_feat[..., :-args.angle_feat_size] *= noise
            f_t[..., :-args.angle_feat_size] *= noise

            h_t, c_t, logit, h1 = self.decoder(input_a_t, f_t, candidate_feat,
                                    h_t, h1, c_t, ctx, None)

            hidden_states.append(h_t)
            candidate_mask = utils.length2mask(candidate_leng)

            # if 'test' in self.env.splits:
            if args.submit == 'True':     # Avoding cyclic path
                for ob_id, ob in enumerate(obs):
                    visited[ob_id].add(ob['viewpoint'])
                    for c_id, c in enumerate(ob['candidate']):
                        if c['viewpointId'] in visited[ob_id]:
                            candidate_mask[ob_id][c_id] = 1
            logit.masked_fill_(candidate_mask, -float('inf'))

            # Supervised training
            if 'test' not in self.env.splits:
                self.loss += WaTA_loss
                self.WaTA_loss += WaTA_loss

                # WeTA
                WeTA_target = []
                for ob_id, ob in enumerate(obs):
                    if ended[ob_id]:
                        WeTA_target.append(AskOracle().DONT_ASK)
                    else:
                        WeTA_t, _ = AskOracle()(logit[ob_id].cpu().detach().numpy(), last_dist[ob_id], ob['distance'])
                        WeTA_target.append(WeTA_t)
                WeTA_target = Variable(torch.Tensor(WeTA_target).long(), requires_grad=False).cuda()

                WeTA_loss = self.WeTA_criterion(WeTA_logit, WeTA_target)
                self.loss += WeTA_loss
                self.WeTA_loss += WeTA_loss

                target = self._teacher_action(obs, ended)

                IL_loss = self.criterion(logit, target)
                if not math.isinf(IL_loss):
                    self.loss += IL_loss
                    self.IL_loss += IL_loss

            probs = F.softmax(logit, dim=1)
            c = D.Categorical(probs)
            # RL
            self.logs['entropy'].append(c.entropy().sum().item())  # For log
            entropys.append(c.entropy())  # For optimization
            a_t = c.sample().detach()
            policy_log_probs.append(c.log_prob(a_t))

            cpu_a_t = a_t.cpu().numpy()
            for i, next_id in enumerate(cpu_a_t):
                if next_id == (candidate_leng[i]-1) or next_id == args.ignoreid:    # The last action is <end>
                    cpu_a_t[i] = -1

            self.make_equiv_action(cpu_a_t, obs, None, traj)
            obs = np.array(self.env._get_obs())

            dist = np.zeros(batch_size, np.float32)
            reward = np.zeros(batch_size, np.float32)
            mask = np.ones(batch_size, np.float32)
            for i, ob in enumerate(obs):
                dist[i] = ob['distance']
                if ended[i]:            # If the action is already finished BEFORE THIS ACTION.
                    reward[i] = 0.
                    mask[i] = 0.
                else:       # Calculate the reward
                    if predict_WeTA[i] >= 0.5:
                        reward[i] = args.ask_reward
                    else:
                        reward[i] = 0
                    action_idx = cpu_a_t[i]
                    if action_idx == -1:        # If the action now is end
                        if dist[i] < 3:         # Correct
                            reward[i] = reward[i] + 3.
                        else:                   # Incorrect
                            reward[i] = reward[i] - 3.
                    else:                       # The action is not end
                        pro = - (dist[i] - last_dist[i])      # Change of distance
                        if pro > 0:                           # Quantification
                            reward[i] = reward[i] + 2
                        elif pro <= 0:
                            reward[i] = reward[i] - 2

            rewards.append(reward)
            masks.append(mask)
            last_dist[:] = dist

            ended[:] = np.logical_or(ended, (cpu_a_t == -1))

            # Early exit if all ended
            if ended.all():
                break

            torch.cuda.empty_cache()

        torch.cuda.empty_cache()
        # Last action in A2C
        input_a_t, f_t, candidate_feat, candidate_leng = self.get_input_feat(obs)
        candidate_feat[..., :-args.angle_feat_size] *= noise
        f_t[..., :-args.angle_feat_size] *= noise

        last_h_, _, _, _ = self.decoder(input_a_t, f_t, candidate_feat,
                         h_t, h1, c_t, ctx, None)
        RL_loss = 0.

        # NOW, A2C!!!
        # Calculate the final discounted reward
        last_value__ = self.critic(last_h_).detach()    # The value esti of the last state, remove the grad for safety
        discount_reward = np.zeros(batch_size, np.float32)  # The inital reward is zero
        for i in range(batch_size):
            if not ended[i]:        # If the action is not ended, use the value function as the last reward
                discount_reward[i] = last_value__[i]

        length = len(rewards)
        total = 0
        for t in range(length-1, -1, -1):
            discount_reward = discount_reward * args.gamma + rewards[t]   # If it ended, the reward will be 0
            mask_ = Variable(torch.from_numpy(masks[t]), requires_grad=False).cuda()
            clip_reward = discount_reward.copy()
            r_ = Variable(torch.from_numpy(clip_reward), requires_grad=False).cuda()
            v_ = self.critic(hidden_states[t])
            a_ = (r_ - v_).detach()

            # r_: The higher, the better. -ln(p(action)) * (discount_reward - value)
            RL_loss += (-policy_log_probs[t] * a_ * mask_).sum()
            RL_loss += (((r_ - v_) ** 2) * mask_).sum() * 0.5     # 1/2 L2 loss
            if self.feedback == 'sample':
                RL_loss += (- 0.01 * entropys[t] * mask_).sum()
            self.logs['critic_loss'].append((((r_ - v_) ** 2) * mask_).sum().item())

            total = total + np.sum(masks[t])
        self.logs['total'].append(total)

        self.RL_loss += RL_loss
        self.loss += RL_loss

        if 'test' not in self.env.splits:
            self.losses.append(self.loss.item() / self.episode_len)
            self.IL_losses.append(self.IL_loss.item() / self.episode_len)
            self.WeTA_losses.append(self.WeTA_loss.item() / self.episode_len)
            self.WaTA_losses.append(self.WaTA_loss.item() / self.episode_len)
            self.RL_losses.append(self.RL_loss.item() / self.episode_len)

        torch.cuda.empty_cache()

        return traj

    def test(self, use_dropout=False, feedback='argmax', allow_cheat=False):
        ''' Evaluate once on each instruction in the current environment '''
        if not allow_cheat: # permitted for purpose of calculating validation loss only
            assert feedback in ['argmax', 'sample'] # no cheating by using teacher at test time!
        self.feedback = feedback
        if use_dropout:
            self.encoder.train()
            self.decoder.train()
            self.critic.train()
            self.WeTA.train()
        else:
            self.encoder.eval()
            self.decoder.eval()
            self.critic.eval()
            self.WeTA.eval()
        with torch.no_grad():
            super(SCoA_Agent, self).test()

    def train(self, encoder_optimizer, decoder_optimizer, critic_optimizer, WeTA_optimizer,
              n_iters, feedback='teacher'):
        ''' Train for a given number of iterations '''
        assert feedback in self.feedback_options
        self.feedback = feedback
        self.encoder.train()
        self.decoder.train()
        self.critic.train()
        self.WeTA.train()

        self.losses = []
        self.WeTA_losses = []
        self.RL_losses = []
        self.WaTA_losses = []
        self.IL_losses = []
        for iter in range(1, n_iters + 1):
            encoder_optimizer.zero_grad()
            decoder_optimizer.zero_grad()
            critic_optimizer.zero_grad()
            WeTA_optimizer.zero_grad()

            self.rollout(iter)
            self.loss.backward()

            encoder_optimizer.step()
            decoder_optimizer.step()
            critic_optimizer.step()
            WeTA_optimizer.step()

    def save(self, encoder_path, decoder_path, critic_path, WeTA_path):
        ''' Snapshot models '''
        torch.save(self.encoder.state_dict(), encoder_path)
        torch.save(self.decoder.state_dict(), decoder_path)
        torch.save(self.critic.state_dict(), critic_path)
        torch.save(self.WeTA.state_dict(), WeTA_path)

    def load(self, encoder_path, decoder_path, critic_path, WeTA_path):
        ''' Loads parameters (but not training state) '''
        print("loading encoder, decoder, critic, WeTA")
        self.encoder.load_state_dict(torch.load(encoder_path))
        self.decoder.load_state_dict(torch.load(decoder_path))
        self.critic.load_state_dict(torch.load(critic_path))
        self.WeTA.load_state_dict(torch.load(WeTA_path))


"""
Suite à la votation d'hier sur la nouvelle constitution pour Genève, le canton va reverser aux communes le Fonds Réservé pour l'Adoption de la Nouvelle Constitution. Ce FRANC sera réparti en fonction du nombre de votants par commune, et du score réalisé, selon les critères suivants :

les communes reçoivent l'un des montants de base suivants, selon le nombre de votes :
    - toutes les communes recevront au minimum CHF 5'000.-
        - ou alors CHF 8'000.- s'il y a plus de 1000 votants
        - ou alors CHF 12'000.- s'il y a plus de 2000 votants
    - selon le score réalisé, un montant peut être rajouté au montant de base :
        - 2'000.- de plus si le OUI l'a emporté
            - et un montant supplémentaire de CHF 4'000.- est encore versé s'il y a eu plus de 65% de OUI.
"""

def montant_final(nb_oui, nb_non, nb_votants):
    nb_votants = nb_oui + nb_non
    argent = 0
    if((nb_votants) > 1000 and (nb_votants) <= 2000):
            argent += 8000
    elif((nb_votants) > 2000):
            argent += 12000
    else:
        argent += 5000

    if(nb_oui > nb_non):
            argent += 2000

    if(100*nb_oui/(nb_votants) > 65):
            argent += 4000
    return argent

def main():
    nb_oui = int(input("Nombre de oui : "))
    nb_non = int(input("Nombre de non : "))
    nb_votants = nb_oui + nb_non
    montant_final(nb_oui, nb_non, nb_votants)

    print(f"Le montant pour cette commune ayant {nb_oui} de OUI et {nb_non} de NON sera de : {montant_final(nb_oui, nb_non, nb_votants)} CHF")

if __name__ == "__main__":
    main()


# coding: utf-8

# In[1]:

import numpy as np
import matplotlib.pyplot as plt
from Random import RandomDist

# experiment parameters
Nmeas = 1
Nexp = 1000
sigma = 2

true = []
best = []

# instantiate Random class
random = RandomDist()

# Loop through different mu values
# use function in random.py returns a random pesudo integer using normal distribution (Box-muller method)
for i in range(-100,100):
    mu_true = i/10.0
    for e in range(0, Nexp):
        mu_best = 0
        for m in range(0, Nmeas):
            # random pesudo number
            x = float(random.normal(mu_true,sigma))
            mu_best += x

        mu_best = mu_best/Nmeas

        # append into array of mu values
        true.append(mu_true)
        best.append(mu_best)

# plotting
plt.figure(figsize=(10,8))
plt.hist2d(true, best, bins=[50,150])
plt.colorbar()
plt.ylim(-10,10)
plt.xlim(-10,10)
plt.xlabel('$\\mu$ True', fontsize = 15)
plt.ylabel('$\\mu$ measured',fontsize = 15)
plt.title('Neyman Construction of Gaussian',fontsize = 15)
plt.savefig('Neyman_Gaussian.png')
plt.show()


from typing import List, Dict
from data.utils.emojis import EMOJIS
import requests
import random
import sys
import logging

def get_json_data_from_url(url: str) -> List[Dict]:
    response = requests.get(url)
    if response.status_code == 200:
        return response.json()
    else:
        sys.exit(-1)

def get_shuffled_emojis() -> List:
    emojis = list(EMOJIS)
    random.shuffle(emojis)
    return emojis

def log_command_pressed(update):
    user = update.message.from_user
    username = user.username
    user_id = user.id
    first_name = user.first_name

    if update.message.location is not None:
        lat = update.message.location.latitude
        long = update.message.location.longitude
        logging.info(f"{username}/{first_name} ({user_id}) sent a location: {lat}, {long}.")
    else:
        command = update.message.text[:255]
        logging.info(f"{username}/{first_name} ({user_id}) sent {command}.")


from pcooja import *
import random
import os
import datetime
import glob
#from custommotes import *

CoojaSimulation.set_contiki_path("/home/user/contiki-ng")

folder = CoojaSimulation.get_contiki_path()+"/examples"

import logging
logger.setLevel(logging.INFO)

def simulation_example1():
    csc_filepath=f"{folder}/rpl-udp/rpl-udp-cooja.csc"

    # Create a simulation object from an existing .csc file.
    simulation = CoojaSimulation.from_csc(csc_filepath)
    simulation.timeout = 10
    # Edit some settings (optional)
    simulation.success_ratio_rx = 1.0

    # Run the simulation and store the log and radio data in files
    simulation.run()

def simulation_example2():
    # Defining cooja mote types and firmware
    server = Z1MoteType(f"{folder}/rpl-udp/udp-server.c")
    client = Z1MoteType(f"{folder}/rpl-udp/udp-client.c")

    # Use a predefined topology that creates 1 server mote and 24 client motes
    topology = Topology.get_tree25_topology(Z1Mote, server, client)

    # Create a simulation with default RX/TX success ratio, seed and timeout values
    simulation = CoojaSimulation(topology, timeout=30)

    # Run the simulation and store the log and radio data in specific files
    simulation.run()

def simulation_example3():
    csc_filepath=f"{folder}/rpl-udp/rpl-udp-sky.csc"

    # Defining cooja mote types and firmware
    server = SkyMoteType(f"{folder}/rpl-udp/udp-server.c")
    client = SkyMoteType(f"{folder}/rpl-udp/udp-client.c")

    # Use topology found in .csc file, mote types are not preserved
    topology = Topology.from_csc(csc_filepath)

    # Set mote types
    topology.set_mote_type(1,server)
    topology.set_mote_type([2,3,4,5,6,7,8], client)

    # Create a simulation with default RX/TX success ratio, seed and timeout values
    simulation = CoojaSimulation(topology, timeout=120)

    # Just for information, it is possible to compile a firmware
    # Compile Server firmware, if it does not exist
    server.compile_firmware()

    logger.setLevel(logging.DEBUG)

    # Compile (and override) Client firmware
    client.compile_firmware(clean=True)

    # Run the simulation and store the log in specific file
    simulation.run(log_file="output.log")

def simulation_example4():
    # Defining cooja mote types and firmware
    server = SkyMoteType(f"{folder}/rpl-udp/udp-server.c")
    client = SkyMoteType(f"{folder}/rpl-udp/udp-client.c")

    # Create a random topology
    n = 10
    width=200
    height=200

    motes=[]
    current_mote_id=1
    for i in range(n):
        x = random.random()*width-width/2
        y = random.random()*height-height/2

        if current_mote_id == 1:
            mote_type = server
        else:
            mote_type = client

        new_mote = SkyMote(current_mote_id,x,y, mote_type)
        motes.append(new_mote)
        current_mote_id += 1

    medium = radio.UDGM(transmitting_range=50, interference_range=70)
    topology = Topology(motes, radiomedium=medium)

    # Create a simulation
    simulation = CoojaSimulation(topology, seed=15468, timeout=100)

    # Run the simulation
    simulation.run(with_gui=True)

def simulation_example5():
    """
    Export simulation.
    """
    csc_filepath=f"{folder}/rpl-udp/rpl-udp-sky.csc"

    # Create a simulation object from an existing .csc file.
    simulation = CoojaSimulation.from_csc(csc_filepath)

    # Run simulation in Cooja with GUI.
    simulation.export()

def simulation_example6():
    # Defining/overriding project configuration in 'project-conf.h'
    project_conf = ProjectConf(RPL_CONF_MAX_INSTANCES=1,
                                NBR_TABLE_CONF_MAX_NEIGHBORS=8,
                                IEEE802154_CONF_PANID=0x42,
                                LOG_CONF_LEVEL_IPV6="LOG_LEVEL_DBG")

    makefile_variables = {"MAKE_ROUTING":"MAKE_ROUTING_RPL_LITE",
                          "MAKE_MAC":"MAKE_MAC_CSMA"}

    # Firmwares
    server = Z1MoteType(f"{folder}/rpl-udp/udp-server.c",
                           project_conf=project_conf,
                           makefile_variables=makefile_variables)
    client = Z1MoteType(f"{folder}/rpl-udp/udp-client.c",
                           project_conf=project_conf,
                           makefile_variables=makefile_variables)

    # Use a predefined topology that creates 1 server mote and 24 client motes
    topology = Topology.get_tree25_topology(Z1Mote, server, client)

    # Create a simulation with default RX/TX success ratio, seed and timeout values
    simulation = CoojaSimulation(topology, timeout=30)

    # Run the simulation and store the log and radio data in specific files
    simulation.run(with_gui=True)

def simulation_example7():
    # Defining/overriding project configuration in 'project-conf.h'
    project_conf = ProjectConf(RPL_CONF_MAX_INSTANCES=1,
                                NBR_TABLE_CONF_MAX_NEIGHBORS=8,
                                IEEE802154_CONF_PANID=0x42,
                                LOG_CONF_LEVEL_RPL="LOG_LEVEL_DBG")

    # Firmwares
    server = CoojaMoteType(f"{folder}/rpl-udp/udp-server.c",
                           project_conf=project_conf)
    client = CoojaMoteType(f"{folder}/rpl-udp/udp-client.c",
                           project_conf=project_conf)

    topology = Topology.get_tree25_topology(CoojaMote, server, client)
    simulation = CoojaSimulation(topology, timeout=100)

    simulation.run()

    log = Log(simulation.get_log_filepath())
    messages = log.get_messages()

    send_requests = log.get_messages(contain="Sending request")
    received_requests = log.get_messages(contain="Received request")
    send_responses = log.get_messages(contain="Sending response")
    received_responses = log.get_messages(contain="Received response")

    print(f"requests sent: {len(send_requests)}")
    print(f"requests received: {len(received_requests)}")
    print(f"responses sent: {len(send_responses)}")
    print(f"responses received: {len(received_responses)}")

    print("")

    app_log = log.get_messages(log_module="App", node_id=4)
    for message in app_log[:5]:
        Log.print_message(message)

    print("")

    errors_log = log.get_messages(log_level=Log.LEVEL_ERR, node_id=5)
    for message in errors_log:
        Log.print_message(message)

def simulation_example8():
    """
    Run simulations on multiple threads
    """
    filepath=folder+"/rpl-udp/rpl-udp-cooja.csc"

    logger.setLevel(logging.ERROR)

    # Thread dispatcher
    simulation_worker = CoojaSimulationWorker(4)

    rx_list = [0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0]
    for rx in rx_list:
        # Create a simulation object from an existing .csc file.
        simulation = CoojaSimulation.from_csc(filepath)
        simulation.topology.radiomedium.success_ratio_rx = rx
        simulation.timeout = 100
        simulation.title = f"Simulation RX={rx}"

        # arguments that would normally be passed to simulation.run()
        args={'pcap_file':'simulation_'+str(rx)+".pcap", 'log_file':'simulation_'+str(rx)+".log"}

        # Add simulation to worker that dispatchs to a thread
        simulation_worker.add_simulation(simulation, run_args=args)

    # Run simulations on multiple threads
    simulation_worker.run()

def simulation_example9():
    """
    Setting startup delay for each mote
    """
    filepath=folder+"/rpl-udp/rpl-udp.csc"

    # Create a simulation object from an existing .csc file.
    simulation = CoojaSimulation.from_csc(filepath)

    for mote in simulation.topology:
        # Generate random delay between 5000 and 10000 milliseconds
        delay = 5000 + random.random()*(10000-5000)
        mote.startup_delay = delay

    # Run the simulation and store the log and radio data in files
    simulation.run(with_gui=True)

if __name__ == "__main__":
    simulation_example7()


import inspect
import weakref
from functools import partial
from typing import Callable, Generic, TypeVar

from ._key import bundle_key
from ..exceptions import RequirementNotFound, AmbiguousDependency
from ..extras import clsname
from ..extras.generics import is_generic_type, get_origin, resolve_type
from ..extras.logging import logger
from ..extras.undef import Undefined, default

class _RebindContext(object):
    def __init__(self, bundle):
        self._bundle = bundle

    @property
    def parent(self):
        return Undefined

    def __getattr__(self, item):
        return object.__getattribute__(self, "_bundle").__getattribute__(item)

class BindMeta(type):

    def __getitem__(cls, item) -> 'Binding':
        c_local = cls.caller_local()
        bundle = c_local.get(bundle_key, Undefined)
        if bundle is Undefined:
            from compose import FactoryBundle
            c_local[bundle_key] = FactoryBundle()
            bundle = c_local[bundle_key]
        binding = None
        if cls == ReBind:
            binding = list(bundle.find(item, _RebindContext(bundle)))
            if len(binding):
                binding = binding[0]
            else:
                binding = None
                logger.warning("Rebind could not find previous binding. Binding instead")

        if binding is None:
            binding = Binding(item)
            bundle.visit(binding)

        return binding

    def caller_local(cls):
        stack = inspect.stack()
        for frame_info in stack:
            if frame_info.frame.f_locals.get("cls", None) != cls:
                return frame_info.frame.f_locals
        return {}

class Bind(object, metaclass=BindMeta):
    """Binding creates a whole new binding This is generally what should be used  we setting up a configuration
    with Compose

    """
    pass

class ReBind(object, metaclass=BindMeta):
    """Rebind will attempt to find previously configured bindings and update the factory.

     This can be useful in scenarios where a higher level framework wants to configure scopingbut allow
     the lower level application to define the binding itself. It can also be used to allow for a default binding
     to be overridden later but the more acceptable way to do that is to have mmultiple bundles since bundles cascade
     only when a bundle does not provide and instance.

    """
    pass

T = TypeVar("T", bound=type)

class Binding(Generic[T]):

    def __init__(self, bind: T):
        self.is_singleton = False
        self._as_singleton = False
        self._config_for = bind
        self._factory = None
        self._additional_check = lambda *a: True
        self.provide_type = None

    def to_multiple(self, *factories):
        for factory in factories:
            self._bundle.add_binding(Binding(self._config_for).to(factory))
        self._bundle.remove_binding(self)
        self._bundle = None
        return None

    def to(self, factory: Callable):
        if isinstance(factory, list):
            raise ValueError("Each factory binding must be its own binding, use to_multiple for an easier syntax")
        if not callable(factory) and not isinstance(factory, str):
            raise RuntimeError("NOT CALLABLE!!!")
        self._factory = factory
        if isinstance(factory, (type, str)):
            self.provide_type = factory
        else:
            self.provide_type = inspect.signature(factory).return_annotation
        if self.provide_type is inspect.Signature.empty:
            self.provide_type = Undefined
            msg = f"Provided factory does not specify a return type in the annotation, some providers rely on this" \
                  f" to detirmine if they provide a class or not. "
            logger.warning(msg)
        return self

    def on_target(self, target):
        def check(kls, context: 'InstantiationContext'):
            for node in list(context.instantiation_chain()):
                if node.provider.provide_type == target:
                    return True
            return False

        return check

    def on(self, predicate) -> 'Binding':
        self._additional_check = predicate
        if isinstance(predicate, type):
            self._additional_check = self.on_target(predicate)
        return self

    def to_self(self) -> 'Binding':
        return self.to(self._config_for)

    def as_singleton(self):
        self._as_singleton = True
        return self

    def accept(self, bundle: 'ComposeBundle'):
        self._bundle = weakref.proxy(bundle)
        bundle.add_binding(self)

    def with_args(self, *args, **kwargs):
        self._factory = partial(self._factory, *args, **kwargs)
        return self

    @property
    def factory(self):
        if isinstance(self._factory, str):
            for sub in self._config_for.__subclasses__():
                if clsname(sub, full=True) == self._factory:
                    return sub
            raise RequirementNotFound(f"No Subclass discovered by name {self._factory}", self._factory, Undefined)
        else:
            return self._factory

    def provides(self, kls, templates=None, context=Undefined):
        provides = False
        if is_generic_type(kls) and get_origin(kls) is type:
            if self._config_for == kls:
                provides = True
        if not provides:
            try:
                if isinstance(kls, type) and issubclass(kls, self._config_for):
                    if not templates or all(issubclass(ot, resolve_type(self._config_for, t)) for t, ot in templates):
                        provides = True
            except TypeError as ex:
                if isinstance(kls, TypeVar):
                    msg = f"A generic type was found and can not be resolved. This usually happens when a property on " \
                          f"a dataclass is typed with a generic class without specifying the types of the generics. For " \
                          f"example my_prop:Mapping = field(default=None). Compose can not resolve Mapping, mapping of what?"
                    raise AmbiguousDependency(msg, context)
                raise ex
        if provides:
            if isinstance(self.provide_type, str):
                self.provide_type = self.factory
            return self._additional_check(kls, default(context.parent, context))
        return False

    @property
    def bound_to(self):
        return self._config_for


#Merge sort
# 나누는 경우 N -> 1  O(N)
# 병합하는 경우 1 -> N  O(NK) = O(NlogN)
# 공간 복잡도 = O(N)
# Stable Sort = 같은 값이라 하여도 순서를 보장

# 코딩 테스트에서 정렬 필수 사용

arr = [ 3 , 2 , 116 ,7 , 62 , 235 , 1 , 23 , 55 , 77]
n = len(arr)
temp_arr = [0] * n

def merge( start , end ) :
    mid = ( start + end ) // 2
    left_idx = start
    right_idx = mid

    for i in range( start , end ) :
        if right_idx == end :
            temp_arr[i] = arr[left_idx]
            left_idx += 1
        elif left_idx == mid or arr[left_idx] > arr[right_idx]:
            temp_arr[i] = arr[right_idx]
            right_idx += 1
        else:
            temp_arr[i] = arr[left_idx]
            left_idx += 1

    arr[start:end] = temp_arr[start:end]

def merge_sort ( start , end ) :
    # 재귀 end조건
    if end == start + 1 :
        return
    mid = ( start + end ) // 2
    merge_sort( start , mid )
    merge_sort( mid , end )
    merge(start,end)

merge_sort( 0 , 3 )
print ( arr )


import discord
import botconfig
from discord.ext import commands

class Invitation(commands.Cog):
  def __init__(self, bot):
    self.bot = bot

  @commands.command(name='invite')
  async def hello(self, ctx, member: discord.Member = None):
    """Send the invitation's link in a DM"""
    member = member or ctx.author
    try:
      await member.send (botconfig.config['invite_bot'])
    except:
      await ctx.send ('Oups je ne peux pas envoyer de DM !')

  @commands.Cog.listener('on_message')
  async def invitation(self, message):
    """ Send the invitation's link in a DM
        if the word 'invitation' is found
    """
    if "invitation" in message.content.lower():
      member = message.author
      try:
        await member.send (botconfig.config['invite_bot'])
      except:
        await message.channel.send ('Oups je ne peux pas envoyer de DM !')


"""
dynamics_tests.py
Description:
    Tests all of the functions related to the pusher slider's dynamics.
"""

import sys, unittest

import jax.numpy as jnp

sys.path.append('../../../')
from src.python.pusher_slider import PusherSliderSystem

class PusherSliderTest2(unittest.TestCase):
    """
    test_get_motion_cone1
    Description:
        Tests that the motion cone computation works as I expect it to.
    """
    def test_get_motion_cone1(self):

        # Constants
        ps = PusherSliderSystem()
        ps.st_cof = 1.0
        ps.s_width = 1.0 # => c = 2
        ps.p_x = 3.0
        ps.p_y = 5.0

        # Algorithm
        gamma_t_expected = (4.0-15.0+1.0*jnp.power(3,2))/(4.0+jnp.power(5.,2)-1*3*5)
        gamma_b_expected = (-4.0-15.0-1*jnp.power(3,2))/(4.0+jnp.power(5.0,2)+1*3*5)

        gt_2, gb_2 = ps.get_motion_cone_vectors()

        self.assertEqual(gamma_t_expected,gt_2)
        self.assertEqual(gamma_b_expected,gb_2)

    """
    test_identify_mode1
    Description:
        Testing the identification of modes from a good input and
        the motion cone computation.
        The input u should be leading to STICKING.
    """
    def test_identify_mode1(self):

        # Constants
        ps = PusherSliderSystem()
        ps.st_cof = 1.0
        ps.s_width = 0.4 # => c = 5
        ps.p_x = 2.0
        ps.p_y = 2.0

        # Algorithm
        mode_out1 = ps.identify_mode(jnp.array([[2.0],[0.5]]))

        self.assertEqual(mode_out1,'Sticking')

    """
    test_identify_mode2
    Description:
        Testing the identification of modes from a good input and
        the motion cone computation.
        The input u should be leading to SLIDING UP.
    """
    def test_identify_mode2(self):

        # Constants
        ps = PusherSliderSystem()
        ps.st_cof = 1.0
        ps.s_width = 0.4 # => c = 5
        ps.p_x = 2.0
        ps.p_y = 2.0

        # Algorithm
        mode_out1 = ps.identify_mode(jnp.array([[2.0],[3.0]]))

        self.assertEqual(mode_out1,'SlidingUp')

    """
    test_identify_mode3
    Description:
        Making sure that this sketch of a plotting algorithm works.
    """
    def test_identify_mode3(self):

        # Constants
        ps = PusherSliderSystem()
        ps.st_cof = 1.0
        ps.s_width = 0.4 # => c = 5
        ps.p_x = 2.0
        ps.p_y = 2.0

        # Algorithm
        mode_out1 = ps.identify_mode(jnp.array([[2.0],[-2.5]]))

        self.assertEqual(mode_out1,'SlidingDown')

    """
    test_C1
    Description:
        Tests that the C matrix is constructed correctly.
    """
    def test_C1(self):
        # constants
        ps = PusherSliderSystem()
        ps.s_theta = jnp.pi/6

        # Algorithm
        C = ps.C()

        self.assertEqual(C[0][0],jnp.cos(jnp.pi/6))
        self.assertEqual(C[0][1],jnp.sin(jnp.pi/6))
        self.assertEqual(C[1][0],-jnp.sin(jnp.pi/6))
        self.assertEqual(C[1][1],jnp.cos(jnp.pi/6))

    """
    test_Q1
    Description:
        Tests that the Q matrix is constructed correctly.
    """
    def test_Q1(self):
        # constants
        ps = PusherSliderSystem()
        ps.ps_cof = 1
        ps.s_width = 0.4 # c = 5
        ps.p_x = 2.0
        ps.p_y = 2.0

        # Algorithm
        Q = ps.Q()

        self.assertEqual(Q[0][0],(1/(25.0+8))*(25+4))
        self.assertEqual(Q[0][1],(1/(25.0+8))*(4))
        self.assertEqual(Q[1][0],(1/(25.0+8))*(4))
        self.assertEqual(Q[1][1],(1/(25.0+8))*(25+4))

    """
    test_f1
    Description:
    	Tests the f() function so that we know that the state of the pusher slider is not modified
		after evaluating f at a given point.
    """
    def test_f1(self):
        # Constants
        ps = PusherSliderSystem()

        x0 = ps.x()
        u_prime = jnp.array([[1.0], [3.0]])
        x1 = x0 + jnp.array([[0.1], [0.0], [0.0], [0.0]])

        x_dot = ps.f(x1,u_prime)
        x_dot2 = ps.f2(x1,u_prime) # This u should call

        x_dim = x_dot.shape[1]
        for x_dim_index in range(x_dim):
            # Constraints
            self.assertEqual(x_dot[0,x_dim_index],x_dot[0,x_dim_index])

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


# import random

class QuickSort(object):

	def __init__(self):
		self.set_input(list())

	def get_user_input(self):
		input_array = [int(number) for number in input().split()]
		self.set_input(input_array)

	def set_input(self, input_array):
		self.input_array = input_array
		self.input_size = len(input_array)

	def quick_sort(self):
		self.quick_sort_helper(0, self.input_size-1)
		return self.input_array

	def quick_sort_helper(self, begin, end):
		if begin < end:
			pi = self.partition(begin, end)
			self.quick_sort_helper(begin, pi-1)
			self.quick_sort_helper(pi+1, end)

	def partition(self, begin, end):
		# import pdb; pdb.set_trace()
		pivot = self.input_array[end]
		counter1 = begin-1
		for counter2 in range(begin, end):
			if (self.input_array[counter2] <= pivot):
				counter1 += 1
				self.swap(counter1, counter2)
		self.swap(counter1+1, end)
		return counter1+1

	def swap(self, position1, position2):
		if position1 != position2:
			self.input_array[position1] += self.input_array[position2]
			self.input_array[position2] = self.input_array[position1] - self.input_array[position2]
			self.input_array[position1] -= self.input_array[position2]

	def print_output(self):
		output_array = self.quick_sort()
		for output in output_array:
			print (output, end=' ')
		print ('')

quick_sort = QuickSort()

quick_sort.set_input([1, 2, 3, 4])
quick_sort.print_output()

quick_sort.set_input([2, 1])
quick_sort.print_output()

quick_sort.set_input([40, 30])
quick_sort.print_output()

quick_sort.set_input([3, 2, 1])
quick_sort.print_output()

quick_sort.set_input([4, 3, 2, 1])
quick_sort.print_output()

quick_sort.set_input([1])
quick_sort.print_output()

quick_sort.set_input([])
quick_sort.print_output()

quick_sort.set_input([10, 10, 4, 10, 9, 1, 2, 5, 6, 100, -100, 10])
quick_sort.print_output()