"""
Tic Tac Toe

##  ##  ##

1 | 2 | 3
---------
4 | 5 | 6
---------
7 | 8 | 9

##  ##  ##

"""

import tkinter as tk
import random

root = tk.Tk()
root.title("Tic Tac Toe")
root.geometry("+600+400")
root.resizable(0, 0)
root.configure(bg="#111111", pady=5)

choices = [None for _ in range(9)]
win = False
winner = None

# To generate a random move from computer

def comp_rand_move():
    global choices
    while True:
        btnFrames = [btnFrame1, btnFrame2, btnFrame3, btnFrame4, btnFrame5, btnFrame6, btnFrame7, btnFrame8, btnFrame9]
        rf = random.choice(btnFrames)

        if choices[btnFrames.index(rf)] is None:
            for wid in rf.winfo_children():
                wid.destroy()
            break
    ch = btnFrames.index(rf)+1
    put_label("X", rf, ch=ch)

    choices[ch - 1] = "X"

# To reset layout

def reset_layout(*args):
    v = options.index(var.get())

    global choices, win
    choices = [None for _ in range(9)]  # Setting the values of choices to None
    win = False

    bntFrames = [btnFrame1, btnFrame2, btnFrame3, btnFrame4, btnFrame5, btnFrame6, btnFrame7, btnFrame8, btnFrame9]

    btnFrames0 = [[widget for widget in frm.winfo_children()] for frm in bntFrames]

    for f in btnFrames0:
        for wd in f:
            wd.destroy()

    if v == 0:
        create_lyt_against_frnd()
    else:
        create_lyt_against_comp()

# Making a window to Display result

def display_win(winner):
    x = root.winfo_x()
    y = root.winfo_y()

    resultWin = tk.Tk()
    resultWin.geometry(f"180x70+{x+60}+{y+170}")
    resultWin.resizable(0, 0)
    resultWin.overrideredirect(True)
    resultWin.configure(bg="black")

    f = tk.Frame(resultWin, bg="cyan")
    f.pack(padx=5, pady=5)
    font = ("calibri", 25)

    if winner == 0:
        lx = tk.Label(f, text="Draw!", font=font, padx=30, pady=10, fg="green", bg="#222222")
        lx.pack()
    else:
        v = options.index(var.get())
        if v == 0:
            lx = tk.Label(f, text=f"{winner} won!", font=font, padx=40, pady=10, fg="green", bg="#222222")
            lx.pack()
        else:
            txt = "You Won!" if winner == "O" else "You Lose!"
            tk.Label(f, text=txt, font=font, padx=40, pady=10, fg="green", bg="#222222").pack()
    resultWin.after(1500, resultWin.destroy)
    resultWin.mainloop(1)

# To store the values in a list

def apply_changes(choice, val):
    global choices
    choices[choice - 1] = val
    check_win()

def check_win():
    global choices, win, winner
    if choices[0] == choices[1] == choices[2] is not None:
        win = True
        winner = choices[0]
    elif choices[3] == choices[4] == choices[5] is not None:
        win = True
        winner = choices[3]
    elif choices[6] == choices[7] == choices[8] is not None:
        win = True
        winner = choices[6]
    elif choices[2] == choices[5] == choices[8] is not None:
        win = True
        winner = choices[2]
    elif choices[1] == choices[4] == choices[7] is not None:
        win = True
        winner = choices[1]
    elif choices[0] == choices[3] == choices[6] is not None:
        win = True
        winner = choices[0]
    elif choices[0] == choices[4] == choices[8] is not None:
        win = True
        winner = choices[0]
    elif choices[2] == choices[4] == choices[6] is not None:
        win = True
        winner = choices[2]

    if all(choices) and not win:
        display_win(0)
        reset_layout()

    if win:
        display_win(winner)
        reset_layout()

# To put given label ('O' or 'X') after pressing button

def put_label(n, frame, btn1=None, btn2=None, ch=0, plyr='human'):
    if btn1 is not None:
        btn1.destroy()
    if btn2 is not None:
        btn2.destroy()

    font = ("calibri", 30) if n == "O" else ("calibri", 30)
    padx = 9 if n == "O" else 10
    fg = "#dd3333" if n == "O" else "yellow"

    lbl = tk.Label(frame, text=n, font=font, fg=fg, bg="#2d2d2d", padx=padx, pady=10)
    lbl.pack()

    if ch in [2, 4, 6, 8]:
        lbl.configure(bg="#03556c")
    apply_changes(ch, n)

    if plyr == 'comp':
        comp_rand_move()

# First frame for buttons

topFrame = tk.Frame(root, padx=6, pady=10, bg="#420c09")
topFrame.grid(row=0, pady=0)

tk.Label(topFrame, text="Play against : ", fg="white", bg="#420c09").pack(padx=(34, 0), side="left")

options = ["A Friend", "Computer"]
var = tk.StringVar(root)
var.set(options[1])
var.trace('w', reset_layout)

optionMenu = tk.OptionMenu(topFrame, var, *options)
optionMenu.configure(width=10, pady=3, borderwidth=1)
optionMenu.pack(padx=(0, 34), side="left")

# Outer frame for buttons

outerFrame = tk.Frame(root, padx=5, pady=0, bg="#111111")
outerFrame.grid(row=1, pady=5)

# Three inner frames

innerFrame0 = tk.Frame(outerFrame, padx=0, pady=0, bg="#2d2d2d")
innerFrame0.grid(row=1)

innerFrame1 = tk.Frame(outerFrame, padx=0, pady=0, bg="#03556c")
innerFrame1.grid(row=2)

innerFrame2 = tk.Frame(outerFrame, padx=0, pady=0, bg="#2d2d2d")
innerFrame2.grid(row=3)

# Three innermost frames on each inner frame

btnFrame1 = tk.Frame(innerFrame0, padx=25, pady=15, bg="#2d2d2d")
btnFrame1.grid(column=0, row=0)

btnFrame2 = tk.Frame(innerFrame0, padx=25, pady=15, bg="#03556c")
btnFrame2.grid(column=1, row=0)

btnFrame3 = tk.Frame(innerFrame0, padx=25, pady=15, bg="#2d2d2d")
btnFrame3.grid(column=2, row=0)

btnFrame4 = tk.Frame(innerFrame1, padx=25, pady=15, bg="#03556c")
btnFrame4.grid(column=0, row=1)

btnFrame5 = tk.Frame(innerFrame1, padx=25, pady=15, bg="#2d2d2d")
btnFrame5.grid(column=1, row=1)

btnFrame6 = tk.Frame(innerFrame1, padx=25, pady=15, bg="#03556c")
btnFrame6.grid(column=2, row=1)

btnFrame7 = tk.Frame(innerFrame2, padx=25, pady=15, bg="#2d2d2d")
btnFrame7.grid(column=0, row=2)

btnFrame8 = tk.Frame(innerFrame2, padx=25, pady=15, bg="#03556c")
btnFrame8.grid(column=1, row=2)

btnFrame9 = tk.Frame(innerFrame2, padx=25, pady=15, bg="#2d2d2d")
btnFrame9.grid(column=2, row=2)

# Second frame for buttons

bottomFrame = tk.Frame(root, padx=10, pady=10, bg="#420c09")
bottomFrame.grid(row=4, pady=0)

btnReset = tk.Button(bottomFrame, text="Restart", pady=3, padx=15, command=reset_layout)
btnReset.pack(side="left", pady=0, padx=(25, 43))

btnQuit = tk.Button(bottomFrame, text="Quit", pady=3, padx=15, command=root.destroy)
btnQuit.pack(side="right", pady=0, padx=(43, 25))

# To create a layout for playing against friend

def create_lyt_against_frnd():
    global btnFrame1, btnFrame2, btnFrame3, btnFrame4, btnFrame5, btnFrame6, btnFrame7, btnFrame8, btnFrame9

    btn1o = tk.Button(btnFrame1, text="O", padx=5, command=lambda: put_label("O", btnFrame1, btn1o, btn1x, 1))
    btn1o.pack(side="right", pady=20)
    btn1x = tk.Button(btnFrame1, text="X", padx=5, command=lambda: put_label("X", btnFrame1, btn1o, btn1x, 1))
    btn1x.pack(pady=20)

    btn2o = tk.Button(btnFrame2, text="O", padx=5, command=lambda: put_label("O", btnFrame2, btn2o, btn2x, 2))
    btn2o.pack(side="right", pady=20)
    btn2x = tk.Button(btnFrame2, text="X", padx=5, command=lambda: put_label("X", btnFrame2, btn2o, btn2x, 2))
    btn2x.pack(pady=20)

    btn3o = tk.Button(btnFrame3, text="O", padx=5, command=lambda: put_label("O", btnFrame3, btn3o, btn3x, 3))
    btn3o.pack(side="right", pady=20)
    btn3x = tk.Button(btnFrame3, text="X", padx=5, command=lambda: put_label("X", btnFrame3, btn3o, btn3x, 3))
    btn3x.pack(pady=20)

    btn4o = tk.Button(btnFrame4, text="O", padx=5, command=lambda: put_label("O", btnFrame4, btn4o, btn4x, 4))
    btn4o.pack(side="right", pady=20)
    btn4x = tk.Button(btnFrame4, text="X", padx=5, command=lambda: put_label("X", btnFrame4, btn4o, btn4x, 4))
    btn4x.pack(pady=20)

    btn5o = tk.Button(btnFrame5, text="O", padx=5, command=lambda: put_label("O", btnFrame5, btn5o, btn5x, 5))
    btn5o.pack(side="right", pady=20)
    btn5x = tk.Button(btnFrame5, text="X", padx=5, command=lambda: put_label("X", btnFrame5, btn5o, btn5x, 5))
    btn5x.pack(pady=20)

    btn6o = tk.Button(btnFrame6, text="O", padx=5, command=lambda: put_label("O", btnFrame6, btn6o, btn6x, 6))
    btn6o.pack(side="right", pady=20)
    btn6x = tk.Button(btnFrame6, text="X", padx=5, command=lambda: put_label("X", btnFrame6, btn6o, btn6x, 6))
    btn6x.pack(pady=20)

    btn7o = tk.Button(btnFrame7, text="O", padx=5, command=lambda: put_label("O", btnFrame7, btn7o, btn7x, 7))
    btn7o.pack(side="right", pady=20)
    btn7x = tk.Button(btnFrame7, text="X", padx=5, command=lambda: put_label("X", btnFrame7, btn7o, btn7x, 7))
    btn7x.pack(pady=20)

    btn8o = tk.Button(btnFrame8, text="O", padx=5, command=lambda: put_label("O", btnFrame8, btn8o, btn8x, 8))
    btn8o.pack(side="right", pady=20)
    btn8x = tk.Button(btnFrame8, text="X", padx=5, command=lambda: put_label("X", btnFrame8, btn8o, btn8x, 8))
    btn8x.pack(pady=20)

    btn9o = tk.Button(btnFrame9, text="O", padx=5, command=lambda: put_label("O", btnFrame9, btn9o, btn9x, 9))
    btn9o.pack(side="right", pady=20)
    btn9x = tk.Button(btnFrame9, text="X", padx=5, command=lambda: put_label("X", btnFrame9, btn9o, btn9x, 9))
    btn9x.pack(pady=20)

# To create a layout for playing against computer

def create_lyt_against_comp():
    global btnFrame1, btnFrame2, btnFrame3, btnFrame4, btnFrame5, btnFrame6, btnFrame7, btnFrame8, btnFrame9

    btn1o = tk.Button(btnFrame1, text="O", padx=5, command=lambda: put_label("O", btnFrame1, btn1o, ch=1, plyr='comp'))
    btn1o.pack(side="right", padx=12, pady=20)

    btn2o = tk.Button(btnFrame2, text="O", padx=5, command=lambda: put_label("O", btnFrame2, btn2o, ch=2, plyr='comp'))
    btn2o.pack(side="right", padx=12, pady=20)

    btn3o = tk.Button(btnFrame3, text="O", padx=5, command=lambda: put_label("O", btnFrame3, btn3o, ch=3, plyr='comp'))
    btn3o.pack(side="right", padx=12, pady=20)

    btn4o = tk.Button(btnFrame4, text="O", padx=5, command=lambda: put_label("O", btnFrame4, btn4o, ch=4, plyr='comp'))
    btn4o.pack(side="right", padx=12, pady=20)

    btn5o = tk.Button(btnFrame5, text="O", padx=5, command=lambda: put_label("O", btnFrame5, btn5o, ch=5, plyr='comp'))
    btn5o.pack(side="right", padx=12, pady=20)

    btn6o = tk.Button(btnFrame6, text="O", padx=5, command=lambda: put_label("O", btnFrame6, btn6o, ch=6, plyr='comp'))
    btn6o.pack(side="right", padx=12, pady=20)

    btn7o = tk.Button(btnFrame7, text="O", padx=5, command=lambda: put_label("O", btnFrame7, btn7o, ch=7, plyr='comp'))
    btn7o.pack(side="right", padx=12, pady=20)

    btn8o = tk.Button(btnFrame8, text="O", padx=5, command=lambda: put_label("O", btnFrame8, btn8o, ch=8, plyr='comp'))
    btn8o.pack(side="right", padx=12, pady=20)

    btn9o = tk.Button(btnFrame9, text="O", padx=5, command=lambda: put_label("O", btnFrame9, btn9o, ch=9, plyr='comp'))
    btn9o.pack(side="right", padx=12, pady=20)

create_lyt_against_comp()

root.mainloop()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 15 23:32:02 2023

@author: dianah
"""
import numpy as np

#function for scalar triple product
#using the numpy cross function
def scalar_triple(a,b,c):
    d = np.cross(b, c)
    result = a[0]*d[0] + a[1]*d[1] + a[2]*d[2]
    return result

#creating another scalar triple product function
#which also uses the numpy dot function
#using this more to check if the previous function is ok
def scalar_triple_dot(a,b,c):
    d = np.cross(b, c)
    result = np.dot(a,d)
    return result

#function for vector triple product
def vector_triple(a,b,c):
    d = np.cross(b,c)
    result = np.cross(a,d)
    return result

#function for printing the input and products
def printing(a,b,c):
    print("a =", a, "\nb =", b, "\nc =", c )
    print("\nThe scalar triple product is = ")
    print( scalar_triple(a,b,c) )
    #print( scalar_triple_dot(a,b,c) )
    #used the line above un-commented the first time just for checking
    print("\nThe vector triple product is = ")
    print( vector_triple(a,b,c) )

#arbitrary test values
print("\nFirst arbitrary test:")
a = (1,1,1)
b = (-5,0,0)
c = (2,4,6)
printing(a,b,c)

print("\nKeyboard values test:")
#testing on vectors entered from keyboard
a=[]
b=[]
c=[]

#reading vectors a,b,c
print("\nEnter values for vector a: ")
for i in range(0,3):
    val = float(input())
    a.append(val)

print("\nEnter values for vector b: ")
for i in range(0,3):
    val = float(input())
    b.append(val)

print("\nEnter values for vector c: ")
for i in range(0,3):
    val = float(input())
    c.append(val)
#testing
printing(a,b,c)


from server.vitamin import models
from fastapi import APIRouter, HTTPException, Depends
from typing import List

from . import schemas, crud
from sqlalchemy import func
from sqlalchemy.orm import Session
from ..dependencies import get_db
from datetime import date

router = APIRouter(
    prefix="/vitamins",
    tags=["vitamins"],
    responses={404: {"description": "Not found"}},
)

## Vitamins
### Vitamin Base
@router.post("/", response_model=schemas.Vitamin)
def create_vitamin(vit: schemas.VitaminCreate, db: Session = Depends(get_db)):
    return crud.create_vitamin(db=db, vit=vit)

@router.get("/", response_model=List[schemas.Vitamin])
def read_vitamins(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    vitamins = crud.get_vitamins(db, skip=skip, limit=limit)
    return vitamins

@router.get("/summary/{cur_date}", response_model=List[schemas.VitaminSummary])
def read_summary(cur_date: date, skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    cgoal = db.query(models.Vitamin_Goal,
                    func.rank().over(
                        order_by=models.Vitamin_Goal.date.desc(),
                        partition_by=models.Vitamin_Goal.vitamin_id
                    ).label('rnk')
                    ).subquery()

    summ = db.query(models.Vitamin, func.sum(models.VitaminRecord.qty).label('totals'))\
        .join(models.VitaminRecord).filter(models.VitaminRecord.date == cur_date)\
        .group_by(models.Vitamin.id).subquery()

    res = db.query(models.Vitamin.id, models.Vitamin.name, summ.c.totals, cgoal.c.qty)\
        .outerjoin(summ, models.Vitamin.id == summ.c.id)\
        .outerjoin(cgoal, models.Vitamin.id == cgoal.c.vitamin_id).\
        filter(cgoal.c.rnk == 1).distinct()

    results=[]
    for r in res:
        payload={"vitamin_id": r.id,
        "name":r.name,
        "goal":r.qty,
        "amount":r.totals}
        results.append(payload)
    return results

@router.get("/{vit_id}", response_model=schemas.Vitamin)
def read_vitamin(vit_id: int, db: Session = Depends(get_db)):
    db_vitamin = crud.get_vitamin(db, vit_id=vit_id)
    if db_vitamin is None:
        raise HTTPException(status_code=404, detail="Vitamin record not found")
    return db_vitamin

@router.delete("/{vit_id}", status_code=204)
def delete_vitamin(vit_id: int, db: Session = Depends(get_db)):
    db_vitamin = crud.get_vitamin(db, vit_id=vit_id)
    if db_vitamin is None:
        raise HTTPException(status_code=404, detail="Water_record not found")
    crud.delete_vitamin(db, vit_id=vit_id)

### Vitamin Records

@router.post("/record/", response_model=schemas.VitaminRecord)
def create_vitamin_record(
        vit_id: int, vit_rec: schemas.VitaminRecordCreate, db: Session = Depends(get_db)):
    return crud.create_vitamin_record(db=db, vit_rec=vit_rec, vit_id=vit_id)

@router.get("/record/", response_model=List[schemas.VitaminRecord])
def read_vitamin_records(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    vitamin_records = crud.get_vitamin_records(db, skip=skip, limit=limit)
    return vitamin_records

@router.get("/record/{vit_rec_id}", response_model=schemas.VitaminRecord)
def read_vit_record(vit_rec_id: int, db: Session = Depends(get_db)):
    db_vit_record = crud.get_vitamin_record(db, vit_rec_id=vit_rec_id)
    if db_vit_record is None:
        raise HTTPException(status_code=404, detail="Vitamin record not found")
    return db_vit_record

@router.delete("/record/{vit_rec_id}", status_code=204)
def delete_vit_record(vit_rec_id: int, db: Session = Depends(get_db)):
    db_vit_rec = crud.get_vitamin_record(db, vit_rec_id=vit_rec_id)
    if db_vit_rec is None:
        raise HTTPException(status_code=404, detail="Vitamin Record not found")
    crud.delete_vitamin_record(db, vit_rec_id=vit_rec_id)

@router.get("/goal/", response_model=List[schemas.VitaminGoal])
def read_vitamin_goals(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    vitamin_goals = crud.get_vitamin_goals(db, skip=skip, limit=limit)
    return vitamin_goals

@router.post("/goal/", response_model=schemas.VitaminGoal)
def create_vitamin_record(
        vit_id: int, vit_goal: schemas.VitaminGoalCreate, db: Session = Depends(get_db)):
    return crud.create_vitamin_goal(db=db, vit_goal=vit_goal, vit_id=vit_id)

@router.get("/goal/first/{vit_id}", response_model=schemas.VitaminGoal)
def read_current_vitamin_goal(vit_id: int, db: Session = Depends(get_db)):
    db_vit_goal = crud.get_current_vit_goal(db, vit_id=vit_id)
    if db_vit_goal is None:
        raise HTTPException(status_code=404, detail="Vitamin Record not found")
    return db_vit_goal


# 6.5 Write code using find() and string slicing (see section 6.10) to extract the number at the end of the line below. Convert the extracted value to a floating point number and print it out.

text = "X-DSPAM-Confidence:    0.8475"
ws = 0
output = ""

while True:
    ws = text.find(" ", ws+1)

    if ws == -1:
        break
    else:
        output = text[ws:]
print(float(output))


import pyautogui
import time

# nome do atalho que esta na area de trabalho
nome_atalho = 'sapi'
usuario = 'seu usuario'
senha   = 'sua senha'

# espera inicialização do computador
time.sleep(2)

# dimensões da tela
tamanho_tela      = pyautogui.size()
clique_horizontal = tamanho_tela.width // 2
clique_vertical   = tamanho_tela.height // 2

# clique com o mouse no centro da tela
pyautogui.click(clique_horizontal, clique_vertical)

# digita o nome do atalho com o teclado
pyautogui.typewrite(nome_atalho)

# abre e confirma
pyautogui.press('enter')
time.sleep(0.5)
pyautogui.press('left')
time.sleep(1)
pyautogui.press('enter')
time.sleep(7)

# usuario e senha - se necessário
pyautogui.typewrite(usuario)
pyautogui.press('tab')
pyautogui.typewrite(senha)
pyautogui.press('tab')
pyautogui.press('enter')


# -*- coding: utf-8 -*-
"""
Created on Sun Nov 15 20:42:44 2020

@author: Mikhail Kuts
Скрипт для автоматизированной генерации директорий git
"""
import os

import os.path as pt

def opendir(folder):
    # print(folder)
    l_dir = os.listdir(folder)
    if 'README.md' in l_dir:
        print('README.md exist')
    else:
        f = open(folder+'\\'+'README.md','w')
        f.close()
    for name in l_dir:
        c_folder = folder + '\\' + name
        if pt.isdir(c_folder) and (name[0]!='.'):
            opendir(c_folder)

def main():
    c_folder = os.getcwd()
    print(c_folder)
    opendir(c_folder)

if __name__=="__main__":
    main()


# Reorder List
# Given a singly linked list L: L(0)->L(1)->L(2)-> ... ->L(n)
# reorder it to: L(0)->L(n)->L(1)->L(n-1)->L(2)->L(n-2)-> ...
# You must do this in-place without altering the nodes' values.
#
# Example
# Given 1->2->3->4->null, reorder it to 1->4->2->3->null.

"""
Definition of ListNode
class ListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""
class Solution:
    """
    @param head: The first node of the linked list.
    @return: nothing
    """
    """
        First we find the middle of the list, reverse the second part.
        Then merge those two lists to get what we want
    """

    # Reverse a list
    def reverse(self, head):
        curr = None # Not head !
        while head != None:
            temp = head.next
            head.next = curr
            curr = head
            head = temp
        return curr

    # Merge two lists
    def merge(self, list1, list2):
        dummy = ListNode(0)
        index = 0
        while list1 != None and list2 != None:
            if index % 2 == 0:
                dummy.next = list1
                list1 = list1.next
            else:
                dummy.next = list2
                list2 = list2.next
            dummy = dummy.next
            index += 1
        if list1 != None:
            dummy.next = list1
        else:
            dummy.next = list2

    # Find the middle node
    def findMiddle(self, head):
        slow = head
        fast = head.next
        while fast != None and fast.next != None: # Use "if" by mistake
            slow = slow.next
            fast = fast.next.next
        return slow

    # Final step
    def reorderList(self, head):
        # write your code here
        if head == None or head.next == None:
            return
        mid = self.findMiddle(head)
        tail = self.reverse(mid.next) # Note here is "mid.next", not "mid"!
        mid.next = None # Don't forget this step !!
        self.merge(head, tail)


def solution(array, commands):
    answer = []
    print(len(commands))
    for i in range(len(commands)):
        print(i)
        s = commands[i][0] - 1
        e = commands[i][1]
        target = commands[i][2] - 1
        tmp = array[s:e]
        tmp.sort()
        #print(tmp)

        answer.append(tmp[target])

    return answer

'''
레벨 1
Sort

그냥 쉬운문제

'''


"""
Evaluate zero-shot ruGPT3 transfer on NPlus1 article rubric prediction
"""
import argparse
from pathlib import Path
from typing import Union

import pandas as pd
from sklearn.metrics import classification_report
from tqdm import tqdm

from classifier import ZeroshotClassifier

QUERY = "Текст: {text}\nКатегория: "

# Other labels have 3 or less items
LABELS = [
    "Наука",
    "Технологии",
    "Оружие",
    "Космос",
    "Гаджеты",
    "Транспорт"
]
REFUSE = "Не знаю"

def load_text_data(data_path: Path):
    texts_path = data_path/"texts"
    text_data = list()

    for file in texts_path.iterdir():
        text_data.append((
            file.name.split(".")[0],  # get filename
            file.read_text(encoding="utf-8").strip().split("\n")[0]  # get the text
        ))

    text_data_df = pd.DataFrame(text_data, columns=["textid", "text"])
    return text_data_df

def load_metadata(data_path: Path):
    return pd.read_csv(data_path/"newmetadata.csv", sep="\t")

def get_data_sample(data_path: Path, sample_size: int, seed: int):
    texts = load_text_data(data_path)
    meta = load_metadata(data_path)
    data = texts.merge(meta, on="textid")
    data = data[["text", "textrubric"]]
    data = data[data.textrubric.isin(LABELS)]
    if sample_size < 1:
        return data

    data = data.sample(data.shape[0], random_state=seed)
    return data[:sample_size]

def evaluate(data_path: Path, model_path: Union[str,Path], sample_size: int=0, seed: int=0):
    data = get_data_sample(data_path, sample_size, seed)
    print("Label distribution:")
    print(data.textrubric.value_counts())
    predictions = []
    print("Loading model...")
    clf = ZeroshotClassifier(model_path, 1024)
    for _, text in tqdm(data.text.items()):
        pred = clf.classify(text, QUERY, LABELS)
        if pred.confident_enough:
            predictions.append(pred.label)
        else:
            predictions.append(REFUSE)
    print(classification_report(data.textrubric, predictions))

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("data_path", help="Path to NPlus1 corpus")
    parser.add_argument("model_path", help="Path to fetched model and tokenizer")
    parser.add_argument("sample_size", type=int, help="Size fo sample to evaluate on")
    parser.add_argument("seed", type=int, help="Random seed")
    args = parser.parse_args()
    evaluate(Path(args.data_path), args.model_path, args.sample_size, args.seed)


# -*- coding: utf-8 -*-
'''Lateral earth pressure on a retaining wall due to a point
    load acting in vertical direction on the backfill.'''

from __future__ import division
from __future__ import print_function

__author__= "Ana Ortega (AO_O) and Luis C. Pérez Tato (LCPT)"
__copyright__= "Copyright 2016, AO_O and LCPT"
__license__= "GPL"
__version__= "3.0"
__email__= "ana.Ortega@ciccp.es" "l.pereztato@ciccp.es"

import math
import xc
from actions.earth_pressure import earth_pressure as ep

vref_cuadCos45=0.5

Qload=1e3 #value of the point load
loadAppPnt=xc.Vector([1,1,10]) #load application point
zBaseWall=0 #global Z coordinate of the base of the wall
distWall=1 # horizontal distance between the wall and the point load
vdir=xc.Vector([0,-1,0])
loadDef=ep.PointVerticalLoadOnBackfill(xcSet=None,Qload=Qload, loadAppPnt=loadAppPnt,zBaseWall=zBaseWall,distWall=distWall,vdir=vdir)
psi1=loadDef.getAngPsi(0,0)
psi01=loadDef.getAngPsi(1,0)
psi2=loadDef.getAngPsi(2,0)
pres1_z5=loadDef.getPressure(0,0,5)
pres0_z5=loadDef.getPressure(1,0,5) # point of maximum pressure for z=5
pres2_z5=loadDef.getPressure(2,0,5)
pres1_z2=loadDef.getPressure(0,0,2)
pres0_z2=loadDef.getPressure(1,0,2) # point of maximum pressure for z=5
pres2_z2=loadDef.getPressure(2,0,2)

loadDef.vdir=xc.Vector([-1,0,0])
psi3=loadDef.getAngPsi(0,0)
psi02=loadDef.getAngPsi(0,1)
psi4=loadDef.getAngPsi(0,2)

loadAppPnt=xc.Vector([-1,-1,10])
vdir=xc.Vector([0,1,0])
loadDef=ep.PointVerticalLoadOnBackfill(xcSet=None,Qload=Qload, loadAppPnt=loadAppPnt,zBaseWall=zBaseWall,distWall=distWall,vdir=vdir)
psi5=loadDef.getAngPsi(0,0)
psi03=loadDef.getAngPsi(-1,0)
psi6=loadDef.getAngPsi(-2,0)
loadDef.vdir=xc.Vector([1,0,0])
psi7=loadDef.getAngPsi(0,0)
psi8=loadDef.getAngPsi(0,-2)

OK01=(math.cos(psi1)**2-vref_cuadCos45)<1e-4 and (math.cos(psi2)**2-vref_cuadCos45)<1e-4 and (math.cos(psi3)**2-vref_cuadCos45)<1e-4 and (math.cos(psi4)**2-vref_cuadCos45)<1e-4 and (math.cos(psi5)**2-vref_cuadCos45)<1e-4 and (math.cos(psi6)**2-vref_cuadCos45)<1e-4 and (math.cos(psi7)**2-vref_cuadCos45)<1e-4 and (math.cos(psi8)**2-vref_cuadCos45)<1e-4

OK02=(math.cos(psi01)**2-1)<1e-5 and (math.cos(psi02)**2-1)<1e-5 and (math.cos(psi03)**2-1)<1e-5

OK3=(pres1_z5-5.078)<1e-3 and (pres0_z5-10.1565)<1e-3 and (pres2_z5-5.078)<1e-3 and (pres1_z2-1.75)<1e-3 and (pres0_z2-3.5)<1e-3 and (pres2_z2-1.75)<1e-3
import os
from misc_utils import log_messages as lmsg
fname= os.path.basename(__file__)
if OK01 and OK02:
    print('test '+fname+': ok.')
else:
    lmsg.error(fname+' ERROR.')


import unittest
from unittest import mock

from mermaid.sequence import SequenceDiagram
from mermaid.sequence.element import Actor, Box, Note, NotePosition, Participant, Rect
from mermaid.sequence.link import ArrowTypes, Link
from mermaid.sequence.logic import Alt, Break, Critical, Loop, Optional, Parallel

class TestActor(unittest.TestCase):
    def test_str(self):
        actor = Actor('John')
        expect_str = '\tactor John\n'
        self.assertEqual(str(actor), expect_str)
        self.assertEqual(actor.id_, 'John')

class TestParticipant(unittest.TestCase):
    def test_str(self):
        participant = Participant('Alice')
        expect_str = '\tparticipant alice as Alice\n'
        self.assertEqual(str(participant), expect_str)

class TestBox(unittest.TestCase):
    def test_str(self):
        # use mocks to create an actor and a participant element
        actor = mock.MagicMock(spec=Actor)
        actor.__str__ = mock.Mock(return_value='\tActor John\n')
        participant = mock.MagicMock(spec=Participant)
        participant.__str__ = mock.Mock(
            return_value='\tparticipant alice as Alice\n')

        box = Box('Test Box', [actor, participant])
        expect_str = """\tbox Test Box
\tActor John
\tparticipant alice as Alice
\tend\n"""
        self.assertEqual(str(box), expect_str)

class TestLink(unittest.TestCase):
    def setUp(self):
        self.source = mock.MagicMock(spec=Actor)
        self.source.id_ = 'John'
        self.target = mock.MagicMock(spec=Participant)
        self.target.id_ = 'Alice'

    def test_str_without_activation_deactivation(self):
        link = Link(self.source, self.target, 'Solid-line', 'Hello World')
        expected_str = '\tJohn->Alice: Hello World\n'
        self.assertEqual(str(link), expected_str)

    def test_str_with_arrow_type_classe(self):
        link = Link(self.source, self.target, ArrowTypes.SOLID_LINE,
                    'Hello World')
        expected_str = '\tJohn->Alice: Hello World\n'
        self.assertEqual(str(link), expected_str)

    def test_str_with_activation(self):
        link = Link(self.source,
                    self.target,
                    'Solid-line',
                    'Hello World',
                    activate_target=True)
        expected_str = '\tJohn->Alice: Hello World\nactivate Alice\n'
        self.assertEqual(str(link), expected_str)

    def test_str_with_deactivation(self):
        link = Link(self.source,
                    self.target,
                    'Solid-line',
                    'Hello World',
                    deactivate_target=True)
        expected_str = '\tJohn->Alice: Hello World\ndeactivate Alice\n'
        self.assertEqual(str(link), expected_str)

class TestNote(unittest.TestCase):
    def setUp(self) -> None:
        self.actor = mock.Mock(spec=Actor)
        self.actor.id_ = 'actor'
        self.participant = mock.Mock(spec=Participant)
        self.participant.id_ = 'participant'
        self.note = 'This is a note'
        return super().setUp()

    def test_note_str_single_element(self) -> None:
        note = Note(self.note, self.actor)
        self.assertEqual(str(note), '\tNote over actor: This is a note\n')

    def test_note_str_multiple_elements(self) -> None:
        note_multiple = Note(self.note, [self.actor, self.participant],
                             NotePosition.OVER)
        self.assertEqual(str(note_multiple),
                         '\tNote over actor,participant: This is a note\n')

    def test_note_position(self) -> None:
        note_left = Note(self.note, self.actor, NotePosition.LEFT_OF)
        self.assertEqual(str(note_left),
                         '\tNote left of actor: This is a note\n')
        note_right = Note(self.note, self.actor, NotePosition.RIGHT_OF)
        self.assertEqual(str(note_right),
                         '\tNote right of actor: This is a note\n')

    def test_note_assertion(self) -> None:
        with self.assertRaises(ValueError):
            Note(self.note, [self.actor, self.participant],
                 NotePosition.LEFT_OF)
        with self.assertRaises(ValueError):
            Note(self.note, [self.actor, self.participant],
                 NotePosition.RIGHT_OF)

class TestLoop(unittest.TestCase):
    def test_loop_str(self) -> None:
        link = mock.MagicMock(spec=Link)
        link.configure_mock(__str__=lambda _: '\tJohn->Alice: Hello World\n')
        loop = Loop('condition', [link])
        self.assertEqual(
            str(loop), '\tloop condition\n\tJohn->Alice: Hello World\n\tend\n')

class TestAlt(unittest.TestCase):
    def setUp(self):
        self.link_1 = mock.MagicMock(spec=Link)
        self.link_1.configure_mock(__str__=lambda _: '\tA-->B: message\n')
        self.link_2 = mock.MagicMock(spec=Link)
        self.link_2.configure_mock(__str__=lambda _: '\tA-->B: message\n')

    def test_str_one_condition(self):
        alt = Alt({'condition': [self.link_1]})
        excepted_str = '\talt condition\n\tA-->B: message\n\tend\n'
        self.assertEqual(str(alt), excepted_str)

    def test_str_multiple_condition(self):
        alt = Alt({'condition-1': [self.link_1], 'condition-2': [self.link_2]})
        except_str = '\talt condition-1\n\tA-->B: message\n\telse condition-2\n\tA-->B: message\n\tend\n'
        self.assertEqual(str(alt), except_str)

class TestOptional(unittest.TestCase):
    def setUp(self):
        self.link = mock.MagicMock(spec=Link)
        self.link.configure_mock(__str__=lambda _: '\tA-->B: message\n')

    def test_str_with_one_condition(self):
        optional = Optional('condition', [self.link])
        excepted_str = '\topt condition\n\tA-->B: message\n\tend\n'
        self.assertEqual(str(optional), excepted_str)

    def test_str_with_multiple_condition(self):
        optional = Optional('condition-1', [self.link, self.link])
        excepted_str = '\topt condition-1\n\tA-->B: message\n\tA-->B: message\n\tend\n'
        self.assertEqual(str(optional), excepted_str)

class TestParallel(unittest.TestCase):
    def setUp(self):
        self.link = mock.MagicMock(spec=Link)
        self.link.configure_mock(__str__=lambda _: '\tA-->B: message\n')

    def test_str_with_one_condition(self):
        parallel = Parallel({'condition': [self.link]})
        excepted_str = '\tpar condition\n\tA-->B: message\n\tend\n'
        self.assertEqual(str(parallel), excepted_str)

    def test_str_with_multiple_condition(self):
        parallel = Parallel({
            'condition-1': [self.link],
            'condition-2': [self.link]
        })
        excepted_str = '\tpar condition-1\n\tA-->B: message\n\tand condition-2\n\tA-->B: message\n\tend\n'
        self.assertEqual(str(parallel), excepted_str)

    def test_str_with_multiple_condition_and_logic(self):
        loop = mock.MagicMock(spec=Loop)
        loop.configure_mock(
            __str__=lambda _: '\tloop condition\n\tA-->B: message\n\tend\n')
        parallel = Parallel({
            'condition-1': [self.link],
            'condition-2': [loop]
        })
        excepted_str = '\tpar condition-1\n\tA-->B: message\n\tand condition-2\n\tloop '
        excepted_str += 'condition\n\tA-->B: message\n\tend\n\tend\n'
        self.assertEqual(str(parallel), excepted_str)

class TestCritical(unittest.TestCase):
    def setUp(self):
        self.link = mock.MagicMock(spec=Link)
        self.link.configure_mock(__str__=lambda _: '\tA-->B: message\n')

    def test_str_with_one_condition(self):
        critical = Critical('condition-1', [self.link],
                            {'condition-2': [self.link]})
        expected_str = '\tcritical condition-1\n\tA-->B: message\n'
        expected_str += '\toption condition-2\n\tA-->B: message\n\tend\n'
        self.assertEqual(str(critical), expected_str)

    def test_str_with_multiple_condition(self):
        critical = Critical('condition-1', [self.link, self.link], {
            'condition-2': [self.link],
            'condition-3': [self.link]
        })
        expected_str = '\tcritical condition-1\n\tA-->B: message\n'
        expected_str += '\tA-->B: message\n'
        expected_str += '\toption condition-2\n\tA-->B: message\n'
        expected_str += '\toption condition-3\n\tA-->B: message\n\tend\n'
        self.assertEqual(str(critical), expected_str)

class TestBreak(unittest.TestCase):
    def setUp(self) -> None:
        self.link = mock.MagicMock(spec=Link)
        self.link.configure_mock(__str__=lambda _: '\tA-->B: message\n')

    def test_str_with_one_statement(self):
        break_ = Break('condition', [self.link])
        expected_str = '\tbreak condition\n\tA-->B: message\n\tend\n'
        self.assertEqual(str(break_), expected_str)

    def test_str_with_multiple_statements(self):
        break_ = Break('condition', [self.link, self.link])
        expected_str = '\tbreak condition\n\tA-->B: message\n\tA-->B: message\n\tend\n'
        self.assertEqual(str(break_), expected_str)

class TestRect(unittest.TestCase):
    def setUp(self) -> None:
        self.link = mock.MagicMock(spec=Link)
        self.link.configure_mock(__str__=lambda _: '\tA-->B: message\n')

    def test_str_with_one_statement(self):
        rect = Rect([self.link], (255, 0, 0))
        expected_str = '\trect rgb(255,0,0)\n\tA-->B: message\n\tend\n'
        self.assertEqual(str(rect), expected_str)

    def test_str_with_multiple_statements(self):
        rect = Rect([self.link, self.link], (255, 0, 0))
        expected_str = '\trect rgb(255,0,0)\n\tA-->B: message\n\tA-->B: message\n\tend\n'
        self.assertEqual(str(rect), expected_str)

    def test_rect_assertion(self):
        with self.assertRaises(ValueError):
            Rect([self.link, self.link], (257, 3, 4, 4))
        with self.assertRaises(ValueError):
            Rect([self.link, self.link], (257, 3, -4))

class TestSequenceDiagram(unittest.TestCase):
    def setUp(self) -> None:
        self.actor_1 = mock.MagicMock(spec=Actor)
        self.actor_1.configure_mock(__str__=lambda _: '\tactor A\n')
        self.actor_2 = mock.MagicMock(spec=Actor)
        self.actor_2.configure_mock(__str__=lambda _: '\tactor B\n')
        self.link_1 = mock.MagicMock(spec=Link)
        self.link_1.configure_mock(__str__=lambda _: '\tA-->B: message\n')
        self.link_2 = mock.MagicMock(spec=Link)
        self.link_2.configure_mock(__str__=lambda _: '\tA-->B: message\n')

    def test_str_without_auto_number(self):
        diagram = SequenceDiagram(
            'Test Diagram',
            [self.actor_1, self.actor_2, self.link_1, self.link_2])
        expected_str = """---
title: Test Diagram
---
sequenceDiagram
\tactor A
\tactor B
\tA-->B: message
\tA-->B: message
"""
        self.assertEqual(diagram.script, expected_str)

    def test_str_with_auto_number(self):
        diagram = SequenceDiagram(
            'Test Diagram',
            [self.actor_1, self.actor_2, self.link_1, self.link_2],
            auto_number=True)
        expected_str = """---
title: Test Diagram
---
sequenceDiagram
\tautonumber
\tactor A
\tactor B
\tA-->B: message
\tA-->B: message
"""
        self.assertEqual(diagram.script, expected_str)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 31 01:33:29 2020

@author: abhijithneilabraham
"""

a=[1,2, 3 ,2,2,2,1, 2, 3, 3, 3]
def equalizeArray(arr):
    x=arr.count(max(list(set(arr)),key=arr.count))
    return len(arr)-x

equalizeArray(a)


import pandas as pd
import numpy as np
import json
import requests
from requests.auth import HTTPBasicAuth
import networkx as nx
import data
from collections import OrderedDict
import random

def getNeigbors(fun, st):
    if st == [] or (st is None):
        return []
    if type(st) == str:
        return fun(st)
    if type(st) == unicode:
        return fun(str(st))
    if type(st) == list and len(st) > 0 and type(st[0]) == list:
        st = st[0]
    # print "ST"
    # print st
    # print type(st)
    final = [fun(item) for item in st]
    if any(isinstance(i, list) for i in final):  # check to see if is a list
        final = [val for sublist in final for val in sublist]  # flatten
    final = list(set(final))  # note this fucks up order
    if final is None:
        return []
    return final

def getImpact(user, content, G):
    newPrediction = []
    impactedPredictions = []
    A = set([user])

    B = set(G.neighbors(content))

    C = set(getNeigbors(G.neighbors, getNeigbors(G.neighbors, user)))
    C.remove(user)
    abcUnion = (A | B | C)
    for someUser in abcUnion:
        before = G.neighbors(someUser)
        before = getNeigbors(G.neighbors, before).remove(someUser)
        before = getNeigbors(G.neighbors, before)
        before = [item for item in before if item not in G.neighbors(someUser)]
        if someUser in A:
            after = getNeigbors(
                G.neighbors, getNeigbors(G.neighbors, content))
            after = [
                item for item in after if item not in G.neighbors(content)]
            after.remove(content)
        elif someUser in B:
            after = set(getNeigbors(G.neighbors, user)) - \
                set(getNeigbors(G.neighbors, someUser))
        elif someUser in C:
            after = content
        for someContent in (set(after) or set(before)):
            impactedPredictions.append((someUser, someContent))
    #     for item in (set(after) - set(before)):
    #         newPrediction.append( (someUser,someContent))
    # return impactedPredictions, newPrediction
    return len(impactedPredictions)

def checkUnwatched(userItemVids):
    allVids = data.getAllContentIds()
    allVidsSet = set()
    for i in allVids:
        allVidsSet.add(str(i['video_id']))
    unWatchedVids = allVidsSet - userItemVids
    return unWatchedVids

def getBestRec(user):
    G = data.getGraph()
    userItemVidObjective = OrderedDict() # for getting top impacted user content pairs
    userItemVids = []
    numImpactedRecs = []
    if user not in G.nodes():
        return
    visited = set(G.neighbors(user))
    userItemVids = set()
    for i in G.nodes(data=True):  # get list of all watched vids
        if i[1]['type'] == 'video':
            userItemVids.add(i[0])
    unWatchedVids = checkUnwatched(userItemVids)
    numUnWatchedVids = len(unWatchedVids)
    if numUnWatchedVids >= 6:
        return random.sample(list(unWatchedVids), 6)
    else:
        for product in list(userItemVids - visited):
            userItemVidObjective[product] = getImpact(user, product, G)
        userItemVnseenvids = userItemVidObjective.keys()
        scores = userItemVidObjective.values()
        sorted_idx = np.argsort(scores)
        sorted_words = [userItemVnseenvids[ii] for ii in sorted_idx[::-1]]
        numRecomsToUse = 6 - numUnWatchedVids
        finalrecs = random.sample(sorted_words[:15], numRecomsToUse) + list(unWatchedVids)
        return finalrecs


def convert_to_melody(_music):
    lst = []
    for m in _music:
        if m == '#':
            lst[len(lst) - 1] = lst[len(lst) - 1] + '#'
        else:
            lst.append(m)
    return lst

def solution(music, musicinfos):
    answer = [0, '(None)']

    music = convert_to_melody(music)
    len_music = len(music)

    for musicinfo in musicinfos:
        start, end, title, melody = musicinfo.split(',')
        melody = convert_to_melody(melody)
        len_melody = len(melody)
        s_h, s_m = map(int, start.split(':'))
        e_h, e_m = map(int, end.split(':'))
        length = (e_h - s_h) * 60 + (e_m - s_m)
        for m in range(len_melody):
            if melody[m] == music[0]:
                for n in range(1, len_music):
                    if m + n + 1 > length or music[n] != melody[(m + n) % len_melody]:
                        break
                else:
                    if length > answer[0]:
                        answer = [length, title]
                    break

    return answer[1]

정준현/15_프로그래머스_4/방금그곡.py


from PIL import ImageFont

def get_font(font_file, font_size, text_weight, text_decoration):
    font_files = {
    "Roboto": "fonts/Roboto-Regular.ttf",
    "Staatliches": "fonts/Staatliches-Regular.ttf",
    "AbrilFatface": "fonts/AbrilFatface-Regular.ttf",
    "AlfaSlabOne": "fonts/AlfaSlabOne-Regular.ttf",
    "Belanosima-Bold": "fonts/Belanosima-Bold.ttf",
    "Belanosima-Regular": "fonts/Belanosima-Regular.ttf",
    "Belanosima-SemiBold": "fonts/Belanosima-SemiBold.ttf",
    "Caprasimo-Regular": "fonts/Caprasimo-Regular.ttf",
    "LilitaOne-Regular": "fonts/LilitaOne-Regular.ttf",
    "Lobster-Regular": "fonts/Lobster-Regular.ttf",
    "PatuaOne-Regular": "fonts/PatuaOne-Regular.ttf",
    "Righteous-Regular": "fonts/Righteous-Regular.ttf",
    "Rowdies-Bold": "fonts/Rowdies-Bold.ttf",
    "Rowdies-Light": "fonts/Rowdies-Light.ttf",
    "Rowdies-Regular": "fonts/Rowdies-Regular.ttf"
    }

    font_file = font_files.get(font_file)

    if font_file is not None:
        font = ImageFont.truetype(font_file, font_size)
    else:
        font = ImageFont.truetype("fonts/Roboto-Regular.ttf", font_size)

    if text_weight == "bold":
        font = font.font_variant(weight="bold")

    if text_decoration == "underline":
        font = font.font_variant(underline=True)

    return font

def get_text_position_x(image_width, text_width, alignment, padding):
    if alignment == "center":
        return (image_width - text_width) // 2
    elif alignment == "right":
        return image_width - text_width - padding
    else:
        return padding


#TP3 Ej 1
import random

class MenorMinimoError(Exception):
    pass

class MayorMaximoError(Exception):
    pass

def validar_numero(texto_numero, nro_min, nro_max):
    numero = int(texto_numero)
    if numero <= nro_min:
        raise MenorMinimoError()
    if numero >= nro_max:
        raise MayorMaximoError()
    return numero

def ingresar_numero(mensaje, nro_min, nro_max, mensaje_min, mensaje_max):

    while True:
        try:
            return validar_numero(input(mensaje), nro_min, nro_max)

        except ValueError:
            print("Debe ingresar un número entero")

        except MenorMinimoError:
            print(mensaje_min)

        except MayorMaximoError:
            print(mensaje_max)

def cargar_matriz(matriz):
    for f in range(0,len(matriz)):
        for c in range(0,len(matriz[f])):
            matriz[f][c] = ingresar_numero("Ingrese un número: ", 0, 100, "Ingrese un número mayor a cero", "Ingrese un número menor a 100")

def cargar_matriz_aleatoria(matriz):
    for f in range(0,len(matriz)):
        for c in range(0,len(matriz[f])):
            matriz[f][c] = random.randint(0,99)

def imprimir_matriz(matriz):
    for f in range(0,len(matriz)):
        for c in range(0,len(matriz[f])):
            print("{0:>2}".format(matriz[f][c]), end='|')
        print()

def porcentaje_impares_fila(matriz, fila):
    cantidad_impares = 0
    cantidad_columnas = len(matriz[0])

    for c in range(0, cantidad_columnas):
        if matriz[fila][c] % 2 != 0:
            cantidad_impares = cantidad_impares + 1

    porcentaje = ( cantidad_impares / cantidad_columnas ) * 100
    return porcentaje

def porcentaje_impares_columna(matriz, columna):
    cantidad_impares = 0
    cantidad_filas = len(matriz)
    cantidad_columnas = len(matriz[0])

    for f in range(0, cantidad_filas):
        if matriz[f][columna] % 2 != 0:
            cantidad_impares = cantidad_impares + 1

    porcentaje = ( cantidad_impares / cantidad_filas ) * 100
    return porcentaje

def es_matriz_simetrica(matriz):
    for f in range(0,len(matriz)):
        for c in range(0,len(matriz[f])):
            if matriz[f][c] != matriz[c][f]:
                return False
    return True

def main():
    fila_columna= 10
    vector = [(0 * j) for j in range(fila_columna)]
    matriz = [vector for i in range(fila_columna)]

    imprimir_matriz(matriz)

    matriz_simetrica = [[1,2,3,4,5],[2,1,3,4,7],[3,3,1,4,6],[4,4,4,1,5],[5,7,6,5,1]]
    # imprimir_matriz(matriz_simetrica)
    matriz_asimetrica = [[1,2,3,4,5],[2,1,3,4,7],[3,3,1,4,6],[4,4,4,1,5],[5,7,6,9,1]]

    #Ejercicio a
    #cargar_matriz(matriz)

    #Ejercicio h
    cargar_matriz_aleatoria(matriz)
    porcentaje = porcentaje_impares_columna(matriz, 5)
    imprimir_matriz(matriz)
    print("Porcentaje: ", porcentaje)

    if es_matriz_simetrica(matriz_asimetrica):
        print("Es simetrica")
    else:
        print("Es asimetrica")

if __name__ == "__main__":
    main()


#!/usr/bin/env python3
# -*- encoding: utf-8 -*-

import logging
from copy import copy
from functools import partial
from itertools import chain, combinations, product

import six

from .patterns import dollar_prefix, pop_dollar_prefix, _convert_names_with_underlines_to_dots

logger = logging.getLogger(__name__)

class MongoAggregation(list):

    def __init__(self, pipeline='', collection='', allowDiskUse=False):
        self.collection = collection
        self.allowDiskUse = allowDiskUse
        self.actual_fields = set()
        self.pipeline = pipeline if pipeline else []

    def aggregate(self, collection='', allowDiskUse=False, as_list=False, collation=None):
        if collection:
            self.collection = collection
        if self.collection.__class__.__name__ == 'TopLevelDocumentMetaclass':
            self.collection = self.collection.objects
        if allowDiskUse:
            self.allowDiskUse = allowDiskUse
        if self.collection.__class__.__name__ != 'QuerySet' and not self.collection:
            logger.error('Агрегация невозможна: не указана коллекция')
            return
        aggregate = partial(self.collection.aggregate, allowDiskUse=self.allowDiskUse, collation=collation)
        if self.collection.__class__.__name__ == 'QuerySet':
            result = aggregate(*self.pipeline)
        else:
            result = aggregate(self.pipeline)
        return list(result) if as_list else result

    def append(self, object=None, *args):
        if not object: object = []
        if isinstance(object, list):
            self.pipeline.extend(object)
        else:
            self.pipeline.append(object)
        if args:
            for arg in args:
                self.pipeline.append(arg)
        return self

    def extend(self, object=None, *args):
        self.append(object, *args)

    def count(self, **kwargs):
        self.pipeline.append({'$count': 'count'})
        count = next(self.aggregate(**kwargs), {}).get('count', 0)
        # Revert last stage
        self.revert_last_stage()
        return count

    def match(self, *args, **kwargs):
        if not args and not kwargs:
            return self
        if args:
            for arg in args:
                self.pipeline.append({
                    '$match': arg
                })
        kwargs = _convert_names_with_underlines_to_dots(kwargs, convert_operators=True)
        if args and kwargs:
            self.pipeline[-1]['$match'].update(kwargs)
        elif kwargs:
            self.pipeline.append({
                '$match': kwargs
            })
        self._add_to_actual_fields([
            x for x in self.last_stage.statement.keys()
            if not x.startswith('$')
        ])
        return self

    def lookup_unwind(self, collection, local_field='_id', as_field='', foreign_field='_id',
                      preserveNullAndEmptyArrays=True):
        if not as_field:
            as_field = local_field
        self.lookup(collection, local_field, as_field, foreign_field),
        self.unwind(as_field, preserveNullAndEmptyArrays)
        return self

    def lookup(self, collection, local_field='_id', as_field='', foreign_field='_id'):
        if not as_field:
            as_field = local_field
        self.pipeline.append({"$lookup": {
            'from': collection,
            'foreignField': foreign_field,
            'localField': local_field,
            'as': as_field,
        }})
        self._add_to_actual_fields(local_field, ignore_if_theres_children=True)
        self._add_to_actual_fields(as_field, ignore_if_theres_children=True)
        return self

    def unwind(self, field, preserveNullAndEmptyArrays=False):
        field = dollar_prefix(field)
        if preserveNullAndEmptyArrays:
            self.pipeline.append({'$unwind': {'path': field, 'preserveNullAndEmptyArrays': True}})
        else:
            self.pipeline.append({'$unwind': field})
        self._add_to_actual_fields(field, ignore_if_theres_children=True)
        return self

    def order_by(self, *args, **kwargs):
        return self.sort(*args, **kwargs)

    def sort(self, *args, **kwargs):
        def _prepare_str_order_rule(order_rule):
            if not isinstance(order_rule, six.string_types):
                return order_rule
            sign = -1 if order_rule.startswith('-') else 1
            sort_field = order_rule.strip('-+')
            return {sort_field: sign}

        kwargs = _convert_names_with_underlines_to_dots(kwargs)
        # Складываем все в args
        args = list(args)
        if kwargs:
            args.append(kwargs)

        if not args: return self
        # Делаем project
        for order_rule in args:
            order_rule = _prepare_str_order_rule(order_rule)
            self.pipeline.append({"$sort": order_rule})
            self._add_to_actual_fields(order_rule.keys())
        return self

    def skip(self, offset=0):
        if not offset: return self
        self.pipeline.append({"$skip": offset})
        return self

    def limit(self, limit=0):
        if not limit: return self
        self.pipeline.append({"$limit": limit})
        return self

    def project(self, *args, **kwargs):
        kwargs = _convert_names_with_underlines_to_dots(kwargs)
        # Складываем все в args
        if args and kwargs:
            args[-1].update(kwargs)
        elif kwargs:
            args = (kwargs,)
        if not args: return self

        # Делаем project
        for arg in args:
            self.pipeline.append({'$project': arg})
        # Заполняем актуальные поля
        self._set_actual_fields(arg.keys())
        return self

    def _get_fields_without_children(self, fields):
        parents = copy(fields)
        for one, another in combinations(fields, 2):
            is_children = another.startswith(f'{one}.')
            if is_children:
                parents.discard(another)
                continue
            is_children = one.startswith(f'{another}.')
            if is_children:
                parents.discard(one)
                continue
        return parents

    @staticmethod
    def _str_to_list(variable):
        return variable.split(',') if isinstance(variable, str) else variable

    def _set_actual_fields(self, *fields):
        """Устанавливает список актуальных полей"""
        self.actual_fields = set(chain(*fields))

    def _add_to_actual_fields(self, fields, ignore_if_theres_children=True):
        """Добавляет поля в список актуальных полей"""
        _fields = set(self._str_to_list(fields))
        if ignore_if_theres_children:
            _fields = [
                field
                for field in _fields
                if pop_dollar_prefix(field) not in self.get_parents(self.actual_fields, all_levels=True)
            ]
        for field in _fields:
            self.actual_fields.add(pop_dollar_prefix(field))

    @staticmethod
    def get_parents(fields, all_levels=False, upper_level=True):
        if isinstance(fields, str):
            fields = set(fields.split(','))

        # Самый нижний уровень
        if not all_levels and not upper_level:
            return {field.split('.')[0] for field in fields}

        # Все уровни и верхний
        parents = set()
        for field in fields:
            splitted = field.split('.')
            for i in range(len(splitted)):
                splitted.pop()
                if not splitted: break
                parents.add('.'.join(splitted))
                # Только верхний уровень
                if not all_levels: break
        return parents

    def replace_root(self, expression):
        """Replaces the input document with the specified document.
        The operation replaces all existing fields in the input document, including the _id field.
        From MongoDB version 3.4."""
        if isinstance(expression, six.string_types):
            expression = dollar_prefix(expression)
        self.pipeline.append({'$replaceRoot': {'newRoot': expression}})
        return self

    def add_fields(self, **kwargs):
        """Adds new fields to documents.
        $addFields outputs documents that contain all existing fields from the input documents and newly added fields.
        From MongoDB version 3.4
        Starting in version 4.2, MongoDB adds a new aggregation pipeline stage $set that is an alias for $addFields.
        """
        kwargs = _convert_names_with_underlines_to_dots(kwargs)
        self.pipeline.append({'$addFields': kwargs})
        self._add_to_actual_fields(kwargs.keys())
        return self

    def set(self, **kwargs):
        """Adds new fields to documents.
        $set outputs documents that contain all existing fields from the input documents and newly added fields.
        From MongoDB version 4.2."""
        kwargs = _convert_names_with_underlines_to_dots(kwargs)
        self.pipeline.append({'$set': kwargs})
        self._add_to_actual_fields(kwargs.keys())
        return self

    def smart_project(self, include_fields='', exclude_fields='', include_all_by_default=True, *args, **kwargs):
        """Custom realization of $addFields for an older versions of MongoDB. Bases on $project stage."""
        if not include_all_by_default:
            self.actual_fields = set()

        if include_fields:
            include_fields = set(include_fields.split(','))
            parent_fields = self.get_parents(include_fields, True)
            self.actual_fields -= parent_fields
            self.actual_fields.update(include_fields)

        # Проверяем обращение к полям объекта с помощью __ в kwargs
        kwargs = _convert_names_with_underlines_to_dots(kwargs)

        # Складываем kwargs в args
        args = self._add_kwargs_to_args(args, kwargs)

        if exclude_fields:
            exclude_fields = set(exclude_fields.split(','))

        if any(args) or include_fields:
            # Exclude fields may contain some information of what fields to include (calculate by contradiction)
            if exclude_fields:
                # Add parents first
                # actual_fields = {'count'}
                # exclude_field = 'menu.elements.option'
                # Parent: 'menu.elements'
                # Result: actual_fields = {'count', 'menu.elements'}
                for excl_field in exclude_fields:
                    self.actual_fields.update(self.get_parents(excl_field, True))
                for excl_field in exclude_fields:
                    # Remove the field itself
                    self.actual_fields.discard(excl_field)
                    # Remove all children
                    # actual_fields = {'menu.elements.option', 'menu.elements.count', 'count'}
                    # exclude_field = 'menu.elements'
                    # Children: 'menu.elements.option', 'menu.elements.count'
                    # Result: actual_fields = {'count'}
                    child_fields = {
                        act_field for act_field in self.actual_fields
                        if '{}.'.format(excl_field) in act_field
                    }
                    self.actual_fields -= child_fields

            paths = self._get_stage_hierarchy_fields(args[-1])
            if not paths and self.actual_fields:
                prolong_fields = self.actual_fields
            else:
                prolong_fields = set([actual_field
                                      for new_field, actual_field in product(paths, self.actual_fields)
                                      if actual_field != new_field
                                      and not actual_field.startswith(f'{new_field}.')
                                      and not new_field.startswith(f'{actual_field}.')])
            prolong_fields = self._get_fields_without_children(prolong_fields)
            for field in prolong_fields:
                args[-1].setdefault(field, 1)

            # Делаем project
            if args:
                for arg in args:
                    self.pipeline.append({'$project': arg})
                # Заполняем актуальные поля
                self._set_actual_fields(self._get_stage_hierarchy_fields(arg))

        # Then esclude fields and children
        if exclude_fields:
            # !!! This is the same section, we double it because it may save some fields in earlier projections
            # Add parents first
            for excl_field in exclude_fields:
                self.actual_fields.update(self.get_parents(excl_field, True))
            for excl_field in exclude_fields:
                # Remove the field itself
                self.actual_fields.discard(excl_field)
                # Remove all children
                child_fields = {
                    act_field for act_field in self.actual_fields
                    if '{}.'.format(excl_field) in act_field
                }
                self.actual_fields -= child_fields
            # Exclude projection itself
            self.pipeline.append({'$project': {field: 0 for field in exclude_fields}})

        return self

    def _get_stage_hierarchy_fields(self, stage, prefix=''):
        def get_fields_for_dict_value(value, prefix=''):
            if not isinstance(value, dict):
                return []
            if list(value.keys())[0].startswith('$'):
                literal = value.get('$literal')
                if literal and isinstance(literal, dict):
                    return self._get_stage_hierarchy_fields(literal, prefix)

                return [prefix]
            return self._get_stage_hierarchy_fields(value, prefix)

        paths = []
        for field, value in stage.items():
            new_prefix = f'{prefix}.{field}' if prefix else field
            if isinstance(value, list):
                for obj in value:
                    if isinstance(obj, dict):
                        paths.extend(get_fields_for_dict_value(obj, prefix=new_prefix))
                        break
                continue
            elif isinstance(value, dict):
                paths.extend(get_fields_for_dict_value(value, prefix=new_prefix))
                continue
            paths.append(new_prefix)
            continue
        return paths

    @staticmethod
    def _add_kwargs_to_args(args, kwargs):
        # Складываем kwargs в args
        if args and kwargs:
            args[-1].update(kwargs)
        elif kwargs:
            args = (kwargs,)
        elif not args:
            args = ({},)
        return args

    def group(self, *args, **kwargs):
        """
        Стадия группировки

        :param group_by: Поля группировки. Можно подавать строкой через запятую, либо списком, либо словарем
        :param first_fields: Список полей для оператора $first. Строка либо список.
        :param min_fields: Список полей для оператора $min. Строка либо список.
        :param max_fields: Список полей для оператора $max. Строка либо список.
        :param sum_fields: Список полей для оператора $sum. Строка либо список.
        :param counter_fields: Список полей для оператора $sum, количество просуммированных строк. Строка либо список.
        :param avg_fields: Список полей для оператора $avg. Строка либо список.
        :param push_fields: Список полей для оператора $push. Строка либо список.
        :param addToSet_fields: Список полей для оператора $addToSet. Строка либо список.
        :param operator_by_default: Используемый оператор для остальных полей actual_fields. По умолчанию не добавляет остальные поля в результат.
        :param exclude_fields: Использовать operator_by_default для всех, кроме перечисленных. Строка через запятую, либо список.
        :param args: Описание остальных полей группировки словарем, либо несколькими словарями.
        :param kwargs: Описание остальных полей группировки именованными аргументами.
        :return:
        """
        group_by = kwargs.pop('group_by', None)
        first_fields = kwargs.pop('first_fields', None)
        min_fields = kwargs.pop('min_fields', None)
        max_fields = kwargs.pop('max_fields', None)
        sum_fields = kwargs.pop('sum_fields', None)
        counter_fields = kwargs.pop('counter_fields', None)
        avg_fields = kwargs.pop('avg_fields', None)
        push_fields = kwargs.pop('push_fields', None)
        add_to_set_fields = kwargs.pop('addToSet_fields', None)
        operator_by_default = kwargs.pop('operator_by_default', None)
        exclude_fields = kwargs.pop('exclude_fields', False)
        if exclude_fields:
            exclude_fields = exclude_fields.split(',')

        # Инициализируем stage группировки
        stage = {}

        kwargs = _convert_names_with_underlines_to_dots(kwargs, convert_operators=True)
        # Добавляем kwargs и args в stage
        args = self._add_kwargs_to_args(args, kwargs)
        for arg in args:
            if not isinstance(arg, dict): continue
            if not arg: continue
            stage.update(arg)

        # Подготовка и обработка операторов группировки
        operators = {
            '$first': first_fields,
            '$min': min_fields,
            '$max': max_fields,
            '$sum': sum_fields,
            '$avg': avg_fields,
            '$push': push_fields,
            '$addToSet': add_to_set_fields,
        }
        for operator, fields in operators.items():
            if not fields: continue
            self._group_set_operator(stage, fields, operator)
        if counter_fields:
            self._counter_set_operator(stage, counter_fields)

        # Указываем поле группировки
        stage['_id'] = self._group_get_id(group_by)

        # Устанавливаем по дефолту $first для остальных полей
        if operator_by_default:
            parent_fields = self.get_parents(self.actual_fields, True)
            if isinstance(stage['_id'], str):
                _id_fields = pop_dollar_prefix(stage['_id'])
            else:
                _id_fields = stage['_id'].keys()
            for field in parent_fields:
                if field in chain(stage, _id_fields):
                    continue
                elif field in exclude_fields:
                    continue
                stage[field] = {operator_by_default: dollar_prefix(field)}

        # Формируем actual_fields
        if not stage['_id']:
            _id_fields = []
        elif isinstance(stage['_id'], str):
            _id_fields = ['_id']
        else:
            _id_fields = ['_id.{}'.format(key) for key in stage['_id'].keys()]

        def get_prolonged_actual_fields_for(*fields_lists):
            prolong_fields = []
            new_fields = [self._str_to_list(fields) for fields in fields_lists if fields]
            for actual_field, new_field in product(self.actual_fields, chain(*new_fields)):
                if not actual_field.startswith(new_field):
                    continue
                prolong_fields.append(actual_field)
            return prolong_fields

        prolonged_actual_fields = get_prolonged_actual_fields_for(first_fields, push_fields, add_to_set_fields)
        self._set_actual_fields(stage, _id_fields, prolonged_actual_fields)

        self.pipeline.append({'$group': stage})
        return self

    def _group_set_operator(self, stage, fields, operator):
        if not fields: return
        if isinstance(fields, str):
            fields = fields.split(',')
        fields = _convert_names_with_underlines_to_dots(fields)
        if isinstance(fields, dict):
            fields = fields.keys()
        for field in fields:
            stage[pop_dollar_prefix(field)] = {operator: dollar_prefix(field)}

    def _counter_set_operator(self, stage, fields):
        if not fields: return
        if isinstance(fields, str):
            fields = fields.split(',')
        fields = _convert_names_with_underlines_to_dots(fields)
        if isinstance(fields, dict):
            fields = fields.keys()
        for field in fields:
            stage[pop_dollar_prefix(field)] = {'$sum': 1}

    def _group_get_id(self, group_by=None):
        # Допустимая ситуация: группировка всех строк в одну
        if not group_by: return None

        # Преобразуем к списку, если строка
        if isinstance(group_by, str):
            group_by = group_by.split(',')

        # Преобразуем имена вида item__name к item.name
        group_by = _convert_names_with_underlines_to_dots(group_by)

        # Если group_by - словарь, считаем его сформированным корректно
        if isinstance(group_by, dict):
            return group_by

        # Если список, формируем словарь или одно соответсвие
        if isinstance(group_by, list):
            if len(group_by) == 1:
                return dollar_prefix(group_by[0])

            return {pop_dollar_prefix(field): dollar_prefix(field) for field in group_by}

        # Опасная ситуация, но иначе никак - пусть группирует по всем строкам
        return None

    @property
    def last_stage(self):
        if not self.pipeline:
            return None
        return LastStage(self.pipeline)

    def revert_last_stage(self):
        if not self.pipeline:
            return
        self.pipeline = self.pipeline[:-1]

    def get_first(self, default=None, **kwargs):
        # Limit pipeline to 1 document
        self.limit(1)
        # Get first document to include statistics_today lately
        first_doc = next(self.aggregate(**kwargs), default)
        # Undo limit
        self.revert_last_stage()
        return first_doc

    def get_count(self, **kwargs):
        return self.count(**kwargs)

class LastStage():

    def __init__(self, pipeline):
        if not pipeline:
            raise Exception("Последнего этапа в этой агрегации не существует.")
        self.__data = pipeline[-1]

    @property
    def name(self):
        return list(self.__data.keys())[0]

    @name.setter
    def name(self, value):
        self.__data[value] = self.__data.pop(self.name)

    @property
    def statement(self):
        return self.__data[self.name]

    @statement.setter
    def statement(self, value):
        self.__data[self.name] = value

    def __repr__(self):
        return str(self.__data)

if __name__ == "__main__":
    import logging
    import os

    from dotenv import load_dotenv

    load_dotenv()

    mongo_connection = os.environ.get('MONGODB_HOST', 'mongodb://localhost:27017/test')
    import pymongo
    from datetime import datetime
    from dateutil.relativedelta import relativedelta

    logger = logging.getLogger()
    client = pymongo.MongoClient(mongo_connection)
    db = client.get_default_database()
    today = datetime.now()
    yesterday = today - relativedelta(days=1)

    pipeline = MongoAggregation(collection=db.action)
    pipeline.match(
        {'date': {'$gte': yesterday, '$lt': today}},
        completed=True,
        _cls={'$in': [
            'Action.Order', 'Action.StorageIncome', 'Action.StorageCancellation', 'Action.StorageMovementOutcome'
        ]},
    ).smart_project(
        'transactions.amount,_cls', '_id'
    ).append([
        {'$project': {
            '_cls': 1,
            'date': 1,
            'transactions.amount': 1,
            'transactions.cashbox': 1,
        }},
    ]).project(
        {'transactions.amount': 1, 'transactions.cashbox': 1}, _cls=1, date=1
    ).project(
        transactions=1, _cls=1, date=1
    )
    cursor = pipeline.aggregate()

    for doc in cursor:
        print(doc)
        break


# -*- coding: utf-8 -*-
from eaglet.core import watchdog
from eaglet.utils.resource_client import Resource

from business import model as business_model
from db.mall import models as mall_models

class WZCard(business_model.Model):
    """
    订单
    """

    __slots__ = (

    )

    @staticmethod
    def refund_for_order(order):
        """
        微众卡退款
        """
        # 交易类型（支付失败退款：0、普通退款：1）

        trade_id = mall_models.OrderCardInfo.select().dj_where(order_id=order.order_id).first().trade_id
        data = {
            'trade_id': trade_id,
            'trade_type': 1  # 普通退款
        }

        msg = {
            'uuid': 'refund_wzcard',
            'order_id': order.order_id,
            'weizoom_card_money': order.weizoom_card_money
        }

        watchdog.info(message=msg, log_type='business_log')

        resp = Resource.use('card_apiserver').delete({
            'resource': 'card.trade',
            'data': data
        })

        return resp


import urllib

import treq
from twisted.internet import reactor
from twisted.internet.defer import CancelledError
from twisted.internet.task import deferLater

from twisted.python import log

from src.config import BACKEND_REQUEST_TIMEOUT, BACKEND_URL

class DecoupledRequest(object):
    def __init__(self, factory, _id, client_request):
        self.factory = factory
        self.id = _id
        self.client_request = client_request

        self.request_defer = self.do_request()

        # save timeout_Defer for later to be cancelled in case callback got received in time
        self.timeout_defer = deferLater(reactor, BACKEND_REQUEST_TIMEOUT, self.on_timeout)
        self.timeout_defer.addErrback(self.on_timeout_error)

        # if client disconnects (close browser) then cancel all activity
        client_request.notifyFinish().addErrback(self.on_client_disconnect)

    def create_url(self):
        args = self.client_request.args
        args['request_id'] = [self.id]
        query_string = urllib.urlencode(self.client_request.args, True)
        return "%s?%s" % (BACKEND_URL, query_string)

    @staticmethod
    def on_timeout_error(error):
        if not isinstance(error.value, CancelledError):
            raise error.value

    def on_client_disconnect(self, _):
        self.log('client disconnected, destroying request')

        self.timeout_defer.cancel()
        self.request_defer.cancel()
        self.destroy()

    def do_request(self):
        self.log('requesting backend')

        d = treq.get(self.create_url())
        d.addCallback(self.on_request_success)
        d.addErrback(self.on_request_error)
        return d

    def on_request_success(self, response):
        if response.code == 200:
            self.log('request successful. waiting for callback')
        else:
            return treq.content(response).addCallback(self.print_error, 502)

    def on_request_error(self, failure):
        self.log('request error')
        self.print_error(failure.getErrorMessage(), 503)
        self.destroy()

    def print_error(self, msg, code):
        self.client_request.setResponseCode(code)
        self.client_request.write("Backend failed with: %s" % msg)
        self.client_request.finish()

    def on_timeout(self):
        self.log('got timeout')

        self.request_defer.cancel()

        self.client_request.setResponseCode(503)
        self.client_request.write('Response took longer than %s sec, cancelled. '
                                  'Please try again later.' % BACKEND_REQUEST_TIMEOUT)
        self.client_request.finish()

        self.destroy()

    def notify(self, callback_request):
        value = callback_request.content.getvalue()

        self.log('got callback: %s' % value)

        self.client_request.write(value)
        self.client_request.finish()

        self.destroy()

    def destroy(self):
        self.timeout_defer.cancel()
        self.factory.remove_by_id(self.id)

    def log(self, msg):
        log.msg('request %s: %s' % (self.id, msg))


#-------------------------------------------------------------------------------
# -*- coding: UTF-8 -*-
# Name:        模块1
# Purpose:
#
# Author:      li
#
# Created:     28/12/2016
# Copyright:   (c) li 2016
# Licence:     <your licence>
#-------------------------------------------------------------------------------
def substitute():
    start=int(input("change a word from article No.:"))
    stop=int(input("to article No.:"))

    while input('continue?(No:0000):')!='0000':
        print('\n')
        origin=input('original word?:')
        new=input('change to?:')
        for i in range(start,stop+1):
            f1=open('corpus/'+repr(i)+'-std.txt','r',encoding='UTF-8')
            std=f1.read()
            count=std.count(origin)
            if count!=0:
                std2=std.replace(origin,new)
                print("第{0}篇替换了{1}个'{2}'，换成了“{3}”；".format(i,count,origin,new))
                f2=open('corpus/'+str(i)+'-std.txt','w',encoding='UTF-8')
                f2.write(std2)
                f2.close()
            f1.close()

def main():
    def getdate():
        import time
        date_str=time.asctime()
        date_str=date_str[4:10]+date_str[-5:]
        return date_str
    date_str=getdate()

    def initial():
        ver_file=open('./dict/latest.log','r',encoding='UTF-8')
        ver=ver_file.readline()
        ver=ver.replace('\n','')
        url_file=open('./dict/'+ver[:-3]+'log','r',encoding='UTF-8')
        urls=url_file.readlines()
        global urls
        url_file.close()

        url_file=open('./dict/'+ver[:-3]+'log','w',encoding='UTF-8')
        url_file.write('')
        url_file.close()

        dic_file=open('./dict/'+ver,'w',encoding='UTF-8')
        dic_file.write('')
        dic_file.close()

    initial()

    import dictionary as d

    def Add_to_dictionary():
        print('现在开始执行Add_to_dictionary()')
        def output_to_dict(dic,url_list):
            def freshdict(dic,file_str):
                    '''This output dic into a .dic file'''
                    def format_fix(fix_dict):# for Prefix and Suffix
                            ret=''
                            for ele in fix_dict.keys():
                                    ret=ret+ele+':'+str(fix_dict[ele])+','
                            return ret
                    f=open(file_str,'w',encoding='UTF-8')
                    for entry in dic:
            #中文|Word|360|Num|简体:290,繁体:60,None:10|Pre|分词:230,自修:100,考试:20,None:10|Suf|
                            f.write("{0}|Word|{1}|Num|{2}|Pre|{3}|Suf|\n"
                                    .format(entry['Word'],entry['Num'],format_fix(entry['Pre']),format_fix(entry['Suf'])))
                    f.close()

            def freshurl(url_list,file_str):
                    """This output new_url_list into a .log file"""
                    f=open(file_str,'w',encoding='UTF-8')
                    for ele in url_list:
                        if ele not in urls:
                            f.write(ele)
                    f.writelines(urls)
                    f.close()
   #Refresh Version Information
            f=open("dict/latest.log","w")

            file_str=date_str+'.dic'
            f.write(file_str+'\n')
            f.close()
            freshdict(dic,"dict/"+file_str)

        start=int(input("""Now we add words in ariticles into a fresh dict!
Start:"""))
        stop=int(input("Stop:"))

        for i in range(start,stop+1):
            dic,url_list=d.getdict()
            d.train_one_passage(dic,url_list,text_str='corpus/'+repr(i)+'-std.txt')
            d.output_to_dict(dic,url_list)

    Add_to_dictionary()

substitute()
main()


# logic: we can find the largest possible palindrome in a given string, lets say that if not and can take only small part and leave the rest to
# others to minimize and can reduce the other cuts, then need to give away on both sides, so which means it increases the cuts on botjh sides, if
# were able to get on both sides then again they can be merged to main one

# so finding the best one in given string and doing recursively can give the solution i.e. finding the no of max palindromes

# can do it in o(n^2) as we pass every element we can check if that point can lead us to the best, else can move to next
# also we can cut the limit to which the max we found, let us say in midd.sle we found 5 as max means no need of going next to last but but one
# as even found no use. so if in middle we found greater automatically the limit would end the loop with out going further

# better to slice rather than split, as we might loose the necessary data if the repeated sequence is repeated else where
# abcabc or abcabceee

def minCut(s):

        arr=[]
        arr.append(s)
        cuts=0
        print("len is {0}".format(len(s)))

        while arr:
            s=arr[0]
            slen=len(s)
            slice_start=0
            slice_end = 0
            max_pal = 1
            max_pal_str = ''

            limit = len(s)
            if limit < 2 or s==s[::-1]:
                del arr[0]
                continue

            i = 0

            while i < limit:

                pres = s[i]
                j = i + 1
                while j < slen and pres == s[j]:
                    j += 1
                diff = j - i

                if diff > 1:  # we proceed only if the difference is > 1 else its just a single element

                    count = 0
                    trace = start = end = 0

                    trace = i + ((diff - 1) // 2)
                    shift = trace + 1

                    if diff % 2 == 1:  # for odd length can find the middle

                        count += 1
                        start = trace - 1
                        end = trace + 1
                    else:
                        count += 2
                        start = trace - 1
                        end = trace + 2

                    while start >= 0 and end < slen and s[start] == s[end]:
                        count += 2
                        start -= 1
                        end += 1

                    if count >= max_pal:
                        max_pal = count
                        max_pal_str = s[start + 1:end]
                        slice_start = start+1
                        slice_end = end
                    limit = slen - (max_pal // 2)

                    i = max(i + 1, trace + 1)
                    i = shift
                else:  # we chose to iterate normally
                    start = i - 1
                    end = i + 1

                    count = 1
                    while start >= 0 and end < slen and s[start] == s[end]:
                        count += 2
                        start -= 1
                        end += 1

                    if count >= max_pal:
                        max_pal = count
                        max_pal_str = s[start + 1:end]
                        slice_start = start + 1
                        slice_end = end
                    limit = slen - (max_pal // 2)

                    i += 1

            temp=[]
            temp.extend([s[0:slice_start],s[slice_end:] ])
            temp=[i for i in temp if i]
            cuts += len(temp)
            temp = [i for i in temp if len(i)>1]

            del arr[0]
            print("temp array", arr,'\n')

            # temp=[i for i in s.split(max_pal_str) if i]

            arr.extend(temp)

        return cuts

print(minCut("adabdcaebdcebdcacaaaadbbcadabcbeabaadcbcaaddebdbddcbdacdbbaedbdaaecabdceddccbdeeddccdaabbabbdedaaabcdadbdabeacbeadbaddcbaacdbabcccbaceedbcccedbeecbccaecadccbdbdccbcbaacccbddcccbaedbacdbcaccdcaadcbaebebcceabbdcdeaabdbabadeaaaaedbdbcebcbddebccacacddebecabccbbdcbecbaeedcdacdcbdbebbacddddaabaedabbaaabaddcdaadcccdeebcabacdadbaacdccbeceddeebbbdbaaaaabaeecccaebdeabddacbedededebdebabdbcbdcbadbeeceecdcdbbdcbdbeeebcdcabdeeacabdeaedebbcaacdadaecbccbededceceabdcabdeabbcdecdedadcaebaababeedcaacdbdacbccdbcece"))

# a='sdsdfsvsfvsfvsfgasdadrefaef'
# a = a.split('g')
# print(a)
# del a[a.index('sdsdfsvsfvsfvsf')]
# print(a.split('fvsfgasdadrefaef'))


import cv2
import time
import os
import sys
import boto3
import re
from picamera.array import PiRGBArray
from picamera import PiCamera

from time import sleep
import RPi.GPIO as GPIO

from led import green_light_verfied, red_light

GPIO.setmode(GPIO.BCM)

GPIO.setup(21, GPIO.IN, pull_up_down=GPIO.PUD_UP)

faceClient = boto3.client('rekognition')
s3Client = boto3.client("s3")
dynamoClient = boto3.resource("dynamodb")

def runpicam():
    camera = PiCamera()
    camera.vflip = True
    camera.resolution = (640, 480)
    camera.framerate = 32
    rawCapture = PiRGBArray(camera, size=(640, 480))
    time.sleep(0.1)

    faceCascade = cv2.CascadeClassifier(
        "/home/pi/facial-recognition/haarcascade.xml")

    for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):

        image = frame.array
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

        faces = faceCascade.detectMultiScale(
            gray,
            scaleFactor=1.1,
            minNeighbors=5,
            minSize=(30, 30),
            flags=cv2.CASCADE_SCALE_IMAGE
        )

        key = cv2.waitKey(1) & 0xFF
        rawCapture.truncate(0)
        for (x, y, w, h) in faces:
            cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
        if key == ord("q"):
            break

        if len(faces) > 0:
            # if face is detected save the image to file
            detected = True
            img_name = "captured_face.png"
            path = "/home/pi/facial-recognition/Images"
            cv2.imwrite(os.path.join(path, img_name), image)
            camera.stop_preview()
            camera.close()

            return True
        else:
            camera.stop_preview()
            camera.close()
            return False

def uploadToS3():
    # upload web cam footage to s3
    for root, dirs, files in os.walk("/home/pi/facial-recognition/Images"):
        for file in files:
            s3Client.upload_file(os.path.join(root, file),
                                 "face-recogonition", file)  # note this is the spelling on S3

def getAllFaces():
    faceList = []
    bucket = s3Client.list_objects_v2(Bucket="face-recogonition")
    for obj in bucket["Contents"]:
        faceList.append(obj["Key"])
    faceRef = filter(lambda item: "reference" in item, faceList)
    return faceRef

def runFaceCompare():
    referenceList = list(getAllFaces())
    verified = ""
    count = len(referenceList)
    for ref in referenceList:
        response = faceClient.compare_faces(
            SourceImage={
                # "Bytes": b'bytes',
                "S3Object": {
                    "Bucket": "face-recogonition",
                    "Name": ref
                }
            },
            TargetImage={
                # "Bytes": b'bytes',
                "S3Object": {
                    "Bucket": "face-recogonition",
                    "Name": "captured_face.png"
                }
            },
            SimilarityThreshold=70.0
        )
        # get confidence
        confidence = 0
        if len(response["FaceMatches"]) != 0:
            confidence = response["FaceMatches"][0]["Similarity"]

        if (confidence > 90):
            green_light_verfied()
            setActiveUser(ref)
            #os.system('sh kill.sh')
            #os.system('sh script_slideshow.sh')
            return True
        else:
            count -= 1
            red_light(3)

        if count == 0:
            return False

def setActiveUser(ref):
    user = re.match(r"(.*?)-", ref).group(1)
    print(user)
    table = dynamoClient.Table("Moments-prod")
    setActiveUser = table.update_item(
        Key={"usr": "Active"},
        UpdateExpression="SET refActive = :val",
        ExpressionAttributeValues={
            ":val": user,
        },
        ReturnValues="UPDATED_NEW"
    )

def start():

    faceDetected = runpicam()
    if faceDetected:
        uploadToS3()
        runFaceCompare()
    else:
        print("sorry couldn't verify your face")
        red_light(3)

while True:
    if(GPIO.input(21) == True):
        red_light(0.5)
        start()
        sleep(0.2)