'''
    Class gameProblem, implements simpleai.search.SearchProblem
'''

from simpleai.search import SearchProblem
# from simpleai.search import breadth_first,depth_first,astar,greedy
import simpleai.search
import math

class GameProblem(SearchProblem):

    # Object attributes, can be accessed in the methods below

    MAP=None
    POSITIONS=None
    INITIAL_STATE=None
    GOAL=None
    CONFIG=None
    AGENT_START=None
    SHOPS=None
    CUSTOMERS=None
    MAXBAGS = 0

    MOVES = ('West','North','East','South') # West: left / East: right

   # --------------- Common functions to a SearchProblem -----------------

    def actions(self, state):
        '''Returns a LIST of the actions that may be executed in this state
        '''
        pos = state[0]
        customer = (state[2][0], state[2][1])
        acciones = []
        if(pos[0]-1 >= 0 and
            not self.getAttribute((pos[0]-1, pos[1]), 'blocked')):
            acciones.append('West')

        if(pos[0]+1 < self.CONFIG['map_size'][0] and
            not self.getAttribute((pos[0]+1, pos[1]), 'blocked')):
            acciones.append('East')

        if(pos[1]-1 >= 0 and
            not self.getAttribute((pos[0], pos[1]-1), 'blocked')):
            acciones.append('North')

        if(pos[1]+1 < self.CONFIG['map_size'][1] and
            not self.getAttribute((pos[0], pos[1]+1), 'blocked')):
            acciones.append('South')

        if(pos[0] == customer[0]  and pos[1] == customer[1]):
            acciones.append('Unload')

        if(pos in self.SHOPS):
            acciones.append('Load')

        return acciones

    def result(self, state, action):
        '''Returns the state reached from this state when the given action is executed
        '''
        next_state = state
        pos = state[0]
        pizzas = state[1]
        customer = list(state[2])

        if(action == 'West'):
            pos = (pos[0]-1, pos[1])
        if(action == 'East'):
            pos = (pos[0]+1, pos[1])

        if(action == 'North'):
            pos = (pos[0], pos[1]-1)
        if(action == 'South'):
            pos = (pos[0], pos[1]+1)

        if(action == 'Unload'):
            order = customer[2]
            if pizzas > 0 and order > 0:
                    # Deliver all available pizzas
                    customer[2] = max(0, order - pizzas)
                    pizzas = max(0, pizzas - order)
        if(action == 'Load' and pizzas < self.MAXBAGS):
            pizzas += 1

        return (pos, pizzas, tuple(customer))

    def is_goal(self, state):
        '''Returns true if state is the final state
        '''
        customer = state[2]
        pos = state[0]
        goal = self.GOAL[0]
        pizzas = state[1]
        allDelivered = customer[2] == 0 and pos[0] == goal[0] and pos[1] == goal[1] and pizzas == 0

        if allDelivered:
            print("Reached goal!")

        return allDelivered

    def cost(self, state, action, state2):
        '''Returns the cost of applying `action` from `state` to `state2`.
           The returned value is a number (integer or floating point).
           By default this function returns `1`.
        '''
        if action in ('West','North','East','South'):
            return self.getAttribute(state2[0], 'cost')
        elif action in ('Load', 'Unload'):
            return 1

        # In case something goes wrong
        return 9223372036854775807

    def heuristic(self, state):
        '''Returns the heuristic for `state`
        '''
        pos = state[0]
        goal = (state[2][0], state[2][1])
        order = state[2][2]
        pizzas = state[1]

        h = 0

        if order > 0:
            distX = math.fabs(pos[0] - goal[0])
            distY = math.fabs(pos[1] - goal[1])

            h = math.sqrt(math.pow(distX, 2) + math.pow(distY, 2))

            h += math.fabs(order - pizzas)
        else:
            distX = math.fabs(pos[0] - goal[0])
            distY = math.fabs(pos[1] - goal[1])

            h = math.sqrt(math.pow(distX, 2) + math.pow(distY, 2))

        return h

    def setup (self):
        '''This method must create the initial state, final state (if desired) and specify the algorithm to be used.
           This values are later stored as globals that are used when calling the search algorithm.
           final state is optional because it is only used inside the is_goal() method

           It also must set the values of the object attributes that the methods need, as for example, self.SHOPS or self.MAXBAGS
        '''

        print('\nMAP: {}\n'.format(self.MAP))
        print('POSITIONS: {}\n'.format(self.POSITIONS))
        print('CONFIG: {}\n'.format(self.CONFIG))

        print('map_size: {}\n'.format(self.CONFIG['map_size']))

        # Initialize self.SHOPS with pizza shops data
        self.SHOPS = self.POSITIONS['pizza']
        customer = ()
        self.MAXBAGS = self.CONFIG['maxBags']

        # Add customer to state with its order size
        for x in xrange(self.CONFIG['map_size'][0]):
            for y in xrange(self.CONFIG['map_size'][1]):
                if self.getAttribute((x,y), 'unload'):
                    customer = (x, y, self.getAttribute((x,y), 'objects'))
                    break

        ''' ((X, Y), pizzas, orders)'''
        initial_state = (self.AGENT_START, 0, customer)
        final_state = (self.AGENT_START, 0, (customer[0], customer[1], 0))
        # breadth_first, depth_first, iterative_limited_depth_first, uniform_cost, greedy, astar
        algorithm = simpleai.search.depth_first

        self.GOAL = final_state

        return initial_state, final_state, algorithm

    def printState (self,state):
        '''Return a string to pretty-print the state '''

        pos = state[0]
        pizzas = state[1]
        customer = state[2]
        pps='\nPosition: {}, {}\nNo. pizzas carried: {}\nCustomer(s) waiting for delivery:\n'.format(pos[0], pos[1], pizzas)
        pps += '  ({}, {}): {} pizza(s)\n'.format(customer[0], customer[1], customer[2])
        return (pps)

    def getPendingRequests (self, state):
        ''' Return the number of pending requests in the given position (0-N).
            MUST return None if the position is not a customer.
            This information is used to show the proper customer image.
        '''
        pos = state[0]
        customer = state[2]
        requests = None

        # Get the number of requests from the state
        if customer[0] == pos[0] and customer[1] == pos[1]:
            requests = customer[2]

        return requests

    # -------------------------------------------------------------- #
    # --------------- DO NOT EDIT BELOW THIS LINE  ----------------- #
    # -------------------------------------------------------------- #

    def getAttribute (self, position, attributeName):
        '''Returns an attribute value for a given position of the map
           position is a tuple (x,y)
           attributeName is a string

           Returns:
               None if the attribute does not exist
               Value of the attribute otherwise
        '''
        tileAttributes=self.MAP[position[0]][position[1]][2]
        if attributeName in tileAttributes.keys():
            return tileAttributes[attributeName]
        else:
            return None

    def getStateData (self,state):
        stateData={}
        pendingItems=self.getPendingRequests(state)
        if pendingItems >= 0:
            stateData['newType']='customer{}'.format(pendingItems)
        return stateData

    # THIS INITIALIZATION FUNCTION HAS TO BE CALLED BEFORE THE SEARCH
    def initializeProblem(self,map,positions,conf,aiBaseName):
        self.MAP=map
        self.POSITIONS=positions
        self.CONFIG=conf
        self.AGENT_START = tuple(conf['agent']['start'])

        initial_state,final_state,algorithm = self.setup()
        if initial_state == False:
            print ('-- INITIALIZATION FAILED')
            return True

        self.INITIAL_STATE=initial_state
        self.GOAL=final_state
        self.ALGORITHM=algorithm
        super(GameProblem,self).__init__(self.INITIAL_STATE)

        print ('-- INITIALIZATION OK')
        return True

    # END initializeProblem


from opMgr import opMgr
from core import core
import sys
import networkx as nx
from math import floor
import random

NUM_OF_CORES = 20
HEAD_PERCENT = 0
TAIL_PERCENT = 0.1
FLOW_MAGNIFY = 1

# GLOBAL VARIABLES
# dict for all ops
op_mgr = opMgr()
# dict for all flows
flowPri = {}
flowDep = {}
# list record the task status
finList = []
# unFinList only keep the computing tasks
unFinList = []
# ready computing tasks
readyList = []
# core set (plus one for flows, index 0)
coreList = []

flow_sum = 0.0
computing_sum = 0.0
# init the dict
def initEnv():
    op_mgr.recover_ops("./vgg16-1_1-128-op.pkl")
    for key in op_mgr.op_dict.keys():
        if (op_mgr.op_dict[key].op_type == 'N'):
            op_mgr.op_dict[key].op_size *= FLOW_MAGNIFY
    global computing_sum
    for key in op_mgr.op_dict.keys():
        if (op_mgr.op_dict[key].op_type == 'C'):
            unFinList.append(key)
            computing_sum += op_mgr.op_dict[key].op_size
    for i in range(0,NUM_OF_CORES + 1):
        newCore = core()
        coreList.append(newCore)
    #print(coreList)
    print("Sum load of %d computing is %f" % (len(unFinList), computing_sum))
    #print(len(unFinList))
    #op_mgr.ops_show()

# assign the priorities for all flows
def assignPri():
    flow_num = 0
    global flow_sum
    for key in op_mgr.op_dict.keys():
        if (op_mgr.op_dict[key].op_type == 'N'):
            flow_num += 1
            flow_sum += op_mgr.op_dict[key].op_size
    print("Sum load of %d flow is %f" % (flow_num, flow_sum))

    topo = []
    for i in range(0, flow_num):
        for key in op_mgr.op_dict.keys():
            if (op_mgr.op_dict[key].op_index == i) and op_mgr.op_dict[key].op_type == 'N':
                topo.append(key)

    print(topo)
    order = topo
    #order.reverse()
    '''
    # find a topo sort of all flows
    # find the depth of each flow
    # 1. build the digraph of this job
    job_dag = nx.DiGraph()
    for key in op_mgr.op_dict.keys():
        job_dag.add_node(key)
    #print(job_dag.number_of_nodes())
    for key in op_mgr.op_dict.keys():
        if len(op_mgr.op_dict[key].op_input) != 0:
            for input_op in op_mgr.op_dict[key].op_input:
                job_dag.add_edge(input_op, key)
    #print(job_dag.number_of_edges())
    topo = []
    for key in list(nx.topological_sort(job_dag)):
        if (op_mgr.op_dict[key].op_type == 'N'):
            topo.append(key)
    #print(len(topo))
    #rint(topo)
    order = topo
    #order.reverse()
    #print(order)
    head_num = floor(len(topo)*HEAD_PERCENT)
    shuffle_1 = order[head_num:]
    random.shuffle(shuffle_1)
    order[head_num:] = shuffle_1
    #print(len(order))

    '''
    # inser the flows into prio
    for i in range(0, len(order)):
        flowPri[str(i+1)] = order[i]
    #print(flowPri)

# get next time
def nextTime(last_min_time):
    min_time = sys.float_info.max
    for i in range(0, NUM_OF_CORES+1):
        if coreList[i].next_time < min_time and coreList[i].next_time > last_min_time:
            min_time = coreList[i].next_time
    #print("@@@@ time %f, %f, %f" % (coreList[0].next_time, coreList[1].next_time, coreList[2].next_time))
    #print(min_time)
    return min_time

# check if a computing task is ready
def checkReady(task_name):
    if (len(op_mgr.op_dict[task_name].op_input) == 0):
        return True
    else:
        for parent_task in op_mgr.op_dict[task_name].op_input:
            if parent_task in finList:
                continue
            else:
                return False
        return True

# print simulation stats
def printStats():
    print("========  Simulation Summary ========")
    for i in range(0, NUM_OF_CORES + 1):
        if (len(coreList[i].task_list) > 0):
            print("CORE %d :" % i)
            print("Task number : %d" % len(coreList[i].task_list))
            print("Finish time : %f" % coreList[i].finish_time)

# begin simulate
def simulate():
    print("========  Simulation Begin ========")
    step = 0
    while (len(unFinList) != 0):
    #while (step <= 194):
        #print(coreList[1].finish_time)
        step = step + 1
        next_time = nextTime(0.0)
        #print("===step %d, time %f" %(step, next_time))
        #print("= 11 time %f, %f, %f" % (coreList[0].next_time, coreList[1].next_time, coreList[2].next_time))
        # initial state
        if next_time == sys.float_info.max:
            # add first flow to the core[0]
            #print("Initial State")
            coreList[0].task_list.append(flowPri['1'])
            coreList[0].time_list.append(op_mgr.op_dict[flowPri['1']].op_size)
            coreList[0].next_time = coreList[0].time_list[-1]
            coreList[0].finish_time = coreList[0].time_list[-1]
            #print(coreList[0].next_time)
            for task in unFinList:
                if checkReady(task) == True:
                    unFinList.remove(task)
                    readyList.append(task)
            #print(len(readyList))
            if len(readyList) <= NUM_OF_CORES:
                #print("enough cores")
                i = 1
                for task in readyList:
                    coreList[i].task_list.append(readyList[0])
                    coreList[i].time_list.append(op_mgr.op_dict[readyList[0]].op_size)
                    coreList[i].next_time = op_mgr.op_dict[readyList[0]].op_size
                    coreList[i].finish_time = coreList[i].next_time
                    readyList.remove(readyList[0])
                    i = i + 1
            else:
                #print("not enough cores")
                for i in range(1, NUM_OF_CORES + 1):
                    #print(i)
                    coreList[i].task_list.append(readyList[0])
                    coreList[i].time_list.append(op_mgr.op_dict[readyList[0]].op_size)
                    coreList[i].next_time = coreList[i].time_list[-1]
                    #print(coreList[i].next_time)
                    coreList[i].finish_time = coreList[i].next_time
                    readyList.remove(readyList[0])
            #print(len(readyList))
        # normal state
        else:
            # get all new finished tasks in all cores
            for i in range(0, NUM_OF_CORES + 1):
                if coreList[i].next_time == next_time:
                    newFinTask = coreList[i].task_list[-1]
                    if newFinTask not in finList:
                        finList.append(newFinTask)
                        #print("%d tasks have finished, new task is %s . " % (len(finList), newFinTask))
            #print(len(finList))
            #print(newFinTask)
            # get ready tasks
            # 1. get ready computing tasks
            for task in unFinList:
                if checkReady(task) == True:
                    unFinList.remove(task)
                    readyList.append(task)
            #print("Num of ready tasks is %d and flow id is %d" % (len(readyList), len(coreList[0].task_list)))
            # assign ready tasks to all cores
            for i in range(0, NUM_OF_CORES + 1):
                # need action at this time
                if coreList[i].next_time == next_time:
                    # for the network core
                    if i == 0:
                        newFlowIndex = len(coreList[0].task_list) + 1
                        if newFlowIndex <= len(flowPri):
                            coreList[0].task_list.append(flowPri[str(newFlowIndex)])
                            new_time = next_time + op_mgr.op_dict[flowPri[str(newFlowIndex)]].op_size
                            coreList[0].time_list.append(new_time)
                            coreList[0].next_time = new_time
                            coreList[0].finish_time = new_time
                    # for computing cores
                    else:
                        if len(readyList) != 0:
                            coreList[i].task_list.append(readyList[0])
                            new_time = next_time + op_mgr.op_dict[readyList[0]].op_size
                            coreList[i].time_list.append(new_time)
                            coreList[i].next_time = new_time
                            readyList.remove(readyList[0])
                            coreList[i].finish_time = next_time
            #print("= time %f, %f, %f" % (coreList[0].next_time, coreList[1].next_time, coreList[2].next_time))
            # if no task is assigned, the next_time need to be reset
            for i in range(0, NUM_OF_CORES + 1):
                if coreList[i].next_time == next_time:
                    time_2 = nextTime(next_time)
                    #print("########### Reset time to %f" % new_time)
                    coreList[i].next_time = time_2
        #print("= 22 time %f, %f, %f" % (coreList[0].next_time, coreList[1].next_time, coreList[2].next_time))

# do the experiments
def run_experiments():
    pass

# main function
def main():
    initEnv()
    assignPri()
    simulate()
    printStats()

if __name__ == "__main__":
    main()


while 1:
	try:
		a,b=map(int, input().split())
		if a==b==0:
			break
		carry=0
		count=0
		while a!=0 or b!=0:
			if a%10+b%10+carry>9:
				carry=1
				count+=1
			a=a//10
			b=b//10

		if count==0:
			print('No carry operation.')
		elif count==1:
			print('1 carry operation.')
		else:
			print(str(count)+' carry operations.')
	except:
		break

# while 1:
# 	try:
# 		a,b=input().split()
# 		if a==b=='0':
# 			break
# 		a=list(map(int, a))
# 		b=list(map(int, b))
# 		if len(a)>len(b):
# 			while len(a)!=len(b):
# 				b.insert(0,0)
# 		else:
# 			while len(a)!=len(b):
# 				a.insert(0,0)
# 		carry=0
# 		count=0
# 		for i in range(len(a)-1,-1,-1):
# 			if a[i]+b[i]+carry>9:
# 				carry=1
# 				count+=1
# 			else:
# 				carry=0
# 		if count==1:
# 			print('1 carry operation.')
# 		elif count==0:
# 			print('No carry operation.')
# 		else:
# 			print(str(count)+' carry operations.')

# 	except:
# 		break

CPE/done/(carry)10035 - Primary Arithmetic.py


# -*- coding: utf-8 -*-

from PySide6.QtCore import QSettings

from scihub_eva.globals.versions import *
from scihub_eva.utils.sys_utils import *

class Preferences(object):
    if is_macos():
        QSettings.setDefaultFormat(QSettings.Format.NativeFormat)
        SETTINGS = QSettings(
            QSettings.NativeFormat,
            QSettings.UserScope,
            ORGANIZATION_DOMAIN,
            APPLICATION_NAME)
    else:
        QSettings.setDefaultFormat(QSettings.Format.IniFormat)
        SETTINGS = QSettings(
            QSettings.IniFormat,
            QSettings.UserScope,
            ORGANIZATION_DOMAIN,
            APPLICATION_NAME)

    def __init__(self):
        super(Preferences, self).__init__()

    @classmethod
    def contains(cls, key):
        return cls.SETTINGS.contains(key)

    @classmethod
    def get(cls, key, type=None):
        return cls.get_or_default(key, None, type=type)

    @classmethod
    def get_or_default(cls, key, default, type=None):
        if type is None:
            return cls.SETTINGS.value(key, default)
        else:
            return cls.SETTINGS.value(key, default, type=type)

    @classmethod
    def set(cls, key, value):
        cls.SETTINGS.setValue(key, value)

    @classmethod
    def remove(cls, key):
        cls.SETTINGS.remove(key)

__all__ = [
    'Preferences'
]


class Vacancies:
    """
    Класс для работы с вакансиями
    """
    def __init__(self, title, salary, experience, description, area, link):
        self.title = title
        self.salary = salary
        self.experience = experience
        self.description = description
        self.area = area
        self.link = link

    def __str__(self):
        """
        Метод для отображения информации об объекте класса для пользователей
        """
        return f'''Вакансия: {self.title}
Зарплата: {self.salary}
Требуемый опыт: {self.experience}
Описание: {self.description}
Город: {self.area}
Ссылка: {self.link}'''

    def __ge__(self, other):
        """
        Метод для сравнения (>=) зарплат двух экземпляров класса
        """
        return self.salary >= other.salary


import gc

# node creation

class Node:

    def __init__(self, data):
        self.data = data
        self.next = None
        self.prev = None

class DoublyLinkedList:

    def __init__(self):
        self.head = None

    # insert node at the front
    def insert_front(self, data):

        # allocate memory for newNode and assign data to newNode
        new_node = Node(data)

        # make newNode as a head
        new_node.next = self.head

        # assign null to prev (prev is already none in the constructore)

        # previous of head (now head is the second node) is newNode
        if self.head is not None:
            self.head.prev = new_node

        # head points to newNode
        self.head = new_node

    # insert a node after a specific node
    def insert_after(self, prev_node, data):

        # check if previous node is null
        if prev_node is None:
            print("previous node cannot be null")
            return

        # allocate memory for newNode and assign data to newNode
        new_node = Node(data)

        # set next of newNode to next of prev node
        new_node.next = prev_node.next

        # set next of prev node to newNode
        prev_node.next = new_node

        # set prev of newNode to the previous node
        new_node.prev = prev_node

        # set prev of newNode's next to newNode
        if new_node.next:
            new_node.next.prev = new_node

    # insert a newNode at the end of the list
    def insert_end(self, data):

        # allocate memory for newNode and assign data to newNode
        new_node = Node(data)

        # assign null to next of newNode (already done in constructor)

        # if the linked list is empty, make the newNode as head node
        if self.head is None:
            self.head = new_node
            return

        # store the head node temporarily (for later use)
        temp = self.head

        # if the linked list is not empty, traverse to the end of the linked list
        while temp.next:
            temp = temp.next

        # now, the last node of the linked list is temp

        # assign next of the last node (temp) to newNode
        temp.next = new_node

        # assign prev of newNode to temp
        new_node.prev = temp

        return

    # print the doubly linked list
    def display_list(self, node):

        while node:
            print(node.data, end="->")
            last = node
            node = node.next


lst=[]
lstodd=[]
lsteven=[]
for i in range(1,101):
    lst.append(i)
print(lst)

for i in lst:
    if(i % 2 == 0):
        lsteven.append(i)
    else:
        lstodd.append(i)

print("Even: ",lsteven)
print("Odd: ",lstodd)


# Given the row index, return the row indexth row of the pascal's triangle recursively.
# This is confusing to do recursively because we are dealing with a list. I guess we start by establishing the base case of [1] and [1, 1] for indices 0 and 1.
# You don't exactly build anything here though, you just have to reference previous.
class Solution:
	def getRow(self, rowIndex: int) -> List[int]:
		memo = {} # to avoid timeout from repeat expensive function call

		def helper(rowIndex: int) -> List[int]:
			# base case
			if rowIndex == 0:
				return [1]
			if rowIndex == 1:
				return [1, 1]

			# build the row like usual but solve the number by recursively checking the value from the one above, might be better if you memoize
			row = []
			for i in range(rowIndex + 1):
				if i == 0 or i == rowIndex:
					row.append(1)
				else:
					if rowIndex - 1 in memo:
						row.append(memo[rowIndex - 1][i - 1] + memo[rowIndex - 1][i])
					else:
						row.append(helper(rowIndex - 1)[i-1] + helper(rowIndex - 1)[i])

			# since we repeated need to check for previous row, use a hash map as a memo to reference that instead of computing the expensive calculation again
			if rowIndex not in memo:
				memo[rowIndex] = row

			return row

		return helper(rowIndex)


from nltk.tree import *
from fastapi import FastAPI
from itertools import *

def flatten_nested_list(lst):
    if not any((type(i) == list) for i in lst):
        return [lst]

    result = []
    for position, item in enumerate(lst):
        if type(item) == list:
            for nested_item in item:
                new_lst = lst[:position] + [nested_item] + lst[position + 1:]
                result += (flatten_nested_list(new_lst))
            break

    return result

# this function relies on the fact, that positions[0] is a list of normal positions of elements we want to combine
def make_combinations(lst, positions):  # [[0, 2], [2, 0]]
    result = []
    for pos in positions:
        new_lst = lst.copy()
        normal_positions = positions[0]
        for i in range(len(pos)):
            new_lst[pos[i]] = lst[normal_positions[i]]
        result.append(new_lst)
    return result

def paraphrases(tree, change_labels=('NP',), conjunctions=('CC', ','), limit=20):
    def paraphrase_children(children):
        child_result = []
        for child in children:
            child_result.append(paraphrases(child))
        return flatten_nested_list(child_result)

    # case - leaf
    if len(tree) == 1:
        return tree

    # case - "NP"
    if tree.label() in change_labels:
        positions_to_change = []
        length = len(tree)
        position = 0
        for position, child in enumerate(tree):
            if child.label() in change_labels:
                positions_to_change.append(position)
            elif child.label() not in conjunctions:
                break

        # any other element is encountered
        if position < length - 1:
            to_add = paraphrase_children(tree)
            result = []
            for comb in to_add:
                if limit != -1 and len(result) >= limit:
                    return result
                result.append(Tree(tree.label(), comb))

        # only elements from change_labels and conjunctions are encountered
        else:
            lst_combinations = make_combinations(tree, list(permutations(positions_to_change)))
            result = []
            for tree_comb in lst_combinations:
                if limit != -1 and len(result) >= limit:
                    return result
                to_add = paraphrase_children(tree_comb)
                for comb in to_add:
                    result.append(Tree(tree.label(), comb))

    else:
        to_add = paraphrase_children(tree)
        result = []
        for combination in to_add:
            if limit != -1 and len(result) >= limit:
                return result
            result.append(Tree(tree.label(), combination))

    return result

def console_test(test_str, test_limit):
    tree = Tree.fromstring(test_str)
    lst_paraphrases = paraphrases(tree, limit=test_limit)
    for iterator in lst_paraphrases:
        print(iterator.leaves())

#console_test('(NP(NP I)(, ,)(NP her)(CC or)(NP him))', 4)

app = FastAPI()

@app.get("/paraphrase")
def read_tree(tree: str, limit: int = 20):
    lst = paraphrases(Tree.fromstring(tree), limit=limit)
    data = [{"tree": var.__str__().replace('\n', ' ')} for var in lst]
    return {"paraphrases": data}


"""

Filename: pca_tryme

Purpose: Test the pca_tools module

Author: John Weaver
Date created: 02.05.18
Possible problems:

"""
# ------------------------------------------------------------------------------
# Standard Packages
# ------------------------------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt

# ------------------------------------------------------------------------------
# Additional Packages
# ------------------------------------------------------------------------------
import pygappy.pca_projection as pca
import pygappy.visualization as pcaplot

# ------------------------------------------------------------------------------
# Parameters
# ------------------------------------------------------------------------------

# Number of eigenspectra to use ( >2 & <<440)
Nspec = 10

# Number of test spectra to generate
Ntry = 100

# Verbosity
verbose = True

# Noise
noise = True

# Norm factor
appnorm = 1.

# PCs to be shown
Nshow = 0

# Display error windows
windows = True
windowsize = 10 # in pixels

# Number of gaps
Ngappy = 10

# Seed
np.random.seed(0)

# ------------------------------------------------------------------------------
# Declarations and Functions
# ------------------------------------------------------------------------------

# Get eigensystem
ewave, espec, emean, evar = pca.eigenbasis()
espec = espec[:Nspec]

# Generate test spectra
test_pcs = np.random.normal(0, 0.5, (Ntry, Nspec))
test_pcs[:, 0] = np.random.normal(-6, 2, Ntry)
test_pcs[:, 1] = np.random.normal(0, 2, Ntry)
test_spec = test_pcs @ espec

# Generate error array
error = np.ones(440)
for i in np.random.randint(0, 440, Ngappy):
    start = i
    end = i + windowsize
    if end >= len(error):
        end = len(error) - 1
    error[start: end] = 0.

# Create figure
fig1, ax1 = plt.subplots(ncols=1, nrows=2)

# ------------------------------------------------------------------------------
# Main Program
# ------------------------------------------------------------------------------

# Loop over test spectra
for i, spec in enumerate(test_spec):

    # Prepare data
    data = emean + spec
    if noise:
        data = data + np.random.normal(0, 0.02, 440)
    data = appnorm * (data / np.mean(data))

    if verbose:
        print(f'\n{i+1}/{Ntry} -----------------------------------')
        x, y, z = test_pcs[i, :3]
        print(f'    first 3 PCs: {x:2.1f} {y:2.1f} {z:2.1f}')

    # Get GappyPCA results
    gpcs, cov = pca.gappy(
        data, error, espec, emean, cov=True, verbose=verbose)

    # Check them
    if verbose:
        x, y, z = gpcs[:3]
        print(
            f'    GappyPCA: {x:2.1f} {-y:2.1f} {z:2.1f}'
        )

    # Plot them
    pcaplot.model(data, ewave, gpcs, espec, ax=ax1[0], error=error, mean=emean,
                   nshow=Nshow, windows=windows)

    # Get NormGappyPCA results
    npcs, norm, cov = pca.normgappy(
        data, error, espec, emean, cov=True, verbose=verbose)

    # Check them
    if verbose:
        x, y, z = npcs[:3]
        print(
            f'    NormGappyPCA: {x:2.1f} {-y:2.1f} {z:2.1f} | N={norm:2.1f}'
        )

    # Plot them
    pcaplot.model(data, ewave, npcs, espec, ax=ax1[1], error=error, mean=emean,
                   norm=norm, nshow=Nshow, windows=windows)

    # ID the axes
    ax1[0].text(
        0.1, 0.1, 'GappyPCA', color='darkred', transform=ax1[0].transAxes)
    ax1[1].text(
        0.1,
        0.1,
        'NormGappyPCA',
        color='royalblue',
        transform=ax1[1].transAxes)

    # Next
    plt.pause(0.001)
    if (i + 1) != Ntry:
        input('\nNext? ')
        ax1[0].clear()
        ax1[1].clear()
    else:
        print('\nEnd.')

# End Script


N = int(input())

numbers = input().split(maxsplit=N)

numbers = [int(number) for number in numbers]
value = max(numbers) + 1

isCorrect = 0

def computeGCD(x, y):

   while(y):
       x, y = y, x % y

   return x

while True:
    for numb in numbers:
        result = computeGCD(value, numb)

        if result == 1:
            isCorrect = 1

    if isCorrect == 1:
        print(value)
        break

    value += 1


from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from django.views import defaults as default_views
from rest_framework_jwt.views import obtain_jwt_token
from space_manager import views

urlpatterns = [
    # Django Admin, use {% url 'admin:index' %}
    url(settings.ADMIN_URL, admin.site.urls),

    # User management
    url(r'^rest-auth/', include('rest_auth.urls')),
    url(r'^rest-auth/registration/', include('rest_auth.registration.urls')),
    url(r'^seats/', include('space_manager.seats.urls', namespace='seats')),
    url(r'^rooms/', include('space_manager.rooms.urls', namespace='rooms')),
    url(r'^users/', include('space_manager.users.urls', namespace='users')),
    url(r'^cabinets/',
        include('space_manager.cabinets.urls', namespace='cabinets')),
    url(r'^membership/',
        include('space_manager.membership.urls', namespace='membership')),
    url(r'^branch/',
        include('space_manager.branches.urls', namespace='branches')),
    url(r'^payment/',
        include('space_manager.payment.urls', namespace='payments')),
    url(r'^qrcodes/', include(
        'space_manager.qrcodes.urls', namespace='qrcodes')),
    # url(r'^accounts/', include('allauth.urls')),
    # url(r'^', views.ReactAppView.as_view()),

    # Your stuff: custom urls includes go here
] + static(
    settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

# urlpatterns += [
#     url(r'^', views.ReactAppView.as_view()),
# ]
if settings.DEBUG:
    # This allows the error pages to be debugged during development, just visit
    # these url in browser to see how these error pages look like.
    urlpatterns += [
        url(r'^400/$',
            default_views.bad_request,
            kwargs={
                'exception': Exception('Bad Request!')
            }),
        url(r'^403/$',
            default_views.permission_denied,
            kwargs={
                'exception': Exception('Permission Denied')
            }),
        url(r'^404/$',
            default_views.page_not_found,
            kwargs={
                'exception': Exception('Page not Found')
            }),
        url(r'^500/$', default_views.server_error),
    ]
    if 'debug_toolbar' in settings.INSTALLED_APPS:
        import debug_toolbar
        urlpatterns = [
            url(r'^__debug__/', include(debug_toolbar.urls)),
        ] + urlpatterns


#指先を検出するプログラム
import cv2
import numpy as np
import sys
from scipy.spatial import distance
import time

def main():
    # 入力画像の取得
    t1 = time.time()
    im = cv2.imread("%s"%param[1])
    height,width = im.shape[:2]
    gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
    gray = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
    cv2.rectangle(gray, (0, height-200), (width-1, height-1), (0, 0, 0), -1)

    label = cv2.connectedComponentsWithStats(gray)
    # ブロブ情報を項目別に抽出
    n = label[0] - 1
    data = np.delete(label[2], 0, 0)
    center = np.delete(label[3], 0, 0)
    max_index = np.argsort(data[:,4])[::-1][0] + 1
    #print("最大面積のラベル番号", max_index)
    x_center = int(center[max_index -1][0])
    y_center = int(center[max_index -1][1])

    dst = label[1]
    list = []
    list2 = []
    #a = np.array(center[max_index -1])
    a = np.array([y_center,x_center])
    print("1a")

    for y in range(height):
        for x in range(width):
            if dst[y][x] == max_index:
                b = np.array([y,x])
                list.append(distance.euclidean(a,b))

    #ave = np.mean(list)
    ave = np.average(list)
    print("1b")

    for y in range(height):
        for x in range(width):
            if dst[y][x] == max_index:
                c = np.array([y,x])
                #dis = np.linalg.norm(a-c)
                dis = distance.euclidean(a,c)
                list2.append(dis - ave)
                #print(dis - ave)
                if (dis - ave) < 1000:
                    im[y][x] = (255,255,0)

    print("1c")
    ave2 = np.average(list2)
    su = np.sum(list2)

    print("中心との距離の平均",ave)
    print("偏差の平均",ave2)
    print("偏差の和",su)

    """
    # ラベルの個数nだけ色を用意
    print("ブロブの個数:", n)
    print("各ブロブの外接矩形の左上x座標", data[:,0])
    print("各ブロブの外接矩形の左上y座標", data[:,1])
    print("各ブロブの外接矩形の幅", data[:,2])
    print("各ブロブの外接矩形の高さ", data[:,3])
    print("各ブロブの面積", data[:,4])
    print("中心座標:\n",center[max_index - 1])
    """

    cv2.circle(im,(x_center,y_center), 20,(0,0,255),-1)
    cv2.imwrite("yubisaki.jpg", im)
    t2 = time.time()
    elapsed_time = t2-t1
    print(f"経過時間：{elapsed_time}")

if __name__ == '__main__':
    param = sys.argv
    main()


import csv
import datetime
import os
import re

import titlecase
from beancount.core import amount
from beancount.core import data
from beancount.core import flags
from beancount.core import number as beancount_number
from beancount.ingest import importer

_COLUMN_DATE = 'Posting Date'
_COLUMN_PAYEE = 'Description'
_COLUMN_AMOUNT = 'Amount'

_FILENAME_PATTERN = re.compile(r'Chase(\d{4})_Activity_[\d_]{8}.*\.CSV',
                               re.IGNORECASE)

class CheckingImporter(importer.ImporterProtocol):

    def __init__(self,
                 account,
                 lastfour=None,
                 currency='USD',
                 account_patterns=None):
        self._account = account
        self._last_four_account_digits = lastfour
        self._currency = currency
        self._account_patterns = []
        if account_patterns:
            for pattern, account_name in account_patterns:
                self._account_patterns.append(
                    (re.compile(pattern, flags=re.IGNORECASE), account_name))

    def _parse_amount(self, amount_raw):
        return amount.Amount(beancount_number.D(amount_raw), self._currency)

    def file_date(self, file):
        return max(map(lambda x: x.date, self.extract(file)))

    def file_account(self, _):
        return self._account

    def identify(self, file):
        match = _FILENAME_PATTERN.match(os.path.basename(file.name))
        if not match:
            return False
        return self._last_four_account_digits == match.group(1)

    def extract(self, f):
        transactions = []

        with open(f.name, encoding='utf-8') as csv_file:
            for index, row in enumerate(csv.DictReader(csv_file)):
                metadata = data.new_metadata(f.name, index)
                transaction = self._extract_transaction_from_row(row, metadata)
                if not transaction:
                    continue
                transactions.append(transaction)

        return transactions

    def _extract_transaction_from_row(self, row, metadata):
        transaction_date = datetime.datetime.strptime(row[_COLUMN_DATE],
                                                      '%m/%d/%Y').date()
        payee, transaction_description = _parse_description(row[_COLUMN_PAYEE])
        if payee:
            payee = titlecase.titlecase(payee)
        else:
            raise ValueError(f'failed to parse {row[_COLUMN_PAYEE]}')
        if transaction_description:
            narration = titlecase.titlecase(transaction_description)
        if row[_COLUMN_AMOUNT]:
            transaction_amount = self._parse_amount(row[_COLUMN_AMOUNT])
        else:
            return None  # 0 dollar transaction

        if transaction_amount == amount.Amount(beancount_number.D(0),
                                               self._currency):
            return None

        postings = [
            data.Posting(account=self._account,
                         units=transaction_amount,
                         cost=None,
                         price=None,
                         flag=None,
                         meta=None)
        ]
        for pattern, account_name in self._account_patterns:
            if pattern.search(payee) or pattern.search(
                    narration) or pattern.search(payee + narration):
                postings.append(
                    data.Posting(account=account_name,
                                 units=-transaction_amount,
                                 cost=None,
                                 price=None,
                                 flag=None,
                                 meta=None))
                break

        # For some reason, pylint thinks data.Transactions is not callable.
        # pylint: disable=not-callable
        return data.Transaction(
            meta=metadata,
            date=transaction_date,
            flag=flags.FLAG_OKAY,
            payee=payee,
            narration=narration,
            tags=data.EMPTY_SET,
            links=data.EMPTY_SET,
            postings=postings,
        )

_DESCRIPTION_PATTERN = re.compile(
    # pylint: disable=line-too-long
    r'ORIG CO NAME:(.+?)\s*ORIG ID:.*DESC DATE:.*CO ENTRY DESCR:(.+?)\s*SEC:.*TRACE#:.*EED:.*',
    re.IGNORECASE)

_OUTBOUND_TRANSFER_PATTERN = re.compile(
    r'Online Transfer \d+ to (.+?)\s*transaction #', re.IGNORECASE)

_INBOUND_TRANSFER_PATTERN = re.compile(
    r'Online Transfer \d+ from (.+?)\s*transaction #', re.IGNORECASE)

def _parse_description(description):
    match = _DESCRIPTION_PATTERN.search(description)
    if match:
        return match.group(1), match.group(2)
    match = _OUTBOUND_TRANSFER_PATTERN.search(description)
    if match:
        return match.group(1), description
    match = _INBOUND_TRANSFER_PATTERN.search(description)
    if match:
        return match.group(1), description
    return None, None


from datetime import datetime
import sqlite3 as sql
con = sql.connect("bank_data.db")
cur = con.cursor()
import traceback

global account_no
global cust_id

def change_addr():
    address = input("Enter address : ")
    cur.execute('UPDATE customer SET address = (?) WHERE cust_id = (?);',(address, cust_id))
    print("Address successfully changed\n")
    con.commit()

def open_account():
    try:
        li=["Savings Account","Current Account","Fixed Deposit Account"]
        for n,val in enumerate(li):
            print(n+1,val)
        amount = int(input("Enter Amount to be deposited in the FD : "))
        if amount > 0 and not amount%100:
            pass
        else:
            print("Enter amount in multiples of 1000")
            exit()
        term = int(input("Enter the term for the FD(in terms of years): "))
        if (not term > 1) :
            print("Enter term period greater than 12 months")
            exit()
        cur.execute('INSERT INTO FD_table(account_no,amount,term) VALUES(?,?,?);',(account_no,amount,term))
        con.commit()
        value = cur.execute("SELECT fd_no FROM FD_table order by fd_no desc limit 1;")
        for row in value:
            fd_no = row[0]
            print("Your fixed deposit number is :", fd_no)

        value=cur.execute("SELECT * FROM FD_table WHERE account_no=(?);",(account_no,))
        for row in value:
            print("FD number: ",row[0])
            print("Customer ID: ",row[1])
            print("Amount: ", row[2])
            print("Term: ", row[3])

    except Exception as e:
        print(e)
        traceback.print_exc()

def deposit():
    amount = int(input("Enter Amount to be deposited : "))
    value = cur.execute('SELECT balance FROM accounts WHERE account_no = (?);', (account_no,))
    for row in value:
        bal=row[0]

    bal = bal + amount
    print("New balance is : ",bal)
    cur.execute('UPDATE accounts SET balance = (?) WHERE account_no = (?);', (bal, account_no))
    con.commit()
    cur.execute('INSERT INTO logTable(cust_id,account_no,deposit,withdraw,transfer,balance) VALUES (?,?,?,?,?,?);', (account_no,account_no,amount,'NULL','NULL', bal))
    con.commit()
    value = cur.execute('SELECT transaction_id FROM logTable ORDER BY transaction_id DESC limit 1;')
    for row in value:
        print("Your transaction ID is : ", row[0])

def withdraw():
    amount = int(input("Enter Amount to be withdrawl : "))
    value = cur.execute('SELECT balance FROM accounts WHERE account_no = (?);', (account_no,))
    for row in value:
        bal = row[0]

    if (bal - amount < 0):
        print('Not enough balance')
        exit()
    else:
        bal = bal-amount
        print("New balance is : ",bal)
        cur.execute('UPDATE accounts SET balance = (?) WHERE account_no = (?);', (bal, account_no))
        cur.execute('INSERT INTO logTable(cust_id,account_no,deposit,withdraw,transfer,balance) VALUES (?,?,?,?,?,?);',(account_no, account_no,"NULL", amount,"NULL", bal))
        con.commit()
        value = cur.execute('SELECT transaction_id FROM logTable ORDER BY transaction_id DESC limit 1;')
        for row in value:
            print("Your transaction ID is : ", row[0])

def get_statement():
    value = cur.execute('SELECT account_no, transaction_id, deposit, withdraw, transfer, balance FROM logTable WHERE account_no = (?);',(account_no,))
    for row in value:
        print("Account_no",row[0])
        print("Transaction_id",row[1])
        print("Deposit", row[2])
        print("Withdraw", row[3])
        print("Transfer", row[4])
        print("Balance", row[5])

def transfer_money():
    acc2 = int(input('Enter Account No. to transfer money : '))
    a = cur.execute('SELECT account_no FROM accounts WHERE account_no = (?);', (acc2,))
    value = cur.execute('SELECT balance FROM accounts WHERE account_no = (?);', (acc2,))
    for row in value:
        bal = row[0]
        print(bal)
    if(a):
        amount = int(input('Enter amount to Transfer : '))
        value = cur.execute('SELECT balance FROM accounts WHERE account_no = (?);', (account_no,))
        for row in value:
            my = row[0]

        if ((my - amount) < 0):
            print('Not enough balance')
        else:
            my = my - amount
            bal = bal + amount
            cur.execute('UPDATE accounts SET balance = (?) WHERE account_no = (?);', (my, account_no))
            cur.execute('INSERT INTO logTable(cust_id,account_no,deposit,withdraw,transfer,balance) VALUES (?,?,?,?,?,?);',(account_no,account_no,"NULL","NULL",amount,my))
            cur.execute('UPDATE accounts SET balance = (?) WHERE account_no = (?);', (bal, acc2))
            print("Transfer Complete")
            con.commit()
            value = cur.execute('SELECT transaction_id FROM logTable ORDER BY transaction_id DESC limit:1;')
            for row in value:
                print("Your trabsaction ID is : ", row[0])
    else:
        exit()

def close_account():
    cur.execute('UPDATE accounts SET account_status=(?), account_closing_date =CURRENT_TIMESTAMP WHERE account_no = (?);', ("closed", account_no,))
    con.commit()
    print("Account closed")

def get_loan():
    amount = int(input("Enter Amount of loan to be issued : "))
    if(amount>0 and not amount%100):
        pass
    else:
        print("Enter amount in multiples of 1000")
        exit()
    term = int(input("Enter the term of the loan(in terms of years): "))
    cur.execute('INSERT INTO loan_table(account_no,amount,term) VALUES(?,?,?);',(account_no,amount,term))
    con.commit()
    value = cur.execute("SELECT loan_id FROM loan_table order by loan_id desc limit 1;")
    for row in value:
        loan_id = row[0]
        print("Your Loan ID is :", loan_id)
    value = cur.execute("SELECT * FROM loan_table WHERE account_no=(?);",(account_no,))
    for row in value:
        print("Loan number: ",row[0])
        print("Customer ID: ",row[1])
        print("Amount: ", row[2])
        print("Term: ", row[3])

def logout():
    print("logging out")
    exit()

def profile_func(acc):
    global account_no
    account_no = acc
    global cust_id
    cust_id = acc
    li = ["Address Change","Open New Acccount", "Money Deposit","Money Withdrawal", "Transfer Money","Print Statement","Account Closure","Avail Loan","Customer Logout"]
    for n,val in enumerate(li):
        print(n+1,val)
    choice_dict={
                    1:change_addr,
                    2:open_account,
                    3:deposit,
                    4:withdraw,
                    5:transfer_money,
                    6:get_statement,
                    7:close_account,
                    8:get_loan,
                    9:logout
                }
    choice = int(input("Enter your choice : "))
    choice_dict[choice]()


from opensearchpy import OpenSearch

host = 'localhost'
port = 9200
auth = ('admin', 'admin') # For testing only. Don't store credentials in code.
# ca_certs_path = '/full/path/to/root-ca.pem' # Provide a CA bundle if you use intermediate CAs with your root CA.

# Optional client certificates if you don't want to use HTTP basic authentication.
# client_cert_path = '/full/path/to/client.pem'
# client_key_path = '/full/path/to/client-key.pem'

# Create the client with SSL/TLS enabled, but hostname verification disabled.
client = OpenSearch(
    hosts = [{'host': host, 'port': port}],
    http_compress = True, # enables gzip compression for request bodies
    http_auth = auth,
    # client_cert = client_cert_path,
    # client_key = client_key_path,
    use_ssl = True,
    verify_certs = False,
    ssl_assert_hostname = False,
    ssl_show_warn = False,
    # ca_certs = ca_certs_path
)

# Create an index with non-default settings.
index_name = 'qa_index_384'

# document = {
#   'Q_text':'abc',
#   'Q_vec':[1,2,3,4],
#   'Ans':'ABC',
# }

from sentence_transformers import SentenceTransformer, util
model = SentenceTransformer('paraphrase-MiniLM-L6-v2')
embedding = model.encode("朋友圈信息流", convert_to_tensor=True)
Q_vec = embedding.tolist()
document = {
  'Q_text':"朋友圈信息流",
  'Q_vec':Q_vec,
  'Ans':'ABC',
}
print(len(Q_vec))
id = '20'

response = client.index(
    index = index_name,
    body = document,
    id = id,
    refresh = True
)

print('\nAdding document:')
print(response)


import os
import time as tm
import shutil

def getAllUserVideos(user_name):
    videos_id = list(())
    video_id = input("Enter video id: ")
    while video_id != "-1":
        videos_id.append(video_id)
        video_id = input("Enter video id: ")
    return videos_id

def fileToList(file_name):
    list_name = list(())
    f = open(file_name, "r")
    list_name = f.read().splitlines()
    f.close()
    return list_name

def downloadVideo(video_id, user_name):
    command = "youtube-dl.exe https://www.tiktok.com/@" + user_name + "/video/" + video_id + " -o \"" + user_name + "/%(upload_date)s - %(title)s - %(id)s - (%(duration)ss) [%(resolution)s].%(ext)s\""
    os.system(command)
    if not os.path.exists(user_name):
        os.system(command)
        if not os.path.exists(user_name):
            os.system(command)

def moverVideo(user_name):
    file_name = os.listdir(user_name)
    source = 'E:/Downloads/Entites/tiktokdownload/' + user_name + '/' + file_name[0]
    folder = 'E:/Downloads/Entites/tiktok/' + user_name
    destination = 'E:/Downloads/Entites/tiktok/' + user_name + '/' + file_name[0]
    if not os.path.exists(folder):
        os.mkdir(folder)
    shutil.move(source, destination)
    os.rmdir(user_name)

def downloadUserVideos(videos_to_download, user_name):

    for video_id in videos_to_download:
        downloadVideo(video_id, user_name)
        if os.path.exists(user_name):
            moverVideo(user_name)

def user(user_name):
    all_videos_id = getAllUserVideos(user_name)

    downloadUserVideos(all_videos_id, user_name)

def main():
    user_name = input("Enter username: ")
    user(user_name)

main()


'''
0-1背包问题：
徒步旅行者，可携带物品险种为a公斤，右n种物品可选择装入包中，
已知每种物品的重量及其使用价值，问此人如何选择携带的物品，使使用价值最大？
类似问题：
工厂下料问题、运输过程中的货物装载问题、人造卫星内物品装载问题
'''
# 1. 通过回溯法求解0-1背包问题
info = [
    [3,8],
    [2,5],
    [5,12]
]
mem = {}
def search(depth,rest):
    # 放还是不放，决策
    if "{}_{}".format(depth,rest) in mem:
        return mem["{}_{}".format(depth,rest)]
    if depth == 2:
        data = info[depth][1] if rest >= info[depth][0] else 0
    else:
        # 1.分任务
        values = []
        values.append(search(depth+1,rest))
        if rest >= info[depth][0]:
            values.append(search(depth+1,rest-info[depth][0]) + info[depth][1])
        # 2.选最大
        data = max(values)
    if "{}_{}".format(depth,rest) not in mem:
        mem["{}_{}".format(depth, rest)] = data
    return data

if __name__ == "__main__":
    print(search(0,5))
    print(mem)


from modules.menu import Menu
from modules.pizza import Pizza

menu = Menu()

def saveMenu(file_path, menu):
    ##sauvegarder le menu dans le fichier file_path
    fichier = open(file_path, 'w')
    fichier.write("menu :\n")
    fichier.write(str(menu))
    fichier.close()

def getMenuFromFile(file_path):
    ##recuperer le menu du fichier file_path
    print("getMenu")

def helpAdmin():
    print(""" Help :
				- addPizza pizzaName (ajouter une pizza au menu)
				- addIngredient pizzaName ingredient (ajouter un ingrédient à une pizza)
				- addPrix pizzaName prix (ajouter un prix à une pizza)
				- addQte pizzaName qte (ajouter une qte à une pizza)
				- exit (sortir du menu admin)
		""")

def addPizza(option):
    global menu
    _, pizzaName = option.split(" ")
    menu.addPizza(Pizza(pizzaName))

def addIngredient(option):
    global menu
    _, pizzaname, ingredient = option.split(" ")
    menu.getPizza(pizzaname).addIngredient(ingredient)

def addPrix(option):
    global menu
    _, pizzaname, prix = option.split(" ")
    menu.getPizza(pizzaname).fixerPrix(int(prix))

def addQte(option):
    global menu
    _, pizzaname, quantite = option.split(" ")
    menu.getPizza(pizzaname).addQuantite(int(quantite))

def helpClient():
    print(""" Help :
				- menu (afficher le menu)
				- manger pizzaName (manger une pizza)
				- exit (sortir du restaurant)
			""")

def displayMenu():
    global menu
    print(menu)

def manger(action):
    global menu
    _, pizza = action.split(" ")
    if menu.getPizza(pizza).getQuantite()>0:
        print("bonap")
        menu.getPizza(pizza).addQuantite(-1)
    else:
        print("pizza non disponible")

while True:
    login = input("login : ")
    if login == "exit":
        break
    if login == "admin":
        while True:
            option = input("choisir une option : ")
            if option == "exit":
                break
            if option == "help":
                helpAdmin()
            # Traiter les commandes admin
            if option.startswith("addPizza"):
                addPizza(option)
            if option.startswith("addIngredient"):
                addIngredient(option)
            if option.startswith("addPrix"):
                addPrix(option)
            if option.startswith("addQte"):
                addQte(option)
            if option.startswith("saveMenu"):
                saveMenu("./menu.txt", menu)

    if login == "client":
        while True:
            action = input("que voulez vous faire : ")
            if action == "exit":
                print("Au revoir")
                break
            if action == "help":
                helpClient()
            if action == "menu":
                displayMenu()
            if action.startswith("manger"):
                manger(action)

        # Traiter les commandes client


import random

def gen_suit():
    suit = random.randint(1, 4)
    if suit == 1:
        return "Clubs"
    if suit == 2:
        return "Diamonds"
    if suit == 3:
        return "Hearts"
    if suit == 4:
        return "Spades"
    return "Whoops!"

def gen_rank():
    rank = random.randint(1, 13)
    if rank == 1:
        return "Ace"
    if rank == 11:
        return "Jack"
    if rank == 12:
        return "Queen"
    if rank == 13:
        return "King"
    return str(rank)

def draw_card():
    return gen_rank() + " of " + gen_suit()

def test():
    n = 0
    while n < 10:
        print(draw_card())
        n += 1

def value(card):
    position = card.find(" ")
    rank = card[0:position]
    # print( rank )
    if rank == "Ace":
        return 11
    if rank == "King" or rank == "Queen" or rank == "Jack":
        return 10
    return int(rank)

def hand():
    card1 = draw_card()
    card2 = draw_card()
    print(card1, ", ", card2, sep="")
    return value(card1), value(card2)

def hit_me():
    card = value(draw_card())
    print("The draw card is", card)
    return card

def the_game():
    card1, card2 = hand()
    print(card1, card2)
    total = card1 + card2
    if total <= 16:
        print("Hit me!")
        total += hit_me()
    elif 16 < total < 21:
        print("Don't hit me")
    elif total == 21:
        print("Blackjack!")

    print("The total is ", total)
    if total > 21:
        print("You've lost!")

the_game()


class School:
    def __init__(self,name,address) -> None:
        self.name = name
        self.address = address
        self.classrooms = {}
        self.teachers = {}
    def add_classroom(self,classroom):
        self.classrooms[classroom.name] = classroom
    def add_teacher(self,subject,teacher):
        if subject in self.teachers:
            self.teachers[subject] = teacher
        else:
            print(f'no subject named {subject}')
    def student_admission(self,student):
        className= student.classroom.name

        if className in self.classrooms:
            self.classrooms[className].add_student(student)
        else:
            print(f'no classroom as named {className}')
    def __repr__(self) -> str:
        for key,value in self.classrooms.items():
            print(key)
        eight = self.classrooms['eight']
        for student in eight.students:
            print(student.name)
        for subject in eight.subjects:
            print(subject.name,subject.teacher.name)
        for student in eight.students:
            for key,value in student.marks.items():
                print(student.name,key,value,student.subject_grade[key])
        return ''
    @staticmethod
    def calculate_grade(marks):
        if 80 <= marks <= 100:
            return 'A+'
        elif 70 <= marks < 80:
            return 'A'
        elif 60 <= marks < 70:
            return 'A-'
        elif 50 <= marks < 60:
            return 'B'
        elif 40 <= marks < 50:
            return 'C'
        elif 33 <= marks < 40:
            return 'D'
        else:
            return 'F'
    @staticmethod
    def grade_to_value(grade):
        grade_map = {"A+":5.00,"A":4.00,"A-":3.50,"B":3.00,"C":2.00,"D":1.00,"F":0.00}
        return grade_map[grade]
    @staticmethod
    def value_to_grade(value):
        if 4.5 <= value <= 5.00:
            return 'A+'
        elif 3.5 <= value < 4.5:
            return 'A'
        elif 3.0 <= value < 3.5:
            return 'A-'
        elif 2.5 <= value < 3.0:
            return 'B'
        elif 2.0 <= value < 2.5:
            return 'C'
        elif 1.0 <= value < 2.0:
            return 'D'
        else:
            return 'F'


from django.db.models import Q, Sum, F, Func, Max, Min

from rest_framework import filters
from rest_framework import viewsets
from rest_framework.response import Response

from time_tracker.models import TimeReport
from time_tracker.serializers import TimeReportSerializer
from time_tracker.permissions import TimeReportPermission
from time_tracker.filters.time_report_filter import TimeReportFilter
from time_tracker.serializers import TimeReportProfileSerializer
from time_tracker.serializers import TimeReportProjectSerializer
from django_filters.rest_framework import DjangoFilterBackend

class TimeReportViewSet(viewsets.ModelViewSet):
    """
        Working with TimeReport data

        retrieve:
        Return the given time report.

        list:
        Return a list of all the existing time report.

        create:
        Create a new time report.

        update:
        Create a new time report instance.

        partial_update:
        Update an existing time report

        destroy:
        Delete an existing time report

    """

    queryset = TimeReport.objects.all()
    serializer_class = TimeReportSerializer
    permission_classes = (TimeReportPermission,)
    filter_backends = (DjangoFilterBackend, filters.OrderingFilter)
    filter_class = TimeReportFilter
    ordering_fields = ('date', 'id')
    ordering = ('-date', '-id')

    def get_queryset(self):
        user = self.request.user
        time_report = TimeReport.objects.active_projects(user, seconds__gt=0)
        return time_report

    def get_profiles_reports(self, request):
        """
        Get total profiles hours for given filter
        """
        user = self.request.user
        time_report = TimeReportFilter(request.GET, queryset=TimeReport.objects.total_time_by(user, 'profile', 'profile__first_name'))

        serializer = TimeReportProfileSerializer(time_report.qs, many=True)
        return Response(serializer.data)

    def get_projects_reports(self, request):
        """
        Get total projects hours for given filter
        """
        user = self.request.user
        time_report = TimeReportFilter(request.GET, queryset=TimeReport.objects.total_time_by(user, 'project', 'project__name'))

        serializer = TimeReportProjectSerializer(time_report.qs, many=True)
        return Response(serializer.data)

    def get_total_hours(self, request):
        """
        Get total hours for given filter
        """
        user = self.request.user
        time_report = TimeReportFilter(request.GET, queryset=TimeReport.objects.active_projects(user, seconds__gt=0))
        time_report = time_report.qs.aggregate(total_seconds=Sum('seconds'))
        time_report['total_hours'] = TimeReport.sec_to_hours(time_report['total_seconds'])
        return Response(time_report)


'''
Given the root of a binary tree, collect a tree's nodes as if you were doing this:
Collect all the leaf nodes.
Remove all the leaf nodes.
Repeat until the tree is empty.

Example 1:
Input: root = [1,2,3,4,5]
Output: [[4,5,3],[2],[1]]
Explanation:
[[3,5,4],[2],[1]] and [[3,4,5],[2],[1]] are also considered correct answers since per each level it does not matter the order on which elements are returned.
'''
'''
Time:O(n)
Space:O(n)
'''
class Solution:
    def findLeaves(self, root: TreeNode) -> List[List[int]]:
        res = []
        def dfs(node):
            if not node:
                return -1
            level = max(dfs(node.left), dfs(node.right))+1
            if len(res)<=level:
                res.append([])
            res[level].append(node.val)
            return level

        dfs(root)
        return res


import argparse
import sys

from absl import app

from google.protobuf import message
from google.protobuf import text_format
from tensorflow.core.framework import graph_pb2
from tensorflow.core.protobuf import config_pb2
from tensorflow.core.protobuf import meta_graph_pb2
from tensorflow.core.protobuf import saved_model_pb2
from tensorflow.python.framework import importer
from tensorflow.python.framework import ops
from tensorflow.python.grappler import cost_analyzer
from tensorflow.python.grappler import tf_optimizer
from tensorflow.python.platform import gfile
from tensorflow.python.training import saver

def get_metagraph():
  """Constructs and returns a MetaGraphDef from the input file."""
  with gfile.GFile(FLAGS.input) as input_file:
    input_data = input_file.read()
    try:
      saved_model = saved_model_pb2.SavedModel()
      text_format.Merge(input_data, saved_model)
      meta_graph = saved_model.meta_graphs[0]
    except text_format.ParseError:
      try:
        saved_model.ParseFromString(input_data)
        meta_graph = saved_model.meta_graphs[0]
      except message.DecodeError:
        try:
          meta_graph = meta_graph_pb2.MetaGraphDef()
          text_format.Merge(input_data, meta_graph)
        except text_format.ParseError:
          try:
            meta_graph.ParseFromString(input_data)
          except message.DecodeError:
            try:
              graph_def = graph_pb2.GraphDef()
              text_format.Merge(input_data, graph_def)
            except text_format.ParseError:
              try:
                graph_def.ParseFromString(input_data)
              except message.DecodeError:
                raise ValueError(f"Invalid input file: {FLAGS.input}.")
            importer.import_graph_def(graph_def, name="")
            graph = ops.get_default_graph()
            meta_graph = saver.export_meta_graph(
                graph_def=graph.as_graph_def(), graph=graph)
  if FLAGS.fetch is not None:
    fetch_collection = meta_graph_pb2.CollectionDef()
    for fetch in FLAGS.fetch.split(","):
      fetch_collection.node_list.value.append(fetch)
    meta_graph.collection_def["train_op"].CopyFrom(fetch_collection)
  return meta_graph

def main(_):
  metagraph = get_metagraph()
  config = config_pb2.ConfigProto()
  if FLAGS.rewriter_config is not None:
    text_format.Merge(FLAGS.rewriter_config,
                      config.graph_options.rewrite_options)
  optimized_graph = tf_optimizer.OptimizeGraph(config, metagraph)
  metagraph.graph_def.CopyFrom(optimized_graph)

  report = cost_analyzer.GenerateCostReport(metagraph, FLAGS.per_node_report,
                                            FLAGS.verbose)
  print(report)
  if FLAGS.memory_report:
    report = cost_analyzer.GenerateMemoryReport(metagraph)
    print(report)

if __name__ == "__main__":
  parser = argparse.ArgumentParser()
  parser.add_argument(
      "--input",
      type=str,
      default=None,
      help="Input file path. Accept SavedModel, MetaGraphDef, and GraphDef in "
      "either binary or text format.")
  parser.add_argument(
      "--fetch",
      type=str,
      default=None,
      help="The names of the fetch node delimited by comma.")
  parser.add_argument(
      "--rewriter_config",
      type=str,
      default=None,
      help="Configuration for the grappler optimizers, described as a "
      "RewriterConfig protocol buffer. Usage example 1: "
      "--rewriter_config='optimize_tensor_layout: true "
      "disable_model_pruning: true'. Usage example 2: "
      "--rewriter_config='optimizers: \"constfold\" optimizers: \"layout\"'")
  parser.add_argument(
      "--per_node_report",
      action="store_true",
      help="Generate per-node report. By default the report contains stats "
      "aggregated on a per op type basis, per_node_report adds results "
      "for each individual node to the report.")
  parser.add_argument(
      "--memory_report",
      action="store_true",
      help="Generate memory usage report.")
  parser.add_argument(
      "--verbose",
      action="store_true",
      help="Generate verbose reports. By default, succinct reports are used.")
  FLAGS, unparsed = parser.parse_known_args()
  app.run(main=main, argv=[sys.argv[0]] + unparsed)


import librosa.display
import numpy as np
import matplotlib.pyplot as plt

y,sr = librosa.load(r'D:\数据集\EmoDB\03a01Fa.wav')
plt.figure()
D = librosa.amplitude_to_db(np.abs(librosa.stft(y)),ref=np.max)
# stft短时傅里叶变换，复数的实部：np.abs(D(f,t))频率的振幅
# 幅度转为分贝，ref为参考值
plt.subplot(2,1,1)
librosa.display.specshow(D,y_axis='linear')
plt.colorbar(format='%+2.0f dB')
plt.title('linear-frequency power spectrogram')

plt.subplot(2,1,2)
librosa.display.specshow(D,y_axis='log')   # 频谱以对数刻度展示
plt.colorbar(format='%+2.0f dB')
plt.title('log-frequency power spectrogram')
plt.show()


# By submitting this assignment, I agree to the following:
#   "Aggies do not lie, cheat, or steal, or tolerate those who do."
#   "I have not given or received any unauthorized aid on this assignment."
#
# Name:         Jacob Hou
# Section:      524
# Assignment:   11.13
# Date:         13 November 2022
#

import csv
AllWeather = []
dates = []
windSpeed = []
rain = [] #precipitation
avgTemp = []
maxTemp = []
minTemp = []
with open("WeatherDataCLL.csv") as data:
    reader = csv.reader(data, delimiter = ",")
    for i in reader:
        AllWeather.append(i)
for weather in range(1, len(AllWeather)):
    dates.append(AllWeather[weather][0])
    windSpeed.append(float(AllWeather[weather][1]))
    rain.append(float(AllWeather[weather][2]))
    avgTemp.append(int(AllWeather[weather][3]))
    maxTemp.append(int(AllWeather[weather][4]))
    minTemp.append(int(AllWeather[weather][5]))

#getting absolute max temp
absMaxTemp = int(maxTemp[0])
for temp in maxTemp:
    if int(absMaxTemp) < int(temp):
        absMaxTemp = temp
#getting absolute min temp
absMinTemp = int(minTemp[0])
for temp in minTemp:
    if int(absMinTemp) > int(temp):
        absMinTemp = temp
#getting avg precipation
avgRain = sum(rain) / len(rain)

print(f"3-year maximum temperature: {absMaxTemp} F")
print(f"3-year minimum temperature: {absMinTemp} F")
print(f"3-year average precipitation: {avgRain:.3f} inches")

month = input("Please enter a month: ")
year = input("Please enter a year: ")
print(f"For {month} {year}: ")
monthNums = {"January":"1/", "February":"2/", "March":"3/", "April":"4/", "May":"5/", "June":"6/",
"July":"7/", "August":"8/", "September":"9/", "October":"10", "November":"11", "December":"12"}
monthNum = monthNums[month]

validDays = []
avgMaxTemp = 0
dayRain = 0
avgWindSpeed = 0
days = 0
i = 0
#find valid dates of month and year
for date in dates:
    if date[:2] == monthNum and date[-4:] == year:
        validDays.append(i)
        days += 1
    i += 1
#finds the days with rain, gets max temp, gets wind speed
for index in validDays:
    avgMaxTemp += maxTemp[index]
    avgWindSpeed += windSpeed[index]
    if rain[index] != 0:
        dayRain += 1
avgMaxTemp /= days
avgWindSpeed /= days
dayRain = (dayRain / days) * 100

print(f"Mean maximum daily temperature: {avgMaxTemp:.1f} F")
print(f"Mean daily wind speed: {avgWindSpeed:.2f} mph")
print(f"Percentage of days with precipitation: {dayRain:.1f} %")


from PyQt5 import QtCore, QtGui, QtWidgets
from module import Ui_module
import glob
from pathlib import Path
import os

__copyright__ = "Copyright 2019, RISE Research Institutes of Sweden"
__author__ = "Naveed Anwar Bhatti and Martina Brachmann"

class mainmodule(QtWidgets.QDialog):
    def __init__(self, parent=None):
        QtWidgets.QDialog.__init__(self, parent)
        self.parent = parent
        self.ui = Ui_module()
        self.ui.setupUi(self)
        self.selected_module = ""

        modules = glob.glob(os.path.join("Modules", "*.py"))  # Add all python files in Module directory as items

        for module in modules:
            item = QtWidgets.QListWidgetItem(module)  # create an item with a caption
            self.ui.listWidget.addItem(item)
            # item.setCheckable(True)  # add a checkbox to it
            # model.appendRow(item)  # Add the item to the model

        # self.listWidget.setModel(model)  # Apply the model to the list view
        self.ui.listWidget.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
        self.ui.saveModules.clicked.connect(self.return_modules)

    def return_modules(self):
        items = self.ui.listWidget.selectedItems()
        x = []
        for i in range(len(items)):
            x.append(str(self.ui.listWidget.selectedItems()[i].text()))
        if len(items)>0:
            if "/" in x[0]:
               self.selected_module = str(x[0]).split("/")[1].split(".")[0]
               print(x[0])
            else:
                self.selected_module = str(x[0]).split("\\")[1].split(".")[0]
                print(x[0])
        self.parent.selected_module=self.selected_module
        self.close()


from pymatgen.analysis.adsorption import AdsorbateSiteFinder
from pymatgen.core.structure import Structure
from pymatgen.core.surface import Slab, SlabGenerator
import numpy as np

# struct = Structure.from_file("POSCAR")
# asf = AdsorbateSiteFinder(struct)

def slab_from_structure(miller, structure):
    return Slab(lattice=structure.lattice,
                species=structure.species_and_occu,
                coords=structure.frac_coords,
                miller_index=miller,
                oriented_unit_cell=structure,
                shift=0,
                scale_factor=np.eye(3, dtype=np.int),
                site_properties=structure.site_properties)

from pymatgen.ext.matproj import MPRester

with MPRester() as m:
    struct = m.get_structure_by_material_id('mp-2', conventional_unit_cell=True)

miller_index = (1, 1, 1)
sg = SlabGenerator(initial_structure=struct,
                   miller_index=miller_index,
                   min_slab_size=10,
                   min_vacuum_size=10,
                   max_normal_search=max([abs(i) for i in miller_index]),
                   primitive=True,
                   lll_reduce=True,
                   in_unit_planes=True,
                   center_slab=True)

slab = sg.get_slabs()[0]
slab.make_supercell([2, 2, 1])

# struct = Structure.from_file('POSCAR_Pd_79.vasp')
# slab = slab_from_structure((1, 1, 1), struct)
asf = AdsorbateSiteFinder(slab)
sites = asf.find_adsorption_sites(symm_reduce=False)
from pymatgen.core.structure import Molecule
site_coords = list(sites.values())
site_coords = [a for b in site_coords for a in b]
mol = Molecule(['H'], [[0, 0, 0]])
# for site in site_coords:
#     asf = AdsorbateSiteFinder(slab)
#     slab = asf.add_adsorbate(molecule=mol, ads_coord=site)
# slab.to('poscar', 'pd_slab.vasp')


import growSomae
import sys
import dataIO
import os
import time
import glob
import numpy as np
import re
import struct

prefix = 'JWR'

if(len(sys.argv))!=4:
    raise ValueError(" Scripts needs exactley 3 input arguments (bz, by, bx)")
else:
    bz = int(sys.argv[1])
    by = int(sys.argv[2])
    bx = int(sys.argv[3])

print("bz by bx: " + str((bz,by,bx)))

n_points_block = 0

print("Block: " + str((bz,by,bx)))

blocksize = dataIO.Blocksize(prefix)
sheet_size = blocksize[1]*blocksize[2]
row_size = blocksize[2]

print("Blocksize is: " + str(blocksize))

input_directory = "segments_out/"
output_directory = "blocks_out/"

filenames = sorted(glob.glob(input_directory+"*"))

labels_out = np.zeros((blocksize),dtype=np.uint64)

for fname in filenames:

    temp = fname.strip().split("-")

    if(len(temp)<4): continue

    bz_read = int(re.sub("[^0-9]", "", temp[-3]))
    by_read = int(re.sub("[^0-9]", "", temp[-2]))
    bx_read = int(re.sub("[^0-9]", "", temp[-1]))
    ID_in_fname = int(temp[-4])

    if bz_read != bz or by_read != by or by_read != by: continue

    # print("reading: " + str(fname))

    blocksize_read = [-1,-1,-1]
    volumesize_read = [-1,-1,-1]
    ID_read = -1
    checksum_read = -1
    n_points = -1

    with open(fname, 'rb') as fd:
        volumesize_read[0], volumesize_read[1], volumesize_read[2], blocksize_read[0] = struct.unpack('qqqq', fd.read(32))
        blocksize_read[1], blocksize_read[2], ID_read, n_points = struct.unpack('qqqq', fd.read(32))

        assert (tuple(volumesize_read) == dataIO.Volumesize(prefix))
        assert (tuple(blocksize_read) == blocksize)
        assert (ID_read == ID_in_fname)

        point_cloud_global = struct.unpack('%sq' % n_points, fd.read(8*n_points))
        point_cloud_local = struct.unpack('%sq' % n_points, fd.read(8*n_points))

        checksum_read = struct.unpack('q', fd.read(32))

        points_global = set(point_cloud_global)
        points_local = set(point_cloud_local)

        del points_global
        del point_cloud_global

    n_points_block+=n_points

    if len(points_local)>0:
        print("Block indices read: " + str((bz_read, by_read, bx_read)))
        print("ID read: " + str(ID_in_fname))

    for index in points_local:
        iz = index // sheet_size
        iy = (index - iz * sheet_size) // row_size
        ix = index % row_size

        labels_out[iz,iy,ix] = ID_read

# print("n_points for block: " + str(n_points_block))

filename_out = "JWR-labels_discarded-"+str(bz).zfill(4)+"z-"+str(by).zfill(4)+"y-"+str(bx).zfill(4)+"x"+".h5"
dataIO.WriteH5File(labels_out, output_directory+filename_out, "main")


from data import windows, signal, WINDOW_SIZE, fs
from matplotlib import pyplot as plt
from matplotlib import transforms
from matplotlib.gridspec import GridSpec
from numpy import fft
from waterfall_plot import plot_waterfall
import numpy as np

spectral_content = fft.rfft(windows, axis=0)
normed_spectral_content = np.abs(spectral_content)
sample_size = (WINDOW_SIZE // 2) + ((WINDOW_SIZE + 1) % 2)
freq_scaling = np.linspace(0, fs / 2, normed_spectral_content.shape[0])
freq_scaling = freq_scaling.reshape((sample_size, 1))

pl = np.log(freq_scaling * normed_spectral_content + 0.0001)

# Summarize data
# Our buckets will be roughly:
# 0 - 100 Hz
# 101 - 2 Khz
# 2Khz - 20Khz
div1 = int(sample_size * (100 / (fs * 2)))
div2 = int(sample_size * (2000 / (fs * 2)))

SEG_START = 100
SEG_END = 300

def sumarize(start, stop):
    # Select the right part of the array
    tr = np.sum(pl[start:stop,SEG_START:SEG_END], axis=0)
    # Compute a moving average (window size = 16)
    # to smooth out measurements
    MA_SIZE = 3
    tr = np.cumsum(tr)
    tr[MA_SIZE:] = tr[MA_SIZE:] - tr[:-MA_SIZE]
    tr = tr[MA_SIZE-1:] / MA_SIZE
    # Normalize the moving average
    mi = np.min(tr)
    ma = np.max(tr)
    # Normalize TR
    tr = (tr - mi) / (ma - mi)
    return tr

sum0 = sumarize(0, div1)
sum1 = sumarize(div1, div2)
sum2 = sumarize(div2, -1)

fig = plt.figure(figsize=(8,16))

subplots = fig.subplots(ncols=1, nrows=4, sharex='col')

p0 = subplots[0].plot(sum0)
subplots[0].set_title('lows')
subplots[0].axhline(y=0.75)
p1 = subplots[1].plot(sum1)
subplots[1].set_title('mids')
subplots[1].axhline(y=0.8)
p2 = subplots[2].plot(sum2)
subplots[2].set_title('his')
subplots[2].axhline(y=0.6)

subplots[3].imshow(pl[:,SEG_START:SEG_END], aspect='auto')

plt.savefig('img/beats.png', bbox_inches='tight', dpi=fig.dpi)


from typing import Optional

import tokenizers

# toks from https://github.com/facebookresearch/esm/blob/main/esm/constants.py#L7
# prepend/append toks from https://github.com/facebookresearch/esm/blob/main/esm/data.py#L153
PROTEINSEQ_TOKS = {
    "toks": [
        "L",
        "A",
        "G",
        "V",
        "S",
        "E",
        "R",
        "T",
        "I",
        "D",
        "P",
        "K",
        "Q",
        "N",
        "F",
        "Y",
        "M",
        "H",
        "W",
        "C",
        "X",
        "B",
        "U",
        "Z",
        "O",
        ".",
        "-",
    ],
    "prepend_toks": ["<cls>", "<pad>", "<eos>", "<unk>"],
    "append_toks": ["<null_1>", "<mask>"],
}

def protein_tokenizer(
    pad_to_multiple_of: Optional[int] = None, max_length: Optional[int] = 1024
) -> tokenizers.Tokenizer:
    """Returns the default protein tokenizer.

    Args:
        pad_to_multiple_of (Optional[int]): If specified, pads all sequences to
            nearest (higher) multiple of value. Defaults to None.
        max_length (Optional[int]): Maximum length to truncate to. Defaults to 1024.

    Returns:
        tokenizers.Tokenizer: HuggingFace Tokenizer to tokenize proteins.
    """

    # Just repurpose the WordLevel tokenizer, since the vocabulary is fully known.
    tokenizer = tokenizers.Tokenizer(
        tokenizers.models.WordLevel(
            {
                key: idx
                for (idx, key) in enumerate(
                    PROTEINSEQ_TOKS["prepend_toks"]
                    + PROTEINSEQ_TOKS["toks"]
                    + PROTEINSEQ_TOKS["append_toks"]
                )
            },
            unk_token="<unk>",
        )
    )

    # Use regex to strip out the capital letters + <special> tokens.
    tokenizer.pre_tokenizer = tokenizers.pre_tokenizers.Split(
        tokenizers.Regex("[A-Z]|[<][a-z]*[>]"), behavior="removed", invert=True
    )

    # Specify the special tokens; makes decoding + printing neater.
    tokenizer.add_special_tokens(
        PROTEINSEQ_TOKS["prepend_toks"] + PROTEINSEQ_TOKS["append_toks"]
    )

    # Add template, to add <cls> to start and <eos> to end of all sequences.
    tokenizer.post_processor = tokenizers.processors.TemplateProcessing(
        single="<cls> $A <eos>",
        pair=None,
        special_tokens=[("<cls>", 0), ("<eos>", 2)],
    )

    # If padding is requested, enable padding.
    if pad_to_multiple_of:
        tokenizer.enable_padding(
            pad_id=1, pad_token="<pad>", pad_to_multiple_of=pad_to_multiple_of
        )

    # Enable truncation to specified max length.
    tokenizer.enable_truncation(max_length=max_length)

    return tokenizer


from django.conf.urls import url
from . import views

# mysite/urls.py 에서 url(r'', include('blog.urls')) 했어서
# Django will redirect everything that comes into htp://127.0.0.1:8000/
# to blog.urls and look for further instructions there.

urlpatterns = [
    url(r'^$', views.home, name='home'),
    url(r'^category/([0-9]+)/$', views.category, name='category'),
    url(r'^posts/$', views.post_list, name='post_list'),
    url(r'^posts/([0-9]+)/$', views.post_view, name='post_view'),
    url(r'^write/$', views.write_post, name='write_post'),
]


import asyncio

import Time
from db import db
from loader import dp, bot
from aiogram import types
from aiogram.types import Message
from aiogram.dispatcher.filters import Command, Text
from aiogram.dispatcher import FSMContext

from misc.throttling import rate_limit
from states import States
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher.filters.state import StatesGroup, State
import keyboards
import messages
import datetime
from Time import switchWeekday
import create_message

@rate_limit
@dp.message_handler(Command("start"))
async def start(message: types.Message):
    if db.user_exists(message.from_user.id):
        await message.answer(messages.WELCOME_MESSAGE, reply_markup=keyboards.start)
    else:
        await message.answer(messages.WELCOME_MESSAGE)
        await message.answer(messages.REGISTRATION_MESSAGE)
        States.Registration.set()

@rate_limit
@dp.message_handler(state=States.Registration)
async def registration(message: types.Message, state: FSMContext):
    group_number = message.text
    while True:

        if message.text in messages.groups:
            db.add_user(0, message.from_user.id, message.from_user.full_name, group_number)
            await message.answer(messages.end_registration, reply_markup=keyboards.start)
            break
        else:
            await message.answer(messages.group_number_fall)

    await state.update_data(answer1=group_number)

    await state.finish()

@rate_limit
@dp.message_handler(Text("О нас"))
async def about_us(message: types.Message):
    await message.answer(messages.ABOUT_US_MESSAGE)

@rate_limit
@dp.message_handler(Text("Функции"))
async def functions(message: types.Message):
    await message.answer(messages.FUNCTION_MESSAGE, reply_markup=keyboards.functions)

@rate_limit
@dp.message_handler(Text("Свое расписание"), state=None)
async def student_tt(message: types.Message):
    await message.answer(messages.what_tt, reply_markup=keyboards.what_tt)
    await States.Ques_What_tt.set()

@rate_limit
@dp.message_handler(state=States.Ques_What_tt)
async def student_ques_what_tt(message: types.Message, state: FSMContext):
    answer = message.text
    group_number = await db.get_user_group(message.from_user.id)
    await state.update_data(answer1=answer)

    if answer == "На завтра":
        await message.answer(messages.get_tt)
        await message.answer(db.get_tt_tomorrow(group_number,
                             switchWeekday(datetime.datetime.today().weekday() + 1)),
                             reply_markup=keyboards.functions)

    elif answer == "На сегодня":
        await message.answer(messages.get_tt)
        await message.answer(db.get_tt_today(group_number, switchWeekday(datetime.datetime.today().weekday())),
                             reply_markup=keyboards.functions)

    elif answer == "На неделю":
        await message.answer(messages.get_tt)
        await message.answer(db.get_tt_week(group_number),
                             reply_markup=keyboards.functions)

    await state.finish()

@rate_limit
@dp.message_handler(Text("Расписание звонков"))
async def get_tt_calls(message: types.Message):
    await message.answer(messages.TT_cals)
    await message.answer(Time.tt_Time())

@rate_limit
@dp.message_handler(Text("Расписание преподавателя"), state=None)
async def get_tt_Lec(message: types.Message):
    await message.answer(messages.SELECT_NAME_LECTURER, reply_markup=keyboards.back)
    await States.Get_Lecturer_tt.set()

@rate_limit
@dp.message_handler(Text("Числитель / Знаменатель"))
async def get_tipe_weel(message: types.Message):
    await message.answer(Time.get_ch_zn())

@rate_limit
@dp.message_handler(Text("Назад"))
async def back(message: types.Message):
    await message.answer(messages.FUNCTION_MESSAGE, reply_markup=keyboards.functions)

@rate_limit
@dp.message_handler(state=States.Confirm)
async def confirm(message: types.Message, state: FSMContext):
    if message.text == "Да":
        with await state.proxy() as data:
            db.change_user_group(message.from_user.id, data['group'])
            await message.answer(create_message.change_group_successful(data['group']))
        await state.finish()
    else:
        await message.answer("Окей, отменил", reply_markup=keyboards.functions)

@rate_limit
@dp.message_handler(Text, state=States.Get_Lecturer_tt)
async def get_what_Lec_tt(message: types.Message, state: FSMContext):
    if message.text.lower() not in messages.lecturers_lastnames:
        await message.answer(messages.WRONG_SELECT_NAME_LEC)
    else:
        await message.answer(db.get_tt_lecther(message), reply_markup=keyboards.functions)
        await state.finish()

@rate_limit
@dp.message_handler(Text, state=None)
async def change_group_number(message: types.Message, state: FSMContext):
    if message.text in messages.groups:

        await States.Confirm().set()
        async with state.proxy() as data:
            data['group'] = message.text

# @dp.message_handler(state=None)
# async def another(message: types.Message, state: FSMContext):


import csv
import pandas as pd
from utils import *
# cols=con_mul+cat_mul+['oegest_comb']
# tb2014=pd.read_csv('../natl2014.csv',usecols=cols)
# print('2014 done, columns are', tb2014.columns)
# tb2015=pd.read_csv('../natl2015.csv',usecols=cols)
# print('2015 done')
# tb2016=pd.read_csv('../natl2016.csv',usecols=cols)
# print('2016 done')
# tb2017=pd.read_csv('../natl2017.csv',usecols=cols)
# print('2017 done')
# tb2018=pd.read_csv('../natl2018us.csv',usecols=cols)
# print('2018 done')
# tb2014_2017=pd.concat([tb2014,tb2015,tb2016,tb2017])
# ori_1417=(len(tb2014_2017))
# ori_18=(len(tb2018))
# print('original 2014-2017 has size %s, 2018 has size %s'%(ori_1417,ori_18))
#
# tb2014_2017=tb2014_2017.reset_index()
#
# col_list=['rf_pdiab','rf_gdiab','rf_phype','rf_ghype','rf_ehype','rf_ppterm','rf_inftr','rf_fedrg','rf_artec','ip_gon','ip_syph','ip_chlam','ip_hepatb','ip_hepatc','sex','mar_p','wic']
# tb2014_2017=tb2014_2017[tb2014_2017['oegest_comb']!=99]
# tb2018=tb2018[tb2018['oegest_comb']!=99]
# print('remained oegest_comb %s for 2014-2017, %s for 2018'%(len(tb2014_2017['oegest_comb']==99),len(tb2018['oegest_comb']==99)))
# tb2014_2017,tb2018=define_missing(tb2014_2017),define_missing(tb2018)
# # tb2014_2017,tb2018=recode(tb2014_2017,col_list),recode(tb2018,col_list)
# tb2014_2017=tb2014_2017[tb2014_2017['precare']<6]
# tb2018=tb2018[tb2018['precare']<6]
# precare_1417=(len(tb2014_2017))
# precare_18=(len(tb2018))
# d1_1417= precare_1417-ori_1417
# d1_18=precare_18-ori_18
# tb2014_2017.to_csv('../tb1417.csv')
# tb2018.to_csv('../tb2018.csv')
# print('after screening out precare>=6,  2014-2017 has size %s, 2018 has size %s.\n screened out %s subjects, %s subjects seperately'%(precare_1417,precare_18,d1_1417,d1_18))
#
#
# #
# tb2018=pd.read_csv('../tb2018.csv')
# tb2014_2017=pd.read_csv('../tb1417.csv')
# tb2014_2017=preterm_recode(tb2014_2017)
# tb2018=preterm_recode(tb2018)
# print(len(tb2018))
# nulli_2014_2017,multi_2014_2017=split_nul_mul(tb2014_2017)
# nulli_2018,multi_2018=split_nul_mul(tb2018)
# print(len(tb2018))
# nulli_2014_2017,multi_2014_2017=select_useful(nulli_2014_2017,multi_2014_2017)
# nulli_2018,multi_2018=select_useful(nulli_2018,multi_2018)
# print(len(nulli_2018))

# nulli_2014_2017.to_csv('../nulli_2014_2018.csv')
# nulli_2014_2017[nulli_2014_2017['cat3']==0].to_csv('../pretermNul.csv')
# nulli_2014_2017[nulli_2014_2017['cat3']==1].to_csv('../normalNul.csv')
multi_2014_2017=pd.read_csv('../multi_2014_2018.csv')
# multi_2014_2017.to_csv('../multi_2014_2018.csv')
multi_2014_2017[multi_2014_2017['cat3']==0].to_csv('../pretermMul.csv')
multi_2014_2017[multi_2014_2017['cat3']==1].to_csv('../normalMul.csv')
# nulli_2018.to_csv('../nulli_2018.csv')
# multi_2018.to_csv('../multi_2018.csv')

flag = 1
with open('/home/shuying/predictBirth/normalMul.csv', newline='') as f1:
    with open('/home/shuying/predictBirth/pretermMul.csv', newline='') as f2:
        f2.readline()
        with open('../mul_1417_even.csv', 'w+', newline='') as f:
            # while flag < 845369:
            a=1
            while a:
                if flag % 10 != 0:
                    a=f1.readline()
                    f.write(a)
                else:
                    f.write(f2.readline())
                flag += 1
print('mul done')
# flag = 1
# with open('/home/shuying/predictBirth/normalNul.csv', newline='') as f1:
#     with open('/home/shuying/predictBirth/pretermNul.csv', newline='') as f2:
#         f2.readline()
#         with open('../nul_1417_even.csv', 'w+', newline='') as f:
#             a=1
#             while a:
#                 # while True:
#                 if flag % 11 != 0:
#                     a=f1.readline()
#                     f.write(a)
#                 else:
#                     f.write(f2.readline())
#                 flag += 1
# print('nul done')
# #
# f=pd.read_csv('/home/shuying/predictBirth/nul_1417_even.csv')
# for col in cat_nul:
#     # if 'U' in f[col].unique():
#     print(col)
#     print(f[col].value_counts()/len(f))
#
# f=pd.read_csv('/home/shuying/predictBirth/mul_1417_even.csv')
# for col in cat_mul:
#     # if 'U' in f[col].unique():
#     print(col)
#     print(f[col].value_counts()/len(f))


def ret_eratos(N: int):
    '''エラトステネスの篩'''
    is_prime = [True] * (N + 1)
    is_prime[0] = False  # 0と1は素数ではない
    is_prime[1] = False
    for i in range(2, int(N ** 0.5) + 1):
        if i % 100 == 0:
            print(i)
        if is_prime[i]:
            for j in range(i * 2, N + 1, i):  # iの倍数は素数でない
                is_prime[j] = False
    return is_prime

def _make_prime_numbers(N: int):
    # N以下の素数を列挙 -> set
    is_prime = ret_eratos(N)

    primes = set()
    for i, flg in enumerate(is_prime):
        if i % 10000000 == 0:
            print(i)
        if flg:
            primes.add(i)

    return primes

with open('primes_10^6.txt', 'w') as f:
    res = _make_prime_numbers(10**6)
    print(res, file=f)
print(len(res))