import json
import time
from uuid import uuid4

import redis
import settings

# Connecting to Redis
db = redis.Redis(
    host=settings.REDIS_IP,
    port=settings.REDIS_PORT,
    db=settings.REDIS_DB_ID
)

def model_predict(query_dict):

    prediction = None

    #Generating unique id for the job
    job_id = str(uuid4())
    #Generating the job
    job_data = dict({
        "id": job_id,
        "query_dict":query_dict
    })

    # Send the job to the model service using Redis
    db.lpush(
    settings.REDIS_QUEUE,
    json.dumps(job_data)
    )

    # Loop until we received the response from our ML model
    while True:
        print("esperando", job_id)
        output = db.get(job_id)
        if output:
            output = json.loads(output.decode("utf-8"))

        #Deleting the job from Redis after we get the results!
            db.delete(job_id)
            break
        # Sleep some time waiting for model results
        time.sleep(settings.API_SLEEP)
    prediction = output["prediction"]
    score = output["score"]

    return prediction, score


def examenGYV():
  #Definir variable y otros
  print("Consulte su nota del curso de fundamentos de programacion segun la ponderacion")
  notafinalGYV=0
  #Datos de entrada
  unidad1GYV=int(input("Ingresa tu nota de la primera unidad: "))
  unidad2GYV=int(input("Ingresa tu nota de la segunda unidad: "))
  unidad3GYV=int(input("Ingresa tu nota de la tercera unidad: "))
  trabajofGYV=int(input("Ingresa tu nota de la cuarta unidad: "))
  #Proseso
  if unidad1GYV>=0 and unidad1GYV<=20:
    nota1GYV=unidad1GYV*20/100
  if unidad2GYV>=0 and unidad2GYV<=20:
    nota2GYV=unidad2GYV*15/100
  if unidad3GYV>=0 and unidad3GYV<=20:
    nota3MLOA=unidad3MLOA*15/100
  if trabajofGYV>=0 and trabajofGYV<=20:
    nota4GYV=trabajofGYV*50/100
  notafinalGYV=nota1MLOA+nota2MLOA+nota3GYV+nota4GYV
  #datos de salida
  print("Su nota final es:",notafinalGYV)
examenGYV()


# 문제 20. 각 자릿수의 합 구하기
# 정수 number가 주어질 때, 각 자릿수의 합을 구해서 출력하세요.
n= 123
x=str(n)
sum1=0
sum2=0
for i in x:
  sum1+=int(i)
print(sum1)

def solution(n):
    answer=0
    while n>0 :
        answer+=n%10
        n//=10
    return answer

print(solution(n))
# 문제 21. 숫자 뒤집기
# 주어진 숫자를 뒤집은 결과를 출력하시오.
# * 문자열이 아닌 숫자로 활용해서 풀어주세요. str() 사용 금지
Number=1234
Reverse = 0

while(Number > 0):
    Reminder = Number %10
    Reverse = (Reverse *10) + Reminder
    Number = Number //10

print(Reverse)


import numpy as np
import matplotlib.pyplot as plt

##### 	Fonction permettant d'afficher un jeu de donnee ####
#
#
def plotData(X,y):
	plt.scatter(X, y, c="g", alpha=0.8, marker='o')
	plt.ylabel("y")
	plt.xlabel("x")

	plt.show(block=False)

def plotData2D(X,y):
	plt.scatter(X[:,0],X[:,1], c=y, alpha=0.8, marker='o')
	plt.ylabel("x_0")
	plt.xlabel("x_1")
	plt.axis([-15, 15, -15, 15])

	plt.show(block=False)


class StackNode:
	def __init__(self, value, next):
		self.value = value
		self.next = next

class Stack:
	def __init__(self):
		self.head = None

	def pop(self):
		if self.head is None:
			print("Empty stack")
			return
		value = self.head.value
		self.head = self.head.next
		return value

	def push(self, value):
		self.head = StackNode(value, self.head)

	def peek(self):
		if self.head is None:
			print("Empty stack")
			return
		return self.head.value

	def isEmpty(self):
		return self.head is None

stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.peek())
print(stack.pop())
print(stack.pop())
print(stack.pop())
print(stack.pop())

Python/Chapter 03 - Stacks and Queues/stack.py


def sort_by_cloudcover(search_result):
    entries = search_result["feed"]["entry"]
    sorted_entries = []
    for entry in entries:
        sorted_entries.append(
            [
                float(e["content"])
                for e in entry["double"]
                if e["name"] == "cloudcoverpercentage"
            ][0]
        )
    return sorted(sorted_entries, key=float)


# احمدرضا ذبیحی                       به نام خدا                 ش.د: ۴۰۰۵۲۱۳۴۲

import random

def barabri(student_answer, answer):
    luck = random.randint(1, 3)
    while answer != student_answer:
        if luck == 1:
            student_answer = int(input('No. Keep trying.'))
        elif luck == 2:
            student_answer = int(input('Wrong. Try once more.'))
        else:
            student_answer = int(input("No. Please try again. "))
        luck = random.randint(1, 3)
    if luck == 1:
        print('Nice work!')
    elif luck == 2:
        print('Keep up the good work!')
    else:
        print("very good!")

def sum(number_one, number_two):
    answer = number_one + number_two
    student_answer = int(input("how much is {}+{}? (for select type of problems enter -90): ".format(number_one, number_two)))
    if student_answer == -90:
        return "go out"
    barabri(student_answer, answer)

def Submission(number_one, number_two):
    answer = number_one - number_two
    student_answer = int(input("how much is {}-{}? (for select type of problems enter -90): ".format(number_one, number_two)))
    if student_answer == -90:
        return "go out"
    barabri(student_answer, answer)

def Multiplication(number_one, number_two):
    answer = number_one * number_two
    student_answer = int(input("how much is {}*{}? (for select type of problems enter -90): ".format(number_one, number_two)))
    if student_answer == -90:
        return "go out"
    barabri(student_answer, answer)

def Division(number_one, number_two):
    if number_two == 0:
        number_two = random.randint(1, 9)
    answer = ((float(number_one / number_two))//0.01)/100
    student_answer = ((float(input("how much is {}/{}? (If the answer was a floating number, calculate it to 2 decimal places.)(for select type of problems enter -90): ".format(number_one, number_two))))//0.01)/100
    if student_answer == -90:
        return "go out"
    barabri(student_answer, answer)

while True:
    level = int(input("enter a difficulty level (1 or 2)\n(1:Questions of one-digit numbers , 2:Questions of two-digit numbers)(for exit enter -1): "))
    if level == -1:
        break
    elif level == 1:
        start = 0
        end = 9
    else:
        start = 10
        end = 99
    while True:
        challenge_type = int(input("Choose an arithmetic problem(1,2,3,4 or 5)\n(1:addition problems only , 2:subtraction problems only , 3:multiplication problems only , 4: division problems only , 5:random mixture of all these types.)\n(for select level enter -1): "))
        if challenge_type == -1:
            break
        while True:
            number_one = random.randint(start, end)
            number_two = random.randint(start, end)
            if challenge_type == 1:
                run = sum(number_one, number_two)
                if run == "go out":
                    break
            elif challenge_type == 2:
                run = Submission(number_one, number_two)
                if run == "go out":
                    break
            elif challenge_type == 3:
                run = Multiplication(number_one, number_two)
                if run == "go out":
                    break
            elif challenge_type == 4:
                run = Division(number_one, number_two)
                if run == "go out":
                    break
            else:
                functions = [sum, Submission, Division, Multiplication]
                x = random.choice(functions)(number_one, number_two)
                if x == "go out":
                    break


from fastapi import APIRouter
from .schemas import RequestRegisterCashboxCharacter, ResponseRegisterCashboxCharacter, \
    ResponseGetSystemID
from .doc_kwargs import doc_register_character, doc_get_sys_id
from .functions import register_cashbox_character, get_sys_id

router = APIRouter()

@router.post('/register_character', **doc_register_character)
async def register_character(character: RequestRegisterCashboxCharacter):
    kwargs = {'valid_schema_data': character.dict()}
    data = await register_cashbox_character(**kwargs)
    return ResponseRegisterCashboxCharacter(**data)

# @router.post('/register_fiscal_cashier', **doc_register_fiscal_cashier)
# async def register_cashier(cashier_data: RequestRegisterFiscalCashier):
#     kwargs = {'valid_schema_data': cashier_data.dict()}
#     data = await register_fiscal_cashier(**kwargs)
#     return ResponseRegisterFiscalCashier(**data)
#

@router.get('/get_system_id', **doc_get_sys_id)
async def get_system_id():
    data = await get_sys_id()
    return ResponseGetSystemID(**data)


class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        dummy = ListNode(0, head)
        l = dummy
        r = head
        while n>0 and r:
            r = r.next
            n-=1
        while r:
            l = l.next
            r = r.next
        l.next = l.next.next
        return dummy.next


# Exo 1:
def fusion(tab1: list, tab2: list) -> list:
    r = []
    while tab1 != [] or tab2 != []:
        if tab1 == []:
            r.append(tab2.pop(0))
        elif tab2 == []:
            r.append(tab1.pop(0))
        else:
            if tab1[0] > tab2[0]:
                r.append(tab2.pop(0))
            else:
                r.append(tab1.pop(0))
    return r

assert fusion([3, 5], [2, 5]) == [2, 3, 5, 5]
assert fusion([-2, 4], [-3, 5, 10]) == [-3, -2, 4, 5, 10]
assert fusion([4], [2, 6]) == [2, 4, 6]

# Exo 2:
romains = {"I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000}

def traduire_romain(nombre):
    """ Renvoie l’écriture décimale du nombre donné en chiffres
    romains """
    if len(nombre) == 1:
        return romains[nombre]
    elif romains[nombre[0]] >= romains[nombre[1]]:
        return romains[nombre[0]] + traduire_romain(nombre[1:])
    else:
        return -romains[nombre[0]] + traduire_romain(nombre[1:])

assert traduire_romain("XIV") == 14
assert traduire_romain("CXLII") == 142
assert traduire_romain("MMXXIII") == 2023


import random

class Game:
    def __init__(self, num_matches):
        self.num_matches = num_matches
        self.matches = num_matches
        self.drink_chance = 0.3

    def reset_game(self):
        self.matches = self.num_matches

    def print_game(self):
        print("Number of matches:", self.matches)
        print("| " * self.matches,"\n")

    def verify_move(self, number):
        if len(number) != 1:
            return False
        if not number.isdigit():
            return False
        else:
            number = int(number)

        if number < 1 or number > 3:
            return False
        if number > self.matches:
            return False

        return True

    def take_matches(self):
        number = input("Take 1-3 matches:")

        if not self.verify_move(number):
            print("Invalid move!")
            return self.take_matches()
        else:
            number = int(number)
            self.matches -= number

    def computer_turn(self):
        number = (self.matches - 1) % 4
        if number == 0:
            number = random.randint(1, 3)

        self.matches -= number
        print("Computer took", number, "matches")

    def drink(self):
        if random.random() < self.drink_chance:
            print("DRINK!")
            input("Press any key to continue")

        self.drink_chance += 0.05

def main():
    game = Game(15)
    won = False
    while True:
        game.reset_game()
        while True:
            game.print_game()
            game.take_matches()

            if game.matches == 1:
                game.print_game()
                print("You won!")
                won = True
                break

            if game.matches == 0:
                print("You lost!")
                game.drink()
                break

            game.print_game()
            game.computer_turn()

        if won:
            break

if __name__ == '__main__':
    main()


def mySqrt(x: int) -> int:
    if x==0 or x==1:
        return 0
    L,R=1,x//2
    while L<=R:
        mid=(L+R)//2
        if mid==x//mid:
            return mid
        elif mid<x//mid:
            L=mid+1
        else:
            R=mid-1
    return R

x=int(input())
print(mySqrt(x))


#Biblioteca time
#Trabalhando com tempo, no caso ele utiliza o for para contar até 5, começando do 0 até o 4, em um time de 1 segundo
#Basicamente ele conta 0 até 4 esperando 1 segundo
import time

for i in range(5):
    print(i)

    time.sleep(1)

#Biblioteca tkinter
#Fazendo um botão básico que ao clicar ele fecha a tela, nome do botão é OK
from tkinter import *
box = Button(text="Ok", command='exit')
box.pack()
box.mainloop()


import argparse
import getpass
import logging
import socket
import sys
from datetime import datetime

from simplekit import email

from recipe.utils import OptionParser
from recipe.utils import config_logging

EMAIL_API = 'http://10.16.75.24:3000/framework/v1/mail'

class Command(object):
    """this is the base class for all commands

    """
    name = None
    SNAP = {}
    parser = argparse.ArgumentParser(description='recipe')

    def __init__(self, options):
        self.options = options
        config_logging(options)
        self.config = OptionParser()
        email.settings.URL_EMAIL = self.config.get('email', 'api', EMAIL_API)
        self.logger = logging.getLogger('recipe')

    @staticmethod
    def register(cmd_class=None):
        """register the command

        :param cmd_class: `class`:`str`
        :return:
        """
        if cmd_class is None:
            parser = Command.parser = argparse.ArgumentParser(description='recipe')
            parser.add_argument('--verbose', '-v', action='count', default=2,
                                help='Give more output, Options is additive, and can be used up to 3 times.')
            parser.add_argument('--log', dest='log', default=None, help='Path to a verbose appending log')
            Command.sub_parser = parser.add_subparsers(help='Available commands', dest='command')
        else:
            if cmd_class.name not in Command.SNAP:
                cmd_class.register(Command.sub_parser)
                Command.SNAP[cmd_class.name] = cmd_class

    @staticmethod
    def parse(args=None):
        if args is None:
            args = sys.argv[1:]
        parser = Command.parser
        options = parser.parse_args(args)
        cmd = options.command
        if cmd in Command.SNAP:
            return Command.SNAP[cmd](options)

    def run(self):
        """ run this command

        :return:
        """
        raise NotImplementedError

    def execute(self):
        try:
            self.run()
        except Exception as e:
            self.logger.exception(e)
            # send email
            sender = 'Recipe@newegg.com'
            receiver = self.config.get('email', 'receiver', 'benjamin.c.yan@newegg.com')
            cc = self.config.get('email', 'cc')
            subject = "(Info) Recipe Error"
            body = "Hi, \n Recipe occur unknown error with login {0} on {1} at {2}".format(getpass.getuser(),
                                                                                socket.gethostname(),
                                                                                datetime.now().strftime(
                                                                                '%a %b %d %H:%M:%S %Y'))
            email.send_email(sender, receiver, subject, body, cc=cc, files=[self.options.log])
            sys.exit(3)


# -*- coding: utf-8 -*-
"""
Created on Thu Feb 25 17:27:00 2021

@author: prano
"""

class Node:

    def __init__(self,value):
        self.value = value
        self.next = None

class Queue:

    def __init__(self):
        self.first = None
        self.last = None
        self.length = 0

    def enqueue(self, value):
        if self.length == 0:
            self.first=Node(value)
            self.last=self.first
            self.length+=1
            return
        newLast = Node(value)
        self.last.next = newLast
        self.last = newLast
        self.length+=1

    def dequeue(self):
       if not self.first:
           return None
       if self.first==self.last:
           self.last=None
       poppedNode = self.first
       self.first = self.first.next
       self.length-=1
       return poppedNode.value

    def peek(self):
        if self.length==0:return None
        return self.first.value

    def isEmpty(self):
        if not self.first: return None
        return self.first.value

    def printQueue(self):
        currentNode = self.first
        while currentNode!=None:
            print(currentNode.value,'-->', end="")
            currentNode = currentNode.next
        print()

myQueue = Queue()

myQueue.enqueue(6)
myQueue.enqueue(7)
myQueue.enqueue(9)
myQueue.enqueue(12)
print(myQueue.dequeue())
myQueue.printQueue()


# 1. write a program to read file sample.json. Display all distance and name of locations.
import json

print('================================================ 1 =======================================')
def display_json(filename):
    with open(filename,'r') as outfile:
        obj=json.load(outfile)

    v1 = obj['student']
    for v2 in v1:
        print('Distance: ',v2['distance'])
        print('Name: ',v2['name'])
        print('\n')
display_json('students.json')

# 2. write a program
print('================================================ 2 =======================================')
# Define a python object (dictionary) containing fields: date,location,gps(lat,lon), wether, population.

sampleDict =[
    {
        'date': '2012',
        'location': 'ha noi',
        'gps': {
            'lat': 1222,
            'long':93939
        },
        'wether':29,
        'population':1234
    },
    {
        'date': '2012',
        'location': 'hai phong',
        'gps':  {
            'lat': 1222,
            'long':93939
        },
        'wether':24,
        'population':123477
    }
]

# store a python object (dictionary) into a json file name sample_w.json
def into_json(new_data):
    json_object = json.dumps(new_data, indent=4)
    with open("sample_w.json", "w") as outfile:
        outfile.write(json_object)
        print("into successful")
# into_json(sampleDict)

# 3. Write a program to to create a new json file from an existing json file (sample_w.json)
print('================================================ 3 =======================================')
def copy_file(filename):
    with open(filename) as outfile:
        data = json.load(outfile)

    with open('new_file.json', 'w') as outfile:
        json.dump(data, outfile, indent=4)
        print("New json file is created from sample_w.json file")
# copy_file('sample_w.json')

# 4. Write a program to add new user into existing json file (users.json). User information will be input from keyboard.

users=[
    {
        'name': 'John',
        'email': 'john@example.com',
        'age': 18,
        'address': 'John Street'
    },
    {
        'name': 'Su',
        'email': 'su@example.com',
        'age': 18,
        'address': 'Su Street'
    }
]
def add_user_from_keyboard(filename):

    user_list = []
    check='y'
    while check == 'y':
        user=dict()
        print("Enter user infor:")
        user['name']=input('Enter Name: ')
        user['email']=input('Enter Email: ')
        user['age']=int(input('Enter Age: '))
        user['address']=input('Enter Address: ')
        check = input("Do you want to continue(y/n): ")
        user_list.append(user)
    with open(filename,'w') as outfile:
        json.dump(user_list, outfile, indent=4)

# add_user_from_keyboard('users.json')

# 5. Write a program to delete users which have age is a number entered from keyboard in users.json file.
print('================================================ 5 =======================================')
def del_user_from_keyboard(filename, age):
    with open(filename,'r') as outfile:
        obj=json.load(outfile)
        for v in obj:
            if v['age']==age:
                obj.remove(v)
    with open(filename,'w') as outfile:
        json.dump(obj,outfile)

# age=int(input("Enter age which you want to delete: "))
# del_user_from_keyboard('users.json',age)


# -*- coding: utf-8 -*-
# 创建时间：2019年7月30日
# 直方图均衡化测试

import cv2
import numpy as np
from matplotlib import pyplot as plt
from time import clock
import sys

'''
# 进行图像均衡化demo
img_1 = cv2.imread('../images/alphabets/A.jpg', 0)
print(img_1)
equ_1 = cv2.equalizeHist(img_1)
res = np.hstack((img_1,equ_1))
res = cv2.resize(res,(1280,640))
cv2.imshow('hist_test',res)
cv2.waitKey(0)
'''
'''
# 画2D直方图
img_1 = cv2.imread('../images/test_rectangle.jpg')
img_1 = cv2.resize(img_1, (1280, 720))
hsv_1 = cv2.cvtColor(img_1, cv2.COLOR_BGR2HSV)
hist_1 = cv2.calcHist([hsv_1], [0, 1], None, [180, 256], [0, 180, 0, 256])
cv2.imshow('rectangle', img_1)
plt.imshow(hist_1,interpolation = 'nearest')
plt.show()
cv2.waitKey(0)
'''
# 颜色直方图编码
if __name__ == '__main__':
    # 构建 HSV 颜色地图
    hsv_map = np.zeros((180, 256, 3), np.uint8)

    h, s = np.indices(hsv_map.shape[:2])
    hsv_map[:,:,0] = h
    hsv_map[:,:,1] = s
    hsv_map[:,:,2] = 255
    hsv_map = cv2.cvtColor(hsv_map, cv2.COLOR_HSV2BGR)
    cv2.imshow('hsv_map', hsv_map)
    cv2.namedWindow('hist', 0)

    hist_scale = 10
    def set_scale(val):
        global hist_scale
        hist_scale = val
    cv2.createTrackbar('scale', 'hist', hist_scale, 32, set_scale)
    # cap = cv2.VideoCapture('../video/test_rectangle_1.mp4')
    cap = cv2.VideoCapture(1)
    while True:
        flag, frame = cap.read()
        cv2.imshow('camera', frame)

        small = cv2.pyrDown(frame)
        hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
        # 去除孤立的点
        dark = hsv[:, :, 2] < 32
        hsv[dark] = 0
        h = cv2.calcHist( [hsv], [0, 1], None, [180, 256], [0, 180, 0, 256] )
        h = np.clip(h*0.005*hist_scale, 0, 1)

        # 从一维变成三维
        # 将得到的直方图和颜色直方图相乘
        vis = hsv_map*h[:, :, np.newaxis] / 255.0
        cv2.imshow('hist', vis)
        ch = 0xFF & cv2.waitKey(1)
        if ch == 27:
            break
cv2.destroyAllWindows()


import math
import numpy as numpy

inp=open('C-small-attempt1.in', 'r')
out=open("C-small-1.out", 'w')

T=int(inp.readline())
for index in range(T):
	J, P, S, K=[int(x) for x in (inp.readline()).split()]
	number=0;
	result="";
	Jred=J/K; Jres=J-K*Jred; Pred=P/K; Pres=P-K*Pred; Sred=S/K; Sres=S-K*Sred;
	if (Jres==0):
		Jred=Jred-1; Jres=K;
	if (Pres==0):
		Pred=Pred-1; Pres=K;
	if (Sres==0):
		Sred=Sred-1; Sres=K;
	if Sred-Pred>=1:
		number=J*P*K;
		if (Pres==K):
			modulo=P;
		else:
			modulo=(Pred+1)*K;
		for j in range(J):
			for p in range(P):
				for s in range(K):
					result=result+str(j+1)+" "+str(p+1)+" "+str((s+(j/K)*K+(p/K)*K)%(modulo) +1)+"\n"
	else:
		if(Jred==0):
			choice1=J*(Pred*K*K+Pres*Sres)
			choice2=J*((Pred-1)*K*K+Sres*Pres)
			if choice1>= choice2:
				number=J*(Pred*K*K+Pres*Sres)
				for j in range(J):
					for p in range(Pred*K):
						for s in range(K):
							result=result+str(j+1)+" "+str(p+1)+" "+str((s+(j/K)*K+(p/K)*K)%(Sres*K) +1)+"\n"
					for p in range(Pres):
						for s in range(Sres):
							result=result+str(j+1)+" "+str(p+Pred*K+1)+" "+str(s+Sred*K+1)+"\n"
			else:
				number=choice2;
				for j in range(J):
					for k in range(P):
						if (j/K)*K+(p/K)*K==Sred:
							for s in range(Sres):
								result=result+str(j+1)+" "+str(p+1)+" "+str((s+(j/K)*K+(p/K)*K)+1)+"\n"
						else:
							for s in range(K):
								result=result+str(j+1)+" "+str(p+1)+" "+str((s+(j/K)*K+(p/K)*K)%(Sred*K) +1)+"\n"
		else:
			if (Pred-Jred>=1):
				choice1=K*(Pred*K*K+Pres*Sres)+(J-K)*((Pred-1)*K*K+K*(Pres+Sres));
				choice2=K*(Pred*K*K+Pres*Sres) + (J-K)*(Pred*K*K);
				if choice2>= choice1:
					number=choice2;
					for j in range(J):
						for p in range(Pred*K):
							for s in range(K):
								result=result+str(j+1)+" "+str(p)+" "+str((s+(j/K)*K+(p/K)*K)%(Sres*K) +1)+"\n"
					for j in range(K):
						for p in range(Pres):
							for s in range(Sres):
								result=result+str(j+1)+" "+str(p+Pred*K+1)+" "+str(s+Sres*K+1)+"\n"
				else:
					number=choice1
					for j in range(J):
						for k in range(P):
							if (j/K)*K+(p/K)*K==Sred:
								for s in range(Sres):
									result=result+str(j+1)+" "+str(p+1)+" "+str((s+(j/K)*K+(p/K)*K)+1)+"\n"
							else:
								for s in range(K):
									result=result+str(j+1)+" "+str(p+1)+" "+str((s+(j/K)*K+(p/K)*K)%(Sred*K) +1)+"\n"
			else:
				number=K*(Pred*K*K+Pres*Sres)+(J-K)*((Pred-1)*K*K+K*(Pres+Sres));
				for j in range(J):
					for k in range(P):
						if (j/K)*K+(p/K)*K==Sred:
							for s in range(Sres):
								result=result+str(j+1)+" "+str(p+1)+" "+str((s+(j/K)*K+(p/K)*K)+1)+"\n"
						else:
							for s in range(K):
								result=result+str(j+1)+" "+str(p+1)+" "+str((s+(j/K)*K+(p/K)*K)%(Sred*K) +1)+"\n"

	out.write('Case #{}: {}\n'.format(index+1, number))
	out.write(result)

inp.close()
out.close()


import csv

with open('../data/oscar.csv', 'r', encoding='utf-8') as rOscar:
	oscarReader = csv.reader(rOscar)
	# oscar index 5 title
	Oscar = [movie for movie in oscarReader]

	with open('../data/tmdb_5000_movies.csv', 'r', encoding='utf-8') as rTMDB:
		TMDBReader = csv.reader(rTMDB)
		TMDB = [movie for movie in TMDBReader]
		# TMDB index 17 title
		# for i in range(4800):
		# 	next(TMDBReader)
		# for line in TMDBReader:
		# 	print(line[17])

		oscarTMDB = []
		for oscarMovie in Oscar:
			for TMDBMovie in TMDB:
				if len(TMDBMovie[11].split('-')) > 1:
					year = int(TMDBMovie[11].split('-')[0])
				else:
					year = 0
				if len(oscarMovie[0].split('/')) > 1:
					oscarYear = int(oscarMovie[0].split('/')[1])
				else:
					if oscarMovie[0] != 'Year':
						oscarYear = int(oscarMovie[0])
					else:
						oscarYear = 0;
				if (oscarMovie[4].lower() == TMDBMovie[17].lower() or oscarMovie[5].lower() == TMDBMovie[17].lower()) and (oscarYear == year):
					oscarTMDB.append([year, TMDBMovie[17], TMDBMovie[1], TMDBMovie[18], oscarMovie[2], oscarMovie[3]])

		with open('../data/result.csv', 'w', encoding='utf-8') as result:
			fieldnames = ['year', 'title', 'genre', 'vote_average', 'award', 'winner']
			csv_writer = csv.writer(result, delimiter=',')
			csv_writer.writerow(fieldnames)
			for line in oscarTMDB:
				csv_writer.writerow(line)


import sys
si = sys.stdin.readline

n, m = map(int, si().split())
truth = list(map(int, si().split()))[1:]

parties = []
parent = list(range(n + 1))

# find 연산 함수
def find(parent, x):
    if parent[x] != x:
        parent[x] = find(parent, parent[x])
    return parent[x]

# union 연산 함수
def union(parent, a, b, truth):
    a = find(parent, a)
    b = find(parent, b)

    # 두 사람 다 진실을 알고 있다면 연산 즉시종료
    if a in truth and b in truth:
        return
    # 한 사람만 아는 경우 해당 사람을 모르는 사람의 부모로
    if a in truth:
        parent[b] = a
    elif b in truth:
        parent[a] = b
    # 둘 다 모르는 경우는 더 작은 쪽을 부모로 (한 파티로 묶기 위해서 필요)
    else:
        if a < b:
            parent[b] = a
        else:
            parent[a] = b

for _ in range(m):
    party_info = list(map(int, si().split()))
    party_len = party_info[0]
    party = party_info[1:]

    # 파티 내 모든 요소를 돌며 union 연산 수행
    for i in range(party_len - 1):
        union(parent, party[i], party[i + 1], truth)

    parties.append(party)

cnt = 0
for party in parties:
    temp = True
    for i in range(len(party)):
        # 부모가 진실을 알고 있는 사람이라면
        if find(parent, party[i]) in truth:
            temp = False
            break
    if temp:
        cnt += 1

print(cnt)

09_그래프 이론/거짓말.py


# Code from Chapter 9 of Machine Learning: An Algorithmic Perspective
# by Stephen Marsland (http://seat.massey.ac.nz/personal/s.r.marsland/MLBook.html)

# You are free to use, change, or redistribute the code in any way you wish for
# non-commercial purposes, but please maintain the name of the original author.
# This code comes with no warranty of any kind.

# Stephen Marsland, 2008

from numpy import *

class kmeans:
    """The k-Means Algorithm implemented as a neural network"""
    def __init__(self,k,data,nEpochs=1000,eta=0.25):

        self.nData = shape(data)[0]
        self.nDim = shape(data)[1]
        self.k = k
        self.nEpochs = nEpochs
        self.weights = random.rand(self.nDim,self.k)
        self.eta = eta

    def kmeanstrain(self,data):
        # Preprocess data (won't work if (0,0,...0) is in data)
        normalisers = sqrt(sum(data**2,axis=1))*ones((1,shape(data)[0]))
        data = transpose(transpose(data)/normalisers)

        for i in range(self.nEpochs):
            for j in range(self.nData):
                activation = sum(self.weights*transpose(data[j:j+1,:]),axis=0)
                winner = argmax(activation)
                self.weights[:,winner] += self.eta * data[j,:] - self.weights[:,winner]

    def kmeansfwd(self,data):
        best = zeros(shape(data)[0])
        for i in range(shape(data)[0]):
            activation = sum(self.weights*transpose(data[i:i+1,:]),axis=0)
            best[i] = argmax(activation)
        return best


#!/usr/bin/python3

""" module Write a script that reads stdin line by line and computes metrics.
"""
import sys

def print_data(status_codes: dict, file_size: int):
    """ print data to stdout
        Args:
            status_codes: a dict with status codes
            file_size: the size of file
    """
    sys.stdout.write(f"File size: {file_size}\n")
    for x, y in status_codes.items():
        sys.stdout.write(f"{x}: {y}\n")
        sys.stdout.flush()
    sys.stdout.flush()

def get_metrics():
    """ script that reads stdin line by line and computes metrics
    """
    file_size = 0
    line_count = 0

    status_codes = {}

    try:
        for line in sys.stdin:
            message = line.split()
            line_count += 1

            # if len(message) less than 2 go to the next iteration
            if len(message) < 2:
                line_count += 1
                continue

            code = message[-2]  # status code
            size = message[-1]  # file size

            if code.isnumeric():
                if code not in status_codes:
                    status_codes[code] = 1
                else:
                    status_codes[code] += 1

            if size.isnumeric():
                file_size += int(size)

            if line_count % 10 == 0:
                print_data(dict(sorted(status_codes.items())), file_size)

        # for cases where we have only one line in file
        if line_count == 1 or len(status_codes) == 0:
            print_data(status_codes, file_size)

    except KeyboardInterrupt:
        print_data(dict(sorted(status_codes.items())), file_size)
        raise

get_metrics()


import requests, json, urllib3

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

class AlphaVantage:

    def __init__(self, key):
        self.api_key = key

    def get_intraday(self, stock_symbol, time_interval_min, api_key):
        url = f"https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=" \
              f"{stock_symbol}&interval={time_interval_min}min&apikey={api_key}"
        raw_payload = requests.get(url, verify=False)
        if raw_payload.status_code == 200:
            return json.dumps(raw_payload.json(), indent=4)
        else:
            return f"HTTP Error: {raw_payload.status_code}"

    def get_daily_ts(self, stock_symbol, api_key):

        url = f"https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol={stock_symbol}&apikey={api_key}"
        raw_payload = requests.get(url, verify=False)

        # Parsing raw API return values into clean ones
        # .rsplit method used to separate the numbers from datatype "1. open" --> "open"
        ts_data_payload = dict(raw_payload.json()["Time Series (Daily)"])
        for date, datapoints in ts_data_payload.items():
            for datapoint_type in list(datapoints):
                datapoints[datapoint_type.rsplit(". ")[-1].capitalize()] = datapoints[datapoint_type]
                del datapoints[datapoint_type]

        return json.dumps(raw_payload.json(), indent=4), {"target": stock_symbol, "payload": ts_data_payload}

if __name__ == '__main__':
    pass


from fractions import gcd
import heapq

def lcm(a, b):
    return (a * b) // gcd(a, b)

def solve_simulate(N, barber_times):
    last_barber_cut_index = 0
    available_barbers = [(index, value) for index, value in enumerate(barber_times)]
    heapq.heapify(available_barbers)
    unavailable_barbers = []
    for i in range(N + 1):
        if len(available_barbers) > 0:
            barber_index_time = heapq.heappop(available_barbers)
            heapq.heappush(unavailable_barbers, (barber_index_time[1], barber_index_time[0]))
            last_barber_cut_index = barber_index_time[0]
        else:
            min_time = unavailable_barbers[0][0]
            while len(unavailable_barbers) > 0 and unavailable_barbers[0][0] == min_time:
                now_available = heapq.heappop(unavailable_barbers)
                barber_index = now_available[1]
                heapq.heappush(available_barbers, (barber_index, barber_times[barber_index]))
            for i in range(len(unavailable_barbers)):
                unavailable_barbers[i] = (unavailable_barbers[i][0] - min_time, unavailable_barbers[i][1])
            heapq.heapify(unavailable_barbers)
            barber_index_time = heapq.heappop(available_barbers)
            heapq.heappush(unavailable_barbers, (barber_index_time[1], barber_index_time[0]))
            last_barber_cut_index = barber_index_time[0]
    return last_barber_cut_index

def solve_small(N, barber_times):
    max_lcm = 1
    for barber_time in barber_times:
        max_lcm = lcm(max_lcm, barber_time)
    cycle_length = 0
    for barber_time in barber_times:
        cycle_length += (max_lcm // barber_time)
    new_N = (N % cycle_length)
    return solve_simulate(new_N, barber_times) + 1

if __name__ == "__main__":
    with open("input.txt", "r") as input, open("output.txt", "w") as output:
        T = int(input.readline())
        for t in range(1, T + 1):
            B_N_tokens = input.readline().split(" ")
            B = int(B_N_tokens[0])
            N = int(B_N_tokens[1]) - 1
            Mk_tokens = input.readline().split(" ")
            barber_times = list(map(int, Mk_tokens))
            small_answer = solve_small(N, barber_times)
            print("Case #{0}: {1}".format(t, small_answer), file=output)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import print_function
from jinja2 import Environment, FileSystemLoader
import os.path
import numpy as np

# uniform
def gen_popcnt_test_cases(n_bits, n_samples):
    """
    """
    assert n_bits <= 64

    test_in = []
    test_out = []
    if n_bits < 14:
        for x in range(2 ** n_bits):
            x_str = '{0:0{w}b}'.format(x, w=n_bits)
            x_arr = np.array([int(s) for s in x_str])
            test_in.append('0b' + x_str)
            test_out.append(np.sum(x_arr))
    else:
        bits = np.random.randint(0, high=2, size=(n_samples, n_bits))
        for xb in bits:
            test_in.append('0b' + ''.join([str(b) for b in xb]))
            test_out.append(np.sum(xb))
    return test_in, test_out

# uniform
def gen_popcnt_test_cases_vr(n_bits, n_samples, rate=None):
    """
    """
    assert n_bits <= 64
    if (n_bits < 14) or (rate is None) or (rate == 0.5):
        return gen_popcnt_test_cases(n_bits, n_samples)
    # bits = np.random.randint(0, high=2, size=(n_samples, n_bits))
    rv = np.random.rand(n_samples, n_bits)
    bits = np.zeros((n_samples, n_bits), dtype=int)
    bits[rv < rate] = 1
    test_in = []
    test_out = []
    for xb in bits:
        test_in.append('0b' + ''.join([str(b) for b in xb]))
        test_out.append(np.sum(xb))
    return test_in, test_out

def gen_vector(dim, dtype):
    if dtype == 'float':
        return np.array(np.random.randn(dim), dtype=np.float32)
    elif dtype == 'int':
        return np.random.randint(0, high=256, size=dim)
    elif dtype == 'bit' or dtype == 'bit_enc':
        return np.random.randint(0, high=2, size=dim)

def stringtify(vec, dtype, word_size=None):
    """

    :param vec:
    :param dtype:
    :return:
    """
    if (dtype is not 'bit') and (dtype is not 'bit_enc'):
        s = ', '.join(['{}'.format(vi) for vi in vec])
    else:
        dim = len(vec)
        tmp = []
        if word_size is None:
            word_size = 64
        i = 0
        while dim >= word_size:
            tmp.append(int(''.join([str(vi) for vi in vec[i:(i + word_size)]]), 2))
            dim -= word_size
            i += word_size
        if dim > 0:
            tmp.append(int(''.join([str(vi) for vi in vec[i:]]), 2))

        suf = 'u'
        s = ','.join([str(ti) + suf for ti in tmp])
    return s

def gen_dot_prod_test_cases(dim, n_samples, dtype1, dtype2, rtype, word_size=None):
    """

    :param dim:
    :param n_samples:
    :param dtype1:
    :param dtype2:
    :return:
    """
    tests_ = []
    for _ in range(n_samples):
        va = np.array(gen_vector(dim, dtype=dtype1))
        vb = np.array(gen_vector(dim, dtype=dtype2))

        tests_.append(
            {
                'va': {
                    'data': stringtify(va, dtype1, word_size),
                    'dtype': dtype1 if (dtype1 != 'bit' and dtype1 != 'bit_enc') else 'uint{}_t'.format(word_size)
                },
                'vb': {
                    'data': stringtify(vb, dtype2, word_size),
                    'dtype': dtype2 if (dtype2 != 'bit' and dtype2 != 'bit_enc') else 'uint{}_t'.format(word_size)
                },
                'dlen': dim,
                'res': 0,
                'rtype': rtype
            }
        )
        if dtype1 == 'bit_enc':
            va[va == 0] = -1
        if dtype2 == 'bit_enc':
            vb[vb == 0] = -1
        tests_[-1]['res'] = np.dot(va, vb)
    return tests_

# Capture our current directory
THIS_DIR = os.path.dirname(os.path.abspath(__file__))

def generate_dot_prod_cpp_test_file(template_filename, test_cases, n_tests_each=200, out_filename=None):
    # Create the jinja2 environment.
    # Notice the use of trim_blocks, which greatly helps control whitespace.
    j2_env = Environment(loader=FileSystemLoader(os.path.join(THIS_DIR, 'templates')),
                         trim_blocks=True)
    if out_filename is None:
        filename, file_extension = os.path.splitext(template_filename)
        out_filename = filename
    test_dims = (2, 4, 8, 16, 32)
    test_dims_compact = (64, 128, 256, 60, 59, 100, 119, 24, 23, 150)
    config = []
    type_name = {
        'int': 'int /* {} */',
        'float': 'float /* {} */',
        'bit': 'uint{}_t',
        'bit_enc': 'uint{}_t'
    }
    for test_case in test_cases:
        if test_case[1].find('cb') != -1:
            tdims = test_dims_compact
        else:
            tdims = test_dims
        func_suf = {
            'dot_prod': '<{t1}, {t2}, {res}>',
            'dot_prod_cb': '<{t1}, {res}, {t2}>',
            'dot_prod_cb_enc': '<{t1}, {res}, {t2}>',
            'dot_prod_cb_cb_enc': '<{res}, {t}>'
        }
        for d in tdims:
            ws = test_case[-1]
            if isinstance(ws, str):
                ws = None
            tests = gen_dot_prod_test_cases(d, n_tests_each, test_case[2], test_case[3], test_case[4], word_size=ws)
            ws_str = ws if ws is not None else ''
            config.append({
                'description': test_case[0].format(d),
                'tests': tests,
                'func': test_case[1] + func_suf[test_case[1]].format(t1=type_name[test_case[2]].format(ws_str),
                                                                     t2=type_name[test_case[3]].format(ws_str),
                                                                     res=type_name[test_case[4]].format(ws_str)) if
                test_case[
                    1] != 'dot_prod_cb_cb_enc' else
                test_case[1] + func_suf[test_case[1]].format(t=type_name[test_case[2]].format(ws_str),
                                                             res=type_name[test_case[4]].format(ws_str))
            })
    with open(out_filename, 'w') as wfp:
        wfp.write(j2_env.get_template(template_filename).render(all_tests=config))

def generate_cc_test_file(template_filename, n_tests_each=200, out_filename=None):
    # Create the jinja2 environment.
    # Notice the use of trim_blocks, which greatly helps control whitespace.
    j2_env = Environment(loader=FileSystemLoader(os.path.join(THIS_DIR, 'templates')),
                         trim_blocks=True)
    if out_filename is None:
        filename, file_extension = os.path.splitext(template_filename)
        out_filename = filename
    test_cases = (
        (32, 'unsigned_int_tests'), (64, 'unsigned_long_long_tests'),
        (8, 'uint8_t_tests'), (16, 'uint16_t_tests'), (32, 'uint32_t_tests'),
        (64, 'uint64_t_tests'), (16, 'unsigned_short_tests'), (32, 'unsigned_long_tests')
    )
    config = {}
    #
    rate = None
    for nb, key in test_cases:
        k = n_tests_each
        test_in = []
        test_out = []
        for rate in (0.2, 0.4, 0.6, 0.8):
            test_in_, test_out_ = gen_popcnt_test_cases_vr(nb, n_samples=k, rate=rate)
            test_in += test_in_
            test_out += test_out_
        test_in.append('0b0')
        test_out.append(0)
        test_in.append('0b' + ('1' * nb))
        test_out.append(nb)
        config[key] = [
            {'in': i, 'out': o} for i, o in zip(test_in, test_out)
        ]
    with open(out_filename, 'w') as wfp:
        wfp.write(j2_env.get_template(template_filename).render(tests=config))

if __name__ == '__main__':
    generate_cc_test_file("popcnt_test.cpp.template", n_tests_each=10, out_filename="popcnt_s_test.cpp")
    generate_cc_test_file("popcnt_test.cpp.template", n_tests_each=200, out_filename="popcnt_l_test.cpp")
    for test_cases in (
            (
            ('T dot_prod(const T *,const T *, size_t) with T=int, dim={}', 'dot_prod', 'int', 'int', 'int'),
            ('T dot_prod(const T *,const T *, size_t) with T=float, dim={}', 'dot_prod', 'float', 'float',
             'float'),
            ('float dot_prod(const T1 *,const T2 *, size_t) with T1=int, T2=float, dim={}', 'dot_prod', 'int',
             'float',
             'float'),
            ('float dot_prod(const T1 *,const T2 *, size_t) with T1=float, T2=int, dim={}', 'dot_prod', 'float',
             'int',
             'float')),
            (('int dot_prod_cb(const int *,const uint32_t *, size_t), dim={}', 'dot_prod_cb', 'int', 'bit', 'int', 32),
             ('float dot_prod_cb(const float *,const uint32_t *, size_t), dim={}', 'dot_prod_cb', 'float', 'bit',
              'float',
              32),
             ('int dot_prod_cb(const int*, const uint64_t*, size_t), dim={}', 'dot_prod_cb', 'int', 'bit', 'int', 64),
             (
                     'float dot_prod_cb(const float*, const uint64_t*, size_t), dim={}', 'dot_prod_cb', 'float', 'bit',
                     'float',
                     64)),
            (('int dot_prod_cb_enc(const int*, const uint32_t*, size_t), dim={}', 'dot_prod_cb_enc', 'int', 'bit_enc',
              'int',
              32),
             ('float dot_prod_cb_enc(const float*, const uint32_t*, size_t), dim={}', 'dot_prod_cb_enc', 'float',
              'bit_enc',
              'float', 32),
             (
                     'int dot_prod_cb_enc(const int*, const uint64_t*, size_t), dim={}', 'dot_prod_cb_enc', 'int',
                     'bit_enc', 'int',
                     64),
             ('float dot_prod_cb_enc(const float*, const uint64_t*, size_t), dim={}', 'dot_prod_cb_enc', 'float',
              'bit_enc',
              'float', 64)),
            ((
                     'int dot_prod_cb_cb_enc(const uint64_t*, const uint64_t*, size_t), dim={}', 'dot_prod_cb_cb_enc',
                     'bit_enc',
                     'bit_enc',
                     'int', 64),
             ('int dot_prod_cb_cb_enc(const uint32_t*, const uint32_t*, size_t), , dim={}', 'dot_prod_cb_cb_enc',
              'bit_enc',
              'bit_enc', 'int', 32))):
        generate_dot_prod_cpp_test_file('dot_prod_test.cpp.template',
                                        test_cases=test_cases,
                                        n_tests_each=5,
                                        out_filename=test_cases[0][1] + '_s_test.cpp')
        generate_dot_prod_cpp_test_file('dot_prod_test.cpp.template',
                                        test_cases=test_cases,
                                        n_tests_each=100,
                                        out_filename=test_cases[0][1] + '_l_test.cpp')


import graphene
from django.contrib.auth.models import AnonymousUser
from django.core.exceptions import ValidationError

from core.gql.gql_mutations.base_mutation import BaseMutation, BaseCreateMutationMixin, BaseUpdateMutationMixin, \
    BaseHistoryModelCreateMutationMixin, BaseHistoryModelUpdateMutationMixin, BaseHistoryModelDeleteMutationMixin
from core.schema import OpenIMISMutation
from invoice.apps import InvoiceConfig
from invoice.gql.input_types import CreateBillPaymentInputType, UpdateBillPaymentInputType
from invoice.models import BillPayment, BillPaymentMutation

class CreateBillPaymentMutation(BaseHistoryModelCreateMutationMixin, BaseMutation):
    _mutation_class = "CreateBillPaymentMutation"
    _mutation_module = "invoice"
    _model = BillPayment

    @classmethod
    def _mutate(cls, user, **data):
        client_mutation_id = data.get("client_mutation_id")
        if "client_mutation_id" in data:
            data.pop('client_mutation_id')
        if "client_mutation_label" in data:
            data.pop('client_mutation_label')
        p = cls.create_object(user=user, object_data=data)
        if p:
            BillPaymentMutation.object_mutated(
                user,
                client_mutation_id=client_mutation_id,
                bill_payment=p
            )

    @classmethod
    def _validate_mutation(cls, user, **data):
        if type(user) is AnonymousUser or not user.id or not user.has_perms(
                InvoiceConfig.gql_bill_payment_create_perms):
            raise ValidationError("mutation.authentication_required")

    class Input(CreateBillPaymentInputType):
        pass

class UpdateBillPaymentMutation(BaseHistoryModelUpdateMutationMixin, BaseMutation):
    _mutation_class = "UpdateBillPaymentMutation"
    _mutation_module = "invoice"
    _model = BillPayment

    @classmethod
    def _validate_mutation(cls, user, **data):
        if type(user) is AnonymousUser or not user.id or not user.has_perms(
                InvoiceConfig.gql_bill_payment_update_perms):
            raise ValidationError("mutation.authentication_required")

    class Input(UpdateBillPaymentInputType):
        pass

class DeleteBillPaymentMutation(BaseHistoryModelDeleteMutationMixin, BaseMutation):
    _mutation_class = "DeleteBillPaymentMutation"
    _mutation_module = "invoice"
    _model = BillPayment

    @classmethod
    def _validate_mutation(cls, user, **data):
        if type(user) is AnonymousUser or not user.id or not user.has_perms(
                InvoiceConfig.gql_bill_payment_delete_perms):
            raise ValidationError("mutation.authentication_required")

    class Input(OpenIMISMutation.Input):
        uuids = graphene.List(graphene.UUID)


import pandas as pd

# 读取表A和表B
df_a = pd.read_excel('03_14_500Hz_new_data.xlsx')
df_b = pd.read_excel('0818_True_倍频程T60.xlsx')

# 剔除表A中已经出现在表B中的行数据
df_c = df_a[~df_a.isin(df_b)].dropna()

# 将表A中出现而表B中没出现的行数据保存到表C中
df_c.to_excel('table_c.xlsx', index=False)


from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
import xlrd

arq = open("Resultado.xls","w")
workbook = xlrd.open_workbook(r'C:\Repositorio projeto-automacao\projeto-automacao\CNPJ_FIs.xls')
sheet = workbook.sheet_by_name('CNPJ_FI')
rows = sheet.nrows
columns = sheet.ncols

options = webdriver.EdgeOptions()
options.add_argument('--disable-logging')
options.add_argument('--log-level=3')

driver = webdriver.Edge("C:\Repositorio projeto-automacao\projeto-automacao\msedgedriver.exe", options= options)
driver.get ("https://web.cvm.gov.br/app/fundosweb/#/consultaPublica")

for curr_row in range(0,rows):
    x = sheet.cell_value(curr_row,0)
    time.sleep(10)
    #BuscaFundo = driver.find_element(By.LINK_TEXT,'https://sistemas.cvm.gov.br/port/fundos/consultafundos.asp')
    time.sleep(3)
    Pesquisa = driver.find_element(By.ID,"txtCnpj")
    time.sleep(3)
    Pesquisa.clear()
    time.sleep(4)
    Pesquisa.send_keys(x)
    time.sleep(5)
    #Pesquisa.send_keys(Keys.RETURN)
    time.sleep(3)
    click_pesquisa = driver.find_element(By.XPATH, '//*[@id="panelFiltros"]/div/div/a[1]/span' )
    click_pesquisa.click()
    time.sleep(3)
    visualizar_pesquisa = driver.find_element(By.XPATH,'//*[@id="containerView"]/div[2]/div[3]/table/tbody/tr/td[9]/a[1]')
    visualizar_pesquisa.click()
    time.sleep(3)
    click_participantes = driver.find_element(By.XPATH,'//*[@id="tabFundo"]/ul/li[2]')
    click_participantes.click()
    time.sleep(3)
    Dados_Distribuidor = driver.find_element(By.XPATH,'//*[@id="tabPanelVisualizarParticipante"]/div/div[2]/div[21]/div/fieldset/div[2]/div/div/table[1]/tbody/tr/td[3]')

    texto = 'O FI %s %s\n' %(x,Dados_Distribuidor.accessible_name)
    time.sleep(1)

    Boton_Return = driver.find_element(By.XPATH,'//*[@id="containerView"]/div[2]/div[2]/div[1]/a/span[2]')
    Boton_Return.click()
    arq.write(texto)
    time.sleep(2)
arq.close()


import numpy as np
import matplotlib.pyplot as plt
# plt.switch_backend('agg')  # 服务器上跑
import os
import sys
from ready_for_train import Vector_Reader as v_reader
head_path = os.path.dirname(
    os.path.dirname(os.path.abspath(__file__)))
# print(head_path)
sys.path.append(head_path)
import config
from utils import *
from collections import defaultdict
import logging

def _gen_defaultdict():
    # return copy.copy(defaultdict(int))
    return defaultdict(int)

class Coin_Reader(v_reader):
    def __init__(self, input_dir='null', out_put_dir='null'):
        v_reader.__init__(self, input_dir, out_put_dir)

    def _do_read_user_data(self, file_machine, file_bonus, file_payin, file_odds, file_line, seq_len, max_len, mid_line_odds_count):
        """
        max_len : 原始文件的最大序列长度
        """
        # mid_lv_count = [defaultdict(_gen_defaultdict),
        #                 defaultdict(_gen_defaultdict)]
        if (not os.path.exists(file_machine)):
            return False
        f_machine = open(file_machine, 'r')
        f_bonus = open(file_bonus, 'r')
        f_payin = open(file_payin, 'r')
        f_odds = open(file_odds, 'r')
        f_line = open(file_line, 'r')
#            has_zero = False
        while True:
            machine_line = f_machine.readline().strip()
            if not machine_line:
                break
            bonus_line = f_bonus.readline().strip()
            payin_line = f_payin.readline().strip()
            odds_line = f_odds.readline().strip()
            line_line = f_line.readline().strip()

            machine_line = machine_line.split(" ")
            bonus_line = bonus_line.split(" ")
            payin_line = payin_line.split(" ")
            odds_line = odds_line.split(" ")
            line_line = line_line.split(" ")
            # if len(line) < seq_len or line[-1] == "-1":  # 被抛掉的数据
            if machine_line[-1] == '-1':
                continue
            cr_len = len(machine_line)
            # for in line[::-1]
            for i in range(seq_len):
                # cr_index = max(0, cr_len - seq_len + i)
                cr_index = cr_len - seq_len + i
                if cr_index >= cr_len or cr_index < 0:
                    continue
                # print(line[cr_index])
                try:
                    cr_mid = int(float(machine_line[cr_index]))
                    cr_bonus = int(float(bonus_line[cr_index]))
                    cr_payin = int(float(payin_line[cr_index]))
                    cr_odds = float(odds_line[cr_index])
                    cr_line = int(float(line_line[cr_index]))
                    if cr_bonus != 0:
                        cr_odds = (cr_odds * cr_payin + cr_bonus) / cr_payin if cr_payin != 0 else 0
                    cr_odds = round(cr_odds, 1)
                    mid_line_odds_count[cr_mid][cr_line][cr_odds] += 1

                except Exception as ex:
                    logging.exception(ex)
                    print(ex)
                    break
            #         # [cr_mid] += 1
            # f_machine.close()
            # f_bonus.close()
            # f_coin.close()
            # f_time.close()
        # return [data, lable]
        f_machine.close()
        f_bonus.close()
        f_line.close()
        f_payin.close()
        f_odds.close()
        return True

    """
    读玩家数据，继承类可以重写这个函数
    """

    def _read_user_data(self, file_dir, seq_len, max_len):
        """
        max_len : 原始文件的最大序列长度
        """

        arr_dir = file_dir.split(os.path.sep)
        uid = arr_dir[-1]
        # print(uid)
        # exit()

        mid_line_odds_count = defaultdict(lambda: defaultdict(lambda: defaultdict(int)))

        for payed in range(2)[::-1]:
            pre_fix = ""
            if payed == 1:
                pre_fix = 'pay_'
            file_machine = os.path.join(file_dir, pre_fix + "machine_id.txt")
            if (not os.path.exists(file_machine)):
                continue
            file_bonus = os.path.join(file_dir, pre_fix + "win_bonus.txt")
            file_payin = os.path.join(file_dir, pre_fix + "pay_in.txt")
            file_odds = os.path.join(file_dir, pre_fix + "odds.txt")
            file_line = os.path.join(file_dir, pre_fix + "line.txt")
            self._do_read_user_data(
                file_machine, file_bonus, file_payin, file_odds, file_line, seq_len, max_len, mid_line_odds_count)
        # 读drop out的pay记录
        drop_dir = file_dir + os.path.sep + '..' + os.path.sep + \
            '__waring__' + os.path.sep + 'drop_pay' + os.path.sep + uid
        # print(drop_dir)
        file_machine = os.path.join(drop_dir, "machine_id.txt")
        if (os.path.exists(file_machine)):
            file_bonus = os.path.join(drop_dir, "win_bonus.txt")
            file_payin = os.path.join(drop_dir, "pay_in.txt")
            file_odds = os.path.join(drop_dir, "odds.txt")
            file_line = os.path.join(drop_dir, "line.txt")
            self._do_read_user_data(
                file_machine, file_bonus, file_payin, file_odds, file_line, seq_len, max_len, mid_line_odds_count)

        return mid_line_odds_count


# coding = utf-8
import json
import cv2
from fastapi import FastAPI, UploadFile
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse
import numpy as np
from handler.http_handler import init_http_exception_handler
from models.captcha_models import *
from models.response_models import captcha_response

from hypercorn.asyncio import serve
from hypercorn import Config
import asyncio

ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'JPG', 'JPEG', 'PNG'])

app = FastAPI(
    title="圖片驗證API",
    description='',
    version="0.0.1",
    terms_of_service="",
)

init_http_exception_handler(app)

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

@app.get("/")
def index():
    return "HI, 歡迎使用圖形驗證碼API，若要看相關文件請至 /docs"

@app.post("/api/captcha_id", response_model= captcha_response)
async def captcha_id(file: UploadFile):
    """
    圖形驗證碼

    - **tags**: 圖片驗證碼五碼六碼通用
    - **consumes**: ["multipart/form-data"]
    - **parameters**:
        - name: file
        - in: formData
        - type: file
        - required: true
    - **responses**:
        - HttpStatus:
            - 200: 回傳運算結果
            - 400: 檔案上傳不成功 / 檔案格式不符
            - 404: 更版或維修中，請通知管理員
            - 500: 服務機出現異常，請通知管理員
        - status: S成功 F失敗
        - res: 運算結果或錯誤資訊
    """

    if not file:
        return captcha_response(status = 400, res = '檔案上傳不成功')
    else:
        if allowed_file(file.filename):
            try:
                contents = await file.read()
                image_bytes = np.frombuffer(contents, np.uint8)
                image = cv2.imdecode(image_bytes, cv2.IMREAD_COLOR)
                image = cv2.resize(image, (200, 60), interpolation=cv2.INTER_AREA)
                model = captcha_model_id()
                model.load_weights('./checkpoints/verificatioin_code-1118-id.h5')
                captcha_text = model.predict(image)
                # return captcha text
                return JSONResponse(jsonable_encoder(captcha_response(status = "S", res = captcha_text)), 200)
            except:
                return JSONResponse(jsonable_encoder(captcha_response(status = "F", res = '服務機出現異常，請通知管理員')), 500)
        else:
            return JSONResponse(jsonable_encoder(captcha_response(status = "F", res = '檔案格式不符')), 400)

if __name__ == "__main__":
    file = open("./configs/hypercorn_config.json")
    config = json.load(file)

    hc_config = Config()
    hc_config.worker_class = config["worker_class"]
    hc_config.workers = config["workers"]
    hc_config.keep_alive_timeout = config["keep_alive_timeout"]

    if config['https']:
        hc_config.bind = [config['ip'] + ':443']
        hc_config.certfile = config['certfile']
        hc_config.keyfile = config['keyfile']
        hc_config.insecure_bind = [config['ip'] + ":" + config['port']]
    else:
        hc_config.bind = [config['ip'] + ":" + config['port']]

    # config定義在 ./config/hypercorn_config
    asyncio.run(serve(app, hc_config))


# -*- coding: utf-8 -*-
# !/usr/bin/env python

import logging
import yaml
import os

from tornado.escape import json_encode
from tornado.ioloop import IOLoop
from tornado.options import define, options, parse_command_line
from tornado.web import Application, RequestHandler

from web3 import Web3
from libs.transaction_maker import TransactionMaker

define('port', default=11211, help="port to listen on")
define('host', default='127.0.0.1', help="host to listen on")
define('debug', default=False, group='application',
       help="run in debug mode (with automatic reloading)")

estconf = yaml.load(open(os.path.dirname(__file__) + '/conf/est.yaml'))

class BaseHandler(RequestHandler):

    def get(self):
        self.write_error(404)

    def write_error(self, status_code, **kwargs):
        data = dict()
        data["ret"] = data["code"] = status_code
        data["msg"] = "error"
        data['data'] = dict()
        self.write(json_encode(data))

class MainHandler(BaseHandler):
    """
    """

    def get(self):
        pass

class EstAccountHandler(BaseHandler):

    def get(self):
        ret = {'ret': 0, 'code': 0, 'msg': '', 'data': dict()}
        address = self.get_argument('address', '', True)
        est = self.get_argument('est', '', True)
        if not address or not est:
            ret['ret'] = ret['code'] = 400
            ret['msg'] = 'address or est cannot be empty'
            self.write(json_encode(ret))
            return

        address = Web3.toChecksumAddress(address)
        if not Web3.isChecksumAddress(address):
            ret['ret'] = ret['code'] = 400
            ret['msg'] = 'address invalid'
            self.write(json_encode(ret))
            return

        base_conf = estconf['base']

        trans = TransactionMaker(provider_url=base_conf['provider_url'], my_wallet_address=base_conf['from_address'])
        trans.set_abi_type(erc20_abi_json=base_conf['erc20_abi'])

        value = int(float(est) * 10 ** 9)
        cost = trans.get_transfer_cost(to=address, value=value, contract_address=base_conf['contract_address'])
        if not cost:
            ret['ret'] = ret['code'] = 400
            ret['msg'] = 'System maintenance'
            self.write(json_encode(ret))
            return
        ret['data'] = {'cost': cost}

        self.write(json_encode(ret))
        return

def main():
    parse_command_line()

    app = Application([(r"/", MainHandler), (r"/est", EstAccountHandler), (r".*", BaseHandler), ])
    print(options.port)
    app.listen(options.port, address='127.0.0.1')
    logging.info('Listening on http://localhost:%d' % options.port)

    IOLoop.current().start()

if __name__ == '__main__':
    main()


import pandas as pd
from pcf.common.dbconnect import connect
from sqlite3 import Error

def create_connection():
    """ create a database connection to the SQLite database
    """
    conn = None
    try:
        conn = connect()
    except Error as e:
        print(e)

    return conn

def load_entity(fname='../data/entity.csv'):
    dfentity_csv = pd.read_csv(fname)
    #    print(dfentity_csv.head())

    conn = create_connection()
    dfentity_sql = pd.read_sql("select * from entity", conn)
    print(dfentity_sql.head())

    #    print("start iteration")
    #    df = dfentity_sql.assign(rn=dfentity_sql.sort_values('entityId', ascending=False)
    #                                            .groupby(['entityName'])
    #                                            .cumcount() +1)

    dfentity_sql_rnk1 = dfentity_sql.assign(rn=dfentity_sql.sort_values(['entityId'], ascending=False) \
                             .groupby(['entityName']) \
                             .cumcount() + 1) \
        .query('rn == 1 ')

    #print(df_sql_rnk1)

    df = pd.merge(dfentity_csv, dfentity_sql_rnk1 , how='left' , left_on=['entityName'] , right_on=['entityName'])
    print(df)

"""
    # using itertulples to iterate the csv dataframe. when a match is found the flag column will be updated.
    for row in dfentity_csv.itertuples():
        print(getattr(row,'entityName'))
        #if getattr(row,'entityName') in dfentity_sql['entityName'].values:
        #    print ("exists" + str(dfentity_sql['entityId'].values) )
        if dfentity_sql.isin(getattr(row,'entityName')):
            print
        else:
            print("does not exist")
"""

load_entity()


#
#  Project: MXCuBE
#  https://github.com/mxcube
#
#  This file is part of MXCuBE software.
#
#  MXCuBE is free software: you can redistribute it and/or modify
#  it under the terms of the GNU Lesser General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  MXCuBE is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU Lesser General Public License for more details.
#
#  You should have received a copy of the GNU Lesser General Public License
#  along with MXCuBE.  If not, see <http://www.gnu.org/licenses/>.

import logging
import numpy.oldnumeric as Numeric

from mxcubeqt.utils import qt_import
from mxcubeqt.base_components import BaseWidget

try:
    if qt_import.qt_variant == "PyQt5":
        from PyMca5.PyMca import McaAdvancedFit
        from PyMca5.PyMca import ConfigDict
    else:
        from PyMca import McaAdvancedFit
        from PyMca import ConfigDict
except BaseException:
    pass

__credits__ = ["MXCuBE collaboration"]
__license__ = "LGPLv3+"
__category__ = "General"

class McaSpectrumBrick(BaseWidget):
    def __init__(self, *args):
        BaseWidget.__init__(self, *args)

        self.defineSlot("setData", ())

        self.mcafit = McaAdvancedFit.McaAdvancedFit(self)
        self.mcafit.dismissButton.hide()

        # Layout --------------------------------------------------------------
        main_layout = qt_import.QVBoxLayout(self)
        main_layout.addWidget(self.mcafit)
        # main_layout.addWidget(self.scan_plot_widget)
        main_layout.setSpacing(0)
        main_layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(main_layout)

    def setData(self, data, calib, config):
        try:
            configured = False
            if config.get("file", None):
                self._configure(config)
                configured = True
            data = Numeric.array(data)
            x = Numeric.array(data[:, 0]).astype(Numeric.Float)
            y = Numeric.array(data[:, 1]).astype(Numeric.Float)
            calib = Numeric.ravel(calib).tolist()
            self.mcafit.setdata(x, y)
            self.mcafit._energyAxis = False
            self.mcafit.toggleEnergyAxis()
            result = self._fit()
            # pyarch file name and directory
            pf = config["legend"].split(".")
            pd = pf[0].split("/")
            outfile = pd[-1]
            outdir = config["htmldir"]
            sourcename = config["legend"]

            if configured:
                report = McaAdvancedFit.QtMcaAdvancedFitReport.QtMcaAdvancedFitReport(
                    None,
                    outfile=outfile,
                    outdir=outdir,
                    fitresult=result,
                    sourcename=sourcename,
                    plotdict={"logy": False},
                    table=2,
                )

                text = report.getText()
                report.writeReport(text=text)

        except BaseException:
            logging.getLogger().exception(
                "McaSpectrumBrick: problem fitting %s %s %s"
                % (str(data), str(calib), str(config))
            )

    def _fit(self):
        return self.mcafit.fit()

    def _configure(self, config):
        d = ConfigDict.ConfigDict()
        d.read(config["file"])
        if "concentrations" not in d:
            d["concentrations"] = {}
        if "attenuators" not in d:
            d["attenuators"] = {}
            d["attenuators"]["Matrix"] = [1, "Water", 1.0, 0.01, 45.0, 45.0]
        if "flux" in config:
            d["concentrations"]["flux"] = float(config["flux"])
        if "time" in config:
            d["concentrations"]["time"] = float(config["time"])
        self.mcafit.mcafit.configure(d)

    def clear(self):
        x = Numeric.array([0]).astype(Numeric.Float)
        y = Numeric.array([0]).astype(Numeric.Float)
        self.mcafit.setdata(x, y)


from django.shortcuts import render,HttpResponse
import json,time,Show.communication

from Show import models
# Create your views here.

def wsssetting(req):
    wssinfo1 = models.wssInfo.objects.filter(id=1)
    wssinfo2 = models.wssInfo.objects.filter(id=2)
    wssinfo3 = models.wssInfo.objects.filter(id=3)
    wssinfo4 = models.wssInfo.objects.filter(id=4)

    return render(req,"WSSsetting.html",{
        "wssinfo1":wssinfo1[0],"wssinfo2":wssinfo2[0],
        "wssinfo3": wssinfo3[0],"wssinfo4":wssinfo4[0]
    })

# 当停止OEO服务的时候
def ajax_wsssetting_stop(req):
    # 这里直接在数据库中标记一下即可
    print("WSS服务暂停...")
    deviceid = int(req.POST.get("Device",None))

    if(True):
        # 先修改数据库记录
        models.wssInfo.objects.filter(id=deviceid).update(
            wssstate="OFF"
        )
        # 生成操作记录
        models.wssSetLog.objects.create(
            logtime=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
            loginfo='WSS#'+str(deviceid)+' 服务暂停...' +
                    str(models.wssInfo.objects.filter(id=deviceid)[0]),
            logtype='暂停操作'
        )
        # 生成操作结果
        dic = {"result": "success"}
    else:
        dic = {"result": "error"}
    # 返回操作结果
    time.sleep(2)
    return HttpResponse(json.dumps(dic))

# 当启动WSS服务的时候
def ajax_wsssetting_start(req):
    # 这里尝试发送一个hello包
    print("WSS服务启动...")
    deviceid = int(req.POST.get("Device", None))

    getinfo = models.wssInfo.objects.filter(id=deviceid)[0]
    result = Show.communication.testHello(getinfo.wssip,getinfo.wssport,getinfo.wsskey)

    # 当hello包发送与接收正确的时候
    if(result.startswith("SUCCESS")):
        # 先修改数据库记录
        models.wssInfo.objects.filter(id=deviceid).update(
            wssstate="ON"
        )
        # 然后记录操作
        models.wssSetLog.objects.create(
            logtime=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
            loginfo='WSS#'+str(deviceid)+' 服务启动...' +
                    str(models.wssInfo.objects.filter(id=deviceid)[0]),
            logtype='启动操作'
        )
        # 生成操作结果
        dic = {"result": "success"}
    else:
        # 如果失败则什么也不操作，直接返回操作失败结果
        dic = {"result": "error"}
    # 返回操作结果
    time.sleep(2)
    return HttpResponse(json.dumps(dic))

# 当WSS设置发生变化时候
def ajax_wsssetting_change(req):
    print("WSS信息修改...")

    deviceid = int(req.POST.get("Device", None))
    # TODO 这里可能还需要添加数据验证代码，目前先默认正确
    # 更新数据库数据
    models.wssInfo.objects.filter(id=deviceid).update(
        wsstype=req.POST.get("wsstype", None),
        wssip=req.POST.get("wssip", None),
        wssport=req.POST.get("wssport", None),
        wsskey=req.POST.get("wsskey", None),
        wssright="NULL",
        wssstate="OFF",
        wsslocation=req.POST.get("wsslocation", None)
    )
    # 生成操作日志
    models.wssSetLog.objects.create(
        logtime=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
        loginfo='WSS#'+str(deviceid)+' 信息修改...'+
                str(models.wssInfo.objects.filter(id=deviceid)[0]),
        logtype='信息修改'
    )
    # 返回操作结果
    dic={"result":"success"}
    time.sleep(2)
    return HttpResponse(json.dumps(dic))

# 获取日志信息
def ajax_wsssetting_getlog(req):
    count = models.wssSetLog.objects.count()
    if(count<=10):
        dataraw = models.wssSetLog.objects.all()
    else:
        lastid = models.wssSetLog.objects.last().id
        dataraw = models.wssSetLog.objects.filter(id__gt=(lastid-10))

    data = []
    for e in dataraw:
        data.append(str(e.id))
        data.append(str(e.logtime))
        data.append(e.loginfo)

    # print(data)
    data_ret = {"data":data}
    return HttpResponse(json.dumps(data_ret))


import pygame
from collections import deque
from random import choice, randrange

class Ant():
    def __init__(self,app,pos,color):
        self.app = app
        self.color = color
        self.x, self.y = pos
        self.increments = deque([(1,0),(0,1),(-1,0),(0,-1)])
    def run(self): #définition des règles que doit suivre la fourmi pour se déplacer
        value = self.app.grid[self.y][self.x] #position de la fourmi sur l'écran défini par app
        self.app.grid[self.y][self.x] = not value

        SIZE = self.app.CELL_SIZE #On dessine non plus des carrés mais des ronds
        center = self.x * SIZE, self.y * SIZE
        if value:
            pygame.draw.circle(self.app.screen, self.color, center, SIZE)

        self.increments.rotate(1) if value else self.increments.rotate(-1) #rotate deque de droite à gauche si 1 et gauche à droite si -1, dépend de la case sur laquelle se trouve la fourmi à la position d'avant

        dx, dy = self.increments[0] #le premier élément de deque est donc l'incrément du prochain pas de la fourmi
        self.x = (self.x + dx) % self.app.COLS #pour que la fourmi ne quitte pas les frontières du tableau on prend le reste
        self.y = (self.y + dy) % self.app.ROWS

class App():
    def __init__(self,CELL_SIZE=6,COLOR=(0,0,0),SPEED=120,NUMBER=400):
        pygame.init()
        self.screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
        WIDTH, HEIGHT = self.screen.get_size()
        self.clock = pygame.time.Clock()
        self.screen.fill(COLOR)
        self.speed = SPEED
        self.number = NUMBER

        self.CELL_SIZE = CELL_SIZE
        self.ROWS, self.COLS = HEIGHT//CELL_SIZE, WIDTH//CELL_SIZE
        self.grid = [[0 for col in range(self.COLS)] for row in range(self.ROWS)]

#On crée 2 groupes de fourmis tels que au sein d'un groupe, les fourmis démarrent toutes du même point
        colors1 = [(250, 150, i) for i in range(256)]
        colors2 = [(50, i, 200) for i in range(256)]
        ants1 = [Ant(self, [self.COLS // 3, self.ROWS // 2],
                     choice(colors1)) for i in range(NUMBER//2)]
        ants2 = [Ant(self, [self.COLS - self.COLS // 3, self.ROWS // 2],
                     choice(colors2)) for i in range(NUMBER//2)]
        self.ant = ants1 + ants2

    @staticmethod
    def get_color():
        channel = lambda: randrange(30,220)
        return channel(), channel(), channel()

    def run(self):
        A = 1
        while A == 1:
            [ant.run() for ant in self.ant]

            for event in pygame.event.get() :
                if event.type == pygame.QUIT :
                    exit()
                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE :
                    A = 0

            pygame.display.flip()
            self.clock.tick(self.speed)

if __name__ == '__main__':
    app = App()
    app.run()


# -*- coding : utf-8 -*-
# 创建时间：2019年7月20
# 功能：调试出最佳的识别黑色兴趣区域的参数值
import cv2
import numpy as np

# cap = cv2.VideoCapture(0)  # 获取摄像头图像
# cap = cv2.VideoCapture('../video/test_rectangle_1.mp4')

img = cv2.imread("./1.jpg")
img = cv2.resize(img,(960,600))
hsv_frame = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)

def nothing(x):
    pass

def createbars():
    """
    实现创建六个滑块的作用，分别控制H、S、V的最高值与最低值
    H:色调；S：饱和度；V：亮度
    """
    cv2.createTrackbar("H_l", "image", 0, 180, nothing)
    cv2.createTrackbar("H_h", "image", 0, 180, nothing)
    cv2.createTrackbar("S_l", "image", 0, 255, nothing)
    cv2.createTrackbar("S_h", "image", 0, 255, nothing)
    cv2.createTrackbar("V_l", "image", 0, 255, nothing)
    cv2.createTrackbar("V_h", "image", 0, 255, nothing)

cv2.namedWindow("image")
createbars()  # 创建六个滑块

lower = np.array([0, 0, 0])  # 设置初始值
upper = np.array([0, 0, 0])
while True:
    # ret, frame = cap.read()
    # hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)  # 将图片由BGR颜色空间转化成HSV空间，HSV可以更好地分割颜色图形
    hsv_frame = cv2.GaussianBlur(hsv_frame,(9,9),0)
    lower[0] = cv2.getTrackbarPos("H_l", "image")  # 获取"H_l"滑块的实时值
    upper[0] = cv2.getTrackbarPos("H_h", "image")  # 获取"H_h"滑块的实时值
    lower[1] = cv2.getTrackbarPos("S_l", "image")
    upper[1] = cv2.getTrackbarPos("S_h", "image")
    lower[2] = cv2.getTrackbarPos("V_l", "image")
    upper[2] = cv2.getTrackbarPos("V_h", "image")

    mask = cv2.inRange(hsv_frame, lower, upper)  # cv2.inrange()函数通过设定的最低、最高阈值获得图像的掩膜
    # mask = cv2.inRange(hsv_img, lower, upper)  # cv2.inrange()函数通过设定的最低、最高阈值获得图像的掩膜
    # cv2.imshow("img", frame)
    cv2.imshow("img",img)
    cv2.imshow("mask", mask)
    if cv2.waitKey(1) & 0xff == 27:
        break

cv2.destroyAllWindows()


from django.db import models
app_name = 'example_app'

class GenericMethods():
    @classmethod
    def get_model_urls(cls):
        return {
            'index':    f'{app_name}:{cls.__name__.lower()}_index'
            ,'create':  f'{app_name}:{cls.__name__.lower()}_create'
            ,'detail':  f'{app_name}:{cls.__name__.lower()}_detail'
            ,'update':  f'{app_name}:{cls.__name__.lower()}_update'
            ,'delete':  f'{app_name}:{cls.__name__.lower()}_delete'
            ,'list':    f'{app_name}:{cls.__name__.lower()}_list'
        }

    @classmethod
    def get_model_form_name(cls):
        return f'{cls.__name__}Form'

class GenderExample(models.Model, GenericMethods):
    id          = models.AutoField(primary_key=True)
    uuid        = models.CharField(max_length=50, unique=True)
    description = models.CharField(max_length=50)

    delete_flag = models.BooleanField(default=False)
    created_at  = models.DateTimeField(auto_now_add=True)
    updated_at  = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.uuid

    @classmethod
    def get_model_info(cls):
        return {
            'title': {
                'main':     ''
                ,'index':   'Género - Gestión'
                ,'detail':  'Género - Detalle'
                ,'create':  'Género - Nuevo'
                ,'update':  'Género - Editar'
                ,'delete':  'Género - Borrar'
                ,'list':    'Género - Listado'

            },
            'index': {
                'data_table': {
                    'objects': cls.objects.order_by('-updated_at'),
                    'object_info': [
                        {'label': 'Género'        ,'attr': 'uuid'         ,'exportable': True},
                        {'label': 'Descripción'   ,'attr': 'description'  ,'exportable': True}
                    ]
                }
            },
            'detail': {
                'object_info': [
                    {'label': 'Género: '        ,'attr': 'uuid'},
                    {'label': 'Descripción: '   ,'attr': 'description'}
                ]
            }
        }

class PersonExample(models.Model, GenericMethods):
    id 			= models.AutoField(primary_key=True)
    uuid 		= models.CharField(max_length=50, unique=True)
    firstName 	= models.CharField(max_length=50)
    lastName  	= models.CharField(max_length=50)
    gender      = models.ForeignKey(GenderExample, on_delete=models.CASCADE, null=True)

    delete_flag = models.BooleanField(default=False)
    created_at 	= models.DateTimeField(auto_now_add=True)
    updated_at 	= models.DateTimeField(auto_now=True)

    def __str__(self):
        return 'DNI: ' + self.uuid + ' - ' + self.firstName + ' ' + self.lastName

    @classmethod
    def get_model_info(cls):
        return {
            'title': {
                'main':     ''
                ,'index':   'Personas - Gestión'
                ,'detail':  'Personas - Detalle'
                ,'create':  'Personas - Nueva'
                ,'update':  'Personas - Editar'
                ,'delete':  'Personas - Borrar'
                ,'list':    'Personas - Listado'

            },
            'index': {
                'data_table': {
                    'objects': cls.objects.order_by('-updated_at'),
                    'object_info': [
                        {'label': 'DNI'                     ,'attr': 'uuid'       ,'exportable': True},
                        {'label': 'Nombre '                 ,'attr': 'firstName'  ,'exportable': True},
                        {'label': 'Apellido'                ,'attr': 'lastName'   ,'exportable': True},
                        {'label': 'Género'                  ,'attr': 'gender'     ,'exportable': True},
                        {'label': 'Actualizado en'          ,'attr': 'updated_at' ,'exportable': True}
                    ]
                }
            },
            'detail': {
                'object_info': [
                    {'label': 'DNI'             ,'attr': 'uuid'},
                    {'label': 'Nombre '         ,'attr': 'firstName'},
                    {'label': 'Apellido'        ,'attr': 'lastName'},
                    {'label': 'Género'          ,'attr': 'gender'},
                    {'label': 'Actualizado en'  ,'attr': 'updated_at'},
                ]
            }
        }


import re
from datetime import date, timedelta

from dateutil.relativedelta import relativedelta

from RPA.Robocorp.WorkItems import WorkItems

def get_date_range(months: int) -> tuple:
    """
    Get date range between the last day of current month
    and the first day of X months ago

    Args:
        months: The number of months to look back

    Raises:
        Exception: Invalid month in case of a negative value

    Returns:
        Date range tuple in a string DD/MM/YYYY format
    """
    if months == 0:
        months = 1
    if months < 0:
        raise Exception("Invalid month requested")
    today = date.today()
    start_date = (today - relativedelta(months=months - 1)).replace(day=1)
    end_date = date.today().replace(day=1, month=today.month + 1) - timedelta(days=1)
    start_date = date.strftime(start_date, "%m/%d/%Y")
    end_date = date.strftime(end_date, "%m/%d/%Y")
    return start_date, end_date

def search_currency(string: str) -> bool:
    """
    Search for any currency occurrence in string
    using regex

    Args:
        string: String to search

    Returns:
        Matches or None
    """
    exp = r"(\$[0-9][0-9,]*(.[0-9]+)?)|([0-9][0-9,]*(.[0-9]+)?( dollars| USD))"
    return re.search(exp, string)

def configure():
    config = WorkItems()
    config.get_input_work_item()
    search_phrase = config.get_work_item_variable("search_phrase", "Python")
    section = config.get_work_item_variable("section", "")
    months = int(config.get_work_item_variable("months", 0))
    return search_phrase, section, months


from itertools import combinations
import pathlib
import unittest

PUZZLE_INPUT = "input.txt"
TEST_INPUT = "test-input.txt"

def encoding_error_1(xmas_data: list[int], preamble_len: int) -> int:
    for num in range(preamble_len, len(xmas_data)):
        prev_nums = [xmas_data[n] for n in range(num - preamble_len, num)]
        if not check_sum(prev_nums, xmas_data[num]):
            return xmas_data[num]

def check_sum(nums: list[int], k: int) -> bool:
    return any(sum(pair) == k for pair in combinations(nums, 2))

def encoding_error_2(xmas_data: list[int], preamble_len: int) -> int:
    invalid_num = encoding_error_1(xmas_data, preamble_len)
    con_set = find_contiguous_set(xmas_data, invalid_num)
    return min(con_set) + max(con_set)

def find_contiguous_set(xmas_data: list[int], invalid_num: int) -> list[int]:
    curr_set = []
    for i in range(len(xmas_data)):
        curr_set.append(xmas_data[i])
        curr_sum = sum(curr_set)
        if curr_sum == invalid_num:
            return curr_set
        while curr_sum > invalid_num:
            curr_set.pop(0)
            curr_sum = sum(curr_set)
            if curr_sum == invalid_num:
                return curr_set

def process_input(file_name: str) -> list[int]:
    with (pathlib.Path(__file__).parent / file_name).open() as input_file:
        output = list(map(int, input_file.readlines()))
    # Output: [0, 1, 2, 3,...]
    return output

class Test(unittest.TestCase):
    def test_1(self):
        self.assertEqual(127, encoding_error_1(process_input(TEST_INPUT), 5))
    def test_2(self):
        self.assertEqual(62, encoding_error_2(process_input(TEST_INPUT), 5))

if __name__ == "__main__":
    unittest.main(exit=False)

    pro_input = process_input(PUZZLE_INPUT)
    print(f"Part 1 Answer: {encoding_error_1(pro_input, 25)}")
    print(f"Part 2 Answer: {encoding_error_2(pro_input, 25)}")


import contextlib

from .base_object import BaseObject, BaseObjectTraits
from .block_state.constants import Axis, Direction
from .block_state.transformations import Reflect, Rotate
from .inventory import Inventory

class BlockProperty:
    """Describes default value and possible state values for a block property"""

    id: str
    default: str
    allowed: "list[str]"

    def __init__(
        self, id: str, default_value: str, allowed_values: "list[str]"
    ) -> None:
        self.id = id
        self.default = str(default_value).lower()
        self.allowed = [str(v).lower() for v in allowed_values]

class BlockTraits(BaseObjectTraits):
    """The definition of a block. Describes possible states and behavior in the game."""

    props: "list[BlockProperty]"
    piston_behavior: str
    inventory_slots: int

    def __init__(self, id: str, **kwargs) -> None:
        super().__init__(id)
        self.props = kwargs.get("props", [])
        self.inventory_slots = kwargs.get("inventory_slots", None)
        self.piston_behavior = kwargs.get("piston_behavior", "NORMAL")

    @staticmethod
    def create_from_toml(block_id: str, **kwargs: dict) -> "BlockTraits":
        prop_dict = kwargs.get("properties", {})
        piston_behavior = kwargs.get("piston_behavior", "NORMAL")
        inventory_slots = kwargs.get("inventory_slots", None)

        block_props = [
            BlockProperty(prop_name, state["default"], state["allowed"])
            for prop_name, state in prop_dict.items()
        ]
        return BlockTraits(
            block_id,
            props=block_props,
            piston_behavior=piston_behavior,
            inventory_slots=inventory_slots,
        )

class Block(BaseObject):
    """Represents a block and its state. Restricts state to valid values."""

    _state: "dict[str, str]"
    traits: BlockTraits
    inventory: Inventory

    @property
    def state(self) -> "dict[str, str]":
        """Gets a copy of the block's state."""
        return self._state.copy()

    def __init__(self, traits: BlockTraits, **kwargs) -> None:
        super().__init__(traits)
        if self.traits.inventory_slots is not None:
            self.inventory = Inventory(self.traits.inventory_slots)

        self._state = {x.id: x.default for x in self.traits.props}
        self.set_states(**kwargs)

    def copy(self) -> "Block":
        return Block(self.traits, **self._state)

    def set_state(self, prop_name: str, state_value: str) -> None:
        """Sets the state of a block property.

        Args:
            prop_name (str): the name of the property
            state_value (str): the value to be set"""
        prop_name = str(prop_name).lower()
        block_prop = [p for p in self.traits.props if p.id == prop_name]
        if not any(block_prop):
            raise ValueError(
                f"'{prop_name}' is not a valid property for block {self.id}. Valid properties are: {[p.id for p in self.traits.props]}"
            )
        block_prop = block_prop[0]
        state_value = str(state_value).lower()
        if state_value in block_prop.allowed:
            self._state[prop_name] = state_value
        else:
            raise ValueError(
                f"'{state_value}' is not a valid state. Valid values are: {block_prop.allowed}"
            )

    def set_states(self, **kwargs) -> None:
        """Sets the states of input block property keyword arguments."""
        for prop, value in kwargs.items():
            self.set_state(prop, value)

    def get_state(self, prop_name: str) -> str:
        """Gets the state for a block property.

        Args:
            prop_name (str): the name of the property"""
        prop_name = str(prop_name).lower()
        return self._state.get(prop_name)

    def try_get_state(self, prop_name: str, default: any) -> str:
        """Gets the state for a block property. Return default if not found.

        Args:
            prop_name (str): the name of the property
            default (any): Value to return if block does not have property"""
        prop_name = str(prop_name).lower()
        return self._state.get(prop_name, default)

    def reflect(self, axis: Axis) -> None:
        """Update block state to swap north & south (x), up & down (y), or east & west (z).

        Args:
            axis (Axis): x, y, or z. Flip states along this direction.

        Some blocks do not have true reflections over the y-axis. Beware of:
            rail, torch, banner, carpet, pressure plate, bed, plants, etc.
        """
        axis = Axis(str(axis).lower())
        if not any(self._state):
            return
        self._reflect_props(axis)
        self._reflect_compass_props(axis)

    def rotate(self, axis: Axis, angle: int) -> None:
        """Rotates block about axis by angle.

        Args:
            axis (Axis): x, y, or z. Rotate blocks about this axis.
            angle (int): A multiple of 90

        Some blocks can't truly rotate states for x and z axis rotations of 90 or 270 degrees:
            Beware of banners, doors, torches, rails. slabs, fences, stairs, dripstone, plants, etc.

        Rotation follows the "right hand rule". To visualize:
            Point your right thumb along the positive direction of axis with fingers outstretched. Curl your fingers toward your palm.
            They will naturally curl in the same direction the block will rotate for postitive angles.

        Example:
            If axis is Y and angle is 90, when you look up at the block from below (facing +y), it will appear to rotate clockwise 90 degrees.
        """
        axis = Axis(str(axis).lower())
        angle = angle % 360
        if angle not in [90, 180, 270]:
            raise ValueError("Rotation angle must correspond to 90, 180, or 270")

        if not any(self._state):
            return

        if angle == 180:
            # two reflections are equivalent to a 180 degree rotation.
            for reflection_axis in Axis:
                if axis != reflection_axis:
                    self.reflect(reflection_axis)
        else:
            forwards = angle == 90
            self._rotate_props_90(axis, forwards)
            self._rotate_direction_props_90(axis, forwards)

    def _reflect_props(self, axis: Axis) -> None:
        "Update state from predefined list of reflection mappings."
        source, target = 0, 1

        if axis == Axis.X:
            prop_maps = Reflect.X
        if axis == Axis.Y:
            prop_maps = Reflect.Y
        if axis == Axis.Z:
            prop_maps = Reflect.Z

        for state_name, curr_value in self._state.items():
            if state_name in prop_maps:
                new_value = next(
                    (
                        m[target]
                        for m in prop_maps[state_name]
                        if m[source] == curr_value
                    ),
                    None,
                )
                if new_value is not None:
                    # Some states may not be reflectable .
                    # Attempt the state change and ignore failure.
                    with contextlib.suppress(ValueError):
                        self.set_state(state_name, new_value)

    def _reflect_compass_props(self, axis: Axis) -> None:
        "Swap prop pairs: (east, west),(up, down),(north, south)"
        if (
            axis == Axis.X
            and Direction.EAST in self._state
            and Direction.WEST in self._state
        ):
            self._state[Direction.EAST], self._state[Direction.WEST] = (
                self._state[Direction.WEST],
                self._state[Direction.EAST],
            )
        if (
            axis == Axis.Y
            and Direction.UP in self._state
            and Direction.DOWN in self._state
        ):
            self._state[Direction.UP], self._state[Direction.DOWN] = (
                self._state[Direction.DOWN],
                self._state[Direction.UP],
            )
        if (
            axis == Axis.Z
            and Direction.NORTH in self._state
            and Direction.SOUTH in self._state
        ):
            self._state[Direction.NORTH], self._state[Direction.SOUTH] = (
                self._state[Direction.SOUTH],
                self._state[Direction.NORTH],
            )

    def _rotate_props_90(self, axis: Axis, forwards: bool) -> None:
        "Update props from predefined list of rotation mappings."
        if forwards:
            source, target = 0, 1
        else:
            source, target = 1, 0

        prop_maps = Rotate.get_mappings(
            axis,
            forwards,
            self.try_get_state("face", None),
            self.try_get_state("facing", None),
        )

        for state_name, curr_value in self._state.items():
            if state_name in prop_maps:
                new_value = next(
                    (
                        m[target]
                        for m in prop_maps[state_name]
                        if m[source] == curr_value
                    ),
                    None,
                )
                if new_value is not None:
                    # Some states may not be rotatable.
                    # Attempt the state change and ignore failure.
                    with contextlib.suppress(ValueError):
                        self.set_state(state_name, new_value)

    def _rotate_direction_props_90(self, axis: Axis, forwards: bool) -> None:
        "Rotate props with name: up, down, north, south, east, west"
        if axis == Axis.X:
            self._rotate_direction_props_90_x(forwards)
        if axis == Axis.Y:
            self._rotate_direction_props_90_y(forwards)
        if axis == Axis.Z:
            self._rotate_direction_props_90_z(forwards)

    def _rotate_direction_props_90_x(self, forwards: bool) -> None:
        "Rotate props: up, south, down, north"
        if not all(
            state_name in self._state
            for state_name in [
                Direction.UP,
                Direction.SOUTH,
                Direction.DOWN,
                Direction.NORTH,
            ]
        ):
            return
        if forwards:
            (
                self._state[Direction.SOUTH],
                self._state[Direction.DOWN],
                self._state[Direction.NORTH],
                self._state[Direction.UP],
            ) = (
                self._state[Direction.UP],
                self._state[Direction.SOUTH],
                self._state[Direction.DOWN],
                self._state[Direction.NORTH],
            )
        else:
            (
                self._state[Direction.NORTH],
                self._state[Direction.UP],
                self._state[Direction.SOUTH],
                self._state[Direction.DOWN],
            ) = (
                self._state[Direction.UP],
                self._state[Direction.SOUTH],
                self._state[Direction.DOWN],
                self._state[Direction.NORTH],
            )

    def _rotate_direction_props_90_y(self, forwards: bool) -> None:
        "Rotate props: north, west, south, east"
        if not all(
            state_name in self._state
            for state_name in [
                Direction.NORTH,
                Direction.WEST,
                Direction.SOUTH,
                Direction.EAST,
            ]
        ):
            return
        if forwards:
            (
                self._state[Direction.WEST],
                self._state[Direction.NORTH],
                self._state[Direction.EAST],
                self._state[Direction.SOUTH],
            ) = (
                self._state[Direction.NORTH],
                self._state[Direction.EAST],
                self._state[Direction.SOUTH],
                self._state[Direction.WEST],
            )
        else:
            (
                self._state[Direction.EAST],
                self._state[Direction.SOUTH],
                self._state[Direction.WEST],
                self._state[Direction.NORTH],
            ) = (
                self._state[Direction.NORTH],
                self._state[Direction.EAST],
                self._state[Direction.SOUTH],
                self._state[Direction.WEST],
            )

    def _rotate_direction_props_90_z(self, forwards: bool) -> None:
        "Rotate props: up, west, down, east"
        if not all(
            state_name in self._state
            for state_name in [
                Direction.UP,
                Direction.WEST,
                Direction.DOWN,
                Direction.EAST,
            ]
        ):
            return
        if forwards:
            (
                self._state[Direction.WEST],
                self._state[Direction.DOWN],
                self._state[Direction.EAST],
                self._state[Direction.UP],
            ) = (
                self._state[Direction.UP],
                self._state[Direction.WEST],
                self._state[Direction.DOWN],
                self._state[Direction.EAST],
            )
        else:
            (
                self._state[Direction.EAST],
                self._state[Direction.UP],
                self._state[Direction.WEST],
                self._state[Direction.DOWN],
            ) = (
                self._state[Direction.UP],
                self._state[Direction.WEST],
                self._state[Direction.DOWN],
                self._state[Direction.EAST],
            )


class Solve:
    def __init__(self,n):
        self.counter5 = 0
        self._n = n

    def perform(self):

        if self.is_odd(self._n):
            return 0

        #５割り切れる値まで戻る
        while(True):

            if self._n%5 == 0:
                break
            else:
                self._n -= 2

        # 5の何乗かを考える- > 5^1で割り切れる 5^2でわれる・・・
        t = 10
        while(self._n>=t):
            self.counter5 += self._n // t
            t *= 5

        return self.counter5

    def is_odd(self,n):

        if not n %2 == 0:
            return True
        else:
            return False

        return None

if __name__ == '__main__':

    N = int(input())

    Count = Solve(N)

    ans = Count.perform()

    print(ans)