import pickle
import os
import re
import sqlalchemy as db
from sqlalchemy.sql import text
import cx_Oracle

#################################################################################

###################################################################################
def main() :
    student = []
    name = ''
    kor_s = 0
    math_s = 0
    eng_s = 0
    os.environ['NLS_LANG'] = '.UTF8'
    engine = db.create_engine("oracle://hr:hr@localhost:1521/xe")
    # student = []
    student = load_cust(student, engine)
    print(student)
    while True:
        print("""
    다음 중 작업하실 메뉴를 선택하세요
    I : 성적 입력
    S : 과목별 성적 조회
    P : 학생별 성적 조회
    U : 학생 성적 수정
    D : 학생 성적 삭제
    Q : 프로그램 종료""")
        sel_main = input("원하시는 작업을 선택해 주세요 :  ").strip().upper()
        if sel_main == "I":
            sel_I(student, name, kor_s, math_s, eng_s)
        elif sel_main == "S":
            sel_S(student)
        elif sel_main == "P":
            sel_P(student)
        elif sel_main == "U":
            sel_U(student)
        elif sel_main == "D":
            sel_D(student)
        elif sel_main == "Q":
            break
        else :
            print("다시 입력해 주세요.", end = "  ")
    return student
#################################################################################
#################################################################################
def sel_I(student, name, kor_s, math_s, eng_s):
    print("성적 입력란입니다.")
    name = ''
    point = 0
    i = 0
    score = {"name":"", "kor":"", "math":"", "eng":""}
    name = input("이름을 입력해 주세요 : " )
    #ins_score(kor_s, math_s, eng_s)
    while i < 4 :
        if i == 0 :
            sub = "국어"
            i = i  + 1
        elif i == 1 :
            sub = "수학"
            kor_s = point
            i = i  + 1
        elif i == 2 :
            sub = "영어"
            math_s = point
            i = i  + 1
        elif i == 3:
            eng_s = point
            i = i + 1
            break
        print('%s' % sub, "점수를 입력해 주세요.")
        point = input()
        if 0 <= int(point) <=100 :
            pass
        else:
            print("잘못 입력하셨습니다.")
            i = i-1
    score["name"] = name
    score["kor"] = kor_s
    score["math"] = math_s
    score["eng"] = eng_s
    student.append(score)
    print((len(student)-1), "번 학생이 저장 됐습니다.")
    return name, kor_s, math_s, eng_s, student

#################################################################################
#################################################################################
def ins_score(kor_s, math_s, eng_s) :
    i = 0
    point = 0
    kor_s = 0
    math_s = 0
    eng_s = 0
    while i < 4 :
        if i == 0 :
            sub = "국어"
            i = i  + 1
        elif i == 1 :
            sub = "수학"
            kor_s = point
            i = i  + 1
        elif i == 2 :
            sub = "영어"
            math_s = point
            i = i  + 1
        elif i == 3:
            eng_s = point
            i = i + 1
            break
        print('%s' % sub, "점수를 입력해 주세요.")
        point = input()
        if type(point) == "int" :
            if int(point) >= 0 and int(point) <= 100 :
                pass
            else :
                print("0 ~ 100의 숫자를 입력해 주세요.")
                i = i-1
        else :
            print("잘못입력하셨습니다.")
    return kor_s, math_s, eng_s
#################################################################################
#################################################################################
def sel_S(student):
    while True :
        print("""
과목별 점수 조회 화면입니다.
원하는 작업을 골라주세요
kor : 국어 점수 조회
math : 수학 점수 조회
eng : 영어 점수 조회
max : 최고 점수 조회
min : 최저 점수 조회
back : 뒤로 가기 """)
        sub_s = input()
        if sub_s in ("kor", "math", "eng") :
            sub_s2 = sub_s.replace("kor", "국어")
            sub_s2 = sub_s2.replace("math", "수학")
            sub_s2 = sub_s2.replace("eng", "영어")
            print('%s' % sub_s2, "과목입니다.")
            for i in range(len(student)) :
                print(student[i]["name"],"  ", student[i][sub_s], "점")
            break
        elif sub_s in ("max", "min") :
            comparison = []
            m_name = []
            while True :
                print ("""
어떤 과목을 조회할까요""")
                sub_s2 = input("""
kor : 국어점수
math : 수학점수
eng : 영어점수
""")
                if sub_s2 in ("kor", "math", "eng") :
                    for i in range(len(student)):
                        comparison.append(int(student[i][sub_s2]))

                    if sub_s == "max" :
                        a1 = max(comparison)
                    else :
                        a1 = min(comparison)
                    for i in range(len(student)):
                        if a1 == int(student[i][sub_s2]):
                            m_name.append(student[i]["name"])

                    sub_s2 = sub_s2.replace("kor", "국어 ")
                    sub_s2 = sub_s2.replace("math", "수학 ")
                    sub_s2 = sub_s2.replace("eng", "영어 ")
                    sub_s = sub_s.replace("max", "최고")
                    sub_s = sub_s.replace("min", "최저")
                    for i in range (len(m_name)):
                        print ("{} 득점자는".format(sub_s), m_name[i], "이고")
                    print("{} {}".format(sub_s2, sub_s), "점수는 ", a1, "점 입니다.")
                    break
                else :
                    print("다시 입력해 주세요.")
        elif sub_s in ("back") :
            break
        else :
            print("다시 입력해 주세요.")
#################################################################################
#################################################################################
def sel_P(student):
    stu_s = input("""
조회할 학생 이름을 입력해 주세요. :  """)
    r1 = 0
    for i in range(len(student)) :
        if student[i]["name"] == stu_s :
            print(student[i])
            r1 = r1+1
            break
    if r1 == 0:
        print("학생이 없습니다.")
#################################################################################
#################################################################################
def sel_U(student):
    while True :
        stu_u = input("""
    수정할 학생 이름을 입력해 주세요.
    취소를 원하시면 Q를 입력해 주세요 : """)
        if stu_u == "Q":
            break
        else :
            r1 = 0
            for i in range(len(student)) :
                if student[i]["name"] == stu_u :
                    r1 = r1+1
                    print (
        "%s" %stu_u,"의 정보입니다.",
        student[i])
                    while True :
                        stu_u2 = input(
            """수정할 과목을 입력해 주세요(국어, 수학, 영어, 취소)  """)
                        stu_u3 = stu_u2.replace("국어", "kor")
                        stu_u3 = stu_u3.replace("수학", "math")
                        stu_u3 = stu_u3.replace("영어", "eng")
                        # while True :
                        if stu_u3 in ("kor", "math", "eng"):
                            stu_u4 = input("""
        몇점으로 수정하시겠습니까  """)
                            student[i][stu_u3] = stu_u4
                            print("""
        {0}의 {1}점수가 {2}점으로 수정됐습니다.""".format(stu_u, stu_u2, stu_u4))
                            break
                        elif stu_u2 == "취소":
                            break
                        else :
                            print("잘못입력하셨습니다.")
            if r1 == 0:
                    print("다시 입력해 주세요")
            else :
                break
    return student
#################################################################################
#################################################################################
def sel_D(student):
    while True:
        r1 = 0
        stu_d = input("""
삭제할 학생 이름을 입력해 주세요.""")
        for i in range (len(student)):
            if stu_d == student[i]["name"]:
                del student[i]
                print("%s" %stu_d, "의 정보가 삭제됐습니다.")
                r1 = r1+1
                break
        if r1 == 0:
            print("학생 이름이 없습니다.")
        else : break
#################################################################################
#################################################################################
def load_cust(student, engine):
    with engine.connect() as conn:
        result = conn.execute("SELECT * FROM score")
        student = [dict(row) for row in result]
    return student

main()

##앞으로 구현해야 할것
##오라클 디벨로퍼랑 연결하기
##student list에 '반' 넣고 과목별, 개인별, 반별 평균, 표준편차 구해보기
##t분포,F분포 이용해서 검추정 및 회귀분석 이용해서 회귀분석 구현하기
##가능하다면 html 과 연결해서 html(f.e)-python-오라클(b.e)로 연결되게 만들기


import sqlite3
import csv

con = sqlite3.connect("./db.sqlite3") # 빈 .db파일 생성
cur = con.cursor()
cur.execute("create table books (id integer primary key autoincrement, book_name text, publisher text, author text, publication_date DATETIME, pages integer, isbn integer, description text, link text);")

# csv 파일 읽기
# 인코딩 문제 나오면 encoding = ''에 utf-8 > euc-kr > cp949 순서로 해봐라
with open('book_list.csv') as datas :
    records = csv.DictReader(datas)
    result = [ (w['book_name'], w['publisher'], w['author'], w['publication_date'], w['pages'], w['isbn'], w['description'], w['link']) for w in records]

# csv 파일 sqlite3 디비에 삽입
cur.executemany("insert into books(book_name, publisher, author, publication_date, pages, isbn, description, link) values(?, ?, ?, ?, ?, ?, ?, ?);", result)

con.commit()
con.close()


#dependencies
import csv
import pprint
rev_change={}

# read csv
with open('budget_data.csv', mode='r', newline='') as csv_file: #opens csv file
    csv_reader = csv.DictReader(csv_file) # create reader object
    total_rev =0 #set initial revenue to 0
    months=0 #set number of months to 0
    change_profit=0 #set change in profit to 0
    prev_line= 1154293 #Set to this because the first row is skipped. Maybe find a cleaner way to do this....

    #print(csv_reader.fieldnames) #prints field names

    for row in csv_reader: # total net amount of months
        months +=1
        total_rev += int(row['Revenue'])

        #line_num = data.index(line) # gives line number as index value
        change_profit += int(row['Revenue']) - int(prev_line)

        if row['Date'] not in rev_change.keys(): # if Date is not in dict of rev_change, create entry
            rev_change[row['Date']] =0

        if row['Date'] in rev_change:# if Date exists then add change in revenue
            rev_change[row['Date']] = int(row['Revenue'])- int(prev_line)

        prev_line = int(row['Revenue']) #sets prev_line valuefor the next row. MUST be at the end of for loop

    print('Financial Analysis')
    print('------------------------')
    maxInc='Maximum Increase in Revenue: ' + max(rev_change, key =rev_change.get) + ' (' + str(max(rev_change.values())) + ')' #max rev
    maxDec='Maximum Decrease in Revenue: ' + min(rev_change, key =rev_change.get) + ' (' + str(min(rev_change.values())) + ')' #min rev
    print('Total Months: ' + str(months))
    print('Total Revenue: $' + str(total_rev))
    print('AVG Monthly Change in Revenue: $' + str(round(change_profit/(months),2)))
    print(maxInc)
    print(maxDec)

with open('Results.txt','w') as txt_file: #create a new txt file and print results
    print(f'Total Months: ' + str(months), file=txt_file)
    print(f'Total Revenue: $' + str(total_rev), file=txt_file)
    print(f'AVG Monthly Change in Revenue: $' + str(round(change_profit/(months),2)), file=txt_file)
    print(str(maxInc), file=txt_file)
    print(str(maxDec), file=txt_file)


#5.4) Se ingresan números hasta que la diferencia entre dos números consecutivos se repita. La computadora muestra la cantidad de números ingresados.

diferencia = 0
diferenciaGuardada = 0
numeroGuardado = 0
contador = 0
Salida = True

while Salida:

    numeroIngresado = int(input("Ingresar un número hasta que su diferencia se repita con el consecutivo: "))
    diferencia = numeroIngresado - numeroGuardado

    if diferencia == diferenciaGuardada:
        Salida = False

    else:
        diferenciaGuardada = diferencia
        numeroGuardado = numeroIngresado

    contador += 1

print(f"La cantidad de números ingresados es: {contador}")


# -*- coding: utf-8 -*-
"""
Created on Thu Feb  9 10:08:28 2017

@author: Travis Kemper
@email: travis.kemper.w@gmail.com

"""

import numpy
from stl import mesh
import datetime

class Order:
    def __init__(self):
        self.date = datetime.datetime.now()
        self.parts = {}
        self.number = 0
        self.df = None

class Material:

    def __init__(self,name):
        self.name = name
        self.density = 0.001 #g/mm^3
        self.cost_g = 100.0

class Part:
    def __init__(self,name):

        self.name = name
        self.mesh = None
        self.properties = {}
        self.units = 'mm'
        self.qty = 1
        self.materials = {}
        self.notes = ""
        self.auto_orient = True
        self.cost = 0.0

    def read_mesh(self,stl_file):
        self.stl_file = stl_file
        self.mesh = mesh.Mesh.from_file(stl_file)

    def calc_props(self):

        volume, cog, inertia = self.mesh.get_mass_properties()
        self.properties['Volume'] = volume

        mesh_size = self.mesh.max_ -  self.mesh.min_

        self.properties['Size'] = mesh_size

        surf_areas = numpy.zeros(3)
        surf_areas[0] =  mesh_size[0]* mesh_size[1] # XY
        surf_areas[1] =  mesh_size[1]* mesh_size[2] # YZ
        surf_areas[2] =  mesh_size[2]* mesh_size[0] # XZ
        self.properties['SrufAreas'] = surf_areas #[ round(s,3) for s in surf_areas]

        # Find surface area and height based on given orientation
        self.properties['SrufArea'] = surf_areas[0]
        self.properties['Height'] =  mesh_size[2]

        if( self.auto_orient ):
            max_area_index = numpy.argmax(surf_areas)
            self.properties['SrufArea'] = surf_areas[max_area_index]

            if( max_area_index == 0 ):
                #area_id = 'XY'
                self.properties['Height'] = mesh_size[2]
                self.properties
            elif( max_area_index == 1 ):
                #area_id = 'YZ'
                self.properties['Height'] = mesh_size[0]
            elif( max_area_index == 2 ):
                #area_id = 'XZ'
                self.properties['Height'] = mesh_size[1]

    def calc_mass(self,material):

        self.properties['Mass'] = self.properties['Volume']*material.density


monthly_salary = float(input("Lūdzu, ievadiet savu mēnešalgu: "))
employment_years = int(input("Lūdzu, ievadiet savu darba stāžu uzņēmumā: "))
years_before_bonus = 2 # years before bonus is given
bonus_rate = 0.15 # 15% bonus rate

if employment_years <= years_before_bonus:
    bonus = 0
else:
    bonus = bonus_rate * monthly_salary * (employment_years - years_before_bonus)

total_salary = monthly_salary + bonus
# using :.2f to round to 2 decimal places but display only 2 decimal places
# data is not changed, only displayed
# 15 will be total width of the number including the decimal point and 2 decimal places
print(f"Tavs bonus ir € {bonus:15.2f} un kopējā alga ir € {total_salary:.2f}.")
# without rounding
print(f"Tavs bonus ir € {bonus} un kopējā alga ir € {total_salary}.")
# i could also round the data and then display it
bonus = round(bonus, 2)
total_salary = round(total_salary, 2)
print(f"Tavs bonus noapaļots ir € {bonus} un kopējā alga ir € {total_salary}.")


from trac.core import Component, implements
from bhsearch.api import IDocIndexPreprocessor, IndexFields

class SuggestionFields(IndexFields):
    SUMMARY = 'summary'
    BASKET = 'query_suggestion_basket'

class QuerySuggestionPreprocessor(Component):
    implements(IDocIndexPreprocessor)

    suggestion_fields = [
        IndexFields.NAME,
        IndexFields.CONTENT,
        SuggestionFields.SUMMARY,
    ]

    # IDocIndexPreprocessor methods
    def pre_process(self, doc):
        basket = u' '.join(doc.get(field, '')
                           for field in self.suggestion_fields)
        doc[SuggestionFields.BASKET] = basket


from tkinter import *
from tkinter import font
import tkinter.ttk
from io import BytesIO
from PIL import Image, ImageTk
import tkinter.messagebox
from Set_Parsing import *

class page1():
    def __init__(self,window):
        self.window = window
        self.img = PhotoImage(file="resource/BackGround_1.png")
        self.bg = Label(self.window,image=self.img)
        self.bg.place(x=0,y=0)
        self.bg.image = self.img
        self.fontstyle1 = font.Font(self.window, size=12, family='Consolas')
        self.fontstyle2 = font.Font(self.window, size=11, weight='bold', family='Consolas')
        self.Topfontstyle = font.Font(self.window, size=18, weight='bold', family='Consolas')
        self.set_Parsing = Set_Parsing()
        self.set_Parsing_od = []*4
        for i in range(4):
            self.set_Parsing_od.append(Set_Parsing())
        self.textbox = Text(self.window, width=40, height=8, font=self.fontstyle1)
        self.SearchYearEntryBox = Entry(self.window, font=self.fontstyle1, width=6)
        self.SearchDateEntryBox = Entry(self.window, font=self.fontstyle1, width=6)

    def InitTopText(self):
        self.img = PhotoImage(file = "resource/BackGround_1.png")
        self.bg_canvas = Canvas(self.window,width=1200,height=599)
        self.bg_canvas.create_image(0,0,image=self.img,anchor=NW)

    def InitSearchListBox(self):
        self.MovieList = [] * 10
        self.Rank_Label = [] * 10
        for i in range(10):
            self.MovieList.append(
                Button(self.window, font=self.fontstyle2, overrelief="solid", width=28, height=1, bg='black',fg="white",
                       command=lambda a=i: self.SearchBoxofficeInfo(self.MovieList[a]['text'])))
            self.MovieList[i].place(x=100, y=120 + i * 45)
            self.Rank_Label.append(Label(self.window, font=self.fontstyle2, text=str(i + 1) + ".", bg = "dark slate gray",fg="white"))
            self.Rank_Label[i].place(x=60, y=125 + i * 45)

    def InitSearchBox(self):
        self.SearchYearEntryBoxlabel = Label(self.window, font=self.fontstyle1, text="년도:", bg = "dark slate gray",fg="white")
        self.SearchYearEntryBoxlabel.place(x=225, y=50)
        self.SearchYearEntryBox.place(x=270, y=50)

        self.SearchDateEntryBoxlabel = Label(self.window, font=self.fontstyle1, text="월/일:", bg = "dark slate gray",fg="white")
        self.SearchDateEntryBoxlabel.place(x=345, y=50)
        self.SearchDateEntryBox.place(x=400, y=50)

        Search_Button_img = PhotoImage(file="resource/Button_Print_Box.png")
        self.SearchMovieListButton = Button(self.window, overrelief='solid',image=Search_Button_img ,
                                               command=self.SearchBoxofficeList,bg = "dark slate gray")
        self.SearchMovieListButton.place(x=500, y=45)
        self.SearchMovieListButton.image = Search_Button_img

        self.RadioVariety = tkinter.IntVar()
        self.DailySelectionButton = Radiobutton(self.window, value=1, text="일간",fg="white", bg = "dark slate gray",selectcolor="black", variable=self.RadioVariety,
                                                   command=self.ClearList)
        self.DailySelectionButton.place(x=90, y=50)
        self.WeeklySelectionButton = Radiobutton(self.window, value=2, text="주간",fg="white", bg = "dark slate gray",selectcolor="black", variable=self.RadioVariety,
                                                    command=self.ClearList)
        self.WeeklySelectionButton.place(x=150, y=50)

    def InitSearchlabel(self):
        self.Simage = Label(self.window, image='',bg = "dark slate gray")

        self.textbox.place(x=380,y=425)

    def InitsalesAccGraph(self):
        self.temp_name = ''
        self.salesAccGraph = Canvas(self.window,relief='sunken',bd=1,bg='white',width=300,height=250)
        self.salesAccGraph.place(x=825,y=100)
        self.salesChange_od = ['0']*4
        self.salesAccGraphlabel = []*5
        for i in range(5):
            self.salesAccGraphlabel.append(Label(self.window, font=self.fontstyle1,bg = "dark slate gray",fg="white", text=""))

        Graph_Button_img = PhotoImage(file="resource/Button_Graph.png")
        self.Draw_Graph_Button=Button(self.window,font=self.fontstyle1,image =Graph_Button_img,bg = "dark slate gray",\
                                      command=lambda n=self.temp_name:self.Draw_Graph(self.temp_name))
        self.Draw_Graph_Button.image = Graph_Button_img
        self.Draw_Graph_Button.place(x=824, y=375)
        self.Draw_Graph_Button['state'] = 'disabled'

    def ClearList(self):
        for i in range(10):
            self.MovieList[i].configure(text='')

    def ClearLabel(self):
        self.Simage.configure(image='')

    def SearchBoxofficeList(self):  # 입력한 날짜의 개봉한 박스오피스 출력
        self.set_Parsing.Movie_xml_request(self.SearchYearEntryBox.get() \
                               , self.SearchDateEntryBox.get() \
                               , self.RadioVariety.get())
        count = 0

        if self.set_Parsing.xml_status == 200:
            self.root = ET.fromstring(self.set_Parsing.xml_text)
            if self.RadioVariety.get() == 1:
                for child in self.root.find("dailyBoxOfficeList"):
                    self.MovieList[count].configure(text=child.find('movieNm').text)
                    count += 1
            else:
                for child in self.root.find("weeklyBoxOfficeList"):
                    self.MovieList[count].configure(text=child.find('movieNm').text)
                    count += 1
        self.Draw_Graph_Button['state'] = 'disabled'

    def SearchBoxofficeInfo(self, name):  # 입력한 박스오피스 정보 출력, 날짜가 입력되어야함
        self.set_Parsing.Naver_xml_request(name)
        self.textbox.delete("1.0", "end")
        self.ClearLabel()
        self.temp_name = name

        openDt = ''  # 개봉연도 저장 변수, 제대로된 포스터 이미지 찾기위함

        if self.set_Parsing.xml_status == 200:
            self.Nroot = ET.fromstring(self.set_Parsing.Nxml_text)

            if self.RadioVariety.get() == 1:
                for child in self.root.find("dailyBoxOfficeList"):
                    if child.find("movieNm").text == name:
                        openDt = child.find("openDt").text
                        self.CurrentsalesAcc = child.find("salesAcc").text
                        self.textbox.insert(CURRENT,"제목: "+child.find("movieNm").text+"\n")
                        self.textbox.insert(CURRENT, "순위: " + child.find("rank").text + "위\n")
                        self.textbox.insert(CURRENT, "개봉일: " + child.find("openDt").text + "\n")
                        self.textbox.insert(CURRENT, "누적관객수: " + child.find("audiAcc").text + "명\n")
                        self.textbox.insert(CURRENT, "누적매출액: " + child.find("salesAcc").text + "원\n")
                        break
            else:
                for child in self.root.find("weeklyBoxOfficeList"):
                    if child.find('movieNm').text == name:
                        self.textbox.insert(CURRENT, "제목: " + child.find("movieNm").text + "\n")
                        self.textbox.insert(CURRENT, "순위: " + child.find("rank").text + "위\n")
                        self.textbox.insert(CURRENT, "개봉일: " + child.find("openDt").text + "\n")
                        self.textbox.insert(CURRENT, "누적관객수: " + child.find("audiAcc").text + "명\n")
                        self.textbox.insert(CURRENT, "누적매출액: " + child.find("salesAcc").text + "원\n")
                        openDt = child.find("openDt").text
                        self.CurrentsalesAcc = child.find("salesAcc").text
                        break

            for child in self.Nroot.find('channel'):
                if child.text == None:
                    if child.find('pubDate').text <= openDt[0:4]:
                        image_url = child.find('image').text
                        with urllib.request.urlopen(image_url) as u:
                            raw_data = u.read()
                        image = Image.open(BytesIO(raw_data))
                        image = image.resize((220, 314))
                        movie_image = ImageTk.PhotoImage(image)
                        self.Simage.configure(image=movie_image)
                        self.Simage.image = movie_image
                        break
            self.Draw_Graph_Button['state'] = 'active'
            #_page4.textBox.insert(CURRENT,self.textbox.get("1.0","end"))

        self.Simage.place(x=380, y=100)

    def Draw_Graph(self,name):
        self.salesAccGraph.delete('all')
        for i in range(4):
            if i < 2:
                if len(str(int(self.SearchDateEntryBox.get()))) == 3:
                    self.set_Parsing_od[i].Movie_xml_request(self.SearchYearEntryBox.get() \
                                                                 , '0' + str(int(self.SearchDateEntryBox.get()) + (i - 2)) \
                                                                 , self.RadioVariety.get())
                else:
                    self.set_Parsing_od[i].Movie_xml_request(self.SearchYearEntryBox.get() \
                                                                 , str(int(self.SearchDateEntryBox.get()) + (i - 2)) \
                                                                 , self.RadioVariety.get())
            else:
                if len(str(int(self.SearchDateEntryBox.get()))) == 3:
                    self.set_Parsing_od[i].Movie_xml_request(self.SearchYearEntryBox.get() \
                                                                 , '0' + str(int(self.SearchDateEntryBox.get()) + (i - 1)) \
                                                                 , self.RadioVariety.get())
                else:
                    self.set_Parsing_od[i].Movie_xml_request(self.SearchYearEntryBox.get() \
                                                                 , str(int(self.SearchDateEntryBox.get()) + (i - 1)) \
                                                                 , self.RadioVariety.get())

        self.root_od = []

        for i in range(4):
            if self.set_Parsing_od[i].xml_status == 200:
                self.root_od.append(ET.fromstring(self.set_Parsing_od[i].xml_text))
                if self.RadioVariety.get() == 1:
                    for child in self.root_od[i].find("dailyBoxOfficeList"):
                        if child.find('movieNm').text == name:
                            self.salesChange_od[i] = child.find('salesChange').text
                            break
                else:
                    for child in self.root_od[i].find("weeklyBoxOfficeList"):
                        if child.find('movieNm').text == name:
                            self.salesChange_od[i] = child.find('salesChange').text
                            break
            else:
                self.salesChange_od[i] = '0'
            if i < 2:
                self.salesAccGraph.create_oval(10 + (70*i) - 5, 125-(float(self.salesChange_od[i])*1.2) - 5, \
                                            10 + (70*i)+ 5, 125-(float(self.salesChange_od[i])*1.2) + 5,fill='blue',outline = 'blue')
            else:
                self.salesAccGraph.create_oval(10 + (70 * (i+1)) - 5, 125 - (float(self.salesChange_od[i])*1.2) - 5, \
                                              10 + (70 * (i + 1)) + 5, 125 - (float(self.salesChange_od[i]) * 1.2) + 5,fill='blue',outline = 'blue')

        self.salesAccGraph.create_oval(10+140-5,125-5 ,10+140+5,125+5,fill='blue',outline = 'blue')
        self.salesAccGraph.create_line(10,125-float(self.salesChange_od[0])*1.2\
                                       ,10+70,125-float(self.salesChange_od[1])*1.2\
                                       ,10+140,125\
                                        ,10+210,125-float(self.salesChange_od[2])*1.2\
                                       ,10+280,125-float(self.salesChange_od[3])*1.2,width=2,fill='blue')
        for i in range(30):
            self.salesAccGraph.create_line(0+(i*10),125,5+(i*10),125)
        for i in range(5):
            self.salesAccGraphlabel[i].place(x=810 + (i * 70), y=350)
            if self.RadioVariety.get() == 1:
                if i < 2:
                    self.salesAccGraphlabel[i].configure(text=str(2-i)+"일전")
                elif i > 2:
                    self.salesAccGraphlabel[i].configure(text=str(i - 2)+"일후")
                else:
                    self.salesAccGraphlabel[i].configure(text='기준일')
            else:
                if i < 2:
                    self.salesAccGraphlabel[i].configure(text=str(2 - i) + "주전")
                elif i > 2:
                    self.salesAccGraphlabel[i].configure(text=str(i - 2) + "주후")
                else:
                    self.salesAccGraphlabel[i].configure(text='기준일')

    def Work_page(self):
        self.InitTopText()
        self.InitSearchListBox()
        self.InitSearchBox()
        self.InitSearchlabel()
        self.InitsalesAccGraph()


import binascii
import re
import os
import csv
import shutil
import argparse
from utils import *
import numpy as np
import csv

############################ To get All  Video Trunck info #######################################################
# Read info from cmd, and create relative folder
parser = argparse.ArgumentParser()
parser.add_argument('--input_file', type=str)
parser.add_argument('--save_tape', action='store_true')
args = parser.parse_args()

input_file = args.input_file
input_dir = os.path.dirname(input_file)

output_name = input_file.split('/')[-1].split('.')[0]+'.meta'
output_dir = os.path.join(input_dir, input_file.split('/')[-1].split('.')[0] +  '_audio')
if os.path.isdir(output_dir):
    shutil.rmtree(output_dir)
os.mkdir(output_dir)
os.mkdir(os.path.join(output_dir, 'clips'))
os.mkdir(os.path.join(output_dir, 'other_streams'))

cut_cmd='ffmpeg -i {} -c copy -vn -loglevel quiet "{}/Audio.mp4"'.format(
    input_file, output_dir
)
exit_code = os.system(cut_cmd)
if exit_code != 0:
    print('command failed:', cut_cmd)

print('Succeed in generating audio')

Audio =  os.path.join(output_dir, 'Audio.mp4')
# record the All Frames info, including I, B,P frames ...
cut_cmd = 'FFREPORT=file={}:level=56 ffmpeg -i {}  -f -segment_frames -reset_timestamps 1 -loglevel quiet'.format(
    os.path.join(output_dir, 'allFramesInfo.log'), Audio
    )
exit_code = os.system(cut_cmd)
if exit_code == 0:
    print('Faild in getting Frames info')
print('Success in getting allFramesInfo.log')

allFramesInfoPath = os.path.join(output_dir, 'allFramesInfo.log')

# To get IDR info by reading the log file, that the corresponding IDR sample number, IDR byteoffset

audioSize = [] #[size]

with open(allFramesInfoPath, 'r') as file:
    lines = file.read().splitlines()
    for row in lines:
        if "AVIndex stream 0" in row:
            # print(row)
            audioSize.append(int(row.split(',')[9].split(' ', 2)[2]))
            #c = int(row.split(',')[6].split(' ', 2)[2])
            #audioSize.append([b, c])

file.close()
print(audioSize)
print("****** auido size  overall")
x = 0
for i in  audioSize:
    x+=i
print(x)

############################ Audio Grouping #######################################################
targetSize = 4500000  #4.5MB
overlap = 780         #大约五秒？
cutPlan = []
overall = []
sum = 0
start = 0
i = 0
while(i < len(audioSize)):
    overlap = 80000    #大约五秒？
    sum = sum + audioSize[i]
    if (sum >= targetSize):
        overall.append(sum)
        cutPlan.append([start, i+1])
        sum = 0
        minusOffset = 0
        while(overlap > 0):
            overlap = overlap - audioSize[i + minusOffset]
            minusOffset = minusOffset + 1
        start = i + 1 - minusOffset
        i = start - 1
        # print(start)
    i = i + 1

if(start != len(audioSize) - 1):
    cutPlan.append([start])
cutPlan[0] = [cutPlan[0][1]]
print('##### cut plan ######')
print(cutPlan)
#[[0, 5], [4, 9], [8, 13], [12, 17], [16, 18]]
i = 0
while i < len(cutPlan):
    string = ",".join(str(x) for x in cutPlan[i])
    cut_cmd='ffmpeg -i {} -f segment -segment_frames {} -reset_timestamps 1 -c copy -loglevel quiet "{}/{}clip_%d.mp4"'.format(
            Audio, string, os.path.join(output_dir, 'clips'), i
        )
    exit_code = os.system(cut_cmd)
    if exit_code != 0:
        print('command failed:', cut_cmd)

    # for the middle
    if (i == 0) :
        clip_path1 = "{}/{}clip_{}.mp4".format(os.path.join(output_dir, 'clips'), i, 1)
        cut_cmd_1 = 'rm -f {}'.format(clip_path1)
        exit_code = os.system(cut_cmd_1)
        if exit_code != 0:
            print('command failed:', cut_cmd_1)

    elif (i > 0  and i < len(cutPlan)-1 ):
        clip_path1 = "{}/{}clip_{}.mp4".format(os.path.join(output_dir, 'clips'), i, 0)
        clip_path2 = "{}/{}clip_{}.mp4".format(os.path.join(output_dir, 'clips'),i, 2)
        cut_cmd_1 = 'rm -f {}'.format(clip_path1)
        cut_cmd_2 = 'rm -f {}'.format(clip_path2)
        exit_code = os.system(cut_cmd_1)
        if exit_code != 0:
            print('command failed:', cut_cmd_1)
        exit_code = os.system(cut_cmd_2)
        if exit_code != 0:
            print('command failed:', cut_cmd_2)
    else:
        clip_path1 = "{}/{}clip_{}.mp4".format(os.path.join(output_dir, 'clips'),i, 0)
        cut_cmd_1 = 'rm -f {}'.format(clip_path1)
        exit_code = os.system(cut_cmd_1)
        if exit_code != 0:
            print('command failed:', cut_cmd_1)

    i += 1

print('Succeed in partition videos base on IDR')


import logging
import re

from crawler.config.centres import CENTRE_DATA_SOURCE_RABBITMQ, get_centres_config
from crawler.constants import (
    CENTRE_KEY_LAB_ID_DEFAULT,
    RABBITMQ_CREATE_FEEDBACK_ORIGIN_PLATE,
    RABBITMQ_CREATE_FEEDBACK_ORIGIN_SAMPLE,
)
from crawler.exceptions import TransientRabbitError
from crawler.helpers.sample_data_helpers import normalise_plate_coordinate
from crawler.rabbit.messages.parsers.create_plate_message import CreatePlateError, ErrorType

LOGGER = logging.getLogger(__name__)

class CreatePlateValidator:
    def __init__(self, message, config):
        self._message = message
        self._config = config

        self._centres = None

    def validate(self):
        LOGGER.debug("Starting validation of create message.")

        self._set_centre_conf()
        self._validate_plate()
        self._validate_samples()

        LOGGER.debug("Validation finished.")
        self._message.log_error_count()

    @property
    def centres(self):
        if self._centres is None:
            try:
                self._centres = get_centres_config(self._config, CENTRE_DATA_SOURCE_RABBITMQ)
            except Exception:
                raise TransientRabbitError("Unable to reach MongoDB while getting centres config.")

        return self._centres

    def _set_centre_conf(self):
        """Find a centre from the list of those we're accepting RabbitMQ messages for and store the config for it."""
        lab_id_field = self._message.lab_id
        try:
            self._message.centre_config = next(
                (c for c in self.centres if c[CENTRE_KEY_LAB_ID_DEFAULT] == lab_id_field.value)
            )
        except StopIteration:
            self._message.add_error(
                CreatePlateError(
                    type=ErrorType.ValidationCentreNotConfigured,
                    origin=RABBITMQ_CREATE_FEEDBACK_ORIGIN_PLATE,
                    description=(
                        f"The lab ID provided '{lab_id_field.value}' "
                        "is not configured to receive messages via RabbitMQ."
                    ),
                    field=lab_id_field.name,
                )
            )

    def _validate_plate(self):
        """Perform validation of the plate field in the message values for sanity.
        This does not check that the message can be inserted into the relevant databases.
        """
        # Ensure that the plate barcode isn't an empty string.
        plate_barcode_field = self._message.plate_barcode
        if not plate_barcode_field.value:
            self._message.add_error(
                CreatePlateError(
                    type=ErrorType.ValidationUnpopulatedField,
                    origin=RABBITMQ_CREATE_FEEDBACK_ORIGIN_PLATE,
                    description=f"Value for field '{plate_barcode_field.name}' has not been populated.",
                    field=plate_barcode_field.name,
                )
            )

    def _validate_samples(self):
        """Perform validation of the samples array in the message.
        This does not check that the message can be inserted into the relevant databases.
        """
        if self._message.total_samples == 0:
            return

        sample_uuid_field_name = self._message.samples.value[0].sample_uuid.name
        for sample_uuid in self._message.duplicated_sample_values[sample_uuid_field_name]:
            self._message.add_error(
                CreatePlateError(
                    type=ErrorType.ValidationNonUniqueValue,
                    origin=RABBITMQ_CREATE_FEEDBACK_ORIGIN_SAMPLE,
                    description=f"Sample UUID {sample_uuid} exists more than once in the message.",
                    sample_uuid=sample_uuid,
                    field=sample_uuid_field_name,
                )
            )

        self._message.validated_samples = 0
        for sample in self._message.samples.value:
            if self._validate_sample(sample):
                self._message.validated_samples += 1

    def _validate_sample_field_populated(self, field, sample_uuid):
        if not field.value:
            self._message.add_error(
                CreatePlateError(
                    type=ErrorType.ValidationUnpopulatedField,
                    origin=RABBITMQ_CREATE_FEEDBACK_ORIGIN_SAMPLE,
                    description=f"Value for field '{field.name}' on sample '{sample_uuid}' has not been populated.",
                    sample_uuid=sample_uuid,
                    field=field.name,
                )
            )

            return False

        return True

    def _validate_sample_field_unique(self, field, sample_uuid, normalise_func=None):
        normalised_value = field.value
        if normalise_func is not None:
            normalised_value = normalise_func(normalised_value)

        if normalised_value in self._message.duplicated_sample_values[field.name]:
            self._message.add_error(
                CreatePlateError(
                    type=ErrorType.ValidationNonUniqueValue,
                    origin=RABBITMQ_CREATE_FEEDBACK_ORIGIN_SAMPLE,
                    description=(
                        f"Field '{field.name}' on sample '{sample_uuid}' contains the value '{field.value}' "
                        "which is used in more than one sample but should be unique."
                    ),
                    sample_uuid=sample_uuid,
                    field=field.name,
                )
            )

            return False

        return True

    def _validate_sample_field_matches_regex(self, regex, field, sample_uuid):
        if not regex.match(field.value):
            self._message.add_error(
                CreatePlateError(
                    type=ErrorType.ValidationInvalidFormatValue,
                    origin=RABBITMQ_CREATE_FEEDBACK_ORIGIN_SAMPLE,
                    description=(
                        f"Field '{field.name}' on sample '{sample_uuid}' contains the value '{field.value}' "
                        "which doesn't match the expected format for values in this field."
                    ),
                    sample_uuid=sample_uuid,
                    field=field.name,
                )
            )

            return False

        return True

    def _validate_sample_field_no_later_than(self, timestamp, field, sample_uuid):
        if field.value > timestamp:
            self._message.add_error(
                CreatePlateError(
                    type=ErrorType.ValidationOutOfRangeValue,
                    origin=RABBITMQ_CREATE_FEEDBACK_ORIGIN_SAMPLE,
                    description=(
                        f"Field '{field.name}' on sample '{sample_uuid}' contains the value '{field.value}' "
                        f"which is too recent and should be lower than '{timestamp}'."
                    ),
                    sample_uuid=sample_uuid,
                    field=field.name,
                )
            )

            return False

        return True

    def _validate_sample(self, sample):
        """Perform validation of complete and consistent data for a single sample in the message."""
        valid = True

        # Ensure the sample UUID is unique
        sample_uuid_field = sample.sample_uuid
        sample_uuid = sample_uuid_field.value
        if sample_uuid in self._message.duplicated_sample_values[sample_uuid_field.name]:
            valid = False

        # Validate root sample ID
        root_sample_id_field = sample.root_sample_id
        if not self._validate_sample_field_populated(
            root_sample_id_field, sample_uuid
        ) or not self._validate_sample_field_unique(root_sample_id_field, sample_uuid):
            valid = False

        # Validate RNA ID
        rna_id_field = sample.rna_id
        if not self._validate_sample_field_populated(
            rna_id_field, sample_uuid
        ) or not self._validate_sample_field_unique(rna_id_field, sample_uuid):
            valid = False

        # Validate COG UK ID
        cog_uk_id_field = sample.cog_uk_id
        if not self._validate_sample_field_populated(
            cog_uk_id_field, sample_uuid
        ) or not self._validate_sample_field_unique(cog_uk_id_field, sample_uuid):
            valid = False

        # Validate plate coordinates
        plate_coordinate_field = sample.plate_coordinate
        if not self._validate_sample_field_matches_regex(
            re.compile(r"^[A-H](?:0?[1-9]|1[0-2])$"),  # A1 - H12 or A01 padded format
            plate_coordinate_field,
            sample_uuid,
        ) or not self._validate_sample_field_unique(plate_coordinate_field, sample_uuid, normalise_plate_coordinate):
            valid = False

        # Validate tested date is not newer than the message create date
        message_create_date = self._message.message_create_date.value
        tested_date_field = sample.tested_date
        if not self._validate_sample_field_no_later_than(message_create_date, tested_date_field, sample_uuid):
            valid = False

        return valid


cals = []

with open('input.txt') as f:
    elf = []
    for l in f:
        x = l.strip()
        if x == "":
            cals.append(sum(elf))
            elf = []
        else:
            elf.append(int(x))

print(sorted(cals))
print(sum(sorted(cals)[-3:]))


import sys
from PyPDF2 import PdfFileWriter, PdfFileReader

pdf_name = sys.argv[1]
watermark_name = sys.argv[2]

def open_pdf(file_name):
    try:
        pdf = PdfFileReader(open(file_name, mode='rb'))
        return pdf
    except FileNotFoundError as e:
        print("Check the argument names:", e)
        sys.exit()

def write_pdf(output):
    with open("PDFS/watermarked.pdf", mode='wb') as file:
        output.write(file)
        print("Done.")

def make_watermark(pdf, watermark):
    try:
        input_pdf = open_pdf(pdf)
        wtr_pdf = open_pdf(watermark)
        wtr_page = wtr_pdf.getPage(0)

        output = PdfFileWriter()

        for i in range(input_pdf.getNumPages()):
            page = input_pdf.getPage(i)
            page.mergePage(wtr_page)
            output.addPage(page)
        return output
    except AttributeError:
        print("Check the argv names.")

if __name__ == "__main__":
    out = make_watermark(pdf_name, watermark_name)
    write_pdf(out)


import os, sys
import configparser

from . singleton import *

@Singleton
class GfxConfig(object):
    """Launcher configuration"""

    def __init__(self, config_filename=""):

        self.__error_log = []

        self._default_props()

        self.config_filename = ""

        # Find where our application dir is located
        app_dir = os.path.dirname(os.path.abspath(sys.argv[0]))

        config_alt_loc = []
        config_alt_loc.append("/etc/gfxlauncher.conf")
        config_alt_loc.append(os.path.join(app_dir, "../etc/gfxlauncher.conf"))
        config_alt_loc.append(os.path.join(app_dir, "../ondemand-dt/etc/gfxlauncher.conf"))
        config_alt_loc.append(os.path.join(app_dir, "etc/gfxlauncher.conf"))
        config_alt_loc.append("/sw/pkg/ondemand-dt/etc/gfxlauncher.conf")
        config_alt_loc.append("/pdc/software/tools/thinlinc/etc/gfxlauncher.conf")
        config_alt_loc.append("/sw/pkg/rviz/etc/gfxlauncher.conf")

        if config_filename == "":
            for config_loc in config_alt_loc:
                if os.path.isfile(os.path.expanduser(os.path.realpath(config_loc))):
                    self.config_filename = os.path.abspath(os.path.expanduser(config_loc))
                    break
        else:
            self.config_filename = config_filename

        if not self.parse_config_file():
            self.print_error("Couldn't parse configuration")
            self.is_ok = False
        else:
            self.is_ok = True

    def print_error(self, msg):
        """Print error message"""
        error_msg = "Error: %s" % msg
        print(error_msg)
        self.__error_log.append(error_msg)

    def clear_error_log(self):
        self.__error_log.clear()

    @property
    def errors(self):
        return '\n'.join(self.__error_log)

    def _default_props(self):
        """Assign default properties"""
        self.debug_mode = False
        self.script_dir = "/sw/pkg/rviz/sbin/run"
        self.default_part = "rviz"
        self.default_account = "rviz"
        self.grantfile = ""
        self.grantfile_base = ""
        self.grantfile_dir = ""
        self.grantfile_suffix = ""
        self.client_script_dir = "/home/bmjl/Development/gfxlauncher/scripts/client"

        self.applications_dir = "/home/bmjl/test-menu/share/applications"
        self.directories_dir = "/home/bmjl/test-menu/share/desktop-directories"
        self.menu_dir = "/home/bmjl/test-menu/etc/xdg/menus/applications-merged"
        self.menu_filename = "Lunarc-On-Demand.menu"

        self.applications_direct_dir = "/home/bmjl/test-menu/share/applications"
        self.directories_direct_dir = "/home/bmjl/test-menu/share/desktop-directories"
        self.menu_direct_dir = "/home/bmjl/test-menu/etc/xdg/menus/applications-merged"
        self.menu_direct_filename = "Lunarc-On-Demand-Direct.menu"

        self.menu_prefix = "LUNARC - "
        self.desktop_entry_prefix = "gfx-"

        self.help_url = ""
        self.browser_command = "firefox"

        self.vgl_path = "/sw/pkg/rviz/vgl/bin/latest"
        self.vgl_connect_template = '%s/vglconnect %s %s/%s'
        self.backend_node = "gfx0"
        self.simple_launch_template = 'gfxlaunch --vgl --title "%s" --partition %s --account %s --exclusive --tasks-per-node=-1 --cmd %s --simplified'
        self.adv_launch_template = 'gfxlaunch --vgl --title "%s" --partition %s --account %s --exclusive --cmd %s'
        self.submit_only_slurm_template = 'gfxlaunch --vgl --title "%s" --partition %s --account %s --only-submit --job=%s --simplified'
        self.direct_scripts = False
        self.feature_descriptions = {}
        self.partition_descriptions = {}
        self.only_submit = False
        self.feature_ignore = ""
        self.part_ignore = ""
        self.use_sacctmgr = True

        self.module_json_file = "/sw/pkg/rviz/share/modules.json"

        self.xfreerdp_path = "/sw/pkg/freerdp/2.0.0-rc4/bin"
        self.xfreerdp_cmdline = '%s /v:%s /u:$USER /d:ad.lunarc /sec:tls /cert-ignore /audio-mode:1 /gfx +gfx-progressive -bitmap-cache -offscreen-cache -glyph-cache +clipboard -themes -wallpaper /size:1280x1024 /dynamic-resolution /t:"LUNARC HPC Desktop Windows 10 (NVIDA V100)"'

        self.notebook_module = "Anaconda3"
        self.jupyterlab_module = "Anaconda3"
        self.jupyter_use_localhost = False
        self.conda_source_env = ""
        self.conda_use_env = ""

        self.part_groups = {}
        self.part_groups_defaults = {}

    def print_config(self):
        """Print configuration"""

        print("")
        print("-------------------------------")
        print("Graphics Launcher configuration")
        print("-------------------------------")

        print("")
        print("General settings")
        print("")
        print("script_dir = %s" % self.script_dir)
        print("client_script_dir = %s" % self.client_script_dir)
        print("only_submit = %s" % str(self.only_submit))
        print("modules_json_file = %s" % (self.module_json_file))
        print("help_url = %s" % self.help_url)

        print("")
        print("SLURM settings")
        print("")

        print("default_part = %s" % self.default_part)
        print("default_account = %s" % self.default_account)
        print("grantfile = %s" % self.grantfile)
        print("grantfile_base = %s" % self.grantfile)
        print("grantfile_dir = %s" % self.grantfile_dir)
        print("grantfile_suffix = %s" % self.grantfile_suffix)

        print("simple_launch_template = %s" % self.simple_launch_template)
        print("adv_launch_template = %s" % self.adv_launch_template)
        print("feature_ignore = %s" % self.feature_ignore)
        print("part_ignore = %s" % self.part_ignore)
        print("use_sacctmgr = %s" % self.use_sacctmgr)

        print("")
        print("Menu settings")
        print("")

        print("application_dir = %s" % self.applications_dir)
        print("directories_dir = %s" % self.directories_dir)
        print("menu_dir = %s" % self.menu_dir)
        print("menu_filename = %s" % self.menu_filename)

        print("application_direct_dir = %s" % self.applications_dir)
        print("directories_direct_dir = %s" % self.directories_dir)
        print("menu_direct_dir = %s" % self.menu_dir)
        print("menu_direct_filename = %s" % self.menu_filename)

        print("menu_prefix = '%s'" % self.menu_prefix)
        print("desktop_entry_prefix = %s" % self.desktop_entry_prefix)

        print("")
        print("VGL settings")
        print("")

        print("vgl_path = %s" % self.vgl_path)
        print("backend_node = %s" % self.backend_node)
        print("vgl_connect_template = %s" % self.vgl_connect_template)

        print("")
        print("XFreeRDP settings")
        print("")

        print("xfreerdp_path = %s" % self.xfreerdp_path)

        print("")
        print("Jupyter/JupyterLab settings")
        print("")

        print("notebook_module = %s" % self.notebook_module)
        print("jupyterlab_module = %s" % self.jupyterlab_module)
        print("browser_command = %s" % self.browser_command)
        print("jupyter_use_localhost = %s" % self.jupyter_use_localhost)
        print("conda_source_env = %s" % self.conda_source_env)
        print("conda_use_env = %s" % self.conda_use_env)

    def _config_get(self, config, section, option, default_value=""):
        """Safe config retrieval"""

        if config.has_option(section, option):
            return config.get(section, option)
        else:
            return default_value

    def _config_getboolean(self, config, section, option, default_value=False):
        """Safe config retrieval"""

        if config.has_option(section, option):
            return config.getboolean(section, option)
        else:
            return default_value

    def parse_config_file(self):
        """Parse configuration file"""

        if not os.path.isfile(self.config_filename):
            self.print_error("Configuration file %s not found" %
                        self.config_filename)
            return False

        print("Using configuration file : %s" % self.config_filename)

        config = configparser.RawConfigParser()
        config.read(self.config_filename)

        # Check for correct sections

        try:
            self.script_dir = self._config_get(config, "general", "script_dir")
            self.install_dir = self._config_get(config, "general", "install_dir")

            self.client_script_dir = self._config_get(
                config, "general", "client_script_dir")
            self.debug_mode = self._config_getboolean(
                config, "general", "debug_mode")
            self.only_submit = self._config_getboolean(
                config, "general", "only_submit")
            self.modules_json_file = self._config_get(
                config, "general", "modules_json_file")
            self.help_url = self._config_get(
                config, "general", "help_url").replace('"', '')
            self.browser_command = self._config_get(
                config, "general", "browser_command")

            self.default_part = self._config_get(
                config, "slurm", "default_part")
            self.default_account = self._config_get(
                config, "slurm", "default_account")
            self.grantfile = self._config_get(config, "slurm", "grantfile")
            self.grantfile_base = self._config_get(
                config, "slurm", "grantfile_base")
            self.grantfile_dir = self._config_get(
                config, "slurm", "grantfile_dir")
            self.grantfile_suffix = self._config_get(
                config, "slurm", "grantfile_suffix")
            self.feature_ignore = self._config_get(
                config, "slurm", "feature_ignore")
            self.part_ignore = self._config_get(config, "slurm", "part_ignore")

            self.simple_launch_template = self._config_get(
                config, "slurm", "simple_launch_template")
            self.adv_launch_template = self._config_get(
                config, "slurm", "adv_launch_template")
            self.submit_only_slurm_template = self._config_get(
                config, "slurm", "submit_only_slurm_template")
            self.use_sacctmgr = self._config_getboolean(config, "slurm", "use_sacctmgr", False)

            self.applications_dir = self._config_get(
                config, "menus", "applications_dir")
            self.directories_dir = self._config_get(
                config, "menus", "directories_dir")
            self.menu_dir = self._config_get(config, "menus", "menu_dir")
            self.menu_filename = self._config_get(
                config, "menus", "menu_filename")
            self.direct_scripts = self._config_getboolean(
                config, "menus", "direct_scripts")
            self.menu_prefix = self._config_get(config, "menus", "menu_prefix").replace('"', '')
            self.desktop_entry_prefix = self._config_get(config, "menus", "desktop_entry_prefix").replace('"', '')

            self.applications_direct_dir = self._config_get(
                config, "menus-direct", "applications_dir")
            self.directories_direct_dir = self._config_get(
                config, "menus-direct", "directories_dir")
            self.menu_direct_dir = self._config_get(config, "menus-direct", "menu_dir")
            self.menu_direct_filename = self._config_get(
                config, "menus-direct", "menu_filename")
            self.direct_scripts = self._config_getboolean(
                config, "menus-direct", "direct_scripts")

            self.vgl_path = self._config_get(config, "vgl", "vgl_path")
            self.backend_node = self._config_get(config, "vgl", "backend_node")
            self.vgl_connect_template = self._config_get(
                config, "vgl", "vglconnect_template")

            self.xfreerdp_path = self._config_get(
                config, "xfreerdp", "xfreerdp_path")

            self.notebook_module = self._config_get(
                config, "jupyter", "notebook_module")
            self.jupyterlab_module = self._config_get(
                config, "jupyter", "jupyterlab_module")
            self.conda_source_env = self._config_get(
                config, "jupyter", "conda_source_env")
            self.conda_use_env = self._config_get(
                config, "jupyter", "conda_use_env")

            self.jupyter_use_localhost = self._config_getboolean(config, "jupyter", "jupyter_use_localhost", False)

        except configparser.Error as e:
            self.print_error(e)
            return False

        # Check for feature descriptions

        try:
            slurm_options = config.options("slurm")
            for option in slurm_options:
                if option.find("feature_") != -1:
                    descr = self._config_get(config, "slurm", option)
                    feature = option.split("_")[1]
                    self.feature_descriptions[feature] = descr.strip('"')
        except configparser.Error as e:
            self.print_error(e)
            return False

        # Check for partition descriptions

        try:
            slurm_options = config.options("slurm")
            for option in slurm_options:
                if option.find("part_") != -1:
                    descr = self._config_get(config, "slurm", option)
                    partition = option.split("_")[1]
                    self.partition_descriptions[partition] = descr.strip('"')
        except configparser.Error as e:
            self.print_error(e)
            return False

        # Check for partition groups

        self.part_groups = {}
        self.part_groups_defaults = {}

        try:
            slurm_options = config.options("slurm")
            for option in slurm_options:
                if option.find("group_") != -1:
                    parts = self._config_get(config, "slurm", option)
                    if len(option.split("_"))==2:
                        group = option.split("_")[1].strip()
                        partitions = parts.split(",")
                        self.part_groups[group] = []
                        for part in partitions:
                            self.part_groups[group].append(part.strip())
                    elif len(option.split("_"))==3:
                        group = option.split("_")[1].strip()
                        directive = option.split("_")[2].split(" ")[0].strip()

                        tasks = 1
                        memory = -1
                        exclusive = False

                        if not group in self.part_groups_defaults:
                            self.part_groups_defaults[group] = {}

                        if directive == "tasks":
                            self.part_groups_defaults[group]["tasks"] = int(parts)
                        if directive == "memory":
                            self.part_groups_defaults[group]["memory"] = int(parts)
                        if directive == "exclusive":
                            if parts.strip() == "yes":
                                exclusive = True
                            else:
                                exclusive = False
                            self.part_groups_defaults[group]["exclusive"] = exclusive

        except configparser.Error as e:
            self.print_error(e)
            return False

        return True


from knowledge_base import KnowledgeBase
from fact import Fact

# Edit input knowledge, query and output path here
test_number = input().strip()
inp_file = 'test/' + test_number + '/knowledge.pl'
query_file = 'test/' + test_number + '/query.pl'
outp_file = 'test/' + test_number + '/answers.txt'

kb = KnowledgeBase()
with open(inp_file, 'r') as f_in:
   list_sentences = f_in.readlines()
   KnowledgeBase.declare(kb, list_sentences)

print('Done initialize knowledge base from {}.'.format(inp_file))

with open(query_file, 'r') as f_query:
   with open(outp_file, 'w') as f_out:
      for query_str in f_query.readlines():
         alpha = Fact.parse_fact(query_str)
         alpha_str = str(alpha) + '.'
         print(alpha_str)
         substs = set(kb.query(alpha))
         substs_str = ' ;\n'.join([str(subst) for subst in substs]) + '.\n'
         print(substs_str)
         f_out.write(alpha_str + '\n')
         f_out.write(substs_str + '\n')

print('Results of queries from {} are written to {}.'.format(query_file, outp_file))


from django.urls import path

from . import views
from .views import CategoryListAPIView, CategoryRetrieveAPIView, CategoryCreateAPIView, BookListAPIView,\
    BookDetailAPIView, BookCreateAPIView, ProductListAPIView, ProductRetrieveAPIView,ProductCreateAPIView, \
    ProductUpdateAPIView, CategoryUpdateAPIView, BookUpdateAPIView
from .views import *
urlpatterns = [
    path('category/list/', CategoryListAPIView.as_view(), name='category_list'),
    path('category/detail/<int:pk>/', CategoryRetrieveAPIView.as_view(), name='category_detail'),
    path('category/create/', CategoryCreateAPIView.as_view(), name='category_create'),
    path('category/update/<int:pk>/', CategoryUpdateAPIView.as_view(), name='category_update'),

    path('book/create/', BookCreateAPIView.as_view(), name='book_create'),
    path('book/list/', BookListAPIView.as_view(), name='book_list'),
    path('book/detail/<int:pk>/', BookDetailAPIView.as_view(), name='book_detail'),
    path('book/update/<int:pk>/', BookUpdateAPIView.as_view(), name='book_detail'),

    path('product/list/', ProductListAPIView.as_view(), name='product_list'),
    path('product/detail/<int:pk>/', ProductRetrieveAPIView.as_view(), name='product_detail'),
    path('product/create/', ProductCreateAPIView.as_view(), name='product_detail'),
    path('product/update/<int:pk>/', ProductUpdateAPIView.as_view(), name='product_detail'),

    path('show/data/', views.json_response, name='json_response'),
    path('show/data/2/', views.json_response2, name='json_response'),
]


'''4. Функция принимает предложение,
вычисляет какой буквы в этом предложении больше и возвращает эту букву
 и процент ее вхождения предложение. Например, на вход подается фраза
‘ Мама мыла Аллу, Алла мыла пупса’ вывод будет ‘а’ 25%
Обратите внимание - пробелы, знаки пунктуации не учитываются,
а регистр учитывается. Если имеется несколько букв с максимальным результатом
- выводим все такие буквы.'''

def count_chars(s: str) -> str:
    # Убираем все не буквенные символы из строки и переводим всю строку в нижний регистр
    s = ''.join(char for char in s if char.isalpha()).lower()

    # Считаем количество каждой буквы и находим максимальное значение
    char_count = {}
    max_val = 0
    for char in s:
        if char not in char_count:
            char_count[char] = 0
        char_count[char] += 1
        if char_count[char] > max_val:
            max_val = char_count[char]

    # Создаем список с буквами, которые встречаются максимальное количество раз
    max_chars = [char for char in char_count if char_count[char] == max_val]

    # Вычисляем процент вхождения каждой из максимальных букв
    percent = max_val / len(s) * 100

    # Форматируем вывод
    result_str = ' '.join([f'{char} {percent:.2f}%' for char in max_chars])

    return result_str

s = 'Мама мыла Аллу, Алла мыла пупса'

result = count_chars(s)
print(result)  # Output: а 25.00%


import os
import glob
import numpy as np
import yaml
import h5py
from pathlib import Path
from yaml.loader import SafeLoader

class H5pyHandler:
    main_dirname = "datasets"
    model_dirname = "model"
    control_dirname = "control"

    def __init__(self, with_control: bool, mpi_comm = None, append = False):
        self.with_control = with_control
        self.mpi_comm = mpi_comm
        self.append = append

        if self.append:
            self.current_idx = self._get_data_idx() + 1
        else:
            self.current_idx = 0

    def main_hdf5(self, attr: dict):
        assert not self.append
        rank = self.mpi_comm.Get_rank()
        dir_path = Path(os.path.dirname(__file__)) / self.main_dirname
        if rank == 0:
            self.makedir(dir_path)
        self.mpi_comm.Barrier()

        with h5py.File(dir_path / 'main.hdf5', "w", driver='mpio', comm=self.mpi_comm) as h5f:
            for key, value in attr.items():
                h5f.attrs[key] = value
            h5f.create_group("input_arrays")
            h5f.create_group("output_arrays")
            if self.with_control:
                h5f.create_group("control_arrays")

    def append_main(self, data: np.ndarray, group_name: str):
        size = self.mpi_comm.Get_size()
        rank = self.mpi_comm.Get_rank()
        self.assert_grpname(group_name)

        dir_path = Path(os.path.dirname(__file__)) / self.main_dirname
        with h5py.File(dir_path / "main.hdf5", 'a', driver='mpio', comm=self.mpi_comm) as f:
            dset = []
            grp = f[group_name]
            for i in range(self.current_idx, size + self.current_idx):
                dset.append(grp.create_dataset(f'{group_name[:-1]}{i}', shape=data.shape, dtype=data.dtype))
            dset[rank][:] = data

    def merge_data(self, group_name: str):
        self.assert_grpname(group_name)
        dir_path = Path(os.path.dirname(__file__)) / self.main_dirname
        with h5py.File(dir_path / "main.hdf5", 'r') as f:
            arrays = f[group_name].values()
            data = []
            for arr in arrays:
                data.append(arr[:])
        return np.vstack(data)

    def model_hdf5(self, attr: dict, A: np.ndarray, Ur: np.ndarray, B: np.ndarray = None):
        if B is not None:
            assert self.with_control
        dir_path = Path(os.path.dirname(__file__)) / self.model_dirname
        self.makedir(dir_path)

        with h5py.File(dir_path / 'model.hdf5', "w") as f:
            for key, value in attr.items():
                f.attrs[key] = value
            f.create_dataset("a_operator_red", data=A)
            f.create_dataset("pod_modes", data= Ur)
            if self.with_control:
                f.create_dataset("b_operator_red", data=B)

    def control_hdf5(self, attr: dict, C: np.ndarray):
        dir_path = Path(os.path.dirname(__file__)) / self.control_dirname
        self.makedir(dir_path)
        with h5py.File(dir_path / 'control.hdf5', "w") as f:
            for key, value in attr.items():
                f.attrs[key] = value
            f.create_dataset("control_sequence", data=C)

    def import_model(self):
        dir_path = Path(os.path.dirname(__file__)) / self.model_dirname
        with h5py.File(dir_path /'model.hdf5', 'r') as f:
            Atilde = f['a_operator_red'][:]
            if self.with_control:
                Btilde = f['b_operator_red'][:]
            Ur = f['pod_modes'][:]
        if self.with_control:
            return Atilde, Btilde, Ur
        else:
            return Atilde, Ur

    def import_control(self):
        dir_path = Path(os.path.dirname(__file__)) / self.control_dirname
        with h5py.File(dir_path/ 'control.hdf5', 'r') as f:
            C = f['control_sequence'][:]
        return C

    def _get_data_idx(self):
        dir_path = Path(os.path.dirname(__file__)) / self.main_dirname
        with h5py.File(dir_path / "main.hdf5", 'r') as f:
            input_arrays = f["input_arrays"]
            last_array_key = list(input_arrays.keys())[-1][-1]
        return int(last_array_key)

    def assert_grpname(self, group_name):
        assert group_name in ["input_arrays", "output_arrays", "control_arrays"]
        if group_name == "control_arrays":
            assert self.with_control

    @staticmethod
    def makedir(dir_path: Path):
        if not os.path.exists(dir_path):
            os.makedirs(dir_path)

def load_yml(path):
    with open(path, "r") as ymlfile:
        cfg = yaml.load(ymlfile, Loader=SafeLoader)
    return cfg

def import_model(dir_name: str):
    with h5py.File(Path(dir_name) /'model.hdf5', 'r') as f:
        Atilde = f['a_operator_red'][()]
        Btilde = f['b_operator_red'][()]
        Ur = f['pod_modes'][()]
    return Atilde, Btilde, Ur

def import_control(dir_name: str):
    with h5py.File(Path(dir_name) / 'control.hdf5', 'r') as f:
        C = f['control_sequence'][()]
    return C

def merge_data(dataset_path, control=True):
    with h5py.File(dataset_path, 'r') as f:
        input_arrays = f["input_arrays"].items()
        output_arrays = f["output_arrays"].items()
        if control:
            control_arrays = f["control_arrays"].items()
            arrays_list = [input_arrays, output_arrays, control_arrays]
        else:
            arrays_list = [input_arrays, output_arrays]
        X = []
        Y = []
        if control:
            C = []

        for t in zip(*arrays_list):
            input_key, input_dataset = t[0]
            output_key, output_dataset = t[1]
            if control:
                control_key, control_dataset = t[2]
            assert input_key[-1] == output_key[-1]

            if control:
                output_key[-1] == control_key[-1]

            input_arr = input_dataset[()]
            output_arr = output_dataset[()]
            if control:
                control_arr = control_dataset[()]

            X.append(input_arr)
            Y.append(output_arr)

            if control:
                C.append(control_arr)
    if control:
        return np.vstack(X), np.vstack(Y), np.vstack(C)
    else:
        return np.vstack(X), np.vstack(Y)

def main_hdf5(dir_path: Path, attr: dict, comm, control = True):
    hdf5_path = dir_path / 'main.hdf5'

    with h5py.File(hdf5_path, "w", driver='mpio', comm=comm) as h5f:
        for key, value in attr.items():
            h5f.attrs[key] = value
        h5f.create_group("input_arrays")
        h5f.create_group("output_arrays")
        if control:
            h5f.create_group("control_arrays")

def model_hdf5(dir_name: str, attr: dict, A: np.ndarray, B: np.ndarray, Ur: np.ndarray):
    dir_path = Path(dir_name)
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)
    hdf5_path = dir_path / 'model.hdf5'
    with h5py.File(hdf5_path, "w") as h5f:
        for key, value in attr.items():
            h5f.attrs[key] = value
        h5f.create_dataset("a_operator_red", data=A)
        h5f.create_dataset("b_operator_red", data=B)
        h5f.create_dataset("pod_modes", data= Ur)

def control_hdf5(dir_name: str, attr: dict, C: np.ndarray):
    dir_path = Path(dir_name)
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)
    hdf5_path = dir_path / 'control.hdf5'
    with h5py.File(hdf5_path, "w") as h5f:
        for key, value in attr.items():
            h5f.attrs[key] = value
        h5f.create_dataset("control_sequence", data=C)

def clear_slurm():
    if not os.path.exists("slurm"):
        os.makedirs("slurm")
    files = glob.glob("slurm/*")
    for f in files:
        os.remove(f)

func_dict = {
    0: lambda x: np.sin(np.pi*x)
}


import os
import argparse

# Parse arguments
parser = argparse.ArgumentParser()
parser.add_argument('-n', '--num_run', help='The total number of experiments.', required=True)
parser.add_argument('-f', '--yaml_file', help='The configuration file.', required=True)
parser.add_argument('-g', '--gpu_id', help='The gpu index.', default=0, required=False)
args = parser.parse_args()

for i in range(int(args.num_run)):
    print(f"Start carrying out experiment {i+1}/{args.num_run}...")
    exec_str = f"CUDA_VISIBLE_DEVICES={args.gpu_id} python run.py -f {args.yaml_file} --multi_run_mode"
    os.system(exec_str)
    print("\n\n")


from django.conf.urls.defaults import patterns, include, url

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from resume.views import index, work,projects,skills,courses,home
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'personal_site.views.home', name='home'),
    # url(r'^personal_site/', include('personal_site.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$',index),
    url(r'^work/', work),
    url(r'^home/',home),
    url(r'^courses/',courses),
    url(r'^projects/',projects),
    url(r'^skills/',skills),
    # static

)
urlpatterns += staticfiles_urlpatterns()


import time
import subprocess
import RPi.GPIO as GPIO
from datetime import datetime
from Apps.Wiegand.wiegandEngine import WiegandEngine
from Apps.SIM800L.sim800l import Sim800l
from Apps.Camara.camara import Camara
from Apps.IntruderDetecter.intruderDetecter import IntruderDetecter
from Apps.service import Service

from Apps.Hilos.wiegandThread import WiegandThread
from Apps.Hilos.camaraThread import CamaraThread
from Apps.Hilos.sim800Thread import Sim800Thread

#Pruebas
import threading
try:
    import thread
except ImportError:
    import _thread as thread

def quitFunction(fn_name):
    thread.interrupt_main() # raises KeyboardInterrupt

def exitAfter():
    def outer(fn):
        def inner(*args, **kwargs):
            timeout = float(args[1])
            timer = threading.Timer(timeout, quitFunction, args=[fn.__name__])
            timer.start()
            try:
                result = fn(*args, **kwargs)
            finally:
                timer.cancel()
            return result
        return inner
    return outer

@exitAfter()
def readCard(wiegand, timeout):
    try:
        wiegand.read_card()
    except KeyboardInterrupt:
        print('Time Out')

def _modulesInit():
    wiegand = WiegandEngine(bitMaximo=26)
    sim = Sim800l()
    camara = Camara()
    IntruderD = IntruderDetecter()
    service = Service()
    return wiegand, sim, camara, IntruderD, service

def sistemRestart():
    GPIO.cleanup()
    time.sleep(0.3)
    wiegand, sim, camara, IntruderD, service = _modulesInit()
    return  wiegand, sim, camara, IntruderD, service

def _run(wiegand, sim, camara, intruderD, service):
    while(True):
        try:
            try:
                recognitionTime = 3.0
                intruderD.enable_interrupt()
                print("Esperando Ingreso...")
                while( True ):
                    if(intruderD.areThereIntruders):
                        time.sleep(0.3)
                        # Consulta a la base de datos
                        configutation = service.getConfiguration()
                        systemState = configutation.to_dict()['estadodelsistema']
                        resolution = configutation.to_dict()['resolucioncamara']
                        waitingTime = configutation.to_dict()['tiempodeespera']
                        print("Data Service: ", systemState, resolution, waitingTime)
                        if( systemState ): # si el sistema está encendido
                            intruderD.disable_interrupt()
                            intruderD.togglesLamp()
                            while(intruderD.areThereIntruders):
                                date = datetime.now()
                                # Hilo para la camara
                                camaraModules = [ camara, resolution, date, waitingTime ]
                                myCamaraThread = CamaraThread("camaraThread", camaraModules)
                                myCamaraThread.start()
                                #Lectura de Wiegand
                                readCard(wiegand, waitingTime)
                                # Intruders Validation
                                userValidate, user = service.wiegandIdValidate(str(wiegand.id))
                                if( wiegand.id != 0 and userValidate):
                                    service.createRegister("Ingreso Seguro [OK]", str(user.id), date)
                                    wiegand.id = 0
                                else:
                                    service.undefinedRegister("Intruso en la Zona [WARNING]", user, date)
                                   # Hilo para el Sim800L
                                    phones = service.getPhones()
                                    simModules = [ service, sim, phones]
                                    mySimThread = Sim800Thread("simThread", simModules)
                                    mySimThread.start()
                                    mySimThread.join()

                                myCamaraThread.join()
                                if(myCamaraThread.is_alive()):
                                    subprocess.call(['kill', '-9', '{}'.format(myCamaraThread.pid)])
                                try:
                                    intruderD.thereArentIntruders()
                                    intruderD.enable_interrupt()
                                    print("Validando...")
                                    time.sleep(recognitionTime)
                                    print("Esperando Ingreso...")
                                except RuntimeError:
                                    pass
                                if( intruderD.areThereIntruders ):
                                    intruderD.disable_interrupt()
                            intruderD.togglesLamp()
                        else:
                            try:
                                print("El sistema esta apagado, Ingrese al apartado de configuracion  de la aplicacion para encenderlo.")
                                intruderD.thereArentIntruders()
                            except RuntimeError:
                               wiegand, sim, camara, intruderD, service = sistemRestart()
            except google.api_core.exceptions.Unknown:
                wiegand, sim, camara, intruderD, service = sistemRestart()
        except NameError:
            wiegand, sim, camara, IntruderD, service = sistemRestart()

if __name__ == '__main__':
    wiegand, sim, camara, intruderD, service = _modulesInit()
    _run(wiegand, sim, camara, intruderD, service)

# 3408 en 80


import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-10,9,20)
y = x**3
z = x**2

# fig,axs = plt.subplot()
""" figure = plt.figure()

axes_cube = figure.add_axes([0.1,0.1,0.8,0.8])

axes_cube.plot(x,y,"o-b")
axes_cube.set_xlabel("X Axis")
axes_cube.set_ylabel("Y Axis")
axes_cube.set_title("Cube")

axes_squere = figure.add_axes([0.15,0.6,0.25,0.25])

axes_squere.plot(x,z,"o-r")
axes_squere.set_xlabel("X Axis")
axes_squere.set_ylabel("Y Axis")
axes_squere.set_title("Squere") """

""" figure = plt.figure()

axes = figure.add_axes([0,0,1,1])

axes.plot(x,z, label="Squere")
axes.plot(x,y, label="Cube")
axes.legend(loc=4)
 """

fig,axes = plt.subplots(nrows=2,ncols=1, figsize=(8,8))
axes[0].plot(x,y)
axes[0].set_title("Cube")

axes[1].plot(x,z)
axes[1].set_title("Squere")

plt.tight_layout()
fig.savefig("figure1.pdf")

plt.show()


import time

def get_mode():
    ans = input("分単位もしくは秒単位どちらで計測しますか?(y or n)")
    if ans == "y":
        return True
    elif ans == "n":
        return False

def get_time(mode):
    while True:
        if mode:
            n = input("設定したい時間を入力してください(分):")
        else:
            n = input("設定したい時間を入力してください(秒):")
        if n.isdigit():
            break
        else:
            print("時間を入力してください\n")
    return n

def main():
    print("タイマーを起動しました")

    # 1分以上かどうか
    mode = get_mode()
    # 計測時間の受け取り
    target_time = float(get_time(mode))
    #計測開始時間の取得
    start_time = time.time()

    if mode:
        target_time *= 60
    tmp = int(float(target_time) - time.time() + start_time)
    tmp2 = tmp + 1
    while True:
        if time.time() - start_time > int(target_time):
            print("設定した時間が経過しました")
            break
        elif tmp != int(float(target_time) - time.time() + start_time) - 0.2 or tmp != int(float(target_time) - time.time() + start_time) + 0.2:
            if tmp != tmp2:
                tmp2 = tmp
                if mode:
                    #if (tmp + 1) / 60 != 0:
                    if (tmp + 1) % 60 > 9:
                        print(str(int((tmp + 1) / 60)) + "分" + str((tmp + 1) % 60) + "秒")
                    else:
                        print(str(int((tmp + 1) / 60)) + "分0" + str((tmp + 1) % 60) + "秒")
                else:
                    if tmp + 1 > 9:
                        print(tmp + 1)
                    else:
                        print("0" + str(tmp + 1))
        tmp = int(float(target_time) - time.time() + start_time)

if __name__ == '__main__':
    main()


import numpy as np

num_bin = 10

def naive_bayes(data_train, data_test):
    prob_cond_x = [0, 0, 0, 0]

    # Calcolo la probabilità a priori del training-set
    prob_priori = calcola_prob_priori(data_train)

    # Calcolo la probabilità condizionata
    for i in range(len(data_test[0]) - 1):
        prob_cond_x[i] = calcola_prob_condizionata(data_train, i)

    classificazione = list(np.ones(len(data_test)))
    # Classificazione del testing-set
    for j in range(len(data_test)):
        classificazione[j] = classificatore(data_train, data_test[j], prob_priori, prob_cond_x)

    return classificazione

# Calcolo le probabilità a priori
def calcola_prob_priori(dataset):
    ultima_colonna = list(zip(*dataset))[-1]

    num_setosa = 0
    num_versicolor = 0
    num_verginica = 0

    for i in range(len(ultima_colonna)):

        if ultima_colonna[i] == "Iris-setosa":
            num_setosa += 1

        elif ultima_colonna[i] == "Iris-versicolor":
            num_versicolor += 1

        else:
            num_verginica += 1

    prob_setosa = num_setosa / len(ultima_colonna)
    prob_versicolor = num_versicolor / len(ultima_colonna)
    prob_verginica = num_verginica / len(ultima_colonna)

    return [prob_setosa, prob_versicolor, prob_verginica]

# Calcolo le probabilità condizionate
def calcola_prob_condizionata(dataset, position):
    bin_x = count_bin(dataset, position)
    prob_cond_x = []

    for j in range(num_bin):
        prob_cond_x.append([0, 0, 0])

    for i in range(len(bin_x)):
        sommariga = bin_x[i][0] + bin_x[i][1] + bin_x[i][2]
        for j in range(0, 3):
            if sommariga != 0:
                prob_cond_x[i][j] = bin_x[i][j] / sommariga
            else:
                prob_cond_x[i][j] = 0

    return prob_cond_x

def count_bin(dataset, position):
    bin_x = []

    for j in range(num_bin):
        bin_x.append([0, 0, 0])

    x = list(zip(*dataset))[position]
    x = [float(i) for i in x]
    min_x = min(x)
    max_x = max(x)
    grandezza_bin = (max_x - min_x) / num_bin

    size_data = len(dataset[0]) - 1

    for i in range(len(dataset)):
        start_bin = min_x
        for j in range(1, num_bin + 1):
            end_bin = min_x + grandezza_bin * j

            if (j < num_bin) & (float(dataset[i][position]) >= start_bin) & (float(dataset[i][position]) < end_bin):
                bin_x = increase_bin(dataset[i][size_data], bin_x, j - 1)
            elif (float(dataset[i][position]) >= start_bin) & (float(dataset[i][position]) <= end_bin):
                bin_x = increase_bin(dataset[i][size_data], bin_x, j - 1)

            start_bin = end_bin

    return bin_x

# Conta il numero di occorrenze dei target nel training-set
def increase_bin(target_train, bin_x, i):
    if target_train == "Iris-setosa":
        bin_x[i][0] += 1
    elif target_train == "Iris-versicolor":
        bin_x[i][1] += 1
    else:
        bin_x[i][2] += 1

    return bin_x

# Trova in quale BIN si trova l'attributo dell'istanza in classificazione
# Restituisce l'indice del BIN in cui si trova l'attributo, altrimenti None
def trova_bin(dataset_train, position, attributo):
    x = list(zip(*dataset_train))[position]
    x = [float(i) for i in x]
    min_x = min(x)
    max_x = max(x)
    grandezza_bin = (max_x - min_x) / num_bin

    for i in range(len(dataset_train)):
        start_bin = min_x
        for j in range(1, num_bin + 1):
            end_bin = min_x + grandezza_bin * j

            if (j < num_bin) & (float(attributo) >= start_bin) & (float(attributo) < end_bin):
                return j - 1
            elif (float(attributo) >= start_bin) & (float(attributo) <= end_bin):
                return j - 1

            start_bin = end_bin

    return None

# Classifica l'attributo x
def classificatore(dataset_train, attributo, prob_priori, prob_condizionate):
    indice = list()
    # numero di attributi nel dataset
    size_data = len(dataset_train[0]) - 1

    for x in range(size_data):
        indice.append(0)

    # Inizializzo le probabilità iniziali a posteriori a 1
    prob_post_setosa = 1
    prob_post_versicolor = 1
    prob_post_virginica = 1

    # Calcolo le probabilità a posteriori
    for i in range(size_data):
        indice[i] = trova_bin(dataset_train, i, attributo[i])
        # Controllo se l'attributo rientra in un BIN
        if indice[i] is not None:
            prob_post_setosa = prob_condizionate[i][indice[i]][0] * prob_post_setosa
            prob_post_versicolor = prob_condizionate[i][indice[i]][1] * prob_post_versicolor
            prob_post_virginica = prob_condizionate[i][indice[i]][2] * prob_post_virginica

    prob_setosa = round(prob_priori[0] * prob_post_setosa, 3)
    prob_versicolor = round(prob_priori[1] * prob_post_versicolor, 3)
    prob_virginica = round(prob_priori[2] * prob_post_virginica, 3)

    # Lista delle probabilità a posteriori del singolo attributo
    lista_prob = [prob_setosa, prob_versicolor, prob_virginica]

    # Restituisco il Max delle probabilità a posteriori dell'attributo ed il suo indice
    # return max(lista_prob), get_label(lista_prob.index(max(lista_prob)))

    # Restituisce l'etichetta con la probabilità massima
    return get_label(lista_prob.index(max(lista_prob)))

# Restituisce l'etichetta
def get_label(position):
    if position == 0:
        return "Iris-setosa"
    elif position == 1:
        return "Iris-versicolor"
    else:
        return "Iris-virginica"

# Calcolo l'accuratezza
def calcola_accuratezza(classificazione, data_test):
    x = list(zip(*data_test))[-1]
    classe = np.ones(len(x))
    for i in range(len(x)):
        if x[i] == "Iris-setosa":
            classe[i] = 0
        elif x[i] == "Iris-versicolor":
            classe[i] = 1
        else:
            classe[i] = 2

    tp = 0
    fp = 0

    for i in range(len(classe)):
        if classificazione[i][1] == classe[i]:
            tp += 1
        else:
            fp += 1

    accurancy = tp / len(data_test)

    return accurancy


#! python3
# -*- coding:utf-8 -*-

__author__ = "yoyo"

import os.path as path

def get_lines(data_dir, filename):
  filepath = path.join(data_dir, filename)
  f = open(filepath, encoding='utf-8')
  contents = f.readlines()
  f.close()
  return contents
  # open file an get the content

def extract_by_label(label, label_num, contents):
  data = []
  for content in contents:
    line = content.split("\t")
    if len(line) > 1:
      labels = line[1].split("|")
      if len(labels) > label_num:
        if label in labels[label_num - 1].strip("\n"):
          data.append(content)
  return data
# specify the label and the number of label(3 types of label in the data)

def write_file(filename, data, symbol=""):
  if type(symbol) == str:
    f = open(filename, "w")
    f.write(symbol.join(data))
    f.close()
  else:
    print("Not a usable joint symbol")
# write file, by specify the joint symbol

if __name__ == "__main__":

  data_dir = "/Users/Yoyo/Desktop/Graduation/ML_test/dataset/device-detection-database"
  filename = "traindata.txt"
  label = "iOS 8.0"
  label_num = 2
  headers = get_lines(data_dir, filename)
  data = extract_by_label(label, 2, headers)
  write_file(path.join(data_dir, label + ".txt"), data)


import os, shutil
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image

import torch
from torch.utils.data import Dataset, DataLoader

# from monai.config import print_config
from monai.transforms import \
    Compose, LoadImage, AddChannel, ScaleIntensity, ToTensor, RandRotate, RandFlip, RandZoom

from monai.networks.nets import densenet121
from monai.metrics import compute_roc_auc

IN = '/mnt/in'
OUT = '/mnt/out'
data_dir = os.path.join(IN)

on_platform = False # Kubernetes platform
if on_platform:
    IN = '/mnt/inputdata/MedNIST'
    OUT = '/mnt/output'
    data_dir = os.path.join(IN)
num_class = 6

# Read image filenames from the dataset folders
image_files = [os.path.join(data_dir,x) for x in os.listdir(os.path.join(data_dir))]
label_key = {0: 'AbdomenCT', 1: 'BreastMRI', 2: 'CXR', 3: 'ChestCT', 4: 'Hand', 5: 'HeadCT'}

# Define MONAI transforms, Dataset and Dataloader to pre-process data
val_transforms = Compose([
    LoadImage(image_only=True),
    AddChannel(),
    ScaleIntensity(),
    ToTensor()
])

class MedNISTDataset(Dataset):
    def __init__(self, image_files, transforms):
        self.image_files = image_files
        self.transforms = transforms
    def __len__(self):
        return len(self.image_files)
    def __getitem__(self, index):
        return self.transforms(self.image_files[index])

test_ds = MedNISTDataset(image_files, val_transforms)
test_loader = DataLoader(test_ds, batch_size=100, num_workers=5)

# Define network and optimizer
device = torch.device("cpu") #CPU
# device = torch.device("cuda:0") #GPU
model = densenet121(
    spatial_dims=2,
    in_channels=1,
    out_channels=num_class
).to(device)
loss_function = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), 1e-5)
epoch_num = 1
val_interval = 1

# model should be in memory and this step is really maybe only necessary during test run
model.load_state_dict(torch.load(os.path.join('best_metric_model.pth')))
model.eval()

y_pred = list()
# This is scoring territory as well
with torch.no_grad():
    data = 0
    for test_data in test_loader:
        print(f'data: {data}'); data += 1;
        test_images = test_data.to(device)
        pred = model(test_images).argmax(dim=1)
        for i in range(len(pred)):
            y_pred.append(pred[i].item())

with open(os.path.join(OUT,'classification_results.csv'), 'w') as f:
    f.write(f'file,class\n')

with open(os.path.join(OUT,'classification_results.csv'), 'a') as f:
    for i,image in enumerate(image_files):
        f.write(f'{image},{label_key[y_pred[i]]}\n')

# Copy model to output
src="best_metric_model.pth"
dest=OUT
shutil.copyfile(src, os.path.join(dest,src))


'''
Created on Mar 8, 2011

@author: joel
'''
import numpy as np

def intersect(linepoint, linedir, planepoint, planedirs):
    ''' Determine where the line given by linepoint + \mu * linedir intersects the plane given by
    planepoint + \lambda planedirs, where \mu \in R and \lambda \in R^n, where n is the dimension of the plane

    Returns (\lambda, \mu) '''

    M = np.vstack((planedirs, -linedir))
    if np.linalg.det(M) == 0: return (None, np.inf)
    P = linepoint - planepoint
    x = np.linalg.solve(M.transpose(), P.transpose()).ravel()
    return (x[:-1], x[-1])

def reflect(linedir, planedirs):
    ''' Reflect linedir in the plane spanned by planedirs'''
    Q, R = np.linalg.qr(np.vstack((planedirs, linedir)).transpose())
    r = R[:,-1] # the final column of R gives the coefficients of linedir in the columns of Q
    r[-1]*=-1 # the final column of Q is orthogonal to the plane.  Lets reverse the direction
    return np.dot(Q,r) # et voila.

class HomogenousTrace(object):
    ''' Knows how to trace through one element assuming homogenous material data'''

    def __init__(self, mesh, nonreflecting):
        self.mesh = mesh
        self.reflectingfaces = mesh.faceentities != [None]
        for e in nonreflecting:
            self.reflectingfaces[mesh.faceentities == e] = False
        self.neighbourface = mesh._connectivity * np.arange(1, mesh.nfaces+1, dtype=int) - 1

    def trace(self, face, point, direction):
        ''' Given an input face, a point on the face and a direction trace a path through the relevant element

        Returns: (e, f, p, d) where:
            e is the element that was traced through,
            f is the next input face
            p is the next point
            d is the next direction'''

        e = self.mesh.ftoe[face]
        fs = self.mesh.etof[e]

        for f in fs:
            if f==face: continue
            dirs = self.mesh.directions[f]
            planedirs = dirs[1:self.mesh.dim]
            l, m = intersect(point, direction, dirs[0], planedirs)
            if l is not None and (l > 0).all() and sum(l) <= 1 and m > 0: # assumes that the face is a simplex
                p = point + m * direction
                if self.reflectingfaces[f]:
                    direction = reflect(direction, planedirs)
                else:
                    f = self.neighbourface[f]
                return (e,f,p,direction)

#        print "Failed to find face to trace ",face,point,direction,e
        return None


import numpy as np

def most_voted(order_labels, k):

    labels, counts = np.unique(order_labels, return_counts=True)
    return labels[np.argmax(counts)]

def modified_plurality(order_labels, k):
    intersection = True
    while intersection:
        labels, counts = np.unique(order_labels, return_counts=True)
        intersection = number_intersections(counts)
        order_labels = order_labels[:-1]
    return labels[np.argmax(counts)]

def borda_count(order_labels, k):
    labels, counts = np.unique(order_labels, return_counts=True)
    votes = np.zeros(len(counts))
    for i in range(len(order_labels)):
        index = np.where(labels == order_labels[i])[0][0]
        votes[index] = votes[index] + (k-i)

    return labels[np.argmax(votes)]

def number_intersections(counts):
    max_value_counts = max(counts)
    intersection = 0
    for ci in counts:
        if ci == max_value_counts:
            intersection = intersection + 1
    if intersection > 1:
        bol_intersection = True
    else:
        bol_intersection = False

    return bol_intersection


#!/usr/bin/env python2
import time
import ConfigParser
import logging.config

from includes.HlstatsInvitationSource import HlstatsInvitationSource
from includes.SteamGroupInviter import SteamGroupInviter

def main():
    logging.config.fileConfig('logging.conf')
    logger = logging.getLogger()

    config = ConfigParser.RawConfigParser()
    config.read('inviter.conf')

    inviter = SteamGroupInviter(**dict(config.items('inviter')))
    invite_candidates = HlstatsInvitationSource(config.get('inviter', 'target_group_id'),
                                                dict(config.items('hlststats_connection')),
                                                **dict(config.items('hlststats_candidates')))
    errors_count = 0
    invitations_sent = 0
    for candidate in invite_candidates:
        try:
            inviter.invite(str(candidate))
            candidate.invited()
            logger.info('%s invited', candidate)
            time.sleep(config.getfloat('limits', 'pause_between_invitations'))
        except Exception as e:
            candidate.failed(str(e))
            logger.exception('Unable to invite %s due to exception `%s`', candidate, e)
            errors_count += 1
            if errors_count >= config.getint('limits', 'max_errors_per_run'):
                logger.warning('Max errors limit is reached')
                break

        invitations_sent += 1
        if invitations_sent >= config.getint('limits', 'max_invitations_per_run'):
            logger.info('Max invitations limit is reached')
            break
    logger.info('Results: %d invitations sent, %d errors', invitations_sent, errors_count)

if __name__ == '__main__':
    main()