import os
from PIL import Image
from scipy.ndimage.filters import gaussian_filter
import cv2
import random       # shuffle
import shutil       # To copy the file
import sys
import numpy as np
import torch
from torchvision import transforms
from torch.utils.data import Dataset

import backbone as b
from config import *

transform = transforms.Compose([
    transforms.ToTensor()
])

class AitexDataSet(Dataset):
    def __init__(self, main_dir, masks=False):
        self.main_dir = main_dir
        self.transform = transform
        self.all_imgs = sorted(os.listdir(main_dir))
        self.masks = masks
        if masks:
            self.mask_dir = aitex_mask_dir
            self.all_mask = sorted(os.listdir(self.mask_dir))

    def __len__(self):
        return len(self.all_imgs)

    def __getitem__(self, idx):
        img_loc = os.path.join(self.main_dir, self.all_imgs[idx])
        image = Image.open(img_loc).convert('L')
        tensor_image = self.transform(image)
        if self.masks:
            mask_name = self.all_imgs[idx].replace('.png', '_mask.png')
            if os.path.isfile(self.mask_dir + '/' + mask_name):
                mask_loc = os.path.join(self.mask_dir, mask_name)
                mask = Image.open(mask_loc).convert('L')
                tensor_mask = transform(mask)
            else:
                tensor_mask = torch.zeros([1, 256, 4096])
            return tensor_image, tensor_mask
        else:
            return tensor_image

    def getName(self, idx, mask=False):
        if mask:
            return self.all_imgs[idx].replace('.png', '_mask.png')
        else:
            return self.all_imgs[idx]

def augmentationDataset(dataset):
    ds = []
    widths = []
    heights = []
    for i in range(len(dataset)):
        j = dataset.__getitem__(i)

        ds.append(j)                                                    # Original image
        widths.append(j.shape[2])
        heights.append(j.shape[1])

        noised_image = b.add_noise(j, noise_factor=0.05)                # Gaussian noise
        ds.append(noised_image)
        widths.append(noised_image.shape[2])
        heights.append(noised_image.shape[1])

        j = np.transpose(j.numpy(), (1, 2, 0))
        ds.append(torch.tensor(np.fliplr(j).copy()).permute(2, 0, 1))   # orizontal flip
        widths.append(j.shape[1])
        heights.append(j.shape[0])

        ds.append(torch.tensor(np.flipud(j).copy()).permute(2, 0, 1))   # vertical flip
        widths.append(j.shape[1])
        heights.append(j.shape[0])

        blurred = gaussian_filter(j, sigma=0.5)                         # blur
        ds.append(torch.tensor(blurred).permute(2, 0, 1))
        widths.append(j.shape[1])
        heights.append(j.shape[0])

    return ds, widths, heights

def resizeAitex(dataset, original_width, original_height, dataset_masks=False):
    ds = []
    new_widths = []
    new_heights = []
    if not dataset_masks:
        for img in dataset:
            img_ = img.squeeze(0).numpy()
            img_ = cv2.normalize(img_, None, alpha = 0, beta = 255, norm_type = cv2.NORM_MINMAX, dtype = cv2.CV_32F)
            img_ = img_.astype(np.uint8)

            # Blur the image for better edge detection
            img_blur = cv2.GaussianBlur(img_,(3,3), sigmaX=0, sigmaY=0)

            # Canny Edge Detection
            edges = cv2.Canny(image=img_blur, threshold1=100, threshold2=200)

            vector = np.zeros(original_width)
            for i in range(original_width):
                for j in range(original_height):
                    vector[i] += edges[j][i]
            derivative = np.gradient(vector)
            max = np.argmax(derivative)
            cut = (int(max/patch_size) + CUT_PATCHES) * patch_size

            crop_img = transforms.functional.crop(img, top=0, left=cut, height=original_height, width=(original_width-cut))
            new_widths.append(crop_img.shape[2])
            new_heights.append(crop_img.shape[1])

            ds.append(crop_img)
    else:
        for img in dataset:
            img_ = img[0].squeeze(0).numpy()
            img_ = cv2.normalize(img_, None, alpha = 0, beta = 255, norm_type = cv2.NORM_MINMAX, dtype = cv2.CV_32F)
            img_ = img_.astype(np.uint8)

            # Blur the image for better edge detection
            img_blur = cv2.GaussianBlur(img_, (3,3), sigmaX=0, sigmaY=0)

            # Canny Edge Detection
            edges = cv2.Canny(image=img_blur, threshold1=100, threshold2=200)

            vector = np.zeros(original_width)
            for i in range(original_width):
                for j in range(original_height):
                    vector[i] += edges[j][i]
            derivative = np.gradient(vector)
            max = np.argmax(derivative)
            cut = (int(max/patch_size) + CUT_PATCHES) * patch_size

            crop_img = transforms.functional.crop(img[0], top=0, left=cut, height=original_height, width=(original_width-cut))
            new_widths.append(crop_img.shape[2])
            new_heights.append(crop_img.shape[1])

            m = transforms.functional.crop(img[1], top=0, left=cut, height=original_height, width=(original_width-cut))
            ds.append([crop_img, m])
    return ds, new_widths, new_heights

# --------------- Functions to create Aitex Dataset ---------------

def Reformat_Image(ImageFilePath, new_width, new_height, color, offset):

    image = Image.open(ImageFilePath, 'r')
    image_size = image.size
    width = image_size[0]
    height = image_size[1]

    if color == 'white':
        color = (255, 255, 255, 255)
    elif color == 'black':
        color = (0, 0, 0, 255)

    if offset == 'center':
        offset = (int(round(((new_width - width) / 2), 0)), int(round(((new_height - height) / 2), 0)))
    elif offset == 'right':
        offset = (0, 0)
    elif offset == 'left':
        offset = ((new_width - width), (new_height - height))

    background = Image.new('RGBA', (new_width, new_height), color)

    background.paste(image, offset)
    background.save(ImageFilePath)
    # print("Image " + ImageFilePath + " has been resized!")

def DeleteFolder(path):
    shutil.rmtree(path)
    # print(path + ' deleted!')

def MergeMasks(name):
    mask1 = Image.open(name+'_mask1.png').convert('L')
    mask2 = Image.open(name+'_mask2.png').convert('L')
    mask1 = np.array(mask1)
    mask2 = np.array(mask2)
    mask = np.add(mask1, mask2)
    mask = Image.fromarray(mask)
    mask.save(name+'_mask.png',"PNG")
    os.remove(name+'_mask1.png')
    os.remove(name+'_mask2.png')

def BinarizeMasks(Mask_path):
    thresh = 128
    maxval = 255

    all_imgs = sorted(os.listdir(Mask_path))
    for i in all_imgs:
        im_gray = np.array(Image.open(Mask_path+i).convert('L'))
        im_bin = (im_gray > thresh) * maxval
        Image.fromarray(np.uint8(im_bin)).save(Mask_path+i)

def FlipImage(filename):
    image = Image.open(filename)
    image = np.fliplr(image)
    Image.fromarray(np.uint8(image)).save(filename)

def CreateAitexDataset(AitexFolder):
    Defect_path = AitexFolder + 'Defect_images/'
    NODefect_path = AitexFolder + 'NODefect_images/'
    Mask_path = AitexFolder + 'Mask_images/'

    NODefect_subdirectories = ['2306881-210020u', '2306894-210033u', '2311517-195063u', '2311694-1930c7u',
                               '2311694-2040n7u', '2311980-185026u', '2608691-202020u']

    Reformat_Image(Defect_path + '0094_027_05.png', 4096, 256, 'white', 'right')
    Reformat_Image(Mask_path + '0094_027_05_mask.png', 4096, 256, 'black', 'right')
    os.remove(Defect_path + '0100_025_08.png')
    FlipImage(Defect_path + '0094_027_05.png')
    FlipImage(Mask_path + '0094_027_05_mask.png')

    defect_images = os.listdir(Defect_path)
    nodefect_images = []

    for i in range(len(NODefect_subdirectories)):
        for j in os.listdir(NODefect_path + NODefect_subdirectories[i]):
            nodefect_images.append(NODefect_subdirectories[i] + '/' + j)

    random.shuffle(nodefect_images)

    train_folder = AitexFolder + 'trainset/'
    validation_folder = AitexFolder + 'validationset/'
    test_folder = AitexFolder + 'testset/'

    os.makedirs(train_folder, exist_ok=True)
    os.makedirs(validation_folder, exist_ok=True)
    os.makedirs(test_folder, exist_ok=True)

    train_range = [0, len(nodefect_images) - int(len(nodefect_images) * 20 / 100)]  # 60% train set without defects
    validation_range = [len(nodefect_images) - int(len(nodefect_images) * 20 / 100),
                                 len(nodefect_images)]  # 20% validation set without defects

    for i in range(train_range[0], train_range[1]):
        shutil.copyfile(NODefect_path + nodefect_images[i], train_folder + nodefect_images[i].split('/')[1])
    for i in range(validation_range[0], validation_range[1]):
        shutil.copyfile(NODefect_path + nodefect_images[i], validation_folder + nodefect_images[i].split('/')[1])
    for i in defect_images:
        shutil.copyfile(Defect_path + i, test_folder + i)

    DeleteFolder(Defect_path)
    DeleteFolder(NODefect_path)
    MergeMasks(Mask_path+'0044_019_04')   # Merge and delete 0044_019_04.png masks:
    MergeMasks(Mask_path+'0097_030_03')   # Merge and delete 0097_030_03.png masks:
    BinarizeMasks(Mask_path)

def checkAitex():
    if os.path.isdir(aitex_folder):
        if (os.path.isdir(aitex_train_dir) and os.path.isdir(aitex_validation_dir) and os.path.isdir(aitex_test_dir) and os.path.isdir(aitex_mask_dir)):
            return
        else:
            info_file = Config().getInfoFile()
            b.myPrint("Preparing the AITEX dataset...", info_file)
            CreateAitexDataset(aitex_folder+'/')
    else:
        print('ERROR: Run \'./utils/get_aitex.sh\' firstly!')
        sys.exit(-1)


from django.core.paginator import Paginator
from django.shortcuts import render

# Create your views here.
from news.Counter import Counter
from news.models import Submission, SubmissionType

def gen_paginator(request, query, number=30):
    subm_paginator = Paginator(query, number)
    page_num = request.GET.get('pages')

    if page_num == None:
        pages = subm_paginator.page(1)
    else:
        pages = subm_paginator.page(page_num)

    page_index = Counter()
    page_index.count = pages.start_index()

    return pages

def news(request):
    pages = gen_paginator(request, Submission.objects.order_by('-points'), 30)
    page_index = Counter()
    page_index.count = pages.start_index()
    return render(request, "news.html", {'pages': pages, 'index': page_index})

def newest(request):
    pages = gen_paginator(request, Submission.objects.order_by('-created_at'), 30)
    page_index = Counter()
    page_index.count = pages.start_index()
    return render(request, "newsest.html", {"pages": pages, 'index': page_index})

def ask(request):
    type = SubmissionType.objects.get(name="ask")
    pages = gen_paginator(request, Submission.objects.filter(type=type).order_by('-points'), 30)
    page_index = Counter()
    page_index.count = pages.start_index()
    return render(request, "ask.html", {"pages": pages, 'index': page_index})


#coding=utf-8
#./node_modules/.bin/chromedriver --verbose --log-path=chromedriver.log
# electron .  --remote-debugging-port=9200  --nokiosk   --http

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9200")

driver = webdriver.Chrome(options=chrome_options)

executor_url = driver.command_executor._url
session_id = driver.session_id
print(session_id)
print(executor_url)
driver.get('https://www.baidu.com')
# driver.find_element_by_id("set_button1").click()

driver2 = webdriver.Remote(command_executor=executor_url, desired_capabilities={})
driver2.session_id = session_id
print(driver2.current_url)


"""
If we wanted to do pages as well as just the link title, we could:

from BeautifulSoup import BeautifulSoup
from urllib import urlopen
soup = BeautifulSoup(urlopen("<<<url>>>").read())
contents = ''.join(soup.findAll(text=True))

to extract the text, then throw everything in the classifier

"""
"""
User clicks an arrow, key + direction are ajax'd to /vote. vote trains the classifier, then
calls Reload which sends info back out through ajax to the page
"""
"""
user clicks down on a link, it fades out, we request a bunch of new new articles from the db.
for each article we classify it, and if it fills the threshold we push it to the user.

"""

import os
import datetime
import simplejson as json
import urllib2
from logging import info as log
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.api import taskqueue

from classifier import *
from models import *

class Vote(webapp.RequestHandler):
    def __init__(self):

        # Load user
        user = users.get_current_user()
        self.user = db.GqlQuery("SELECT * FROM User WHERE user_id = '%s'" % user.user_id()).get()

        # Instantiate the classifier
        self.cl = naivebayes(self.user, getwords)

        self.cl.setthreshold('bad', 2.0)

    def reload(self, user):
        '''
        pull out a bunch of entries. classify each one. take the strongest
        one corresponding with 'up' and display it.

        make sure not to pull any that have already been voted on, OR
        are already being displayed.
        '''

        count = 0
        down = True
        while down and count < 100:
            #print count
            count += 10
            posts = db.GqlQuery("SELECT * FROM Node ORDER BY created, points ASC").fetch(100)
            for p in posts:
                cat = self.cl.classify(p.title, default='unknown')
                log(cat)
                if cat == 'up':
                    log('****FOUND ONE**** %s' %p.title)
                    return p

        log('couldnt find anything')
        return db.GqlQuery("SELECT * FROM Node ORDER BY created, points ASC").get()
        #return story

    def get(self):
        user = self.user

        # Load story
        key = self.request.get("key")
        story = db.get(key)

        # Which direction was clicked?
        dir = str(self.request.get("dir"))

        log("WHOOOOOOOOOOOOOOOOOOOOOOOA %s"  %len(self.request.get("test")))

        # Save the story's key
        user_stories = user.stories.setdefault(dir, [])
        user.stories[dir].append(story.key())
        user.put()

        log('TRAINING:  "%s" | %s' %(story.title, dir))
        self.cl.train(story.title, dir)

        newstory = self.reload(user).to_dict()
        log(newstory)
        self.response.out.write(json.dumps(newstory))

        #self.response.out.write(
        # Set the Threshold

        #print cl.classify('rabbit', default='unknown')
        #print cl.classify('money', default='unknown')
        #print cl.classify('money', default='unknown')
        #print cl.classify('money', default='unknown')
        #self.redirect('/')

class MainPage(webapp.RequestHandler):
    def get(self):
        temp_user = users.get_current_user()
        if temp_user:
            user = db.GqlQuery("SELECT * FROM User WHERE user_id = '%s'" % temp_user.user_id()).get()
            if not user:
                new_user = User(user = temp_user,
                                user_id = temp_user.user_id(),
                                email = temp_user.email())
                new_user.put()
                user = new_user

            posts = db.GqlQuery("SELECT * FROM Node ORDER BY points DESC LIMIT 10")
            template_values = {'user': users.get_current_user(),
                               'logout_url': users.create_logout_url("/"),
                               'posts': posts}

            self.response.out.write(template.render('static/index.html', template_values))
        else:
            self.redirect(users.create_login_url(self.request.uri))

class ScrapeHandler(webapp.RequestHandler):
    def get(self):
        if not db.GqlQuery("SELECT * FROM StopWord").get():
            import stopwords as s
            db.put([StopWord(word = w) for w in s.words()])

        for x in range(10):
            taskqueue.add(url="/scrape_bot", params={'start': (x*100)})

class ScrapeBot(webapp.RequestHandler):
    def post(self):
            base = 'http://api.thriftdb.com/api.hnsearch.com/items/_search?'
            url = base + '%s%s%s' % ('&filter[fields][create_ts]=[NOW-48HOURS%20TO%20NOW]',
                                     '&limit=100', '&filter[fields][type]=submission')
            req = url + '&start=%s' % self.request.get("start")
            log('URL - %s' %req)
            hn_url = "http://news.ycombinator.com/"
            response = urllib2.urlopen(req)
            content = json.loads(response.read())
            for item in content['results']:
                if not db.GqlQuery("SELECT * FROM Node WHERE hn_id = %s" % item['item']['id']).get():
                    i = item['item']
                    scraped_content = Node(hn_id = i['id'], type = i['type'],
                                           url = i['url'] if i['url'] else hn_url + "item?id=%s" % id,
                                           domain = i['domain'] if i['domain'] else hn_url,
                                           title = i['title'], commentcount = i['num_comments'],
                                           username = i['username'], points = i['points'])
                    scraped_content.put()


import scrapy
from scrapy_selenium import SeleniumRequest
from selenium import webdriver
import pandas as pd
from time import sleep

class QuotesSpider(scrapy.Spider):
  # driver = webdriver.Chrome()
  # driver.get('https://quotes.toscrape.com/page/1/')
  # sleep(10)

  name = "quotes"
  allowed_domains = ["quotes.toscrape.com"]
  # start_urls = ["https://quotes.toscrape.com"]

  def start_requests(self):
    url='https://quotes.toscrape.com/'
    yield SeleniumRequest(
      url=url,
      callback=self.parse,
      wait_time=10
    )

  def parse(self, response):
      print('===== parse(self, response) =====')
      # print(response)
      # r = response.css('h1').get()
      # t = response.css('h1 > a::text').get()
      # print(r)
      # print(t)

      for quote in response.css('div.quote'):
        d = {
            'text': quote.css('span.text::text').get(),
            'author': quote.css('small.author::text').get(),
            'tags': quote.css('div.tags a.tag::text').getall(),
        }
        # print(d)
        yield d

      next_page = response.css('li.next a::attr(href)').get()
      print(f'=========={next_page}==========')
      if next_page is not None:
        yield response.follow(next_page, callback=self.parse)

      print('===========')

  # driver.close()

      # pass


import json

import pandas as pd

df = pd.read_csv('./train_finer.csv')
df_result = pd.DataFrame(columns=['text', 'annotation'])

with open('./labels.json', 'r') as JSON:
    label_dict = json.load(JSON)

xbrl_label_dict = {v: k for k, v in label_dict.items()}

f_train = open('./train.txt', 'w')
tokens_length = []
for i, row in df.iterrows():
    tokens = eval(row['tokens'])
    tags = eval(row['ner_tags'])

    #if len(tokens) <= 50:

    for token_index in range(len(tokens)):
        f_train.write(tokens[token_index] + ' ' + xbrl_label_dict[tags[token_index]])
        f_train.write('\n')
        f_train.write('\n')

# print(set(sorted(tokens_length)))


import torch
import torch.nn as nn
import torch.nn.functional as F

class CustomModelLoc(nn.Module):
  def __init__(self, num_classes):
    super(CustomModelLoc, self).__init__()
    self.conv1 = nn.Conv2d(3, 8, 3, padding=1)
    self.conv2 = nn.Conv2d(8, 16, 3, padding=1)
    self.conv3 = nn.Conv2d(16, 32, 3, padding=1)
    self.conv4 = nn.Conv2d(32, 64, 3, padding=1)
    self.pool = nn.MaxPool2d(2, 2)
    self.norm1 = nn.BatchNorm2d(3)
    self.norm2 = nn.BatchNorm2d(8)
    self.norm3 = nn.BatchNorm2d(16)
    self.norm4 = nn.BatchNorm2d(32)
    self.fc1 = nn.Linear(64* 24* 24, 128)
    self.fc2 = nn.Linear(132, 64)
    self.fc3 = nn.Linear(64, num_classes)

  def forward(self, img, data):
    img = self.pool(self.conv1(F.relu(self.norm1(img))))
    img = self.pool(self.conv2(F.relu(self.norm2(img))))
    img = self.pool(self.conv3(F.relu(self.norm3(img))))
    img = self.pool(self.conv4(F.relu(self.norm4(img))))
    img = img.view(img.size(0), -1)
    img = F.relu(self.fc1(img))
    out = torch.cat((img, data), 1)
    out = F.relu(self.fc2(out))
    out = self.fc3(out)
    return out


# result_12 = file2.read()
# print(result_12)
# result_13 = file3.read()
# print(result_13)

    #res = [f'1.txt\n, {result_1} \n, {"line"}\n']
    #with open('resultat.txt','w') as file:
        #file.writelines(res)

file_1 = open('1.txt', 'rt',encoding='utf-8')
file_2 = open('2.txt', 'rt',encoding='utf-8')
file_3 = open('3.txt', 'rt',encoding='utf-8')

result_1 = len(file_1.readlines())
print(f' строк в 1.txt {result_1}')

result_2 = len(file_2.readlines())
print(f' строк в 2.txt {result_2}')

result_3 = len(file_3.readlines())
print(f' Строк в 3.txt {result_3}')

with open('1.txt', 'rt',encoding='utf-8') as file1,open('2.txt', 'rt',encoding='utf-8') as file2,open('3.txt', 'rt',encoding='utf-8') as file3, open('rezultat.txt', 'w', encoding = 'utf-8') as f:

    for line2 in file2:
        f.writelines(f'{file2.name}\n{len(file_2.readlines())+1}\n')
        result_12 = []
        result_12 = line2

        for num_line2, lines2 in enumerate(file2,1):
            otvet2 = f'файл 2, строка, {num_line2},   {lines2}'
            print(otvet2)
            f.writelines(otvet2)

    for line in file1:
        f.writelines(f'\n {file1.name}\n{len(file_1.readlines())+1}\n')
        result_11 = []
        result_11 = line
        for num_line, lines in enumerate(file1,1):
            otvet = f'файл 1, строка, {num_line},   {lines}'
            print(otvet)
            f.writelines(otvet)

    for line in file3:
        f.writelines(f'\n {file3.name}\n{len(file_3.readlines())+1}\n')
        result_13 = []
        result_13 = line
        for num_line, lines in enumerate(file3,1):
            otvet = f'файл 3, строка, {num_line},   {lines}'
            print(otvet)
            f.writelines(otvet)

# res = "1.txt"
# res2 = '2.txt'
# res3 = '3.txt'

# with open('resultat.txt','w+', encoding = 'utf-8') as file_redact:
#     file_redact.writelines(f'{res}\n, {result_1}\n,{result_11}')
#     file_redact.writelines(f'{res2}\n, {result_2}\n,{result_12}')
#     file_redact.writelines(f'{res3}\n, {result_3}\n,{result_13}')

file_1.close()
file_2.close()
file_3.close()
file_1.close()
file_2.close()
file_3.close()

# print(result.sort())


#Escreva um programa que leia um numero n inteiro qualquer e mostre na tela os n primeiros elementos de uma sequencia fibonacci
n = int(input("Digite o número de elementos da sequência Fibonacci que você deseja mostrar: "))

a, b = 0, 1
count = 0

while count < n:
    print(a, end=" ")
    a, b = b, a + b
    count += 1


import sys
from symboltable import SymbolTable
from tokenizer import Tokenizer
from vmwriter import VMWriter

class CompilationEngine:

    def __init__(self, fileName):
        if '-x' in sys.argv:
            self.writer = open(fileName.split('.')[0] + ".xml", 'w')
        self.t = Tokenizer(fileName)
        self.t.advance()
        self.vm = VMWriter(fileName)
        self.table = None
        self.classTable = SymbolTable()
        self.fieldCount = 0
        self.currentWhile = []

    def writeXML(self, s):
        if '-x' in sys.argv:
            self.writer.write(s + '\n')

    def writeToken(self, n=1):
        for i in range(n):
            tempType = '<' + self.t.tokenType + '>'
            tempToken = self.t.token.replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"')
            self.writeXML('<' + self.t.tokenType + '> ' + tempToken + ' </' + self.t.tokenType + '>')
            self.t.advance()

    def compileClass(self):
        self.writeXML("<class>")
        self.writeToken()
        self.className = self.t.token
        self.writeToken(2)
        while self.t.token in ("static", "field"):
            self.compileClassVarDec()
        while self.t.token != '}':
            self.compileSubroutine()
        self.writeToken()
        self.writeXML("</class>")

    def compileClassVarDec(self):
        self.writeXML("<classVarDec>")
        kind = self.t.token
        self.writeToken()
        type = self.t.token
        self.writeToken()
        while self.t.token != ';':
            if self.t.token != ',':
                self.classTable.add(self.t.token, type, kind)
                if kind == "field":
                    self.fieldCount += 1
            self.writeToken()
        self.writeToken()
        self.writeXML("</classVarDec>")

    def compileSubroutine(self):
        self.writeXML("<subroutineDec>")
        self.whileCount = 0
        self.ifCount = 0
        self.table = SymbolTable()
        self.functionKind = self.t.token
        self.writeToken()
        self.functionType = self.t.token
        self.writeToken()
        functionName = self.t.token
        self.writeToken(2)
        self.compileParameterList()
        self.writeToken()
        self.writeXML("<subroutineBody>")
        self.writeToken()
        while self.t.token == "var":
            self.compileVarDec()
        varNum = len([i for i in self.table.table if self.table.getKind(i) == "local"])
        self.vm.writeFunction(self.className + '.' + functionName, varNum)
        if self.functionKind == "constructor":
            self.vm.writePush("constant", self.fieldCount)
            self.vm.writeCall("Memory.alloc", 1)
            self.vm.writePop("pointer", 0)
        elif self.functionKind == "method":
            self.vm.writePush("argument", 0)
            self.vm.writePop("pointer", 0)
        self.compileStatements()
        self.writeToken()
        self.writeXML("</subroutineBody>")
        self.writeXML("</subroutineDec>")

    def compileParameterList(self):
        self.writeXML("<parameterList>")
        if self.functionKind == "method":   # add empty argument for self
            self.table.add('', self.className, "argument")
        while self.t.token != ')':
            type = self.t.token
            self.writeToken()
            self.table.add(self.t.token, type, "argument")
            self.writeToken()
            if self.t.token == ',':
                self.writeToken()
        self.writeXML("</parameterList>")

    def compileVarDec(self):
        self.writeXML("<varDec>")
        self.writeToken()
        type = self.t.token
        self.writeToken()
        while self.t.token != ';':
            if self.t.token != ',':
                self.table.add(self.t.token, type, "local")
            self.writeToken()
        self.writeToken()
        self.writeXML("</varDec>")

    def compileStatements(self):
        self.writeXML("<statements>")
        while self.t.token != '}':
            if self.t.token == 'let':
                self.compileLet()
            elif self.t.token == 'do':
                self.compileDo()
            elif self.t.token == 'if':
                self.compileIf()
            elif self.t.token == 'while':
                self.compileWhile()
            elif self.t.token == 'return':
                self.compileReturn()
            elif self.t.token == 'break':
                self.compileReturn()
        self.writeXML("</statements>")

    def compileDo(self):
        self.writeXML("<doStatement>")
        self.writeToken()
        name = self.t.token
        self.writeToken()
        self.compileCall(name)
        self.vm.writePop("temp", 0)
        self.writeToken()
        self.writeXML("</doStatement>")

    def compileBreak(self):
        self.writeXML("<breakStatement>")
        self.vm.writeGoto("WHILE_END" + str(self.currentWhile[-1]))
        self.writeToken(2)
        self.writeXML("</breakStatement>")

    def compileLet(self):
        self.writeXML("<letStatement>")
        self.writeToken()
        name = self.t.token
        self.writeToken()
        temp = False
        if self.t.token == '[':
            self.compileArray(name)
            temp = True
        self.writeToken()
        self.compileExpression()
        self.writeToken()
        t = self.table
        if not t.has(name):
            t = self.classTable
        if temp:
            self.vm.writePop("temp", 0)
            self.vm.writePop("pointer", 1)
            self.vm.writePush("temp", 0)
            self.vm.writePop("that", 0)
        else:
            self.vm.writePop(t.getKind(name), t.getCount(name))
        self.writeXML("</letStatement>")

    def compileWhile(self):
        self.currentWhile.append(self.whileCount)
        self.whileCount += 1
        self.writeXML("<whileStatement>")
        self.writeToken(2)
        self.vm.writeLabel("WHILE_EXP" + str(self.currentWhile[-1]))
        self.compileExpression()
        self.vm.writeUnary('~')
        self.vm.writeIf("WHILE_END" + str(self.currentWhile[-1]))
        self.writeToken(2)
        self.compileStatements()
        self.vm.writeGoto("WHILE_EXP" + str(self.currentWhile[-1]))
        self.writeToken()
        self.vm.writeLabel("WHILE_END" + str(self.currentWhile[-1]))
        del(self.currentWhile[-1])
        self.writeXML("</whileStatement>")

    def compileIf(self):
        currentCount = self.ifCount
        self.ifCount += 1
        self.writeXML("<ifStatement>")
        self.writeToken(2)
        self.compileExpression()
        self.vm.writeIf("IF_TRUE" + str(currentCount))
        self.vm.writeGoto("IF_FALSE" + str(currentCount))
        self.vm.writeLabel("IF_TRUE" + str(currentCount))
        self.writeToken(2)
        self.compileStatements()
        self.writeToken()
        if self.t.token == "else":
            self.vm.writeGoto("IF_END" + str(currentCount))
            self.vm.writeLabel("IF_FALSE" + str(currentCount))
            self.writeToken(2)
            self.compileStatements()
            self.writeToken()
            self.vm.writeLabel("IF_END" + str(currentCount))
        else:
            self.vm.writeLabel("IF_FALSE" + str(currentCount))
        self.writeXML("</ifStatement>")

    def compileReturn(self):
        self.writeXML("<returnStatement>")
        self.writeToken()
        if self.t.token != ';':
            self.compileExpression()
        self.writeToken()
        if self.functionType == "void":
            self.vm.writePush("constant", 0)
        self.vm.writeReturn()
        self.writeXML("</returnStatement>")

    def compileCall(self, name):    # starts with tokenizer after the function name
        argNum = 0
        if self.t.token == '.':  # not a local method
            self.writeToken()
            t = self.table
            if not t.has(name):  # not a local object's method
                t = self.classTable
            if t.has(name):  # must be a local or field object's method
                self.vm.writePush(t.getKind(name), t.getCount(name))
                name = t.getType(name) + '.' + self.t.token
                argNum = 1
            else:   # must be an external function
                name += '.' + self.t.token
            self.writeToken()
        else:   # local method
            self.vm.writePush("pointer", 0)
            name = self.className + '.' + name
            argNum = 1
        self.writeToken()
        argNum += self.compileExpressionList()
        self.writeToken()
        self.vm.writeCall(name, argNum)

    def compileArray(self, name):   # starts with tokenizer after the array name
        t = self.table
        if not t.has(name):
            t = self.classTable
        self.writeToken()
        self.compileExpression()
        self.writeToken()
        self.vm.writePush(t.getKind(name), t.getCount(name))
        self.vm.writeArithmetic('+')

    def compileExpressionList(self):
        self.writeXML("<expressionList>")
        n = 0
        if self.t.token != ')':
            self.compileExpression()
            n = 1
        while self.t.token == ',':
            n += 1
            self.writeToken()
            self.compileExpression()
        self.writeXML("</expressionList>")
        return n

    def compileExpression(self):
        self.writeXML("<expression>")
        self.compileTerm()
        while self.t.token in "+-*/%&|~=<=>==":
            op = self.t.token
            self.writeToken()
            self.compileTerm()
            self.vm.writeArithmetic(op)
        self.writeXML("</expression>")

    def compileTerm(self):
        self.writeXML("<term>")
        if self.t.tokenType == "stringConstant":
            self.vm.writePush("constant", len(self.t.token))
            self.vm.writeCall("String.new", 1)
            for i in self.t.token:
                self.vm.writePush("constant", ord(i))
                self.vm.writeCall("String.appendChar", 2)
            self.writeToken()
        elif self.t.token in "~-" and self.t.token != '':
            op = self.t.token
            self.writeToken()
            self.compileTerm()
            self.vm.writeUnary(op)
        elif self.t.token == '(':
            self.writeToken()
            self.compileExpression()
            self.writeToken()
        elif self.t.tokenType == "identifier":
            name = self.t.token
            self.writeToken()
            if self.t.token == '[':  # array
                self.compileArray(name)
                self.vm.writePop("pointer", 1)
                self.vm.writePush("that", 0)
            elif self.t.token in "(.":  # function
                self.compileCall(name)
            else:   # normal variable/object
                t = self.table
                if not t.has(name):
                    t = self.classTable
                self.vm.writePush(t.getKind(name), t.getCount(name))
        else:
            if self.t.tokenType == "integerConstant":
                self.vm.writePush("constant", self.t.token)
            elif self.t.tokenType == "keyword":  # this/null/false/true
                if self.t.token == "this":
                    self.vm.writePush("pointer", 0)
                else:
                    self.vm.writePush("constant", 0)
                    if self.t.token == "true":
                        self.vm.writeUnary('~')
            self.writeToken()
        self.writeXML("</term>")


import tkinter as tk
from tkinter import ttk

# Constant colour shorthands
bg_col = "#134074"
fg_col = "#0b2545"
btn_col = "#eef4ed"
img_bg = "#8DA9C4"
font_name = "Yu Gothic Ui Semilight"

widget_bg = tk.PhotoImage(file="ticket_rect.png")
type_bg = tk.PhotoImage(file="type_rect.png")
ticket_bg = tk.PhotoImage(file="ticket_contact.png")

costs = {"adult": 10, "child": 7.5, "student": 9, "pensioner": 7}

# Creating and configuring root window settings
window = None
contact = tk.Frame(window, bg=bg_col, cursor="heart")

def screen_back():
    contact.pack_forget()
    import tickets as ts
    ts.tickets.pack(expand=True, fill="both")

class place:
    # Widget placing class shorthand
    def __init__(self, widget, x, y):
        self.widget = widget
        self.x = x
        self.y = y
        self.widget.place(relx=self.x, rely=self.y, anchor="center")

class create_button:

    def __init__(self, location, text, fg, bg, x, y, comm = None):
        self.location = location
        self.text = text
        self.fg = fg
        self.bg = bg
        self.x = x
        self.y = y
        self.comm = comm
        self.but = tk.Button(self.location, bg = self.bg, text = self.text,
                             fg=self.fg, command= self.comm, height = 2,
                             width=3, borderwidth=0,
                             highlightbackground=bg_col,
                             font=(font_name, 16))
        self.but.place(relx = self.x, rely = self.y, anchor = "center")

# Page widgets

display_bg = tk.Label(contact, image=ticket_bg, bg=bg_col, borderwidth=0)
# display_bg.pack
# display_bg.pack_propagate(False)
place(display_bg, 0.5, 0.25)

# Specified movie and session time
image = tk.Label(display_bg, image=None)
place(image, 0.1, 0.3)

movie_title = tk.Label(display_bg, text=None, font=(font_name, 16), fg=btn_col, bg=img_bg,
                       wraplength=150, justify="center")
place(movie_title, 0.1, 0.7)

time_label = tk.Label(display_bg, text=None, justify="center", font=(font_name, 16),
                      fg=btn_col, bg=img_bg)
place(time_label, 0.1, 0.9)

# frame_tickets = tk.Listbox(display_bg, bg=img_bg, cursor= "mouse",
#                            height=1, width=10)
# frame_tickets.place(relx=0.6, rely=0.3, anchor="n")

show_tickets = tk.Text(display_bg, height=20, width=70, fg="red",
                       bg="yellow", state="disabled")

for i in range(100):
    show_tickets.insert(tk.END, "hello\n")
place(show_tickets, 0.6, 0.6)
scroll = tk.Scrollbar(show_tickets)
place(scroll, 0.9, 0)
scroll.config(command=show_tickets.yview)

back = create_button(contact, "Back", fg_col, btn_col, 0.15, 0.95, comm=screen_back)


import math

class Radios:

    def __init__(self):

        self.fi = 0
        self.lon = 0
        self.az = 0
        self.normal = 0
        self.R = 0
        self.ro = 0
        self.ro_az = 0
        self.rad_med_curv = 0
        self.a = 0
        self.e_cuad = 0

    def calc_radios(self):

        sinfi = math.sin(math.radians(self.fi))
        sinaz = math.sin(math.radians(self.az))
        cosaz = math.cos(math.radians(self.az))
        self.normal = (self.a/math.sqrt((1-(self.e_cuad*((sinfi)**2)))))
        self.R= (self.a*(1-self.e_cuad))/(1-(self.e_cuad*((sinfi)**2)))**(3/2)
        self.ro_az = (self.ro*self.normal)/((self.R*(cosaz**2))+(self.normal*(sinaz**2)))
        self.rad_med_curv = math.sqrt(self.R*self.normal)

    def elipsoides (self):

        print("Con que elipsoide desea trabajar: ")
        print("1) GRS - 80")
        print("2) Internacional")
        opcion = int(input("Seleccione el elipsoide: "))
        if opcion == 1:
            self.a = 6378137
            self.e_cuad = 0.00669438
        elif opcion == 2:
            self.a = 6378388
            self.e_cuad = 0.00672267


import multiprocessing
from collections import OrderedDict
from typing import Dict, List, Optional

import ripyl.protocol.uart as uart
import ripyl.streaming as stream
import ripyl.util.plot as rplot

CHANNEL_COLOR: Dict[int, str] = {0: 'orange', 1: 'blue'}
BITS: int = 8
PARITY: Optional[str] = None
STOP_BITS: int = 1

class UartPlotter(object):

    def __init__(self, samples: Dict[int, List[float]], sample_period: float):
        self._processes: List[multiprocessing.Process] = []
        self._samples: Dict[int, List[float]] = samples
        self._sample_period: float = sample_period

    def __enter__(self, *args, **kwargs):
        self.__init__(*args, **kwargs)
        return self

    @staticmethod
    def decoder_process(channel, data, period):
        print(f"Decoding channel : {channel}")

        txd = stream.samples_to_sample_stream(raw_samples=data, sample_period=period)
        records = list(uart.uart_decode(stream_data=txd, bits=BITS, parity=PARITY, stop_bits=STOP_BITS))
        success = True
        for rec in records:
            if rec.nested_status() != stream.StreamStatus.Ok:
                success = False
                print(f"Failed to decode record : {rec}")
                break
        if success:
            txd = stream.samples_to_sample_stream(raw_samples=data, sample_period=period)
            channels = OrderedDict([(f'CHANNEL {channel} : {CHANNEL_COLOR[channel]} (V)', txd)])
            title = "UART debug"
            plotter = rplot.Plotter()
            plotter.plot(channels=channels, annotations=records, title=title,
                         label_format=stream.AnnotationFormat.Text)
            plotter.show()

    def plot(self):
        for name, data in self._samples.items():
            self._processes.append(multiprocessing.Process(target=self.decoder_process,
                                                           args=(name, data, self._sample_period)))
            self._processes[-1].start()

    def __del__(self):
        for process in self._processes:
            process.join()

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.__del__()


#Exercicio de código de identificação de cliente,idade e doença infecto contagiosa.Decisão while 2.

nome=input("Digite seu nome: ")
idade=int(input("Digite a idade: "))
doenca_infectocontagiosa=input("Suspeita de doença infectocontagiosa? ").upper()

#PRIMEIRO PROBLEMA A SER RESOLVIDO
while doenca_infectocontagiosa!="SIM" and doenca_infectocontagiosa!="NÃO":
    print("Digite SIM ou NÃO")
    doenca_infectocontagiosa = input("Suspeita de doença infectocontagiosa? ").upper()

if doenca_infectocontagiosa=="SIM":
    print("Enacminhe o paciente para a sala AMARELA")
else:
    print("Encaminhe o paciente para a sala BRANCA")

#SEGUNDO PROBLEMA A SER RESOLVIDO
while idade>=65:
    print("Paciente COM prioridade")
else:
    print("Paciente SEM prioridade")

genero=input("Digite o gênero do paciente: ").upper()
while genero=="FEMININO" and idade>10:
        gravidez=input("A paciente está grávida? ").upper()
        if gravidez=="SIM" and gravidez!="NÃO":
            print("Paciente COM prioridade")
        else:
            print("Paciente SEM prioridade")

Capitulo2_Repeticoes - Mini Projetos na prática 2/DesafioDecisaoWhile2 - #Exercicio de código de identificação de cliente,idade e doença infecto contagiosa.py


# Ex. 7.4 Pizza toppings
# Create a loop asking the user to provide a series of pizza toppings. The loop action should terminate when the word
# 'end' is typed. As the user enters more toppings, the loop should display a message that the ingredient has been added
# to the pizza.

message = "\nEnter your pizza topping."
message += "\nIf you end, enter 'end'. "

topping = ""

while topping != 'end':
    topping = input(message)
    if topping != 'end':
        print(f"{topping.title()} was added to pizza.")
    else:
        print("Cya!")


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

from userpage import views

urlpatterns = patterns('',
	url(r'^change/$', views.changeLecture),
	url(r'^(?P<collect_act>collect|decollect)/lecture/(?P<lecture_id>\d+)/$', views.collectLecture),
	url(r'^checksupermessage/(?P<message_id>\d+)/$', views.checkSuperMessage),
	url(r'^getallcollectionlectures/$', views.getAllCollectionLectures),
	url(r'^getallcomments/$', views.getAllComments),
	url(r'^getcollectionlectures/(?P<start>\d+)/(?P<end>\d+)/$', views.getCollectionLectures),
	url(r'^getcomments/(?P<start>\d+)/(?P<end>\d+)/$', views.getComments),
	url(r'^getgossips/(?P<start>\d+)/(?P<end>\d+)/$', views.getGossips),
	url(r'^getrandomcomment/(?P<length>\d+)/$', views.getRandomComment),
	url(r'^setnickname/$', views.setNickname),
	url(r'^setstyle/$', views.setStyle),
	url(r'^freshuserinfluence/$', views.freshUserInfluence),
	url(r'^delete(?P<record_type>gossip|comment)/(?P<id>\d+)/$', views.deleteRecord),
	url(r'^getmessages/$', views.getMessages),
	url(r'^checkmessage/(?P<message_id>\d+)/$', views.checkMessage),
)


import os
import re
from urllib.parse import urlparse
from datetime import datetime
from typing import List

from Common.ThreadManager import ThreadManager
from Managers.CacheManager import CacheManager
from Common.RequestHandler import RequestHandler
from Tools.LinkFinder import LinkFinder
from Models.GetRequestDTO import GetRequestDTO

class Hakrawler:
    def __init__(self, domain, raw_cookies='', headers={}, cookies=''):
        self._domain = domain
        self._raw_cookies = raw_cookies
        self._max_depth = os.environ.get('max_depth')
        self._social_media = ["facebook", "twitter", "linkedin", "youtube", "google", "intercom", "atlassian"]
        self._tool_name = self.__class__.__name__
        self._request_handler = RequestHandler(cookies, headers)
        self._url_ignore_ext_regex = re.compile(
            '\.jpg$|\.jpeg$|\.gif$|\.png$|\.js$|\.zip$|\.pdf$|\.ashx$|\.exe$|\.dmg$|\.txt$|\.xlsx$|\.xls$|\.doc$'
            '|\.docx$|\.m4v$|\.pptx$|\.ppt$|\.mp4$|\.avi$|\.mp3$',
            re.IGNORECASE)
        self._result: List[GetRequestDTO] = []
        self._checked_hrefs = set()

    def get_requests_dtos(self, start_url) -> List[GetRequestDTO]:
        cache_manager = CacheManager('Hakrawler', self._domain)
        result = cache_manager.get_saved_result()
        if result is None:
            result = self.__get_urls(start_url)
            cache_manager.save_result(result)

        print(f'[{datetime.now().strftime("%H:%M:%S")}]: ({self._domain}) {self._tool_name} found {len(result)} items')
        return result

    def __get_urls(self, start_url) -> List[GetRequestDTO]:

        cookie_param = ''
        if self._raw_cookies:
            cookie_param = f"-h 'Cookie: {self._raw_cookies}'"

        command = f"echo '{start_url}' | hakrawler -d {self._max_depth} {cookie_param} -t 20"
        stream = os.popen(command)
        bash_outputs = stream.readlines()
        href_urls = set()
        script_urls = set()
        for output in bash_outputs:
            if output.endswith('\n'):
                output = output[:-1]
            if output.endswith('/'):
                output = output[:-1]
            if output.startswith('[href] '):
                output = output.replace('[href] ', '')
                if not any(word in output for word in self._social_media) and self._domain in output:
                    href_urls.add(output)
            elif output.startswith('[script] '):
                output = output.replace('[script] ', '')
                if not any(word in output for word in self._social_media) and self._domain in output:
                    script_urls.add(output)

        link_finder = LinkFinder(self._domain, start_url)
        get_urls_from_js = link_finder.search_urls_in_js(script_urls)
        href_urls.update(get_urls_from_js)

        tm = ThreadManager()
        tm.run_all(self.__check_href_urls, href_urls, debug_msg=self._tool_name)

        return self._result

    def __check_href_urls(self, url: str):
        url_parts = urlparse(url)
        if url_parts.path in self._checked_hrefs or self._url_ignore_ext_regex.search(url):
            return
        else:
            self._checked_hrefs.add(url_parts.path)

        response = self._request_handler.handle_request(url, timeout=5)
        if response is None:
            return

        if len(self._result) > 0 and any(dto for dto in self._result if
                                         dto.response_length == len(response.text) and
                                         dto.status_code == response.status_code):
            return

        if response.status_code < 400 or response.status_code == 500:
            self._result.append(GetRequestDTO(url, response))

        return self._result


import re
from io import BytesIO

import aiohttp
import pytesseract
from PIL import Image, ImageEnhance
from aiohttp import payload
from asgiref.sync import sync_to_async

async def get_banana_num(stories_url: str) -> int:
    stories_data = await get_stories_data(stories_url)
    banana_num = await find_banana_num(stories_data) if stories_data else None
    return banana_num

async def get_stories_data(stories_url: str) -> payload:
    async with aiohttp.ClientSession() as session:
        async with session.get(stories_url) as response:
            return await response.read()

@sync_to_async
def find_banana_num(stories_data: payload):
    image_data = BytesIO(stories_data)
    img: Image.Image = Image.open(image_data)

    enhancer = ImageEnhance.Sharpness(img)
    img = enhancer.enhance(3)

    img_text = pytesseract.image_to_string(img, lang='eng')
    pattern = re.compile(r"#\d+")
    found_strings = re.findall(pattern=pattern, string=img_text)

    return int(found_strings[-1][1:]) if found_strings else None


from typing import List, Dict, Tuple
from scipy.stats import gmean
import numpy as np
import pandas as pd
from py_muvr.data_structures import (
    SelectedFeatures,
    ScoreCurve,
    FeatureEliminationResults,
    InnerLoopResults,
    FeatureSelectionRawResults,
    FeatureSelectionResults,
)
from py_muvr.utils import (
    average_ranks,
    average_scores,
    normalize_score,
    get_best_n_features,
)

class PostProcessor:
    """Contains several method that can process the results of the double CV loop
    to perform the actual feature selection and extract data for the plot utils.

    Parameters
    ----------
    robust_minimum : float
        maximum normalized-score value to be considered when computing the `min` and
        `max` selected features
    """

    def __init__(self, robust_minimum: float):
        self.robust_minimum = robust_minimum

    def select_features(self, results: FeatureSelectionRawResults) -> SelectedFeatures:
        """Select the best features for the three possible models (`min`, `mid`
        and `max`).
        The best features are chosen based on their average ranks in the three models
        across repetitions. The number of features are chosen based on the average score
        curve across repetitions and on `robust_minimum`.

        Parameters
        ----------
        results : FeatureSelectionRawResults
            results of the double CV feature selection

        Returns
        -------
        SelectedFeatures
            the best features for the three models
        """
        flat_results = [r for repetition in results for r in repetition]
        average_ranks_min = average_ranks([r.min_eval.ranks for r in flat_results])
        average_ranks_mid = average_ranks([r.mid_eval.ranks for r in flat_results])
        average_ranks_max = average_ranks([r.max_eval.ranks for r in flat_results])
        features_min, features_mid, features_max = self._compute_n_features(results)
        return SelectedFeatures(
            min=get_best_n_features(average_ranks_min, features_min),
            mid=get_best_n_features(average_ranks_mid, features_mid),
            max=get_best_n_features(average_ranks_max, features_max),
        )

    def _compute_n_features(self, results: FeatureSelectionRawResults):
        avg_rep_scores = self._get_repetition_avg_scores(results)
        avg_scores = average_scores(avg_rep_scores)
        norm_score = normalize_score(avg_scores)
        n_feats_close_to_min = [
            n for n, s in norm_score.items() if s <= self.robust_minimum
        ]
        max_feats = max(n_feats_close_to_min)
        min_feats = min(n_feats_close_to_min)
        mid_feats = gmean([max_feats, min_feats])
        mid_feats = min(norm_score.keys(), key=lambda x: abs(x - mid_feats))
        return min_feats, mid_feats, max_feats

    @staticmethod
    def _get_repetition_avg_scores(results: FeatureSelectionRawResults) -> List:
        avg_scores = []
        for outer_loops_results in results:
            scores = [ol.n_features_to_score_map for ol in outer_loops_results]
            avg_scores.append(average_scores(scores))
        return avg_scores

    def get_validation_curves(
        self, results: FeatureSelectionRawResults
    ) -> Dict[str, List[ScoreCurve]]:
        """Get validation curves (avg score vs number of features) for all outer
        loop iterations, and their average per repetition and overall. Every group
        of curves is stores in a list and packed in an output dictionary:

            {
                "outer_loops": list of outer loop curves,
                "repetitions": list of average ov outer loop curves across repetitions,
                "total": average of all curves,
            }

        Parameters
        ----------
        results : FeatureSelectionRawResults
            results of the double CV feature selection

        Returns
        -------
        Dict[str, List[ScoreCurve]]:
            List of score curves for all outer loop iterations, for all repetitions,
            and overall
        """
        flat_results = [r for repetition in results for r in repetition]
        outer_loop_scores = [r.n_features_to_score_map for r in flat_results]
        avg_scores_per_loop = self._get_repetition_avg_scores(results)
        avg_scores = average_scores(avg_scores_per_loop)
        return {
            "outer_loops": [self._score_to_score_curve(s) for s in outer_loop_scores],
            "repetitions": [self._score_to_score_curve(s) for s in avg_scores_per_loop],
            "total": [self._score_to_score_curve(avg_scores)],
        }

    @staticmethod
    def _score_to_score_curve(scores: Dict[int, float]) -> ScoreCurve:
        n_features, score_values = zip(*sorted(scores.items()))
        return ScoreCurve(n_features=n_features, scores=score_values)

    def process_feature_elim_results(self, raw_results: Dict[tuple, InnerLoopResults]):
        """Processes the feature elimination inner loop results to produce
        a score curve and a selection of best features from this curve. Results are
        packed in a FeatureEliminationResults object.

        Parameters
        ----------
        raw_results : Dict[tuple, InnerLoopResults]
            the results of the inner loops for every step of the recursive feature
            elimination

        Returns
        -------
        FeatureEliminationResults
            the processed results of the recursive feature elimination
        """
        n_feats_to_score = self._compute_score_curve(raw_results)
        best_features = self._select_best_outer_features(raw_results, n_feats_to_score)

        return FeatureEliminationResults(n_feats_to_score, best_features)

    @staticmethod
    def _compute_score_curve(
        elimination_results: Dict[tuple, InnerLoopResults]
    ) -> Dict[int, float]:
        avg_scores = {}
        for features, in_loop_res in elimination_results.items():
            n_feats = len(features)
            test_scores = [r.test_score for r in in_loop_res]
            avg_scores[n_feats] = np.average(test_scores)
        return avg_scores

    def _select_best_outer_features(
        self,
        elimination_results: Dict[tuple, InnerLoopResults],
        avg_scores: Dict[int, float],
    ) -> SelectedFeatures:
        n_to_features = self._compute_n_features_map(elimination_results)
        norm_score = normalize_score(avg_scores)
        n_feats_close_to_min = [
            n for n, s in norm_score.items() if s <= self.robust_minimum
        ]
        max_feats = max(n_feats_close_to_min)
        min_feats = min(n_feats_close_to_min)
        mid_feats = gmean([max_feats, min_feats])
        mid_feats = min(avg_scores.keys(), key=lambda x: abs(x - mid_feats))

        return SelectedFeatures(
            mid=n_to_features[mid_feats],
            min=n_to_features[min_feats],
            max=n_to_features[max_feats],
        )

    @staticmethod
    def _compute_n_features_map(
        elimination_results: Dict[tuple, InnerLoopResults]
    ) -> Dict[int, Tuple[int]]:
        n_to_features = {}
        for features in elimination_results.keys():
            n_feats = len(features)
            n_to_features[n_feats] = features
        return n_to_features

    def make_average_ranks_df(
        self,
        feature_selection_results: FeatureSelectionResults,
        n_features: int,
        feature_names: List[str] = None,
        exclude_unused_features: bool = True,
    ) -> pd.DataFrame:

        results_df = pd.DataFrame(
            index=np.arange(n_features), columns=["min", "mid", "max"]
        )

        for feature_set in ["min", "mid", "max"]:
            ranks = self._get_feature_ranks(
                feature_selection_results.raw_results, feature_set
            )
            res = pd.DataFrame(ranks).mean()
            results_df.loc[res.index, feature_set] = res.values

        if exclude_unused_features:
            results_df = results_df.dropna(how="all")

        if feature_names is not None:
            results_df.index = [feature_names[i] for i in results_df.index]

        return results_df

    @staticmethod
    def _get_feature_ranks(
        raw_results: FeatureSelectionRawResults, feature_set: str
    ) -> List[Dict[int, float]]:
        ranks = []
        for r in raw_results:
            for ol in r:
                ranks_raw_data = getattr(ol, feature_set + "_eval").ranks.get_data()
                ranks.append(ranks_raw_data)
        return ranks


import numpy as np
import pywt
import peakutils
import matplotlib
from scipy.signal import butter, lfilter
matplotlib.use('TkAgg')
from matplotlib import pyplot as plt

def perform_fft_analysis(time_series, buffer_size, peak_treshold):
    # length of the signal and data
    n = len(time_series)

    # normalizing to discard DC component
    mean = sum(time_series) / n
    time_series = time_series - mean

    # zero padding
    pow_2 = 1 << (n-1).bit_length()
    time_series_padded = np.pad(time_series, (0, pow_2 - n), 'constant')
    n_pad = len(time_series_padded)
    fs = buffer_size  # sampling rate
    k = np.arange(n_pad)
    t = n_pad / fs
    frq = k / t  # two sides frequency range
    frq = frq[range(int(n_pad / 2))]  # one side frequency range

    # computing FFT
    fft_x = np.fft.fft(time_series_padded) / n_pad  # (normalized)
    fft_x = fft_x[range(int(n_pad / 2))]
    fft_abs = abs(fft_x)
    print(max(fft_abs))

    # finding peaks
    indexes = peakutils.indexes(fft_abs, thres=peak_treshold, min_dist=20)
    if len(indexes) > 0:
        detected_freq = max(frq[indexes])
    else:
        detected_freq = 0
    if max(fft_abs) > 7:
        return fft_abs, detected_freq
    else:
        return fft_abs, 0

def perform_wavelet_analysis(time_series, central_freq, sampling_rate, peak_tresh):
    mean = sum(time_series) / len(time_series)
    time_series = time_series - mean
    ts = 1 / sampling_rate
    central_scale = sampling_rate / central_freq
    wav = pywt.ContinuousWavelet('cmor2-1.0')
    f_bound_high = central_scale / 2
    f_bound_low = central_scale / 2
    bands = 64
    widths = np.linspace(central_scale - f_bound_high, central_scale + f_bound_low, bands)
    # (IMPORTANTE) devo trovare la formula che lega direttamente la frequenza rilevata dalla fft coi parametri da settare per le wavelets
    # in pratica ho capito che a bassissime frequenze non ho bisogno di un numero di bande superiore a 50
    # oltretutto a basse frequenze l'analisi wavelet è molto più lenta
    # un altro parametro molto importante è la larghezza della banda di analisi
    # il limite inferiore (in frequenza) deve essere aumentato
    # 6 Hz -> bands = 100, f_bound_high = central_scale / 20, f_bound_low = central_scale / 80
    # 0.15 Hz -> bands = 20, f_bound_high = central_scale / 3, f_bound_low = central_scale / 1
    cwtmatr, freqs = pywt.cwt(time_series, widths, wav, ts)
    cwt_freq_peaks = []
    times = 0;
    for time_stamp in cwtmatr.T: # [int(len(cwtmatr.T)/3):int(len(cwtmatr.T)*2/3)]:
        abs_ts = abs(time_stamp)
        max_value = max(abs_ts)
        indexes = peakutils.indexes(abs_ts, thres=peak_tresh, min_dist=20)
        for i in indexes:
            cwt_freq_peaks.append(freqs[i])
        times = times+1
    #print("Peaks: " + str(cwt_freq_peaks))
    #print("Freqs: " + str(freqs))
    freq_det_cwt = np.mean(cwt_freq_peaks)
    return cwtmatr, freq_det_cwt


import os

cwb = os.getcwd()

folder_list = []

for i in os.listdir(cwb):
    if os.path.isdir(i):
        folder_list.append(i)

for folder in folder_list:
    caminho = os.path.join(cwb,folder)

    files = os.listdir(caminho)
    for file in files:
        caminho_final = os.path.join(caminho, file)
        destino = os.path.join(cwb, file)
        os.replace(caminho_final, destino)
    os.rmdir(caminho)


# -*- coding: utf-8 -*-
# 卷积神经网络的输入输出以及训练流程和全连接神经网络基本一致；唯一区别在于神经网络中相邻两层的连接方式。
# 以图像分类为例，卷积神经网络的输入是图像的原始像素，输出层的每一个节点代表了不同类别的可信度。
# 参数增多除了导致计算速度减慢，还很容易导致过拟合问题。卷积神经网络能有效减少神经网络中参数个数。
# 输入 卷积 池化 全连接 softmax层
# 经过卷积层处理过的节点矩阵会变得更深，池化层不会改变三维矩阵的深度，但是可以缩小矩阵的大小
# 池化层既可以加快计算速度也有防止过拟合问题的作用；但The All Convolutional Net论文中指出池化层对模型效果的影响不大
# 特征提取： 卷积 池化。 分类： 全连接层 softmax（得到当前样例属于不同种类的概率分布情况）
# zero-padding
import tensorflow as tf

# 卷积层： 矩阵中对应元素点积和
filter_weight = tf.get_variable("weight", [5, 5, 3, 16], initializer=tf.truncated_normal_initializer(stddev=0.1))
biases = tf.get_variable("biases", [16], initializer=tf.constant_initializer(0.1))
## tf.nn.conv2d：卷积层前向传播， 有四个参数，第一个参数为当前层的节点矩阵；第二个参数提供了卷积层的权重；第三个参数为不同维度上的步长：
# 一个长度为4的数组，但是第一维和最后一维的数字要求一定是1，这是因为卷积层的步长只对矩阵的长和宽有效，
# 最后一个参数是填充，“SAME”表示添加全0填充，使得卷积过后的矩阵和输入的矩阵大小相等（步长为1时），“VALID”表示不添加
# 比如 一个3X3的矩阵：[[1, -1, 0], [-1, 2, 1], [0, 2, -2]]，经过2X2的过滤器的卷积过程（Tensorflow实现全0填充优先填充右下方）：
# VALID: [[1, -1, 0], [-1, 2, 1], [0, 2, -2]]--》 [[A, B], [C, D]]
# SAME: [[0, 0, 0, 0], [0, 1, -1, 0], [0, -1, 2, 1], [0, 0, 2, -2]] --> [[Y, W, X], [Y, A, B], [Z, C, D]]
## tf.nn.bias_add: 给每个节点加上偏置项，给下一层神经网络2X2矩阵中的每个值都加上这个偏置项
conv = tf.nn.conv2d(input, filter_weight, strides=[1, 1, 1, 1], padding="SAME")
bias = tf.nn.bias_add(conv, biases)
# 将计算结果通过RELU激活函数完成去线性化
actived_conv = tf.nn.relu(bias)

# 池化层：最大池化 or 平均池化
# tf.nn.max_pool 实现最大池化，ksize提供了过滤器的尺寸，strides提供步长信息，padding和卷积类似
pool = tf.nn.max_pool(actived_conv, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding="SAME")


def insert(self, point, payload):

        """!

        @brief Insert new point with payload to kd-tree.

        @param[in] point (list): Coordinates of the point of inserted node.

        @param[in] payload (any-type): Payload of inserted node. It can be identificator of the node or

                    some useful payload that belongs to the point.

        @return (node) Inserted node to the kd-tree.

        """

        if self.__root is None:

            self.__dimension = len(point)

            self.__root = node(point, payload, None, None, 0)

            self.__point_comparator = self.__create_point_comparator(type(point))

            return self.__root

        cur_node = self.__root

        while True:

            if cur_node.data[cur_node.disc] <= point[cur_node.disc]:

                # If new node is greater or equal than current node then check right leaf

                if cur_node.right is None:

                    discriminator = cur_node.disc + 1

                    if discriminator >= self.__dimension:

                        discriminator = 0

                    cur_node.right = node(point, payload, None, None, discriminator, cur_node)

                    return cur_node.right

                else:

                    cur_node = cur_node.right

            else:

                # If new node is less than current then check left leaf

                if cur_node.left is None:

                    discriminator = cur_node.disc + 1

                    if discriminator >= self.__dimension:

                        discriminator = 0

                    cur_node.left = node(point, payload, None, None, discriminator, cur_node)

                    return cur_node.left

                else:

                    cur_node = cur_node.left


#
#
#   带水印  定制版
#
#

from PyQt5.QtWidgets import  QHBoxLayout, QVBoxLayout, QApplication, QWidget, QPushButton, QLabel,QLineEdit,QGroupBox,QListWidget,QListWidgetItem,QCheckBox,QDateTimeEdit
from PyQt5.QtMultimedia import QSound
from PyQt5.QtGui import QIcon,QPixmap,QFont
import PyQt5.QtCore as QtCore
import qdarkstyle
import sys
import queue
from fcoin3 import Fcoin
import random
import time
import datetime
import json
import sms_send
import re
import codecs

def catch_exceptions(t, val, tb):
    print(t,val,tb)
    old_hook(t, val, tb)

old_hook = sys.excepthook
sys.excepthook = catch_exceptions

class workThread(QtCore.QThread):
    logSignal = QtCore.pyqtSignal(dict)

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

    def run(self):
        self.work()

    def work(self):
        global gIniQueue

        self.printLog('软件启动!')
        file=open('./ini.json')
        dic=json.loads( file.read())
        apikey=dic['apikey']
        apisecret=dic['apisecret']
        file.close()

        while gFlag:
            try:

                try:
                    ini=gIniQueue.get(block=False)
                except:
                    pass
                else:
                    str1=ini[0]
                    str2=ini[1]
                    num=ini[2]
                    str3=ini[3]
                    myTime=ini[4]
                    num2=ini[5]
                    buyFlag=ini[6]
                    tel=ini[7]
                    myTime2=ini[8]
                    num3=ini[9]

                    # test
                    self.printLog(str(ini))

                # file = open('./mytxt.txt', 'a+')
                fcoin = Fcoin()
                # 主号
                # fcoin.auth('', '')
                # 刷号
                fcoin.auth(apikey,apisecret,tel)
                # os.system('fskl.mp3')
                # 获取账户资产
                data=fcoin.get_balance()
                self.printLog('交易对：%s'%(str3))
                level= fcoin.get_market_depth('L20',str3)
                if ('data' not in data.keys()) or (not data['data']):
                    continue
                for i in data['data']:
                    if i['currency']==str1:
                        my_usdt=i['balance']
                        self.printLog(str1+'余额: '+my_usdt)
                    if i['currency']==str2:
                        my_ft=i['balance']
                        self.printLog(str2+'余额: '+my_ft)

                nowBids=level['data']['bids'][0]
                sumBids=0
                for i in range(0,len(level['data']['bids'])):
                    if (i%2)==0:
                        nowBids=level['data']['bids'][i]
                        self.printLog('本次价格：%s'%(nowBids))
                    else:
                        temp_Num2=sumBids
                        sumBids+=level['data']['bids'][i]
                        self.printLog('买盘 本次数量总和：%s  本次数量：%s 上次数量总和：%s  总数量：%s'%(sumBids,level['data']['bids'][i],temp_Num2,num3))
                        if sumBids>num3: #num3是输入的数
                            if i!=0:
                                sumBids=temp_Num2
                            self.printLog('本次数量总和：%s'%(sumBids))
                            if i>0:
                                nowBids=level['data']['bids'][i-1]
                                self.printLog('买盘本次价格：%s' % (nowBids))
                            break
                        elif sumBids==num3:
                            break

                nowAsks=level['data']['asks'][0]
                sumAsks=0
                for i in range(0,len(level['data']['asks'])):
                    if(i%2)==0:
                        nowAsks=level['data']['asks'][i]
                        self.printLog('本次价格：%s'%(nowAsks))
                    else:
                        temp_Num2=sumAsks
                        sumAsks+=level['data']['asks'][i]
                        self.printLog('卖盘 本次数量总和：%s  本次数量：%s  上次数量总和：%s  总数量：%s'%(sumAsks,level['data']['asks'][i],temp_Num2,num3)) #sumAsks+temp_Num2 这是什么意思
                        if sumAsks>num3: #num3是输入的数
                            if i!=0:
                                sumAsks=temp_Num2
                            self.printLog('本次数量总和：%s'%(sumAsks))
                            if i>0:
                                nowAsks=level['data']['asks'][i-1]
                                self.printLog('卖盘本次价格：%s' % (nowAsks))
                            break
                        elif sumAsks==num3:
                            break

                self.printLog('价格小数：%s'%(num2))
                nowResult=round((round(nowAsks,num2)+round(nowBids,num2))/2,num2)

                logStr=str(data)
                # self.printLog(logStr)
                # file.write(logStr+ '\n')

                nowtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                resultstr = fcoin.get_market_ticker(str3)
                logStr=str(resultstr)
                # self.printLog(logStr)
                # file.write(logStr+ '\n')
                wantstr = resultstr["data"]["ticker"]
                # a是买一价  b是卖一价
                a, b = wantstr[2], wantstr[4]
                # result = round(random.uniform(a, b), num2)
                result=nowResult
                logStr="random price is:" + str(result) + "now time:" + nowtime
                # self.printLog(logStr)
                # file.write(logStr+ '\n')

                #卖
                if num<float(my_ft):
                    sellop = fcoin.sell(str3, result, str(round(num,2)))
                    if (sellop is not None ) and (sellop['status']==0):
                        logStr=r'限价卖出成功 限价卖出%s个%s  卖出价格是%s  当前时间是%s'%(num,str2,result,nowtime)
                        self.printLog(logStr)
                    else:
                        self.printLog(sellop['msg'])

                elif (num>float(my_ft)) :

                    if buyFlag:
                        buyop = fcoin.buy_market(str3,round(float(num)*float(result)-float(my_ft)*float(result),2))
                        tempFlag=False
                        if  (buyop is not None) and (buyop['status']==3014):
                            tempFlag=True
                            temp_num = int(re.search(r'\d+$', buyop['msg']).group(0))
                            buyop = fcoin.buy_market(str3, str(temp_num))
                            #
                            # if (buyop is not None) and (buyop['status'] == 0):
                            #     # print(num-float(my_ft))*(result/float(my_usdt))
                            #     logStr = r'市价补仓买入成功 市价买入%s个%s的%s  当前时间是%s' % (
                            #     str(round((num - float(my_ft)) * b + (((num - float(my_ft)) * b) * 0.1), 2)), str1,
                            #     str2, nowtime)
                            #     self.printLog(logStr)
                            #     continue
                                # file.write(logStr+ '\n')
                            # else:
                            #     self.printLog(buyop['msg'])
                            #     continue

                        # buyop = fcoin.buy(str3, result,str(float(num-float(my_ft))*(result/float(my_usdt))))
                        # buyop = fcoin.buy(str3, b, str(round(num-float(my_ft)+((num-float(my_ft))*0.1),2)))
                        if (buyop is not None) and (buyop['status']==0):
                            # print(num-float(my_ft))*(result/float(my_usdt))
                            if not tempFlag:
                                logStr=r'市价补仓买入成功 市价买入%s个%s的%s  当前时间是%s'%(str(round(float(num)*float(result)-float(my_ft)*float(result),2)),str1,str2,nowtime)
                            else:
                                logStr=r'市价补仓买入成功 市价买入%s个%s的%s  当前时间是%s'%(temp_num,str1,str2,nowtime)
                            self.printLog(logStr)
                            continue
                            # file.write(logStr+ '\n')

                        else:
                            self.printLog(buyop['msg'])
                            continue
                            # time.sleep(60*?)
                        # buyrecord = buyop["data"]

                        # sellop = fcoin.sell(str3, result, str(num))
                        # if (sellop is not None) and (sellop['status']==0):
                        #     logStr = r'限价卖出成功 卖出%s个s%  卖出价格是%s  当前时间是%s' % (num, str2,result, nowtime)
                        #     self.printLog(logStr)
                        #     # file.write(logStr+ '\n')
                        # else:
                        #     self.printLog(sellop['msg'])
                        # if sellop:
                        #     sellrecord = sellop["data"]
                    else:
                        smsResult=sms_send.send('您当前交易对数量不足，请及时处理', tel, '44060')
                        #在这等15分钟
                        logStr = r'因为交易对数量不足程序已停止，30分钟后重新启动'
                        time.sleep(60 * 30)

                #买
                if num< float(my_usdt):
                    buyop = fcoin.buy(str3, result, str(round(num,2)))
                    if (buyop is not None) and (buyop['status']==0):
                        logStr=r'限价买入成功 限价买入%s个%s  买入价格是%s  当前时间是%s'%(num,str2,result,nowtime)
                        self.printLog(logStr)
                        # file.write(logStr+ '\n')
                    else:
                        self.printLog(buyop['msg'])

                    # buyrecord = buyop["data"]

                elif num> float(my_usdt):

                    if buyFlag:
                        # sell正常卖  sell_market非正常卖
                        # sellop = fcoin.sell_market(str3,  str(round(num-float(my_ft)+((num-float(my_ft))*0.1),2)))
                        sellop = fcoin.sell_market(str3, round((float(num)*float(result)-float(my_usdt)),2))
                        # sellop = fcoin.sell_market(str3, num+(num*result)*0.01)
                        tempFlag = False
                        if (sellop is not None) and (sellop['status'] == 3014):
                            tempFlag = True
                            temp_num = int(re.search(r'\d+$', sellop['msg']).group(0))
                            sellop = fcoin.buy_market(str3, str(temp_num))

                        # sellop =fcoin.sell(str3, round(a,num2), str(round(num-float(my_ft)+((num-float(my_ft))*0.1),2)))
                        if (sellop is not None) and (sellop['status']==0):
                            if not tempFlag:
                                logStr=r'市价补仓卖出成功 市价卖出%s个%s，当前时间是%s'%(str(round((float(num)*float(result)-float(my_usdt)))),str2,nowtime)
                            else:
                                logStr=r'市价补仓卖出成功 市价卖出%s个%s，当前时间是%s'%(temp_num+temp_num*0.1,str2,nowtime)
                            self.printLog(logStr)
                            continue
                            # file.write(logStr+ '\n')
                        else:
                            self.printLog(sellop['msg'])
                            continue

                        # if sellop:
                        #     sellrecord = sellop["data"]

                        # buyop = fcoin.buy(str3, result, str(num))
                        # if (buyop is not None) and (buyop['status']==0):
                        #     logStr = r'限价买入成功 限价买入%s个%s  买入价格是%s  当前时间是%s' % (num,str2, result, nowtime)
                        #     self.printLog(logStr)
                        #     # file.write(logStr+ '\n')
                        # else:
                        #     self.printLog(buyop['msg'])
                        # # buyrecord = buyop["data"]
                    else:
                        smsResult=sms_send.send('您当前交易对数量不足，请及时处理', tel, '44060')
                        logStr = r'因为交易对数量不足程序已停止，30分钟后重新启动'
                        time.sleep(60 * 30)
                time.sleep(myTime)

                # 获取订单列表
                if buyFlag:
                    rol = fcoin.list_orders(str3, 'submitted,partial_filled')
                    if ('data' not in rol.keys()) or (not rol['data']):
                        continue
                    lastTime=rol['data'][len(rol['data'])-1]['created_at']
                    lastTime=int(re.sub(r'\d{3}$','',str(lastTime)))
                    nowTime=int(time.time())

                    if not buyFlag:
                        if (nowTime-lastTime) >(myTime):
                            smsResult=sms_send.send('您当前有超过5分钟未成交的订单，请及时处理', tel, '44060')
                    else:
                        # 这里加not true的else
                        if buyFlag:
                            for p in rol["data"]:
                                if p["side"] == "buy":
                                    lastTime = p['created_at']
                                    lastTime = int(re.sub(r'\d{3}$', '', str(lastTime)))
                                    nowTime = int(time.time())
                                    if (nowTime-lastTime) >(myTime2):
                                        # 市价卖
                                        sellamount = round(float(p["amount"]) - float(p["filled_amount"]), 2)
                                        temptemp_result = fcoin.cancel_order(p["id"])
                                        if (temptemp_result is None) or (temptemp_result['status'] != 0):
                                            logStr = "检测到有超过" + str(
                                                myTime2) + "秒未完成订单 限价买入订单取消失败,因为已取消，现在时间是:" + nowtime
                                        else:
                                            logStr = "检测到有超过" + str(myTime2) + "秒未完成订单 限价买入订单取消成功，现在时间是:" + nowtime

                                        self.printLog(logStr)
                                        file.write(logStr + '\n')

                                        temptemp_result1 = fcoin.buy_market(str3, sellamount)
                                        if (temptemp_result1 is None) or (temptemp_result1['status']!=0):
                                            logStr="检测到有超过"+str(myTime2)+"秒未完成订单 限价买入订单取消失败,因为已取消，现在时间是:" + nowtime
                                        else:
                                            logStr="检测到有超过"+str(myTime2)+"秒未完成订单 限价买入订单取消成功，现在时间是:" + nowtime

                                        self.printLog(logStr)
                                        # file.write(logStr+ '\n')

                                elif p["side"] == "sell":
                                    lastTime = p['created_at']
                                    lastTime = int(re.sub(r'\d{3}$', '', str(lastTime)))
                                    nowTime = int(time.time())
                                    if (nowTime - lastTime) > (myTime2):
                                        # 市价卖
                                        sellamount = round(float(p["amount"]) - float(p["filled_amount"]), 2)
                                        temptemp_result=fcoin.cancel_order(p["id"])
                                        if (temptemp_result is None) or (temptemp_result['status']!=0):
                                            logStr="检测到有超过"+str(myTime2)+"秒未完成订单 限价卖出订单取消失败,因为已取消，现在时间是:" + nowtime
                                        else:
                                            logStr="检测到有超过"+str(myTime2)+"秒未完成订单 限价卖出订单取消成功，现在时间是:" + nowtime

                                        self.printLog(logStr)
                                        file.write(logStr+ '\n')

                                        temptemp_result=fcoin.sell_market(str3,sellamount)
                                        if (temptemp_result is None) or (temptemp_result['status']!=0):
                                            logStr="检测到有超过"+str(myTime2)+"秒未完成订单 市价卖出结果失败，因为已取消，现在时间是:" + nowtime
                                        else:
                                            logStr="检测到有超过"+str(myTime2)+"秒未完成订单  市价卖出结果成功，现在时间是:" + nowtime
                                        self.printLog(logStr)
                                        file.write(logStr+ '\n')

                                # elif ['side']=='buy':
                                #     lastTime = p['created_at']
                                #     lastTime = int(re.sub(r'\d{3}$', '', str(lastTime)))
                                #     nowTime = int(time.time())
                                #     if (nowTime - lastTime) > (myTime2):
                                #         # 市价买
                                #         sellamount = round(float(p["amount"]) - float(p["filled_amount"]), 2)
                                #         temptemp_result = fcoin.buy_market(str3, sellamount)
                                #         if (temptemp_result is None) or (temptemp_result['status'] != 0):
                                #             logStr = "检测到有超过" + str(myTime2) + "秒未完成订单 市价买入结果失败，因为已取消，现在时间是:" + nowtime
                                #         else:
                                #             logStr = "检测到有超过" + str(myTime2) + "秒未完成订单  市价买入结果成功，现在时间是:" + nowtime
                                #         self.printLog(logStr)
                                #         file.write(logStr + '\n')
                                        # file.write(logStr+ '\n')

                # isemprol = fcoin.list_orders('ftusdt', 'submitted,partial_filled')
                # print(isemprol)
                # time.sleep(myTime)
                # if len(isemprol["data"]) != 0:
                #     flag = False
                #     # os.system('fskl.mp3')
                # file.close()
                # # 执行完等3秒继续循
                # time.sleep(1)

            except Exception as e:
                raise e
                time.sleep(myTime)

        self.printLog('软件结束!')

    def printLog(self,str):
        self.logSignal.emit({'msg':str})

class timerThread(QtCore.QThread):
    startSignal=QtCore.pyqtSignal()
    endSignal=QtCore.pyqtSignal()

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

    def run(self):
        while True:
            if gTimeFlag and (gStartTime is not None) and (gEndTime is not None) and (not gWorkRunFlag):
                nowTime=datetime.datetime.now()
                if (nowTime>=gStartTime) and (nowTime<gEndTime) and (gFlag==False):
                    self.startSignal.emit()
                elif nowTime>=gEndTime:
                    self.endSignal.emit()
                    break
            time.sleep(0.5)

class OWO(QWidget):
    def __init__(self):
        super(QWidget,self).__init__()

        tempTime=datetime.datetime.now()
        tempTime=tempTime.strftime(r'%Y-%m-%d %H %M %S')
        self.logFile=codecs.open('./log/'+str(tempTime)+'日志'+'.html','w','utf-8')
        self.htmlPart1="""
                    <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <title>Log</title>
            </head>
            <body>
                <table>
        """
        self.htmlPart2="""
            </table>
            </body>
            </html>
        """
        self.logFile.write(self.htmlPart1)

        vBox = QVBoxLayout()

        logG=QGroupBox()
        logG.setTitle('信息')
        hBox=QHBoxLayout()
        self.logList=QListWidget()
        hBox.addWidget(self.logList)
        logG.setLayout(hBox)

        iniG=QGroupBox()
        iniG.setTitle('设置')
        vBox2 = QVBoxLayout()

        hBox1 = QHBoxLayout()
        mylable1=QLabel('交易对1:')
        self.input1=QLineEdit()
        self.input1.setText('usdt')
        hBox1.addWidget(mylable1)
        hBox1.addWidget(self.input1)
        vBox2.addLayout(hBox1)

        hBox2 = QHBoxLayout()
        mylable2 = QLabel('交易对2:')
        self.input2 = QLineEdit()
        self.input2.setText('ft')
        hBox2.addWidget(mylable2)
        hBox2.addWidget(self.input2)
        vBox2.addLayout(hBox2)

        hBox3 = QHBoxLayout()
        mylable3 = QLabel('交易数量:')
        self.input3 = QLineEdit()
        self.input3.setText('10')
        hBox3.addWidget(mylable3)
        hBox3.addWidget(self.input3)
        vBox2.addLayout(hBox3)

        hBox4 = QHBoxLayout()
        mylable4 = QLabel('交易对:')
        self.input4 = QLineEdit()
        self.input4.setText('ftusdt')
        hBox4.addWidget(mylable4)
        hBox4.addWidget(self.input4)
        vBox2.addLayout(hBox4)

        hBox6=QHBoxLayout()
        mylable6=QLabel('交易时间:')
        self.input6=QLineEdit()
        self.input6.setText('10')
        hBox6.addWidget(mylable6)
        hBox6.addWidget(self.input6)
        vBox2.addLayout(hBox6)

        hBox7 = QHBoxLayout()
        mylable6 = QLabel('价格小数:')
        self.input7 = QLineEdit()
        self.input7.setText('6')
        hBox7.addWidget(mylable6)
        hBox7.addWidget(self.input7)
        vBox2.addLayout(hBox7)

        hBox11 = QHBoxLayout()
        mylable11 = QLabel('输入数值!:')
        self.input11 = QLineEdit()
        self.input11.setText('0')
        hBox11.addWidget(mylable11)
        hBox11.addWidget(self.input11)
        vBox2.addLayout(hBox11)

        hBox5=QHBoxLayout()
        self.input8 = QCheckBox()
        self.input8.setText('当余额不足是否市价增补仓')
        mylable7=QLabel('输入手机号:')
        self.input8.setChecked(True)
        self.input9 = QLineEdit()
        mylable9=QLabel('请输入多久取消订单(秒):')
        self.input10=QLineEdit()
        self.input10.setText('5')
        submitBtn=QPushButton('  提交  ')
        submitBtn.clicked.connect(self.submitFn)
        hBox5.addWidget(self.input8)
        hBox5.addSpacing(8)
        hBox5.addWidget(mylable7)
        hBox5.addWidget(self.input9)
        hBox5.addSpacing(8)
        hBox5.addWidget(mylable9)
        hBox5.addWidget(self.input10)
        hBox5.addStretch()
        hBox5.addWidget(submitBtn)
        # hBox5.addStretch()
        vBox2.addLayout(hBox5)

        iniG.setLayout(vBox2)

        vBox.addWidget(logG)
        vBox.addWidget(iniG)

        hBox7=QHBoxLayout()
        self.startBtn=QPushButton('  运行  ')
        self.startBtn.clicked.connect(self.startBtnClick)
        self.stopBtn=QPushButton('  停止  ')
        self.stopBtn.clicked.connect(self.stopBtnClick)
        mylable8=QLabel('JC软件工作室 微信:jcccccccc1991')
        font=QFont('微软雅黑')
        font.setPixelSize(18)
        mylable8.setFont(font)
        mylable8.setStyleSheet("""
            QLabel{color:#FF0000}
        """)
        hBox7.addWidget(self.startBtn)
        hBox7.addStretch()
        hBox7.addWidget(mylable8)
        hBox7.addStretch()
        hBox7.addWidget(self.stopBtn)

        hBox8 = QHBoxLayout()
        tempNowTime = QtCore.QDateTime.currentDateTime()
        self.timerC = QCheckBox()
        self.timerC.setText('启用定时运行   ')
        self.timerC.stateChanged.connect(self.timerClicked)
        startLab = QLabel('开始时间:')
        self.startTimeEdit = QDateTimeEdit()
        self.startTimeEdit.setDateTime(tempNowTime)
        self.startTimeEdit.setStyleSheet("""
                    QDateTimeEdit{width:110px}
                """)
        endLab = QLabel('<--> 结束时间:')
        self.endTimeEdit = QDateTimeEdit()
        self.endTimeEdit.setDateTime(tempNowTime)
        self.endTimeEdit.setStyleSheet("""
                    QDateTimeEdit{width:110px}
                """)
        hBox8.addWidget(self.timerC)
        hBox8.addWidget(startLab)
        hBox8.addWidget(self.startTimeEdit)
        hBox8.addWidget(endLab)
        hBox8.addWidget(self.endTimeEdit)
        hBox8.addStretch()

        vBox.addLayout(hBox8)
        vBox.addLayout(hBox7)
        self.stopBtn.setEnabled(False)

        icon=QIcon()
        icon.addPixmap(QPixmap('./JC.ico'),QIcon.Normal)
        self.setWindowIcon(icon)
        self.setLayout(vBox)
        self.setWindowTitle('JC全自动挖矿交易软件')
        self.resize(700,500)
        self.show()

    def submitFn(self,click):
        self.sendIni()

    def sendIni(self):
        global gIniQueue
        myList = [
            str(self.input1.text()),
            str(self.input2.text()),
            float(self.input3.text()),
            str(self.input4.text()),
            int(self.input6.text()),
            int(self.input7.text()),
            bool(self.input8.isChecked()),
            str(self.input9.text()),
            int(self.input10.text()),
            int(self.input11.text())
        ]
        gIniQueue.put(myList)

    def printLog(self,dic):
        item=QListWidgetItem(dic['msg'])
        self.logList.addItem(item)
        self.logList.setCurrentRow(self.logList.count()-1)
        self.logFile.write(r'<tr><td>'+dic['msg']+r'</td></tr>')
        if self.logList.count()>1000:
            item=self.logList.takeItem(0)
            del item

    def startBtnClick(self,click):
        self.startBtn.setEnabled(False)
        self.stopBtn.setEnabled(True)
        if not gTimeFlag:
            self.runWorkTh()
        elif gTimeFlag:
            self.runTimerTh()

    def runTimerTh(self):
        global gStartTime
        global gEndTime
        gStartTime=self.startTimeEdit.dateTime().toPyDateTime()
        gEndTime=self.endTimeEdit.dateTime().toPyDateTime()
        self.timerTh=timerThread()
        self.timerTh.startSignal.connect(self.runWorkTh)
        self.timerTh.endSignal.connect(self.stopBtnClick)
        self.timerTh.start()
        self.printLog({'msg':'启动定时器'})

    def runWorkTh(self):
        global gFlag
        gFlag = True
        self.sendIni()
        self.myTh = workThread()
        self.myTh.logSignal.connect(self.printLog)
        self.myTh.start()
        self.printLog({'msg': '正在启动软件'})

    def stopBtnClick(self,click=None):
        global gFlag
        self.startBtn.setEnabled(True)
        self.stopBtn.setEnabled(False)
        gFlag = False
        self.printLog({'msg':'正在关闭软件'})

    def closeEvent(self, QCloseEvent):
        global gFlag
        self.logFile.write(self.htmlPart2)
        self.logFile.close()
        gFlag=False
        QCloseEvent.accept()

    def timerClicked(self,status):
        global gTimeFlag
        gTimeFlag=status

if __name__=='__main__':

    gTimeFlag = False
    gStartTime = None
    gEndTime = None

    gWorkRunFlag = False

    gFlag=False
    gIniQueue=queue.Queue()

    app=QApplication(sys.argv)

    owo=OWO()

    app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())
    sys.exit(app.exec_())