import numpy as np

class Q_learning_player():

    def __init__(self):
        self.name = "Q_player"
        self.qtable = {} # Q-table을 딕셔너리로 정의
        self.epsilon = 0.5 # e-greedy 계수
        self.learning_rate = 0.1 # 학습률
        self.gamma=0.9

    def select_action(self, env):
        """
        policy에 따라 상태에 맞는 행동을 선택
        """
        action = self.policy(env)
        return action

    def policy(self, env):
        available_action = env.get_action() # 행동 가능한 상태를 저장
        qvalues = np.zeros(len(available_action)) # 행동 가능한 상태의 Q-value를 저장

        # 행동 가능한 상태의 Q-value를 조사
        for i, act in enumerate(available_action):
            key = (tuple(env.board_a),act)
            # 현재 상태를 경험한 적이 없다면(딕셔너리에 없다면) 딕셔너리에 추가(Q-value = 0)
            if self.qtable.get(key) ==  None:
                self.qtable[key] = 0
            # 행동 가능한 상태의 Q-value 저장
            qvalues[i] = self.qtable.get(key)

        # e-greedy
        # 가능한 행동들 중에서 Q-value가 가장 큰 행동을 저장
        greedy_action = np.argmax(qvalues)

        pr = np.zeros(len(available_action))

        # max Q-value와 같은 값이 여러개 있는지 확인한 후 double_check에 상태를 저장
        double_check = (np.where(qvalues == np.max(qvalues),1,0))

        #  여러개 있다면 중복된 상태중에서 다시 무작위로 선택
        if np.sum(double_check) > 1:
            double_check = double_check/np.sum(double_check)
            greedy_action =  np.random.choice(range(0,len(double_check)), p=double_check)
        # e-greedy로 행동들의 선택 확률을 계산
        pr = np.zeros(len(available_action))

        for i in range(len(available_action)):
            if i == greedy_action:
                pr[i] = 1 - self.epsilon + self.epsilon/len(available_action)
                if pr[i] < 0:
                    print("{} : - pr".format(np.round(pr[i],2)))
            else:
                pr[i] = self.epsilon / len(available_action)
                if pr[i] < 0:
                    print("{} : - pr".format(np.round(pr[i],2)))
        action = np.random.choice(range(0,len(available_action)), p=pr)

        return available_action[action]

    def learn_qtable(self,board_bakup, action_backup, env, reward):
        key = (board_bakup,action_backup) # 현재 상태와 행동을 키로 저장

        if env.done == True: # 게임이 끝났을 경우 학습
            self.qtable[key] += self.learning_rate*(reward - self.qtable[key])

        else: # 게임이 진행중일 경우 학습
            available_action = env.get_action()
            qvalues = np.zeros(len(available_action))

            for i, act in enumerate(available_action):
                next_key = (tuple(env.board_a),act)
                # 다음 상태를 경험한 적이 없다면(딕셔너리에 없다면) 딕셔너리에 추가(Q-value = 0)
                if self.qtable.get(next_key) ==  None:
                    self.qtable[next_key] = 0
                qvalues[i] = self.qtable.get(next_key)

            # maxQ 조사
            maxQ = np.max(qvalues)

            self.qtable[key] += self.learning_rate*(reward + self.gamma * maxQ - self.qtable[key])


import time
from collections import deque

with open('_input/day18.txt') as f:
    input = f.read().splitlines()

nodes = {}

minX = 10000
maxX = 0
minY = 10000
maxY = 0
minZ = 10000
maxZ = 0

for line in input:
    key = tuple([int(m) for m in line.split(',')])
    minX = min(key[0], minX)
    maxX = max(key[0], maxX)
    minY = min(key[1], minY)
    maxY = max(key[1], maxY)
    minZ = min(key[2], minZ)
    maxZ = max(key[2], maxZ)

for line in input:
    key = tuple([int(m) for m in line.split(',')])
    nodes[key] = 6

    for neighbour in [
        (key[0] + 1, key[1], key[2]),
        (key[0] - 1, key[1], key[2]),
        (key[0], key[1] + 1, key[2]),
        (key[0], key[1] - 1, key[2]),
        (key[0], key[1], key[2] + 1),
        (key[0], key[1], key[2] - 1)
    ]:
        if neighbour in nodes:
            nodes[key] = nodes[key] - 1
            nodes[neighbour] = nodes[neighbour] - 1

print(f'part 1 found: {sum([nodes[idx] for idx in nodes if nodes[idx] >= 0])} sides')

# fill everything with 0s
for key in [(x, y, z) for x in range(minX - 1, maxX + 2) for y in range(minY - 1, maxY + 2) for z in range(minZ - 1, maxZ + 2) if (x, y, z) not in nodes]:
    nodes[key] = -1

# find every empty adjoining node you can
Q = deque([(minX - 1, minY - 1, minZ - 1)])

dx = (maxX - minX) + 2
dy = (maxY - minY) + 2
dz = (maxZ - minZ) + 2
print(f'starting the backfill for {dx} * {dy} * {dz} = {dx * dy * dz} nodes')
counter = 0
while Q:
    e = Q.popleft()
    # have we already been here
    if nodes[e] == 0: continue
    # set this node as visited and up the counter
    nodes[e] = 0
    counter += 1
    if counter % 100 == 0: print(f"\rvisited: {counter} nodes", end='')
    for neighbour in [
        (e[0] + 1, e[1], e[2]),
        (e[0] - 1, e[1], e[2]),
        (e[0], e[1] + 1, e[2]),
        (e[0], e[1] - 1, e[2]),
        (e[0], e[1], e[2] + 1),
        (e[0], e[1], e[2] - 1)
    ]:
        if neighbour in nodes and nodes[neighbour] == -1:
            Q.append(neighbour)

print(f"\rvisited: {counter} nodes")

# find all the -1 nodes
for key in [n for n in nodes if nodes[n] < 0]:
    for neighbour in [
        (key[0] + 1, key[1], key[2]),
        (key[0] - 1, key[1], key[2]),
        (key[0], key[1] + 1, key[2]),
        (key[0], key[1] - 1, key[2]),
        (key[0], key[1], key[2] + 1),
        (key[0], key[1], key[2] - 1)
    ]:
        if nodes[neighbour] > 0:
            nodes[neighbour] -= 1

print(f'part 2 found: {sum([nodes[idx] for idx in nodes if nodes[idx] >= 0])} sides')


"""

"""
import logging
import os
import re
from io import StringIO
from logging import getLogger, basicConfig

import diskcache
import os.path

import pandas
import requests
from matplotlib import pyplot as plt
from pandas import Series
from diskcache import Cache
from pandas import Series, DataFrame
logger = getLogger(__name__)
basicConfig(level=logging.DEBUG)

airfoiltools_cache = Cache(os.path.join(os.path.dirname(__file__), "cache"))

logger.error(airfoiltools_cache.stats())

class AirfoilToolsDatFile(object):

    def __init__(self, filename: str=None, file=None):
        self.designation = "None"
        if file is not None:
            self.populate(file)
            self.designation = filename
        elif filename is not None:
            with open(filename, "r") as f:
                f.readline()
                self.populate(f)
            print(filename)
            self.designation = re.match(r"(.*)?NACA([\d]{4,})(.*)?",filename)[2]
            print(self.designation)

        # self.filename = filename

    def populate(self, file):
        self.data = pandas.read_csv(file, sep='\s+', names=['x', 'y'], skiprows=0, index_col=False)
        # print(self.data)
        self.turning_point = self.data['x'].abs().idxmin()  # Find the index of the turning point (x=0)
        self.xu = self.data['x'][:self.turning_point + 1][::-1].reset_index()
        self.yu = self.data['y'][:self.turning_point + 1][::-1].reset_index()
        # print(self.xu)
        # print(self.yu)
        self.xl = self.data['x'][self.turning_point:].reset_index()
        self.xl.rename(columns={'x': 'xl'}, inplace=True)
        self.yu.rename(columns={'y': "yu"}, inplace=True)
        self.yl = self.data['y'][self.turning_point:].reset_index()
        self.yl.rename(columns={'y': 'yl'}, inplace=True)
        self.xu.rename(columns={'x': 'xu'}, inplace=True)
        self.df = pandas.concat([self.xu["xu"], self.yu["yu"], self.xl["xl"], self.yl["yl"]], axis=1)
        self.s = len(self.df) - 1

    @staticmethod
    # @airfoiltools_cache.memoize("airfoil", expire=None, tag="airfoiltools_dat")
    def load(designation: str, s: int = 100, cs: bool = True, ct: bool = False) -> "AirfoilToolsDatFile":
        """
        Loads an airfoil from the airfoiltools.com database.
        :param designation:
        :return:
        """
        if len(designation) == 4:
            url = f"http://airfoiltools.com/airfoil/naca4digit?MNaca4DigitForm%5Bcamber%5D={designation[0]}&MNaca4DigitForm%5Bposition%5D={int(designation[1]) * 10}&MNaca4DigitForm%5Bthick%5D={designation[2:]}&MNaca4DigitForm%5BnumPoints%5D={s*2}&MNaca4DigitForm%5BcosSpace%5D={int(cs)}&MNaca4DigitForm%5BcosSpace%5D={int(cs)}&MNaca4DigitForm%5BcloseTe%5D={int(ct)}&MNaca4DigitForm%5BcloseTe%5D={int(ct)}&yt0=Plot"
        elif len(designation) == 5:
            url= f"http://airfoiltools.com/airfoil/naca5digit?MNaca5DigitForm%5Bcl%5D={3/20*int(designation[0])}&MNaca5DigitForm%5BposKey%5D={5*int(designation[1])}_{designation[2]}&MNaca5DigitForm%5Bthick%5D={int(designation[3:])}&MNaca5DigitForm%5BnumPoints%5D={s*2}&MNaca5DigitForm%5BcosSpace%5D={int(cs)}&MNaca5DigitForm%5BcosSpace%5D={int(cs)}&MNaca5DigitForm%5BcloseTe%5D={int(ct)}&MNaca5DigitForm%5BcloseTe%5D={int(ct)}&yt0=Plot"

        from bs4 import BeautifulSoup
        soup = BeautifulSoup(requests.get(url).text, "html.parser")
        # print(url)
        # print(soup)
        # print(soup.find("pre").text)
        text = soup.find("pre").text.strip().split("\n", maxsplit=1)[1]
        print(url)
        try:
            assert soup.find("title").text.find(designation)!=-1
        except AssertionError as e:
            print(soup.find("title").text)
            print(designation)
            print(url)

        # print(text)
        return AirfoilToolsDatFile(file=StringIO(text), filename=designation)

    def plot(self) -> None:
        """
        Plots the airfoil.
        :return: None
        """

        fig, ax = plt.subplots()
        ax.plot(self.df["xu"], self.df["yu"])
        ax.plot(self.df["xl"], self.df["yl"])
        if "xc" in self.df.columns.tolist() and "yc" in self.df.columns.tolist():
            ax.plot(self.df["xc"], self.df["yc"])
        # ax.plot(self.df["xc"], self.df["yc"])
        fig.legend(["Upper Surface", "Lower Surface", "Camber Line"])
        plt.title(f"{self.designation} Airfoil (Loaded from AirfoilTools.com)")
        # plt.xlim(0, 1)
        plt.ylim(-0.2, 0.2)
        plt.gca().set_aspect('equal', adjustable='box')
        fig.show()

if __name__ == "__main__":
    a = AirfoilToolsDatFile("NACA/tests/data/airfoiltools/NACA2412.dat")
    print(a.df)
    # a.plot()


from podclip.robot import Robot, RobotState
from typing import Tuple
from PIL import Image, ImageDraw, ImageFont
import logging
import textwrap

"""
  Cool pallettes:
  - https://lospec.com/palette-list/borkfest
  - https://lospec.com/palette-list/bloody
"""

class ThumbnailRobot(Robot):

  def __init__(self):
    self.width = 1280
    self.height = 720
    self.pd = 10

  def run(self, state: RobotState) -> RobotState:
    logging.info(f'Generating Thumbnail w/ frame "{state.thumb_frame}" and quote "{state.thumb_quote}"...')

    thumbnail = Image.new('RGB', self.dimensions, color='#e9345a')
    frame = Image.open(state.thumb_frame, 'r')
    frame = frame.resize(self.frame_with_padding)

    thumbnail.paste(frame, self.frame_pivot)
    frame.close()

    self.draw_text(thumbnail, state.thumb_quote)

    thumbnail.save(state.thumb_path)

    logging.info(f'Thumbnail saved on "{state.thumb_path}"')
    return state

  def draw_text(self, img: Image, text: str):
    font = ImageFont.truetype(r'fonts/Roboto/Roboto-Black.ttf', 116)
    draw = ImageDraw.Draw(img)

    for i, phrase in enumerate(textwrap.wrap(text, width=18)):
      draw.text(
          self.text_pivot(i),
          phrase,
          font=font,
          anchor='mm',
        )

  def text_pivot(self, index: int = 0) -> Tuple[int]:
    return self.width // 2, 500 + index * 100

  @property
  def dimensions(self) -> Tuple[int]:
    return (self.width, self.height)

  @property
  def frame_with_padding(self) -> Tuple[int]:
    return (self.width - (self.pd * 2), self.height - (self.pd * 2))

  @property
  def frame_pivot(self) -> Tuple[int]:
    return (self.pd, self.pd)


# problem:https://leetcode.com/problems/minimum-genetic-mutation/
# Runtime: 42 ms, faster than 76.16% of Python3 online submissions for Minimum Genetic Mutation.
# Memory Usage: 13.9 MB, less than 86.96% of Python3 online submissions for Minimum Genetic Mutation.

import collections
from typing import List

class Solution:
    def minMutation(self, start: str, end: str, bank: List[str]) -> int:
        seen = set([start])
        queue = collections.deque([(start, 0)])
        characters = ['A', 'C', 'G', 'T']
        word_bank = set(bank)
        while queue:
            element, steps = queue.popleft()
            n = len(element)
            for i in range(n):
                for character in characters:
                    mutation = element[:i] + character + element[i + 1:]
                    if mutation in word_bank and mutation not in seen:
                        if mutation == end:
                            return steps + 1
                        seen.add(mutation)
                        queue.append((mutation, steps + 1))
        return -1


import turtle

drawingBoard = turtle.Screen()
drawingBoard.bgcolor("light blue")
drawingBoard.title("Catch the turtle")
drawingBoard.addshape("pic.gif")
turtle.shape("pic.gif")

myTurtle = turtle.Turtle(visible=False) #fare iconunu gorunmez yapar
turtle.penup() #cizgiyi gorunmez yapar

turtle.ht()
turtle.setposition(100, 100)
turtle.st()
turtle.ht()
turtle.setposition(200, 150)
turtle.st()

turtle.mainloop()


import sys
# принимаем строку
word = sys.argv[1]
# преобразуем строку в список
word = list(word)
# сортируем список
word.sort(key=str)
# преобразуем отсортированный список в строку
word = "".join(word)
# вывод результата
print(word)

"""
import sys

word = sys.argv[1]

# Преобразовываем строку в список символов
word = list(word)

# Сортируем список
word.sort()

# Склеиваем все элементы списка обратно в строку
print("".join(word))

#12: СОРТИРОВКА ПО АЛФАВИТУ
Сложность: 2 из 10
Напишите программу sort.py,
которая получает из первого аргумента командной строки слово,
а затем выводит все буквы слова в алфавитном порядке.

Пример использования:
> python sort.py programming
> aggimmnoprr
"""


import numpy as np
import sys

sys.setrecursionlimit(10000)

def dist(pos1,pos2):
    return np.sqrt((pos1[0]-pos2[0])**2 + (pos1[1]-pos2[1])**2)

def solution(dim, pos_1, pos_2, max_dist):
    def isReachable(pos):
        return dist(pos,pos_1) <= max_dist

    l,h = dim
    dx1,dx2,dy1,dy2 = l - pos_2[0], pos_2[0], pos_2[1], h - pos_2[1]
    _dx1,_dx2,_dy1,_dy2 = l - pos_1[0], pos_1[0], pos_1[1], h - pos_1[1]

    pos_2 = tuple(pos_2)
    pos_1 = tuple(pos_1)

    if pos_1 == pos_2:
        return 0

    def explore(non_visited,visited):
        if len(non_visited) == 0:
            return list(visited.keys())
        else:
            for data in non_visited:
                pos = (data[0],data[1])
                dx1,dx2,dy1,dy2 = data[2:]
                visited[pos] = True
                non_visited.remove(data)
                new_datas = [(pos[0] + 2*dx2,pos[1])+(-dx2,-dx1,dy1,dy2),(pos[0] + 2*dx1,pos[1])+(-dx2,-dx1,dy1,dy2),(pos[0],pos[1]+2*dy2)+(dx1,dx2,-dy2,-dy1),(pos[0],pos[1]+2*dy1)+(dx1,dx2,-dy2,-dy1)]
                for new_data in new_datas:
                    new_pos = (new_data[0],new_data[1])
                    if new_pos[0] >= 0 and new_pos[1] >= 0:
                        if isReachable(new_pos) and new_pos not in visited.keys():
                            non_visited.append(new_data)

                return explore(non_visited,visited)

    trainer_pos = explore([pos_2+(dx1,-dx2,-dy1,dy2)],{})
    myself_pos = explore([pos_1+(_dx1,-_dx2,-_dy1,_dy2)],{})

    data_trainer = []
    data_myself = []

    for dx,dy in [(1,1),(1,-1),(-1,1),(-1,-1)]:
        for pos in trainer_pos:
            new_pos = (dx*pos[0],dy*pos[1])
            if isReachable(new_pos):
                data_trainer.append(new_pos + tuple("t"))
        for pos in trainer_pos:
            new_pos = (dx*pos[0],dy*pos[1])
            if isReachable(new_pos):
                data_trainer.append(new_pos + tuple("t"))

    d = {}

    for data in data_trainer:
        pos = data[:2]
        theta = np.arctan2(pos[0]-pos_1[0],pos[1]-pos_1[1])
        distance = dist(pos_1,pos)
        d.setdefault(theta, []).append((distance,data[2]))
    for data in data_myself:
        pos = data[:2]
        theta = np.arctan2(pos[0]-pos_1[0],pos[1]-pos_1[1])
        distance = dist(pos_1,pos)
        d.setdefault(theta, []).append((distance,data[2]))

    def findClosest(L):
        dataMin = (10**8,'t')
        for data in L:
            if data[0] < dataMin[0]:
                dataMin = data
        return dataMin

    reachable = 0

    for key in d.keys():
        dataMin = findClosest(d[key])
        if dataMin[1] == 't':
            reachable += 1

    return reachable

print(solution([300,275], [150,150], [185,100], 500))

print(solution([3,2], [1,1], [2,1], 4))

print(solution([3,2], [1,1],[1,1],4))

print(solution([2,5], [1,2],[1,4],11))

print(solution([345,678],[45,67],[275,134],10000))


#imports librarys
import math
#predefines variables we are going to use
diam = 0.0
circ = 0.0
SA = 0.0
vol = 0.0
radius = "Placeholder"

#Gets initial rad(ius) value
rad = input("Please enter the radius of the sphere: ")

#Checks to make sure input is convertable to float number and assigns float value
while type(radius) != float:

    try:
        radius = float(rad)
    except ValueError:
        print("That doesn't seem to be a number. \n")
        rad = input("Please input a number: ")

#Calculates the diameter
diam = 2 * radius
#Calculates the circumference
circ = 2 * math.pi * radius
#Calculates the surface area
SA = 4 * math.pi * radius**2
#Calculates the volume
vol = (4/3) * math.pi * radius**3

#Prints all the sphere info using f-string formatting
print(f"With your input of {radius}\nThe diameter of the sphere is {diam}\nThe circumference of the sphere is {circ}\n"
      f"The surface area of the sphere is {SA}\nAnd the volume of the sphere is {vol}")


# 시간제한 2초
import sys
input = sys.stdin.readline
n,m = map(int,input().split())
a = set()
b = set()
for i in range(n):
    a.add(input().strip())
for j in range(m):
    b.add(input().strip())
ans = list(a&b)
ans.sort()
print(len(ans))
print(*ans,sep='\n')


"""Execute CLI functions for nat"""
def execute_clear_nat_translation(device):
    """ Clear All NAT Flows

        Args:
            device (`obj`): Device object

        Returns:
            None

        Raises:
            SubCommandFailure
    """
    cmd = "clear ip nat translation *"

    try:
        out = device.execute(cmd)
    except Exception  as err:
        raise Exception(err)

    return out


from django.urls import path, include
from .views import *

app_name = 'app'

urlpatterns = [
    # User Auth
    path('user/sign_up/', CreateUser.as_view(), name="create_user"),
    path('user/log_out/blacklist/', BlacklistTokenView.as_view(), name='blacklist'),

    # Reset User Password
    path('auth/', include('djoser.urls')),

    # Books
    path('books/<str:ISBN>', Books.as_view(), name="retrieve_book"),

    # Friends
    path('friends/', FriendsView.as_view(), name='friends'),
    path('friends/user/<int:other_user_id>', OtherUserFriendsView.as_view(), name='other_user_friends'),
    path('friends/<int:other_user_id>', FriendView.as_view(), name='single_friend'),
    path('friend_requests/', FriendRequestsView.as_view(), name='friend_requests'),

    # Chat
    path('chat/', ChatListView.as_view()),
    path('chat/leave/<pk>/', ChatLeaveView.as_view()),

    # Recommender system
    path('recommender/', RecommenderAPI.as_view(), name='recommender'),
    path('recommender/<str:action>/', RecommenderAPI.as_view(), name='recommender_action'),
    path('recommender/<int:m>/<int:n>/<int:id>/<str:action>/', RecommenderAPI.as_view(), name='recommender_top_n'),
    path('recommender/<int:m>/<int:n>/<int:id>/<str:action>/<str:genre>/', RecommenderAPI.as_view(),
         name='recommender_top_n_for_genre'),
    path('recommender/<int:m>/<int:n>/<str:action>/', RecommenderAPI.as_view(), name='recommender_top_n_global'),
    path('recommender/<int:m>/<int:n>/<str:action>/<str:genre>/', RecommenderAPI.as_view(),
         name='recommender_top_n_global_for_genre'),

    # Feed
    path('feed/', FeedView.as_view(), name='feed'),
    path('posts/', AllPostsView.as_view(), name='all_posts'),
    path('posts/<int:post_id>', PostView.as_view(), name='post'),
    path('posts/<int:post_id>/comments/', AllCommentsView.as_view(), name='all_comments'),
    path('posts/<int:post_id>/comments/<int:comment_id>', CommentView.as_view(), name='comment'),
    path('posts/<int:post_id>/comments/<int:comment_id>/replies/', AllRepliesView.as_view(), name='all_replies'),
    path('posts/<int:post_id>/comments/<int:comment_id>/replies/<int:reply_id>', ReplyView.as_view(), name='reply'),
    path('feed/clubs/<int:club_id>', ClubFeedView.as_view(), name='club_feed'),

    # Club API
    path('user/get_update/<int:id>/', UserDetails.as_view(), name="get_update"),
    path('clubs/', Clubs.as_view(), name='clubs'),
    path('clubs/user/<int:user_id>', UserClubView.as_view(), name='user_clubs'),
    path('singleclub/<int:id>/', SingleClub.as_view(), name='retrieve_single_club'),
    path('singleclub/<int:id>/<str:action>/<int:user_id>', SingleClub.as_view(), name='manage_club'),
    path('singleclub/<int:id>/<str:action>/', SingleClub.as_view(), name='update_club'),

    # Search API
    path('search/', SearchView.as_view(), name='search'),

    # Ratings
    path('ratings/', AllRatingsView.as_view(), name='user_ratings'),
    path('ratings/<int:rating_id>/', RatingView.as_view(), name='rating'),
    path('books/<str:isbn>/ratings/', BookRatingsView.as_view(), name='book_ratings'),
    path('ratings/other_user/<int:other_user_id>', OtherUserRatingsView.as_view(), name='other_user_ratings'),

    # Others
    path('get_current_user/', GetCurrentUserView.as_view(), name='current_user'),

    # Genre API
    path('genres/', GenresView.as_view(), name='genres'),

    # Feed
    path('feed/', FeedView.as_view(), name='feed'),
    path('posts/', AllPostsView.as_view(), name='all_posts'),
    path('posts/<int:post_id>', PostView.as_view(), name='post'),
    path('posts/user/<int:other_user_id>', OtherUserPostsView.as_view(), name='other_user_posts'),
    path('posts/<int:post_id>/comments/', AllCommentsView.as_view(), name='all_comments'),
    path('posts/<int:post_id>/comments/<int:comment_id>', CommentView.as_view(), name='comment'),
    path('posts/<int:post_id>/comments/<int:comment_id>/replies/', AllRepliesView.as_view(), name='all_replies'),
    path('posts/<int:post_id>/comments/<int:comment_id>/replies/<int:reply_id>', ReplyView.as_view(), name='reply'),

    # Scheduling API
    path('scheduling/', SchedulingView.as_view(), name='scheduling'),
    path('scheduling/<int:id>/', SchedulingView.as_view(), name='scheduling_with_id'),
    path('scheduling/<int:id>/<str:action>/', SchedulingView.as_view(), name='scheduling_update'),
    path('calendar/', CalendarView.as_view(), name='calendar'),
    path('calendar/<int:id>', CalendarView.as_view(), name='calendar_with_id'),
    path('meetings/', MeetingsView.as_view(), name='meetings'),
    path('meetings/<int:id>', MeetingsView.as_view(), name='meetings_with_id'),
    path('club_meetings/', ClubMeetingsView.as_view(), name='club_meetings'),
    path('club_meetings/<int:id>', ClubMeetingsView.as_view(), name='club_meetings_with_id'),
]


# Read large CSV file
def csv_reader(file_name):
    for row in open(file_name,"r",encoding="utf8"):
        yield row

filereader = csv_reader("D:\gson\movies.csv")
line_count = 0
while True:
    val = next(filereader, 'end')
    if val == 'end':
        print('list end')
        break
    else:
        line_count += 1
        print(val)

print(line_count)


import timeit
from time import time

def naive():
    ss = []
    for i in range(1000):
        ss.append("a" + str(i) + "b" + str(i+1)\
            + str(i+2) + str(i+2) + str(i+2) + str(i+2) + str(i+2) + str(i+2) + str(i+2) + str(i+2) + str(i+2))
    return ss

def faster():
    ss = []
    for i in range(1000):
        ss.append("a%sb%s%s%s%s%s%s%s%s%s%s" % (str(i), str(i+1), str(i+2), str(i+2), str(i+2), str(i+2), str(i+2), str(i+2), str(i+2), str(i+2), str(i+2)))
    return ss

def n():
    t = time()
    s = 'lksdajflakjdsflku09uweoir'
    for x in range(30):
        ss = s[:int(len(s)/16)]
        s += ss
        s += ss
        s += ss
        s += ss
        s += ss

        s += ss
        s += ss
        s += ss
        s += ss
        s += ss
    print(len(s))
    print('duration:', time()-t)

def f():
    t = time()
    s = 'lksdajflakjdsflku09uweoir'
    for x in range(30):
        ss = s[:int(len(s)/16)]
        s = "".join([s,
                     ss,
                     ss,
                     ss,
                     ss,
                     ss,

                     ss,
                     ss,
                     ss,
                     ss,
                     ss])
    print(len(s))
    print('duration:', time()-t)

def string_concat_test():
    print(timeit.timeit(naive, number=30))
    print(timeit.timeit(faster, number=30))
    n()
    f()

ol = []

def ln():
    nl = []
    for i in ol:
        nl.append(i*2)
    return nl

def lf():
    nl = [i*2 for i in ol]
    return nl

def lf1():
    nl = list(map(lambda x: x*2, ol))
    return nl

def lf2():
    def f(x):
        return x*2
    nl = list(map(f, ol))
    return nl

def lf3():
    nl = (i*2 for i in ol)
    return list(nl)

def loop_test():
    for i in range(100):
        ol.append(i)
    print(timeit.timeit(ln, number=100))
    print(timeit.timeit(lf, number=100))
    print(timeit.timeit(lf1, number=100))
    print(timeit.timeit(lf2, number=100))
    print(timeit.timeit(lf3, number=100))

k = 100

def gf(a, b):
    return a*b

def global_():
    return [gf(100, i) for i in range(1000)]

def local():
    j = 100
    ff = gf
    return [ff(100, i) for i in range(1000)]

def gvl_test():
    # Warm Up
    print(timeit.timeit(global_, number=1000))
    print(timeit.timeit(local, number=1000))
    # Test
    print(timeit.timeit(local, number=1000))
    print(timeit.timeit(global_, number=1000))

def imp0():
    import string
    l = []
    l.append(string.ascii_letters[0])
    return l

import string
def imp1():
    l = []
    l.append(string.ascii_letters[0])
    return l

def import_test():
    print(timeit.timeit(imp0,
                        number=1000))
    print(timeit.timeit(imp1,
                        number=1000))

if __name__ == '__main__':
    # loop_test()
    # gvl_test()
    import_test()
    # import profile
    # profile.run('loop_test()')


# -*- coding: utf-8 -*-
"""
Created on Thu Jun 24 10:36:17 2021

@author: Research_Lab
"""

import numpy as np
from scipy import fftpack
from matplotlib import pyplot as plt
#%%
import pandas
import os
datadir = os.path.join('C:\\Users\\Research Lab\\Desktop\\SI_Resources\\Synthetic_topography\\') # directory for some sample data files
#filename = 'Elevation_profile2.csv'
filename = "site1.csv"
filepath = os.path.join(datadir, filename)
df = pandas.read_csv(filepath)

sig = df.ix[:,1]
sig_non_zero = sig[sig!=0]
#%%
#%%
# The FFT of the signal
sig_fft = fftpack.fft(sig_non_zero)

# And the power (sig_fft is of complex dtype)
power = np.abs(sig_fft)**2

# The corresponding frequencies
sample_freq = fftpack.fftfreq(sig_non_zero.size)

# Plot the FFT power
plt.figure(figsize=(6, 5))
plt.plot(sample_freq, power)
plt.xlabel('Frequency [Hz]')
plt.ylabel('plower')

# Find the peak frequency: we can focus on only the positive frequencies
pos_mask = np.where(sample_freq > 0)
freqs = sample_freq[pos_mask]
peak_freq = freqs[power[pos_mask].argmax()]

# Check that it does indeed correspond to the frequency that we generate
# the signal with
#np.allclose(peak_freq, 1./period)

# An inner plot to show the peak frequency
axes = plt.axes([0.55, 0.3, 0.3, 0.5])
plt.title('Peak frequency')
plt.plot(freqs[:15], power[:15])
plt.setp(axes, yticks=[])

plt.figure(figsize=(9, 7))
plt.plot(freqs[2:50], power[2:50])

# scipy.signal.find_peaks_cwt can also be used for more advanced
# peak detection
#%%
time_vec = np.arange(0, sig_non_zero.size, 1)
time_vec = df.ix[:,0]
#%%
#Setting a cutoff threshold at the first

high_freq_fft_coarse = sig_fft.copy()
high_freq_fft_coarse[np.abs(sample_freq) > peak_freq] = 0
filtered_sig_coarse = fftpack.ifft(high_freq_fft_coarse)

high_freq_fft_fine = sig_fft.copy()
high_freq_fft_fine [np.abs(sample_freq) > freqs[2]] = 0
filtered_sig_fine = fftpack.ifft(high_freq_fft_fine)

high_freq_fft_finest = sig_fft.copy()
high_freq_fft_finest [np.abs(sample_freq) > 0.002] = 0
filtered_sig_finest = fftpack.ifft(high_freq_fft_finest)

#%%
# Estimating the standard deviation for the noise

SD_sample_coarse = np.std(sig_non_zero-filtered_sig_coarse )
noise_random_coarse = np.random.normal(0, .25, sig_non_zero.size)
synthetic_topo_coarse = filtered_sig_coarse + noise_random_coarse

SD_sample_fine = np.std(sig_non_zero-filtered_sig_fine )
noise_random_fine = np.random.normal(0, .25, sig_non_zero.size)
synthetic_topo_fine = filtered_sig_fine + noise_random_fine

SD_sample_finest = np.std(sig_non_zero-filtered_sig_finest )
noise_random_finest = np.random.normal(0, .25, sig_non_zero.size)
synthetic_topo_finest = filtered_sig_finest + noise_random_finest

#%%
# Generating Plots

plt.figure(figsize=(10, 10))
plt.subplot(2, 2, 1)
plt.plot(time_vec, sig_non_zero, linewidth=2, label='Elev Prof Site 1')
plt.xlabel('Distance (degrees)')
plt.ylabel('Elevation (m)')
plt.legend(loc='best')

plt.subplot(2, 2, 2)
plt.plot(time_vec, sig_non_zero, linewidth=2, label='Elev Prof Site 1')
plt.plot(time_vec, synthetic_topo_coarse, linewidth=1, label='Syn topo coarse')
plt.xlabel('Distance (degrees)')
plt.ylabel('Elevation (m)')
plt.legend(loc='best')

plt.subplot(2, 2, 3)
plt.plot(time_vec, sig_non_zero, linewidth=2, label='Elev Prof Site 1')
plt.plot(time_vec, synthetic_topo_fine, linewidth=1, label='Syn topo fine')
plt.xlabel('Distance (degrees)')
plt.ylabel('Elevation (m)')
plt.legend(loc='best')

plt.subplot(2, 2, 4)
plt.plot(time_vec, sig_non_zero, linewidth=2, label='Elev Prof Site 1')
plt.plot(time_vec, synthetic_topo_finest, linewidth=1, label='Syn topo finest')
plt.xlabel('Distance (degrees)')
plt.ylabel('Elevation (m)')
plt.legend(loc='best')

#%%


from clases.preguntas import Pregunta
from clases.respuestas import Respuesta
import sqlite3

contadorPreguntas = 0
puntos = 0

#CREAR PREGUNTAS
p1 = Pregunta(1,"En qué año fue el descubrimiento de América?",1,1)
p2 = Pregunta(2,"Cuál es el país con mayor población del mundo?",1,1)
p3 = Pregunta(3,"Cuál era el nombre del dios del Sol en el Antiguo Egipto?",1,1)
p4 = Pregunta(4,"Quién fue el primer presidente de Estados Unidos?",1,1)
p5 = Pregunta(5,"Quién es el autor de La Odisea?",1,1)

p6 = Pregunta(6,"Cómo se llama el estadio de fútbol del Real Madrid?",2,2)
p7 = Pregunta(7,"En qué deporte destaca Tiger Woods?",2,2)
p8 = Pregunta(8,"Quién ganó el mundial de de fútbol del año 2014?",2,2)
p9 = Pregunta(9,"De que país es el futbolista Radamel Falcao Garcia?",2,2)
p10 = Pregunta(10,"En qué equipo jugó Francesco Totti durante toda su carrera?",2,2)

p11 = Pregunta(11,"Cuál es el río más largo del mundo?",3,3)
p12 = Pregunta(12,"Cuál es el océano más grande del mundo?",3,3)
p13 = Pregunta(13,"Cuántos lados tiene un heptágono?",3,3)
p14 = Pregunta(14,"Cuál es el planeta más grande del Sistema Solar?",3,3)
p15 = Pregunta(15,"Cuántos huesos tiene el cuerpo humano?",3,3)

p16 = Pregunta(16,"Cuántos corazones tiene un gusano de tierra?",4,4)
p17 = Pregunta(17,"Cuántos días tiene un año bisiesto??",4,4)
p18 = Pregunta(18,"Cuántas patas tiene una araña?",4,4)
p19 = Pregunta(19,"Cuántos corazones tiene un pulpo?",4,4)
p20 = Pregunta(20,"Cuanto es 10+80 ?",4,4)

p21 = Pregunta(21,"Cuántas horas tiene un día ?",5,5)
p22 = Pregunta(22,"Cuantos minutos tiene una hora ?",5,5)
p23 = Pregunta(23,"Cuantos departamentos tiene Colombia ?",5,5)
p24 = Pregunta(24,"Cuantas son las ramas del poder público en Colombia ?",5,5)
p25 = Pregunta(25,"Cual es la capital de Colombia ?",5,5)

#crear respuestas

r1 = Respuesta(1,"(1492)",1,True)
r2 = Respuesta(2,"(1342)",1,False)
r3 = Respuesta(3,"(1429)",1,False)
r4 = Respuesta(4,"(1352)",1,False)

r5 = Respuesta(5,"(Perú)",2,False)
r6 = Respuesta(6,"(Colombia)",2,False)
r7 = Respuesta(7,"(China)",2,True)
r8 = Respuesta(8,"(Uruguay)",2,False)

r9 = Respuesta(9,"(Odín)",3,False)
r10 = Respuesta(10,"(Ra)",3,True)
r11 = Respuesta(11,"(platón)",3,False)
r12 = Respuesta(12,"(David)",3,False)

r13 = Respuesta(13,"(Álvaro Uribe)",4,False)
r14 = Respuesta(14,"(George Washington)",4,True)
r15 = Respuesta(15,"(Simón Bolívar)",4,False)
r16 = Respuesta(16,"(Elkin Patarroyo)",4,False)

r17 = Respuesta(17,"(benjamín)",5,False)
r18 = Respuesta(18,"(Simón)",5,False)
r19 = Respuesta(19,"(Alberto)",5,False)
r20 = Respuesta(20,"(Homero)",5,True)

r21 = Respuesta(21,"(Santiago Bernabéu) ",6,True)
r22 = Respuesta(22,"(Wanda Metropolitano)",6,False)
r23 = Respuesta(23,"(Camp Nou)",6,False)
r24 = Respuesta(24,"(San Mames)",6,False)

r25 = Respuesta(25,"((Futbol))",7,False)
r26 = Respuesta(26,"((Natación))",7,False)
r27 = Respuesta(27,"(vóleibol)",7,False)
r28 = Respuesta(28,"(Golf)",7,True)

r29 = Respuesta(29,"(Perú)",8,False)
r30 = Respuesta(30,"(China)",8,False)
r31 = Respuesta(31,"(España)",8,False)
r32 = Respuesta(32,"(Alemania)",8,True)

r33 = Respuesta(33,"(Colombia)",9,True)
r34 = Respuesta(34,"(Chile)",9,False)
r35 = Respuesta(35,"(Ecuador)",9,False)
r36 = Respuesta(36,"(Alemania)",9,False)

r37 = Respuesta(37,"(AC Milán)",10,False)
r38 = Respuesta(38,"(Juventus FC)",10,False)
r39 = Respuesta(39,"(S.S Lazio)",10,False)
r40 = Respuesta(40,"(AS Roma)",10,True)

r41 = Respuesta(41,"(Nilo)",11,False)
r42 = Respuesta(42,"(Amazonas)",11,True)
r43 = Respuesta(43,"(Congo)",11,False)
r44 = Respuesta(44,"(Misisipi)",11,False)

r45 = Respuesta(45,"(Atlántico)",12,False)
r46 = Respuesta(46,"(Indico)",12,False)
r47 = Respuesta(47,"(océano Pacífico)",12,True)
r48 = Respuesta(48,"(Ártico)",12,False)

r49 = Respuesta(49,"(Siete lados) ",13,True)
r50 = Respuesta(50,"(Seis lados)",13,False)
r51 = Respuesta(51,"(Cinco lados)",13,False)
r52 = Respuesta(52,"(Diez lados)",13,False)

r53 = Respuesta(53,"(Plutón)",14,False)
r54 = Respuesta(54,"(Júpiter)",14,True)
r55 = Respuesta(55,"(Urano)",14,False)
r56 = Respuesta(56,"(Neptuno)",14,False)

r57= Respuesta(57,"(206)",15,True)
r58= Respuesta(58,"(300)",15,False)
r59= Respuesta(59,"(400)",15,False)
r60= Respuesta(60,"(150)",15,False)

r61= Respuesta(61,"(Dos)",16,False)
r62= Respuesta(62,"(Quince)",16,False)
r63= Respuesta(63,"(Cinco)",16,True)
r64= Respuesta(64,"(Diez)",16,False)

r65= Respuesta(65,"(380 días)",17,False)
r66= Respuesta(66,"(300 días)",17,False)
r67= Respuesta(67,"(400 días)",17,False)
r68= Respuesta(68,"(366 días)",17,True)

r69= Respuesta(69,"(Ocho)",18,True)
r70= Respuesta(70,"(Dos)",18,False)
r71= Respuesta(71,"(Diez)",18,False)
r72= Respuesta(72,"(Cinco)",18,False)

r73= Respuesta(73,"(Un corazón)",19,False)
r74= Respuesta(74,"(Dos corazones)",19,False)
r75= Respuesta(75,"(Tres corazones)",19,True)
r76= Respuesta(76,"(Cinco corazones)",19,False)

r77= Respuesta(77,"(70)",20,False)
r78= Respuesta(78,"(90)",20,True)
r79= Respuesta(79,"(100)",20,False)
r80= Respuesta(80,"(60)",20,False)

r81= Respuesta(81,"(20 Horas)",21,False)
r82= Respuesta(82,"(15 Horas)",21,False)
r83= Respuesta(83,"(12 Horas)",21,False)
r84= Respuesta(84,"(24 Horas)",21,True)

r85= Respuesta(85,"(50 minutos)",22,False)
r86= Respuesta(86,"(40 minutos)",22,False)
r87= Respuesta(87,"(60 minutos",22,True)
r88= Respuesta(88,"(24 Minutos)",22,False)

r89= Respuesta(89,"(20)",23,False)
r90= Respuesta(90,"(32)",23,True)
r91= Respuesta(91,"(40)",23,False)
r92= Respuesta(92,"(24)",23,False)

r93= Respuesta(93,"(Tres)",24,True)
r94= Respuesta(94,"(Cuatro)",24,False)
r95= Respuesta(95,"(Cinco)",24,False)
r96= Respuesta(96,"(Diez)",24,False)

r97= Respuesta(97,"(Pereira)",25,False)
r98= Respuesta(98,"(Cali)",25,False)
r99= Respuesta(99,"(Bogota)",25,True)
r100= Respuesta(100,"(Barranquilla)",25,False)

#lista de preguntas
preguntas = [p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11,p12,p13,p14,p15,p16,p17,p18,p19,p20,p21,p22,p23,p24,p25]
# lista de respuestas
respuestas = [r1,r2,r3,r4,r5,r6,r7,r8,r9,r10,r11,r12,r13,r14,r15,r16,r17,r18,r19,r20,
    r21,r22,r23,r24,r25,r26,r27,r28,r29,r30,r31,r32,r33,r34,r35,r36,r37,r38,r39,r40,
    r41,r42,r43,r44,r45,r46,r47,r48,r49,r50,r51,r52,r53,r54,r55,r56,r57,r58,r59,r60,r61,r62,r63,
    r64,r65,r66,r67,r68,r69,r70,r71,r72,r73,r74,r75,r76,r77,r78,r79,r80,r81,r82,r83,r84,r85,r86,r87,r88,r89,r90,
    r91,r92,r93,r94,r95,r96,r97,r98,r99,r100]

print("Jugar")

# datos del jugador
nombres = input("registrar nombres:")
apellidos = input("registrar apellidos:")

#funcion  retorna las respuestas de la pregunta
def dimeRespuestas(preguntaId):
    lista = []
    for r in respuestas:
        if r.dime_preguntaId() == preguntaId:
            lista.append(r)
    return lista

# Se crea en la raiz, la base de datos "historico_jugador" al finalizar la ejecucion del programa.
def guardar(nom,apell,puntaje):
    conexion = sqlite3.connect("historico_jugador")
    cursor = conexion.cursor()
    sql = "CREATE TABLE IF NOT EXISTS HISTORICO (NOMBRE VARCHAR(50),APELLIDO VARCHAR(50),PUNTAJE INTEGER)"
    cursor.execute(sql)
    insert = "INSERT INTO HISTORICO VALUES (?,?,?)"
    jugador = [(nom,apell,puntaje)]
    cursor.executemany(insert,jugador)
    conexion.commit()
    cursor.close()

for i in preguntas:
    contadorPreguntas +=1
    print("Pregunta ", contadorPreguntas)
    print("Categoria ", i.dime_categoria())
    print(i.dime_descripcion())
    print("RESPUESTAS")
    #buscar pregunta
    respuestaOpciones = dimeRespuestas(i.dime_id())
    print("A:",respuestaOpciones[0].dime_opcion())
    print("B:",respuestaOpciones[1].dime_opcion())
    print("C:",respuestaOpciones[2].dime_opcion())
    print("D:",respuestaOpciones[3].dime_opcion())
    A = respuestaOpciones[0].dime_isTrue()
    B = respuestaOpciones[1].dime_isTrue()
    C = respuestaOpciones[2].dime_isTrue()
    D = respuestaOpciones[3].dime_isTrue()
    opcionSeleccionada =  input("ESCRIBA LA RESPUESTA: (A,B,C,D):")
    if contadorPreguntas <= 5:
        if opcionSeleccionada.upper() == "A":
            if A:
                print("Correcto!")
                puntos += 1
                print("Puntos:",puntos)

            else:
                puntos = 0
                print('inCorrecta')
                guardar(nombres,apellidos,puntos)
                break
        elif opcionSeleccionada.upper() == "B":
             if B:
                print("Correcto!")
                puntos += 1
                print("Puntos:",puntos)

             else:
                puntos = 0
                print('inCorrecta')
                guardar(nombres,apellidos,puntos)
                break
        elif opcionSeleccionada.upper() == "C":
             if C:
                print("Correcto!")
                puntos += 1
                print("Puntos:",puntos)
             else:
                puntos = 0
                print('inCorrecta')
                guardar(nombres,apellidos,puntos)
                break
        elif opcionSeleccionada.upper() == "D":
             if D:
                print("Correcto!")
                puntos += 1
                print("Puntos:",puntos)
             else:
                puntos = 0
                print('inCorrecta')
                guardar(nombres,apellidos,puntos)
                break
    elif contadorPreguntas > 5 and contadorPreguntas <= 10:
        if opcionSeleccionada.upper() == "A":
            if A:
                print("Correcto!")
                puntos += 2
                print("Puntos:",puntos)

            else:
                puntos = 0
                print('inCorrecta')
                guardar(nombres,apellidos,puntos)
                break
        elif opcionSeleccionada.upper() == "B":
             if B:
                print("Correcto!")
                puntos += 2
                print("Puntos:",puntos)

             else:
                puntos = 0
                print('inCorrecta')
                guardar(nombres,apellidos,puntos)
                break
        elif opcionSeleccionada.upper() == "C":
             if C:
                print("Correcto!")
                puntos += 2
                print("Puntos:",puntos)
             else:
                puntos = 0
                print('inCorrecta')
                guardar(nombres,apellidos,puntos)
                break
        elif opcionSeleccionada.upper() == "D":
             if D:
                print("Correcto!")
                puntos += 2
                print("Puntos:",puntos)
             else:
                puntos = 0
                print('inCorrecta')
                guardar(nombres,apellidos,puntos)
                break
    elif contadorPreguntas > 10 and contadorPreguntas <= 15:
        if opcionSeleccionada.upper() == "A":
            if A:
                print("Correcto!")
                puntos += 3
                print("Puntos:",puntos)
            else:
                puntos = 0
                print('inCorrecta')
                guardar(nombres,apellidos,puntos)
                break
        elif opcionSeleccionada.upper() == "B":
             if B:
                print("Correcto!")
                puntos += 3
                print("Puntos:",puntos)

             else:
                puntos = 0
                print('inCorrecta')
                guardar(nombres,apellidos,puntos)
                break
        elif opcionSeleccionada.upper() == "C":
             if C:
                print("Correcto!")
                puntos += 3
                print("Puntos:",puntos)

             else:
                puntos = 0
                print('inCorrecta')
                guardar(nombres,apellidos,puntos)
                break
        elif opcionSeleccionada.upper() == "D":
             if D:
                print("Correcto!")
                puntos += 3
                print("Puntos:",puntos)
             else:
                puntos = 0
                print('inCorrecta')
                guardar(nombres,apellidos,puntos)
                break
    elif contadorPreguntas > 15 and contadorPreguntas <= 20:
        if opcionSeleccionada.upper() == "A":
            if A:
                print("Correcto!")
                puntos += 4
                print("Puntos:",puntos)

            else:
                puntos = 0
                print('inCorrecta')
                guardar(nombres,apellidos,puntos)
                break
        elif opcionSeleccionada.upper() == "B":
             if B:
                print("Correcto!")
                puntos += 4
                print("Puntos:",puntos)
             else:
                puntos = 0
                print('inCorrecta')
                guardar(nombres,apellidos,puntos)
                break
        elif opcionSeleccionada.upper() == "C":
             if C:
                print("Correcto!")
                puntos += 4
                print("Puntos:",puntos)
             else:
                puntos = 0
                print('inCorrecta')
                guardar(nombres,apellidos,puntos)
                break
        elif opcionSeleccionada.upper() == "D":
             if D:
                print("Correcto!")
                puntos += 4
                print("Puntos:",puntos)
             else:
                puntos = 0
                print('inCorrecta')
                guardar(nombres,apellidos,puntos)
                break
    elif contadorPreguntas > 20 and contadorPreguntas <= 25:
        if opcionSeleccionada.upper() == "A":
            if A:
                print("Correcto!")
                puntos += 5
                print("Puntos:",puntos)
            else:
                puntos = 0
                print('inCorrecta')
                guardar(nombres,apellidos,puntos)
                break
        elif opcionSeleccionada.upper() == "B":
             if B:
                print("Correcto!")
                puntos += 5
                print("Puntos:",puntos)
             else:
                puntos = 0
                print('inCorrecta')
                guardar(nombres,apellidos,puntos)
                break
        elif opcionSeleccionada.upper() == "C":
             if C:
                print("Correcto!")
                puntos += 5
                print("Puntos:",puntos)
             else:
                puntos = 0
                print('inCorrecta')
                guardar(nombres,apellidos,puntos)
                break
        elif opcionSeleccionada.upper() == "D":
             if D:
                print("Correcto!")
                puntos += 5
                print("Puntos:",puntos)

             else:
                puntos = 0
                print('inCorrecta')
                guardar(nombres,apellidos,puntos)
                break

    if contadorPreguntas == 25:
        print('FELICIDADES TERMINASTE EL JUEGO')
        print("PUNTAJE TOTAL OBTENIDO:", puntos)
        guardar(nombres,apellidos,puntos)
        break
    else:
        respuesta = input('Desea seguir en el juego?: ("SI,NO"):')
        if respuesta.upper() == "NO":
            print('JUEGO TERMINADO')
            print("PUNTAJE OBTENIDO:",puntos)
            guardar(nombres,apellidos,puntos)
            break


from __future__ import absolute_import, print_function

import shutil
import tempfile

import pytest
from flask import Flask
from flask_menu import Menu
from invenio_accounts import InvenioAccounts
from invenio_assets import InvenioAssets
from invenio_jsonschemas import InvenioJSONSchemas

from invenio_records_editor.ext import InvenioRecordsEditor
from invenio_records_editor.views import create_editor_blueprint

@pytest.fixture()
def editor_config():
    """Editor example config."""
    config = {
        "items": {
            "recordConfig": {
                "apiUrl": "api/items/",
                "schema": "items/item-v1.0.0.json",
            },
            "editorConfig": {
                "schemaOptions": {
                    "alwaysShow": [
                        "legacy_id",
                        "shelf",
                        "description",
                        "circulation_restriction",
                        "medium",
                        "legacy_library_id",
                    ],
                    "properties": {
                        "$schema": {"hidden": True},
                        "document": {"hidden": True},
                        "internal_location": {"hidden": True},
                        "circulation_status": {"hidden": True},
                    },
                }
            },
        }
    }
    return config

@pytest.fixture()
def instance_path():
    """Temporary instance path."""
    path = tempfile.mkdtemp()
    yield path
    shutil.rmtree(path)

@pytest.fixture()
def base_app(instance_path, editor_config):
    """Flask application fixture."""
    app = Flask("testapp", instance_path=instance_path)

    app.config.update(
        SECRET_KEY="SECRET_KEY", TESTING=True, SERVER_NAME="localhost"
    )
    app.config.update(RECORDS_EDITOR_UI_CONFIG=editor_config)

    InvenioAccounts(app)
    InvenioAssets(app)
    InvenioJSONSchemas(app)
    InvenioRecordsEditor(app)
    Menu(app)

    from invenio_accounts.views.settings import blueprint
    app.register_blueprint(blueprint)

    app.register_blueprint(create_editor_blueprint(app))
    return app

@pytest.fixture()
def app(base_app):
    """Flask application fixture."""
    with base_app.app_context():
        yield base_app


import unittest
import numpy as np
import tensorflow as tf
import tensorflow.keras as ks
from kgcnn.utils.data import ragged_tensor_from_nested_numpy

from gnn_teacher_student.layers import NodeImportanceLayer
from .util import generate_simple_random_graph, model_weights_similar, x_elem

# Disable the GPU - Not supported by KGCNN
tf.config.set_visible_devices([], 'GPU')

class TestNodeImportanceLayer(unittest.TestCase):

    class Model(ks.models.Model):

        def __init__(self):
            ks.models.Model.__init__(self)

            self.lay_node_importance = NodeImportanceLayer(
                units=10
            )

        def call(self, inputs):
            node_importances = self.lay_node_importance(inputs)
            return node_importances

    @classmethod
    def setUpClass(cls) -> None:
        cls.node_attribute_count = 2
        cls.edge_attribute_count = 1

        cls.graphs = [generate_simple_random_graph(
            node_feature_count=cls.node_attribute_count
        ) for _ in range(10)]
        for graph_data in cls.graphs:
            graph_data['graph_labels'] = np.ones(
                shape=(len(graph_data['node_attributes']), ),
                dtype=np.int32
            )

        cls.x_train = [
            ragged_tensor_from_nested_numpy([gd['node_attributes'] for gd in cls.graphs]),
            ragged_tensor_from_nested_numpy([gd['edge_attributes'] for gd in cls.graphs]),
            ragged_tensor_from_nested_numpy([gd['edge_indices'] for gd in cls.graphs])
        ]
        cls.y_train = [
            ragged_tensor_from_nested_numpy([gd['graph_labels'] for gd in cls.graphs])
        ]

    def test_dataset_exists(self):
        self.assertTrue(hasattr(self, 'graphs'))
        self.assertTrue(isinstance(self.graphs, list))
        self.assertNotEqual(0, len(self.graphs))
        self.assertTrue(isinstance(self.graphs[0], dict))

        self.assertTrue(hasattr(self, 'x_train'))
        self.assertTrue(isinstance(self.x_train, list))

    def test_construction_basically_works(self) -> None:
        layer = NodeImportanceLayer(
            units=10
        )
        self.assertTrue(isinstance(layer, NodeImportanceLayer))

    def test_training(self) -> None:

        # Constructing a simple model
        model = self.Model()
        model.compile(
            loss=ks.losses.BinaryCrossentropy(),
            optimizer=ks.optimizers.Adam()
        )
        model(self.x_train)  # build the model

        weights_before = model.get_weights()
        model.fit(self.x_train, self.y_train, batch_size=2, epochs=1, verbose=0)
        weights_after = model.get_weights()

        # The model weights should be a little bit different after training
        self.assertFalse(model_weights_similar(weights_before, weights_after))

    def test_output(self):
        model = self.Model()

        # The output of the layer is the
        x = x_elem(self.x_train, 2)
        node_importances = model(x)
        # batch size 1
        self.assertEqual(1, node_importances.shape[0])
        # The graph size is ragged -> None
        self.assertEqual(None, node_importances.shape[1])
        # Attention coefficients are a single value per node
        self.assertEqual(1, node_importances.shape[2])

        # This layer uses a softmax activation on all the elements in the end, this means that
        # all the individual elements should be normalized such that they add up to 1
        importance_sum = float(tf.reduce_sum(node_importances))
        self.assertAlmostEqual(1, importance_sum)

    def test_lock_parameters(self) -> None:
        # Constructing a simple model
        model = self.Model()
        # ! IMPORTANT: model.compile() has to be called after changing the trainability of parameters or it
        # will not take effect!
        model.lay_node_importance.trainable = False
        model.compile(
            loss=ks.losses.BinaryCrossentropy(),
            optimizer=ks.optimizers.Adam()
        )
        model(self.x_train)

        weights_before = model.get_weights()
        model.fit(self.x_train, self.y_train, batch_size=2, epochs=1, verbose=0)
        weights_after = model.get_weights()

        self.assertTrue(model_weights_similar(weights_before, weights_after))


from django.contrib.auth import get_user_model

from rest_framework import serializers
from rest_framework.relations import SlugRelatedField

from posts.models import Comment, Follow, Group, Post

User = get_user_model()

class PostSerializer(serializers.ModelSerializer):
    author = SlugRelatedField(slug_field='username', read_only=True)

    class Meta:
        fields = '__all__'
        model = Post

class GroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = '__all__'

class CommentSerializer(serializers.ModelSerializer):
    author = serializers.SlugRelatedField(
        read_only=True, slug_field='username'
    )

    class Meta:
        fields = '__all__'
        model = Comment

class FollowSerializer(serializers.ModelSerializer):
    user = serializers.SlugRelatedField(
        read_only=True, slug_field='username'
    )
    following = serializers.SlugRelatedField(
        queryset=User.objects.all(), slug_field='username'
    )

    class Meta:
        fields = '__all__'
        model = Follow

    def validate(self, data):
        follower = self.context.get('request').user
        following = data.get('following')

        if Follow.objects.filter(user=follower, following=following).exists():
            raise serializers.ValidationError(
                'Вы уже подписаны на данного пользователя.'
            )

        if follower == following:
            raise serializers.ValidationError(
                'Нельзя подписаться на самого себя.'
            )
        return data


#Working towards a simple method of fasta header pre-processing (purely for

#USAGE: "python3 prePro.py3 [input file]"

import sys, os
inFile = open(sys.argv[1], "r")
#idLoc = sys.argv[2]
#cyLoc = sys.argv[3]
outfile = open(sys.argv[2]+"PP.fas", "a+")

#print(idLoc)
#print(cyLoc)

for line in inFile:
	if line.startswith(">"):
		line = line.strip('>').strip('\n')

		seqId = line.split('_')[1]
		#for i in range(0,int(len(idLoc)/2)):
			#seqId = seqId.split(idLoc[i*2])[int(idLoc[i*2+1])]

		seqCy = line.split('_')[len(line.split('_'))-1]
		#for i in range(0,int(len(cyLoc)/2)):
			#seqCy = seqCy.split(cyLoc[i*2])[int(cyLoc[i*2+1])]

		line = (">" + seqId + "_" + str(seqCy) + '\n')
		outfile.write(line)

	else:
		outfile.write(line)


"""SumOfNumber"""
def main():
    """SumOfNumber"""
    num_1 = int(input())
    num_2 = int(input())
    while num_2 != num_1:
        num = int(input())
        if num == -1:
            break
        num_2 += num
    print(num_2)
main()


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

# In[1]:

import json
import torch
import gensim
from gensim.test.utils import datapath, get_tmpfile
from gensim.models import KeyedVectors
from gensim.scripts.glove2word2vec import glove2word2vec
from transformers import *
import torch.utils.data as Data
import collections
import os
import random
import tarfile
from torch import nn
import torchtext.vocab as Vocab
import pickle as pk
import torch.nn.functional as F
from IPython.display import display,HTML
from torch.nn.utils.rnn import pad_sequence
from torch.nn.utils.rnn import pack_padded_sequence
from torch.nn.utils.rnn import pad_packed_sequence
from torch.nn.utils.rnn import pack_sequence
from torch.nn import CrossEntropyLoss, MSELoss
from torchcrf import CRF
from sklearn import metrics
import joblib
import math
device=torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
import argparse
import glob
import unicodedata
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset
from torch.utils.data.distributed import DistributedSampler
from tqdm import tqdm_notebook as tqdm
import torch.utils.data as Data
import jieba
import jieba.posseg as pseg
import copy
import time
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import random
from sklearn.model_selection import KFold

# In[2]:

def convert_text_to_ids(tokenizer, text, max_len=100):
    if isinstance(text,str):
        output=tokenizer.encode_plus(text,max_length=max_len,pad_to_max_length=True,return_tensors="pt")
        input_ids=output["input_ids"].squeeze(0)
        token_type_ids=output["token_type_ids"].squeeze(0)
        attention_mask=output["attention_mask"].squeeze(0)
    elif isinstance(text,list):
        input_ids,token_type_ids,attention_mask=[],[],[]
        for e in text:
            output=tokenizer.encode_plus(e,max_length=max_len,pad_to_max_length=True,return_tensors="pt")
            input_ids.append(output["input_ids"].squeeze(0))
            token_type_ids.append(output["token_type_ids"].squeeze(0))
            attention_mask.append(output["attention_mask"].squeeze(0))
    else:
        raise Exception('type error')
    return torch.stack(input_ids).long(),torch.stack(token_type_ids).long(),torch.stack(attention_mask).long()
class RelDataset(Data.Dataset):
    def __init__(self,examples):
        self.input_ids=torch.stack([e['input_ids'] for e in examples]).long()
        self.token_type_ids=torch.stack([e['token_type_ids'] for e in examples]).long()
        self.attention_mask=torch.stack([e['attention_mask'] for e in examples]).long()
        self.rel_label=torch.stack([e['rel_label'] for e in examples]).long()
        self.postag=torch.stack([e['postag'] for e in examples]).long()
        self.feature=torch.stack([e['feature'] for e in examples]).float()
        self.token_vec=np.stack([np.array(e['token_vec']) for e in examples])
        self.word_vec=np.stack([np.array(e['word_vec']) for e in examples])
        self.word_mask=np.stack([np.array(e['word_mask']) for e in examples])
        self.token2docs=[e["token2doc"] for e in examples]
    def __len__(self):
        return self.input_ids.shape[0]
    def __getitem__(self,idx):
        return self.input_ids[idx],self.attention_mask[idx],self.token_type_ids[idx],               self.rel_label[idx],self.postag[idx],self.feature[idx],self.token_vec[idx],self.word_vec[idx],               self.word_mask[idx],self.token2docs[idx]
class NerDataset(Data.Dataset):
    def __init__(self,examples):
        self.input_ids=torch.stack([e['input_ids'] for e in examples]).long()
        self.token_type_ids=torch.stack([e['token_type_ids'] for e in examples]).long()
        self.attention_mask=torch.stack([e['attention_mask'] for e in examples]).long()
        self.rel_label=torch.stack([e['rel_label'] for e in examples]).long()
        self.labels=torch.stack([e['labels'] for e in examples]).long()
        self.postag=torch.stack([e['postag'] for e in examples]).long()
        self.feature=torch.stack([e['feature'] for e in examples]).float()
        self.token2docs=[e["token2doc"] for e in examples]
    def __len__(self):
        return self.input_ids.shape[0]
    def __getitem__(self,idx):
        return self.input_ids[idx],self.attention_mask[idx],self.token_type_ids[idx],               self.rel_label[idx],self.labels[idx],self.postag[idx],self.feature[idx],self.token2docs[idx]
import unicodedata
def _is_whitespace(char):
    """Checks whether `chars` is a whitespace character."""
    # \t, \n, and \r are technically contorl characters but we treat them
    # as whitespace since they are generally considered as such.
    if char == " " or char == "\t" or char == "\n" or char == "\r":
        return True
    cat = unicodedata.category(char)
    if cat == "Zs":
        return True
    return False
def is_chinese_char(cp):
    """Checks whether CP is the codepoint of a CJK character."""
    # This defines a "chinese character" as anything in the CJK Unicode block:
    #   https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
    #
    # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
    # despite its name. The modern Korean Hangul alphabet is a different block,
    # as is Japanese Hiragana and Katakana. Those alphabets are used to write
    # space-separated words, so they are not treated specially and handled
    # like the all of the other languages.
    if (
        (cp >= 0x4E00 and cp <= 0x9FFF)
        or (cp >= 0x3400 and cp <= 0x4DBF)  #
        or (cp >= 0x20000 and cp <= 0x2A6DF)  #
        or (cp >= 0x2A700 and cp <= 0x2B73F)  #
        or (cp >= 0x2B740 and cp <= 0x2B81F)  #
        or (cp >= 0x2B820 and cp <= 0x2CEAF)  #
        or (cp >= 0xF900 and cp <= 0xFAFF)
        or (cp >= 0x2F800 and cp <= 0x2FA1F)  #
    ):  #
        return True

    return False
def is_punctuation(char):
    """Checks whether `chars` is a punctuation character."""
    cp = ord(char)
    # We treat all non-letter/number ASCII as punctuation.
    # Characters such as "^", "$", and "`" are not in the Unicode
    # Punctuation class but we treat them as punctuation anyways, for
    # consistency.
    if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126):
        return True
    cat = unicodedata.category(char)
    if cat.startswith("P"):
        return True
    return False
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import TruncatedSVD

def build_tfidf_svd_matrix(texts,n_output,tfidf_vec=None,svd=None):
    corpus=[]
    for text in tqdm(texts):
#         print(text)
        words=word_segment(str(text['text']))
#         print(words)
        use_words=[]
        for word in words:
            if word in stop_words:
                continue
            use_words.append(word)
#         print(use_words)
        corpus.append(" ".join(use_words))
    print(len(corpus))
    print(corpus[0])
    if tfidf_vec is None:
        tfidf_vec=TfidfVectorizer()
        tfidf_matrix=tfidf_vec.fit_transform(corpus)
    else:
        tfidf_matrix=tfidf_vec.transform(corpus)
    if svd is None:
        svd=TruncatedSVD(n_components=n_output,n_iter=7,random_state=42)
        tf_idf_svd=svd.fit_transform(tfidf_matrix)
    else:
        tf_idf_svd=svd.transform(tfidf_matrix)
    return tf_idf_svd,tfidf_vec,svd
def word_segment(sentence):
    words=jieba.cut(sentence)
    return ",".join(words).split(",")
stop_words=set()
def load_stopwords():
    with open("./middle_data/stopwords.txt","r",encoding="UTF-8") as r:
        for line in r.readlines():
            stop_words.add(line.strip())
load_stopwords()
def remove_stopwords(word_list):
    res=[]
    for word in word_lists:
        if word not in stop_words:
            res.append(word)
    return ' '.join(res)
def clean_text(string):
    return string.replace(' ', '').replace('\n', '').replace('\u3000', '')
def _convert_example_to_record(example,
                               tokenizer):
    if example.__contains__('spo_list'):
        spo_list = example['spo_list']
    else:
        spo_list = []
    text_raw = example['text']
    sub_text = []
    buff = ""
    for char in text_raw:
        if is_chinese_char(ord(char)) or is_punctuation(char):
            if buff != "":
                sub_text.append(buff)
                buff = ""
            sub_text.append(char)
        else:
            buff += char
    if buff != "":
        sub_text.append(buff)
    tok_to_orig_start_index = []
    tok_to_orig_end_index = []
    orig_to_tok_index = []
    tokens = []
    text_tmp = ''
    for (i, token) in enumerate(sub_text):
        orig_to_tok_index.append(len(tokens))
        sub_tokens = tokenizer.tokenize(token)
        text_tmp += token
        for sub_token in sub_tokens:
            tok_to_orig_start_index.append(len(text_tmp) - len(token))
            tok_to_orig_end_index.append(len(text_tmp) - 1)
            tokens.append(sub_token)
        else:
            continue
        break
    #  find all entities and tag them with corresponding "B"/"I" labels
    labels_list=[[0
              for i in range(len(tokens))] for i in range(len(id2rels))]
    rel_labels=[]
    for spo in spo_list:
        for spo_object in spo['object'].keys():
            if not spo['predicate'] in special_rels:
                rel_label=rels2id[spo["predicate"]]
            else:
                rel_label=rels2id[spo["predicate"]+"_"+spo_object]
            labels = labels_list[rel_label] #复杂类的不同part还是不会被归到一个，以后再讲
            label_subject = label2ids['B-SUB']
            label_object = label2ids['B-OBJ']
            subject_sub_tokens = tokenizer.tokenize(spo['subject'])
            object_sub_tokens = tokenizer.tokenize(spo['object'][
                spo_object])
            forbidden_index = None
            if len(subject_sub_tokens) > len(object_sub_tokens):
                for index in range(
                        len(tokens) - len(subject_sub_tokens) + 1):
                    if tokens[index:index + len(
                            subject_sub_tokens)] == subject_sub_tokens:
                        labels[index]=label_subject
                        for i in range(len(subject_sub_tokens) - 1):
                            labels[index + i + 1]=label_subject+1
                        forbidden_index = index
                        break

                for index in range(
                        len(tokens) - len(object_sub_tokens) + 1):
                    if tokens[index:index + len(
                            object_sub_tokens)] == object_sub_tokens:
                        if forbidden_index is None:
                            labels[index]=label_object
                            for i in range(len(object_sub_tokens) - 1):
                                labels[index + i + 1]=label_object+1
                            break
                        # check if labeled already
                        elif index < forbidden_index or index >= forbidden_index + len(
                                subject_sub_tokens):
                            labels[index]=label_object
                            for i in range(len(object_sub_tokens) - 1):
                                labels[index + i + 1]=label_object+1
                            break

            else:
                for index in range(
                        len(tokens) - len(object_sub_tokens) + 1):
                    if tokens[index:index + len(
                            object_sub_tokens)] == object_sub_tokens:
                        labels[index]=label_object
                        for i in range(len(object_sub_tokens) - 1):
                            labels[index + i + 1]=label_object+1
                        forbidden_index = index
                        break

                for index in range(
                        len(tokens) - len(subject_sub_tokens) + 1):
                    if tokens[index:index + len(
                            subject_sub_tokens)] == subject_sub_tokens:
                        if forbidden_index is None:
                            labels[index]=label_subject
                            for i in range(len(subject_sub_tokens) - 1):
                                labels[index + i + 1]=label_subject+1
                            break
                        elif index < forbidden_index or index >= forbidden_index + len(
                                object_sub_tokens):
                            labels[index]=label_subject
                            for i in range(len(subject_sub_tokens) - 1):
                                labels[index + i + 1]=label_subject+1
                            break
            labels_list[rel_label]=labels
            if rel_label not in rel_labels:
                rel_labels.append(rel_label)

    return tok_to_orig_start_index,tok_to_orig_end_index,orig_to_tok_index,tokens,labels_list,rel_labels
def _convert_example_to_cls_record(example,
                               tokenizer):
    if example.__contains__('spo_list'):
        spo_list = example['spo_list']
    else:
        spo_list = []
    text_raw = example['text']
    sub_text = []
    buff = ""
    for char in text_raw:
        if is_chinese_char(ord(char)) or is_punctuation(char):
            if buff != "":
                sub_text.append(buff)
                buff = ""
            sub_text.append(char)
        else:
            buff += char
    if buff != "":
        sub_text.append(buff)
    tok_to_orig_start_index = []
    tok_to_orig_end_index = []
    orig_to_tok_index = []
    tokens = []
    text_tmp = ''
    for (i, token) in enumerate(sub_text):
        orig_to_tok_index.append(len(tokens))
        sub_tokens = tokenizer.tokenize(token)
        text_tmp += token
        for sub_token in sub_tokens:
            tok_to_orig_start_index.append(len(text_tmp) - len(token))
            tok_to_orig_end_index.append(len(text_tmp) - 1)
            tokens.append(sub_token)
        else:
            continue
        break
    #  find all entities and tag them with corresponding "B"/"I" labels
    labels_list=[]
    rel_labels=[]
    for spo in spo_list:
        for spo_object in spo['object'].keys():
            labels = [0
                  for i in range(len(tokens))]  # initialize tag
            if not spo['predicate'] in special_rels:
                rel_label=rels2id[spo["predicate"]]
            else:
                rel_label=rels2id[spo["predicate"]+"_"+spo_object]
            rel_labels.append(rel_label)

    return tok_to_orig_start_index,tok_to_orig_end_index,orig_to_tok_index,tokens,rel_labels
def create_cls_example(tokens,rel,token2doc,postag,tfidf_svd,word_vec,token_vec,tokenizer):
        word_vec=copy.deepcopy(word_vec)
        token_vec=copy.deepcopy(token_vec)
        if len(tokens)>max_len-2:
                tokens=tokens[:(max_len-2)]
                token2doc=[e[:(max_len-2)] if ind<2 else e for ind,e in enumerate(token2doc)]
        tag=[postag[token2doc[0][idx]] for idx in range(len(tokens))]
        tokenvec=[token_vec[token2doc[0][idx]] for idx in range(len(tokens))]
        tag=[pos2id_BIO[tokenizer.cls_token]]+tag+[pos2id_BIO[tokenizer.sep_token]]
        tokenvec=[word2id[tokenizer.cls_token]]+tokenvec+[word2id[tokenizer.sep_token]]
        full_tokens=[tokenizer.cls_token]+tokens+[tokenizer.sep_token]
        token_type_ids=[0]*len(full_tokens)
        attention_mask=[1]*len(token_type_ids)
        cur_len=len(full_tokens)
        if cur_len<max_len:
            full_tokens+=[tokenizer.pad_token]*(max_len-cur_len)
            attention_mask+=[0]*(max_len-cur_len)
            token_type_ids+=[0]*(max_len-cur_len)
            tag+=[pos2id_BIO[tokenizer.pad_token]]*(max_len-cur_len)
            tokenvec+=[word2id[tokenizer.pad_token]]*(max_len-cur_len)
        if len(word_vec)>max_len//2:
            word_vec=word_vec[:max_len//2]
        word_mask=[1]*len(word_vec)
        if len(word_vec)<max_len//2:
            word_mask+=[0]*(max_len//2-len(word_vec))
            word_vec+=[word2id[tokenizer.pad_token]]*(max_len//2-len(word_vec))

        full_ids=tokenizer.convert_tokens_to_ids(full_tokens)
        if len(rel)>0:
            example={"input_ids":torch.tensor(full_ids,dtype=torch.long),"token_type_ids":torch.tensor(token_type_ids,dtype=torch.long),                    "attention_mask":torch.tensor(attention_mask,dtype=torch.long),
                    "rel_label":(F.one_hot(torch.tensor(rel),len(id2rels)).sum(dim=0)!=0).long(),
                     "postag":torch.tensor(tag).long(),"feature":torch.tensor(tfidf_svd).float(),\
                     "token_vec":tokenvec,"word_vec":word_vec,"word_mask":word_mask,"token2doc":token2doc}
        else:
            example={"input_ids":torch.tensor(full_ids,dtype=torch.long),"token_type_ids":torch.tensor(token_type_ids,dtype=torch.long),                    "attention_mask":torch.tensor(attention_mask,dtype=torch.long),
                     "rel_label":torch.zeros(len(id2rels)).long(),
                     "postag":torch.tensor(tag).long(),"feature":torch.tensor(tfidf_svd).float(),\
                     "token_vec":tokenvec,"word_vec":word_vec,"word_mask":word_mask,"token2doc":token2doc}
        return example
def create_example(tokens,rel,labels,token2doc,tokenizer,rel_text,tfidf_svd,postag,rel_postag,rel_token2doc):
        tag=[postag[token2doc[0][idx]] for idx in range(len(tokens))]
        tag=[pos2id_BIO[tokenizer.cls_token]]+tag+[pos2id_BIO[tokenizer.sep_token]]
        rel_tag=[rel_postag[rel_token2doc[idx]] for idx in range(len(rel_text))]
        rel_tag=rel_tag+[pos2id_BIO[tokenizer.sep_token]]
        tag=tag+rel_tag
        second_token=rel_text
        full_tokens=[[tokenizer.cls_token]+tokens+[tokenizer.sep_token],second_token+[tokenizer.sep_token]]
        full_labels=[[label2ids[tokenizer.cls_token]]+labels+[label2ids[tokenizer.sep_token]],[label2ids["[category]"]]*len(second_token)+[label2ids[tokenizer.sep_token]]]
        token_type_ids=[0]*len(full_tokens[0])+[1]*len(full_tokens[1])
        attention_mask=[1]*len(token_type_ids)
        full_tokens=full_tokens[0]+full_tokens[1]
        full_labels=full_labels[0]+full_labels[1]
        cur_len=len(full_labels)
        if cur_len<max_len:
            full_tokens+=[tokenizer.pad_token]*(max_len-cur_len)
            full_labels+=[label2ids[tokenizer.pad_token]]*(max_len-cur_len)
            attention_mask+=[0]*(max_len-cur_len)
            token_type_ids+=[0]*(max_len-cur_len)
            tag+=[pos2id_BIO[tokenizer.pad_token]]*(max_len-cur_len)
        full_ids=tokenizer.convert_tokens_to_ids(full_tokens)
        example={"input_ids":torch.tensor(full_ids,dtype=torch.long),"token_type_ids":torch.tensor(token_type_ids,dtype=torch.long),                "attention_mask":torch.tensor(attention_mask,dtype=torch.long),"labels":torch.tensor(full_labels,dtype=torch.long),
                "rel_label":F.one_hot(torch.tensor(rel),num_classes=len(id2rels)),"postag":torch.tensor(tag).long(),"feature":torch.tensor(tfidf_svd).float(),\
                 "token2doc":token2doc}
        return example
def index_token(text_raw):
    sub_text = []
    buff = ""
    for char in text_raw:
        if is_chinese_char(ord(char)) or is_punctuation(char):
            if buff != "":
                sub_text.append(buff)
                buff = ""
            sub_text.append(char)
        else:
            buff += char
    if buff != "":
        sub_text.append(buff)
    tok_to_orig_start_index = []
    tok_to_orig_end_index = []
    orig_to_tok_index = []
    tokens = []
    text_tmp = ''
    for (i, token) in enumerate(sub_text):
        orig_to_tok_index.append(len(tokens))
        sub_tokens = tokenizer.tokenize(token)
        text_tmp += token
        for sub_token in sub_tokens:
            tok_to_orig_start_index.append(len(text_tmp) - len(token))
            tok_to_orig_end_index.append(len(text_tmp) - 1)
            tokens.append(sub_token)
        else:
            continue
        break
    return tok_to_orig_start_index,tok_to_orig_end_index,orig_to_tok_index
def find_subs_obs(token_label_pred,text):
    subs=[]
    sub_offsets=[]
    obs=[]
    ob_offsets=[]
    index=0
    while index<token_label_pred.shape[0]:
        if token_label_pred[index]==3:
            subs.append(text[index])
            index+=1
            while(index<token_label_pred.shape[0] and (token_label_pred[index]==4 or token_label_pred[index]==3)):
                subs[-1]+=(text[index])
                index+=1
            sub_offsets.append([index-len(subs[-1]),index])
            index-=1
        if index<token_label_pred.shape[0] and token_label_pred[index]==1:
            obs.append(text[index])
            index+=1
            while(index<token_label_pred.shape[0] and (token_label_pred[index]==2 or token_label_pred[index]==1)):
                obs[-1]+=(text[index])
                index+=1
            ob_offsets.append([index-len(obs[-1]),index])
            index-=1
        index+=1
    if len(subs)==0:
        subs.append('')
        sub_offsets.append([0,0])
    if len(obs)==0:
        obs.append('')
        ob_offsets.append([0,0])
    return subs,obs,sub_offsets,ob_offsets

# In[3]:

# do_lower_case=True
# max_len=256
# device=torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# # bert_dir="./bert-pytorch-chinese/"
# # vocab="bert-base-chinese-vocab.txt"
# # config_file="bert_config.json"
# bert_dir="./roberta-zh-wwm-pytorch/"
# vocab="vocab.txt"
# config_file="bert_config.json"
# tokenizer=BertTokenizer.from_pretrained(os.path.join(bert_dir,vocab),do_lower_case=do_lower_case)

# In[4]:

text_data=[]
with open("./dataset/train_data/train_data.json","r") as r:
    raw_data=r.readlines()
    for d in raw_data:
        text_data.append(json.loads(d))
print(len(text_data))
test_text_data=[]
with open("./dataset/test1_data/test1_data.json","r") as r:
    raw_data=r.readlines()
    for d in raw_data:
        test_text_data.append(json.loads(d))
schema=[]
with open("./dataset/schema.json","r") as r:
    raw_schema=r.readlines()
    for d in raw_schema:
        schema.append(json.loads(d))
rels=set()
special_rels=set()
for e in schema:
        if len(e['object_type'].keys())==1:
            rels.add(e["predicate"])
        else:
            special_rels.add(e["predicate"])
            for key in e['object_type'].keys():
                rels.add(e['predicate']+"_"+key)
if not os.path.exists("./dataset/dict.pk"):
    special_rels=list(special_rels)
    id2rels=list(rels)
    rels2id=dict([(rel,idx) for idx,rel in enumerate(id2rels)])
    id2labels=["O","B-OBJ","I-OBJ","B-SUB","I-SUB","[category]","[SEP]","[CLS]","[PAD]"]
    label2ids=dict([ (label,idx) for idx,label in enumerate(id2labels)])
    pk.dump([special_rels,id2rels,rels2id,id2labels,label2ids],open("./dataset/dict.pk","wb"))
else:
    print("loading dict...")
    special_rels,id2rels,rels2id,id2labels,label2ids=pk.load(open("./dataset/dict.pk","rb"))

# In[5]:

k_split=KFold(n_splits=8,shuffle=True,random_state=20)
num=0
for train_index,test_index in k_split.split(text_data):
    print(num)
    num+=1
    train_text_data=[]
    for i in train_index:
        train_text_data.append(text_data[i])
    test_text_data=[]
    for i in test_index:
        test_text_data.append(text_data[i])
    spo_corpus=[]
    for idx,e in tqdm(enumerate(train_text_data)):
        for spo in e['spo_list']:
            if spo['predicate'] in special_rels:
                for key,value in spo['object'].items():
                    rel=spo['predicate']+"_"+key
                    ob=value
                    sub=spo['subject']
                    sample={'predicate':rel,'object':ob,'subject':sub}
                    spo_corpus.append(sample)
            else:
                for key,value in spo['object'].items():
                    rel=spo['predicate']
                    ob=value
                    sub=spo['subject']
                    sample={'predicate':rel,'object':ob,'subject':sub}
                    spo_corpus.append(sample)
    for idx,e in tqdm(enumerate(test_text_data)):
        self_corpus=[]
        for spo in spo_corpus:
            if spo['subject'] in e['text']  and spo['object'] in e['text'] :
                if (spo['subject']!='' or spo['object']!='') and spo not in self_corpus:
                    self_corpus.append(spo)
        e['plan_spo_list']=e.get('plan_spo_list',[])+self_corpus

# In[16]:

with open("./dataset/train_data/new_train_data.json","w") as w:
    for d in text_data:
        w.write(json.dumps(d, ensure_ascii=False)+"\n")

if not os.path.exists("./dataset/test1_data/new_test1_data.json"):
    spo_corpus=[]
    for idx,e in tqdm(enumerate(text_data)):
        for spo in e['spo_list']:
            if spo['predicate'] in special_rels:
                for key,value in spo['object'].items():
                    rel=spo['predicate']+"_"+key
                    ob=value
                    sub=spo['subject']
                    sample={'predicate':rel,'object':ob,'subject':sub}
                    spo_corpus.append(sample)
            else:
                for key,value in spo['object'].items():
                    rel=spo['predicate']
                    ob=value
                    sub=spo['subject']
                    sample={'predicate':rel,'object':ob,'subject':sub}
                    spo_corpus.append(sample)
    for idx,e in tqdm(enumerate(test_text_data)):
        self_corpus=[]
        for spo in spo_corpus:
            if spo['subject'] in e['text']  and spo['object'] in e['text'] :
                if (spo['subject']!='' or spo['object']!='') and spo not in self_corpus:
                    self_corpus.append(spo)
        e['plan_spo_list']=e.get('plan_spo_list',[])+self_corpus
    with open("./dataset/test1_data/new_test1_data.json","w") as w:
        for e in test_text_data:
            w.write(json.dumps(e, ensure_ascii=False)+'\n')
else:
    print("loading...")
    new_test_text_data=[]
    with open("./dataset/test1_data/new_test1_data.json","r") as r:
        raw_data=r.readlines()
        for d in raw_data:
            new_test_text_data.append(json.loads(d))

if not os.path.exists("./dataset/test2_data/new_test2_data.json"):
    spo_corpus=[]
    for idx,e in tqdm(enumerate(text_data)):
        for spo in e['spo_list']:
            if spo['predicate'] in special_rels:
                for key,value in spo['object'].items():
                    rel=spo['predicate']+"_"+key
                    ob=value
                    sub=spo['subject']
                    sample={'predicate':rel,'object':ob,'subject':sub}
                    spo_corpus.append(sample)
            else:
                for key,value in spo['object'].items():
                    rel=spo['predicate']
                    ob=value
                    sub=spo['subject']
                    sample={'predicate':rel,'object':ob,'subject':sub}
                    spo_corpus.append(sample)
    for idx,e in tqdm(enumerate(test2_text_data)):
        self_corpus=[]
        for spo in spo_corpus:
            if spo['subject'] in e['text']  and spo['object'] in e['text'] :
                if (spo['subject']!='' or spo['object']!='') and spo not in self_corpus:
                    self_corpus.append(spo)
        e['plan_spo_list']=e.get('plan_spo_list',[])+self_corpus
    with open("./dataset/test2_data/new_test2_data.json","w") as w:
        for e in test2_text_data:
            w.write(json.dumps(e, ensure_ascii=False)+'\n')
else:
    print("loading...")
    new_test2_text_data=[]
    with open("./dataset/test2_data/new_test2_data.json","r") as r:
        raw_data=r.readlines()
        for d in raw_data:
            new_test2_text_data.append(json.loads(d))


import tensorflow as tf
from numpy import *
import matplotlib.pyplot as plt
def loadDataSet():
    dataMat = []
    labelMat = []
    fr = open('testSet.txt')
    for line in fr.readlines() :
        lineArr = line.strip().split()
        dataMat.append([1.0,float(lineArr[0]),float(lineArr[1])])
        labelMat.append(int(lineArr[2]))

    print(dataMat)
    return dataMat , labelMat

def sigmoid(inX):
    return 1.0/(1+exp(-inX))

def gradAscent(dataMatIn, classLabels):
    dataMatrix = mat(dataMatIn)
    labelMat = mat(classLabels).transpose()
    m,n = shape(dataMatrix)
    print(m,n)
    alpha = 0.001
    maxCycles = 1000
    weights = ones((n,1))
    for k in range(maxCycles) :
        h = sigmoid(dataMatrix*weights)
        error = (labelMat - h)
        weights = weights + alpha * dataMatrix.transpose()*error
    return weights

def plotBestFit(weights):
    dataMat, labelMat = loadDataSet()
    dataArr = array(dataMat)
    n = shape(dataArr)[0]
    xcord1 = []
    xcord2 = []
    ycord1 = []
    ycord2 = []
    for i in range(n) :
        if int(labelMat[i]) == 1 :
            xcord1.append(dataArr[i,1])
            ycord1.append(dataArr[i,2])
        else :
            xcord2.append(dataArr[i,1])
            ycord2.append(dataArr[i,2])
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.scatter(xcord1,ycord1,s=30,c='red',marker='s')
    ax.scatter(xcord2,ycord2,s=30,c='green')
    x = arange(-3.0,3.0,0.1)
    y = array((-weights[0]-weights[1]*x)/weights[2])
    y = reshape(y,60)
    ax.plot(x,y)
    plt.xlabel('X1')
    plt.ylabel('X2')
    plt.show()

In , label = loadDataSet()
weight = gradAscent(In, label)
plotBestFit(weight)


from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from main.models import TenantFAQ, PartnerFAQ, News, TopBanner
from main.serializers import TenantFAQSerializer, PartnerFAQSerializer, NewsSerializer

class TenantFAQView(ListAPIView):
    """"""
    queryset = TenantFAQ.objects.all()
    serializer_class = TenantFAQSerializer

class PartnerFAQView(ListAPIView):
    """"""
    queryset = PartnerFAQ.objects.all()
    serializer_class = PartnerFAQSerializer

class NewsView(ListAPIView):
    """"""
    queryset = News.objects.all()
    serializer_class = NewsSerializer

class TopBannerView(APIView):
    """"""
    @staticmethod
    def get(request, format=None):
        results = TopBanner.objects.filter(is_active=True)
        if results:
            return Response({"text": results[0].text})
        else:
            return Response({"text": None})


import pyautogui
import keyboard as key
from PIL import ImageGrab
from PIL import Image
import pygame

pygame.init()

swidth, sheigth = pyautogui.size()

win = pygame.display.set_mode((swidth,sheigth))

pygame.display.set_caption("RAT")

def PrtScn():
    width, heigth = pyautogui.size()
    run = True
    while run:
        if key.is_pressed("p"):
            bbox = 0, 0, width, heigth
            screenshot = ImageGrab.grab(bbox)
            screenshot.save(r"C:\Users\siaaa013\Documents\Programering\python\backdoor\image.png")

sc = pygame.image.load(r"C:\Users\siaaa013\Documents\Programering\python\backdoor\image.png")

def redraw(win):
    win.blit(sc,(0,0))
    pygame.display.update()

#main loop

run = True
while run:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()

    sc = pygame.image.load(r"C:\Users\sigur\OneDrive\Bilder\Kamerabilder\image.png")

    redraw(win)

pygame.quit()


# List Methods and Functions Part 2

data = [
    "kaustubh",
    "albert",
    "mark",
    "kaustubh",
    "andres",
    "alan",
]

# Methods :

# .copy() method
data2 = data.copy()
print(data2)

# .clear() method -> deletes the elements permanently
data.clear()
print(data)


def solution(record):
    answer = []
    _msg={"Enter":"님이 들어왔습니다.","Leave":"님이 나갔습니다."}
    user={}
    for r in record:
        tmp=r.split(" ")
        if tmp[0]=='Enter' or tmp[0]=="Change":
            user[tmp[1]]=tmp[2]
    for r in record:
        tmp=r.split(" ")
        if tmp[0]=="Enter" or tmp[0]=="Leave":
            answer.append(user[tmp[1]]+_msg[tmp[0]])
    return answer


from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

driver = webdriver.Chrome(executable_path="D:\webdrivers\chromedriver\chromedriver_win32\chromedriver.exe")

driver.maximize_window()

driver.get("http://www.flipkart.com")
time.sleep(2)
print(driver.title)

#login by entering user id and password
driver.find_element_by_xpath("/html/body/div[2]/div/div/div/div/div[2]/div/form/div[1]/input").send_keys(9439749279)
driver.find_element_by_xpath("/html/body/div[2]/div/div/div/div/div[2]/div/form/div[2]/input").send_keys("manojyavam")
driver.find_element_by_xpath("(//*[@type='submit'])[2]").click()

time.sleep(10)
driver.find_element_by_name("q").send_keys("mobile",Keys.ENTER)
time.sleep(2)
#driver.find_element_by_xpath("//*[@id='container']/div/div[1]/div[1]/div[2]/div[2]/form/div/button").click()

time.sleep(10)
driver.close()     # Closing the web browser


import spacy
import itertools
import en_core_web_sm
nlp = en_core_web_sm.load()

def isSentence(changedSentence, originalSentence):
    '''
    Takes a changed sentence and the original sentence and returns True if
    they are close enough in meaning. If not, function return False.
    '''
    # Initializes the variables needed.
    originalSubject = None
    originalSentenceVerb = None
    changedSubject = None
    changedSentenceVerb = None

    # Makes both sentences Doc objects.
    nlpChangedSentence = nlp(changedSentence)
    nlpOriginalSentence = nlp(originalSentence)

    # Initializes dictionaries that will hold parts of speech data.
    sentenceElementsChangedSentence = dict()
    sentenceElementsOriginalSentence = dict()

    # Loops over both lists using itertools and populate dictionaries with part of speech data.
    for changedWord, originalWord in itertools.zip_longest(nlpChangedSentence, nlpOriginalSentence):

        # Once one of the lists ends, itertools makes the other list populate with None.
        # This makes sure None doesn't get added to dictionaries.
        if changedWord == None:
            continue
        sentenceElementsChangedSentence[changedWord] = (changedWord.dep_, changedWord.pos_)

        if originalWord == None:
            continue
        sentenceElementsOriginalSentence[originalWord] = (originalWord.dep_, originalWord.pos_)

    # Loops over both dictionaries and checks for conditions
    for key1, key2 in itertools.zip_longest(sentenceElementsChangedSentence, sentenceElementsOriginalSentence):
        similarity = nlpOriginalSentence.similarity(nlpChangedSentence)
        if key1 == None:
            continue
        if key2 == None:
            continue

        # Gets the subject and verb from the changed sentence and the original sentence.
        if sentenceElementsChangedSentence[key1][0] == 'ROOT' and sentenceElementsChangedSentence[key1][1] == 'VERB':
            changedSentenceVerb = key1
        if sentenceElementsOriginalSentence[key2][0] == 'ROOT' and sentenceElementsOriginalSentence[key2][1] == 'VERB':
            originalSentenceVerb = key2

        if (sentenceElementsChangedSentence[key1][0] == 'nsubj' or sentenceElementsChangedSentence[key1][0] == 'nsubjpass') and ((sentenceElementsChangedSentence[key1][1] == 'NOUN') or (sentenceElementsChangedSentence[key1][1] == 'PRON')):
            changedSubject = key1

        if (sentenceElementsOriginalSentence[key2][0] == 'nsubj' or sentenceElementsOriginalSentence[key2][0] == 'nsubjpass') and ((sentenceElementsOriginalSentence[key2][1] == 'NOUN') or (sentenceElementsOriginalSentence[key2][1] == 'PRON')):
            originalSubject = key2

    # Replaces elements in dictinary with None when they are empty.
    if changedSentenceVerb == None:
        changedSentenceVerb = nlp("None")
    if changedSubject == None:
        changedSubject = nlp("None")

    # Test to see if the two sentences are similar enough. If so, returns True.
    try:
        if (changedSentenceVerb.text == originalSentenceVerb.text) and \
                (originalSubject.text == changedSubject.text) \
                and (similarity > .91):
            return True
    except:
        return False


import pandas as pd
import json
import streamlit as st
import time
from snowflake.snowpark import Session

import pandas as pd
import json
import streamlit as st
from snowflake.snowpark import Session
import time

if 'snowflake_connection' not in st.session_state:
    # connect to Snowflake
    with open('creds.json') as f:
        connection_parameters = json.load(f)
    st.session_state.snowflake_connection = Session.builder.configs(connection_parameters).create()
    session = st.session_state.snowflake_connection
else:
    session = st.session_state.snowflake_connection

st.set_page_config(layout="centered", page_title="Data Editor", page_icon="ðŸ§®")
st.title("Demo APP")
st.caption("This is a demo powered by Thirdeyedata.")

def get_dataset():
    # load messages df
    df = session.table("TEDEMO")

    return df

dataset = get_dataset()

with st.form("data_editor_form"):
     st.caption("Edit the dataframe below")
     edited = st.experimental_data_editor(dataset, use_container_width=True, num_rows="dynamic")
     submit_button = st.form_submit_button("Submit")

if submit_button:
    try:
        session.write_pandas(edited, "TEDEMO", overwrite=True)
        st.success("Table updated")
        time.sleep(5)
    except:
        st.warning("Error updating table")
    #display success message for 5 seconds and update the table to reflect what is in Snowflake
    st.experimental_rerun()


import torch.nn as nn
import torch.nn.init as init
import torchvision.models as models
import torch

def xavier_init(tensor):
    init.xavier_uniform_(tensor)

def gaussian_init(tensor):
    init.normal_(tensor, mean=0.0, std=0.02)

def uniform_init(tensor):
    init.uniform_(tensor, a=-0.1, b=0.1)

class VGG(nn.Module):
    def __init__(self, num_classes=1000, pretrained=True, init_type='pretrained',
                 saved_weights_path=None):
        super(VGG, self).__init__()

        self.features = models.vgg16(pretrained=pretrained).features

        self.avgpool = nn.AdaptiveAvgPool2d((7, 7))
        self.classifier = nn.Sequential(
            nn.Linear(512 * 7 * 7, 4096),
            nn.ReLU(inplace=True),
            nn.Dropout(),
            nn.Linear(4096, 4096),
            nn.ReLU(inplace=True),
            nn.Dropout(),
            nn.Linear(4096, num_classes),
        )

        # Initialize the weights based on the selected initialization type
        if init_type == "pretrained":
            self.reset_classifier()
            return
        elif init_type == 'xavier':
            self.apply_init(xavier_init)
            self.reset_classifier()
        elif init_type == 'gaussian':
            self.apply_init(gaussian_init)
            self.reset_classifier()
        elif init_type == 'uniform':
            self.apply_init(uniform_init)
            self.reset_classifier()
        elif init_type == 'finetuned':
            if saved_weights_path is not None:
                self.load_saved_weights(saved_weights_path)
            else:
                raise ValueError('No path given.')

    def forward(self, x):
        x = self.features(x)
        x = self.avgpool(x)
        x = x.view(x.size(0), -1)
        x = self.classifier(x)
        return x

    def load_pretrained_weights(self):
        vgg16 = models.vgg16(pretrained=True)
        self.features.load_state_dict(vgg16.features.state_dict())

    def load_saved_weights(self, saved_weights_path):
        saved_weights = torch.load(saved_weights_path, map_location='cuda:1')
        self.load_state_dict(saved_weights["state_dict"])

    def apply_init(self, init_func):
        for m in self.modules():
            if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):
                init_func(m.weight.data)
                if m.bias is not None:
                    m.bias.data.zero_()

    def reset_classifier(self):
        for m in self.classifier.modules():
            if isinstance(m, nn.Linear):
                init.kaiming_uniform_(m.weight, mode='fan_in', nonlinearity='relu')
                if m.bias is not None:
                    m.bias.data.zero_()


import tkinter as tk
import unittest
import sys
import os
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + '/../../src')

from ai import Ai
from board import Board

class AiTest(unittest.TestCase):

    def test_update(self):
        board = Board(tk.Toplevel())
        ai = Ai('black', board.squares, board, None, None)
        ai.update((1,0))
        self.assertEqual(ai.contpieces, 15)

    def test_random(self):
        board = Board(tk.Toplevel())
        ai = Ai('black', board.squares, board, None, None)
        ai.random()
        piece = board.squares[(ai.rowpiece, ai.colpiece)]['piece']
        if piece is not None:
            self.assertTrue(piece.color == 'black')


#!/usr/bin/python3
"""
    Write a function that finds a peak in a list of unsorted integers.
"""

def find_peak(inArray):
    """
    function that finds a peak in a list of unsorted integers.
    """
    if not inArray:
        return None
    newArray = []
    lenArray = len(inArray)

    for i in range(1, lenArray-1):
        newArray.append(inArray[i])
    searchPeak = newArray[0]
    for j in range(len(newArray)):
        if newArray[j] >= searchPeak:
            searchPeak = newArray[j]
    return searchPeak


from anvil import *
from ._anvil_designer import CreateFormTemplate
from ..db_actions import create_sail_boat_record, delete_boat_record
from ..sailboats import SailBoat

class CreateForm(CreateFormTemplate):
    def __init__(self, **properties):
        # Set Form properties and Data Bindings.
        self.init_components(**properties)
        self.sail_boat_store = properties['store']
        if properties.get('boat_name', None):
            # edit form
            self.sail_boat = SailBoat(**self.sail_boat_store[properties['boat_name']])
            self.text_box_name.text = self.sail_boat.name
            self.text_box_length.text = self.sail_boat.length
            self.repeating_panel_1.items = self.sail_boat.sails
        else:
            # create form
            self.repeating_panel_1.items = [{'sail_name': 'mainsail', 'sail_area': ''}]
            self.sail_boat = SailBoat(name='', length=0)

        # Any code you write here will run before the form opens.

    def store_form_data(self):
        """Store the form data in the sail_boat object and in the sail_boat_store"""
        boat_name = self.text_box_name.text
        if boat_name == '':
            alert('Please enter a name for your boat')
            return
        if self.sail_boat.name != '':
            # updated sailboat so delete old one
            delete_boat_record(self.sail_boat.name, self.sail_boat_store)
        self.sail_boat = SailBoat(name=boat_name,
                                  length=float(self.text_box_length.text),
                                  sails=self.repeating_panel_1.items[:])
        create_sail_boat_record(self.sail_boat, self.sail_boat_store)

    def button_save_click(self, **event_args):
        """This method is called when the button is clicked"""
        # return to list form
        self.store_form_data()
        get_open_form().display_list(**event_args)

    def button_cancel_click(self, **event_args):
        """This method is called when the button is clicked"""
        get_open_form().display_list(**event_args)


from pymongo import MongoClient

if __name__ == '__main__':
    earliest = 7804800
    count = 0
    client = MongoClient('localhost', 27017)
    db = client.darksky
    collection = db.pastCurrentConditions
    cursor = collection.find({}).sort("time",1)
    #make a list of each document that doesn't have a time greater than 3600 from the last record
    gap_list = []
    prior_time = 7801200
    print("STARTING TIME", prior_time)
    # for document in cursor:
    #     print("beginning of for loop, count is",count)
    #     if count > 0:
    #         if document["time"] != (prior_time + 3600):
    #             print("DOC TIME (IN THE IF LOOP)",document["time"])
    #             print("prior time plus 3600",str((prior_time + 3600)))
    #             gap_list.append(document)
    #             #print("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^")
    #             #print(document)
    #             #print("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^")
    #     prior_time = document["time"]
    #     print("SET the prior_time by document time", prior_time)
    #     count +=1
    #     print("count is now",count)

    for document in cursor:
        if document["time"] != (prior_time + 3600):
            print("DOC TIME",document["time"])
            print("prior time plus 3600",str((prior_time + 3600)))
            gap_list.append(document)
            print(document["_id"])
        # else:
        #     print("ok",document["time"])
        prior_time = document["time"]
        #print("SET the prior_time by document time", prior_time)