#-*- coding: utf-8 -*-
from tkinter import *
from socket import *

class Ps_server:
    def __init__(self):
        self.ip = None
        self.port = None
        self.data = None
        self.c_sock = None

        self.root = Tk()
        self.root.geometry('300x300+250+250')

        self.et_ip = Entry(self.root,width=30)
        self.et_port = Entry(self.root,width=6)

        self.ip_label = Label(self.root,text='IP地址',width=10)
        self.port_label = Label(self.root,text='端口',width=10)

        self.bt_conn = Button(self.root,text='连接',width=5,
            height=1,command=self.connect,
            )
        self.bt_close = Button(self.root,text='断开',width=5,height=1,
            state='disable',
            command=self.close,
            )
        self.bt_get_info = Button(self.root,text='获取',width=5,height=1,
            state='disable',
            command=self.get_info
            )

        self.la_data = Label(self.root,text='信息...')

    def main(self):
        self.et_ip.place(x=0,y=0)
        self.ip_label.place(x=150,y=0)

        self.et_port.place(x=0,y=30)#下一行是下一个输入框
        self.port_label.place(x=50,y=30)

        self.bt_conn.place(x=0,y=60)
        self.bt_close.place(x=100,y=60)
        self.bt_get_info.place(x=200,y=60)

        self.la_data.place(x=0,y=110)
        self.root.mainloop()

    def connect(self):
        self.ip = self.et_ip.get()#获取输入框的文本
        self.port = self.et_port.get()
        print('ip:',self.ip)
        print('port:',self.port)
        if not self.ip and not self.port :
            self.la_data['text'] = '输入有效信息...'
            return
        self.la_data['text'] = '正在连接...'
        self.c_sock = socket(AF_INET,SOCK_STREAM)
        try:
            self.c_sock.connect((self.ip,int(self.port)))
        except Exception as e:
            print(e)
            self.la_data['text'] = '连接失败...'
        else:
            self.bt_close['state'] = 'active'
            self.bt_get_info['state'] = 'active'
            self.la_data['text'] = '连接成功...'

    def close(self):
        self.c_sock.close()
        self.bt_close['state'] = 'disable'
        self.bt_get_info['state'] = 'disable'
        self.la_data['text'] = '连接断开...'

    def get_info(self):
        self.c_sock.send('cpu'.encode('utf-8'))
        data = self.c_sock.recv(1024).decode('utf-8')
        if not data:
            self.la_data['text'] = '远程主机关闭连接...'
        self.la_data['text'] = data

ps = Ps_server()
ps.main()


from cafle import Account
from functools import partial

from astn0_index import idx
from astn1_account import acc

loan = Account(idx)
with loan as l:
    l.mtrt = idx.mtrt
    l.idxfn = idx.loan
    l.is_wtdrbl = False
    l.is_repaid = False

loan.ntnl = loan.subacc('ntnl')
with loan.ntnl as l:
    l.amt = 65_000
    l.subscd(loan.idxfn[0], l.amt)
    l.addscd(loan.idxfn[-1], l.amt)

loan.IR = loan.subacc('IR')
with loan.IR as l:
    l.rate = 0.08
    l.cycle = 1
    l.rate_cycle = l.rate / 12 * l.cycle

loan.fee = loan.subacc('fee')
with loan.fee as l:
    l.rate = 0.02

#Estimate Loan Cost
def estimate_fee_amt(loan, idxno):
    if idxno == loan.idxfn[0]:
        feeamt = loan.ntnl.amt * loan.fee.rate
        loan.fee.addscd(idxno, feeamt, note='fee_amt')
        return feeamt
    return 0
loan.estimate_fee_amt = partial(estimate_fee_amt, loan)

def estimate_IR_amt(loan, idxno):
    if loan.is_wtdrbl is False:
        return 0
    if loan.is_repaid is True:
        return 0
    ntnlbal = -loan.ntnl.bal_strt[idxno]
    IRamt = ntnlbal * loan.IR.rate_cycle
    if IRamt > 0.0:
        loan.IR.addscd(idxno, IRamt, note='IR_amt')
        return IRamt
    return 0
loan.estimate_IR_amt = partial(estimate_IR_amt, loan)

#Withdraw Loan Amount
def set_loan_withdrawable(loan, idxno):
    if idxno == loan.idxfn[0]:
        loan.is_wtdrbl = True
loan.set_loan_withdrawable = partial(set_loan_withdrawable, loan)

def withdraw_ntnl_fixed(loan, acc, idxno):
    amt_wtdrw = loan.ntnl.scd_out[idxno]
    loan.ntnl.send(idxno, amt_wtdrw, acc, "withdraw loan")
loan.withdraw_ntnl_fixed = partial(withdraw_ntnl_fixed, loan)

#Pay Loan Costs
def pay_fee_amt(loan, acc, idxno):
    feeamt = loan.fee.scd_in[idxno]
    acc.send(idxno, feeamt, loan.fee, f"pay fee amt at {idxno}")
    return feeamt
loan.pay_fee_amt = partial(pay_fee_amt, loan)

def pay_IR_amt(loan, acc, idxno):
    IRamt = loan.IR.scd_in[idxno]
    acc.send(idxno, IRamt, loan.IR, f"pay IR amt at {idxno}")
    return IRamt
loan.pay_IR_amt = partial(pay_IR_amt, loan)

#Repay Loan Amount
def repay_ntnl_amt(loan, acc, idxno):
    #at maturity
    if idxno >= idx.loan[-1]:
        amt_scd_in = loan.ntnl.rsdl_in_cum[idxno]
        acc.send(idxno, amt_scd_in, loan.ntnl, "repay loan")
loan.repay_ntnl_amt = partial(repay_ntnl_amt, loan)

def setback_loan_unwithdrawable(loan, idxno):
    if idxno >= idx.loan[-1]:
        loan.is_wtdrbl = False
loan.setback_loan_unwithdrawable = partial(setback_loan_unwithdrawable, loan)


import urllib3 as ul3
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.chrome.options import Options
from tqdm import tqdm
import sys
import copy
import time

from redeem2DB import FundDB

'''
    股票基金评分排名系统
    url : http://fund.eastmoney.com/data/fundranking.html
'''
#============= Configer =======================
bar_lengh = 60

fund_types = ['股票型', '混合型', '债券型', '指数型']
#============ Global Data =====================
data_array = [] # 基金数据 , shape = (array, map)
data_date = {'month' : 0, 'day' : 0} # 基金数据获取日期
fundDB = FundDB() #赎回连接对象
#========= Rubbish Data =========================
remove_data = [] #被删除的基金
#============ Tools ===========================
def web_driver():
    '''浏览器驱动'''
    chrome_options = Options()
    chrome_options.add_argument('--headless')
    # 无头浏览
    browser = webdriver.Chrome(chrome_options=chrome_options)
    # 有头浏览
##    browser = webdriver.Chrome()
    return browser
def init_Rank_Sort(map_):
    '''Add&Init key-[rank] to Map'''
    map_['rank'] = 0
def combine_rank(orig_, rank):
    '''combine rank from [rank] to [orig_]'''
    for index,rank_ in enumerate(rank):
        for orig__ in orig_:
            if orig__['基金代码'] == rank_['基金代码']:
                orig__['rank'] += index
def wait_action(browser, name=None):
    if name == None: name = ''
    else: name = '['+str(name)+']'
    print(name+'Waiting for Reflesh ...')
    while(BeautifulSoup(browser.page_source, "html.parser").get_text().find('长时间不更新') != -1):
        ''' Waiting for Reflesh '''
        pass
    print('Reflesh Done.')
#============ Get Fund Detail =======================
url = "http://fund.eastmoney.com/data/fundranking.html"
browser = web_driver()
print('Getting page ==> ', url)
browser.get(url)

for fund_type in fund_types:
    print('Getting Fund Data (', fund_type, ') ...')
    lis = browser.find_elements_by_tag_name('li')
    for li in lis:
        soup = BeautifulSoup(li.text, "html.parser")
        if soup.get_text().find(fund_type)>-1:
            ActionChains(browser).click(li).perform()
            break
    wait_action(browser)

    soup = BeautifulSoup(browser.page_source, "html.parser")
    trs = soup.find(id='dbtable').tbody.findAll('tr')
    if len(trs) <= 50:
        ActionChains(browser).click(browser.find_element_by_id('showall')).perform()
        wait_action(browser, '点击<showall>')
        soup = BeautifulSoup(browser.page_source, "html.parser")
        trs = soup.find(id='dbtable').tbody.findAll('tr')

    # Data Date
    try:
        tr = trs[0]
        tds = tr.findAll('td')
        date = tds[4].get_text().replace(' ', '').split('-')
        data_date['month'] = int(date[0])
        data_date['day'] = int(date[1])
    except ValueError:
        data_date['month'] = 0
        data_date['day'] = 0
    if data_date['month'] == 0 or data_date['day'] == 0:
        print('ERROR : 未能获取数据时间！')
    else:
        print('数据时间 (' + fund_type + ') -->', data_date['month'], '月', data_date['day'], '日')

    #Scope
    for tr in tqdm(trs, ncols=bar_lengh):
    ##for tr in trs[:20]:
        tds = tr.findAll('td')
        detail_map = {}
        detail_map['基金代码'] = tds[2].get_text().replace(' ', '')
        detail_map['基金简称'] = tds[3].get_text().replace(' ', '')
        try:
            detail_map['日增长率'] = float(tds[7].get_text().replace(' ', '').replace('%', ''))
            detail_map['近1周'] = float(tds[8].get_text().replace(' ', '').replace('%', ''))
            detail_map['近1月'] = float(tds[9].get_text().replace(' ', '').replace('%', ''))
            detail_map['近3月'] = float(tds[10].get_text().replace(' ', '').replace('%', ''))
        except ValueError:
            continue
        try:
            detail_map['近6月'] = float(tds[11].get_text().replace('---', '').replace(' ', '').replace('%', ''))
        except ValueError:
            detail_map['近6月'] = 0
        try:
            detail_map['近1年'] = float(tds[12].get_text().replace('---', '').replace(' ', '').replace('%', ''))
        except ValueError:
            detail_map['近1年'] = 0
        try:
            detail_map['近2年'] = float(tds[13].get_text().replace('---', '').replace(' ', '').replace('%', ''))
        except ValueError:
            detail_map['近2年'] = 0
        try:
            detail_map['近3年'] = float(tds[14].get_text().replace('---', '').replace(' ', '').replace('%', ''))
        except ValueError:
            detail_map['近3年'] = 0
        try:
            detail_map['今年来'] = float(tds[15].get_text().replace('---', '').replace(' ', '').replace('%', ''))
        except ValueError:
            detail_map['今年来'] = 0
        try:
            detail_map['成立来'] = float(tds[16].get_text().replace('---', '').replace(' ', '').replace('%', ''))
        except ValueError:
            detail_map['成立来'] = 0
        try:
            detail_map['手续费'] = float(tds[18].get_text().replace('---', '').replace(' ', '').replace('%', ''))
        except ValueError:
            detail_map['手续费'] = 100

        data_array.append(detail_map)

browser.quit()

#============== 加入赎回手续费 ===================================
url = "http://tools.fund.10jqka.com.cn/calculator/redeem.html"
browser = web_driver()
print('Getting page ==> ', url)
browser.get(url)
print('Adding Redemption Rates:')
#Scope
for map_ in tqdm(data_array, ncols=bar_lengh):
##for map_ in data_array:
    rate = None #赎回费率初始化
    rate = fundDB.get_redeem_by_code(map_['基金代码'])
    if rate == None:
        elem = browser.find_element_by_id('hqjij')
        elem.clear()
        elem.send_keys(map_['基金代码'])
        clock = time.clock()
        while True:
            if time.clock()-clock > 5 : break
            soup = BeautifulSoup(browser.page_source, "html.parser")
            if soup.find(id='hqjij').previous_sibling['style'] != 'left: 0px; top: 21px; width: 214px; z-index: 9999; display: none;':
                break

        promoteDis_1 = BeautifulSoup(browser.page_source, "html.parser").find(id='promoteDis')
        clock = time.clock()
        while True:
            if time.clock()-clock > 5 : break
            if promoteDis_1 != None:
                if BeautifulSoup(browser.page_source, "html.parser").find(id='promoteDis') != None \
                and BeautifulSoup(browser.page_source, "html.parser").find(id='promoteDis').get_text() != promoteDis_1.get_text():
                    break
            elif BeautifulSoup(browser.page_source, "html.parser").find(id='promoteDis') != None:
                break
            elem.send_keys(Keys.RETURN)

        soup = BeautifulSoup(browser.page_source, "html.parser")
        trs = soup.find(id='promoteDis').table.tbody.find_all('tr')
        trs = trs[1:]

        for tr in trs:
            try:
                rate_temp = float(tr.find_all('td')[1].get_text().replace('%','').replace(' ',''))
                if rate == None or rate < rate_temp:
                    rate = rate_temp
            except ValueError:
                pass

        if rate != None:
            fundDB.insert_redeem(map_['基金代码'], rate)

    if rate != None:
        map_['赎回费率'] = rate
    else:
        remove_data.append(copy.deepcopy(map_))
        del map_

fundDB.close()
browser.quit()

#============== Rank ============================================
for map_ in data_array:
    init_Rank_Sort(map_)

日增长率_sorted = sorted(data_array, key=lambda x : x['日增长率']-x['手续费']-x['赎回费率'], reverse=True)
近1周_sorted = sorted(data_array, key=lambda x : x['近1周']-x['手续费']-x['赎回费率'], reverse=True)
近1月_sorted = sorted(data_array, key=lambda x : x['近1月']-x['手续费']-x['赎回费率'], reverse=True)
近3月_sorted = sorted(data_array, key=lambda x : x['近3月']-x['手续费']-x['赎回费率'], reverse=True)
近6月_sorted = sorted(data_array, key=lambda x : x['近6月']-x['手续费']-x['赎回费率'], reverse=True)
近1年_sorted = sorted(data_array, key=lambda x : x['近1年']-x['手续费']-x['赎回费率'], reverse=True)
近2年_sorted = sorted(data_array, key=lambda x : x['近2年']-x['手续费']-x['赎回费率'], reverse=True)

combine_rank(data_array, 日增长率_sorted)
combine_rank(data_array, 近1周_sorted)
combine_rank(data_array, 近1月_sorted)
combine_rank(data_array, 近3月_sorted)
combine_rank(data_array, 近6月_sorted)
combine_rank(data_array, 近1年_sorted)
combine_rank(data_array, 近2年_sorted)

total_rank = sorted(data_array, key=lambda x : x['rank'])
print('=========================== Rank ======================================')
for index,item in enumerate(total_rank):
    print(index, item['基金代码'], item['基金简称'], item['rank'])

#=========== GUI for Search ======================
import tkinter as tk

root = tk.Tk()
root.title('股票基金评分排名')

def entry_Return(event):
    button_action()
entry = tk.Entry(root)
entry.bind('<Return>', entry_Return)
entry.grid(row=0, column=2)

def button_action():
    try:
        if int(entry.get()) >= len(total_rank):
            label['text'] = 'Sorry!No found.'
        else:
            detail = total_rank[int(entry.get())]
            label['text'] = 'rank:' + entry.get() + '\n'\
                            + '基金代码:' + str(detail['基金代码']) + '\n'\
                            + '基金简称:' + str(detail['基金简称']) + '\n'\
                            + '日增长率:' + str(detail['日增长率']) + '%\n'\
                            + '近1周:' + str(detail['近1周']) + '%\n'\
                            + '近1月:' + str(detail['近1月']) + '%\n'\
                            + '近3月:' + str(detail['近3月']) + '%\n'\
                            + '近6月:' + str(detail['近6月']) + '%\n'\
                            + '近1年:' + str(detail['近1年']) + '%\n'\
                            + '近2年:' + str(detail['近2年']) + '%\n'\
                            + '手续费:' + str(detail['手续费']) + '%\n'\
                            + '赎回费率:' + str(detail['赎回费率']) + '%'

    except ValueError:
        label['text'] = "Please input correct 'Number' !"
button = tk.Button(root, text='Check', command=button_action)
button.grid(row=0, column=3)

def button_code_action():
    code = ''
    try:
        int(entry.get())
        code = entry.get()
    except ValueError:
        code = 0
    detail = None
    rank_index = '---'
    for index,fund in enumerate(total_rank):
        if str(fund['基金代码']) == code:
            detail = fund
            rank_index = index
    if rank_index == '---':
        label['text'] = 'Sorry!No found.'
    else:
        label['text'] = 'rank:' + str(rank_index) + '\n'\
                        + '基金代码:' + str(detail['基金代码']) + '\n'\
                        + '基金简称:' + str(detail['基金简称']) + '\n'\
                        + '日增长率:' + str(detail['日增长率']) + '%\n'\
                        + '近1周:' + str(detail['近1周']) + '%\n'\
                        + '近1月:' + str(detail['近1月']) + '%\n'\
                        + '近3月:' + str(detail['近3月']) + '%\n'\
                        + '近6月:' + str(detail['近6月']) + '%\n'\
                        + '近1年:' + str(detail['近1年']) + '%\n'\
                        + '近2年:' + str(detail['近2年']) + '%\n'\
                        + '手续费:' + str(detail['手续费']) + '%\n'\
                        + '赎回费率:' + str(detail['赎回费率']) + '%'

button_code = tk.Button(root, text='Code', command=button_code_action)
button_code.grid(row=0, column=4)

label = tk.Label(root)
label.grid(row=1, column=2, columnspan=3)

root.mainloop()


"""Streaming video with face recognition."""
# ----------------------------------------------
# --- Author         : Hani YOUSFI
# --- Mail           : haniyousfi@gmail.com
# --- Date           : 10th May 2018
# ----------------------------------------------

import cv2

recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read('trainer/trainer.yml')
cascadePath = "Cascades/haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascadePath)

font = cv2.FONT_HERSHEY_SIMPLEX
# Iniciate id counter
id = 0

# names related to ids: example ==> Marcelo: id=1,  etc
names = ['None']

class VideoCamera(object):
    def __init__(self):
        # Capturing video from camera 0, if you face troubles, change the
        # camera index or use a saved video.
        self.video = cv2.VideoCapture(0)
        self.video.set(3, 640)  # Set video widht
        self.video.set(4, 480)  # Set video height
        # If you're using a video.mp4, you must have this file in the folder
        # as the main.py and uncomment the following line
        # self.video = cv2.VideoCapture('video.mp4')

    def __del__(self):
        self.video.release()

    def get_frame(self):
        success, image = self.video.read()
        # I'm using Motion JPEG, but OpenCV defaults to capture raw images,
        # so we must encode it into JPEG in order to correctly display the
        # video stream.

        # Define min window size to be recognized as a face
        minW = 0.1*self.video.get(3)
        minH = 0.1*self.video.get(4)
        while True:
            gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

            faces = \
                faceCascade.detectMultiScale(gray, scaleFactor=1.2,
                                             minNeighbors=5,
                                             minSize=(int(minW), int(minH)),)
            for(x, y, w, h) in faces:
                cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
                id, confidence = recognizer.predict(gray[y:y+h, x:x+w])

            # Check if confidence is less them 100 ==> "0" is perfect match
                if (confidence < 100):
                    id = names[id]
                    confidence = "  {0}%".format(round(100 - confidence))
                else:
                    id = "unknown"
                    confidence = "  {0}%".format(round(100 - confidence))

                cv2.putText(image, str(id), (x+5, y-5),
                            font, 1, (255, 255, 255), 2)
                cv2.putText(image, str(confidence), (x+5, y+h-5),
                            font, 1, (255, 255, 0), 1)
            ret, jpeg = cv2.imencode('.jpg', image)
            return jpeg.tobytes()


import os
from copy import deepcopy
from typing import List

from to_typescript.core.filter import FilterAbstract
from to_typescript.core.transform.extra_rules import ClassInheritance
from to_typescript.filters.function_save import FilterFunctionSave

class FilterOOPSave(FilterAbstract):
    FILE_STARTER = FilterFunctionSave.FILE_STARTER
    DUMP_FOLDERS = dict(server='output/server/oop',
                        client='output/client/oop',
                        client_gui='output/client/oop/gui')

    imports = FilterFunctionSave.imports

    @staticmethod
    def shift_lines(text: str, spaces: int) -> str:
        return '\n'.join(
            ' ' * spaces + line if line else line
            for line in text.split('\n')
        )

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

        self.imports = deepcopy(self.imports)
        for key in self.imports['shared']:
            self.imports['client'].append(key)
            self.imports['server'].append(key)

    @staticmethod
    def get_class_begin(class_name: str, generic_string: str) -> str:
        inherit = ClassInheritance(class_name).get_child()
        if inherit:
            inherit_inline = f' extends {inherit}'
        else:
            inherit_inline = ''

        return f'''
/** @customConstructor {class_name} */
export class {class_name}{generic_string}{inherit_inline} {{
'''

    @staticmethod
    def get_class_end() -> str:
        return '}\n'

    def save_file_category(self,
                           class_name: str, side: str,
                           fields: List[str],
                           methods: List[str],
                           class_templates: List[str]):
        if not fields and not methods:
            return

        is_gui = class_name.startswith('Gui')
        cache_file = os.path.join(
            self.DUMP_FOLDERS[side + ('_gui' if is_gui else '')],
            f'{class_name}.d.ts'
        )

        imports: List[str] = deepcopy(self.imports[side])
        if class_name in imports:
            imports.remove(class_name)

        class_started = self.get_class_begin(class_name,
                                             '\n'.join(class_templates))

        text = (
                self.FILE_STARTER +
                FilterFunctionSave.generate_imports(imports, (
                    '../' if is_gui else '') + '../structure') +
                class_started
        )
        if fields:
            text += self.shift_lines('\n\n'.join(fields), 4) + '\n\n'
        if methods:
            text += self.shift_lines('\n\n'.join(methods), 4) + '\n'
        text += self.get_class_end()

        with open(cache_file, 'w', encoding='UTF-8', newline='\n') as cache:
            cache.write(text)

    def apply(self):
        for key in self.DUMP_FOLDERS:
            folder = self.DUMP_FOLDERS[key]
            if not os.path.exists(folder):
                os.mkdir(folder)

        # TODO: move into Context method
        keys = set(self.context.declarations.oop_methods.keys())
        keys.update(set(self.context.declarations.oop_fields.keys()))

        for key in sorted(keys):
            for side in ['client', 'server']:
                self.save_file_category(
                    class_name=key,
                    side=side,
                    fields=self.context.declarations.oop_fields[key].get(
                        side,
                        []
                    ),
                    methods=self.context.declarations.oop_methods[key].get(
                        side,
                        []
                    ),
                    class_templates=self.context.declarations
                                        .oop_class_templates[key].get(
                                            side,
                                            []
                                        ),
                )

        print('Generated .d.ts files with OOP\u001b[0m')


from pathlib import Path
import os
import pandas as pd

def by_condition(*args, dataset=None, output=None):
    import math
    import pandas as pd

    # Create condition name list
    condition_names = [arg.name for arg in args]

    # Use condition names to create a condition:level dataframe
    conditions = pd.DataFrame(columns=condition_names)
    for i in condition_names:
        conditions[i] = data[i]

    # Merge all conditions into line by line tuples and add to dataset
    tup_list = list(tuple(conditions.itertuples(index=False, name=None)))
    data['all_conds'] = tup_list

    # Remove nan values and zero tuples (if any exist)
    nonan = [t for t in tup_list if not any(isinstance(n, float) and math.isnan(n) for n in t)]
    nozero = [i for i in nonan if 0 not in i]

    # Define and sort the unique iterations of your conditions
    unique = list(set(nozero)); unique.sort()

    keys = list(output.keys())
    for i, level in enumerate(unique):
        output[keys[i]] = data[data['all_conds'] == level]

    return output

# Load in your data
data = pd.read_csv(os.path.join(Path.cwd(), 'r-inputs', 'sub-01_peaks.csv'))

# Create a Dictionary of DataFrames for your split data
peaks = dict({'S01R01':pd.DataFrame(),'S01R02':pd.DataFrame(),'S01R03':pd.DataFrame(),
              'S02R01':pd.DataFrame(),'S02R02':pd.DataFrame(),'S02R03':pd.DataFrame(),
              'S03R01':pd.DataFrame(),'S03R02':pd.DataFrame(),'S03R03':pd.DataFrame(),
              'S04R01':pd.DataFrame(),'S04R02':pd.DataFrame(),'S04R03':pd.DataFrame(),})

# Call function listing each of your conditions, full dataset, and new output dict
split_data = by_condition(data['sound_factor'], data['repetition_factor'], dataset=data, output=peaks)


from langchain.agents import create_sql_agent
from langchain.agents.agent_toolkits import SQLDatabaseToolkit
from langchain.utilities.sql_database import SQLDatabase
from tests.unit_tests.llms.fake_llm import FakeLLM

def test_create_sql_agent() -> None:
    db = SQLDatabase.from_uri("sqlite:///:memory:")
    queries = {"foo": "Final Answer: baz"}
    llm = FakeLLM(queries=queries, sequential_responses=True)
    toolkit = SQLDatabaseToolkit(db=db, llm=llm)

    agent_executor = create_sql_agent(
        llm=llm,
        toolkit=toolkit,
    )

    assert agent_executor.run("hello") == "baz"


import os
import pickle
import torch
import numpy

NUM_SNIPPETS = 50

class DatasetConverter:
    @staticmethod
    def convert_pickles(path: str):
        dir_list = os.listdir(path)
        for dir_file in dir_list:

            if '.pkl' in dir_file:
                print("Opening {0}".format(dir_file))
                pkl = open(path + '/' + dir_file, 'rb')
                header = pickle.load(pkl)
                dataset = pickle.load(pkl)
                pkl.close()

                properties = dir_file.split('_')
                task = properties[1]
                if task is "T0":
                    size = properties[3]
                    type = properties[4].split('.')[0]
                else:
                    size = properties[3].split('.')[0]
                    type = "train"

                print("Converting...")
                torch_data = []
                torch_snippet = []

                if not isinstance(dataset[0], torch.Tensor):
                    # convert to torch tensors
                    images = torch.from_numpy(numpy.array(dataset[0])).permute(0, 2, 3, 1)
                    labels = torch.from_numpy(numpy.array(dataset[1]))
                else:
                    images = dataset[0]
                    labels = dataset[1]

                torch_data.append(images)
                torch_data.append(labels)
                part_images = images[:NUM_SNIPPETS].clone()
                part_labels = labels[:NUM_SNIPPETS].clone()
                torch_snippet.append(part_images)
                torch_snippet.append(part_labels)

                torch.save(torch_data, path + '/' + "SE_" + task + "_" + size + "_" + type + "_" + "full.set")
                torch.save(torch_snippet, path + '/' + "SE_" + task + "_" + size + "_" + type + "_" + "snippet.set")

                os.remove(path + '/' + dir_file)

    @staticmethod
    def change_snippet_size(path: str):
        dir_list = os.listdir(path)
        for dir_file in dir_list:
            if '.set' in dir_file and 'snippet' in dir_file:
                print("Removed.")
                os.remove(path + dir_file)

        for dir_file in dir_list:
            if '.set' in dir_file:
                print("Opening {0}".format(dir_file))
                dataset = torch.load(path + dir_file)

                properties = dir_file.split('_')
                task = properties[1]
                size = properties[2]
                type = properties[3]
                part = properties[4].split('.')[0]

                print("Converting...")
                images = dataset[0]
                labels = dataset[1]
                instance_ids = dataset[2]
                examples = dataset[3]

                # create a snippet containing NUM_SNIPPETS trajectories:
                last_id = torch.sum(examples[:NUM_SNIPPETS])
                torch_snippet = [images[:last_id].clone(),
                                 labels[:last_id].clone(),
                                 instance_ids[:last_id].clone(),
                                 examples[:NUM_SNIPPETS].clone()]

                torch.save(torch_snippet, path + "SE_" + task + "_" + size + "_" + type + "_" + "snippet.set")

if __name__ == '__main__':
    DatasetConverter.change_snippet_size('./data/eval/')
    print("Done.")


# Integer Break Problem
# Dynamic Programming approach
# Rescusive solution could be done using dfs but not effective

"""
n   1 2 3 4
dp  1 2 3 4 (dp should never be less than n, hence we can use the product or the num itself)

"""
class Solution:
    def integerBreak(self, n: int) -> int:
        dp = {1:1} # Base conditon 1 -> 1

        for num in range(2,n+1):
            dp[num] = 0 if num == n else num # if condition is to not to break into sub problems
            for i in range(1,num):
                a = dp[i]*dp[num-i]
                dp[num] = max(dp[num],a)
        return dp[num]


#####################################################################################
#extract.py
#Authors: Revanth Pobala and Hussain Mucklai.
#This project is about the Testing of Lilac(Lightweight low latency anonymous chat)
#This program will provide the graph for cdf(Cumulative Distribution function)
#####################################################################################
import os
import matplotlib.pyplot as plt
from pylab import *
from scipy.stats import norm
import matplotlib.patches as mpatches
from bisect import bisect_left

class discrete_cdf:
    def __init__(self,data):
        self._data = data # must be sorted
        self._data_len = float(len(data))

    def __call__(self,point):
        return (len(self._data[:bisect_left(self._data, point)]) /
                self._data_len)

class extract():

    def __init__(self):
        self.to_draw = []

    def read_from_file(self,filename):
        file = open(filename,'rw')
        return file

    def merge_files(self):
        os.system('cat /home/revanth/Projects/workspace/Lilac_Testing/src/users/logs/*.txt >/home/revanth/Projects/workspace/Lilac_Testing/src/Results/finalfile.log')

    def add_to_dict(self):
        items = {}
        graph_values = []
        to_draw = []
        median = []
        sum = 0
        file = extract.read_from_file('finalfile.log')
        for i in file.readlines():
            if len(i.strip()) != 0:
                content = i.split(',')
                msg = content[0].strip()
                Time = float(str(content[1].strip()))
                if msg not in items:
                    items[msg] = []
                items[msg].append(Time)

        for i in items:
            for j in items[i]:
                graph_values.append(float(max(items[i])- min(items[i])))
        #graph_values = set(graph_values)
        for i in graph_values:
            if i >= 1.5:
                to_draw.append(i*0.1)
                sum = sum+i
        avg = np.average(sum)/len(to_draw)*0.1
        #plt.plot(0,avg)
        self.to_draw = np.array(to_draw)
        anthax =  np.arange(0,len(to_draw))
        plt.plot(anthax, self.to_draw, '-')
        plt.ylabel('Time (Seconds)')
        plt.xlabel('Number of Messages')
        plt.title(r'Time  vs Number of messages')
        plt.show()

    def draw_cdf(self):
        self.to_draw = sort(self.to_draw)
        #print self.to_draw
        cdf = discrete_cdf(self.to_draw)
        xvalues =  np.arange(0,6)
        yvalues = [cdf(point) for point in xvalues]
        plt.plot( yvalues)
        #plt.xticks(xvalues)
       # red_patch = mpatches.Patch(color='green', label='')
       # plt.legend(handles=[red_patch])
        plt.title(r'Cumulative Distribution Function')
        plt.ylabel('cdf of messages')
        plt.xlabel('Time')
        plt.show()

extract =  extract()
extract.merge_files()
extract.add_to_dict()
extract.draw_cdf()