from django.contrib import admin
from django.urls import path, include
from Crud import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('company/', include('company.urls')),
    path('department/', include('department.urls')),
    path('employee/',include('employee.urls')),
    path('project/',include('project.urls')),
    path('', views.index),
]


import curses
import sys
import time

if False:

    def pbar(window):
        for i in range(10):
            j = str(i * 10)
            window.addstr(
                0,
                0,
                "Time to download "
                + "["
                + ("#" * i)
                + ("-" * (9 - i))
                + "]"
                + " " * len(j)
                + j
                + "%",
            )
            window.addstr(10, 10, "[" + ("#" * i) + ("-" * (9 - i)) + "]")
            window.refresh()
            time.sleep(0.5)

    curses.wrapper(pbar)

else:
    for i in range(11):
        sys.stdout.write("\r[{0}{1}] {2}%".format("#" * i, "-" * (10 - i), i * 10))
        sys.stdout.flush()
        time.sleep(0.5)
    print


# -*- coding: utf-8 -*-
"""
Created on Fri Mar 11 16:03:50 2022

@author: ethan
"""

# -*- coding: utf-8 -*-
"""
Created on Sat Feb 19 14:05:58 2022

@author: ethan
"""

from datetime import date
from datetime import datetime as dt
from time import time
import math

import numpy as np
import pandas as pd
from scipy import stats

from bokeh.io import export_png, output_file, show
from bokeh.plotting import figure
from bokeh.models import NumeralTickFormatter, LabelSet, ColumnDataSource
from bokeh.models.tickers import FixedTicker
from bokeh.layouts import row, column

df1 = (
    pd.read_excel(
        "data.xlsx", sheet_name="Sheet1", index_col="date_daily", parse_dates=True
    ).dropna()
    / 100
)

df2 = pd.read_excel("data.xlsx", sheet_name="Sheet2").dropna()
date_convert = lambda x: dt(
    year=int(x[-2:]) + 1900, day=int(x[-4:-2]), month=int(x[:-4])
)
df2.index = df2["MTGDATE"].astype(str).apply(date_convert)
df2 = df2 / 100

print(df2)

NIUred = (200, 16, 46)
NIUpantone = (165, 167, 168)
#%%
def set_up(x, y, truncated=True, margins=None):
    if truncated:
        b = (3 * y.min() - y.max()) / 2
    else:
        b = y.min()
    if margins == None:
        xrng = (x.min(), x.max())
        yrng = (b, y.max())
    else:
        xrng = (x.min() - margins, x.max() + margins)
        yrng = (b - margins, y.max() + margins)

    x = x.dropna()
    y = y.dropna()

    return (x, y, xrng, yrng)

# Chart of approximately stionary time series, e.g. PCE-Core inflation from 2008 to 2020
def chart1(df, series, title, name):
    xdata, ydata, xrng, yrng = set_up(df.index, df[series], truncated=False)
    scale = 1
    p = figure(
        width= int(1000 * scale),
        height=int(666 * scale),
        title=title,
        x_axis_label="Date",
        x_axis_type="datetime",
        y_range=yrng,
        x_range=xrng,
        toolbar_location=None,
    )
    p.line(xrng, [0, 0], color="black", width=1)

    p.line(xdata, ydata, color=NIUred, width=2)

    p.xaxis[0].ticker.desired_num_ticks = 10
    # p.legend.location = "bottom_right"
    p.xgrid.grid_line_color = None
    p.ygrid.grid_line_color = None
    p.yaxis.formatter = NumeralTickFormatter(format="0.0%")
    #p.xaxis.major_label_orientation = math.pi/4
    p.title.text_font_size = "16pt"
    p.xaxis.axis_label_text_font_size = "14pt"
    p.yaxis.axis_label_text_font_size = "14pt"
    # p.legend.label_text_font_size = "14pt"
    export_png(p, filename=name)

    return p

# Chart of a regression e.g. inflation vs money supply
def chart2(df):
    xdata, ydata, xrng, yrng = set_up(
        df["DFF"], df["GDPC1_PCA"], truncated=False, margins=0.005
    )
    xrng = (0, xrng[1])
    p = figure(
        width=700,
        height=500,
        title="Do Rate Hikes Decrease Real GDP? 1954 to 2019",
        x_axis_label="Federal Funds Effective Rate (Quarterly Average)",
        y_axis_label="RGDP Growth (Annualized)",
        y_range=yrng,
        x_range=xrng,
    )
    p.line(xrng, [0, 0], color="black", width=3)
    p.line([0, 0], yrng, color="black", width=3)

    slope, intercept, r_value, p_value, std_err = stats.linregress(xdata, ydata)
    leg = "R = {:.4f}, Slope = {:.4f}".format(r_value, slope)
    p.line(xdata, xdata * slope + intercept, legend=leg, color=NIUpantone, width=4)
    p.circle(xdata, ydata, color=NIUred, size=5)

    p.xaxis[0].ticker.desired_num_ticks = 10
    p.xgrid.grid_line_color = None
    p.ygrid.grid_line_color = None
    p.xaxis.formatter = NumeralTickFormatter(format="0.0%")
    p.yaxis.formatter = NumeralTickFormatter(format="0.0%")
    p.title.text_font_size = "16pt"
    p.xaxis.axis_label_text_font_size = "14pt"
    p.yaxis.axis_label_text_font_size = "14pt"
    p.legend.label_text_font_size = "14pt"

    export_png(p, filename="imgs/ffrRgdp.png")

    return p

show(
    column(
        chart1(df1, "FFR_shock", "Gertler and Karadi Baseline Indicator", "gk15.png"),
        chart1(df2, "RESIDF", "Romer and Romer Indicator", "rr04.png"),
    )
)


import os
import time
import logging
import os.path as osp

import torch.distributed as dist

def setup_logger(logpth):
    logfile = 'Deeplab_v3plus-{}.log'.format(time.strftime('%Y-%m-%d-%H-%M-%S'))
    logfile = osp.join(logpth, logfile)
    FORMAT = '%(levelname)s %(filename)s(%(lineno)d): %(message)s'
    log_level = logging.INFO
    if dist.is_initialized() and dist.get_rank()!=0:
        log_level = logging.WARNING
    logging.basicConfig(level=log_level, format=FORMAT, filename=logfile)
    logging.root.addHandler(logging.StreamHandler())

class Logger(object):
    def __init__(self, args, logger_str):
        self._logger_name = args.save_path
        # if os.path
        self._logger_str = logger_str
        self._save_path = os.path.join(
            self._logger_name, self._logger_str+'.txt')
        # self._save_path = os.path.abspath(_save_path)
        self._file = open(self._save_path, 'w')

    def log(self, string, save=True):
        print(string)
        if save:
            self._file.write('{:}\n'.format(string))
            self._file.flush()

    def close(self):
        self._file.close()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/3/28 8:39 下午
# @Author  : 宋继贤
# @Description  :
# @File    : utils.py
# @Software: PyCharm

import torch
import gensim

def build_optimizer(args, model):
    optimizer = getattr(torch.optim, args.optim)(
        model.parameters(),
        lr=args.lr,
        weight_decay=args.weight_decay,
        amsgrad=args.amsgrad
    )
    return optimizer

def set_lr(optimizer, lr):
    for group in optimizer.param_groups:
        group['lr'] = lr

def load_embedding(w2v_file, vocab_size=859, embedding_size=256):
    w2v = gensim.models.Word2Vec.load(w2v_file).wv
    embedding = torch.zeros((vocab_size, embedding_size), dtype=torch.float32)
    for i in range(1, vocab_size):
        embedding[i] = torch.from_numpy(w2v[str(i - 1)].copy())
    return embedding


import discord
from discord import app_commands
from discord.ext import commands
from discord.ext import tasks
from discord import ui
import requests
from bs4 import BeautifulSoup
import json
import sqlite3
import os
import asyncio
import twitchio
from twitchio.ext import commands as cmd

import datetime
from typing import List

from discord.interactions import Interaction

bot = commands.Bot(command_prefix="!", intents = discord.Intents.all())
con = sqlite3.connect("C:/Users/nelso/OneDrive/Desktop/HenryBot/Stats.db")
cur = con.cursor()

@tasks.loop(minutes=1.0)
async def auto_stream_start():
    global ISLIVE
    channel = bot.get_channel(1112906850090893362)
    guild = bot.get_guild(1112902755426783394)
    role = guild.get_role(1114393370744340621)
    cur.execute("SELECT Live FROM Live_Info ORDER BY Entry DESC LIMIT 1")
    liveStatus = cur.fetchone()[0]
    cur.execute("SELECT Title FROM Live_Info ORDER BY Entry DESC LIMIT 1")
    title = cur.fetchone()[0]
    cur.execute("SELECT Game FROM Live_Info ORDER BY Entry DESC LIMIT 1")
    gameName = cur.fetchone()[0]
    cur.execute("SELECT Noti FROM Live_Info ORDER BY Entry DESC LIMIT 1")
    ISLIVE = cur.fetchone()[0]

    if liveStatus == "True" and ISLIVE == 'False':
        message = await channel.send(embed=EmbedSections.twitch_noti(title, gameName.upper()))
        with open('notiID.txt', "r+") as file:
            file.truncate(0)
            file.writelines(str(message.id))
        await channel.send(role.mention)
        ISLIVE = 'True'
    elif liveStatus == "True" and ISLIVE == 'True':
        with open('notiID.txt', "r+") as file:
            id = file.readline()
            message = await channel.fetch_message(int(id))
        await message.edit(embed=EmbedSections.twitch_noti(title, gameName.upper()))
    else:
        pass

@tasks.loop(minutes=1.0)
async def auto_stream_end():
    channel = bot.get_channel(1112906850090893362)
    guild = bot.get_guild(1112902755426783394)
    role = guild.get_role(1114393370744340621)
    cur.execute("SELECT Live FROM Live_Info ORDER BY Entry DESC LIMIT 1")
    liveStatus = cur.fetchone()[0]
    cur.execute("SELECT Noti FROM Live_Info ORDER BY Entry DESC LIMIT 1")
    ISLIVE = cur.fetchone()[0]

    if liveStatus == "False" and ISLIVE == 'True':
        await channel.purge(limit=10)
        cur.execute(f"UPDATE Live_Info SET Noti = '{False}' WHERE Noti = 'True'")
        con.commit()

@bot.event
async def on_ready():
    print("Bot is up")
    auto_stream_start.start()
    auto_stream_end.start()
    try:
        synced = await bot.tree.sync()
        print(f"Synced {len(synced)} commands")
    except Exception as e:
        print(e)

#Choices testing
@bot.tree.command(name="test", description="This is used for testing!")
@app_commands.choices(choices=[
    app_commands.Choice(name="Yes", value="yep"),
    app_commands.Choice(name="No", value="yep")
])
async def test(interaction: discord.Interaction, choices: app_commands.Choice[str]):
        if (choices.value == 'yep'):
            await interaction.response.send_message(content="Alright!", ephemeral=True)
        else:
            await interaction.response.send_message(content="Nope!")

#       ACTUAL BOT        #
#-------------------------#
class Variables():
    alternate = False #Button alternate functions. (Off by default)
    notiamount = 0

class EmbedSections():

    def title_card():
        embed = discord.Embed(title="Tatox3 Menu", color=0x6FFF7B)
        embed.set_image(url="https://media.giphy.com/media/pYy1pETzRveSzWQmEz/giphy.gif")
        return embed

    def help_body(name, avatar_url):
        embed=discord.Embed(color=0x6FFF7B)
        embed.set_author(name=f'\n{name}', icon_url=avatar_url)
        embed.add_field(name="ðŸŸ£ Subscriber roles ðŸŸ£", value="To get access to your twitch roles if you are subscribed please ensure you have the twitch connection enabled in your personal account settings and we do the rest.", inline=False)
        embed.add_field(name="ðŸŸ£ Twitch Live Notifications ðŸŸ£", value=f"To get notified when Tatox3 goes live on twitch head over to #live-notifications in order to get the notification role")
        embed.add_field(name="ðŸš§ More helpful tips to be added soon...ðŸš§\nIf you have any suggestions notify any of the admins", value="", inline=False)
        embed.set_footer(text="If you require further assistance, click on the option you are confused about using the buttons below.")
        return embed

    def twitch_body(name, avatar_url):
        embed = discord.Embed(color=0x6FFF7B)
        embed.set_author(name=f'\n{name}', icon_url=avatar_url)
        embed.set_image(url="https://media.giphy.com/media/v1.Y2lkPTc5MGI3NjExMjZjZTZiZWQxOGY5YWE0NzIwOThkZDM0YjQxZDJhOTUwN2ZmZjU1ZiZlcD12MV9pbnRlcm5hbF9naWZzX2dpZklkJmN0PWc/gli9wNZ5gt2gy9m2Zg/giphy.gif")
        embed.add_field(name="Further assistance:", value="Below you can find a gif of where you should be looking in your settings to enable your twitch connection.", inline=False)
        embed.add_field(name="", value="1. Go to your settings\n2. Click on the 'Connections' tab\n3. Click on the twitch Icon\n4. Authorize the connection through twitch")
        embed.set_footer(text="If you do not find it useful you can contact a moderator or admin.")
        return embed

    def twitch_noti_body(name, avatar_url, channel):
        embed = discord.Embed(color=0x6FFF7B)
        embed.set_author(name=f'\n{name}', icon_url=avatar_url)
        embed.add_field(name="Further assistance:", value="", inline=False)
        embed.add_field(name="", value=f"1. Go to {channel.mention} at the top of the discord\n2. Click on the reaction for which you want to get notified for!")
        embed.set_footer(text="If you do not find it useful you can contact a moderator or admin.")
        return embed

    def twitch_noti(title, game):
        channel = bot.get_channel(1112906850090893362)
        guild = bot.get_guild(1112902755426783394)
        embed = discord.Embed(title=f"{title}", description=f"TATOX3 IS LIVE ON TWITCH PLAYING {game} COME JOIN!", url="https://www.twitch.tv/tatox3_", color=0x6441a5)
        embed.set_image(url="https://cdn.discordapp.com/attachments/1112902756022358039/1120788781268750437/20230620_145403.jpg") #https://i.pinimg.com/originals/da/99/60/da99605920778b7b85b4fbb96cbacb78.gif
        #https://media.giphy.com/media/v1.Y2lkPTc5MGI3NjExNmFiY2ZlZjUxMmJiYmU0Yzc1ZTY4NGNhNTBkODQ2MDhhODcwODczMyZlcD12MV9pbnRlcm5hbF9naWZzX2dpZklkJmN0PWc/SMoMrhoSQvPBXhxqzj/giphy.gif
        return embed

    def leaderboard_body(result):
        count = 0
        embed = discord.Embed(title="POTATO LEADERBOARD", color=0x6FFF7B)
        embed.set_thumbnail(url="https://media.giphy.com/media/v1.Y2lkPTc5MGI3NjExdWZvbXVvYmdjNW92ZTNua2EwZWRobnV1N2VqMHBlemM2aWk3eWVjcCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/24vTxomgaewVz5ZwPx/giphy.gif")
        embed.add_field(name=f"LEADER: {result[0][0]} -> {result[0][1]} potatoes", value=f"Â· â€¢ â€”â€“â€”â€“ Ù  âœ¤ Ù  â€”â€“â€”â€“ â€¢ Â·")
        for i in result:
            if count > 0:
                embed.add_field(name=f"#{count+1} {result[count][0]}: {result[count][1]}", value="", inline=False)
            count += 1
        embed.set_footer(text="Chat in Henry's twitch chat to earn more")
        return embed

class MenuButtons(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)

    @discord.ui.button(label="1", style=discord.ButtonStyle.green)
    async def One(self, interaction: discord.Interaction, button: discord.Button):
        self.Two.disabled = True
        try:
            if Variables.alternate == False:
                button.label = "Back"
                await interaction.response.edit_message(embeds=[EmbedSections.title_card(), EmbedSections.twitch_body(interaction.user.name, interaction.user.avatar.url)], view=self)
                Variables.alternate = True
            else:
                await interaction.response.edit_message(embeds=[EmbedSections.title_card(), EmbedSections.help_body(interaction.user.name, interaction.user.avatar.url)], view=MenuButtons())
                Variables.alternate = False
        except Exception as e:
            print(e)

    @discord.ui.button(label='2', style=discord.ButtonStyle.green)
    async def Two(self, interaction: discord.Interaction, button: discord.Button):
        self.One.disabled = True
        try:
            if Variables.alternate == False:
                button.label = "Back"
                await interaction.response.edit_message(embeds=[EmbedSections.title_card(), EmbedSections.twitch_noti_body(interaction.user.name, interaction.user.avatar.url, channel=bot.get_channel(1114394449657745488))], view=self)
                Variables.alternate = True
            else:
                await interaction.response.edit_message(embeds=[EmbedSections.title_card(), EmbedSections.help_body(interaction.user.name, interaction.user.avatar.url)], view=MenuButtons())
                Variables.alternate = False
        except Exception as e:
            print(e)

    @discord.ui.button(label="Exit", style=discord.ButtonStyle.danger)
    async def Exit(self, interaction: discord.Interaction, Button: discord.Button):
        await interaction.response.edit_message(view=None, content="Exited.", embed=None)

class ClearModal(ui.Modal, title='Clear Command'):
    amount = ui.TextInput(label='How much do you want to delete?', style=discord.TextStyle.short,required=True)
    member = ui.TextInput(label="Member name (Optional)", style=discord.TextStyle.short, required=False, default=None)
    reason = ui.TextInput(label="Reason (Optional)", style=discord.TextStyle.paragraph, required=False, default=None)

    async def on_submit(self, interaction: discord.Interaction):
        try:
            if self.member.value == "":
                await interaction.channel.purge(limit=int(self.amount.value), reason=self.reason.value)
                await interaction.response.send_message(f"Chat was cleared by: {interaction.user.mention} ({int(self.amount.value)} messages cleared!)", delete_after=30)
            else:
                await interaction.channel.purge(limit=int(self.amount.value), reason=self.reason.value, check=lambda m: m.author.name == self.member.value)
                await interaction.response.send_message(f"{self.member.value}'s chat was cleared by: {interaction.user.mention} ({int(self.amount.value)} messages cleared!)", delete_after=30)
        except Exception:
            await interaction.response.send_message("Hmmm... Something went wrong! Please make sure you put a valid integer as an amount.", ephemeral=True, delete_after=10)

@bot.event
async def on_member_join(person):
    await person.add_roles(person.guild.get_role(1112902914160197724))

@bot.event
async def on_raw_reaction_add(payload):
    message = await bot.get_channel(payload.channel_id).fetch_message(payload.message_id)
    global member
    member = payload.member
    guild = bot.get_guild(1112902755426783394)
    twitch_role = guild.get_role(1114393370744340621)
    music_role = guild.get_role(1114396915400986734)
    if message.id == 1114942064321376256:
        if str(payload.emoji) == "ðŸŸ£":
            await payload.member.add_roles(twitch_role)
        if str(payload.emoji) == "ðŸŽ¶":
            await payload.member.add_roles(music_role)

@bot.event
async def on_raw_reaction_remove(payload):
    message = await bot.get_channel(payload.channel_id).fetch_message(payload.message_id)
    guild = bot.get_guild(1112902755426783394)
    twitch_role = guild.get_role(1114393370744340621)
    music_role = guild.get_role(1114396915400986734)
    if message.id == 1114942064321376256:
        if str(payload.emoji) == "ðŸŸ£":
            await member.remove_roles(twitch_role)
        if str(payload.emoji) == "ðŸŽ¶":
            await member.remove_roles(music_role)

@bot.tree.command(name="discord-help")
async def help(interaction: discord.Interaction):
    await interaction.response.send_message(embeds=[EmbedSections.title_card(), EmbedSections.help_body(interaction.user.name, interaction.user.avatar.url)], view=MenuButtons(), ephemeral=True, delete_after=120)

@bot.tree.command(name="clear")
@app_commands.default_permissions(manage_messages=True)
async def clear(interaction: discord.Interaction):
    await interaction.response.send_modal(ClearModal())

@bot.tree.command(name="whiffs")
async def Whiff(interaction: discord.Interaction):
    point = cur.execute("SELECT Amount From Whiff")
    result = point.fetchone()
    await interaction.response.send_message(f"Henry has been caught whiffing {result[0]} times on stream!\n\nIf you catch him whiffing do !whiff on his stream", ephemeral=False)

@bot.tree.command(name="link", description="Link the discord bot to your twitch account **CASE SENSITIVE**")
async def link(interaction: discord.Interaction, twitchname: str=None):
    channel = bot.get_channel(1119398653468082270)
    if twitchname is None:
        await interaction.response.send_message("Please specify your twitch username...")
    else:
        try:
            cur.execute(f"SELECT TwitchName FROM Economy WHERE TwitchName = '{twitchname}'")
            result = cur.fetchone()
            cur.execute(f"SELECT DiscordID FROM Economy WHERE TwitchName = '{twitchname}'")
            discord_result = cur.fetchone()
            if int(discord_result[0]) != 0:
                await interaction.response.send_message(f"This twitch name has already been registered to a user with the ID {discord_result[0]}", ephemeral=True)
            if result is None:
                pass
            if int(discord_result[0]) == 0:
                cur.execute(f"UPDATE Economy SET DiscordID = {interaction.user.id} WHERE TwitchName = '{twitchname}'")
                con.commit()
                await interaction.response.send_message(f"{twitchname} and {interaction.user.name} have been linked succesfully!")
                await channel.send(
                f"""- - - LINK INFO:
                Discord Name: {interaction.user.name}
                Twitch Name: {twitchname}
                Discord ID: {interaction.user.id}
                LINK SUCCESSFUL""")
                #FUcking make it an embed pls
        except Exception as e:
            await interaction.response.send_message("Please enter a valid twitch username, make sure you have sent at least 1 message in twitch chat", ephemeral=True)

@bot.tree.command(name="balance", description="Gets the balance of twitch potatoes")
async def bal(interaction: discord.Interaction):
    user_id = interaction.user.id
    cur.execute(f'SELECT DiscordID FROM Economy WHERE DiscordID = {user_id}')
    result = cur.fetchall()
    try:
        if result is None:
            pass
        else:
            cur.execute(f"SELECT Potatoes FROM Economy WHERE DiscordID = {user_id}")
            result = cur.fetchone()
            await interaction.response.send_message(f"Your current potato balance is {result[0]}", ephemeral=True)
    except:
        await interaction.response.send_message("Please use /link (twitch username) to link this bot to your twitch account and access your potatoes!")

@bot.tree.command(name="leaderboard", description="Displays the top 5 potato owners in Henry's stream!")
async def leaderboard(interaction: discord.Interaction):
    cur.execute(f'SELECT TwitchName, Potatoes FROM Economy ORDER BY Potatoes DESC LIMIT 5')
    result = cur.fetchall()
    await interaction.response.send_message(embed=EmbedSections.leaderboard_body(result=result))

@bot.tree.command(name="rank", description="Shows your ranking on the potato leaderboard")
async def rank(interaction: discord.Interaction):
    count = 0
    cur.execute(f'SELECT DiscordID, Potatoes FROM Economy ORDER BY Potatoes DESC')
    result = cur.fetchall()

    for i in result:
        count += 1
        if i[0] == interaction.user.id:
            await interaction.response.send_message(f"{interaction.user.mention} you are rank #{count} on the potato leaderboard with {i[1]} potatoes")
bot.run("MTExMjQ2OTY4MDU5NTE1MjkxNw.Gkw5Br.rrW9d2huMMaDruE2lzL33cchKH3xq7S12ilDp8")
#-------------------------------------------------------------------#


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/12/24 13:57
# @Author  : Tian Hao
# @Email   : hao.tian@intcolon.cn
# @File    : tools.py
# @Software: PyCharm
# @Desc    : 时间处理

import calendar
import datetime

from BaiduIndex.tools.DBHelper import DBHelper

def get_time_range_list(start_date, end_date):
    """
    根据开始时间和结束时间按月份获取每月第一天和最后一天
    :param start_date: 起始时间 --> str
    :param end_date: 结束时间 --> str
    :return: date_range_list -->list
    """
    date_range_list = []
    start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d')
    end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')
    while 1:
        next_month = start_date + datetime.timedelta(days=calendar.monthrange(start_date.year, start_date.month)[1])
        month_end = next_month - datetime.timedelta(days=1)
        if month_end < end_date:
            date_range_list.append((datetime.datetime.strftime(start_date,
                                                               '%Y-%m-%d'),
                                    datetime.datetime.strftime(month_end,
                                                               '%Y-%m-%d')))
            start_date = next_month
        else:
            return date_range_list

class QueryData(object):
    def __init__(self):
        self.db_helper = DBHelper()

    def get_region_id(self):
        # 查询省份ID
        query_sql = "SELECT id FROM province_id ORDER BY id"
        return self.db_helper.query_task(query_sql)

    def get_keyword(self, table_name):
        keywords_list = []
        sql = 'SELECT distinct(keyword) FROM {}'.format(table_name)
        keywords = self.db_helper.query_task(sql)
        for keyword in keywords:
            keywords_list.append(str.lower(str(keyword[0])).strip())
        return keywords_list[2400:]

if __name__ == '__main__':
    startDate = "2020-03-01"
    endDate = "2020-09-01"
    print(get_time_range_list(startDate, endDate))


# encoding: utf-8
"""Test keras.layers.core.Layer.__call__"""

from __future__ import print_function

import unittest
import numpy as np

from numpy.testing import assert_allclose

from keras import backend as K
from keras.layers.core import Dense
from keras.models import Sequential

class TestCall(unittest.TestCase):
    """Test __call__ methods"""

    def test_layer_call(self):
        """Test keras.layers.core.Layer.__call__"""
        nb_samples, input_dim, output_dim = 3, 10, 5
        layer = Dense(output_dim, input_dim=input_dim)
        W = np.asarray(K.eval(layer.W)).astype(K.floatx())
        X = K.placeholder(ndim=2)
        Y = layer(X)
        F = K.function([X], [Y])

        x = np.ones((nb_samples, input_dim)).astype(K.floatx())
        y = F([x])[0].astype(K.floatx())
        t = np.dot(x, W).astype(K.floatx())
        assert_allclose(t, y, rtol=.2)

    def test_sequential_call(self):
        """Test keras.models.Sequential.__call__"""
        nb_samples, input_dim, output_dim = 3, 10, 5
        model = Sequential()
        model.add(Dense(output_dim=output_dim, input_dim=input_dim))
        model.compile('sgd', 'mse')

        X = K.placeholder(ndim=2)
        Y = model(X)
        F = K.function([X], [Y])

        x = np.ones((nb_samples, input_dim)).astype(K.floatx())
        y1 = F([x])[0].astype(K.floatx())
        y2 = model.predict(x)
        # results of __call__ should match model.predict
        assert_allclose(y1, y2)

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


from flask_wtf import FlaskForm
from wtforms import StringField, TextAreaField, validators

class CategoryForm(FlaskForm):
    # Minimum in name is only one because some languages such as Japanese can easily have
    # one character long words such as ухх as in picture.
    name = StringField(
        "Category",
        [
            validators.Length(min=1, max=64),
            validators.data_required()
        ]
    )

    description = TextAreaField(
        "Description",
        [validators.Length(max=1024)]
    )

    class Meta:
        csrf = False


"""Tool for sorting imports alphabetically, and automatically separated into sections."""
import argparse
import functools
import json
import os
import sys
from gettext import gettext as _
from io import TextIOWrapper
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence, Union
from warnings import warn

from . import __version__, api, files, sections
from .exceptions import FileSkipped, ISortError, UnsupportedEncoding
from .format import create_terminal_printer
from .logo import ASCII_ART
from .profiles import profiles
from .settings import VALID_PY_TARGETS, Config, find_all_configs
from .utils import Trie
from .wrap_modes import WrapModes

DEPRECATED_SINGLE_DASH_ARGS = {
    "-ac",
    "-af",
    "-ca",
    "-cs",
    "-df",
    "-ds",
    "-dt",
    "-fas",
    "-fass",
    "-ff",
    "-fgw",
    "-fss",
    "-lai",
    "-lbt",
    "-le",
    "-ls",
    "-nis",
    "-nlb",
    "-ot",
    "-rr",
    "-sd",
    "-sg",
    "-sl",
    "-sp",
    "-tc",
    "-wl",
    "-ws",
}
QUICK_GUIDE = f"""
{ASCII_ART}

Nothing to do: no files or paths have have been passed in!

Try one of the following:

    `isort .` - sort all Python files, starting from the current directory, recursively.
    `isort . --interactive` - Do the same, but ask before making any changes.
    `isort . --check --diff` - Check to see if imports are correctly sorted within this project.
    `isort --help` - In-depth information about isort's available command-line options.

Visit https://pycqa.github.io/isort/ for complete information about how to use isort.
"""

class SortAttempt:
    def __init__(self, incorrectly_sorted: bool, skipped: bool, supported_encoding: bool) -> None:
        self.incorrectly_sorted = incorrectly_sorted
        self.skipped = skipped
        self.supported_encoding = supported_encoding

def sort_imports(
    file_name: str,
    config: Config,
    check: bool = False,
    ask_to_apply: bool = False,
    write_to_stdout: bool = False,
    **kwargs: Any,
) -> Optional[SortAttempt]:
    incorrectly_sorted: bool = False
    skipped: bool = False
    try:
        if check:
            try:
                incorrectly_sorted = not api.check_file(file_name, config=config, **kwargs)
            except FileSkipped:
                skipped = True
            return SortAttempt(incorrectly_sorted, skipped, True)

        try:
            incorrectly_sorted = not api.sort_file(
                file_name,
                config=config,
                ask_to_apply=ask_to_apply,
                write_to_stdout=write_to_stdout,
                **kwargs,
            )
        except FileSkipped:
            skipped = True
        return SortAttempt(incorrectly_sorted, skipped, True)
    except (OSError, ValueError) as error:
        warn(f"Unable to parse file {file_name} due to {error}")
        return None
    except UnsupportedEncoding:
        if config.verbose:
            warn(f"Encoding not supported for {file_name}")
        return SortAttempt(incorrectly_sorted, skipped, False)
    except ISortError as error:
        _print_hard_fail(config, message=str(error))
        sys.exit(1)
    except Exception:
        _print_hard_fail(config, offending_file=file_name)
        raise

def _print_hard_fail(
    config: Config, offending_file: Optional[str] = None, message: Optional[str] = None
) -> None:
    """Fail on unrecoverable exception with custom message."""
    message = message or (
        f"Unrecoverable exception thrown when parsing {offending_file or ''}! "
        "This should NEVER happen.\n"
        "If encountered, please open an issue: https://github.com/PyCQA/isort/issues/new"
    )
    printer = create_terminal_printer(
        color=config.color_output, error=config.format_error, success=config.format_success
    )
    printer.error(message)

def _build_arg_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        description="Sort Python import definitions alphabetically "
        "within logical sections. Run with no arguments to see a quick "
        "start guide, otherwise, one or more files/directories/stdin must be provided. "
        "Use `-` as the first argument to represent stdin. Use --interactive to use the pre 5.0.0 "
        "interactive behavior."
        " "
        "If you've used isort 4 but are new to isort 5, see the upgrading guide: "
        "https://pycqa.github.io/isort/docs/upgrade_guides/5.0.0.html",
        add_help=False,  # prevent help option from appearing in "optional arguments" group
    )

    general_group = parser.add_argument_group("general options")
    target_group = parser.add_argument_group("target options")
    output_group = parser.add_argument_group("general output options")
    inline_args_group = output_group.add_mutually_exclusive_group()
    section_group = parser.add_argument_group("section output options")
    deprecated_group = parser.add_argument_group("deprecated options")

    general_group.add_argument(
        "-h",
        "--help",
        action="help",
        default=argparse.SUPPRESS,
        help=_("show this help message and exit"),
    )
    general_group.add_argument(
        "-V",
        "--version",
        action="store_true",
        dest="show_version",
        help="Displays the currently installed version of isort.",
    )
    general_group.add_argument(
        "--vn",
        "--version-number",
        action="version",
        version=__version__,
        help="Returns just the current version number without the logo",
    )
    general_group.add_argument(
        "-v",
        "--verbose",
        action="store_true",
        dest="verbose",
        help="Shows verbose output, such as when files are skipped or when a check is successful.",
    )
    general_group.add_argument(
        "--only-modified",
        "--om",
        dest="only_modified",
        action="store_true",
        help="Suppresses verbose output for non-modified files.",
    )
    general_group.add_argument(
        "--dedup-headings",
        dest="dedup_headings",
        action="store_true",
        help="Tells isort to only show an identical custom import heading comment once, even if"
        " there are multiple sections with the comment set.",
    )
    general_group.add_argument(
        "-q",
        "--quiet",
        action="store_true",
        dest="quiet",
        help="Shows extra quiet output, only errors are outputted.",
    )
    general_group.add_argument(
        "-d",
        "--stdout",
        help="Force resulting output to stdout, instead of in-place.",
        dest="write_to_stdout",
        action="store_true",
    )
    general_group.add_argument(
        "--overwrite-in-place",
        help="Tells isort to overwrite in place using the same file handle. "
        "Comes at a performance and memory usage penalty over its standard "
        "approach but ensures all file flags and modes stay unchanged.",
        dest="overwrite_in_place",
        action="store_true",
    )
    general_group.add_argument(
        "--show-config",
        dest="show_config",
        action="store_true",
        help="See isort's determined config, as well as sources of config options.",
    )
    general_group.add_argument(
        "--show-files",
        dest="show_files",
        action="store_true",
        help="See the files isort will be run against with the current config options.",
    )
    general_group.add_argument(
        "--df",
        "--diff",
        dest="show_diff",
        action="store_true",
        help="Prints a diff of all the changes isort would make to a file, instead of "
        "changing it in place",
    )
    general_group.add_argument(
        "-c",
        "--check-only",
        "--check",
        action="store_true",
        dest="check",
        help="Checks the file for unsorted / unformatted imports and prints them to the "
        "command line without modifying the file. Returns 0 when nothing would change and "
        "returns 1 when the file would be reformatted.",
    )
    general_group.add_argument(
        "--ws",
        "--ignore-whitespace",
        action="store_true",
        dest="ignore_whitespace",
        help="Tells isort to ignore whitespace differences when --check-only is being used.",
    )
    general_group.add_argument(
        "--sp",
        "--settings-path",
        "--settings-file",
        "--settings",
        dest="settings_path",
        help="Explicitly set the settings path or file instead of auto determining "
        "based on file location.",
    )
    general_group.add_argument(
        "--cr",
        "--config-root",
        dest="config_root",
        help="Explicitly set the config root for resolving all configs. When used "
        "with the --resolve-all-configs flag, isort will look at all sub-folders "
        "in this config root to resolve config files and sort files based on the "
        "closest available config(if any)",
    )
    general_group.add_argument(
        "--resolve-all-configs",
        dest="resolve_all_configs",
        action="store_true",
        help="Tells isort to resolve the configs for all sub-directories "
        "and sort files in terms of its closest config files.",
    )
    general_group.add_argument(
        "--profile",
        dest="profile",
        type=str,
        help="Base profile type to use for configuration. "
        f"Profiles include: {', '.join(profiles.keys())}. As well as any shared profiles.",
    )
    general_group.add_argument(
        "--old-finders",
        "--magic-placement",
        dest="old_finders",
        action="store_true",
        help="Use the old deprecated finder logic that relies on environment introspection magic.",
    )
    general_group.add_argument(
        "-j",
        "--jobs",
        help="Number of files to process in parallel. Negative value means use number of CPUs.",
        dest="jobs",
        type=int,
        nargs="?",
        const=-1,
    )
    general_group.add_argument(
        "--ac",
        "--atomic",
        dest="atomic",
        action="store_true",
        help="Ensures the output doesn't save if the resulting file contains syntax errors.",
    )
    general_group.add_argument(
        "--interactive",
        dest="ask_to_apply",
        action="store_true",
        help="Tells isort to apply changes interactively.",
    )
    general_group.add_argument(
        "--format-error",
        dest="format_error",
        help="Override the format used to print errors.",
    )
    general_group.add_argument(
        "--format-success",
        dest="format_success",
        help="Override the format used to print success.",
    )
    general_group.add_argument(
        "--srx",
        "--sort-reexports",
        dest="sort_reexports",
        action="store_true",
        help="Automatically sort all re-exports (module level __all__ collections)",
    )

    target_group.add_argument(
        "files", nargs="*", help="One or more Python source files that need their imports sorted."
    )
    target_group.add_argument(
        "--filter-files",
        dest="filter_files",
        action="store_true",
        help="Tells isort to filter files even when they are explicitly passed in as "
        "part of the CLI command.",
    )
    target_group.add_argument(
        "-s",
        "--skip",
        help="Files that isort should skip over. If you want to skip multiple "
        "files you should specify twice: --skip file1 --skip file2. Values can be "
        "file names, directory names or file paths. To skip all files in a nested path "
        "use --skip-glob.",
        dest="skip",
        action="append",
    )
    target_group.add_argument(
        "--extend-skip",
        help="Extends --skip to add additional files that isort should skip over. "
        "If you want to skip multiple "
        "files you should specify twice: --skip file1 --skip file2. Values can be "
        "file names, directory names or file paths. To skip all files in a nested path "
        "use --skip-glob.",
        dest="extend_skip",
        action="append",
    )
    target_group.add_argument(
        "--sg",
        "--skip-glob",
        help="Files that isort should skip over.",
        dest="skip_glob",
        action="append",
    )
    target_group.add_argument(
        "--extend-skip-glob",
        help="Additional files that isort should skip over (extending --skip-glob).",
        dest="extend_skip_glob",
        action="append",
    )
    target_group.add_argument(
        "--gitignore",
        "--skip-gitignore",
        action="store_true",
        dest="skip_gitignore",
        help="Treat project as a git repository and ignore files listed in .gitignore."
        "\nNOTE: This requires git to be installed and accessible from the same shell as isort.",
    )
    target_group.add_argument(
        "--ext",
        "--extension",
        "--supported-extension",
        dest="supported_extensions",
        action="append",
        help="Specifies what extensions isort can be run against.",
    )
    target_group.add_argument(
        "--blocked-extension",
        dest="blocked_extensions",
        action="append",
        help="Specifies what extensions isort can never be run against.",
    )
    target_group.add_argument(
        "--dont-follow-links",
        dest="dont_follow_links",
        action="store_true",
        help="Tells isort not to follow symlinks that are encountered when running recursively.",
    )
    target_group.add_argument(
        "--filename",
        dest="filename",
        help="Provide the filename associated with a stream.",
    )
    target_group.add_argument(
        "--allow-root",
        action="store_true",
        default=False,
        help="Tells isort not to treat / specially, allowing it to be run against the root dir.",
    )

    output_group.add_argument(
        "-a",
        "--add-import",
        dest="add_imports",
        action="append",
        help="Adds the specified import line to all files, "
        "automatically determining correct placement.",
    )
    output_group.add_argument(
        "--append",
        "--append-only",
        dest="append_only",
        action="store_true",
        help="Only adds the imports specified in --add-import if the file"
        " contains existing imports.",
    )
    output_group.add_argument(
        "--af",
        "--force-adds",
        dest="force_adds",
        action="store_true",
        help="Forces import adds even if the original file is empty.",
    )
    output_group.add_argument(
        "--rm",
        "--remove-import",
        dest="remove_imports",
        action="append",
        help="Removes the specified import from all files.",
    )
    output_group.add_argument(
        "--float-to-top",
        dest="float_to_top",
        action="store_true",
        help="Causes all non-indented imports to float to the top of the file having its imports "
        "sorted (immediately below the top of file comment).\n"
        "This can be an excellent shortcut for collecting imports every once in a while "
        "when you place them in the middle of a file to avoid context switching.\n\n"
        "*NOTE*: It currently doesn't work with cimports and introduces some extra over-head "
        "and a performance penalty.",
    )
    output_group.add_argument(
        "--dont-float-to-top",
        dest="dont_float_to_top",
        action="store_true",
        help="Forces --float-to-top setting off. See --float-to-top for more information.",
    )
    output_group.add_argument(
        "--ca",
        "--combine-as",
        dest="combine_as_imports",
        action="store_true",
        help="Combines as imports on the same line.",
    )
    output_group.add_argument(
        "--cs",
        "--combine-star",
        dest="combine_star",
        action="store_true",
        help="Ensures that if a star import is present, "
        "nothing else is imported from that namespace.",
    )
    output_group.add_argument(
        "-e",
        "--balanced",
        dest="balanced_wrapping",
        action="store_true",
        help="Balances wrapping to produce the most consistent line length possible",
    )
    output_group.add_argument(
        "--ff",
        "--from-first",
        dest="from_first",
        action="store_true",
        help="Switches the typical ordering preference, "
        "showing from imports first then straight ones.",
    )
    output_group.add_argument(
        "--fgw",
        "--force-grid-wrap",
        nargs="?",
        const=2,
        type=int,
        dest="force_grid_wrap",
        help="Force number of from imports (defaults to 2 when passed as CLI flag without value) "
        "to be grid wrapped regardless of line "
        "length. If 0 is passed in (the global default) only line length is considered.",
    )
    output_group.add_argument(
        "-i",
        "--indent",
        help='String to place for indents defaults to "    " (4 spaces).',
        dest="indent",
        type=str,
    )
    output_group.add_argument(
        "--lbi", "--lines-before-imports", dest="lines_before_imports", type=int
    )
    output_group.add_argument(
        "--lai", "--lines-after-imports", dest="lines_after_imports", type=int
    )
    output_group.add_argument(
        "--lbt", "--lines-between-types", dest="lines_between_types", type=int
    )
    output_group.add_argument(
        "--le",
        "--line-ending",
        dest="line_ending",
        help="Forces line endings to the specified value. "
        "If not set, values will be guessed per-file.",
    )
    output_group.add_argument(
        "--ls",
        "--length-sort",
        help="Sort imports by their string length.",
        dest="length_sort",
        action="store_true",
    )
    output_group.add_argument(
        "--lss",
        "--length-sort-straight",
        help="Sort straight imports by their string length. Similar to `length_sort` "
        "but applies only to straight imports and doesn't affect from imports.",
        dest="length_sort_straight",
        action="store_true",
    )
    output_group.add_argument(
        "-m",
        "--multi-line",
        dest="multi_line_output",
        choices=list(WrapModes.__members__.keys())
        + [str(mode.value) for mode in WrapModes.__members__.values()],
        type=str,
        help="Multi line output (0-grid, 1-vertical, 2-hanging, 3-vert-hanging, 4-vert-grid, "
        "5-vert-grid-grouped, 6-deprecated-alias-for-5, 7-noqa, "
        "8-vertical-hanging-indent-bracket, 9-vertical-prefix-from-module-import, "
        "10-hanging-indent-with-parentheses).",
    )
    output_group.add_argument(
        "-n",
        "--ensure-newline-before-comments",
        dest="ensure_newline_before_comments",
        action="store_true",
        help="Inserts a blank line before a comment following an import.",
    )
    inline_args_group.add_argument(
        "--nis",
        "--no-inline-sort",
        dest="no_inline_sort",
        action="store_true",
        help="Leaves `from` imports with multiple imports 'as-is' "
        "(e.g. `from foo import a, c ,b`).",
    )
    output_group.add_argument(
        "--ot",
        "--order-by-type",
        dest="order_by_type",
        action="store_true",
        help="Order imports by type, which is determined by case, in addition to alphabetically.\n"
        "\n**NOTE**: type here refers to the implied type from the import name capitalization.\n"
        ' isort does not do type introspection for the imports. These "types" are simply: '
        "CONSTANT_VARIABLE, CamelCaseClass, variable_or_function. If your project follows PEP8"
        " or a related coding standard and has many imports this is a good default, otherwise you "
        "likely will want to turn it off. From the CLI the `--dont-order-by-type` option will turn "
        "this off.",
    )
    output_group.add_argument(
        "--dt",
        "--dont-order-by-type",
        dest="dont_order_by_type",
        action="store_true",
        help="Don't order imports by type, which is determined by case, in addition to "
        "alphabetically.\n\n"
        "**NOTE**: type here refers to the implied type from the import name capitalization.\n"
        ' isort does not do type introspection for the imports. These "types" are simply: '
        "CONSTANT_VARIABLE, CamelCaseClass, variable_or_function. If your project follows PEP8"
        " or a related coding standard and has many imports this is a good default. You can turn "
        "this on from the CLI using `--order-by-type`.",
    )
    output_group.add_argument(
        "--rr",
        "--reverse-relative",
        dest="reverse_relative",
        action="store_true",
        help="Reverse order of relative imports.",
    )
    output_group.add_argument(
        "--reverse-sort",
        dest="reverse_sort",
        action="store_true",
        help="Reverses the ordering of imports.",
    )
    output_group.add_argument(
        "--sort-order",
        dest="sort_order",
        help="Specify sorting function. Can be built in (natural[default] = force numbers "
        "to be sequential, native = Python's built-in sorted function) or an installable plugin.",
    )
    inline_args_group.add_argument(
        "--sl",
        "--force-single-line-imports",
        dest="force_single_line",
        action="store_true",
        help="Forces all from imports to appear on their own line",
    )
    output_group.add_argument(
        "--nsl",
        "--single-line-exclusions",
        help="One or more modules to exclude from the single line rule.",
        dest="single_line_exclusions",
        action="append",
    )
    output_group.add_argument(
        "--tc",
        "--trailing-comma",
        dest="include_trailing_comma",
        action="store_true",
        help="Includes a trailing comma on multi line imports that include parentheses.",
    )
    output_group.add_argument(
        "--up",
        "--use-parentheses",
        dest="use_parentheses",
        action="store_true",
        help="Use parentheses for line continuation on length limit instead of slashes."
        " **NOTE**: This is separate from wrap modes, and only affects how individual lines that "
        " are too long get continued, not sections of multiple imports.",
    )
    output_group.add_argument(
        "-l",
        "-w",
        "--line-length",
        "--line-width",
        help="The max length of an import line (used for wrapping long imports).",
        dest="line_length",
        type=int,
    )
    output_group.add_argument(
        "--wl",
        "--wrap-length",
        dest="wrap_length",
        type=int,
        help="Specifies how long lines that are wrapped should be, if not set line_length is used."
        "\nNOTE: wrap_length must be LOWER than or equal to line_length.",
    )
    output_group.add_argument(
        "--case-sensitive",
        dest="case_sensitive",
        action="store_true",
        help="Tells isort to include casing when sorting module names",
    )
    output_group.add_argument(
        "--remove-redundant-aliases",
        dest="remove_redundant_aliases",
        action="store_true",
        help=(
            "Tells isort to remove redundant aliases from imports, such as `import os as os`."
            " This defaults to `False` simply because some projects use these seemingly useless "
            " aliases to signify intent and change behaviour."
        ),
    )
    output_group.add_argument(
        "--honor-noqa",
        dest="honor_noqa",
        action="store_true",
        help="Tells isort to honor noqa comments to enforce skipping those comments.",
    )
    output_group.add_argument(
        "--treat-comment-as-code",
        dest="treat_comments_as_code",
        action="append",
        help="Tells isort to treat the specified single line comment(s) as if they are code.",
    )
    output_group.add_argument(
        "--treat-all-comment-as-code",
        dest="treat_all_comments_as_code",
        action="store_true",
        help="Tells isort to treat all single line comments as if they are code.",
    )
    output_group.add_argument(
        "--formatter",
        dest="formatter",
        type=str,
        help="Specifies the name of a formatting plugin to use when producing output.",
    )
    output_group.add_argument(
        "--color",
        dest="color_output",
        action="store_true",
        help="Tells isort to use color in terminal output.",
    )
    output_group.add_argument(
        "--ext-format",
        dest="ext_format",
        help="Tells isort to format the given files according to an extensions formatting rules.",
    )
    output_group.add_argument(
        "--star-first",
        help="Forces star imports above others to avoid overriding directly imported variables.",
        dest="star_first",
        action="store_true",
    )
    output_group.add_argument(
        "--split-on-trailing-comma",
        help="Split imports list followed by a trailing comma into VERTICAL_HANGING_INDENT mode",
        dest="split_on_trailing_comma",
        action="store_true",
    )

    section_group.add_argument(
        "--sd",
        "--section-default",
        dest="default_section",
        help="Sets the default section for import options: " + str(sections.DEFAULT),
    )
    section_group.add_argument(
        "--only-sections",
        "--os",
        dest="only_sections",
        action="store_true",
        help="Causes imports to be sorted based on their sections like STDLIB, THIRDPARTY, etc. "
        "Within sections, the imports are ordered by their import style and the imports with "
        "the same style maintain their relative positions.",
    )
    section_group.add_argument(
        "--ds",
        "--no-sections",
        help="Put all imports into the same section bucket",
        dest="no_sections",
        action="store_true",
    )
    section_group.add_argument(
        "--fas",
        "--force-alphabetical-sort",
        action="store_true",
        dest="force_alphabetical_sort",
        help="Force all imports to be sorted as a single section",
    )
    section_group.add_argument(
        "--fss",
        "--force-sort-within-sections",
        action="store_true",
        dest="force_sort_within_sections",
        help="Don't sort straight-style imports (like import sys) before from-style imports "
        "(like from itertools import groupby). Instead, sort the imports by module, "
        "independent of import style.",
    )
    section_group.add_argument(
        "--hcss",
        "--honor-case-in-force-sorted-sections",
        action="store_true",
        dest="honor_case_in_force_sorted_sections",
        help="Honor `--case-sensitive` when `--force-sort-within-sections` is being used. "
        "Without this option set, `--order-by-type` decides module name ordering too.",
    )
    section_group.add_argument(
        "--srss",
        "--sort-relative-in-force-sorted-sections",
        action="store_true",
        dest="sort_relative_in_force_sorted_sections",
        help="When using `--force-sort-within-sections`, sort relative imports the same "
        "way as they are sorted when not using that setting.",
    )
    section_group.add_argument(
        "--fass",
        "--force-alphabetical-sort-within-sections",
        action="store_true",
        dest="force_alphabetical_sort_within_sections",
        help="Force all imports to be sorted alphabetically within a section",
    )
    section_group.add_argument(
        "-t",
        "--top",
        help="Force specific imports to the top of their appropriate section.",
        dest="force_to_top",
        action="append",
    )
    section_group.add_argument(
        "--combine-straight-imports",
        "--csi",
        dest="combine_straight_imports",
        action="store_true",
        help="Combines all the bare straight imports of the same section in a single line. "
        "Won't work with sections which have 'as' imports",
    )
    section_group.add_argument(
        "--nlb",
        "--no-lines-before",
        help="Sections which should not be split with previous by empty lines",
        dest="no_lines_before",
        action="append",
    )
    section_group.add_argument(
        "--src",
        "--src-path",
        dest="src_paths",
        action="append",
        help="Add an explicitly defined source path "
        "(modules within src paths have their imports automatically categorized as first_party)."
        " Glob expansion (`*` and `**`) is supported for this option.",
    )
    section_group.add_argument(
        "-b",
        "--builtin",
        dest="known_standard_library",
        action="append",
        help="Force isort to recognize a module as part of Python's standard library.",
    )
    section_group.add_argument(
        "--extra-builtin",
        dest="extra_standard_library",
        action="append",
        help="Extra modules to be included in the list of ones in Python's standard library.",
    )
    section_group.add_argument(
        "-f",
        "--future",
        dest="known_future_library",
        action="append",
        help="Force isort to recognize a module as part of Python's internal future compatibility "
        "libraries. WARNING: this overrides the behavior of __future__ handling and therefore"
        " can result in code that can't execute. If you're looking to add dependencies such "
        "as six, a better option is to create another section below --future using custom "
        "sections. See: https://github.com/PyCQA/isort#custom-sections-and-ordering and the "
        "discussion here: https://github.com/PyCQA/isort/issues/1463.",
    )
    section_group.add_argument(
        "-o",
        "--thirdparty",
        dest="known_third_party",
        action="append",
        help="Force isort to recognize a module as being part of a third party library.",
    )
    section_group.add_argument(
        "-p",
        "--project",
        dest="known_first_party",
        action="append",
        help="Force isort to recognize a module as being part of the current python project.",
    )
    section_group.add_argument(
        "--known-local-folder",
        dest="known_local_folder",
        action="append",
        help="Force isort to recognize a module as being a local folder. "
        "Generally, this is reserved for relative imports (from . import module).",
    )
    section_group.add_argument(
        "--virtual-env",
        dest="virtual_env",
        help="Virtual environment to use for determining whether a package is third-party",
    )
    section_group.add_argument(
        "--conda-env",
        dest="conda_env",
        help="Conda environment to use for determining whether a package is third-party",
    )
    section_group.add_argument(
        "--py",
        "--python-version",
        action="store",
        dest="py_version",
        choices=tuple(VALID_PY_TARGETS) + ("auto",),
        help="Tells isort to set the known standard library based on the specified Python "
        "version. Default is to assume any Python 3 version could be the target, and use a union "
        "of all stdlib modules across versions. If auto is specified, the version of the "
        "interpreter used to run isort "
        f"(currently: {sys.version_info.major}{sys.version_info.minor}) will be used.",
    )

    # deprecated options
    deprecated_group.add_argument(
        "--recursive",
        dest="deprecated_flags",
        action="append_const",
        const="--recursive",
        help=argparse.SUPPRESS,
    )
    deprecated_group.add_argument(
        "-rc", dest="deprecated_flags", action="append_const", const="-rc", help=argparse.SUPPRESS
    )
    deprecated_group.add_argument(
        "--dont-skip",
        dest="deprecated_flags",
        action="append_const",
        const="--dont-skip",
        help=argparse.SUPPRESS,
    )
    deprecated_group.add_argument(
        "-ns", dest="deprecated_flags", action="append_const", const="-ns", help=argparse.SUPPRESS
    )
    deprecated_group.add_argument(
        "--apply",
        dest="deprecated_flags",
        action="append_const",
        const="--apply",
        help=argparse.SUPPRESS,
    )
    deprecated_group.add_argument(
        "-k",
        "--keep-direct-and-as",
        dest="deprecated_flags",
        action="append_const",
        const="--keep-direct-and-as",
        help=argparse.SUPPRESS,
    )

    return parser

def parse_args(argv: Optional[Sequence[str]] = None) -> Dict[str, Any]:
    argv = sys.argv[1:] if argv is None else list(argv)
    remapped_deprecated_args = []
    for index, arg in enumerate(argv):
        if arg in DEPRECATED_SINGLE_DASH_ARGS:
            remapped_deprecated_args.append(arg)
            argv[index] = f"-{arg}"

    parser = _build_arg_parser()
    arguments = {key: value for key, value in vars(parser.parse_args(argv)).items() if value}
    if remapped_deprecated_args:
        arguments["remapped_deprecated_args"] = remapped_deprecated_args
    if "dont_order_by_type" in arguments:
        arguments["order_by_type"] = False
        del arguments["dont_order_by_type"]
    if "dont_follow_links" in arguments:
        arguments["follow_links"] = False
        del arguments["dont_follow_links"]
    if "dont_float_to_top" in arguments:
        del arguments["dont_float_to_top"]
        if arguments.get("float_to_top", False):
            sys.exit("Can't set both --float-to-top and --dont-float-to-top.")
        else:
            arguments["float_to_top"] = False
    multi_line_output = arguments.get("multi_line_output", None)
    if multi_line_output:
        if multi_line_output.isdigit():
            arguments["multi_line_output"] = WrapModes(int(multi_line_output))
        else:
            arguments["multi_line_output"] = WrapModes[multi_line_output]

    return arguments

def _preconvert(item: Any) -> Union[str, List[Any]]:
    """Preconverts objects from native types into JSONifyiable types"""
    if isinstance(item, (set, frozenset)):
        return list(item)
    if isinstance(item, WrapModes):
        return str(item.name)
    if isinstance(item, Path):
        return str(item)
    if callable(item) and hasattr(item, "__name__"):
        return str(item.__name__)
    raise TypeError(f"Unserializable object {item} of type {type(item)}")

def identify_imports_main(
    argv: Optional[Sequence[str]] = None, stdin: Optional[TextIOWrapper] = None
) -> None:
    parser = argparse.ArgumentParser(
        description="Get all import definitions from a given file."
        "Use `-` as the first argument to represent stdin."
    )
    parser.add_argument(
        "files", nargs="+", help="One or more Python source files that need their imports sorted."
    )
    parser.add_argument(
        "--top-only",
        action="store_true",
        default=False,
        help="Only identify imports that occur in before functions or classes.",
    )

    target_group = parser.add_argument_group("target options")
    target_group.add_argument(
        "--follow-links",
        action="store_true",
        default=False,
        help="Tells isort to follow symlinks that are encountered when running recursively.",
    )

    uniqueness = parser.add_mutually_exclusive_group()
    uniqueness.add_argument(
        "--unique",
        action="store_true",
        default=False,
        help="If true, isort will only identify unique imports.",
    )
    uniqueness.add_argument(
        "--packages",
        dest="unique",
        action="store_const",
        const=api.ImportKey.PACKAGE,
        default=False,
        help="If true, isort will only identify the unique top level modules imported.",
    )
    uniqueness.add_argument(
        "--modules",
        dest="unique",
        action="store_const",
        const=api.ImportKey.MODULE,
        default=False,
        help="If true, isort will only identify the unique modules imported.",
    )
    uniqueness.add_argument(
        "--attributes",
        dest="unique",
        action="store_const",
        const=api.ImportKey.ATTRIBUTE,
        default=False,
        help="If true, isort will only identify the unique attributes imported.",
    )

    arguments = parser.parse_args(argv)

    file_names = arguments.files
    if file_names == ["-"]:
        identified_imports = api.find_imports_in_stream(
            sys.stdin if stdin is None else stdin,
            unique=arguments.unique,
            top_only=arguments.top_only,
            follow_links=arguments.follow_links,
        )
    else:
        identified_imports = api.find_imports_in_paths(
            file_names,
            unique=arguments.unique,
            top_only=arguments.top_only,
            follow_links=arguments.follow_links,
        )

    for identified_import in identified_imports:
        if arguments.unique == api.ImportKey.PACKAGE:
            print(identified_import.module.split(".")[0])
        elif arguments.unique == api.ImportKey.MODULE:
            print(identified_import.module)
        elif arguments.unique == api.ImportKey.ATTRIBUTE:
            print(f"{identified_import.module}.{identified_import.attribute}")
        else:
            print(str(identified_import))

def main(argv: Optional[Sequence[str]] = None, stdin: Optional[TextIOWrapper] = None) -> None:
    arguments = parse_args(argv)
    if arguments.get("show_version"):
        print(ASCII_ART)
        return

    show_config: bool = arguments.pop("show_config", False)
    show_files: bool = arguments.pop("show_files", False)
    if show_config and show_files:
        sys.exit("Error: either specify show-config or show-files not both.")

    if "settings_path" in arguments:
        if os.path.isfile(arguments["settings_path"]):
            arguments["settings_file"] = os.path.abspath(arguments["settings_path"])
            arguments["settings_path"] = os.path.dirname(arguments["settings_file"])
        else:
            arguments["settings_path"] = os.path.abspath(arguments["settings_path"])

    if "virtual_env" in arguments:
        venv = arguments["virtual_env"]
        arguments["virtual_env"] = os.path.abspath(venv)
        if not os.path.isdir(arguments["virtual_env"]):
            warn(f"virtual_env dir does not exist: {arguments['virtual_env']}")

    file_names = arguments.pop("files", [])
    if not file_names and not show_config:
        print(QUICK_GUIDE)
        if arguments:
            sys.exit("Error: arguments passed in without any paths or content.")
        return
    if "settings_path" not in arguments:
        arguments["settings_path"] = (
            arguments.get("filename", None) or os.getcwd()
            if file_names == ["-"]
            else os.path.abspath(file_names[0] if file_names else ".")
        )
        if not os.path.isdir(arguments["settings_path"]):
            arguments["settings_path"] = os.path.dirname(arguments["settings_path"])

    config_dict = arguments.copy()
    ask_to_apply = config_dict.pop("ask_to_apply", False)
    jobs = config_dict.pop("jobs", None)
    check = config_dict.pop("check", False)
    show_diff = config_dict.pop("show_diff", False)
    write_to_stdout = config_dict.pop("write_to_stdout", False)
    deprecated_flags = config_dict.pop("deprecated_flags", False)
    remapped_deprecated_args = config_dict.pop("remapped_deprecated_args", False)
    stream_filename = config_dict.pop("filename", None)
    ext_format = config_dict.pop("ext_format", None)
    allow_root = config_dict.pop("allow_root", None)
    resolve_all_configs = config_dict.pop("resolve_all_configs", False)
    wrong_sorted_files = False
    all_attempt_broken = False
    no_valid_encodings = False

    config_trie: Optional[Trie] = None
    if resolve_all_configs:
        config_trie = find_all_configs(config_dict.pop("config_root", "."))

    if "src_paths" in config_dict:
        config_dict["src_paths"] = {
            Path(src_path).resolve() for src_path in config_dict.get("src_paths", ())
        }

    config = Config(**config_dict)
    if show_config:
        print(json.dumps(config.__dict__, indent=4, separators=(",", ": "), default=_preconvert))
        return
    if file_names == ["-"]:
        file_path = Path(stream_filename) if stream_filename else None
        if show_files:
            sys.exit("Error: can't show files for streaming input.")

        input_stream = sys.stdin if stdin is None else stdin
        if check:
            incorrectly_sorted = not api.check_stream(
                input_stream=input_stream,
                config=config,
                show_diff=show_diff,
                file_path=file_path,
                extension=ext_format,
            )

            wrong_sorted_files = incorrectly_sorted
        else:
            try:
                api.sort_stream(
                    input_stream=input_stream,
                    output_stream=sys.stdout,
                    config=config,
                    show_diff=show_diff,
                    file_path=file_path,
                    extension=ext_format,
                    raise_on_skip=False,
                )
            except FileSkipped:
                sys.stdout.write(input_stream.read())
    elif "/" in file_names and not allow_root:
        printer = create_terminal_printer(
            color=config.color_output, error=config.format_error, success=config.format_success
        )
        printer.error("it is dangerous to operate recursively on '/'")
        printer.error("use --allow-root to override this failsafe")
        sys.exit(1)
    else:
        if stream_filename:
            printer = create_terminal_printer(
                color=config.color_output, error=config.format_error, success=config.format_success
            )
            printer.error("Filename override is intended only for stream (-) sorting.")
            sys.exit(1)
        skipped: List[str] = []
        broken: List[str] = []

        if config.filter_files:
            filtered_files = []
            for file_name in file_names:
                if config.is_skipped(Path(file_name)):
                    skipped.append(file_name)
                else:
                    filtered_files.append(file_name)
            file_names = filtered_files

        file_names = files.find(file_names, config, skipped, broken)
        if show_files:
            for file_name in file_names:
                print(file_name)
            return
        num_skipped = 0
        num_broken = 0
        num_invalid_encoding = 0
        if config.verbose:
            print(ASCII_ART)

        if jobs:
            import multiprocessing

            executor = multiprocessing.Pool(jobs if jobs > 0 else multiprocessing.cpu_count())
            attempt_iterator = executor.imap(
                functools.partial(
                    sort_imports,
                    config=config,
                    check=check,
                    ask_to_apply=ask_to_apply,
                    write_to_stdout=write_to_stdout,
                    extension=ext_format,
                    config_trie=config_trie,
                ),
                file_names,
            )
        else:
            # https://github.com/python/typeshed/pull/2814
            attempt_iterator = (
                sort_imports(  # type: ignore
                    file_name,
                    config=config,
                    check=check,
                    ask_to_apply=ask_to_apply,
                    show_diff=show_diff,
                    write_to_stdout=write_to_stdout,
                    extension=ext_format,
                    config_trie=config_trie,
                )
                for file_name in file_names
            )

        # If any files passed in are missing considered as error, should be removed
        is_no_attempt = True
        any_encoding_valid = False
        for sort_attempt in attempt_iterator:
            if not sort_attempt:
                continue  # pragma: no cover - shouldn't happen, satisfies type constraint
            incorrectly_sorted = sort_attempt.incorrectly_sorted
            if arguments.get("check", False) and incorrectly_sorted:
                wrong_sorted_files = True
            if sort_attempt.skipped:
                num_skipped += (
                    1  # pragma: no cover - shouldn't happen, due to skip in iter_source_code
                )

            if not sort_attempt.supported_encoding:
                num_invalid_encoding += 1
            else:
                any_encoding_valid = True

            is_no_attempt = False

        num_skipped += len(skipped)
        if num_skipped and not config.quiet:
            if config.verbose:
                for was_skipped in skipped:
                    print(
                        f"{was_skipped} was skipped as it's listed in 'skip' setting, "
                        "matches a glob in 'skip_glob' setting, or is in a .gitignore file with "
                        "--skip-gitignore enabled."
                    )
            print(f"Skipped {num_skipped} files")

        num_broken += len(broken)
        if num_broken and not config.quiet:
            if config.verbose:
                for was_broken in broken:
                    warn(f"{was_broken} was broken path, make sure it exists correctly")
            print(f"Broken {num_broken} paths")

        if num_broken > 0 and is_no_attempt:
            all_attempt_broken = True
        if num_invalid_encoding > 0 and not any_encoding_valid:
            no_valid_encodings = True

    if not config.quiet and (remapped_deprecated_args or deprecated_flags):
        if remapped_deprecated_args:
            warn(
                "W0502: The following deprecated single dash CLI flags were used and translated: "
                f"{', '.join(remapped_deprecated_args)}!"
            )
        if deprecated_flags:
            warn(
                "W0501: The following deprecated CLI flags were used and ignored: "
                f"{', '.join(deprecated_flags)}!"
            )
        warn(
            "W0500: Please see the 5.0.0 Upgrade guide: "
            "https://pycqa.github.io/isort/docs/upgrade_guides/5.0.0.html"
        )

    if wrong_sorted_files:
        sys.exit(1)

    if all_attempt_broken:
        sys.exit(1)

    if no_valid_encodings:
        printer = create_terminal_printer(
            color=config.color_output, error=config.format_error, success=config.format_success
        )
        printer.error("No valid encodings.")
        sys.exit(1)

if __name__ == "__main__":
    main()


import requests
from bs4 import BeautifulSoup
import smtplib
import email.message

Req = "https://store.playstation.com/pt-br/product/UP0082-PPSA10664_00-FF16SIEA00000002"

#Substituir o "browserA' pelo seu Browser agent > https://www.whatismybrowser.com/detect/what-is-my-user-agent/
headers = {'User-Agent': "browserA"}

store = requests.get(Req, headers=headers)

soup = BeautifulSoup(store.content, 'html.parser')

ff = soup.find('h1', class_ = 'psw-m-b-5').get_text()
valor = soup.find('span', class_= 'psw-l-line-left psw-l-line-wrap').get_text()

nvalor = valor[2:6]
nvalor = nvalor.replace(',','')
nvalor = float(nvalor)

def gomail():
    email_content = """
    Final Fantasy XVI acaba de entrar no valor desejado, aproveite! >>>
    https://store.playstation.com/pt-br/product/UP0082-PPSA10664_00-FF16SIEA00000002
    """
    cont = email.message.Message()
    cont['Subject'] = 'FFXVI BARATINHO!'

    # Substitua o 'email' pelo seu email
    cont['From'] = 'email'

    # Substitua o 'email' pelo seu email
    cont['To'] = 'email'

    # Substitua 'pw' pela senha do seu email
    senha = 'pw'
    cont.add_header('Content-Type', 'text/html')
    cont.set_payload(email_content)

    # Substitua o "outlook.com" pelo dominio do seu email
    envio = smtplib.SMTP('smtp.outlook.com: 587')

    envio.ehlo()
    envio.starttls()
    envio.login(cont['From'], senha)
    envio.sendmail(cont['From'], [cont['To']], cont.as_string())
    envio.quit()

#200 reais é o valor máximo que eu pagaria por esse novo final fantasy, mas você pode substituir o "200" pelo valor que desejar :)
if (nvalor < 200):
    gomail()


from pygame import mixer   # for audio playing
from tkinter import *      # for gui
import os
from mutagen.mp3 import MP3    # extracting metadata from file
import tkinter.messagebox      # for messages showing error for example
from tkinter import filedialog
from tkinter import ttk
from ttkthemes import themed_tk as tk
import time
import threading

# create a window for the mp3 player
root = tk.ThemedTk()
root.get_themes()
root.set_theme("keramik")

status_bar = ttk.Label(root, text="Welcome to Acoustic!", relief=SUNKEN, anchor=W, font='Arial 10 bold')
status_bar.pack(side=BOTTOM, fill=X)

# Create the menu bar
menu_bar = Menu(root)
subMenu = Menu(menu_bar, tearoff=0)
root.config(menu=menu_bar)
root.title("Acoustic")                           # change the title displayed on top of the window
root.iconbitmap(r'images/acoustic_logo.ico')     # change the logo

mixer.init()                                     # initiate the mixer module

# Root Window contains the status bar, left frame and right frame
# Left frame contains the list box
# Right frame contains the top, middle and bottom frames

left_frame = ttk.Frame(root)
left_frame.pack(side=LEFT, padx=30)

right_frame = ttk.Frame(root)
right_frame.pack()

top_frame = ttk.Frame(right_frame)
top_frame.pack()

length_label = ttk.Label(top_frame, text='Total Length: --:--', font='Arial 10 bold')
length_label.pack(pady=10)

current_duration_label = ttk.Label(top_frame, text='Current Duration: --:--', font='Arial 10 bold')
current_duration_label.pack()

# Playlist contains the full path + filename
# Playlist box contains just the filename
# Full path + filename is required to play music inside play_music function
playlist = []

# function to choose file from directory and adding functionality to the 'open' cascade
def browse_file():
    global song_path
    song_path = filedialog.askopenfilename()
    add_to_playlist(song_path)

def add_to_playlist(song_name):
    song_name = os.path.basename(song_name)
    index = 0
    playlist_box.insert(index, song_name)
    playlist.insert(index, song_path)
    index += 1

def about_us():
    tkinter.messagebox.showinfo('About Acoustic', 'This is a music player build using tkinter on Python')

def show_details(play_song):
    file_data = os.path.splitext(play_song)

    if file_data[1] == '.mp3':
        audio = MP3(play_song)
        total_length = audio.info.length
    else:
        a = mixer.Sound(play_song)
        total_length = a.get_length()

    # div - total_length/60, mod - total_length%60
    mins, secs = divmod(total_length, 60)
    mins = round(mins)
    secs = round(secs)
    # proper format to display the length
    time_format = '{:02d}:{:02d}'.format(mins, secs)
    length_label['text'] = "Total Length: " + ' - ' + time_format

    # Threading is necessary because the while loop in start_count will stop the other parts of the program until it is finished
    t1 = threading.Thread(target=start_count, args=(total_length,))
    t1.start()

def start_count(t):
    global paused
    # mixer.music.get_busy() stops the duration count when we press the stop button
    # continue - ignores all of the statements below it and we check if the music is paused or not
    current_time = 0
    while current_time <= t and mixer.music.get_busy():
        if paused:
            continue
        else:
            mins, secs = divmod(current_time, 60)
            mins = round(mins)
            secs = round(secs)
            time_format = '{:02d}:{:02d}'.format(mins, secs)
            current_duration_label['text'] = "Current Duration: " + ' - ' + time_format
            time.sleep(1)
            current_time += 1

def play_music(event):
    global paused
    if paused:
        mixer.music.unpause()
        status_bar['text'] = "Music resumed."
        paused = FALSE
    else:
        try:
            # when switching the song in the playlist we need to stop the song that is already playing because
            # if it is not stopped another thread will be started and the duration label will not display
            # the time correctly
            stop_music()
            time.sleep(1)
            selected_song = playlist_box.curselection()
            selected_song = int(selected_song[0])
            play_song = playlist[selected_song]
            mixer.music.load(play_song)
            mixer.music.play()
            status_bar['text'] = "Playing music " + ' ' + os.path.basename(play_song)
            show_details(play_song)
        except:
            tkinter.messagebox.showerror("File not found", "Acoustic could not find the file, please check again.")

def stop_music():
    mixer.music.stop()
    status_bar['text'] = "Music stopped."

paused = FALSE

# function that pauses the music
def pause_music(event):
    global paused
    paused = TRUE
    mixer.music.pause()
    status_bar['text'] = "Music paused."

def rewind_music(event):
    play_music(event)
    status_bar['text'] = "Music rewound."

muted = FALSE

# function for the mute and unmute functionality
def mute_music(event):
    global muted
    if muted:  # Unmute the music
        mixer.music.set_volume(0.5)
        volume_btn.configure(image=volume_photo)
        scale_vol.set(50)
        muted = FALSE
    else:  # Mute the music
        mixer.music.set_volume(0)
        volume_btn.configure(image=mute_photo)
        scale_vol.set(0)
        muted = TRUE

# set_volume function of mixer takes value only from 0 to 1 exp: 0.1, 0.25
def set_vol(val):
    volume = float(val) / 100
    mixer.music.set_volume(volume)

def del_song():
    selected_song = playlist_box.curselection()
    selected_song = int(selected_song[0])
    playlist_box.delete(selected_song)
    playlist.pop(selected_song)

# center frame for play,stop,pause buttons and status bar
center_frame = ttk.Frame(right_frame)
center_frame.pack(pady=30, padx=30)

# Create the sub-menu
menu_bar.add_cascade(label="File", menu=subMenu)
subMenu.add_command(label="Open", command=browse_file)
subMenu.add_command(label="Exit", command=root.destroy)

subMenu = Menu(menu_bar, tearoff=0)
menu_bar.add_cascade(label="Help", menu=subMenu)
subMenu.add_command(label="About us", command=about_us)

playlist_box = Listbox(left_frame)
playlist_box.pack()

add_photo = PhotoImage(file='images/add_button.png')
add_btn = ttk.Button(left_frame, image=add_photo, command=browse_file)
add_btn.pack(side=LEFT)

del_photo = PhotoImage(file='images/remove_button.png')
del_btn = ttk.Button(left_frame, image=del_photo, command=del_song)
del_btn.pack(side=RIGHT)

play_photo = PhotoImage(file='images/play_button.png')          # specify what is the image to be inserted
play_btn = ttk.Button(center_frame, image=play_photo)               # convert the image into a button
play_btn.bind("<Button-1>", play_music)
play_btn.grid(row=0, column=0, padx=10)

stop_photo = PhotoImage(file='images/stop_button.png')          # specify what is the image to be inserted
stop_btn = ttk.Button(center_frame, image=stop_photo, command=stop_music)               # convert the image into a button
stop_btn.grid(row=0, column=1, padx=10)

pause_photo = PhotoImage(file='images/pause_button.png')
pause_btn = ttk.Button(center_frame, image=pause_photo)
pause_btn.bind("<Button-1>", pause_music)
pause_btn.grid(row=0, column=2, padx=10)

# bottom frame for mute,rewind,scale of volume
bottom_frame = ttk.Frame(right_frame)
bottom_frame.pack()

rewind_photo = PhotoImage(file='images/rewind_button.png')
rewind_btn = ttk.Button(bottom_frame, image=rewind_photo)
rewind_btn.bind("<Button-1>", rewind_music)
rewind_btn.grid(row=0, column=0)

mute_photo = PhotoImage(file='images/mute_btn.png')
volume_photo = PhotoImage(file='images/sound_btn.png')
volume_btn = ttk.Button(bottom_frame, image=volume_photo)
volume_btn.bind("<Button-1>", mute_music)
volume_btn.grid(row=0, column=1, padx=10, pady=10)

# adding a scale for the sound level
scale_vol = ttk.Scale(bottom_frame, from_=0, to=100, orient=HORIZONTAL, command=set_vol)
scale_vol.set(50)   # implement the default value of scale when music player starts
mixer.music.set_volume(0.5)
scale_vol.grid(row=0, column=2, pady=15, padx=30)

def on_close():
    stop_music()
    root.destroy()

# makes sure that when you exit the program while
# it is playing music it doesnt display an error relating the thread function
root.protocol("WM_DELETE_WINDOW", on_close)
root.mainloop()


try:
    import importlib.resources as pkg_resources
except ImportError:
    # Try backported to PY<37 `importlib_resources`.
    import importlib_resources as pkg_resources

import pandas as pd

from worldcereal import resources

def load_refid_lut():
    with pkg_resources.open_text(resources, 'CIB_RefIdLUT.csv') as LUTfile:
        LUT = pd.read_csv(LUTfile, delimiter=";")

    return LUT

def load_refidweights():

    LUT = load_refid_lut()[['CIB', 'LC', 'CT', 'IRR']]

    LUT = LUT[LUT.isnull().sum(axis=1) == 0]
    LUT['CIB'] = ['_'.join(x.split('_')[:3]) for x in
                  LUT['CIB'].values]
    LUT = LUT.drop_duplicates().set_index('CIB')

    return LUT.to_dict(orient='index')

def get_refid_weight(ref_id, label, refidweights=None):
    '''
    Function to get the weight to be put on
    a particular ref_id.
    '''

    refid_weights = refidweights or load_refidweights()
    weight = refid_weights.get(ref_id, None)
    if weight is not None:
        weight = weight[label]
    else:
        weight = 90

    return weight


import numpy as np
from scipy.optimize import root_scalar
from scipy.optimize import fsolve

class sieplasma(object):
    def __init__(self, theta_E_g, eta, zl, c, Dl, Ds, Dls, psi0_plasma_num, theta_0_num, B, C, delta_rs, deltab_10, deltab_20):

        self.theta_E_g = theta_E_g
        self.eta = eta
        self.psi0_plasma_num = psi0_plasma_num
        self.theta_0_num = theta_0_num
        self.B = B
        self.C = C
        self.delta_rs = delta_rs
        self.deltab_10 = deltab_10
        self.deltab_20 = deltab_20

        def f(r):
            tmp_f = r - theta_E_g + C/r * (r/B/theta_0_num)**C * psi0_plasma_num * np.exp(-(r/B/theta_0_num)**C)
            return tmp_f

        zero = root_scalar(f, bracket=[theta_E_g*.1, theta_E_g*1.9], method='bisect')
        self.theta_E = zero.root
        self.r = zero.root
        r = self.r

        def g(phi_k):
            tmp_g =  theta_E_g*eta*np.sin(2.*phi_k)/np.sqrt(1.-eta*np.cos(2.*phi_k)) - deltab_10*np.sin(phi_k) + deltab_20*np.cos(phi_k)
            return tmp_g

        phi_arr = np.array([np.pi/4, 5/4*np.pi])
        zeros_g = fsolve(g, phi_arr)
        self.zeros_phi = zeros_g
        zeros_phi = self.zeros_phi

        tmp_psi = theta_E_g*r*np.sqrt(1.-eta*np.cos(2.*zeros_phi)) + \
                  psi0_plasma_num*np.exp(-(r/B/theta_0_num)**C)
        self.psi = tmp_psi

        tmp_dpsi = theta_E_g*r*(np.sqrt( 1. - eta*np.cos(2*zeros_phi)) - 1)
        self.dpsi = tmp_dpsi

        tmp_psi0 = theta_E_g*r + psi0_plasma_num*np.exp(-(r/B/theta_0_num)**C)
        self.psi0 = tmp_psi0

        tmp_psi_plasma = psi0_plasma_num*np.exp(-(r/B/theta_0_num)**C)
        self.psi_plasma = tmp_psi_plasma

        tmp_ddpsi_dr = theta_E_g*(np.sqrt( 1. - eta*np.cos(2*zeros_phi)) - 1)
        self.ddpsi_dr = tmp_ddpsi_dr

        tmp_ddpsi_dphi = theta_E_g*r*eta*np.sin(2.*zeros_phi)/np.sqrt(1.-eta*np.cos(2.*zeros_phi))
        self.ddpsi_dphi = tmp_ddpsi_dphi

        tmp_d2dpsi_dphi2 = theta_E_g*r*eta*( 2*np.cos(2.*zeros_phi)/np.sqrt(1.-eta*np.cos(2.*zeros_phi)) - (1.-eta*np.cos(2.*zeros_phi))**(-3/2)*eta*np.sin(2*zeros_phi)**2)
        self.d2dpsi_dphi2 = tmp_d2dpsi_dphi2

        tmp_d2psi0 = self.psi_plasma * ( - C*(C-1)/r**2*(r/B/theta_0_num)**C + (C/r*(r/B/theta_0_num)**C)**2 )
        self.d2psi0_dr2 = tmp_d2psi0

        delta_r = 1/(1 - self.d2psi0_dr2 )*(self.ddpsi_dr + deltab_10*np.cos(zeros_phi) + deltab_20*np.sin(zeros_phi) )

        self.delta_r = delta_r

        r_ = r + delta_r

        psi = theta_E_g*r_*np.sqrt(1.-eta*np.cos(2.*zeros_phi)) + psi0_plasma_num*np.exp(-(r_/B/theta_0_num)**C)
        psi_plasma = psi0_plasma_num*np.exp(-(r_/B/theta_0_num)**C)
        d2psi_dr2 = psi_plasma * ( - C*(C-1)/r_**2*(r_/B/theta_0_num)**C + (C/r_*(r_/B/theta_0_num)**C)**2 )
        dpsi_dr = theta_E_g*np.sqrt(1.-eta*np.cos(2.*zeros_phi)) - C/r_*(r_/B/theta_0_num)**C*psi0_plasma_num*np.exp(-(r_/B/theta_0_num)**C)
        d2psi_dphi2 = theta_E_g*r_*eta*( 2*np.cos(2.*zeros_phi)/np.sqrt(1.-eta*np.cos(2.*zeros_phi)) - (1.-eta*np.cos(2.*zeros_phi))**(-3/2)*eta*np.sin(2*zeros_phi)**2)
        dpsi_dphi = theta_E_g*r_*eta*np.sin(2.*zeros_phi)/np.sqrt(1.-eta*np.cos(2.*zeros_phi))
        d2psi_dphidr = theta_E_g*eta*np.sin(2.*zeros_phi)/np.sqrt(1.-eta*np.cos(2.*zeros_phi))

        mu = r_*( (1 - d2psi_dr2)*(r_ - dpsi_dr - 1/r_*d2psi_dphi2) - 1/r_*(1/r_*dpsi_dphi - d2psi_dphidr )**2  )**(-1)

        R = np.abs(mu[0]/mu[1])
        self.R = R

        t = (1 + zl)/c*Dl*Ds/Dls*(1/2* ( (r_*np.cos(zeros_phi) - deltab_10)**2 + (r_*np.sin(zeros_phi) - deltab_20)**2  ) - psi )

        self.t = t/24/60/60*0.000004848136811095**2

        dt = np.abs(t[0]-t[1])/24/60/60*0.000004848136811095**2 #convert seconds to days and arcsec^2 to rad
        self.dt = dt


#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2021/8/6 上午10:04
# @Author  : PeiP Liu
# @FileName: BertModel.py
# @Software: PyCharm

import torch
import torch.nn as nn
from torch.nn import LayerNorm as BertLayerNorm
import sys
sys.path.append("..")
import torch.nn.functional as F

class BERT_SC(nn.Module):
    def __init__(self, bert_model, idx2label, hidden_size=768, device='cpu'):
        super(BERT_SC, self).__init__()
        self.bert_model = bert_model
        self.hidden_size = hidden_size
        self.num_label = len(idx2label)
        self.device = device

        self.dropout = nn.Dropout(0.5)
        self.bert_sigmod = nn.Sigmoid()
        self.softmax = nn.Softmax(dim=-1)

        self.hid2label = nn.Linear(self.hidden_size, self.num_label)
        # init the weight and bias of feature-emission layer
        nn.init.xavier_uniform_(self.hid2label.weight)
        nn.init.constant_(self.hid2label.bias, 0.0)
        self.apply(self.init_bert_weight)

    def init_bert_weight(self, module):
        # cf https://github.com/Louis-udm/NER-BERT-CRF/blob/master/NER_BERT_CRF.py
        # rf https://www.cnblogs.com/BlueBlueSea/p/12875517.html
        if isinstance(module, (nn.Linear, nn.Embedding)):
            module.weight.data.normal_(mean=0.0, std=0.02)
        elif isinstance(module, BertLayerNorm):
            module.bias.data.zero_()
            module.weight.data.fill_(1.0)
        if isinstance(module, nn.Linear) and module.bias is not None:
            module.bias.data.zero_()

    def get_bert_features(self, input_ids, seg_ids, atten_mask):
        # rf https://huggingface.co/transformers/model_doc/bert.html#bertmodel
        outputs = self.bert_model(input_ids, token_type_ids=seg_ids,
                                  attention_mask=atten_mask, output_hidden_states=True, output_attentions=True)
        # last_hidden_states = outputs[0]
        last_hidden_states = outputs.last_hidden_state # (batch_size, seq_length, hidden_size)

        # pooler_outputs = outputs[1]
        # the feature of [CLS], and it represents the feature of whole sentence
        # We can better average or pool the sequence of hidden-states for the whole sequence.
        pooler_outputs = outputs.pooler_output  # (batch_size, hidden_size)

        return pooler_outputs, last_hidden_states  # the feature of [CLS] and all the tokens

    def tfidf_seq(self, bert_seq_features, tfidf_token_masks):
        batch_size, seq_len, feature_dim = bert_seq_features.shape
        seq_reps = torch.zeros((batch_size, feature_dim), dtype=torch.float32).to(self.device)
        for i_seq in range(batch_size):
            i_seq_feature = bert_seq_features[i_seq]
            i_seq_mask = tfidf_token_masks[i_seq]

            assert len(i_seq_feature) == len(i_seq_mask)

            extended_i_seq_mask = i_seq_mask.unsqueeze(1)  # (seq_len, 1)

            masked_seq_feature = i_seq_feature * extended_i_seq_mask  # (seq_len, feature_dim)

            i_seq_rep = masked_seq_feature.sum(0)  # 对所有tf-idf的token-embedding进行了sum-pooling

            seq_reps[i_seq] = i_seq_rep

        return seq_reps

    def forward(self, input_ids, input_mask, seg_ids, tfidf_token_masks, sents_labels, mode):
        bert_cls_features, bert_seq_features = self.get_bert_features(input_ids, seg_ids, input_mask)

        if tfidf_token_masks.count_nonzero().detach().item() == 0:  # 非0数据为0，即没有非0数据，即都是0。此时，我们使用CLS来表示序列信息
            seq_rep = self.bert_sigmod(self.dropout(bert_cls_features))
        else:
            seq_rep = self.tfidf_seq(bert_seq_features, tfidf_token_masks)  # 对于有tf-idf选择的词汇，我们使用tf-idf来表示序列特征
            seq_rep = self.bert_sigmod(self.dropout(seq_rep))

        class_result = self.softmax(self.hid2label(seq_rep))

        if mode == 'train':
            try:
                object_score = F.cross_entropy(class_result, sents_labels, ignore_index=2)
                return object_score
            except:
                print('There is something wrong with the prediction result!')
        else:
            return torch.argmax(class_result, dim=-1).detach().cpu().tolist()


from twisted.trial.unittest import TestCase
from twisted.python.filepath import FilePath

from epsilon.extime import Time

from nevow import loaders, rend
from nevow.testutil import renderPage, renderLivePage

from axiom.store import Store
from axiom.dependency import installOn

from xmantissa.people import Person, EmailAddress

from xquotient.exmess import Message, MessageDetail, PartDisplayer
from xquotient.inbox import Inbox, InboxScreen
from xquotient import compose
from xquotient.test.util import MIMEReceiverMixin, PartMaker, ThemedFragmentWrapper
from xquotient.qpeople import MessageList, MessageLister

from xquotient.test.util import DummyMessageImplementation
from xquotient.test.test_inbox import testMessageFactory

def makeMessage(receiver, parts, impl):
    """
    Create a new L{exmess.Message}, either by parsing C{parts} or by wrapping
    one around C{impl}.
    """
    if impl is None:
        return receiver.feedStringNow(parts)
    else:
        return testMessageFactory(store=impl.store,
                                  receivedWhen=Time(),
                                  sentWhen=Time(),
                                  spam=False,
                                  subject=u'',
                                  impl=impl)

class RenderingTestCase(TestCase, MIMEReceiverMixin):
    aBunchOfRelatedParts = PartMaker(
        'multipart/related', 'related',
        *(list(PartMaker('text/html', '
html-' + str(i) + '
')
               for i in xrange(100)) +
          list(PartMaker('image/gif', '')
               for i in xrange(100)))).make()

    def setUp(self):
        """
        Make a copy of the very minimal database for a single test method to
        mangle.
        """
        receiver = self.setUpMailStuff()
        makeMessage(receiver, self.aBunchOfRelatedParts, None)

    def test_messageRendering(self):
        """
        Test rendering of message detail for an extremely complex message.
        """
        msg = self.substore.findUnique(Message)
        msg.classifyClean()
        return renderLivePage(
                   ThemedFragmentWrapper(
                       MessageDetail(msg)))

    def test_inboxRendering(self):
        """
        Test rendering of the inbox with a handful of extremely complex
        messages in it.
        """
        def deliverMessages():
            for i in xrange(5):
                makeMessage(
                    self.createMIMEReceiver(), self.aBunchOfRelatedParts, None)
        self.substore.transact(deliverMessages)

        inbox = self.substore.findUnique(Inbox)

        composer = compose.Composer(store=self.substore)
        installOn(composer, self.substore)

        return renderLivePage(
                   ThemedFragmentWrapper(
                       InboxScreen(inbox)))

    def test_inboxComposeFragmentRendering(self):
        """
        Test rendering of the L{xquotient.compose.ComposeFragment} returned
        from L{xquotient.inbox.InboxScreen.getComposer}
        """
        installOn(compose.Composer(store=self.substore), self.substore)

        inbox = self.substore.findUnique(Inbox)
        inboxScreen = InboxScreen(inbox)

        composeFrag = inboxScreen.getComposer()

        return renderLivePage(
            ThemedFragmentWrapper(composeFrag))

    def test_peopleMessageListRendering(self):
        mlister = MessageLister(store=self.substore)
        installOn(mlister, self.substore)

        p = Person(store=self.substore, name=u'Bob')

        EmailAddress(store=self.substore, person=p, address=u'bob@internet')

        for i in xrange(5):
            testMessageFactory(
                store=self.substore, subject=unicode(str(i)),
                receivedWhen=Time(), spam=False, sender=u'bob@internet')

        self.assertEqual(len(list(mlister.mostRecentMessages(p))), 5)
        return renderPage(
            rend.Page(docFactory=loaders.stan(MessageList(mlister, p))))

class MockPart(object):
    """
    A mock L{xquotient.mimestorage.Part} which implements enough functionality
    to satisfy L{xquotient.exmess.PartDisplayer}
    """
    def __init__(self, unicodeBody, contentType='text/plain'):
        """
        @param unicodeBody: the body of the part
        @type unicodeBody: C{unicode}

        @param contentType: the content type of the part.  defaults to
        text/plain
        @type contentType: C{str}
        """
        self.unicodeBody = unicodeBody
        self.contentType = contentType

    def getUnicodeBody(self):
        return self.unicodeBody

    def getBody(self, decode=False):
        return str(self.unicodeBody)

    def getContentType(self):
        return self.contentType

class PartDisplayerTestCase(TestCase):
    """
    Tests for L{xquotient.exmess.PartDisplayer}
    """
    def setUp(self):
        self.partDisplayer = PartDisplayer(None)

    def test_scrubbingInvalidDocument(self):
        """
        Pass a completely malformed document to L{PartDisplayer.scrubbedHTML}
        and assert that it returns C{None} instead of raising an exception.
        """
        self.assertIdentical(None, self.partDisplayer.scrubbedHTML(''))

    def test_scrubbingSimpleDocument(self):
        """
        Pass a trivial document to L{PartDisplayer.scrubbedHMTL} and make sure
        it comes out the other side in-tact.
        """
        self.assertEquals('

', self.partDisplayer.scrubbedHTML('

'))

    def test_renderablePartReplacesInvalidCharsinHTML(self):
        """
        Test that L{xquotient.exmess.PartDisplayer.renderablePart} replaces
        XML-illegal characters in the body of the text/html part it is passed
        """
        part = MockPart(u'
\x00 hi \x01
', 'text/html')
        tag = self.partDisplayer.renderablePart(part)
        self.assertEquals(tag.content, '
0x0 hi 0x1
')

    def test_renderablePartDoesntReplaceInvalidCharsElsewhere(self):
        """
        Test that L{xquotient.exmess.PartDisplayer.renderablePart} doesn't
        replace XML-illegal characters if the content-type of the part isn't
        text/html
        """
        part = MockPart(u'\x00', 'text/plain')
        tag = self.partDisplayer.renderablePart(part)
        self.assertEquals(tag.content, '\x00')