# -*- coding: utf-8 -*-
# @Author  : lileilei
# @File    : views.py
# @Time    : 2017/12/7 12:19
from flask import  Blueprint
from  flask import  redirect,request,render_template,url_for,flash,session,abort,jsonify,make_response
from flask.views import MethodView
from app import  db
from app.models import *
from app.form import  *
from flask.views import MethodView,View
from flask_login import current_user,login_required,login_user,logout_user
from app.common.decorators import admin_required,permission_required
from app import loginManager
from app.common.dict_com import comp_dict,dict_par
import  json,time,os
from app.common.send_email import send_emails
from app.common.py_Html import createHtml
from app.test_case.Test_case import ApiTestCase
from app import  scheduler
from app.common.Dingtalk import send_ding
def addtask(id):#定时任务执行的时候所用的函数
    in_id=int(id)
    task=Task.query.filter_by(id=in_id).first()
    starttime = datetime.datetime.now()
    star = time.time()
    day = time.strftime("%Y%m%d%H%M", time.localtime(time.time()))
    basedir = os.path.abspath(os.path.dirname(__file__))
    file_dir = os.path.join(basedir, 'upload')
    file = os.path.join(file_dir, (day + '.log'))
    if os.path.exists(file) is False:
        os.system('touch %s' % file)
    filepath = os.path.join(file_dir, (day + '.html'))
    if os.path.exists(filepath) is False:
        os.system(r'touch %s' % filepath)
    projecct_list = []
    model_list = []
    Interface_name_list = []
    Interface_url_list = []
    Interface_meth_list = []
    Interface_pase_list = []
    Interface_assert_list = []
    Interface_headers_list = []
    id_list = []
    for task_yongli in task.interface.all():
        id_list.append(task_yongli.id)
        projecct_list.append(task_yongli.projects)
        model_list.append(task_yongli.models)
        Interface_url_list.append(task_yongli.Interface_url)
        Interface_name_list.append(task_yongli.Interface_name)
        Interface_meth_list.append(task_yongli.Interface_meth)
        Interface_pase_list.append(task_yongli.Interface_pase)
        Interface_assert_list.append(task_yongli.Interface_assert)
        Interface_headers_list.append(task_yongli.Interface_headers)
    apitest = ApiTestCase(Interface_url_list, Interface_meth_list, Interface_pase_list, Interface_assert_list, file,
                          Interface_headers_list)
    result_toal, result_pass, result_fail, relusts, bask_list = apitest.testapi()
    endtime = datetime.datetime.now()
    end = time.time()
    createHtml(titles=u'接口测试报告', filepath=filepath, starttime=starttime, endtime=endtime, passge=result_pass,
               fail=result_fail, id=id_list, name=projecct_list, headers=Interface_headers_list,
               coneent=Interface_url_list, url=Interface_meth_list, meth=Interface_pase_list,
               yuqi=Interface_assert_list, json=bask_list, relusts=relusts)
    hour = end - star
    user_id = User.query.filter_by(role_id=2).first().id
    new_reust = TestResult(Test_user_id=user_id, test_num=result_toal, pass_num=result_pass, fail_num=result_fail,
                           test_time=starttime, hour_time=hour, test_rep=(day + '.html'), test_log=(day + '.log'))
    db.session.add(new_reust)
    db.session.commit()
    send_ding(content="%s定时任务执行完毕，测试时间：%s，\\n 通过用例：%s，失败用例：%s，\\n,详情见测试平台测试报告！" % (
        task.taskname, starttime, result_pass, result_fail))
@loginManager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))
def get_pro_mo():
    projects=Project.query.all()
    model=Model.query.all()
    return  projects,model
task = Blueprint('task', __name__)
class TestforTaskView(MethodView):#为测试任务添加测试用例
    @login_required
    def get(self,id):
        procjet = Project.query.all()
        task_one=Task.query.filter_by(id=id).first()
        return  render_template('add/addtestyongfortask.html', task_one=task_one, procjets=procjet)
    @login_required
    def post(self,id):
        procjet = Project.query.all()
        task_one = Task.query.filter_by(id=id).first()
        proc_test=request.form.get('project')
        if proc_test =='':
            flash(u'不能不添加测试项目！')
            return render_template('add/addtestyongfortask.html', task_one=task_one, procjets=procjet)
        test_yongli=request.form.getlist('testyongli')
        if test_yongli=='':
            flash(u'亲你见过只有测试项目没有测试用例的测试任务吗！')
            return render_template('add/addtestyongfortask.html', task_one=task_one, procjets=procjet)
        for oldtask in task_one.interface.all():
            task_one.interface.remove(oldtask)
        task_one.prject=Project.query.filter_by(project_name=proc_test).first().id
        for yongli in test_yongli:
            task_one.interface.append(InterfaceTest.query.filter_by(id=yongli).first())
            db.session.add(task_one)
        try:
            db.session.commit()
            flash(u'任务更新用例成功')
            return  redirect(url_for('home.timingtask'))
        except:
            flash(u'任务更新用例失败')
            return redirect(url_for('home.timingtask'))
class StartTaskView(MethodView):#开始定时任务
    @login_required
    def get(self,id):
        task=Task.query.filter_by(id=id).first()
        next = request.headers.get('Referer')
        if len(task.interface.all())<=1:
            flash(u'定时任务执行过程的测试用例为多用例，请你谅解')
            return  redirect(next or url_for('home.timingtask'))
        try:
            scheduler.add_job(func=addtask, id=str(id), args=str(id),trigger=eval(task.taskstart),replace_existing=True)
            task.yunxing_status=u'启动'
            db.session.commit()
            flash(u'定时任务启动成功！')
            return  redirect(next or url_for('home.timingtask'))
        except Exception as e:
            flash(u'定时任务启动失败！请检查任务的各项内容各项内容是否正常')
            return redirect(next or url_for('home.timingtask'))
class ZantingtaskView(MethodView):#暂停定时任务
    @login_required
    def get(self,id):
        next = request.headers.get('Referer')
        task = Task.query.filter_by(id=id).first()
        try:
            scheduler.pause_job(str(id))
            task.yunxing_status = u'暂停'
            db.session.commit()
            flash(u'定时任务暂停成功！')
            return redirect(next or url_for('home.timingtask'))
        except:
            task.yunxing_status = u'创建'
            db.session.commit()
            flash(u'定时任务暂停失败！已经为您初始化')
            return redirect(next or url_for('home.timingtask'))
class HuifutaskView(MethodView):#回复定时任务
    @login_required
    def get(self,id):
        task = Task.query.filter_by(id=id).first()
        next = request.headers.get('Referer')
        try:
            scheduler.resume_job(str(id))
            task.yunxing_status=u'启动'
            db.session.commit()
            flash(u'定时任务恢复成功！')
            return redirect(next or url_for('home.timingtask'))
        except:
            task.yunxing_status = u'创建'
            db.session.commit()
            flash(u'定时任务恢复失败！已经为您初始化')
            return redirect(next or url_for('home.timingtask'))
class YichuTaskView(MethodView):#移除定时任务
    @login_required
    def get(self,id):
        next = request.headers.get('Referer')
        task = Task.query.filter_by(id=id).first()
        try:
            scheduler.delete_job(str(id))
            task.yunxing_status=u'关闭'
            db.session.commit()
            flash(u'定时任务移除成功！')
            return redirect(next or url_for('home.timingtask'))
        except:
            task.yunxing_status = u'创建'
            db.session.commit()
            flash(u'定时任务移除失败！已经为您初始化')
            return redirect(next or url_for('home.timingtask'))
class AddtimingtaskView(MethodView):
    @login_required
    def get(self):
        return  render_template('add/addtimingtasks.html')
    @login_required
    def post(self):
        taskname=request.form['taskname']
        tinmingtime=request.form['time']
        to_email_data=request.form['to_email']
        cao_email=request.form['cao_email']
        weihu=request.form['weihu']
        if taskname =='':
            flash(u'任务名不能为空！')
            return render_template('add/addtimingtasks.html')
        if tinmingtime =='':
            flash(u'任务执行时间不能为空！')
            return render_template('add/addtimingtasks.html')
        if to_email_data=='':
            flash(u'发送给谁邮件不能为空！')
            return render_template('add/addtimingtasks.html')
        if weihu=='':
            flash(u'维护人邮件不能为空！')
            return render_template('add/addtimingtasks.html')
        taskname_is = Task.query.filter_by(taskname=taskname).first()
        if taskname_is:
            flash(u'任务已经存在请重新填写！')
            return render_template('add/addtimingtasks.html')
        new_task=Task(taskname=taskname,taskstart=tinmingtime,taskrepor_to=to_email_data,taskrepor_cao=cao_email,task_make_email=weihu,
                      makeuser=current_user.id)
        db.session.add(new_task)
        try:
            db.session.commit()
            flash(u'添加定时任务成功')
            return  redirect(url_for('home.timingtask'))
        except Exception as e:
            db.session.rollback()
            flash(u'添加过程貌似异常艰难！')
            return redirect(url_for('home.addtimingtasks'))
class Editmingtaskview(MethodView):
    @login_required
    def get(self,id):
        task_one=Task.query.filter_by(id=id).first()
        procjet=Project.query.all()
        if not task_one:
            flash(u'你编辑的不存在')
            return  redirect(url_for('home.timingtask'))
        return  render_template('edit/Edittimingtasks.html', task_one=task_one, porjects=procjet)
    def post(self,id):
        task_one = Task.query.filter_by(id=id).first()
        procjet = Project.query.all()
        taskname = request.form['taskname']
        tinmingtime = request.form['time']
        to_email_data = request.form['to_email']
        cao_email = request.form['cao_email']
        weihu = request.form['weihu']
        if taskname =='':
            flash(u'任务名不能为空！')
            return render_template('add/addtimingtasks.html')
        if tinmingtime =='':
            flash(u'任务执行时间不能为空！')
            return render_template('add/addtimingtasks.html')
        if to_email_data=='':
            flash(u'发送给谁邮件不能为空！')
            return render_template('add/addtimingtasks.html')
        if weihu=='':
            flash(u'维护人邮件不能为空！')
            return render_template('add/addtimingtasks.html')
        task_one.taskname=taskname
        task_one.taskrepor_to=to_email_data
        task_one.taskrepor_cao=cao_email
        task_one.task_make_email=weihu
        task_one.makeuser=current_user.id
        try:
            db.session.commit()
            flash(u'编辑成功')
            return  redirect(url_for('home.timingtask'))
        except:
            db.session.rollback()
            flash(u'编辑出现问题！')
            return redirect(url_for('home.timingtask'))
class DeteleTaskViee(MethodView):
    def get(self,id):
        next = request.headers.get('Referer')
        task_one = Task.query.filter_by(id=id).first()
        if not task_one:
            flash(u'你删除的不存在')
            return redirect(next or url_for('home.timingtask'))
        if task_one.status==True:
            flash(u'已经删除')
            return redirect(next or url_for('home.timingtask'))
        task_one.status=True
        try:
            db.session.commit()
            flash(u'删除任务成功')
            return redirect(next or url_for('home.timingtask'))
        except:
            db.session.rollback()
            flash(u'删除任务休息了')
            return redirect(next or url_for('home.timingtask'))


#GUI for setting of experimental parameters in DLS GUI

import sys
try:
    from Tkinter import *
except ImportError:
    from tkinter import *

try:
    import ttk
    py3 = False
except ImportError:
    import tkinter.ttk as ttk
    py3 = True

def vp_start_gui():
    '''Starting point when module is the main routine.'''
    global val, w, root
    root = Tk()
    top = OptionWindow(root)
    root.mainloop()

def create_New_OptionWindow(root, mode = 'normal'):
    '''Starting point when module is imported by another program.'''
    global w, w_win, rt
    rt = root
    w = Toplevel (root)
    top = OptionWindow (w,mode)
    Tk.wait_window(w) #This is critical to letting the updated GUI parameters be returned
    return (w, top)

def destroy_OptionWindow():
    global w
    w.destroy()
    w = None

class OptionWindow:
    def __init__(self, top=None,mode = 'normal'):
        '''This class configures and populates the toplevel window.
           top is the toplevel containing window.'''
        _bgcolor = '#d9d9d9'  # X11 color: 'gray85'
        _fgcolor = '#000000'  # X11 color: 'black'
        _compcolor = '#d9d9d9' # X11 color: 'gray85'
        _ana1color = '#d9d9d9' # X11 color: 'gray85'
        _ana2color = '#d9d9d9' # X11 color: 'gray85'
        font10 = "-family {Segoe UI} -size 12 -weight normal -slant "  \
            "roman -underline 0 -overstrike 0"
        font9 = "-family {Courier New} -size 12 -weight normal -slant "  \
            "roman -underline 0 -overstrike 0"

        top.geometry("350x300+154+102")
        top.title("Experiment Parameters")
        top.configure(background="#d9d9d9")
        top.configure(highlightbackground="#d9d9d9")
        top.configure(highlightcolor="black")

        #Key Quantities We Want to Determine
        self.newData = "Yes"
        self.acqDur = 300
        self.maxNumTrials=1
        self.correlations = [1,1,1,1] #correlation pairs to compute and/or bin counts

        #Popup menu and label for Acquisition Duration
        self.Label1 = Label(top)
        self.Label1.place(relx=0.01, rely=0.02, height=51, width=154)
        self.Label1.configure(activebackground="#f9f9f9")
        self.Label1.configure(activeforeground="black")
        self.Label1.configure(background="#d9d9d9")
        self.Label1.configure(disabledforeground="#a3a3a3")
        self.Label1.configure(font=font10)
        self.Label1.configure(foreground="#000000")
        self.Label1.configure(highlightbackground="#d9d9d9")
        self.Label1.configure(highlightcolor="black")
        self.Label1.configure(text='''Acquisition Time (s)''')

        self.timeVar = StringVar(top)
        self.timeVar.set(str(self.acqDur)) # default value
        self.acqTimes = OptionMenu(top, self.timeVar,"10","30","100","300","1000")
        self.acqTimes.configure(activebackground="#f9f9f9")
        self.acqTimes.configure(activeforeground="black")
        self.acqTimes.configure(background="#d9d9d9")
        self.acqTimes.configure(state = mode)
        self.acqTimes.configure(font=font10,justify=CENTER)
        self.acqTimes.pack()
        self.acqTimes.place(relx=0.10, rely=0.17,height=41, width=80)

        #entry and label for Number oF Trials
        self.Label2 = Label(top)
        self.Label2.place(relx=0.47, rely=0.02, height=51, width=184)
        self.Label2.configure(activebackground="#f9f9f9")
        self.Label2.configure(activeforeground="black")
        self.Label2.configure(background="#d9d9d9")
        self.Label2.configure(disabledforeground="#a3a3a3")
        self.Label2.configure(font=font10)
        self.Label2.configure(foreground="#000000")
        self.Label2.configure(highlightbackground="#d9d9d9")
        self.Label2.configure(highlightcolor="black")
        self.Label2.configure(text='''Num. Trials''')

        #Entry
        self.maxTrialStr = StringVar(top)
        self.maxTrials = Entry(top)
        self.maxTrials.place(relx=0.60, rely=0.20,height=30, relwidth=0.25)
        self.maxTrials.configure(background="white")
        self.maxTrials.configure(validate = "focus")
        self.maxTrials.configure(disabledforeground="#a3a3a3")
        self.maxTrials.configure(font=font10, justify = CENTER)
        self.maxTrials.configure(foreground="#000000")
        self.maxTrials.configure(highlightbackground="#d9d9d9")
        self.maxTrials.configure(highlightcolor="black")
        self.maxTrials.configure(insertbackground="black")
        self.maxTrials.configure(selectbackground="#c4c4c4")
        self.maxTrials.configure(selectforeground="black")
        self.maxTrials.configure(textvariable=self.maxTrialStr)
        self.maxTrials.bind("<FocusOut>",self.validateNumTrials)
        self.maxTrialStr.set(str(1))

        #Label for correlations
        self.Label3 = Label(top)
        self.Label3.place(relx=0.22, rely=0.35, height=51, width=184)
        self.Label3.configure(activebackground="#f9f9f9")
        self.Label3.configure(activeforeground="black")
        self.Label3.configure(background="#d9d9d9")
        self.Label3.configure(disabledforeground="#a3a3a3")
        self.Label3.configure(font=font10)
        self.Label3.configure(foreground="#000000")
        self.Label3.configure(highlightbackground="#d9d9d9")
        self.Label3.configure(highlightcolor="black")
        self.Label3.configure(text='''Correlations to Compute''')

        #Correlations To Compute
        self.Ch1ACFVar = IntVar()
        self.Ch1ACFVar.set(1)
        self.Ch1xCh1 = Checkbutton(top,text = 'Ch1 ACF')
        self.Ch1xCh1.configure(activebackground="#f9f9f9")
        self.Ch1xCh1.configure(activeforeground="black")
        self.Ch1xCh1.configure(background="#f9f9f9")
        self.Ch1xCh1.configure(disabledforeground="#a3a3a3")
        self.Ch1xCh1.configure(font=font10)
        self.Ch1xCh1.configure(foreground="#000000")
        self.Ch1xCh1.configure(highlightbackground="#d9d9d9")
        self.Ch1xCh1.configure(highlightcolor="black")
        self.Ch1xCh1.configure(variable = self.Ch1ACFVar)
        self.Ch1xCh1.pack()
        self.Ch1xCh1.place(relx=0.15, rely=0.50,height=30, relwidth=0.30)

        self.Ch1xCh2Var = IntVar()
        self.Ch1xCh2Var.set(1)
        self.Ch1xCh2 = Checkbutton(top,text = 'Ch1 x Ch2')
        self.Ch1xCh2.configure(activebackground="#f9f9f9")
        self.Ch1xCh2.configure(activeforeground="black")
        self.Ch1xCh2.configure(background="#f9f9f9")
        self.Ch1xCh2.configure(disabledforeground="#a3a3a3")
        self.Ch1xCh2.configure(font=font10)
        self.Ch1xCh2.configure(foreground="#000000")
        self.Ch1xCh2.configure(highlightbackground="#d9d9d9")
        self.Ch1xCh2.configure(highlightcolor="black")
        self.Ch1xCh2.configure(variable = self.Ch1xCh2Var)
        self.Ch1xCh2.pack()
        self.Ch1xCh2.place(relx=0.55, rely=0.50,height=30, relwidth=0.30)

        self.Ch2xCh1Var = IntVar()
        self.Ch2xCh1Var.set(1)
        self.Ch2xCh1 = Checkbutton(top,text = 'Ch2 x Ch1')
        self.Ch2xCh1.configure(activebackground="#f9f9f9")
        self.Ch2xCh1.configure(activeforeground="black")
        self.Ch2xCh1.configure(background="#f9f9f9")
        self.Ch2xCh1.configure(disabledforeground="#a3a3a3")
        self.Ch2xCh1.configure(font=font10)
        self.Ch2xCh1.configure(foreground="#000000")
        self.Ch2xCh1.configure(highlightbackground="#d9d9d9")
        self.Ch2xCh1.configure(highlightcolor="black")
        self.Ch2xCh1.configure(variable = self.Ch2xCh1Var)
        self.Ch2xCh1.pack()
        self.Ch2xCh1.place(relx=0.15, rely=0.60,height=30, relwidth=0.3)

        self.Ch2ACFVar = IntVar()
        self.Ch2ACFVar.set(1)
        self.Ch2xCh2 = Checkbutton(top,text = 'Ch2 ACF')
        self.Ch2xCh2.configure(activebackground="#f9f9f9")
        self.Ch2xCh2.configure(activeforeground="black")
        self.Ch2xCh2.configure(background="#f9f9f9")
        self.Ch2xCh2.configure(disabledforeground="#a3a3a3")
        self.Ch2xCh2.configure(font=font10)
        self.Ch2xCh2.configure(foreground="#000000")
        self.Ch2xCh2.configure(highlightbackground="#d9d9d9")
        self.Ch2xCh2.configure(highlightcolor="black")
        self.Ch2xCh2.configure(variable = self.Ch2ACFVar)
        self.Ch2xCh2.pack()
        self.Ch2xCh2.place(relx=0.55, rely=0.60,height=30, relwidth=0.3)

        #OK and Cancel buttons
        self.OKbutton = Button(top, text="OK", command=self.updateData)
        self.OKbutton.configure(activebackground="#f9f9f9")
        self.OKbutton.configure(activeforeground="black")
        self.OKbutton.configure(background="#f9f9f9")
        self.OKbutton.configure(disabledforeground="#a3a3a3")
        self.OKbutton.configure(font=font10)
        self.OKbutton.configure(foreground="#000000")
        self.OKbutton.configure(highlightbackground="#d9d9d9")
        self.OKbutton.configure(highlightcolor="black")
        self.OKbutton.pack()
        self.OKbutton.place(relx=0.17, rely=0.83,height=30, relwidth=0.25)

        self.cancelButton = Button(top, text="Cancel", command=self.cancelParams)
        self.cancelButton.configure(activebackground="#f9f9f9")
        self.cancelButton.configure(activeforeground="black")
        self.cancelButton.configure(background="#f9f9f9")
        self.cancelButton.configure(disabledforeground="#a3a3a3")
        self.cancelButton.configure(font=font10)
        self.cancelButton.configure(foreground="#000000")
        self.cancelButton.configure(highlightbackground="#d9d9d9")
        self.cancelButton.configure(highlightcolor="black")
        self.cancelButton.pack()
        self.cancelButton.place(relx=0.52, rely=0.83,height=30, relwidth=0.35)

    def validateNumTrials(self,*args):
        y  = self.maxTrialStr.get()
        print(y)
        if y[0] in "0123456789":
            return True
        else:
            print("Invalid Entry")
            self.maxTrialStr.set("1")
            return False

    def cancelParams(self,*args):
        self.newData = "No"
        self.acqDur = 0
        self.maxNumTrials = 0
        self.correlations = [0,0,0,0]
        try:
            root.destroy()
        except:
            destroy_OptionWindow()

    def updateData(self,*args):
        self.newData = "Yes"
        self.acqDur = int(self.timeVar.get())
        self.maxNumTrials = int(self.maxTrialStr.get())
        self.correlations[0] = self.Ch1ACFVar.get()
        self.correlations[1] = self.Ch1xCh2Var.get()
        self.correlations[2] = self.Ch2xCh1Var.get()
        self.correlations[3] = self.Ch2ACFVar.get()
        try:
            root.destroy()
        except:
            destroy_OptionWindow()

if __name__ == '__main__':
    vp_start_gui()


import os, sys
import asyncio
import aiohttp  # pip install aiohttp
import aiofiles  # pip install aiofiles

def download_files_from_report(file_name):
    if sys.version_info[0] == 3 and sys.version_info[1] >= 8 and sys.platform.startswith('win'):
        asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

    REPORTS_FOLDER = "zips"
    FILES_PATH = os.path.join(REPORTS_FOLDER)
    urls = []
    with open(f'{file_name}.txt', 'r', encoding='utf-8') as links:
        for line in links:
            line = line.strip()
            urls.append(line)

    os.makedirs(FILES_PATH, exist_ok=True)
    sema = asyncio.BoundedSemaphore(5)

    async def fetch_file(url):
        fname = url.split("/")[-1]
        async with sema, aiohttp.ClientSession() as session:
            async with session.get(url) as resp:
                assert resp.status == 200
                data = await resp.read()

        async with aiofiles.open(
            os.path.join(FILES_PATH, fname), "wb"
        ) as outfile:
            await outfile.write(data)

    loop = asyncio.get_event_loop()
    tasks = [loop.create_task(fetch_file(url)) for url in urls]
    loop.run_until_complete(asyncio.wait(tasks))
    loop.close()


# import dependencies
from os.path import join
import pandas as pd

# import functions
from eir_functions import scrape_all, to_binary, to_csv, binary_to_csvs, clean_metadata, clean_measurements, clean_csvs, to_individuals

# bring in config values
from sys import path
path.insert(0, "..")
from config import eir_raw_source, eir_cleaned_destination_csv, eir_cleaned_destination_bin, eir_anchor_search_term, eir_file_extension

# toggle routine steps
save_load_binary = False
save_csv = False
clean_existing_raw = True

# cleans existing raw data
if clean_existing_raw:

    # clean the raw csvs
    clean_csvs(eir_cleaned_destination_csv)

else:

    # specify targeted data
    scraped_workbook_qty = 0            # sets a limit on how many workbooks will be scraped, if 0 then no limit
    randomize_workbooks = False         # will select workbooks at random, if qty = 0 then set this to False
    overwrite_targeted_workbooks = []   # if list is empty then scrape_all will use the quantity/randomized parameters

    # scrape all the relevant data from the electronic inspection workbooks
    raw_results_all = scrape_all(
        eir_raw_source,
        eir_anchor_search_term,
        eir_file_extension,
        qty_limit = scraped_workbook_qty,
        is_random = randomize_workbooks,
        workbooks = overwrite_targeted_workbooks)

    raw_metadata_df, raw_measurements_df = raw_results_all
    if (raw_metadata_df is not None) and (raw_measurements_df is not None):

        # saves results to then loads from a binary file
        if save_load_binary:

            # binary file name
            raw_bin_file_name = "raw_results_all.pkl"
            cln_bin_file_name = "cln_results_all.pkl"

            # saves raw results to binary
            to_binary(eir_cleaned_destination_bin, raw_bin_file_name, raw_results_all)

            # saves cleaned results to binary
            raw_metadata_df, raw_measurements_df = raw_results_all
            cln_metadata_df = clean_metadata(raw_metadata_df)
            cln_measurements_df = clean_measurements(raw_measurements_df)
            to_binary(eir_cleaned_destination_bin, cln_bin_file_name, (cln_metadata_df, cln_measurements_df))

            # loads from binary and resaves to csv if the results aren't already being converted directly to csv
            if not save_csv:
                binary_to_csvs(eir_cleaned_destination_bin, eir_cleaned_destination_csv, raw_bin_file_name, cln_bin_file_name)

        # saves results directly to csv files
        if save_csv:

            # extract then clean the raw results
            raw_metadata_df, raw_measurements_df = raw_results_all

            raw_metadata_df.to_csv(join(eir_cleaned_destination_csv, "raw_metadata_df.csv"), index = False)
            raw_measurements_df.to_csv(join(eir_cleaned_destination_csv, "raw_measurements_df.csv"), index = False)

            cln_metadata_df = clean_metadata(raw_metadata_df)
            cln_measurements_df = clean_measurements(raw_measurements_df)

            # saves to csv files
            to_csv(eir_cleaned_destination_csv, raw_results_all, (cln_metadata_df, cln_measurements_df))

            # saves as individual files
            to_individuals(cln_metadata_df, cln_measurements_df, join(eir_cleaned_destination_csv, "_individual_files"))
    else:
        print("Extracted data is null")


from math import prod

from torch import zeros
from torch.nn import Module, Sequential, Conv1d, ReLU, Linear

class SimpleFFDQN(Module):
    def __init__(self, obs_len, n_actions):
        super().__init__()

        self.fc_val = Sequential(
            Linear(obs_len, 512),
            ReLU(),
            Linear(512, 512),
            ReLU(),
            Linear(512, 1)
        )
        self.fc_adv = Sequential(
            Linear(obs_len, 512),
            ReLU(),
            Linear(512, 512),
            ReLU(),
            Linear(512, n_actions)
        )

    def forward(self, x):
        adv, val = self.fc_adv(x), self.fc_val(x)
        return val + (adv - adv.mean(dim=1, keepdim=True))

class DQNConv1D(Module):
    def __init__(self, input_shape, n_actions):
        super().__init__()
        self.conv = Sequential(
            Conv1d(input_shape[0], 128, 5),
            ReLU(),
            Conv1d(128, 128, 5),
            ReLU(),
        )
        conv_out_size = self._get_conv_out(input_shape)
        self.fc_val = Sequential(
            Linear(conv_out_size, 512),
            ReLU(),
            Linear(521, 1)
        )
        self.fc_adv = Sequential(
            Linear(conv_out_size, 512),
            ReLU(),
            Linear(512, n_actions)
        )

    def _get_conv_out(self, shape):
        o = self.conv(zeros(1, *shape))  # 1 is the batch size
        return prod(o.size())

    def forward(self, x):
        conv_out = self.conv(x).flatten(start_dim=1)
        adv, val = self.fc_adv(conv_out), self.fc_val(conv_out)
        return val + (adv - adv.mean(dim=1, keepdim=True))


import json

input_path_labor = "/input/labor/input.json"
input_path_divorce = "/input/divorce/input.json"
input_path_loan = "/input/loan/input.json"
output_path_labor = "/output/labor/output.json"
output_path_divorce = "/output/divorce/output.json"
output_path_loan = "/output/loan/output.json"

def predict(input_path, output_path):
    inf = open(input_path, "r", encoding='utf-8')
    ouf = open(output_path, "w", encoding='utf-8')

    for line in inf:
        pre_doc = json.loads(line)
        new_pre_doc = []
        for sent in pre_doc:
            sent['labels'] = []  # 将该空列表替换成你的模型预测的要素列表结果
            new_pre_doc.append(sent)
        json.dump(new_pre_doc, ouf, ensure_ascii=False)
        ouf.write('\n')

    inf.close()
    ouf.close()

# labor领域预测
predict(input_path_labor, output_path_labor)

# loan领域预测
predict(input_path_loan, output_path_loan)

# divorce领域预测
predict(input_path_divorce, output_path_divorce)


# Summary:
    # referred to leetcode discussion: OldCodingFarmer(https://leetcode.com/problems/add-two-numbers/discuss/1032/Python-concise-solution.)

import sys
input = sys.stdin.readline
from collections import deque

# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution:
    def __init__(self) -> None:
        pass

    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        dummy = cur = ListNode(0)
        carry = 0

        while l1 or l2 or carry:
            if l1:
                carry += l1.val
                l1 = l1.next

            if l2:
                carry += l2.val
                l2 = l2.next

            cur.next = ListNode(carry % 10)
            cur = cur.next
            carry //= 10

        return dummy.next

Solution()


from collections import defaultdict
from nltk import ngrams
import pickle

class SentsFromCorpus():
    def __init__(self, path):
        self.path = path

    def __iter__(self):
        with open(self.path) as f:
            for ln in f:
                if ln == '\n':
                    continue
                yield [x.split('_')[0].lower() for x in ln.split('\t')]

class SentsFromCorpusPP():
    def __init__(self, path):
        self.path = path

    def __iter__(self):
        with open(self.path) as f:
            for ln in f:
                if ln == '\n':
                    continue
                if 'PP' in ln:
                    yield [x for x in ln.split('\t')]

def news_ngrams(cpath):
    corpus_sentences = SentsFromCorpusPP(cpath)
    ngram_dict = defaultdict(int)

    folder_path = '/home/adam/Documents/lexical_blends_project/lexicon_wordlists/'
    with open(folder_path + 'saldo_news_wordlist_f.pickle', 'rb') as f:
        lexicon = pickle.load(f)

    for i, sentence in enumerate(corpus_sentences):
        for ng in ngrams(sentence, 3):
            if 'PP' in ng[1]:
                #print(ng)
                w1 = ng[0].split('_')[0]
                w2 = ng[2].split('_')[0]
                if w1 in lexicon and w2 in lexicon:
                    ngram_dict[(w1,w2)] += 1

    for k, v in ngram_dict.items():
        ngram_dict[k] = ngram_dict[k]/lexicon[k[1]]

    # (w_-1, w_0)
    with open('3-gramsPP_saldo.pickle', '+wb') as o:
        pickle.dump(ngram_dict, o)

if __name__ == '__main__':
    news_ngrams('/home/adam/data/news/sentence_segmented/newscorpus.txt')


n1 = n2 = int(input('Digite um número para ver seu fatorial: '))
f = 1
quant = 0
while quant != n1:
    quant += 1
    f *= n2
    print(f'\033[37m{n2}', end='')
    print('*' if n2 > 1 else '= ', end='')
    n2 -= 1
print(f'\033[m{f}')

n1 = int(input('Digite outro número para ver seu fatorial: '))
f = 1
for c in range(n1, 0, -1):
    f *= c
    print(f'\033[37m{c}', end='')
    print('*' if c > 1 else '= ', end='')
print(f'\033[m{f}')
"""Também pode ser feito da seguinte forma:
from math import factorial
n = int(input('Digite um número'))
print(f'O fatorial de {n} é: {factorial(n)}')"""


#imports contab package
from crontab import CronTab
#creates the cron job of Detect-IP.py script to run every hour
cron = CronTab(user="root")
detectIPjob = cron.new(command="python3 Detect-IP.py")
detectIPjob.hour.every(1)
cron.write()
#creates the cron job of Backup.py to run every Friday
cron = CronTab(user="root")
Backupjob = cron.new(command="python3 Backup.py")
Backupjob.day.on(5)
cron.write()


import sys
sys.stdin = open('input.txt')

N = int(sys.stdin.readline())
cranes = sorted(list(map(int, sys.stdin.readline().split())))
M = int(sys.stdin.readline())
boxes = sorted(list(map(int, sys.stdin.readline().split())))
answer = -1

cnts = [0] * N

# 무게 제한이 작은 크레인부터 순회
# 각 크레인으로만 이동 가능한 박스 개수
c, b = 0, 0
while b < M and c < N:
    if boxes[b] <= cranes[c]:
        cnts[c] += 1
        b += 1
    else:
        c += 1

if c != N:
    # 무게제한이 가장 큰 크레인의 이동 시간
    max_ans = cnts[-1]

    # 무게제한이 큰 두번째 크레인부터 순회
    for i in range(N-2, -1, -1):

        # 현재 크레인 이동 시간 > 현재까지 최대 이동 시간
        if cnts[i] > max_ans:
            remain = cnts[i] - max_ans
            cnts[i] = max_ans

            # 현재 크레인부터 무게 제한 높은 크레인으로 순회하여 최대 이동시간만큼 박스를 나누기
            for j in range(i, N):
                if not remain:
                    break
                elif cnts[j] != max_ans:
                    num = min(remain, max_ans - cnts[j])
                    remain -= num
                    cnts[j] += num

            # 나눠야할 박스가 남아있다면, 이동시간을 늘려가며 추가
            if remain:
                for j in range(N-1, i-1, -1):
                    num = remain // (j-i+1)
                    cnts[j] += num
                    remain -= num
                max_ans = max(max_ans, max(cnts[i:]))
    answer = max(cnts)

print(answer)


from django.forms import ModelForm
from .models import Ticket, Comment
from django import forms
from datetime import date
from dateutil.relativedelta import relativedelta
from bootstrap_datepicker_plus import DatePickerInput
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth import get_user_model

def valid_deadline(value):
	"""
	validate deadline: checks if given date is in the past
						or in the remote future(10 years from now)
	param: value(datetime.date) - given date which we want to validate
	return: value if no error else ValidationError
	"""
	today = date.today()
	upper_limit = today + relativedelta(years=10)
	if value < today:
		raise forms.ValidationError(_('Das Datum darf nicht in der Vergangenheit liegen.'))
	if value > upper_limit:
		raise forms.ValidationError(_('Das Datum liegt zu weit in der Zukunft.'))
	return value

class AddTicketForm(ModelForm):
	"""
	modelform for creating a ticket, used in new_ticket.html/ NewTicketView
	"""
	deadline = forms.DateField(input_formats=['%d.%m.%Y'],widget=DatePickerInput(format='%d.%m.%Y',attrs={'placeholder': 'TT.MM.JJJJ'}, options={
                    "showTodayButton": False,
					"locale": "de-DE",
					"minDate": date.today().isoformat(),
					"allowInputToggle": True,
					"keepInvalid": False,
					"useCurrent": False,
                }), required=False, help_text=_("Der Tag bis das Ticket erledigt sein soll."), validators=[valid_deadline])
	assigned_user = forms.ModelChoiceField(queryset=get_user_model().objects.all().order_by('username'),required=False)
	class Meta:
		model = Ticket
		fields = ["name", "text", "assigned_user", "assigned_group", "priority", "deadline"]

class AddCommentForm(ModelForm):
	"""
	modelform for adding a comment to a ticket
	used in ShowTicketView/show_ticket.html
	"""
	class Meta:
		model = Comment
		fields = ["comment"]
		labels = {
			"comment": _("Schreibe einen Kommentar"),
		}
		widgets = {
            'comment': forms.Textarea(
                attrs={'placeholder': _('Schreibe einen Kommentar')}),
        }

class EditTicketForm(ModelForm):
	"""
	modelform for editing a ticket
	used in EditTicketView/edit_ticket.html
	"""
	deadline = forms.DateField(input_formats=['%d.%m.%Y'],widget=DatePickerInput(format='%d.%m.%Y',attrs={'placeholder': 'TT.MM.JJJJ'}, options={
                    "showTodayButton": False,
					"locale": "de-DE",
					"minDate": date.today().isoformat(),
					"allowInputToggle": True,
					"keepInvalid": True,
					"useCurrent": False,
                }), required=False, help_text=_("Der Tag bis das Ticket erledigt sein soll."))
	class Meta:
		model = Ticket
		fields = ["name", "state", "text", "assigned_user", "assigned_group", "priority", "deadline"]

	def clean(self):
		"""
		overrides modelform clean method
		checks if given deadline is valid else raises ValidationError
		"""
		cleaned_data = super().clean()
		if self.has_changed() and self.is_valid():
			if 'deadline' in self.changed_data:
				try:
					valid_deadline(self.cleaned_data["deadline"])
				except forms.ValidationError as err:
					self.add_error('deadline', err)


import pytest

from game.radio.tacan import (
    OutOfTacanChannelsError,
    TacanBand,
    TacanChannel,
    TacanRegistry,
    TacanUsage,
)

ALL_VALID_X_TR = [1, *range(31, 46 + 1), *range(64, 126 + 1)]
ALL_VALID_X_A2A = [*range(37, 63 + 1), *range(100, 126 + 1)]

def test_allocate_first_few_channels() -> None:
    registry = TacanRegistry()
    chan1 = registry.alloc_for_band(TacanBand.X, TacanUsage.TransmitReceive)
    chan2 = registry.alloc_for_band(TacanBand.X, TacanUsage.TransmitReceive)
    chan3 = registry.alloc_for_band(TacanBand.X, TacanUsage.TransmitReceive)
    assert chan1 == TacanChannel(1, TacanBand.X)
    assert chan2 == TacanChannel(31, TacanBand.X)
    assert chan3 == TacanChannel(32, TacanBand.X)

def test_allocate_different_usages() -> None:
    """Make sure unallocated channels for one use don't make channels unavailable for other usage"""
    registry = TacanRegistry()

    chanA2AX = registry.alloc_for_band(TacanBand.X, TacanUsage.AirToAir)
    chanA2AY = registry.alloc_for_band(TacanBand.Y, TacanUsage.AirToAir)
    assert chanA2AX == TacanChannel(37, TacanBand.X)
    assert chanA2AY == TacanChannel(37, TacanBand.Y)

    chanTRX = registry.alloc_for_band(TacanBand.X, TacanUsage.TransmitReceive)
    chanTRY = registry.alloc_for_band(TacanBand.Y, TacanUsage.TransmitReceive)
    assert chanTRX == TacanChannel(1, TacanBand.X)
    assert chanTRY == TacanChannel(1, TacanBand.Y)

def test_reserve_all_valid_transmit_receive() -> None:
    registry = TacanRegistry()
    print("All valid x", ALL_VALID_X_TR)

    for num in ALL_VALID_X_TR:
        registry.mark_unavailable(TacanChannel(num, TacanBand.X))

    with pytest.raises(OutOfTacanChannelsError):
        registry.alloc_for_band(TacanBand.X, TacanUsage.TransmitReceive)

    # Check that we still can allocate an a2a channel even
    # though the T/R channels are used up
    chanA2A = registry.alloc_for_band(TacanBand.X, TacanUsage.AirToAir)
    assert chanA2A == TacanChannel(47, TacanBand.X)

def test_reserve_all_valid_a2a() -> None:
    registry = TacanRegistry()
    print("All valid x", ALL_VALID_X_A2A)

    for num in ALL_VALID_X_A2A:
        registry.mark_unavailable(TacanChannel(num, TacanBand.X))

    with pytest.raises(OutOfTacanChannelsError):
        registry.alloc_for_band(TacanBand.X, TacanUsage.AirToAir)

    # Check that we still can allocate an a2a channel even
    # though the T/R channels are used up
    chanTR = registry.alloc_for_band(TacanBand.X, TacanUsage.TransmitReceive)
    assert chanTR == TacanChannel(1, TacanBand.X)

def test_reserve_again() -> None:
    registry = TacanRegistry()
    registry.mark_unavailable(TacanChannel(1, TacanBand.X))
    registry.mark_unavailable(TacanChannel(1, TacanBand.X))

def test_tacan_parsing() -> None:
    assert TacanChannel.parse("1X") == TacanChannel(1, TacanBand.X)
    assert TacanChannel.parse("1Y") == TacanChannel(1, TacanBand.Y)
    assert TacanChannel.parse("10X") == TacanChannel(10, TacanBand.X)
    assert TacanChannel.parse("100X") == TacanChannel(100, TacanBand.X)

    with pytest.raises(ValueError):
        TacanChannel.parse("1000X")
    with pytest.raises(ValueError):
        TacanChannel.parse("0X")
    with pytest.raises(ValueError):
        TacanChannel.parse("1Z")
    with pytest.raises(ValueError):
        TacanChannel.parse("X")
    with pytest.raises(ValueError):
        TacanChannel.parse("1")
    with pytest.raises(ValueError):
        TacanChannel.parse("1 X")
    with pytest.raises(ValueError):
        TacanChannel.parse(" 1X")
    with pytest.raises(ValueError):
        TacanChannel.parse("1X ")
    with pytest.raises(ValueError):
        TacanChannel.parse("1x")


# С5.6. Итоговое практическое задание
# Телеграм-бот: Конвертор валют
# Студент: Кулагин Станислав
# Поток: FWP_123

import requests
import json
from config import keys, HEADERS

class APIException(Exception):
    pass

class CryptoConvertor:
    @staticmethod
    def get_price(quote: str, base: str, amount: str):
        if quote == base:
            raise APIException(f'Вы указали одинаковые валюты {base}.')

        try:
            quote_ticker = keys[quote]
        except KeyError:
            raise APIException(f"Не удалось обработать валюту {quote}")

        try:
            base_ticker = keys[base]
        except KeyError:
            raise APIException(f"Не удалось обработать валюту {base}")

        try:
            amount = float(amount)
        except ValueError:
            raise APIException(f"Ну удалось обработать количество {amount}")

        url = f'https://api.apilayer.com/currency_data/convert?to={base_ticker}&from={quote_ticker}&amount={amount}'
        r = requests.get(url, headers=HEADERS)  # добавляем apikey в заголовок запроса
        total_base = json.loads(r.content)['result']

        return total_base


#!/usr/bin/python3

import logging
import logging.handlers
import speedtest
import thingspeak
import traceback
import json
import os

rootLogger = logging.getLogger('')
rootLogger.setLevel(logging.INFO)

def joinPathToScriptDirectory(path):
    return os.path.join(os.path.dirname(os.path.abspath(__file__)), path)

def configure_log():
    root = logging.getLogger()
    log_file_name = joinPathToScriptDirectory('speedtest.log')
    h = logging.handlers.RotatingFileHandler(log_file_name, maxBytes=1024*1024, backupCount=5)
    f = logging.Formatter('%(asctime)s %(name)s %(levelname)-8s %(message)s')
    h.setFormatter(f)
    root.addHandler(h)

def main():
    configure_log()

    global channel

    try:
        config_file_path = joinPathToScriptDirectory('thingspeak.json')

        with open(config_file_path) as config_file:
            config = json.load(config_file)

        channel_id = config["channel"]
        write_key = config["writekey"]

        #for server in speedtest.list_servers():
        #    print('%(id)4s) %(sponsor)s (%(name)s, %(country)s) ''[%(d)0.2f km]' % server)

        ping, download, upload, server = speedtest.test_speed(timeout=30, secure=True)
        download = download /(1000.0*1000.0)*8
        upload = upload /(1000.0*1000.0)*8

        logging.info('Ping %dms; Download: %2f; Upload %2f', ping, download, upload)
        channel = thingspeak.Channel(id=channel_id, write_key=write_key)
        response = channel.update({1: ping, 2: download, 3: upload})
        print(response)
    except KeyboardInterrupt:
        print('\nCancelling...')
        speedtest.cancel_test()
    except Exception:
        logging.exception("Exception has occurred")
        traceback.print_exc()

if __name__ == '__main__':
    main()


""" Cheddargetter models used in framework."""
from collections import namedtuple
from hashlib import md5
import requests

try:
    from urllib import urlencode
except ImportError:
    from urllib.parse import urlencode

from . import six
from .settings import settings
from .client import Client
from .utils import namedtuple_as_dict, classproperty

class FactoryMeta(type):

    """ Proxy objects metaclass. """

    __store__ = dict()

    def __new__(class_, name, bases, params):
        cls = super(FactoryMeta, class_).__new__(class_, name, bases, params)
        class_.__store__[name] = cls
        return cls

class Factory(object):
    @staticmethod
    def instantiate(class_name, **kwargs):
        class_name = str(class_name)
        cls_mixin_name = class_name + "Mixin"
        cls_mixin = FactoryMeta.__store__.get(cls_mixin_name, object)
        cls_base = namedtuple(class_name, kwargs.keys())
        methods = {"as_dict": property(namedtuple_as_dict)}
        cls = type(class_name, (cls_base, cls_mixin), methods)
        return cls(**kwargs)

class ClientMixin(object):
    @classproperty
    @classmethod
    def client(cls):
        return Client(
            settings.USERNAME,
            settings.PASSWORD,
            settings.PRODUCT_CODE
        )

@six.add_metaclass(FactoryMeta)
class CustomerMixin(ClientMixin):
    @property
    def key(self):
        """ Customer key used in url links.

        The Customer Key is a hash of the Customer Code and your Product
        Secret Key. Customers will also be able to update their data through
        links. Some of the links should have customer key as a parameter.

        :return str: customer key

        """
        KEY_LENGTH = 10
        key = md5("{}|{}".format(
            self.code, settings.PASSWORD)).\
            hexdigest()[:KEY_LENGTH]
        return key

    @property
    def create_url(self):
        params = urlencode(dict(code=self.code)) if hasattr(self, "code") \
            else ""
        url = "{}/create?{}".format(settings.BASE_URL, params)
        return url

    @property
    def update_url(self):
        params = urlencode(dict(key=self.key, code=self.code))
        url = "{}/update?{}".format(settings.BASE_URL, params)
        return url

    @property
    def cancel_url(self):
        params = urlencode(dict(key=self.key, code=self.code))
        url = "{}/cancel?{}".format(settings.BASE_URL, params)
        return url

    @property
    def status_url(self):
        params = urlencode(dict(key=self.key, code=self.code))
        url = "{}/status?{}".format(settings.BASE_URL, params)
        return url

    @property
    def status(self):
        """ Return Customer status.

        http://support.cheddargetter.com/kb/hosted-payment-pages/
            hosted-payment-pages-setup-guide#status
        :return str status: ('active'|'canceled'|'pending')
        """
        return requests.get(self.status_url, verify=False).content

    @classmethod
    def get_all(cls):
        return cls.client.get_all_customers()

    def delete(self):
        return self.client.delete_customer(self.code)


import requests
from lxml import etree as et
import multiprocessing
import google.cloud.bigquery as bq
import os
import traceback

def position(arg):
    l = arg
    if l == 0:
        pos = 1
        return (pos)
    else:
        return (l + 1)

def foc_cum_call(url):
    try:
        return_list = [1]
        response = requests.get(url)
        tree = et.fromstring(response.content)
        cum_srh = tree.xpath('//srh/text()')
        cum_power_id = tree.xpath('//cumulativePower/@id')
        if len(cum_power_id) > 0:
            cum_href = tree.xpath('//href/text()')
            cum_srh = tree.xpath('//srh/text()')
            cum_start_date = tree.xpath('//interval/startDate/text()')
            cum_end_date = tree.xpath('//interval/endDate/text()')
            cum_total_power = tree.xpath('//totalPower/text()')
            meter_list = tree.xpath('//meter/@id')
            meter_list_len = len(meter_list)
            rang = range(meter_list_len)
            if meter_list_len > 0:
                for l, i in zip(rang, meter_list):
                    interim_list = []
                    pos = position(l)
                    meter_id = tree.xpath("//meter[position()='%s'][@id='%s']/@id" % (pos, i))
                    meter_active = tree.xpath("//meter[position()='%s'][@id='%s']/@active" % (pos, i))
                    meter_serialnum = tree.xpath("//meter[position()='%s'][@id='%s']/serialNumber/text()" % (pos, i))
                    meter_provider = tree.xpath("//meter[position()='%s'][@id='%s']/provider/text()" % (pos, i))
                    meter_power = tree.xpath("//meter[position()='%s'][@id='%s']/meterPower/text()" % (pos, i))
                    meter_start_dt = tree.xpath(
                        "//meter[position()='%s'][@id='%s']/interval/startDate/text()" % (pos, i))
                    meter_end_dt = tree.xpath("//meter[position()='%s'][@id='%s']/interval/endDate/text()" % (pos, i))
                    if meter_power == ['0.0']:
                        meter_start_read = ['']
                        meter_end_read = ['']
                        meter_first_read_dt = ['']
                        meter_last_read_dt = ['']
                    else:
                        meter_start_read = tree.xpath(
                            "//meter[position()='%s'][@id='%s']/readings/reading[position()='1']/text()" % (pos, i))
                        meter_end_read = tree.xpath(
                            "//meter[position()='%s'][@id='%s']/readings/reading[position()='2']/text()" % (pos, i))
                        meter_first_read_dt = tree.xpath(
                            "//meter[position()='%s'][@id='%s']/readings/reading[position()='1']/@time" % (pos, i))
                        meter_last_read_dt = tree.xpath(
                            "//meter[position()='%s'][@id='%s']/readings/reading[position()='2']/@time" % (pos, i))
                    interim_list = [cum_srh, cum_power_id, cum_start_date[0], cum_end_date[0], cum_total_power,
                                    meter_id, meter_active, meter_serialnum, meter_provider, meter_start_dt,
                                    meter_end_dt, meter_start_read, meter_end_read, meter_first_read_dt,
                                    meter_last_read_dt]
                    l = []
                    for item in interim_list:
                        l.append(''.join(item))
                    return_list.append(l)
    except Exception as errmsg:
        print(errmsg)
        return_list = [1]
    return return_list

if __name__ == '__main__':
    p = 20
    pool = multiprocessing.Pool(p)
    try:
        failed_list = []
        success_list = []
        os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "noc_service_account_sr-dev-datahub.json"
        project_id = 'sr-dev-datahub'
        bigquery_client = bq.Client(project=project_id)
        select_sql = """SELECT Agreement_Number__c,PTO__c FROM `sr-dev-datahub.Datahub.ORN_SERVICE_CONTRACT_V` order by 1 LIMIT 1"""
        select_job = bigquery_client.query(select_sql)
        select_results = select_job.result()
        print("...............................", select_results)
        for row in select_results:
            srh = row[0]
            endDate = row[1].strftime('%Y-%m-%d')
            # url = 'https://foc.sunrun.com/foc/rest/v1/power?srh={}&endDate={}'.format(srh, endDate)
            url = 'https://foc.sunrun.com/foc/rest/v1/power?srh={}&endDate={}'.format('03', '2018-11-01')
            if len(srh) > 0 and len(endDate) > 0:
                return_list = foc_cum_call(url)
                print(return_list)
                if return_list[0] == 1:
                    failed_list.append(url)
                else:
                    success_list.append(url)
            else:
                failed_list.append(url)

        print("failed list is : {}".format(failed_list))
        print("success list is: {}".format(success_list))
    except Exception as e:
        print(traceback.format_exc())


"""
Este código implementa a parte Coletora de um programa de fila de mensagens que coleta,
classifica e distribui tweets de acordo com tópicos selecionados pelo cliente.

Autores:
  - Caio Miglioli @caiomiglioli
  - Ryan Lazaretti @ryanramos01

Data de Criação: 30 de Maio de 2023
Ultima alteração: 31 de Maio de 2023
"""

import pika
from json import dumps
from csv import reader
from time import sleep

def tw2dict(header, tw):
    """
    Recebe um vetor header contendo o nome de cada coluna do csv
    Recebe um vetor tw contendo os valores de uma coluna qualquer do csv
    Junta ambos em um dicionário chave-valor e retorna
    """
    res = dict()
    for i, head in enumerate(header):
        res[head] = tw[i]
    return res

def publishFromCSV(filename, channel, interval):
    """
    Função que lê cada linha do CSV, e coordena a publicação chamando as funções necessárias (tw2dict e publish)
    """
    with open(filename, newline='') as tws:
        _reader = reader(tws)
        header = None

        for i, tw in enumerate(_reader):
            # if i > 1: break #enviar somente 1 tweet xd

            if i == 0:
                header = tw
                continue

            t = tw2dict(header, tw)
            publish(channel, t)
            sleep(interval)
        #end for
    #end open

def publish(channel, tw):
    """
    Recebe um channel de MQ e um dicionario contendo as informações do tweet,
    retira somente os valores importantes e publica na fila de mensagens para o classificador
    """
    # user = literal_eval(tw["tweet_user"])

    body = {
        "tweet": tw['text'],
        "at": tw['name'],
        # "tweet": tw['tweet_full_text'],
        # "author": user["name"],
        # "at": user['screen_name']
    }

    channel.basic_publish(exchange='', routing_key='raw-tweets', body=dumps(body))
    print(f'tweet by @{body["at"]} published')
#end publish

def main():
    # cria a conexão com o RabbitMQ
    connection = pika.BlockingConnection(pika.ConnectionParameters('localhost', '5672'))
    print('connection started')

    # declara a fila
    channel = connection.channel()
    channel.queue_declare(queue='raw-tweets')
    print('raw-tweets queue started')

    # envia os tweets para a fila
    try:
        publishFromCSV('tweet_data.csv', channel, .5)
    finally:
        print('connection closed')
        connection.close()

if __name__ == '__main__':
    main()


from collections import deque

PAID_COMMAND = "Paid"
END_COMMAND = "End"

q = deque()

while True:
    command = input()
    if command == PAID_COMMAND:
        while q:
            print(q.popleft())
    elif command == END_COMMAND:
        print(f"{len(q)} people remaining.")
        break
    else:
        q.append(command)


from cvxopt import matrix, solvers
import numpy as np
import cvxopt

'''
问题描述：
minimize xQx+px
subject Gx <= h
        Ax = b
注：Q=[[2, .5], [.5, 1]]，即xQx=2x1^2+x^2+x1*x2
'''

Q = 2*matrix(np.array([[2, .5], [.5, 1]]))  # 一定要乘以2
p = matrix([1.0, 1.0])
G = matrix([[-1.0, 0.0], [0.0, -1.0]])
h = matrix([0.0, 0.0])
A = matrix([1.0, 1.0], (1, 2))
b = matrix(1.0)

sol = solvers.qp(Q, p, G, h, A, b)
print(sol['x'], sol['y'])


import os
import sys

sys.stdin = open(
    os.path.join("/", *__file__.split("/")[:-1], "sample_input.txt"), "r"
)

# https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV5PpLlKAQ4DFAUq

import heapq

DR = [-1, 0, 1, 0]
DC = [0, 1, 0, -1]

STRUCT = {
    0: [],
    1: [0, 1, 2, 3],
    2: [0, 2],
    3: [1, 3],
    4: [0, 1],
    5: [1, 2],
    6: [2, 3],
    7: [3, 0],
}

def is_valid(r: int, c: int):
    return 0 <= r < len(tunnel) and 0 <= c < len(tunnel[0])

def is_connected(d: int, struct_id: int):
    return (d + 2) % 4 in STRUCT[struct_id]

def bfs(r: int, c: int, l: int):
    visited = {(r, c)}

    pq = [(1, r, c)]
    while pq:
        t, r, c = heapq.heappop(pq)
        if t == l:
            return len(visited)

        for d in STRUCT[tunnel[r][c]]:
            _r, _c = r + DR[d], c + DC[d]
            if not is_valid(_r, _c):
                continue
            if not is_connected(d, tunnel[_r][_c]):
                continue
            if (_r, _c) in visited:
                continue

            heapq.heappush(pq, (t + 1, _r, _c))
            visited.add((_r, _c))

    return len(visited)

for t in range(1, int(input()) + 1):
    m, n, r, c, l = map(int, input().split())
    tunnel = [list(map(int, input().split())) for _ in range(m)]
    print(f"#{t} {bfs(r, c, l)}")


import subprocess
import logging
import cliff.command
import configparser
import workflowlister
import json
import os
import sys

class Generator(cliff.command.Command):
    "This Generator will generate new job orders based on the contents of ~/ini-dir. Be aware that it will also rewrite your params.json file and your ~.youxia/config file."
    log = logging.getLogger(__name__)
    def get_parser(self,prog_name):
        parser = super(Generator,self).get_parser(prog_name)
        parser.add_argument('--workflow',dest='workflow_name',help='The name of the workflow for which you would like to generate jobs.',required=True)
        parser.add_argument('--force',dest='force_generate',help='Force the generation of the jobs, even if the system detects that the job has already been generated once before.', required=False, action='store_true')
        parser.add_argument('--keep_failed',dest='keep_failed',help='Keep failed workers in the fleet. Useful for debugging workflows.', required=False, action='store_true')
        parser.add_argument('--os_env_name',dest='os_env_name',help='The name of the OpenStack environment you\'re working in. Only useful if you are working in OpenStack. If you omit this, you will be prompted for this information when necessary.', required=False)
        #parser.add_argument('--no_config_update',dest='no_config_update',help='Do not update any configuration files.', required=False, action='store_true')
        #parser.add_argument('--uses_gnos', dest='use_gnos',help='Indicates that your worfklow will be using GNOS repositories. --use_gnos and --use_s3 are not mutually exclusive - you could configure your workflow\'s INI file to use both GNOS and AWS S3 repositories.',required=False, default=True, choices=[True,False])
        #parser.add_argument('--uses_s3', dest='use_s3',help='Indicates that your worfklow will be using S3 repositories.  --use_gnos and --use_s3 are not mutually exclusive - you could configure your workflow\'s INI file to use both GNOS and AWS S3 repositories.',required=False, default=False, choices=[True,False])
        return parser

    def take_action(self, parsed_args):
        workflow_name = vars(parsed_args)['workflow_name']
        force_generate = vars(parsed_args)['force_generate']
        keep_failed = vars(parsed_args)['keep_failed']
        os_env_name = vars(parsed_args)['os_env_name']
        self.log.debug('workflow_name: %s',workflow_name)
        self.log.debug('all workflows: '+workflowlister.WorkflowLister.get_workflow_names())
        cloud_env = os.environ['HOST_ENV'].upper()

        if workflow_name in workflowlister.WorkflowLister.get_workflow_keys():

            # First thing: if the directory is empty, don't bother going any further.
            if os.listdir(path='/home/ubuntu/ini-dir') != []:

                sysconfig_cmd = 'pancancer sysconfig'
                return_code = subprocess.call(sysconfig_cmd.split(' '))
                if return_code != 0:
                    self.log.warn('Attempt to (re)configure system may have encountered an error...')

                master_config_path = os.path.expanduser('~/arch3/config/masterConfig.ini')
                self.log.debug('setting check_previous_job_hash to false in '+master_config_path)
                master_config = configparser.ConfigParser()
                master_config.optionxform = str
                # We have to update the master config file so that the generator process will allow duplicates.
                master_config.read(master_config_path)

                # if --force then do NOT check previous hash
                master_config['generator']['check_previous_job_hash']=str(not force_generate).lower()
                # keep_failed==true -> reap_failed_workers=false
                master_config['provision']['reap_failed_workers']=str(not keep_failed).lower()

                with open(master_config_path,'w') as master_config_file:
                    master_config.write(master_config_file,space_around_delimiters=True)

                workflow_details = workflowlister.WorkflowLister.get_workflow_details(workflow_name)

                if cloud_env == 'AWS' :
                    cloud_specific_details = workflow_details['cloud-specific-details']['aws']
                elif cloud_env == 'OPENSTACK' :
                    # If there is only one OpenStack choice, we'll just go with that.
                    self.log.debug('OpenStack options: '+str(workflow_details['cloud-specific-details']['openstack']))
                    if len(workflow_details['cloud-specific-details']['openstack'].keys())==0:
                        print('No OpenStack environments are available. Exiting.')
                        sys.exit(1)
                    elif len(workflow_details['cloud-specific-details']['openstack'].keys())==1:
                        k = list(workflow_details['cloud-specific-details']['openstack'].keys())[0]
                        cloud_specific_details = workflow_details['cloud-specific-details']['openstack'][k]
                    else:
                        # Check to see if the user did not provide an OpenStack environment name, or if it's not in the list of *actual* names
                        if os_env_name is None or os_env_name not in workflow_details['cloud-specific-details']['openstack']:
                            print('Please enter one of the following OpenStack configurations that are available for this workflow:')
                            for k in workflow_details['cloud-specific-details']['openstack']:
                                print(k)
                            user_value = input().strip()
                            while user_value.strip() == '' or user_value not in workflow_details['cloud-specific-details']['openstack']:
                                print('Sorry, but \''+user_value+'\' was not a valid value. Please try again; valid values are: ')
                                for k in workflow_details['cloud-specific-details']['openstack']:
                                    print(k)
                                user_value = input().strip()
                            cloud_specific_details = workflow_details['cloud-specific-details']['openstack'][user_value]
                        else:
                            # If the user provided an OpenStack environment name and it's legit, just use it.
                            cloud_specific_details = workflow_details['cloud-specific-details']['openstack'][os_env_name]

                elif cloud_env == 'AZURE' :
                    cloud_specific_details = workflow_details['cloud-specific-details']['azure']
                else:
                    self.log.error("Unrecognized cloud environment: "+cloud_env)

                workflow_version = ''
                if 'http_workflow' in workflow_details:
                    workflow_version = workflow_details['http_workflow']['version']
                else:
                    workflow_version = workflow_details['s3_workflow']['version']

                generator_cmd = 'Generator --workflow-name '+workflow_name+' --workflow-version '+workflow_version+' --workflow-path '+'/workflows/'+workflow_details['full_name']+' --ini-dir '+'/home/ubuntu/ini-dir --config /home/ubuntu/arch3/config/masterConfig.ini'
                self.log.debug('generator command will be: '+generator_cmd)
                # Before generating the job, we have to update params.json with the workflow/container info about the requested workflow.
                paramsData=''
                with open('/home/ubuntu/params.json','r') as params_file:
                    paramsData = json.load(params_file)
                    if 'http_workflow' in workflow_details:
                        paramsData['http_workflows'] = {}
                        paramsData['http_workflows'][workflow_name] = workflow_details['http_workflow']
                        paramsData['http_workflows'][workflow_name]['name'] = workflow_details['full_name']
                    if 's3_workflow' in workflow_details:
                        paramsData['s3_workflows'] = {}
                        paramsData['s3_workflows'][workflow_name] = workflow_details['s3_workflows']
                        paramsData['s3_workflows'][workflow_name]['name'] = workflow_details['full_name']
                    if 'containers' in workflow_details:
                        paramsData['containers'] = workflow_details['containers']
                    if 's3_containers' in workflow_details:
                        paramsData['s3_containers'] = workflow_details['s3_containers']
                    if 'http_containers' in workflow_details:
                        paramsData['http_containers'] = workflow_details['http_containers']

                    paramsData['lvm_device_whitelist']=cloud_specific_details['lvm_devices']

                    if paramsData['lvm_device_whitelist'] == "" or paramsData['lvm_device_whitelist'].strip() == "":
                        paramsData['single_node_lvm'] = "false"
                    else:
                        paramsData['single_node_lvm'] = "true"

                    # if --force then do NOT check previous hash
                    #paramsData['generator']['check_previous_job_hash']=str(not force_generate)
                    # keep_failed==true -> reap_failed_workers=false
                    #paramsData['provision']['reap_failed_workers']=str(not keep_failed)
                    #
                    paramsData['workflow_name'] = workflow_name

                # Now write the params.json file.
                with open('/home/ubuntu/params.json','w+') as params_file:
                    params_file.write(str(json.dumps(paramsData,sort_keys=True, indent=4) ))

                # Update the youxia config file with the correct AMI and instance-type
                config = configparser.ConfigParser()
                config.read('/home/ubuntu/.youxia/config')
                if cloud_env == 'AWS':
                    config['deployer']['instance_type']=cloud_specific_details['instance-type']
                    config['deployer']['ami_image']=cloud_specific_details['image']
                elif cloud_env == 'OPENSTACK':
                    config['deployer_openstack']['flavor']=cloud_specific_details['instance-type']
                    config['deployer_openstack']['image_id']=cloud_specific_details['image']
                elif cloud_env == 'AZURE':
                    config['deployer_azure']['flavor']=cloud_specific_details['instance-type']
                    config['deployer_azure']['image_name']=cloud_specific_details['image']

                with open('/home/ubuntu/.youxia/config','w') as youxia_configfile:
                    config.write(youxia_configfile,space_around_delimiters=True)

                provisioner_cmd = 'pancancer provisioner restart'
                return_code = subprocess.call(provisioner_cmd.split(' '))
                if return_code != 0:
                    self.log.warn('Attempt to restart the provisioner may have encountered an error...')

                #sysconfig = SysConfig(SysConfig)
                #parsed_args = sysconfig.get_parser('SysConfig').parse_args('')
                #sysconfig.run()
                #provisioner = Provisioner()
                #provisioner.run(self, provisioner_cmd.split(' '))

                return_code = subprocess.call(generator_cmd.split(' '))
                if return_code != 0:
                    self.log.warn('Attempt to generate jobs may have encountered an error...')
                else:
                    self.log.info('Job requests have been generated for the '+workflow_name+' using the INIs in ~/ini-dir')
            else:
                self.log.info('/home/ubuntu/ini-dir is empty. Place your INI files here before attempting to run the generator.')
        else:
            self.log.info(workflow_name+' is not the name of an available workflow.\nPlease use the command \'workflows list\' to see the list of currently available workflows.')


"""
Реализовать структуру «Рейтинг», представляющую собой не возрастающий набор натуральных чисел. У пользователя
необходимо запрашивать новый элемент рейтинга. Если в рейтинге существуют элементы с одинаковыми значениями,
то новый элемент с тем же значением должен разместиться после них. Подсказка. Например, набор натуральных чисел: 7,
5, 3, 3, 2. Пользователь ввел число 3. Результат: 7, 5, 3, 3, 3, 2. Пользователь ввел число 8. Результат: 8, 7, 5, 3,
3, 2. Пользователь ввел число 1. Результат: 7, 5, 3, 3, 2, 1.

Набор натуральных чисел можно задать непосредственно в коде, например, my_list = [7, 5, 3, 3, 2].
"""

my_list = [7, 5, 3, 3, 2]

while True:
    print(f'Текущий рейтинг {my_list}')
    number = input('Введите целое число (или q для выхода) >>> ')
    if number.isdigit():
        number = int(number)
        my_list.append(number)
        my_list.sort(reverse=True) # Думаю что сортировка будет работать быстрее чем мой кустарный способ вставки
        # элемента на нужную позицию
    elif number == 'q':
        break


import random
from copy import deepcopy
import numpy as np
from Individual import Individual

class Population:
    def __init__(self, pop_size, p_cross, p_mut,
                 genotype_size, decode_fun, fit_fun,
                 cross_fun, plot=False):
        self.population = [Individual(genotype_size, decode_fun, fit_fun, p_mut) for _ in range(pop_size)]
        self.p_cross = p_cross
        self.pop_size = pop_size
        self.cross_fun = cross_fun
        self.best_val = 0
        self.best_x = 0
        self.avg = []
        self.bests = []
        self.plot = plot
        self.best = None

    def calculate_fitness(self):
        for ind in self.population:
            ind.calculate_fitness()

    def crossing(self):

        cross_size = int(self.pop_size * self.p_cross)
        if cross_size % 2:
            cross_size -= 1
        ind_to_cross = random.sample(range(self.pop_size), cross_size)
        pairs_to_cross = [[ind_to_cross[i], ind_to_cross[int(i + cross_size // 2)]] for i in range(cross_size // 2)]
        for pair in pairs_to_cross:
            self.cross_fun(self.population[pair[0]], self.population[pair[1]])

    def mutation(self):
        for ind in self.population:
            ind.mutate()

    def create_new_population(self):
        fit_array = np.array([ind.fit_val for ind in self.population])
        best_ind = max(fit_array)
        if best_ind > self.best_val:
            self.best_val = best_ind
            best_index = np.where(fit_array == best_ind)[0][0]
            self.best_x = self.population[best_index].get_x()
            self.best = deepcopy(self.population[int(best_index)])

        self.bests.append(self.best_val)
        self.avg.append(sum(fit_array) / len(fit_array))

        # print  , self.best_x, self.best_val
        old_min = min(fit_array)
        old_range = max(fit_array) - old_min
        new_min = 0
        new_range = 1
        positive = np.array([float((n - old_min) / ((old_range * new_range) + new_min)) for n in fit_array])
        normalized = [float(i) / sum(positive) for i in positive]
        #a = sum(normalized)
        new_pop_nums = [np.random.choice(range(self.pop_size), p=normalized) for i in range(self.pop_size)]
        new_pop = [deepcopy(self.population[i]) for i in new_pop_nums]
        self.population = new_pop


from django.urls import path
from .views import *

app_name = 'usermanagement'

urlpatterns = [
    path('', login, name='login'),
    path('dashboard', dashboard, name='dashboard'),
    path('validate', login_validate, name='login_validate'),
    path('logout/', logout, name='logout'),
]


"""
    https://wikidocs.net/17114
    Q4 리스트 총합 구하기
"""

A = [20, 55, 67, 82, 45, 33, 90, 87, 100, 25]

"""
sum = 0
B = []
for a in A:
    if a>= 50:
        B.extend([a])
        sum += a
print("B:", B)
print("Sum:", sum)
"""

result = 0
B = []
while A:
    mark = A.pop()
    if mark >= 50:
        B.extend([mark])
        result += mark

print("B:", B)
print(result)


dadosTemp = dict()
cadastros = list()

while True:
    nome = input('Nome: ').strip().lower().capitalize()
    sexo = input('Sexo[M/F]: ').strip()[0]
    while sexo not in 'MF':
        sexo = input('Erro: Digite somente M ou F. Sexo[M/F]: ').strip()[0]
    idade = int(input('Idade: '))

    dadosTemp['nome'] = nome
    dadosTemp['sexo'] = sexo
    dadosTemp['idade'] = idade

    cadastros.append(dadosTemp.copy())

    resp = input('Deseja continuar[S/N]: ').strip()[0]
    while resp not in 'SN':
        resp = input('Erro: Somente digite S ou N. Deseja continuar[S/N]: ').strip()[0]

    if resp == 'N':
        break

print('-='*30)

s = 0

for c in cadastros:
    s += c['idade']

m = s / len(cadastros)

print(f'''A) Ao todo temos {len(cadastros)} cadastrada(s)
B) A média de idade é de {m:.2f} anos''')

print('C) As mulheres cadastradas são: ')
for c in cadastros:
    if c['sexo'] == 'F':
        print(f'    - {c["nome"]};')

print('\nD) Lista das pessoas que estão acima da média: ')
for c in cadastros:
    if c['idade'] > m:
        print(f'    nome = {c["nome"]}; sexo = {c["sexo"]}; idade = {c["idade"]}')

print('<<< Encerrado >>>')


import datetime

def message(msg):
    print("\n------------------- "+msg.title()+" -------------------\n")

def box_message(msg):
    s = "-" * (len(msg)+6)
    print(s + "\n|  "+msg.title()+"  |\n"+ s)

def transformDate(date):
    try:
        splitted = list(map(lambda item : int(item), date.split("-")))
        if(len(splitted) != 5):
            return None
        year = splitted[0]
        month = splitted[1]
        day = splitted[2]
        hour = splitted[3]
        minute = splitted[4]
        return datetime.datetime(year, month, day, hour, minute).strftime("%c")
    except:
      return None


import os
import sys
import socket
import hashlib

fp = sys.argv[1]
unix_sock_fp = sys.argv[2]

mtds = set()

f = open(fp)
lines = f.read().strip().splitlines()
for line in lines:
    line = line.strip()
    if line[0:2] != '0x':
        continue
    # 0x7fb8e7f840c0  com.facebook.FacebookRequestError$b     <init>  ()V     SourceFile      12      100101010101
    segs = line.split()
    mtd_sig = '/'.join(segs[1:4])
    mtds.add(hashlib.md5(mtd_sig.encode()).hexdigest())

sck = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sck.connect(unix_sock_fp)
sck.sendall(('{' + ','.join(mtds) + '}').encode())
sck.close()


import sys

horizon_n, vertical_n = map(int, sys.stdin.readline().split())
cut_N = int(input())

horizon_cut = [0, vertical_n]
vertical_cut = [0, horizon_n]

for i in range(cut_N):
    tmp = list(map(int, sys.stdin.readline().split()))
    if tmp[0]:
        vertical_cut.append(tmp[1])
    else:
        horizon_cut.append(tmp[1])

vertical_cut = sorted(vertical_cut)
horizon_cut = sorted(horizon_cut)

result = 0
for i in range(1, len(vertical_cut)):
    for j in range(1, len(horizon_cut)):
        width = vertical_cut[i] - vertical_cut[i-1]
        height = horizon_cut[j] - horizon_cut[j-1]
        result = max(result, width * height)

print(result)


import numpy
import scipy.linalg

from utils import utils

def compute_Sw_Sb(D, L):
    num_classes = L.max()+1
    D_c = [D[:, L==i] for i in range(num_classes)]
    n_c = [D_c[i].shape[1] for i in range(num_classes)]
    mu = utils.vcol(D.mean(1))
    mu_c = [utils.vcol(D_c[i].mean(1)) for i in range(len(D_c))]
    S_w, S_b = 0, 0
    for i in range(num_classes):
        DC = D_c[i] - mu_c[i]
        C_i = numpy.dot(DC, DC.T) / DC.shape[1]
        S_w += n_c[i] * C_i
        diff = mu_c[i] - mu
        S_b += n_c[i] * numpy.dot(diff, diff.T)
    S_w /= D.shape[1]
    S_b /= D.shape[1]
    # print(S_w)
    # print(S_b)
    return S_w, S_b

def project(base, D):
    return numpy.dot(base.T, D)

def LDA(D, L, m):
    """perform dimensionality reduction with LDA (supervised)

    Args:
        D : dataset
        L:  labels
        m : number of the dimension of the subspace of the original space (m must be smaller than #classes-1)

    Returns:
        original data projected on the subspace
    """
    S_w, S_b = compute_Sw_Sb(D, L)
    _, U = scipy.linalg.eigh(S_b, S_w)
    W = U[:, ::-1][:, :m]
    DP = project(W, D)
    return DP


# -*- coding:utf-8 -*-
__author__ = 'Jackie'

# import os
# import math
# from socket import *
# import logging
# import datetime
# import pickle
# import threading
# import sys
# from utils import constant as CONS

import random

if __name__ == "__main__":
    i = random.random()
    print(random.randrange(1, 100))
    print(i)


from src.futureLoc import futureLoc
import pytest
from unittest.mock import Mock, patch
from datetime import datetime
import requests

infoMessage = "On the 25/10/2023 at MLA airport: \n"
coldMessage = "It will be cold so you should wear warm clothing.\n"
warmMessage = "It will be warm so you should wear light clothing.\n"
rainMessage = "It is likely to rain so you do need an umbrella.\n\n"
norainMessage = "It is likely to not rain so you don't need an umbrella.\n\n"

@patch("builtins.input", side_effect=["MLA", datetime.today().strftime("%Y-%m-%d")])
def test_getFututreInfoValidInputs(mock_input):
    # Exercise
    airport_out, date_out = futureLoc.getFutureInfo()

    # Assert
    assert airport_out == "MLA"
    assert date_out.strftime("%Y-%m-%d") == datetime.today().strftime("%Y-%m-%d")

@patch(
    "builtins.input",
    side_effect=[
        "123",
        "airport",
        "MLA",
        "2023-10-25",
        "2024-10-26",
        datetime.today().strftime("%Y-%m-%d"),
    ],
)
def test_getFututreInfoInValidInputs(mock_input):
    # Exercise
    airport_out, date_out = futureLoc.getFutureInfo()

    # Assert
    assert airport_out == "MLA"
    assert date_out.strftime("%Y-%m-%d") == datetime.today().strftime("%Y-%m-%d")

@patch("requests.get")
def test_getFutureLocDataSuccess(mock_requests):
    # Setup
    mock_response = Mock()
    mock_response.status_code = 200
    mock_response.json.return_value = {
        "forecast": {
            "forecastday": {0: {"day": {"avgtemp_c": 12, "totalprecip_mm": 0}}}
        }
    }
    mock_requests.return_value = mock_response

    # Exercise
    temp, prec = futureLoc.getFutureLocData(
        "MLA", datetime.today().strftime("%Y-%m-%d")
    )

    # Assert
    assert temp == 12
    assert prec == 0

@patch("requests.get")
def test_getFutureLocDataStatusCodeFailure(mock_requests):
    # Setup
    mock_response = Mock()
    mock_response.status_code = 100
    mock_requests.return_value = mock_response

    # Exercise
    temp, prec = futureLoc.getFutureLocData(
        "MLA", datetime.today().strftime("%Y-%m-%d")
    )

    # Assert
    assert temp == None
    assert prec == None

@patch("requests.get")
def test_getFutureLocDataRequestFailure(mock_requests, capsys):
    # Setup
    mock_requests.side_effect = requests.exceptions.RequestException("Test Exception")

    # Exercise
    temp, prec = futureLoc.getFutureLocData(
        "MLA", datetime.today().strftime("%Y-%m-%d")
    )

    # Assert
    assert capsys.readouterr().out == "Error with WeatherAPI: Test Exception Exiting\n"
    assert temp == None
    assert prec == None

@pytest.mark.parametrize(
    "loc, date, temp, prec, output",
    [
        (
            "MLA",
            datetime(2023, 10, 25),
            12,
            0,
            infoMessage + coldMessage + norainMessage,
        ),
        ("MLA", datetime(2023, 10, 25), 12, 1, infoMessage + coldMessage + rainMessage),
        (
            "MLA",
            datetime(2023, 10, 25),
            16,
            0,
            infoMessage + warmMessage + norainMessage,
        ),
        ("MLA", datetime(2023, 10, 25), 16, 1, infoMessage + warmMessage + rainMessage),
    ],
)
def test_printMessage(loc, date, temp, prec, output, capsys):
    # Exercise
    futureLoc.printMessage(loc, date, temp, prec)

    # Assert
    assert capsys.readouterr().out == output


from django.urls import path

from .views import *

urlpatterns = [
    path('', BaseView.as_view(), name='base'),
    path('catalog/all', CatalogView.as_view(), name='catalog'),
    path('catalog/<str:slug>/', CategoryDetailView.as_view(), name='category_detail'),
    path('catalog/<str:ct_model>/<str:slug>/', ProductDetailView.as_view(), name='product_description'),
    path('brand/', brand_view, name='brand'),
    path('fabrics/', fabrics_view, name='fabrics'),
    path('contacts/', contacts_view, name='contacts'),
    path('how_to_order', how_to_order_view, name='how_to_order'),
    path('register/', RegisterView.as_view(), name='register'),
    path('login/', AuthenticationView.as_view(), name='login'),
    path('cart/', CartView.as_view(), name='cart'),
    path('add-to-cart/<str:ct_model>/<str:slug>', AddToCartView.as_view(), name='add_to_cart'),
    path('remove-from-cart/<str:ct_model>/<str:slug>', DeleteFromCartView.as_view(), name='delete_from_cart'),
    path('change-qty/<str:ct_model>/<str:slug>', ChangeQTYView.as_view(), name='change_qty'),
    path('checkout/', CheckoutView.as_view(), name='checkout'),
    path('make-order/', MakeOrderView.as_view(), name='make_order')
]


# 주소록 프로그램
# 2023-02-06
# DongHyun
# 예외처리!!
# 파일이 없을 때 발생하는 예외 - 예외 발생은 디버깅으로
# 입력시 개수가 다를 때
# 메뉴번호 입력 시 숫자외의 문자는 예외발생

import os # 운영체제용 모듈

# 2번
class Contact:
    # 생성자 - 이름, 전번, 이메일, 주소
    def __init__(self, name, phone_num, email, address) -> None:
        self.__name      = name
        self.__phone_num = phone_num
        self.__email     = email
        self.__address   = address

    #4번
    # __str__ 재정의
    def __str__(self) -> str:
        str_res = (f'이  름 : {self.__name}\n'
                   f'핸드폰 : {self.__phone_num}\n'
                   f'이메일 : {self.__email}\n'
                   f'주  소 : {self.__address}')
        return str_res

    # 11번 - 객체존재여부 확인
    def isNameExist(self, name):
        if self.__name == name:
            return True
        else:
            return False

    # 13. 각 멤버변수에 접근할 수 있는 함수
    # getName, getPhoneNum, getEmail, getAddress
    def getName(self) -> str:
        return self.__name

    def getPhoneNum(self) -> str:
        return self.__phone_num

    def getEmail(self) -> str:
        return self.__email

    def getAddress(self) -> str:
        return self.__address

# 5번 - 사용자입력
def set_contact():
    name, phone_num, email, address = input('정보입력(이름/전번/이메일/주소) : ').split('/')
    #    print(name, phone_num, email, address)
    # 7번 contact 객체 만들기
    contact = Contact(name = name, phone_num = phone_num, email = email, address = address)
    return(contact)

# 10번 - 주소록 출력
def get_contacts(list):
    for item in list:
        print(item)
        print('====================')

# 12번 - 주소록 삭제
def del_contact(list, name):
    count = 0 # 찾는 이름 카운트
    for i, item in enumerate(list): # 리스트 내에 것들을 순서대로 i에 나타내게 만들어줌
        if item.isNameExist(name):
            count += 1
            del list[i] # 리스트 삭제

    if count > 0: # 메세지 출력
        print('삭제했습니다.')
    else:
        print('주소록이 없습니다.')

# 14번 - 주소록 저장
def save_contacts(list):

    file = open('C:/Source/studyPython2023/project/contacts.txt', 'w', encoding = 'utf - 8')

    for item in list:
        text = f'{item.getName()}/{item.getPhoneNum()}/{item.getEmail()}/{item.getAddress()}'
        file.write(f'{text}\n')

    file.close() # 파일 입출력 시 마지막에 항상 종료!!@!@!@!@!#!@#@!#!@#!@#!@#

# 15번 - 주소록 읽어오기
def load_contacts(list):
    try:
        file = open('C:/Source/studyPython2023/project/contacts.txt', 'r', encoding = 'utf - 8')
    except Exception as e:
        f = open('C:/Source/studyPython2023/project/contacts.txt', 'w', encoding = 'utf - 8')
        f.close()
        return # 파일이 없는 경우 except문에 파일을 생성해준후 닫고 return으로 함수에서 탈출

    while True:
        line = file.readline().replace('\n','') # replace = 앞의 문자를 뒤의 문자로 대체

        if not line:
            break
        lines = line.split('/')
        contact = Contact(lines[0], lines[1], lines[2], lines[3])
        list.append(contact)

    file.close()

# 8번 기타: 화면 클리어
def clear_console():
    command = 'clear' # 리눅스나 유닉스 화면 클리어 명령어 = clear
    if os.name in ('nt', 'dos'): # Window 운영체제라면
        command = 'cls'
    os.system(command)

# 6번 메뉴표시
def get_menu():
    str_menu = ('주소록앱 v1.0\n'
                '1. 연락처 추가\n'
                '2. 연락처 출력\n'
                '3. 연락처 삭제\n'
                '4. 앱종료\n')
    print(str_menu)
    try:
        menu = int(input('메뉴 입력 : '))
    except Exception as e:
        menu = 0 # int형 숫자만 들어가면 함수는 다시 시작하니, 문자열을 넣게 되는 경우에 입력값이 0으로 변하게끔 예외처리를 했다.

    return menu

# 3번
def run():
    contacts = [] # 주소록을 담기위한 빈 리스트 생성
    load_contacts(contacts) # 주소록 읽어오기.
    clear_console() # 기타 8번
    while True:
        sel_menu = get_menu()
        if sel_menu == 1: # 9번 연락처추가
            try: # 연락처 입력 개수가 잘못되었을 때의 예외처리!!!
                contact = set_contact()
                contacts.append(contact)
                input('주소록 입력 성공') # 아무것도 안받는 입력
            except Exception as e:
                print('이름/전번/이메일/주소 순으로 입력하세요')
                input()
            finally:
                clear_console()

        elif sel_menu == 2:
            get_contacts(contacts)
            input('주소록 출력 완료') # 아무것도 안받는 입력
            clear_console()

        elif sel_menu == 3:
            name = input('삭제할 이름 입력 : ')
            del_contact(contacts, name)
            input()
            clear_console()

        elif sel_menu == 4: # 종료시 주소록 파일 저장
            save_contacts(contacts)
            break
        else:
            clear_console() # 기타 8번

    # temp = Contact('홍동현', '010-3204-5278',
    #                'tlxmscksals@naver.com', '경상남도 불라불라')
    # set_contact()

# 1번
if __name__ == '__main__':
#    print('주소록앱 시작합니다.')
    run()