import time
from Base.base import Base
from Base.OperExcel import write_xlsBycolName_append
from selenium import webdriver
from selenium.webdriver.common.by import By
from Data.DataMgnt.TestResult import TestResultOper as TR
from Base import ReadConfig
from Base.SysPara import SysPara as sp
from PageObj.ngboss.mainpage import MainPage
from PageObj.ngboss.login_page import LoginPage
from Base.Mylog import LogManager
from Check.PageCheck import PageAssert
from Common.TestAsserts import Assertion as Assert
from Common.function import getDigitFromStr
from PageObj.order.BizCommon.ElementPartBase import MainPlanSelectPart
from PageObj.order.BizCommon.ElementPartBase import DealUserCommon
from PageObj.order.BizCommon.ElementPartBase import SelectElements
from PageObj.order.BizCommon.ElementPartBase import PageCommonPart
from Check.RuleCheck import RuleCheckBefore
from Check.DataCheck import DataCheck as Dc

# logger = LogManager('test').get_logger_and_add_handlers(1,is_add_stream_handler=True, log_path=ReadConfig.log_path, log_filename=time.strftime("%Y-%m-%d")+'.log' )
logger = LogManager('ProdChangePage').get_logger_and_add_handlers(1, log_path=ReadConfig.log_path, log_filename=time.strftime("%Y-%m-%d")+'.log' )

class ProdChangePage(Base):
    def open_base(self):
        # self.driver.get(rc.get_ngboss('url'))
        self.driver.maximize_window()

    def openProductChange(self):
        LoginPage(self.driver).login()  # 登录
        # MainPage(self.driver).open_CataMenu('crm9000', 'crm9200', 'crmw912',menuPath='page/order.page.pc.person.changeproduct.ChangeProduct')  # 进入产品变更页面
        MainPage(self.driver).open_CataMenuNew(funcId='crm9231')
        logger.info('进入产品变更页面')

    def backProdChgPage(self):
        '''新增优惠、服务元素后点击返回'''
        loc_backPopup = (By.XPATH,'//*[@id="elementListpopup-ItemList"]/div[1]/div[1]')
        self.isElementDisplay(loc_backPopup,'click')

    def acceptChgMainProduct(self,accessNum,productId,elementList=[],scene='ChgMainProduct'):
        '''
        个人业务-变更主产品
        :param accessNum:服务号码
        :param productId:主产品编码
        :param elementList:可选组、必选组元素列表
        :return:
        '''
        title = '主产品变更测试记录%s' % accessNum
        self.add_dochead(title)
        self.openProductChange()
        self.screen_step("进入产品变更菜单")
        authUser = DealUserCommon(self.driver).AuthUserInfo(accessNum) #用户鉴权,包含了用户鉴权都结果和规则校验信息
        Assert().assertTrue(authUser['IsAuthSuc'],msg='用户鉴权失败')   #做个鉴权认证
        self.screen_step("点击变更按钮")
        Btn_changeProduct = (By.ID,'changeButton')
        self.isElementDisplay(Btn_changeProduct,'click') #点击产品变更按钮
        self.sleep(1)
        self.screen_step("选择主套餐")
        MainPlanSelectPart(self.driver).MainProductSel(productId,elementList)
        RuleCheckBefore(self.driver).checkRule(scene) #规则校验
        PageCommonPart(self.driver).submit() #点击提交
        submitMsg = PageAssert(self.driver).assertSubmit()
        if Assert().verifyassertIn('业务受理成功',submitMsg):
            Dc().dealMainOrder(orderId=getDigitFromStr(submitMsg)) #处理主订单，如果状态是Y或者X 修改成0
        logger.info('业务受理信息：{}'.format(submitMsg))
        self.screen_step('点击提交,受理信息：{}'.format(submitMsg))
        self.save_docreport(title)
        return submitMsg

    def acceptAddElements(self,accessNum,elementList=[],scene='AddElements'):
        '''
        个人业务-新增服务
        :param accessNum:服务号码
        :param productId:主产品编码
        :param elementList:资费和服务列表
        字典数组，包含 OFFER_CODE 和 Offer_type 2个key
        eg :[{"OFFER_CODE":"120000008174","OFFER_TYPE":"S"},{"OFFER_CODE":"120010122813","OFFER_TYPE":"D"}]
        :return:
        '''
        title = '新增资费_服务测试记录%s' % accessNum
        self.add_dochead(title)
        self.openProductChange()
        self.screen_step("进入产品变更菜单")
        authUser = DealUserCommon(self.driver).AuthUserInfo(accessNum) #用户鉴权,包含了用户鉴权都结果和规则校验信息
        # TR().updateRuleCheckInfo(sceneCode=scene,msg=authUser['msg'])
        Assert().assertTrue(authUser['IsAuthSuc'],msg='用户鉴权失败')   #做个鉴权认证
        #新增优惠按钮
        li_addElement = (By.ID,'addElement')
        self.isElementDisplay(li_addElement,'click')
        self.screen_step("选择资费或者服务订购")
        SelectElements(self.driver).addElements(elementList=elementList,scene=scene)
        self.backProdChgPage() #点击回到产品变更主页面
        PageCommonPart(self.driver).submit() #点击提交
        submitMsg = PageAssert(self.driver).assertSubmit()
        logger.info('业务受理信息：{}'.format(submitMsg))
        if Assert().verifyassertIn('业务受理成功',submitMsg):
            Dc().dealMainOrder(orderId=getDigitFromStr(submitMsg)) #处理主订单，如果状态是Y或者X 修改成0
            Dc().retOrderTrace(orderId=getDigitFromStr(submitMsg),route='jour42')
        self.screen_step('点击提交,受理信息：{}'.format(submitMsg))
        self.save_docreport(title)
        return submitMsg

    def acceptDelElements(self,accessNum,scene='DelElements',elementList=[],):
        '''
        个人业务-新增服务
        :param accessNum:服务号码
        :param productId:主产品编码
        :param elementList:资费和服务列表
        字典数组，包含 OFFER_CODE 和 Offer_type 2个key
        eg :[{"OFFER_CODE":"120000008174","OFFER_TYPE":"S"},{"OFFER_CODE":"120010122813","OFFER_TYPE":"D"}]
        :return:
        '''
        title = '删除资费_服务测试记录%s' % accessNum
        self.add_dochead(title)
        self.openProductChange()
        self.screen_step("进入产品变更菜单")
        authUser = DealUserCommon(self.driver).AuthUserInfo(accessNum) #用户鉴权,包含了用户鉴权都结果和规则校验信息
        # TR().updateRuleCheckInfo(sceneCode=scene,msg=authUser['msg'])
        Assert().assertTrue(authUser['IsAuthSuc'],msg='用户鉴权失败')   #做个鉴权认证
        #删除资费或者服务
        self.screen_step("选择资费或者服务删除")
        SelectElements(self.driver).delElements(elementList)
        PageCommonPart(self.driver).submit() #点击提交
        submitMsg = PageAssert(self.driver).assertSubmit()
        logger.info('业务受理信息：{}'.format(submitMsg))
        if Assert().verifyassertIn('业务受理成功',submitMsg):
            Dc().dealMainOrder(orderId=getDigitFromStr(submitMsg)) #处理主订单，如果状态是Y或者X 修改成0
        self.screen_step('点击提交,受理信息：{}'.format(submitMsg))
        self.save_docreport(title)
        return submitMsg

if __name__ == '__main__':
    driver = webdriver.Chrome()
    test = ProdChangePage(driver)
    # test.acceptChgMainProduct(accessNum='15874139293',productId='99913849',elementList=[{"OFFER_CODE":"99650338","OFFER_TYPE":"D"}]) #必选优惠列表
    # test.acceptAddElements(accessNum='18229967646',elementList=[{"OFFER_CODE":"18013676","OFFER_TYPE":"S"},{"OFFER_CODE":"18009531","OFFER_TYPE":"D"}],scene='AddElements')
    test.acceptDelElements(accessNum='15111048902',elementList=[{"OFFER_CODE":"204","OFFER_TYPE":"S"}])


# kMeans object tracking
import cv2
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans

cap = cv2.VideoCapture(0)

#orange = np.uint8([[[255,69,0 ]]])
#hsv_orange = cv2.cvtColor(orange,cv2.COLOR_BGR2HSV)
#print(hsv_orange)

while(1):

    # Take each frame
    ret, frame = cap.read()
    img = cv2.cvtColor(frame[200:400, 200:400], cv2.COLOR_BGR2RGB)
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    img = img.reshape((img.shape[0] * img.shape[1],3)) #represent as row*column,channel number
    clt = KMeans(n_clusters=3) #cluster number
    clt.fit(img)

    # gaussian filter
    # frameBlur = cv2.GaussianBlur(frame,(5,5),0)

    # define range of color in HSV
    lower_hsv = np.array([145,100,150])
    upper_hsv = np.array([175,255,255])

    # Threshold the HSV image to get only desired colors
    mask = cv2.inRange(hsv, lower_hsv, upper_hsv)
    contours,hierarchy = cv2.findContours(mask, 1, 2)

    # Bitwise-AND mask and original image
    res = cv2.bitwise_and(frame,frame, mask= mask)

    cnt = contours[0]
    M = cv2.moments(cnt)

    if M['m00'] != 0:
        cx = int(M['m10']/M['m00'])
        cy = int(M['m01']/M['m00'])
        cv2.rectangle(frame, (cx-5, cy-5), (cx+5, cy+5), (0, 255, 0))

    cv2.rectangle(frame, (200, 200), (400, 400), clt.cluster_centers_[0], thickness = 10)

    cv2.imshow('frame',frame)
    cv2.imshow('mask',mask)
    cv2.imshow('res',res)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cv2.destroyAllWindows()

img = cv2.imread("colors.jpg")
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

img = img.reshape((img.shape[0] * img.shape[1],3)) #represent as row*column,channel number
clt = KMeans(n_clusters=3) #cluster number
clt.fit(img)


import random as rnd
import math as m
import pandas as pd
import matplotlib.pyplot as plt
import time
timecheck0 =time.time()

# Начальные параметры
XMIN = 1
XMAX = 10
YMIN = 0
YMAX = 10
# Лямбда
H = 1E-5

# Задание вероятнойстей ядерной реакции
#   [0;rlim1] - ничего не происходит
#   (rlim1;rlim2] - поглощение нейтрона, пропадание частицы
#   (rlim2,1] - деление ядра и появление 2 новых нейронов
RLIM1 = 0.5
RLIM2 = 0.8

#N - начальное число частиц
N = 20
TIME = 600

#Контроль стержней
NTARGET = 10
K = 1

def creating_reactor(nnumber: int = 5):
    A = pd.DataFrame({'X': [], 'Y': []})
    for i in range(nnumber):
        x = XMIN + (XMAX - XMIN) * rnd.random()
        y = YMIN + (YMAX - YMIN) * rnd.random()
        A = A.append({'X': x, 'Y': y}, ignore_index=True)
    return A

def main():
    """Основной код программы
    """
    # Базовые функции контроля
    l = lambda h, r: -h * m.log(1 - r)
    control = lambda n: (RLIM2- RLIM1)*(1+K*(n-NTARGET)/NTARGET)

    control_RLIM2 = RLIM2
    # Создание реактора
    Reactor = creating_reactor(N)

    # Запуск деления
    tick = 0
    Rlen = N
    total_n = [Rlen]

    #Количество тиков, каждый тик - 1 дейтсвие всех нейтронов
    while tick < TIME and Rlen != 0 and len(
            Reactor.index) < 1000:

        # Перебор с конца
        nt = Rlen - 1

        # Проверка на включение и выключение системы контроля
        if Rlen< NTARGET: control_RLIM2 = control(Rlen)
        elif Rlen> NTARGET*2:control_RLIM2 = RLIM2

        #Перебор всех нейтронов
        while nt >= 0:

            x0 = Reactor.loc[nt].X
            y0 = Reactor.loc[nt].Y

            # Случайное направление движения
            fi = 0 + 2 * m.pi * rnd.random()
            r = rnd.random()
            x1 = x0 + l(H, r) * m.cos(fi)
            y1 = y0 + l(H, r) * m.sin(fi)

            # Выбираем случайный исход взаимодействия
            result = rnd.random()
            # Исправить на хранение изменений прямо в ячейке, без создания переменных x,y...
            if x1 > XMAX or x1 < XMIN or y1 < YMIN or y1 > YMAX:
                Reactor = Reactor.drop(index=nt)

            elif result <= RLIM1:
                Reactor.loc[nt].X = x1
                Reactor.loc[nt].Y = y1

            elif RLIM1 < result <= control_RLIM2:
                Reactor = Reactor.drop(index=nt)

            elif control_RLIM2 < result:
                Reactor.loc[nt].X = x1
                Reactor.loc[nt].Y = y1
                Reactor = Reactor.append({'X': x1, 'Y': y1}, ignore_index=True)
            nt -= 1

        Rlen = len(Reactor.index)
        Reactor.reset_index(drop=True, inplace=True)
        total_n.append(Rlen)
        tick += 1

    plt.figure(figsize=(10, 10), dpi=80, facecolor='w', edgecolor='k')
    plt.plot(total_n, label="$f(x)$")
    plt.show()
    timecheck1 =time.time()
    print(timecheck1-timecheck0)

main()


"""
Copyright (c) 2019 Intel Corporation

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

from pathlib import Path

from .annotation_converters import BaseFormatConverter, save_annotation, make_subset
from .config import ConfigValidator, StringField, PathField, ListField, DictField, BaseField, NumberField, ConfigError
from .utils import JSONDecoderWithAutoConversion, read_json, get_path, contains_all
from .representation import BaseRepresentation
from .data_readers import DataReaderField

class DatasetConfig(ConfigValidator):
    """
    Specifies configuration structure for dataset
    """
    name = StringField()
    annotation = PathField(optional=True, check_exists=False)
    data_source = PathField(optional=True, check_exists=False)
    dataset_meta = PathField(optional=True, check_exists=False)
    metrics = ListField(allow_empty=False, optional=True)
    postprocessing = ListField(allow_empty=False, optional=True)
    preprocessing = ListField(allow_empty=False, optional=True)
    reader = DataReaderField(optional=True)
    annotation_conversion = DictField(optional=True)
    subsample_size = BaseField(optional=True)
    subsample_seed = NumberField(floats=False, min_value=0, optional=True)

class Dataset:
    def __init__(self, config_entry):
        self._config = config_entry
        self.batch = 1
        self.iteration = 0
        dataset_config = DatasetConfig('Dataset')
        dataset_config.validate(self._config)
        annotation, meta = None, None
        use_converted_annotation = True
        self._images_dir = Path(self._config.get('data_source', ''))
        if 'annotation' in self._config:
            annotation_file = Path(self._config['annotation'])
            if annotation_file.exists():
                annotation = read_annotation(get_path(annotation_file))
                meta = self._load_meta()
                use_converted_annotation = False
        if not annotation and 'annotation_conversion' in self._config:
            annotation, meta = self._convert_annotation()

        if not annotation:
            raise ConfigError('path to converted annotation or data for conversion should be specified')

        subsample_size = self._config.get('subsample_size')
        if subsample_size:
            subsample_seed = self._config.get('subsample_seed', 666)
            if isinstance(subsample_size, str):
                if subsample_size.endswith('%'):
                    subsample_size = float(subsample_size[:-1]) / 100 * len(annotation)
            subsample_size = int(subsample_size)
            annotation = make_subset(annotation, subsample_size, subsample_seed)

        if use_converted_annotation and contains_all(self._config, ['annotation', 'annotation_conversion']):
            annotation_name = self._config['annotation']
            meta_name = self._config.get('dataset_meta')
            if meta_name:
                meta_name = Path(meta_name)
            save_annotation(annotation, meta, Path(annotation_name), meta_name)

        self._annotation = annotation
        self._meta = meta
        self.size = len(self._annotation)
        self.name = self._config.get('name')

    @property
    def annotation(self):
        return self._annotation

    def __len__(self):
        return self.size

    @property
    def metadata(self):
        return self._meta

    @property
    def labels(self):
        return self._meta.get('label_map', {})

    def __call__(self, context, *args, **kwargs):
        batch_annotation = self.__getitem__(self.iteration)
        self.iteration += 1
        context.annotation_batch = batch_annotation
        context.identifiers_batch = [annotation.identifier for annotation in batch_annotation]

    def __getitem__(self, item):
        if self.size <= item * self.batch:
            raise IndexError

        batch_start = item * self.batch
        batch_end = min(self.size, batch_start + self.batch)
        batch_annotation = self._annotation[batch_start:batch_end]

        return batch_annotation

    @staticmethod
    def set_image_metadata(annotation, images):
        image_sizes = []
        data = images.data
        if not isinstance(data, list):
            data = [data]
        for image in data:
            image_sizes.append(image.shape)
        annotation.set_image_size(image_sizes)

    def set_annotation_metadata(self, annotation, image, data_source):
        self.set_image_metadata(annotation, image.data)
        annotation.set_data_source(data_source)

    def _load_meta(self):
        meta_data_file = self._config.get('dataset_meta')
        return read_json(meta_data_file, cls=JSONDecoderWithAutoConversion) if meta_data_file else None

    def _convert_annotation(self):
        conversion_params = self._config.get('annotation_conversion')
        converter = conversion_params['converter']
        annotation_converter = BaseFormatConverter.provide(converter, conversion_params)
        annotation, meta = annotation_converter.convert()

        return annotation, meta

def read_annotation(annotation_file: Path):
    annotation_file = get_path(annotation_file)

    result = []
    with annotation_file.open('rb') as file:
        while True:
            try:
                result.append(BaseRepresentation.load(file))
            except EOFError:
                break

    return result


__author__ = 'wojtekniedzwiecki'

import unittest
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
#from __builtin__ import classmethod

class HomePageTest(unittest.TestCase):

    @classmethod
    def setUp(cls):
        # create a new Firefox session """
        cls.driver = webdriver.Firefox()
        cls.driver.implicitly_wait(30)
        cls.driver.maximize_window()

        # navigate to the application home page """
        cls.driver.get("http://demo.magentocommerce.com/")

    def test_language_options(self):
        # list of expected values in Language dropdown
        exp_options = ["ENGLISH", "FRENCH", "GERMAN"]

        # empty list for capturing actual options displayed # in the dropdown
        act_options = []

        # get the Your language dropdown as instance of Select class
        select_language = \
            Select(self.driver.find_element_by_id("select-language"))

        # check number of options in dropdown
        self.assertEqual(3, len(select_language.options))

        # get options in a list
        for option in select_language.options:
            act_options.append(option.text)

        # check expected options list with actual options list
        self.assertListEqual(exp_options, act_options)

        # check default selected option is English
        self.assertEqual("ENGLISH", select_language.first_selected_option.text)

        # select an option using select_by_visible text
        select_language.select_by_visible_text("German")

        # check store is now German
        self.assertTrue("store=german&___from_store" in self.driver.current_url)

        # changing language will refresh the page,
        # we need to get find language dropdown once again
        select_language = \
            Select(self.driver.find_element_by_id("select-language"))
        select_language.select_by_index(0)

    @classmethod
    def tearDown(cls):
        # close the browser window
        cls.driver.quit()

if __name__ == '__main__':
    unittest.main(verbosity=2)


from question.models import *
from question.forms import *
from django.shortcuts import *
import datetime

def edit(request):
    if request.method == 'POST':
        form = SingleChoiceQuestionForm(request.POST)
        if form.is_valid():
            scq = form.save(commit = False)
            scq.save()

            question = Question()
            question.status = 2
            question.content_object = scq
            question.author = request.user
            question.last_modify = datetime.datetime.now()
            question.save()
            return HttpResponseRedirect("/question/edit/scq/" + str(scq.id))

    else:
        form = SingleChoiceQuestionForm()
        return render_to_response("question/add/scq.html", locals(), context_instance = RequestContext(request))


"""Scrape the total homicide count from the Philadelphia Police Department's
Crime Stats website."""

from dataclasses import dataclass

import pandas as pd
import requests
from bs4 import BeautifulSoup
from cached_property import cached_property
from loguru import logger

from . import DATA_DIR

@dataclass
class PPDHomicideTotal:
    """Total number of homicides scraped from the Philadelphia Police
    Department's website.

    This provides:
        - Annual totals since 2007 for past years.
        - Year-to-date homicide total for the current year.

    Source
    ------
    https://www.phillypolice.com/crime-maps-stats/
    """

    debug: bool = False

    URL = "https://www.phillypolice.com/crime-maps-stats/"

    def __post_init__(self):
        self.soup = BeautifulSoup(requests.get(self.URL).content, "html.parser")

    @cached_property
    def years(self):
        """The years available on the page. Starts with 2007."""

        return [
            int(td.text)
            for td in self.soup.select("#homicide-stats")[0]
            .find("tr")
            .find_all("th")[1:]
        ]

    @cached_property
    def as_of_date(self):
        """The current "as of" date on the page."""

        date = (
            self.soup.select("#homicide-stats")[0]
            .select("tbody")[0]
            .select_one("td")
            .text.split("\n")[0]
        )
        return pd.to_datetime(date + " 11:59:00")

    @cached_property
    def annual_totals(self):
        """The annual totals for homicides in Philadelphia."""

        # This is for historic data only (doesn't include current year)
        annual_totals = [
            int(td.text)
            for td in self.soup.select("#homicide-stats")[1].find_all("td")[1:]
        ]

        if len(annual_totals) != len(self.years[1:]):
            raise ValueError(
                "Length mismatch between parsed years and annual homicide totals"
            )

        return pd.DataFrame(
            {"year": self.years[1:], "annual": annual_totals}
        ).sort_values("year", ascending=False)

    @cached_property
    def ytd_totals(self):
        """The year-to-date totals for homicides in Philadelphia."""

        # Scrape the table
        table = self.soup.select("#homicide-stats")[0]
        ytd_totals = [table.select("tbody")[0].select(".homicides-count")[0].text]
        ytd_totals += [td.text for td in table.select("tbody")[0].find_all("td")[2:-1]]
        ytd_totals = list(map(int, ytd_totals))

        if len(ytd_totals) != len(self.years):
            raise ValueError("Length mismatch between parsed years and homicides")

        # Return ytd totals, sorted in ascending order
        out = pd.DataFrame({"year": self.years, "ytd": ytd_totals})
        return out.sort_values("year", ascending=False)

    @property
    def path(self):
        return DATA_DIR / "raw" / "homicide_totals_daily.csv"

    def get(self):
        """Get the shooting victims data, either loading
        the currently downloaded version or a fresh copy."""

        # Load the database of daily totals
        df = pd.read_csv(self.path, parse_dates=[0])

        # Make sure it's in ascending order by date
        return df.sort_values("date", ascending=True)

    def update(self):
        """Update the local data via scraping the PPD website."""

        # Load the database
        database = self.get()

        # Latest database date
        latest_database_date = database.iloc[-1]["date"]

        # Update if we need to
        if latest_database_date < self.as_of_date:

            if self.debug:
                logger.debug("Parsing PPD website to update YTD homicides")

            # Merge annual totals (historic) and YTD (current year)
            data = pd.merge(self.annual_totals, self.ytd_totals, on="year", how="outer")

            # Save it
            path = DATA_DIR / "processed" / "homicide_totals.json"
            data.set_index("year").to_json(path, orient="index")

            # Add new row to database
            YTD = self.ytd_totals.iloc[0]["ytd"]
            database.loc[len(database)] = [self.as_of_date, YTD]

            # Save it
            if self.debug:
                logger.debug("Updating PPD homicides data file")
            database.to_csv(self.path, index=False)


# Copyright 2013-2015 Rackspace US, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Bottle Server Module."""

import logging
import os

import bottle

LOG = logging.getLogger(__name__)

class EventletLogFilter(object):  # pylint: disable=R0903

    """Receives eventlet log.write() calls and routes them.

    Thread and WSGI messages only get written in debug mode. Eventlet writes
    these out starting with a thread id in parens or "wsgi" messages:
    - "(46722) wsgi starting up on http://127.0.0.1:8080/"
    - "(47001) accepted ('127.0.0.1', 53046)"
    - "wsgi exiting"

    All other calls are assumed to be apache log-style API calls and we want
    these written as INFO and to an access_log if provided.

    API calls are assumed to start with the IP address:
    - "127.0.0.1 - - [07/Jul/2015 16:16:31] "GET /version HTTP/1.1" 200 ..."

    An instance of this class can be passed in to a bottle.run command using
    the `log` keyword.
    """

    def __init__(self, log, access_log=None):
        """Initialize with config and optional access_log.

        :param log: logger instance (ex. logging.getLogger()).
        :keyword access_log: a file handle to an access log that should receive
            apache-style entries for each call and response.
        """
        self.log = log
        self.access_log = access_log

    def write(self, text):
        """Write to appropriate target."""
        if text:
            if text[0] in '(w':
                # write thread and wsgi messages to debug only
                self.log.debug(text[:-1])
                return
            if self.access_log:
                self.access_log.write(text)
            self.log.info(text[:-1])

class XEventletServer(bottle.ServerAdapter):

    r"""Eventlet Bottle Server Adapter with extensions.

    Supports SSL. Accepts additional tuning parameters:

    * `backlog` adjust the eventlet backlog parameter which is the maximum
      number of queued connections. Should be at least 1; the maximum
      value is system-dependent.
    * `family`: (default is 2) socket family, optional. See socket
      documentation for available families.
    * `**kwargs`: directly map to python's ssl.wrap_socket arguments from
      https://docs.python.org/2/library/ssl.html#ssl.wrap_socket and
      wsgi.server arguments from
      http://eventlet.net/doc/modules/wsgi.html#wsgi-wsgi-server

    To create a self-signed key and start the eventlet server using SSL::

      openssl genrsa -des3 -out server.orig.key 2048
      openssl rsa -in server.orig.key -out test.key
      openssl req -new -key test.key -out server.csr
      openssl x509 -req -days 365 -in server.csr -signkey test.key -out \
      test.crt

      bottle.run(server='eventlet', keyfile='test.key', certfile='test.crt')
    """

    def get_socket(self):
        """Create listener socket based on bottle server parameters."""
        import eventlet

        # Separate out socket.listen arguments
        socket_args = {}
        for arg in ('backlog', 'family'):
            try:
                socket_args[arg] = self.options.pop(arg)
            except KeyError:
                pass
        # Separate out wrap_ssl arguments
        ssl_args = {}
        for arg in ('keyfile', 'certfile', 'server_side', 'cert_reqs',
                    'ssl_version', 'ca_certs', 'do_handshake_on_connect',
                    'suppress_ragged_eofs', 'ciphers'):
            try:
                ssl_args[arg] = self.options.pop(arg)
            except KeyError:
                pass
        address = (self.host, self.port)
        try:
            sock = eventlet.listen(address, **socket_args)
        except TypeError:
            # Fallback, if we have old version of eventlet
            sock = eventlet.listen(address)
        if ssl_args:
            sock = eventlet.wrap_ssl(sock, **ssl_args)
        return sock

    def run(self, handler):
        """Start bottle server."""
        import eventlet.patcher
        if not eventlet.patcher.is_monkey_patched(os):
            msg = ("%s requires eventlet.monkey_patch() (before "
                   "import)" % self.__class__.__name__)
            raise RuntimeError(msg)

        # Separate out wsgi.server arguments
        wsgi_args = {}
        for arg in ('log', 'environ', 'max_size', 'max_http_version',
                    'protocol', 'server_event', 'minimum_chunk_size',
                    'log_x_forwarded_for', 'custom_pool', 'keepalive',
                    'log_output', 'log_format', 'url_length_limit', 'debug',
                    'socket_timeout', 'capitalize_response_headers'):
            try:
                wsgi_args[arg] = self.options.pop(arg)
            except KeyError:
                pass
        if 'log_output' not in wsgi_args:
            wsgi_args['log_output'] = not self.quiet

        import eventlet.wsgi
        sock = self.options.pop('shared_socket', None) or self.get_socket()
        eventlet.wsgi.server(sock, handler, **wsgi_args)

    def __repr__(self):
        """Show class name, even if subclassed."""
        return self.__class__.__name__

bottle.server_names['xeventlet'] = XEventletServer

class XTornadoServer(bottle.ServerAdapter):  # pylint: disable=R0903

    """The Tornado Server Adapter with xheaders enabled."""

    def run(self, handler):
        """Start up the server."""
        import tornado.httpserver
        import tornado.ioloop
        import tornado.wsgi
        container = tornado.wsgi.WSGIContainer(handler)
        server = tornado.httpserver.HTTPServer(container, xheaders=True)
        server.listen(port=self.port, address=self.host)
        tornado.ioloop.IOLoop.instance().start()

bottle.server_names['xtornado'] = XTornadoServer


import jinja2
import webapp2
import json

from utils import maps

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader('templates'),
    extensions=['jinja2.ext.autoescape'])

class MainHandler(webapp2.RequestHandler):
  def get(self):

    # Render to templates
    template_values = {
      'message': 'Hello'
    }
    template = JINJA_ENVIRONMENT.get_template('index.html')
    self.response.write(template.render(template_values))

class GetSectionsHandler(webapp2.RequestHandler):
  def get(self):

    # result
    result = {
      'success': False,
    }

    # query
    sw_lat = self.request.get('sw_lat')
    ne_lat = self.request.get('ne_lat')
    sw_lng = self.request.get('sw_lng')
    ne_lng = self.request.get('ne_lng')
    if not (sw_lat and ne_lat and sw_lng and ne_lng):
      result['message'] = 'ERROR: Please specify bounds'
      self.response.write(json.dumps(result))
      return

    # floatify
    sw_lat = float(sw_lat)
    ne_lat = float(ne_lat)
    sw_lng = float(sw_lng)
    ne_lng = float(ne_lng)

    # Get sections
    sections = maps.pick_sections(self.request.host_url, sw_lat, sw_lng, ne_lat, ne_lng)
    if sections:
      result['success'] = True
      result['sections'] = sections

    self.response.write(json.dumps(result))


from django.conf.urls import patterns, include, url
from django.views.generic.base import TemplateView

urlpatterns = patterns('',

	url(r'^todas/','subasta.views.todas',name="todas"),
	url(r'^recientes/','subasta.views.recientes',name="recientes"),
	url(r'^proximas/','subasta.views.proximas',name="proximas"),
	url(r'^mis_subastas/$','subasta.views.mis_subastas',name="mis_subastas"),
	url(r'^ver/(?P<subastaid>\d+)/(?P<comentarioid>\d+)','comentario.views.responder',name="responder_subasta"),
	url(r'^ver/(?P<id>\d+)','subasta.views.ver_subasta',name="ver_subasta"),
	url(r'^editar/(?P<id>\d+)','subasta.views.editar_subasta',name="editar_subasta"),
	url(r'^nueva/','subasta.views.nueva_subasta',name="nueva_subasta"),
	#url(r'^editar/(?P<id>\d+)','subasta.views.editar_subasta',name="editar_subasta"),
	url(r'^eliminar/(?P<id>\d+)','subasta.views.eliminar_subasta',name="eliminar_subasta"),
	url(r'^buscar/','subasta.views.buscar_subastas',name="buscar_subasta"),
	#url(r'^nueva/','subasta.views.nueva',name="nueva"),

	#url(r'^ver/(?P<id>\d+)/comentario/',include('comentario.urls')),

)


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render
# 추가로직 - jayden
from django.http import HttpResponse
from .models import Photo
from django.shortcuts import get_object_or_404
# from photos.forms import create
from .forms import PhotoForm
from django.shortcuts import redirect

# Create your views here.
# 추가로직 - jayden
def hello(request):
    return HttpResponse('안녕하쉽늬까')

def detail(request,pk):
#    msg = '{}번 사진 보여주겠슴다'.format(pk)
#    photo = Photo.objects.get(pk=pk)
    photo = get_object_or_404(Photo, pk=pk)
    messages = (
        '
{pk}번 사진 출력합니다.
'.format(pk=photo.pk),
        '
주소는 {url}
'.format(url=photo.image.url),
        '

'.format(url=photo.image.url),
    )
#    return HttpResponse('detail 뷰 함수')
#    return HttpResponse(msg)
    return HttpResponse('\n'.join(messages))

def create(request):
    form = PhotoForm()
    if request.method == "GET":
        form = PhotoForm()
    elif request.method == "POST":
        form = PhotoForm(request.POST, request.FILES)
        if form.is_valid():
            obj = form.save()
            return redirect(obj)
    ctx = {
        'form': form,
    }
    return render(request, 'edit.html', ctx)


import cv2
import numpy as np
import imutils

def Contornos(fotogramas,min,max,area_minima):
    # Conversion a HSV
    hsv = cv2.cvtColor(fotogramas, cv2.COLOR_BGR2HSV)

    # Segmentacion de la imagen
    mascara = cv2.inRange(hsv,min, max)

    # Detectanto contornos a partir de la segmentacion
    lista_contornos, jerarquia = cv2.findContours(mascara, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    # Ordenar los contornos
    lista_contornos = sorted(lista_contornos, key=cv2.contourArea, reverse=True)

    # Separar los contornos
    contornos_ok = []
    for cada_contorno in lista_contornos:
        area_contorno = len(cada_contorno)
        if area_contorno > area_minima:
            contornos_ok.append(cada_contorno)

    # Ordenar los contornos de mayor a menor solo los que estan como ok
    ord_contornos = sorted(contornos_ok, key=cv2.contourArea, reverse=True)

    # Regresamos la imagen en HSV, la lista de contornos que estan ok
    return (hsv, lista_contornos, ord_contornos)


import time
import requests
import board
import busio
import asyncio
import threading
import urllib.request
import RPi.GPIO as GPIO
import os
import subprocess
from subprocess import Popen
from pathlib import Path
import pygame

time.sleep(60.0)
os.environ["DISPLAY"] = ":0"
pygame.display.init()
#game = pygame.display.set_mode((200,300))
game = pygame.display.set_mode((0,0),pygame.FULLSCREEN)
#game = pygame.display.set_mode((0,0),0,32,pygame.NOFRAME)
#game = pygame.display.set_mode((0,0),pygame.NOFRAME)
pygame.display.set_caption('picture')
img = pygame.image.load('/home/pi/Downloads/hnd/5.jpg')
img = pygame.transform.scale(img,(400,300))
white =(255,255,255)

GPIO.setup(26, GPIO.IN) # señal entrada
GPIO.setup(11, GPIO.OUT) #señal apagado entrada
GPIO.setup(13, GPIO.IN) #persona en entrada

GPIO.setup(6, GPIO.OUT) #señal apagado salida
GPIO.setup(5, GPIO.IN) #señal salida(arduino2)
GPIO.setup(19, GPIO.IN)#persona salida

GPIO.setup(10, GPIO.OUT) #apagado señal oportunidad
GPIO.setup(9, GPIO.IN) #señal oportunidad
oportunidad = GPIO.input(9)

GPIO.setup(6, GPIO.OUT)
GPIO.output(6,GPIO.HIGH)
time.sleep(0.5)
GPIO.setup(6, GPIO.OUT)
GPIO.output(6,GPIO.LOW)
señalSalida = GPIO.input(5)
personaSalida = GPIO.input(19)

GPIO.setup(11, GPIO.OUT)
GPIO.output(11,GPIO.HIGH)
time.sleep(0.5)
GPIO.setup(11, GPIO.OUT)
GPIO.output(11,GPIO.LOW)
personaEntrada = GPIO.input(13)
señalEntrada = GPIO.input(26)

def PostOport():
    url= 'http://143.198.132.112/smarthh/novaspost_oportunidades.php'
    status_code = 200
    try:
        status_code = requests.get(url, timeout = 10)

    except requests.exceptions.ConnectTimeout:
        #print ('time out')
        status_code = 3
    except requests.exceptions.ConnectionError:
        #print ('error de conexion')
        status_code = 3

    if status_code == 200:
        query = {'lat':'45','lon':'180'}
        response = requests.post('http://143.198.132.112/smarthh/novaspost_oportunidades.php',data = {'foo2':'bar2'})
        #print (response.text)
    else:
        pass

def PostEfect():

    url= 'http://143.198.132.112/smarthh/novaspost_efectivo.php'
    status_code = 200
    try:
        status_code = requests.get(url, timeout = 5)
        status_code.raise_for_status()
    except requests.exceptions.ConnectTimeout:
        #print ('time out')
        status_code = 3
    except requests.exceptions.ConnectionError:
       # print ('error de conexion')
        status_code = 3

    if status_code == 200:
        query = {'lat':'45','lon':'180'}
        response = requests.post('http://143.198.132.112/smarthh/novaspost_efectivo.php',data = {'foo2':'bar2'})
        #print (response.text)
    else:
        pass
        #print ('no fue posible entrar')
    #print("lavado de manos")

def apagarbomba():
    GPIO.output(10,GPIO.HIGH)
    time.sleep(0.4)
    GPIO.output(10,GPIO.LOW)
    time.sleep(0.1)

def apagarentrada():
    global k
    GPIO.setup(26, GPIO.IN)
    señalEntrada = GPIO.input(26)
    while(señalEntrada == 1):
        GPIO.setup(26, GPIO.IN)
        señalEntrada = GPIO.input(26)
        GPIO.setup(5, GPIO.IN)
        señalSalida = GPIO.input(5)
        GPIO.setup(6, GPIO.OUT)
        GPIO.output(6,GPIO.HIGH)
        time.sleep(0.1)
        GPIO.setup(6, GPIO.OUT)
        GPIO.output(6,GPIO.LOW)
        time.sleep(0.1)
    k = 1

def apagarsalida():

    GPIO.setup(5, GPIO.IN)
    señalSalida = GPIO.input(5)
    global l
    while(señalSalida == 1):
        GPIO.setup(5, GPIO.IN)
        señalSalida = GPIO.input(5)
        GPIO.setup(11, GPIO.OUT)
        GPIO.output(11,GPIO.HIGH)
        time.sleep(0.1)
        GPIO.setup(11, GPIO.OUT)
        GPIO.output(11,GPIO.LOW)
        time.sleep(0.1)
    l = 1

def screen():
	global screen_status
	url= 'http://143.198.132.112/smarthh/pantalla.php'
	status_code = 200
	try:
		status_code = requests.get(url,timeout = 10)
		#print(status_code)

	except requests.exceptions.ConnectTimeout:
		status_code = 3
	except requests.exceptions.ConnectionError:
		status_code = 3
	if status_code == 200 or "[200]":
		query = {'lat':'45','lon':'180'}
		r = requests.post('http://143.198.132.112/smarthh/pantalla.php')
		screen_status = r.text
		#print(r.text)
		#print('request realizado')
	else:print('no hubo request')
def imagen(j):
    if(j == 1):
        img = pygame.image.load('/home/pi/Downloads/hnd/2.jpg')
        img = pygame.transform.rotate(img,-90)
        img = pygame.transform.scale(img,(720,600))
    elif(j == 2):
        img = pygame.image.load('/home/pi/Downloads/hnd/3.jpg')
        img = pygame.transform.rotate(img,-90)
        img = pygame.transform.scale(img,(720,600))
    else:
        img = pygame.image.load('/home/pi/Downloads/hnd/5.jpg')
        img = pygame.transform.rotate(img,-90)
        img = pygame.transform.scale(img,(720,600))

    game.blit(img,(0,0))

def start_img():
    j = 0
    crash = False
    while not crash:
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_DOWN:
                    pygame.quit()
                    crash = True
                elif event.key == pygame.K_RIGHT:
                    j = 1
                elif event.key == pygame.K_LEFT:
                    j = 2
            #print('dentro del for')

        game.fill(white)
        imagen(j)
        pygame.display.update()

flag = 1
video = Path("/home/pi/Downloads/hnd/camalion.mp4")
video2 = Path("/home/pi/Downloads/AnimatedSF.mp4")
global a
os.environ['DISPLAY']= ":0"
global screen_status
screen_status = ''
a = 'no video'
flag = 1
print("Iniciando...")
i = 1

s = threading.Thread(target = start_img)
s.start()

while True:

    GPIO.setup(26, GPIO.IN)
    señalEntrada = GPIO.input(26)
    GPIO.setup(5, GPIO.IN)
    señalSalida = GPIO.input(5)
    #print("señal entrada:")
    #print(señalEntrada)
    #print("señal salida:")
    #print(señalSalida)

    if(señalEntrada == 1):
        GPIO.setup(13, GPIO.IN)
        personaEntrada = GPIO.input(13)
        GPIO.setup(19, GPIO.IN)
        personaSalida = GPIO.input(19)
        oportunidad = GPIO.input(9)
        #print("alguien en la puerta")
         #print(personaEntrada)
        if(oportunidad == 1):
            flag = 1;
        else:
            flag = 0;
        while(personaEntrada == 1 or personaSalida == 1):
            personaEntrada = GPIO.input(13)
            personaSalida = GPIO.input(19)
            #print("alguien en la puerta")
            #print(personaEntrada)

        if(flag ==1):
            b = threading.Thread(target = apagarbomba)
            b.start()
            e = threading.Thread(target = PostEfect)
            e.start()
            f = threading.Thread(target = PostOport)
            f.start()
            #print('realizar peticion http oportunidad con lavado de manos')
        else:
            b = threading.Thread(target = apagarbomba)
            b.start()
            f = threading.Thread(target = PostOport)
            f.start()
            #i = ventana(i)

            #print('realizar peticion http oportunidad sin lavado de manos')

        greenflag = 1
        global k
        global l
        k = 0
        l = 0
        while(k == 0):

            if(greenflag ==1):
                es = threading.Thread(target = apagarentrada)
                es.start()
                greenflag = 0
                #print("valor de k es:")
                #print(k)
            else:
                pass

        greenflag = 1
        #print(k)

        while(l == 0):

            if(greenflag ==1):
                ec = threading.Thread(target = apagarsalida)
                ec.start()
                greenflag = 0

            else:
                pass
        greenflag = 1

  #############################################################
        #print("apagando... entrada")
        #print("señal apagada")
        i = i + 1
        #print(i)

    elif (señalSalida == 1):

        GPIO.setup(13, GPIO.IN)
        personaEntrada = GPIO.input(13)
        GPIO.setup(19, GPIO.IN)
        personaSalida = GPIO.input(19)
        while(personaEntrada == 1 or personaSalida == 1):
            personaEntrada = GPIO.input(13)
            personaSalida = GPIO.input(19)
            #print("alguien en la puerta")
            #print(personaEntrada)

        greenflag = 1

        k = 0
        l = 0

        while(l == 0):

            if(greenflag ==1):
                er = threading.Thread(target = apagarsalida)
                er.start()
                greenflag = 0

            else:
                pass
        greenflag = 1

        while(k == 0):

            if(greenflag ==1):
                ee = threading.Thread(target = apagarentrada)
                ee.start()
                greenflag = 0
                #print("valor de k es:")
                #print(k)
            else:
                pass

        greenflag = 1
        #print(k)

        #print("salida")

    else:

        GPIO.output(6,GPIO.LOW)
        GPIO.setup(11, GPIO.OUT)
        GPIO.output(11,GPIO.LOW)
        #print("no hay nadie")


'''
@author:lvming
@time:2021/6/21
'''
#发送邮箱 (三)

#发送附件 pytest+jenkins下载工具就行 json文件
import smtplib
#发送附件
from email.mime.multipart import MIMEMultipart
#发送正文
from email.mime.text import MIMEText
#头部
from email.header import Header

con=smtplib.SMTP_SSL('smtp.qq.com','465')
con.login('421312525@qq.com','vzvzaftwntutbgbh')
sender='421312525@qq.com'
recevier=['v_lvming@baidu.com']

#发送附件
#创建一个信封
message=MIMEMultipart()
#先找到文件
content=open('file/1.html','rb').read()
#写信
file1=MIMEText(content,'plain','utf-8')
#信封取个名字 附件名 有个html文件发送
file1['Content-Disposition']='attachment;filename="a.html"'
#把信放在信封中
message.attach(file1)

#发送人
message['Form']=Header('喔嚯<421312525@qq.com>')
#收件人
message['To']=Header('小朋友')
#标题
message['Subject']=Header('今天是个好日子')

#发送邮件
con.sendmail(sender,recevier,message.as_string())

#先压缩文件 zip包  把zip包以附件的形式发送给负责人 负责人再去下载，解压再看
# pytest allure测试报告  界面  链接,点击链接 再登录就可以看到了


import cv2
import numpy as np
import os
from create_base import *
import time

def get_contours(filename,pic_path):
    #pic_path = "./tmp/tmp.jpg"
    y,sr = get_cqt_pic(filename,pic_path)
    rms = librosa.feature.rmse(y=y)[0]
    length = len(rms)
    img = cv2.imread(pic_path)
    # kernel = np.ones((2, 2), np.uint8)*np.max(img)  # 全为1的过滤数组
    # # 膨胀(去黑小点)
    # img = cv2.dilate(img, kernel)  # 膨胀

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    ret,binary = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY)

    _,contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_TC89_KCOS)

    # draw_img0 = cv2.drawContours(img.copy(),contours,0,(0,255,255),3)
    # draw_img1 = cv2.drawContours(img.copy(),contours,1,(255,0,255),3)
    # draw_img2 = cv2.drawContours(img.copy(),contours,2,(255,255,0),3)
    #draw_img3 = cv2.drawContours(img.copy(), contours, -1, (0, 0, 255), 1)
    draw_img3 = img.copy()
    contours_dict = {}
    right_lines = []
    right_points = []
    for i in range(0,len(contours)):
        x, y, w, h = cv2.boundingRect(contours[i])
        right_points.append(x + w)
    for i in range(0,len(contours)):
        x, y, w, h = cv2.boundingRect(contours[i])
        #cv2.rectangle(draw_img3, (x, y), (x + w, y + h), (0, 0, 255), 2)
        if w * h > 30:
            cv2.rectangle(draw_img3, (x,y), (x+w,y+h), (0, 0, 255), 2)
            font = cv2.FONT_HERSHEY_SIMPLEX
            cv2.putText(draw_img3, str(x) + ',' + str(y), (x,y), font, 0.4, (255, 255, 255), 1)
            #print("START x,w is {},{}".format(x, x + w))
            #根据左边线判断
            is_exist = False
            tmp = []
            for j in range(x-5,x+5):
                if j in contours_dict.keys():
                    #print("1. x,w is {},{}".format(x,x+w))
                    tmp.append(contours_dict.get(j))
                    tmp.append([x, y, w, h])
                    contours_dict.update({int((x + j)/2):tmp})
                    #添加右边线
                    if w > 10 and h > 10 and check_right_line(right_points,x + w):
                        right_lines.append(x + w)
                    is_exist = True
                    break
            if is_exist is False:
                tmp.append([x, y, w, h])
                contours_dict.update({x:tmp})
                #print("2. x,w is {},{}".format(x, x + w))
            # 根据右边线判断
            # is_exist = False
            # tmp = []
            # for j in range(x + w - 3, x + w + 3):
            #     if j in contours_dict.keys():
            #         tmp.append(contours_dict.get(j))
            #         tmp.append(contours[i])
            #         contours_dict.update({int((x + w + j) / 2): tmp})
            #         is_exist = True
            #         break
    find_notes = find_note_by_contours(contours_dict)
    for x in find_notes:
        cv2.line(draw_img3, (x, 10), (x, 200), (0, 255, 0), 2)  # 绿色，3个像素宽度
    right_lines.sort()
    if len(right_lines)>0:
        right_lines = del_overrate(right_lines)
        right_lines = check_with_start(find_notes, right_lines)
    for x in right_lines:
        cv2.line(draw_img3, (x, 10), (x, 200), (255, 255, 0), 2)  # 绿色，3个像素宽度
        find_notes.append(x)
    find_notes.sort()
    return draw_img3,img,find_notes,length

def get_note_lines(img,find_notes,lenght):
    width = img.shape[1]
    result = []
    for x in find_notes:
        tmp = int(x * lenght /width)
        result.append(tmp)
    return result

def find_note_by_contours(contours_dict):
    result = []
    for key in contours_dict.keys():
        tmp = contours_dict.get(key)
        if len(tmp)>=2:
            result.append(key)
        elif tmp[0][2]*tmp[0][3] > 50 and tmp[0][2]*tmp[0][3] < 10000:
            result.append(key)
    result.sort()
    result = del_overrate(result)
    return result

def del_overrate(result):
    new_result = [result[0]]
    last = result[0]
    for i in range(1, len(result)):
        if result[i] - last > 3:
            new_result.append(result[i])
            last = result[i]
    return new_result

def check_with_start(start_nots,right_lines):
    result = []
    for r in right_lines:
        tmp = [np.abs(r - x) for x in start_nots]
        if np.min(tmp) > 5:
            result.append(r)
    return result

def check_right_line(right_points,right):
    offset = [x - right for x in right_points]
    find_nearly = [x for x in offset if x<=1]
    if len(find_nearly)>3:
        return True
    else:
        return False

def get_cqt_pic(filename,pic_path):
    _,y,sr = draw_on_cqt(filename,pic_path, False)
    plt.close()
    return y,sr

if __name__ == "__main__":
    filename = 'F:/项目/花城音乐项目/样式数据/3.06MP3/旋律/旋8录音4(93).wav'
    filename = 'F:/项目/花城音乐项目/样式数据/3.06MP3/旋律/旋律八（2）（60）.wav'
    start_time = time.time()
    #get_cqt_pic(filename)
    end_time = time.time()
    print("runing is {}".format(end_time - start_time))
    # filename = 'E:/test_image/n/A/50.jpg'
    # filename = 'e:/test_image/n/D/4.jpg'
    # filename = 'e:/test_image/n/C/54.jpg'
    pic_path = "./tmp/tmp.jpg"
    draw_img3,img,note_lines,length = get_contours(filename,pic_path)
    #cv2.imshow("img", img)
    # cv2.imshow("draw_img0", draw_img0)
    # cv2.imshow("draw_img1", draw_img1)
    # cv2.imshow("draw_img2", draw_img2)
    cv2.imshow("draw_img3", draw_img3)
    print("width,height is {},{}".format(img.shape[1],img.shape[0]))

    cv2.waitKey(0)
    cv2.destroyAllWindows()
    cv2.imwrite( "f:/test1111..jpg",draw_img3)

    dir_list = ['F:/项目/花城音乐项目/样式数据/3.06MP3/旋律/']
    dir_list = ['e:/test_image/n/B/']
    dir_list = []
    total_accuracy = 0
    total_num = 0
    result_path = 'e:/test_image/c/'
    # clear_dir(result_path)
    # 要测试的数量
    test_num = 100
    score = 0
    for dir in dir_list:
        file_list = os.listdir(dir)
        # shuffle(file_list)  # 将语音文件随机排列
        # file_list = ['视唱1-01（95）.wav']
        for filename in file_list:
            # clear_dir(image_dir)
            # wavname = re.findall(pattern,filename)[0]
            print(dir + filename)
            # plt = draw_start_end_time(dir + filename)
            draw_img3, img = get_contours(dir + filename)

            grade = 'B'
            cv2.imwrite(result_path + grade + "/" + filename, draw_img3)


"""The reactions list"""
from math import isclose

import cobra
from qtpy.QtCore import QMimeData, Qt, Signal, Slot
from qtpy.QtGui import QDrag, QIcon
from qtpy.QtWidgets import (QHBoxLayout, QHeaderView, QLabel, QLineEdit,
                            QMessageBox, QPushButton, QSizePolicy, QSplitter,
                            QTableWidget, QTableWidgetItem, QTreeWidget,
                            QTreeWidgetItem, QVBoxLayout, QWidget)

from cnapy.cnadata import CnaData
from cnapy.utils import SignalThrottler, turn_red, turn_white

class DragableTreeWidget(QTreeWidget):
    '''A list of dragable reaction items'''

    def mouseMoveEvent(self, _event):
        item = self.currentItem()
        if item is not None:
            reaction: cobra.Reaction = item.data(3, 0)
            mime_data = QMimeData()
            mime_data.setText(reaction.id)
            drag = QDrag(self)
            drag.setMimeData(mime_data)
            drag.exec_(Qt.CopyAction | Qt.MoveAction, Qt.CopyAction)

class ReactionList(QWidget):
    """A list of reaction"""

    def __init__(self, appdata: CnaData):
        QWidget.__init__(self)
        self.appdata = appdata
        self.last_selected = None
        self.reaction_counter = 1

        self.add_button = QPushButton("Add new reaction")
        self.add_button.setIcon(QIcon.fromTheme("list-add"))
        policy = QSizePolicy()
        policy.ShrinkFlag = True
        self.add_button.setSizePolicy(policy)

        self.reaction_list = DragableTreeWidget()
        self.reaction_list.setDragEnabled(True)
        self.reaction_list.setHeaderLabels(["Id", "Name", "Flux"])
        self.reaction_list.setSortingEnabled(True)

        for r in self.appdata.project.cobra_py_model.reactions:
            self.add_reaction(r)

        self.reaction_mask = ReactionMask(self)
        self.reaction_mask.hide()

        self.layout = QVBoxLayout()
        self.layout.setContentsMargins(0, 0, 0, 0)
        l = QHBoxLayout()
        l.setAlignment(Qt.AlignRight)
        l.addWidget(self.add_button)
        self.splitter = QSplitter()
        self.splitter.setOrientation(Qt.Vertical)
        self.splitter.addWidget(self.reaction_list)
        self.splitter.addWidget(self.reaction_mask)
        self.layout.addItem(l)
        self.layout.addWidget(self.splitter)
        self.setLayout(self.layout)

        self.reaction_list.currentItemChanged.connect(self.reaction_selected)
        self.reaction_mask.reactionChanged.connect(
            self.handle_changed_reaction)
        self.reaction_mask.reactionDeleted.connect(
            self.handle_deleted_reaction)
        self.reaction_mask.jumpToMap.connect(self.emit_jump_to_map)
        self.reaction_mask.jumpToMetabolite.connect(
            self.emit_jump_to_metabolite)

        self.add_button.clicked.connect(self.add_new_reaction)

    def clear(self):
        self.reaction_list.clear()
        self.reaction_mask.hide()

    def add_reaction(self, reaction: cobra.Reaction) -> QTreeWidgetItem:
        ''' create a new item in the reaction list'''
        self.reaction_list.clearSelection()
        item = QTreeWidgetItem(self.reaction_list)
        item.setText(0, reaction.id)
        item.setText(1, reaction.name)
        self.set_flux_value(item, reaction.id)

        text = "Id: " + reaction.id + "\nName: " + reaction.name \
            + "\nEquation: " + reaction.build_reaction_string()\
            + "\nLowerbound: " + str(reaction.lower_bound) \
            + "\nUpper bound: " + str(reaction.upper_bound) \
            + "\nObjective coefficient: " + str(reaction.objective_coefficient)

        item.setToolTip(1, text)
        item.setData(3, 0, reaction)

        return item

    def set_flux_value(self, item, key):
        if key in self.appdata.project.scen_values.keys():
            (vl, vu) = self.appdata.project.scen_values[key]
            if isclose(vl, vu, abs_tol=self.appdata.abs_tol):
                item.setData(2, 0, round(vl, self.appdata.rounding))
            else:
                item.setData(
                    2, 0, str((round(vl, self.appdata.rounding), round(vu, self.appdata.rounding))))
            item.setBackground(2, self.appdata.scen_color)
            item.setForeground(2, Qt.black)
        elif key in self.appdata.project.comp_values.keys():
            (vl, vu) = self.appdata.project.comp_values[key]

            # We differentiate special cases like (vl==vu)
            if isclose(vl, vu, abs_tol=self.appdata.abs_tol):
                if self.appdata.modes_coloring:
                    if vl == 0:
                        item.setBackground(2, Qt.red)
                    else:
                        item.setBackground(2, Qt.green)
                else:
                    item.setBackground(2, self.appdata.comp_color)

                item.setData(2, 0, round(vl, self.appdata.rounding))
            else:
                if isclose(vl, 0.0, abs_tol=self.appdata.abs_tol):
                    item.setBackground(2, self.appdata.special_color_1)
                elif isclose(vu, 0.0, abs_tol=self.appdata.abs_tol):
                    item.setBackground(2, self.appdata.special_color_1)
                elif vl <= 0 and vu >= 0:
                    item.setBackground(2, self.appdata.special_color_1)
                else:
                    item.setBackground(2, self.appdata.special_color_2)
                item.setData(
                    2, 0, str((round(vl, self.appdata.rounding), round(vu, self.appdata.rounding))))

            item.setForeground(2, Qt.black)

    def add_new_reaction(self):
        self.reaction_mask.show()
        while True:
            name = "rxn_"+str(self.reaction_counter)
            self.reaction_counter += 1
            if name not in self.appdata.project.cobra_py_model.reactions:
                break
        reaction = cobra.Reaction(name)
        self.appdata.project.cobra_py_model.add_reactions([reaction])
        item = self.add_reaction(reaction)
        self.reaction_selected(item, 1)
        self.appdata.window.unsaved_changes()

    def update_annotations(self, annotation):

        self.reaction_mask.annotation.itemChanged.disconnect(
            self.reaction_mask.throttler.throttle)
        c = self.reaction_mask.annotation.rowCount()
        for i in range(0, c):
            self.reaction_mask.annotation.removeRow(0)
        i = 0
        for key in annotation:
            self.reaction_mask.annotation.insertRow(i)
            keyl = QTableWidgetItem(key)
            iteml = QTableWidgetItem(str(annotation[key]))
            self.reaction_mask.annotation.setItem(i, 0, keyl)
            self.reaction_mask.annotation.setItem(i, 1, iteml)
            i += 1

        self.reaction_mask.annotation.itemChanged.connect(
            self.reaction_mask.throttler.throttle)

    def reaction_selected(self, item: QTreeWidgetItem, _column):
        if item is None:
            self.reaction_mask.hide()
        else:
            item.setSelected(True)
            self.reaction_mask.show()
            reaction: cobra.Reaction = item.data(3, 0)

            self.last_selected = reaction.id
            self.reaction_mask.reaction = reaction

            self.reaction_mask.id.setText(reaction.id)
            self.reaction_mask.name.setText(reaction.name)
            self.reaction_mask.equation.setText(
                reaction.build_reaction_string())
            self.reaction_mask.lower_bound.setText(str(reaction.lower_bound))
            self.reaction_mask.upper_bound.setText(str(reaction.upper_bound))
            self.reaction_mask.coefficent.setText(
                str(reaction.objective_coefficient))
            self.reaction_mask.gene_reaction_rule.setText(
                str(reaction.gene_reaction_rule))
            self.update_annotations(reaction.annotation)

            self.reaction_mask.changed = False

            turn_white(self.reaction_mask.id)
            turn_white(self.reaction_mask.name)
            turn_white(self.reaction_mask.name)
            turn_white(self.reaction_mask.equation)
            turn_white(self.reaction_mask.lower_bound)
            turn_white(self.reaction_mask.upper_bound)
            turn_white(self.reaction_mask.coefficent)
            turn_white(self.reaction_mask.gene_reaction_rule)
            self.reaction_mask.is_valid = True
        (_, r) = self.splitter.getRange(1)
        self.splitter.moveSplitter(r/2, 1)
        self.reaction_mask.update_state()

    def handle_changed_reaction(self, reaction: cobra.Reaction):
        # Update reaction item in list
        root = self.reaction_list.invisibleRootItem()
        child_count = root.childCount()
        for i in range(child_count):
            item = root.child(i)
            if item.data(3, 0) == reaction:
                old_id = item.text(0)
                item.setText(0, reaction.id)
                item.setText(1, reaction.name)
                break

        self.last_selected = self.reaction_mask.id.text()
        self.reactionChanged.emit(old_id, reaction)

    def handle_deleted_reaction(self, reaction: cobra.Reaction):
        '''Remove reaction item from reaction list'''
        root = self.reaction_list.invisibleRootItem()
        child_count = root.childCount()
        for i in range(child_count):
            item = root.child(i)
            if item.data(3, 0) == reaction:
                # remove item
                self.reaction_list.takeTopLevelItem(
                    self.reaction_list.indexOfTopLevelItem(item))
                break

        self.last_selected = self.reaction_mask.id.text()
        self.reactionDeleted.emit(reaction)

    def update_selected(self, string):
        root = self.reaction_list.invisibleRootItem()
        child_count = root.childCount()
        for i in range(child_count):
            item = root.child(i)
            item.setHidden(True)

        for item in self.reaction_list.findItems(string, Qt.MatchContains, 0):
            item.setHidden(False)
        for item in self.reaction_list.findItems(string, Qt.MatchContains, 1):
            item.setHidden(False)

    def update(self):
        self.reaction_list.clear()
        for r in self.appdata.project.cobra_py_model.reactions:
            self.add_reaction(r)

        if self.last_selected is None:
            pass
        else:
            items = self.reaction_list.findItems(
                self.last_selected, Qt.MatchExactly)

            for i in items:
                self.reaction_list.setCurrentItem(i)
                break

        self.reaction_mask.update_state()

    def set_current_item(self, key):
        self.last_selected = key
        self.update()

    def emit_jump_to_map(self, idx: str, reaction: str):
        self.jumpToMap.emit(idx, reaction)

    def emit_jump_to_metabolite(self, metabolite):
        self.jumpToMetabolite.emit(metabolite)

    itemActivated = Signal(str)
    reactionChanged = Signal(str, cobra.Reaction)
    reactionDeleted = Signal(cobra.Reaction)
    jumpToMap = Signal(str, str)
    jumpToMetabolite = Signal(str)

class JumpButton(QPushButton):
    """button to jump to reactions on map"""

    def __init__(self, parent, r_id: str):
        QPushButton.__init__(self, r_id)
        self.parent = parent
        self.id: str = r_id
        self.clicked.connect(self.emit_jump_to_map)

    def emit_jump_to_map(self):
        self.jumpToMap.emit(self.id)

    jumpToMap = Signal(str)

class JumpList(QWidget):
    """List of buttons to jump to reactions on map"""

    def __init__(self, parent):
        QWidget.__init__(self)
        self.parent = parent
        self.layout = QHBoxLayout()
        self.layout.setAlignment(Qt.AlignLeft)

    def clear(self):
        for i in reversed(range(self.layout.count())):
            self.layout.itemAt(i).widget().setParent(None)

    def add(self, name: str):
        if self.layout.count() == 0:
            label = QLabel("Jump to reaction on map:")
            self.layout.addWidget(label)

        jb = JumpButton(self, name)
        policy = QSizePolicy()
        policy.ShrinkFlag = True
        jb.setSizePolicy(policy)
        self.layout.addWidget(jb)
        self.setLayout(self.layout)

        jb.jumpToMap.connect(self.parent.emit_jump_to_map)

    @ Slot(str)
    def emit_jump_to_map(self: JumpButton, name: str):
        self.parent.emit_jump_to_map(name)

    jumpToMap = Signal(str)

class ReactionMask(QWidget):
    """The input mask for a reaction"""

    def __init__(self, parent: ReactionList):
        QWidget.__init__(self)

        self.parent = parent
        self.reaction = None
        self.is_valid = True
        self.changed = False
        self.setAcceptDrops(False)

        layout = QVBoxLayout()
        l = QHBoxLayout()
        self.delete_button = QPushButton("Delete reaction")
        self.delete_button.setIcon(QIcon.fromTheme("edit-delete"))
        policy = QSizePolicy()
        policy.ShrinkFlag = True
        self.delete_button.setSizePolicy(policy)
        l.addWidget(self.delete_button)
        layout.addItem(l)

        l = QHBoxLayout()
        label = QLabel("Id:")
        self.id = QLineEdit()
        l.addWidget(label)
        l.addWidget(self.id)
        layout.addItem(l)

        l = QHBoxLayout()
        label = QLabel("Name:")
        self.name = QLineEdit()
        l.addWidget(label)
        l.addWidget(self.name)
        layout.addItem(l)

        l = QHBoxLayout()
        label = QLabel("Equation:")
        self.equation = QLineEdit()
        l.addWidget(label)
        l.addWidget(self.equation)
        layout.addItem(l)

        l = QHBoxLayout()
        label = QLabel("Rate min:")
        self.lower_bound = QLineEdit()
        l.addWidget(label)
        l.addWidget(self.lower_bound)
        layout.addItem(l)

        l = QHBoxLayout()
        label = QLabel("Rate max:")
        self.upper_bound = QLineEdit()
        l.addWidget(label)
        l.addWidget(self.upper_bound)
        layout.addItem(l)

        l = QHBoxLayout()
        label = QLabel("Coefficient in obj. function:")
        self.coefficent = QLineEdit()
        l.addWidget(label)
        l.addWidget(self.coefficent)
        layout.addItem(l)

        l = QHBoxLayout()
        label = QLabel("Gene reaction rule:")
        self.gene_reaction_rule = QLineEdit()
        l.addWidget(label)
        l.addWidget(self.gene_reaction_rule)
        layout.addItem(l)

        l = QVBoxLayout()
        label = QLabel("Annotations:")
        l.addWidget(label)
        l2 = QHBoxLayout()
        self.annotation = QTableWidget(0, 2)
        self.annotation.setHorizontalHeaderLabels(
            ["key", "value"])
        self.annotation.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        l2.addWidget(self.annotation)

        self.add_anno = QPushButton("+")
        self.add_anno.clicked.connect(self.add_anno_row)
        l2.addWidget(self.add_anno)
        l.addItem(l2)
        layout.addItem(l)

        l = QVBoxLayout()
        label = QLabel("Metabolites involved in this reaction:")
        l.addWidget(label)
        l2 = QHBoxLayout()
        self.metabolites = QTreeWidget()
        self.metabolites.setHeaderLabels(["Id"])
        self.metabolites.setSortingEnabled(True)
        l2.addWidget(self.metabolites)
        l.addItem(l2)
        self.metabolites.itemDoubleClicked.connect(
            self.emit_jump_to_metabolite)
        layout.addItem(l)

        self.jump_list = JumpList(self)
        layout.addWidget(self.jump_list)

        self.setLayout(layout)

        self.delete_button.clicked.connect(self.delete_reaction)

        self.throttler = SignalThrottler(500)
        self.throttler.triggered.connect(self.reaction_data_changed)

        self.id.textEdited.connect(self.throttler.throttle)
        self.name.textEdited.connect(self.throttler.throttle)
        self.equation.textEdited.connect(self.throttler.throttle)
        self.lower_bound.textEdited.connect(self.throttler.throttle)
        self.upper_bound.textEdited.connect(self.throttler.throttle)
        self.coefficent.textEdited.connect(self.throttler.throttle)
        self.gene_reaction_rule.textEdited.connect(self.throttler.throttle)
        self.annotation.itemChanged.connect(self.throttler.throttle)

        self.validate_mask()

    def add_anno_row(self):
        i = self.annotation.rowCount()
        self.annotation.insertRow(i)
        self.changed = True

    def apply(self):
        try:
            self.reaction.id = self.id.text()
        except ValueError:
            turn_red(self.id)
            QMessageBox.information(
                self, 'Invalid id', 'Could not apply changes identifier ' +
                self.id.text() + ' already used.')
        else:
            self.reaction.name = self.name.text()
            self.reaction.build_reaction_from_string(self.equation.text())
            self.reaction.lower_bound = float(self.lower_bound.text())
            self.reaction.upper_bound = float(self.upper_bound.text())
            self.reaction.objective_coefficient = float(self.coefficent.text())
            self.reaction.gene_reaction_rule = self.gene_reaction_rule.text()
            self.reaction.annotation = {}
            rows = self.annotation.rowCount()
            for i in range(0, rows):
                key = self.annotation.item(i, 0).text()
                if self.annotation.item(i, 1) is None:
                    value = ""
                else:
                    value = self.annotation.item(i, 1).text()

                self.reaction.annotation[key] = value

            self.changed = False
            self.reactionChanged.emit(self.reaction)

    def delete_reaction(self):
        self.hide()
        self.reactionDeleted.emit(self.reaction)

    def validate_id(self):

        with self.parent.appdata.project.cobra_py_model as model:
            try:
                r = cobra.Reaction(id=self.id.text())
                model.add_reaction(r)
            except ValueError:
                turn_red(self.id)
                return False
            else:
                turn_white(self.id)
                return True

    def validate_name(self):
        with self.parent.appdata.project.cobra_py_model as model:
            try:
                r = cobra.Reaction(id="testid", name=self.name.text())
                model.add_reaction(r)
            except ValueError:
                turn_red(self.name)
                return False
            else:
                turn_white(self.name)
                return True

    def validate_equation(self):
        ok = False
        test_reaction = cobra.Reaction(
            "xxxx_cnapy_test_reaction", name="cnapy test reaction")
        with self.parent.appdata.project.cobra_py_model as model:
            model.add_reaction(test_reaction)

            try:
                eqtxt = self.equation.text().rstrip()
                if len(eqtxt) > 0 and eqtxt[-1] == '+':
                    turn_red(self.equation)
                else:
                    test_reaction.build_reaction_from_string(eqtxt)
                    turn_white(self.equation)
                    ok = True
            except ValueError:
                turn_red(self.equation)

        try:
            test_reaction = self.parent.appdata.project.cobra_py_model.reactions.get_by_id(
                "xxxx_cnapy_test_reaction")
            self.parent.appdata.project.cobra_py_model.remove_reactions(
                [test_reaction], remove_orphans=True)
        except KeyError:
            pass

        return ok

    def validate_lowerbound(self):
        try:
            _x = float(self.lower_bound.text())
        except ValueError:
            turn_red(self.lower_bound)
            return False
        else:
            turn_white(self.lower_bound)
            return True

    def validate_upperbound(self):
        try:
            _x = float(self.upper_bound.text())
        except ValueError:
            turn_red(self.upper_bound)
            return False
        else:
            turn_white(self.upper_bound)
            return True

    def validate_coefficient(self):
        try:
            _x = float(self.coefficent.text())
        except ValueError:
            turn_red(self.coefficent)
            return False
        else:
            turn_white(self.coefficent)
            return True

    def validate_gene_reaction_rule(self):
        try:
            _x = float(self.gene_reaction_rule.text())
        except ValueError:
            turn_red(self.gene_reaction_rule)
            return False
        else:
            turn_white(self.gene_reaction_rule)
            return True

    def validate_mask(self):

        valid_id = self.validate_id()
        valid_name = self.validate_name()
        valid_equation = self.validate_equation()
        valid_lb = self.validate_lowerbound()
        valid_ub = self.validate_upperbound()
        valid_coefficient = self.validate_coefficient()
        if valid_id & valid_name & valid_equation & valid_lb & valid_ub & valid_coefficient:
            self.is_valid = True
        else:
            self.is_valid = False

    def reaction_data_changed(self):
        self.changed = True
        self.validate_mask()
        if self.is_valid:
            self.apply()
            self.update_state()

    def update_state(self):
        self.jump_list.clear()
        for name, m in self.parent.appdata.project.maps.items():
            if self.id.text() in m["boxes"]:
                self.jump_list.add(name)

        self.metabolites.clear()
        if self.parent.appdata.project.cobra_py_model.reactions.has_id(self.id.text()):
            reaction = self.parent.appdata.project.cobra_py_model.reactions.get_by_id(
                self.id.text())
            for m in reaction.metabolites:
                item = QTreeWidgetItem(self.metabolites)
                item.setText(0, m.id)
                item.setText(1, m.name)
                item.setData(2, 0, m)
                text = "Id: " + m.id + "\nName: " + m.name
                item.setToolTip(1, text)

    def emit_jump_to_map(self, name):
        self.jumpToMap.emit(name, self.id.text())

    def emit_jump_to_metabolite(self, metabolite):
        self.jumpToMetabolite.emit(str(metabolite.data(2, 0)))

    jumpToMap = Signal(str, str)
    jumpToMetabolite = Signal(str)
    reactionChanged = Signal(cobra.Reaction)
    reactionDeleted = Signal(cobra.Reaction)


# uncompyle6 version 3.7.4
# Python bytecode 3.6 (3379)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: D:\pycharm_project\ecd\ecd\password_manage\app\handle_data.py
# Compiled at: 2019-05-07 11:28:55
# Size of source mod 2**32: 2072 bytes
"""
@author:ZouLingyun
@date:
@summary:
"""
import os
from difflib import SequenceMatcher
from itertools import chain
import pandas as pd

class HandleData(object):

    def __init__(self, cache_file=None):
        self.cache_file = cache_file or 'D:\\tmp\\password_infos.xlsx'
        if not os.path.exists(os.path.dirname(self.cache_file)):
            os.makedirs((os.path.dirname(self.cache_file)), exist_ok=True)
        self.cache_dict = None
        self.pre_mtime = None
        self.load_cache()

    def load_cache(self):
        self.cache_dict = {}
        if not os.path.exists(self.cache_file):
            cache_df = pd.DataFrame(columns=['key', 'value'])
            cache_df.to_excel((self.cache_file), index=False)
            self.cache_dict = {}
        else:
            cache_df = pd.read_excel(self.cache_file)
            cache_df = cache_df.astype(str)
            _tmp_dict = cache_df.to_dict(orient='records')
            for row_dict in _tmp_dict:
                key, value = row_dict['key'].strip(), row_dict['value']
                if key not in self.cache_dict:
                    self.cache_dict[key] = []
                if row_dict not in self.cache_dict[key]:
                    row_dict['show'] = key.ljust(20) + ':' + value
                    self.cache_dict[key].append(row_dict)

        self.pre_mtime = os.stat(self.cache_file).st_mtime

    def search(self, input_word=None, pre_count=10):
        if self.pre_mtime != os.stat(self.cache_file).st_mtime:
            self.load_cache()
        key_seq = self.cache_dict.keys()
        sim_seq = [(key, SequenceMatcher(a=input_word, b=(key.lower())).quick_ratio()) for key in key_seq]
        sim_seq.sort(key=(lambda x: x[1]), reverse=True)
        sim_seq = list(filter(lambda x: x[1] > 0.2, sim_seq))
        targ_keys = [self.cache_dict[key] for key, _ in sim_seq[:pre_count]]
        return list(chain.from_iterable(targ_keys))

if __name__ == '__main__':
    a = HandleData().search('大战', 10)
    print(a)


from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse, reverse_lazy
from django.views.generic import ListView, DetailView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic.edit import FormMixin
from django.db.models import Q
from .models import modelPaket, imagesPaket
from Transaksi.models import modelTransaksi
from Transaksi.form import TransaksiForm
import datetime

# Create your views here.

class SearchPaket(ListView):
    model = modelPaket
    template_name = 'paket/viewPaket.html'
    context_object_name = 'paket_object'
    extra_context = {
        'title': 'PAKET LIST',
    }
    query_string = None

    def findSeacrh(self):
        url = self.request.GET.get('search', False)
        if url != False:
            dataPaket = []
            self.queryset = self.model.objects.filter(
                Q(nama_paket__icontains=self.request.GET['search']) |
                Q(destinasi__icontains=self.request.GET['search'])
            )
            for x in self.queryset:
                if x.tgl_berangkat > datetime.date.today():
                    print(x.tgl_berangkat)
                    dataPaket.append(x)
                print(len(dataPaket))
            if len(dataPaket) == 0:
                self.extra_context = {
                    'title': 'PAKET LIST',
                    'error': "Data Tidak diTemukan"
                }
                self.queryset = None
                return self.queryset
            else:
                return dataPaket
        else:
            self.query_string = False

    def get_queryset(self):
        if self.query_string:
            data = self.findSeacrh()
            return data
        else:
            dataPaket = []
            for x in self.model.objects.all():
                if x.tgl_berangkat > datetime.date.today():
                    dataPaket.append(x)
            return dataPaket;

    def get(self, *args, **kwargs):
        if self.query_string:
            if self.request.GET.get('search', False) is False:
                return HttpResponseRedirect(reverse('paket:view'))
        return super().get(self.request, *args, **kwargs)

class DetailPaket(FormMixin, DetailView):
    form_class = TransaksiForm
    model = modelPaket
    initial={}
    template_name = 'paket/detailPaket.html'
    extra_context = {
        'title': 'DETAIL',
    }

    def get_initial(self):
        dataPaket = self.model.objects.get(slug=self.kwargs['slug'])

        if self.request.user.is_authenticated:
            self.initial={
            'paket':dataPaket.slug,
            'user':self.request.user.email
            }
            return self.initial.copy()
        else:
            return super().get_initial()


from distutils.command.install import install
from distutils.command.build_scripts import build_scripts
from distutils.core import setup
import hashlib
import os
import platform
import re
import tempfile
import sys
import zipfile

try:
    from urllib import request
except ImportError:
    import urllib as request

class BuildScripts(build_scripts):
    """Downloads and unzips the requested chrome executable."""

    def _download(self, zip_path):

        base_url = "http://commondatastorage.googleapis.com/chromium-browser-snapshots/Linux_x64"

        version = request.urlopen(base_url+'/LAST_CHANGE').read().decode("utf-8")

        url = "{0}/{1}/chrome-linux.zip".format(base_url,version)

        def reporthoook(x, y, z):
            global download_ok

            percent_downloaded = '{0:.0%}'.format((x * y) / float(z))
            sys.stdout.write('\r')
            sys.stdout.write("{0} [{1}]".format(url,
                                                percent_downloaded))
            download_ok =  percent_downloaded == '100%'
            if download_ok:
                sys.stdout.write(' OK')
            sys.stdout.flush()

        request.urlretrieve(url, zip_path, reporthoook)

        print('')
        if not download_ok:
            print('\t - download failed!')

    def _unzip(self, zip_path):
        zf = zipfile.ZipFile(zip_path)
        print("\t - extracting '{0}' to '{1}'."
              .format(zip_path, self.build_dir))

        tmp = os.path.join(tempfile.gettempdir(), 'tmp')
        zf.extractall(tmp)
        self.copy_tree(tmp+'/chrome-linux/',self.build_dir)

    def run(self):

        file_name = 'chrome-linux.zip'
        zip_path = os.path.join(tempfile.gettempdir(), file_name)

        # if validate:
        #     if os.path.exists(zip_path):
        #         print("\t - requested file '{0}' found at '{1}'."
        #               .format(file_name, zip_path))
        #
        #         if self._validate(zip_path):
        #             print("\t - cached file '{0}' is valid.".format(zip_path))
        #         else:
        #             print("\t - cached file '{0}' is not valid!"
        #                   .format(zip_path))
        #             self._download(zip_path, validate=True)
        #     else:
        #         self._download(zip_path, validate=True)
        # else:
        self._download(zip_path)

        self._unzip(zip_path)
        self.scripts = [os.path.join(self.build_dir, script) for script in
                        os.listdir(self.build_dir)]
        build_scripts.run(self)

    def finalize_options(self):
        build_scripts.finalize_options(self)
        self.scripts = []

class Install(install):
    """Used to get chromedriver version and checksums from install options"""

    # Fix an error when pip calls setup.py with the
    # --single-version-externally-managed and it is not supported due to
    # old setuptools version.
    _svem = list(filter(lambda x: x[0] == 'single-version-externally-managed',
                        install.user_options))

    if not _svem:
        single_version_externally_managed = None
        install.user_options.append(('single-version-externally-managed',
                                     None, ""))

    user_options = install.user_options + [
        ('chromedriver-version=', None, 'Chromedriver version'),
        ('chromedriver-checksums=', None, 'Chromedriver checksums'),
    ]

    def initialize_options(self):
        self.chromedriver_version = None
        self.chromedriver_checksums = []
        install.initialize_options(self)

    def run(self):

        install.run(self)

setup(
    name='chrome_install',
    version='0.0.1',
    author='Guy Matzliach',
    author_email='gmatzlia@akamai.com',
    description='Chrome Install',
    long_description=open(os.path.join(os.path.dirname(__file__), 'README.rst'))
        .read(),
    keywords='chrome install',
    url='https://github.com/akaguy/chrome_install',
    classifiers=[
    ],
    license='MIT',
    package_data={'': ['*.txt', '*.rst']},
    packages=['chrome_install'],
    scripts=['if', 'empty', 'BuildScripts', 'will', 'be', 'ignored'],
    cmdclass=dict(build_scripts=BuildScripts, install=Install)
)


# mysite/routing.py
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import chat.routing

#ProtocolTypeRouter将首先检查连接类型，如果它是WebSocket(ws://或wss://),将连接到AuthMiddlewareStack
#在AuthMiddlewareStack 将填充的连接的范围与到当前认证用户，然后将连接到URLRouter
application = ProtocolTypeRouter({
    # (http->django views is added by default)
    'websocket': AuthMiddlewareStack(
        URLRouter(
            chat.routing.websocket_urlpatterns
        )
    ),
})


import argparse
import csv
import logging
from typing import Dict, Iterator, List

from django.core.exceptions import ValidationError
from django.core.management.base import BaseCommand

from mapusaurus.batch_utils import save_batches
from respondents.models import Agency, Institution
from respondents.zipcode_utils import create_zipcode

logger = logging.getLogger(__name__)

def fixup(line):
    """Account for misformatted data from FFIEC with one-off fixups"""
    if line[0] == "2016" and line[1] == "0000021122" and len(line) == 23:
        return line[:6] + line[7:]
    return line

def load_from_csv(
        agencies: Dict[int, Agency], transmittal_reader: Iterator[List[str]]):
    for zero_line_number, line in enumerate(transmittal_reader):
        line_number = zero_line_number + 1
        line = fixup(line)
        if len(line) not in (15, 22):
            logger.warning(
                "Line %s is invalid, has length %s (expected 15 or 22)",
                line_number,
                len(line),
            )
            break
        year = int(line[0])
        zipcode_city = create_zipcode(
            city=line[6], state=line[7], year=year, zip_code=line[8])

        agency_id = line[2]
        if not agency_id.isdigit() or int(agency_id) not in agencies:
            logger.warning("Line %s has an invalid agency: %s",
                           line_number, agency_id)
            break

        if len(line) == 22 and not line[17].isdigit():
            logger.warning("Line %s has an invalid asset amount: %s",
                           line_number, line[17])
            break

        respondent_id = line[1]

        inst = Institution(
            year=year,
            respondent_id=line[1],
            agency=agencies[int(agency_id)],
            institution_id=f"{year}{agency_id}{respondent_id}",
            tax_id=line[3],
            name=line[4],
            mailing_address=line[5],
            zip_code=zipcode_city,
            assets=int(line[17]) if len(line) == 22 else None,
        )
        try:
            inst.full_clean(exclude=["agency"], validate_unique=False)
        except ValidationError:
            logger.exception("Line %s has invalid data:", line_number)
            break

        yield inst

class Command(BaseCommand):
    help = "Loads data from a HMDA Transmittal Sheet."  # noqa

    def add_arguments(self, parser):
        parser.add_argument("file_name", type=argparse.FileType("r"))
        parser.add_argument("--replace", action="store_true")
        parser.add_argument("--delimiter", default="\t")

    def handle(self, *args, **options):
        agencies = Agency.objects.get_all_by_code()
        transmittal_reader = csv.reader(
            options["file_name"], delimiter=options["delimiter"])
        institutions = load_from_csv(agencies, transmittal_reader)
        save_batches(institutions, options["replace"], batch_size=1000)
        options["file_name"].close()