import master
import os
import openpyxl as xl
from pathlib import Path

step = "nine"
status = ""

if Path(master.masterpath+"costcenter.xlsx").exists() and Path(master.temppath+"exception_department.xlsx").exists() and Path(master.temppath+"delete.xlsx").exists():
    print("Step "+step)
    wb1 = xl.load_workbook(master.masterfile+"costcenter.xlsx")
    sh1 = wb1["Sheet1"]
    maxmasterrow = sh1.max_row

    wb2 = xl.load_workbook(master.tempfile+"exception_department.xlsx")
    sh2 = wb2["Sheet"]
    maxrow = sh2.max_row

    wb3 = xl.load_workbook(master.tempfile+"delete.xlsx")
    sh3 = wb3.create_sheet("exception_delete")
    deleted_data_row = 2

    # print(maxrow)

    cort_compcode_data_cell = sh2.cell(1, 1)
    cort_emp_data_cell = sh2.cell(1, 2)
    cort_date_data_cell = sh2.cell(1, 3)
    cort_comp_data_cell = sh2.cell(1, 20)
    cort_wrkhrs_data_cell = sh2.cell(1, 4)
    cort_not_data_cell = sh2.cell(1, 5)
    cort_hot_data_cell = sh2.cell(1, 6)
    cort_exot_data_cell = sh2.cell(1, 7)
    cort_wot_data_cell = sh2.cell(1, 8)
    cort_weekoff_data_cell = sh2.cell(1, 9)
    cort_siteid_data_cell = sh2.cell(1, 10)
    cort_costcode_data_cell = sh2.cell(1, 11)

    cort_compcode_data_cell.value = "cmpycode"
    cort_emp_data_cell.value = "empcode"
    cort_date_data_cell.value = "SalaryDates"
    cort_comp_data_cell.value = "Comp"
    cort_wrkhrs_data_cell.value = "Nhrs"
    cort_not_data_cell.value = "N_ OT_HRS"
    cort_hot_data_cell.value = "H_Othrs"
    cort_exot_data_cell.value = "EXTRA EXT OT"
    cort_wot_data_cell.value = "W_OT_hrs"
    cort_weekoff_data_cell.value = "Weekoff"
    cort_siteid_data_cell.value = "SiteID"
    cort_costcode_data_cell.value = "Costcode"

    del_emp_data_cell = sh3.cell(1, 1)
    del_date_data_cell = sh3.cell(1, 2)
    del_comp_data_cell = sh3.cell(1, 3)

    del_emp_data_cell.value = "empcode"
    del_date_data_cell.value = "SalaryDates"
    del_comp_data_cell.value = "Comp"

    for row in range(2,maxrow+1):
        cort_compcode_data_cell = sh2.cell(row, 1)
        cort_date_data_cell = sh2.cell(row, 3)
        cort_wrkhrs_data_cell = sh2.cell(row, 4)
        cort_not_data_cell = sh2.cell(row, 5)
        cort_hot_data_cell = sh2.cell(row, 6)
        cort_exot_data_cell = sh2.cell(row, 7)
        cort_wot_data_cell = sh2.cell(row, 8)
        cort_weekoff_data_cell = sh2.cell(row, 9)
        cort_siteid_data_cell = sh2.cell(row, 10)
        cort_costcode_data_cell = sh2.cell(row, 11)
        cort_depart_data_cell = sh2.cell(row, 19)
        cort_comp_data_cell = sh2.cell(row, 20)

        emp_data_cell = sh2.cell(row, 2)
        siteid_data_cell = sh2.cell(row, 10)
        costcenter_data_cell = sh2.cell(row,11)

        emp_data = sh2.cell(row,2).value
        department_data = sh2.cell(row,19).value
        comp_data = sh2.cell(row,20).value
        date_data = sh2.cell(row,3).value
        # print(department_data )
        # print(comp_data)

        del_emp_data_cell = sh3.cell(deleted_data_row, 1)
        del_date_data_cell = sh3.cell(deleted_data_row, 2)
        del_comp_data_cell = sh3.cell(deleted_data_row, 3)

        for masterrow in range(2,maxmasterrow+1):
            mastercomp_data = str(sh1.cell(masterrow, 1).value)
            bakery_data = str(sh1.cell(masterrow, 2).value)
            pastry_data = str(sh1.cell(masterrow, 3).value)
            bar_data = str(sh1.cell(masterrow, 4).value)
            mainstore_data = str(sh1.cell(masterrow, 5).value)
            kitchen_data = str(sh1.cell(masterrow, 6).value)

            # print(row)
            # Exception condition:
            if emp_data is not None and emp_data[:-4] != master.emp_start_code or department_data is None or comp_data == "LA BRIOCHE CPU":
            # if comp_data == "LA BRIOCHE CPU":
                # print(row)
                # print(comp_data)
                # delete the row where it's LA BRIOCHE CPU
                emp_data_cell.value=""
                cort_compcode_data_cell.value = ""
                cort_date_data_cell.value = ""
                cort_comp_data_cell.value = ""
                cort_wrkhrs_data_cell.value = ""
                cort_not_data_cell.value = ""
                cort_hot_data_cell.value = ""
                cort_exot_data_cell.value = ""
                cort_wot_data_cell.value = ""
                cort_weekoff_data_cell.value = ""
                cort_siteid_data_cell.value = ""
                cort_costcode_data_cell.value = ""
                cort_depart_data_cell.value = ""

                del_emp_data_cell.value = emp_data
                del_date_data_cell.value = date_data
                del_comp_data_cell.value = comp_data

                deleted_data_row += 1
                break
            # elif emp_data is not None and emp_data.find("Z00") != -1:
            #     # print(row)
            #     # print(emp_data + date_data)
            #
            #     emp_data_cell.value = ""
            #     cort_compcode_data_cell.value = ""
            #     cort_date_data_cell.value = ""
            #     cort_comp_data_cell.value = ""
            #     cort_wrkhrs_data_cell.value = ""
            #     cort_not_data_cell.value = ""
            #     cort_hot_data_cell.value = ""
            #     cort_exot_data_cell.value = ""
            #     cort_wot_data_cell.value = ""
            #     cort_weekoff_data_cell.value = ""
            #     cort_siteid_data_cell.value = ""
            #     cort_costcode_data_cell.value = ""
            #     cort_depart_data_cell.value = ""
            #
            #     # print(row)
            #     # print("Delete")
            #     # row = row - 1
            #     # delete the row where emp code is with Z
            #     # sh2.delete_rows(row, 1)
            #
            #
            #     break
            elif comp_data == mastercomp_data and department_data is not None and bakery_data.find(department_data) != -1:
                siteid_data_cell.value = bakery_data[-3:]
                costcenter_data_cell.value = bakery_data[-3:]
                # print( emp_data + "-----" + comp_data + "----------" + department_data + "----------------" + siteid_data_cell.value)
                break

            elif comp_data == mastercomp_data and department_data is not None and pastry_data.find(department_data) != -1:
                siteid_data_cell.value = pastry_data[-3:]
                costcenter_data_cell.value = pastry_data[-3:]
                # print( emp_data + "-----" + comp_data + "----------" + department_data + "----------------" + siteid_data_cell.value)
                break

            elif comp_data == mastercomp_data and department_data is not None and bar_data.find(department_data) != -1:
                siteid_data_cell.value = bar_data[-3:]
                costcenter_data_cell.value = bar_data[-3:]
                # print( emp_data + "-----" + comp_data + "----------" + department_data + "----------------" + siteid_data_cell.value)
                break

            elif comp_data == mastercomp_data and department_data is not None and mainstore_data.find(department_data) != -1:
                siteid_data_cell.value = mainstore_data[-3:]
                costcenter_data_cell.value = mainstore_data[-3:]
                # print( emp_data + "-----" + comp_data + "----------" + department_data + "----------------" + siteid_data_cell.value)
                break

            elif comp_data == mastercomp_data and department_data is not None and kitchen_data.find(department_data) != -1:
                siteid_data_cell.value = kitchen_data[-3:]
                costcenter_data_cell.value = kitchen_data[-3:]
                # print( emp_data + "-----" + comp_data + "----------" + department_data + "----------------" + siteid_data_cell.value)
                break

            elif comp_data == mastercomp_data and department_data is not None and department_data == "ADMIN":
                siteid_data_cell.value = "481"
                costcenter_data_cell.value = "481"
                # print( emp_data + "-----" + comp_data + "----------" + department_data + "----------------" + siteid_data_cell.value)
                break

    # wb2.save(master.finalpath+"exception.xlsx")

    wb2.save(master.temppath+"exception.xlsx")
    if not Path(master.finalpath+master.cur_month+master.cur_year).exists():
        os.mkdir(master.finalpath+master.cur_month+master.cur_year)
    wb3.save(master.finalpath+"/"+master.cur_month+master.cur_year+"/ignored.xlsx")
    # wb3.save(master.temppath+"ignored.xlsx")
    status = "Done"


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import re

from django import template

register = template.Library()

# This regex is the one for a URI scheme where the name is forced to start
# with "wom-" (see also https://en.wikipedia.org/wiki/Uniform_Resource_Identifier#Definition)
WOM_PROTOCOL_RE = re.compile("^wom-[\w\+\.\-]+:.*")

@register.filter()
def normalize_wom_protocol_url(url):
  """
  When a URL is a "wom" protocol, return a more generally "usable" url.
  """
  if WOM_PROTOCOL_RE.match(url):
      return "#"
  else:
      return url


# -*- mode: python -*-

block_cipher = None

import os
import sys
import datetime
import ntpath
import PyQt5
import serial

# Add working dir to path so we can use uPyLoader modules here
sys.path += [os.getcwd()]
from src.utility.build_info import BuildInfo

BuildInfo().save("build_info.json")

a = Analysis(['main.py'],
             pathex=[os.path.join(ntpath.dirname(PyQt5.__file__), 'Qt', 'bin')],
             binaries=[],
             datas=[],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher)
# From, To, What
a.datas += [('icons//main.png','icons//main.png','DATA'),
            ('icons//main-512.png','icons//main-512.png','DATA'),
            ('icons//floppy.png','icons//floppy.png','DATA'),
            ('icons//refresh.png','icons//refresh.png','DATA'),
            ('icons//run.png','icons//run.png','DATA'),
            ('mcu//download.py','mcu//download.py','DATA'),
            ('mcu//upload.py','mcu//upload.py','DATA'),
            (BuildInfo.pyinstaller_path,'build_info.json','DATA')]
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          name='uPyLoader',
          debug=False,
          strip=False,
          upx=False,
          console=False,
          icon='icons//main.ico' )

app = BUNDLE(exe,
             name='uPyLoader.app',
             icon='icons//main-512.icns',
             bundle_identifier=None)


T = int(input())
# 여러개의 테스트 케이스가 주어지므로, 각각을 처리합니다.
for test_case in range(1, T + 1):
    from collections import deque

    n = int(input())
    x = list(map(int, input().split()))

    queue = x

    sum = 0

    while queue:
        temp = max(queue)
        idx = queue.index(temp)
        for i in range(idx + 1):
            e = queue.pop(0)
            sum += (temp - e)

    print("#{} {}".format(test_case, sum))


import os
import discord
import random
from discord.ext import commands
from datetime import datetime, timedelta
from dotenv import load_dotenv

from public_transport import Public_transportView

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
TEST_CHANNEL_ID = int(os.getenv('TEST_CHANNEL_ID'))
bot_description = "Kein Sex vor der E"

intents = discord.Intents.all()
prefix = "!"
bot = commands.Bot(command_prefix=prefix, description=bot_description, intents=intents)

async def send_message(dm_title, dm_description, switch, color = None, message=None, channel=None, view=None):
    current_time = datetime.utcnow()
    if color == "error":
        colorpick = discord.Color.from_rgb(255, 38 ,0)
    else:
        colorpick = discord.Color.from_rgb(45, 125 ,70)
    embeded_response = discord.Embed(title=dm_title, description=dm_description, timestamp=current_time, color=colorpick)

    if switch == "server":
        if message == None:
            channel = bot.get_channel(channel)
        else:
            channel = bot.get_channel(message.channel.id)
        send_message = await channel.send(embed=embeded_response, view=view)
    elif switch == "dm":
        dmrecipient = bot.get_user(208685464876482561)
        dmrecipient.create_dm
        send_message = await dmrecipient.send(embed=embeded_response)

    return send_message

def validate_times(time_to_validate):
    try:
        datetime.strptime(time_to_validate, "%H:%M")
        return 1
    except ValueError:
        return 0

def activity_decider():
    activity_one = discord.Activity(type=discord.ActivityType.watching, name=f'your naked mum | Prefix: {prefix}')
    activity_two = discord.Activity(type=discord.ActivityType.listening, name=f'your mum moaning | Prefix: {prefix}')
    return random.choice([activity_one, activity_two])

@bot.event
async def on_ready():
    await bot.change_presence(activity=activity_decider())
    await send_message("Start", f'{bot.user} is ready!', switch="server", channel=TEST_CHANNEL_ID)
    print(f'Discord Managment Bot ready!')

@bot.command()
async def msg(ctx, *args):
    response = " ".join(args) if args else "empty :("
    await send_message(f"Message from: {ctx.author}", response, "server", channel=ctx.channel.id)

@bot.command()
async def new_pt(ctx, *args):
    if not args:
        await send_message("Time missing", f"You need to provide the time the transport vehicle departs!\n Use this format: HH:MM\nExample: **{prefix}new_pt 13:37**", "server", channel=ctx.channel.id)
        return

    if len(args) > 1:
        departure_reason = ""
        for reason in args[1:]:
            departure_reason = f'{departure_reason} {reason}'
        departure_reason = f'{departure_reason} -'
    else:
        departure_reason = "Your"

    arg = args[0]

    if not validate_times(arg):
        await send_message("Invalid time format!", f"Use this format: HH:MM\nExample: **{prefix}new_pt 13:37**", "server", channel=ctx.channel.id)
        return

    await ctx.message.delete()

    departure_time = datetime.strptime(arg, "%H:%M")
    embed_title = "New public transport"
    embed_description = "Do you want to take a shower?"
    await send_message(embed_title, embed_description, "server", channel=ctx.channel.id, view=Public_transportView(departure_time, departure_reason))

bot.run(TOKEN)


# """
# Idea by @Pokurt
# Repo: https://github.com/pokurt/Nana-Remix/blob/master/nana/utils/aiohttp_helper.py
# """

import asyncio
from typing import Dict, Optional

import ujson
from aiohttp import ClientSession, ClientTimeout

# """
# Success: status == 200
# Failure: ValueError if status != 200 or timeout
# """

class AioHttp:
    @staticmethod
    def get_session() -> ClientSession:
        return ClientSession(json_serialize=ujson.dumps)

    @staticmethod
    async def _manage_session(
        mode: str,
        link: str,
        params: Optional[Dict] = None,
        session: Optional[ClientSession] = None,
    ):
        try:
            if session and not session.closed:
                return await AioHttp._request(
                    mode=mode, session=session, link=link, params=params
                )
            async with AioHttp.get_session() as xsession:
                return await AioHttp._request(
                    mode=mode, session=xsession, link=link, params=params
                )
        except asyncio.TimeoutError:
            print("Timeout! the site didn't responded in time.")
        except Exception as e:
            print(e)

    @staticmethod
    async def _request(mode: str, session: ClientSession, **kwargs):
        wait = 5 if mode == "status" else 15
        async with session.get(
            kwargs["link"], params=kwargs["params"], timeout=ClientTimeout(total=wait)
        ) as resp:
            if mode == "status":
                return resp.status
            if mode == "redirect":
                return resp.url
            if mode == "headers":
                return resp.headers
            # Checking response status
            if resp.status != 200:
                return False
            if mode == "json":
                r = await resp.json()
            elif mode == "text":
                r = await resp.text()
            elif mode == "read":
                r = await resp.read()
            return r

    @staticmethod
    async def json(
        link: str,
        params: Optional[Dict] = None,
        session: Optional[ClientSession] = None,
    ):
        res = await AioHttp._manage_session(
            mode="json", link=link, params=params, session=session
        )
        if not res:
            raise ValueError
        return res

    @staticmethod
    async def text(
        link: str,
        params: Optional[Dict] = None,
        session: Optional[ClientSession] = None,
    ):
        res = await AioHttp._manage_session(
            mode="text", link=link, params=params, session=session
        )
        if not res:
            raise ValueError
        return res

    @staticmethod
    async def read(
        link: str,
        params: Optional[Dict] = None,
        session: Optional[ClientSession] = None,
    ):
        res = await AioHttp._manage_session(
            mode="read", link=link, params=params, session=session
        )
        if not res:
            raise ValueError
        return res

    # Just returns the status
    @staticmethod
    async def status(link: str, session: Optional[ClientSession] = None):
        return await AioHttp._manage_session(mode="status", link=link, session=session)

    # returns redirect url
    @staticmethod
    async def redirect_url(link: str, session: Optional[ClientSession] = None):
        return await AioHttp._manage_session(
            mode="redirect", link=link, session=session
        )

    # Just returns the Header
    @staticmethod
    async def headers(
        link: str, session: Optional[ClientSession] = None, raw: bool = True
    ):
        headers_ = await AioHttp._manage_session(
            mode="headers", link=link, session=session
        )
        if headers_:
            if raw:
                return headers_
            text = ""
            for key, value in headers_.items():
                text += f"🏷 {key}: {value}\n\n"
            return f"URl: {link}\n\nHEADERS:\n\n{text}"


#Report Card

name = input("Enter your name: ")
roll_no = int(input("Enter your roll number: "))
maths_marks = int(input("Enter your Maths marks out of 100 "))
english_marks = int(input("Enter your English marks out of 100 "))
science_marks = int(input("Ënter your Science Marks out of 100 :"))

total = maths_marks + english_marks + science_marks
fix_total = 300
percentage = total/fix_total * 100

if percentage >= 90:
    grade = "A"
elif percentage >= 80 and percentage < 90:
    grade = "B"
elif percentage >= 70 and percentage < 80:
    grade = "C"
elif percentage >= 60 and percentage <70:
    grade = "D"
elif percentage >= 50 and percentage <60:
    grade = "E"
elif percentage >= 40 and percentage <50:
    grade = "E+"
else:
    grade = "F"

print("*****************Report Card***********************")
print("Name: ",name, "\nMaths Marks is: ",maths_marks,"\nEnglish Marks is: ",english_marks,"\nScience Marks is: ",science_marks,"\nTotal Marks is: ",total,"\nThe percentage is: ",percentage,"\nThe grade is: ",grade)


import os

from libvirt import libvirtError
from libvirttestapi.src import sharedmod
from libvirttestapi.utils import process

required_params = ('poolname',)
optional_params = {}

def display_pool_info(conn):
    """Display current storage pool information"""
    logger.debug("current define storage pool: %s"
                 % conn.listDefinedStoragePools())
    logger.debug("current active storage pool: %s"
                 % conn.listStoragePools())

def display_physical_volume():
    """Display volume group and physical volume information"""
    ret1 = process.run("pvdisplay", shell=True, ignore_status=True)
    if ret1.exit_status == 0:
        logger.debug("pvdisplay command executes successfully")
        logger.debug(ret1.stdout)
    else:
        logger.error("fail to execute pvdisplay command")

    ret2 = process.run("vgdisplay", shell=True, ignore_status=True)
    if ret2.exit_status == 0:
        logger.debug("vgdisplay command executes successfully")
        logger.debug(ret2.stdout)
    else:
        logger.error("fail to execute pvdisplay command")

def check_build_pool(poolname):
    """Check build storage pool result, poolname will exist under
       /etc/lvm/backup/ if pool build is successful
    """
    path = "/etc/lvm/backup/%s" % poolname
    logger.debug("%s xml file path: %s" % (poolname, path))
    if os.access(path, os.R_OK):
        cmd = "grep %s %s" % (poolname, path)
        ret = process.run(cmd, shell=True, ignore_status=True)
        logger.debug(ret.stdout)
        if ret.exit_status == 0:
            return True
        else:
            return False
    else:
        logger.debug("%s file don't exist" % path)
        return False

def build_logical_pool(params):
    """Build a storage pool"""
    global logger
    logger = params['logger']
    poolname = params['poolname']
    conn = sharedmod.libvirtobj['conn']

    if check_build_pool(poolname):
        logger.debug("%s storage pool is built" % poolname)
        return 1

    display_pool_info(conn)
    display_physical_volume()

    try:
        logger.info("build %s storage pool" % poolname)
        poolobj = conn.storagePoolLookupByName(poolname)
        poolobj.build(0)
        display_pool_info(conn)
        display_physical_volume()

        if check_build_pool(poolname):
            logger.info("build %s storage pool is successful" % poolname)
        else:
            logger.error("fail to build %s storage pool" % poolname)
            return 1
    except libvirtError as e:
        logger.error("API error message: %s, error code is %s"
                     % (e.get_error_message(), e.get_error_code()))
        return 1

    return 0


"""
REM Layout classes and functions.
"""
import PySimpleGUI as sg

import REM.constants as mod_const
import REM.data_manipulation as mod_dm
from REM.client import logger, settings, user

# Modifier functions
def set_size(window, element_key, size):
    """
    Set new size for container-like elements.
    """
    options = {'width': size[0], 'height': size[1]}

    element = window[element_key]
    try:
        scrollable = element.Scrollable
    except AttributeError:
        scrollable = False

    if scrollable:
        element.Widget.canvas.configure(**options)
        element.contents_changed()
    else:
        element.Widget.pack_propagate(0)
        element.set_size(size)

    window.refresh()

# GUI Element Functions
def generate_layout(etype, attributes):
    """
    Generate a layout for different element types.
    """
    func_mapper = {'input': input_layout, 'multiline': multiline_layout, 'dropdown': combo_layout,
                   'checkbox': checkbox_layout, 'text': text_layout}
    try:
        layout_func = func_mapper[etype]
    except KeyError:
        logger.warning('unknown element type "{ETYPE}" provided'.format(ETYPE=etype))
        layout_func = func_mapper['text']

    layout = layout_func(attributes)

    return layout

def text_layout(attributes):
    # Standard element parameters
    font = attributes.get('Font', mod_const.LARGE_FONT)
    size = attributes.get('Size', None)
    bw = attributes.get('BW', 0)
    pad = attributes.get('Pad', None)
    bg_col = attributes.get('BackgroundColor', mod_const.DEFAULT_BG_COLOR)
    text_col = attributes.get('TextColor', mod_const.DISABLED_TEXT_COLOR)
    tooltip = attributes.get('Tooltip', None)
    events = not attributes.get('Disabled', False)

    # Element layout
    elem_key = attributes['Key']
    display_value = attributes.get('DisplayValue', None)
    layout = [sg.Text(display_value, key=elem_key, enable_events=events, size=size, pad=pad, background_color=bg_col,
                      text_color=text_col, font=font, border_width=bw, relief='sunken', tooltip=tooltip)]

    return layout

def input_layout(attributes):
    # Standard element parameters
    font = attributes.get('Font', mod_const.LARGE_FONT)
    size = attributes.get('Size', None)
    pad = attributes.get('Pad', None)
    bw = attributes.get('BW', 1)
    bg_col = attributes.get('BackgroundColor', mod_const.DEFAULT_BG_COLOR)
    text_col = attributes.get('TextColor', mod_const.DEFAULT_TEXT_COLOR)

    disabled = attributes.get('Disabled', False)
    tooltip = attributes.get('Tooltip', None)

    # Element layout
    elem_key = attributes['Key']
    display_value = attributes.get('DisplayValue', '')
    layout = [sg.Input(display_value, key=elem_key, enable_events=True, disabled=disabled, size=size, pad=pad,
                       font=font, background_color=bg_col, text_color=text_col, border_width=bw,
                       disabled_readonly_background_color=bg_col, disabled_readonly_text_color=text_col,
                       tooltip=tooltip, metadata={'disabled': disabled})]

    return layout

def combo_layout(attributes):
    # Standard element parameters
    font = attributes.get('Font', mod_const.LARGE_FONT)
    size = attributes.get('Size', None)
    pad = attributes.get('Pad', None)
    bg_col = attributes.get('BackgroundColor', mod_const.DEFAULT_BG_COLOR)
    text_col = attributes.get('TextColor', mod_const.DEFAULT_TEXT_COLOR)

    disabled = attributes.get('Disabled', False)
    tooltip = attributes.get('Tooltip', None)

    # Combobox parameters
    values = attributes.get('ComboValues', [])

    # Element layout
    elem_key = attributes['Key']
    display_value = attributes.get('DisplayValue', '')
    layout = [sg.Combo(values, default_value=display_value, key=elem_key, enable_events=True, size=size, pad=pad,
                       font=font, text_color=text_col, background_color=bg_col,
                       button_arrow_color=mod_const.BORDER_COLOR, button_background_color=bg_col,
                       expand_x=True, expand_y=True,
                       disabled=disabled, tooltip=tooltip, metadata={'disabled': disabled})]

    return layout

def multiline_layout(attributes):
    # Standard element parameters
    font = attributes.get('Font', mod_const.LARGE_FONT)
    size = attributes.get('Size', None)
    pad = attributes.get('Pad', None)
    bw = attributes.get('BW', 1)
    bg_col = attributes.get('BackgroundColor', mod_const.DEFAULT_BG_COLOR)
    def_text_col = attributes.get('TextColor', mod_const.DEFAULT_TEXT_COLOR)
    disabled_text_col = mod_const.DISABLED_TEXT_COLOR

    disabled = attributes.get('Disabled', False)
    tooltip = attributes.get('Tooltip', None)

    if disabled:
        text_col = disabled_text_col
    else:
        text_col = def_text_col

    # Multiline parameters
    height = attributes.get('NRow', 1)
    width = size[0]

    # Element layout
    elem_key = attributes['Key']
    display_value = attributes.get('DisplayValue', '')
    layout = [sg.Multiline(display_value, key=elem_key, size=(width, height), pad=pad, font=font, disabled=disabled,
                           background_color=bg_col, text_color=text_col, border_width=bw,
                           tooltip=tooltip, metadata={'disabled': disabled})]

    return layout

def checkbox_layout(attributes):
    # Standard element parameters
    font = attributes.get('Font', mod_const.LARGE_FONT)
    size = attributes.get('Size', None)
    pad = attributes.get('Pad', None)
    bg_col = attributes.get('BackgroundColor', mod_const.DEFAULT_BG_COLOR)
    text_col = attributes.get('TextColor', mod_const.DEFAULT_TEXT_COLOR)

    disabled = attributes.get('Disabled', False)
    tooltip = attributes.get('Tooltip', None)

    # Checkbox settings
    box_col = bg_col if not disabled else mod_const.DISABLED_BG_COLOR

    width, height = size
    elem_w = 0
    elem_h = height

    # Parameter settings
    elem_key = attributes['Key']
    display_value = attributes.get('DisplayValue', False)
    layout = [sg.Checkbox('', default=display_value, key=elem_key, enable_events=True, disabled=disabled,
                          size=(elem_w, elem_h), pad=pad, font=font, background_color=bg_col, text_color=text_col,
                          checkbox_color=box_col, tooltip=tooltip, metadata={'disabled': disabled})]

    return layout

def button_layout(bttn_key, icon: str = None, **kwargs):
    """
    Program button layout.
    """
    # Button constants
    text_color = mod_const.DEFAULT_TEXT_COLOR
    disabled_text_color = mod_const.DISABLED_TEXT_COLOR
    bg_color = mod_const.BORDER_COLOR
    disabled_bg_color = mod_const.BORDER_COLOR
    highlight_color = mod_const.BUTTON_HOVER_COLOR
    size = mod_const.BTTN_SIZE

    bttn_icon = icon if icon is not None else mod_const.BLANK_ICON
    layout = sg.Button('', key=bttn_key, image_data=bttn_icon, image_size=size, button_color=(text_color, bg_color),
                       disabled_button_color=(disabled_text_color, disabled_bg_color),
                       mouseover_colors=(text_color, highlight_color), border_width=1, use_ttk_buttons=False, **kwargs)

    return layout

def create_table_layout(data, header, keyname, events: bool = False, bind: bool = False, tooltip: str = None,
                        nrow: int = None, height: int = 800, width: int = 1200, font: tuple = None, pad: tuple = None,
                        table_name: str = ''):
    """
    Create table elements that have consistency in layout.
    """
    # Element settings
    text_col = mod_const.DEFAULT_TEXT_COLOR
    alt_col = mod_const.TBL_ALT_COLOR
    bg_col = mod_const.TBL_BG_COLOR
    select_col = mod_const.TBL_SELECT_COLOR
    header_col = mod_const.HEADER_COLOR

    pad_frame = mod_const.FRAME_PAD
    pad = pad if pad else (pad_frame, pad_frame)

    font = font if font else mod_const.LARGE_FONT
    bold_font = mod_const.BOLD_FONT
    font_size = font[1]

    # Arguments
    row_height = mod_const.TBL_ROW_HEIGHT
    width = width
    height = height * 0.5
    nrow = nrow if nrow else int(height / 40)

    # Parameters
    if events and bind:
        bind = False  # only one can be selected at a time
        logger.warning('both bind_return_key and enable_events have been selected during table creation. '
                       'These parameters are mutually exclusive.')

    lengths = mod_dm.calc_column_widths(header, width=width, font_size=font_size, pixels=False)

    if table_name:
        top_layout = [sg.Col([[sg.Text(table_name, pad=(0, 0), font=bold_font, background_color=alt_col)]],
                             justification='c', background_color=header_col, expand_x=True)]
        frame_relief = 'ridge'
    else:
        top_layout = [sg.Canvas(size=(0, 0))]
        frame_relief = 'flat'

    bottom_layout = [sg.Table(data, key=keyname, headings=header, pad=(0, 0), num_rows=nrow,
                              row_height=row_height, alternating_row_color=alt_col, background_color=bg_col,
                              text_color=text_col, selected_row_colors=(text_col, select_col), font=font,
                              display_row_numbers=False, auto_size_columns=False, col_widths=lengths,
                              enable_events=events, bind_return_key=bind, tooltip=tooltip, vertical_scroll_only=False)]

    layout = sg.Frame('', [top_layout, bottom_layout], pad=pad, element_justification='l',
                      vertical_alignment='t', background_color=alt_col, relief=frame_relief)

    return layout

def importer_layout(win_size: tuple = None):
    """
    Create the layout for the database import window.
    """
    if win_size:
        width, height = win_size
    else:
        width, height = (int(mod_const.WIN_WIDTH * 0.9), int(mod_const.WIN_HEIGHT * 0.9))

    # Layout settings
    header_col = mod_const.HEADER_COLOR
    input_col = mod_const.FIELD_BG_COLOR
    bg_col = mod_const.DEFAULT_BG_COLOR
    frame_col = mod_const.FRAME_COLOR
    select_col = mod_const.SELECTED_TEXT_COLOR
    text_col = mod_const.DEFAULT_TEXT_COLOR

    pad_el = mod_const.ELEM_PAD
    pad_v = mod_const.VERT_PAD
    pad_h = mod_const.HORZ_PAD
    pad_frame = mod_const.FRAME_PAD

    font_h = mod_const.HEADING_FONT
    font_bold = mod_const.BOLD_FONT
    font_main = mod_const.MAIN_FONT
    font_large = mod_const.BOLD_HEADING_FONT

    # Keyboard shortcuts
    hotkeys = settings.hotkeys
    cancel_shortcut = hotkeys['-HK_ESCAPE-'][2]
    save_shortcut = hotkeys['-HK_ENTER-'][2]
    next_shortcut = hotkeys['-HK_RIGHT-'][2]
    back_shortcut = hotkeys['-HK_LEFT-'][2]

    # Element sizes
    bwidth = 1
    format_param_w = 14
    frame_w = int(width * 0.85)
    frame_pad = pad_frame * 2
    container_w = frame_w - frame_pad
    subset_w = int(container_w * 0.7)

    try:
        record_types = [i.menu_title for i in settings.records.rules if user.check_permission(i.permissions['upload'])]
    except ValueError:
        record_types = []

    file_types = ['xls', 'csv/tsv']
    encodings = ['Default']

    header_req = ['Record Field', 'Data Type', 'Value']
    header_map = ['Record Field', 'Data Type', 'File Column Name']

    cond_operators = ['=', '!=', '>', '<', '>=', '<=']
    math_operators = ['+', '-', '*', '/', '%', '^', '//']
    def_combo_values = ['', '', '', '', '', '']

    # Window Layout

    # Subset layout
    subset_keys = ['-SUBSET_{}-'.format(i) for i in range(10)]
    subset_layout = [[sg.Canvas(size=(container_w, 0), background_color=bg_col)]]
    for index, subset_key in enumerate(subset_keys):
        oper_key = '-SUBSET_OPER_{}-'.format(index)
        value_key = '-SUBSET_VALUE_{}-'.format(index)
        col_key = '-SUBSET_COL_{}-'.format(index)
        add_key = '-SUBSET_ADD_{}-'.format(index)
        delete_key = '-SUBSET_DELETE_{}-'.format(index)

        if index == 0:  # no delete key
            visible = True
            subset_bttn_layout = [[sg.Button('', key=add_key, image_data=mod_const.ADD_ICON, border_width=1,
                                             button_color=(text_col, bg_col))]]
        elif index == 9:  # no add key
            visible = False
            subset_bttn_layout = [[sg.Button('', key=delete_key, image_data=mod_const.MINUS_ICON, pad=(0, 0),
                                             border_width=1, button_color=(text_col, bg_col))]]
        else:
            visible = False
            subset_bttn_layout = [[sg.Button('', key=delete_key, image_data=mod_const.MINUS_ICON, pad=((0, pad_el), 0),
                                             border_width=1, button_color=(text_col, bg_col)),
                                   sg.Button('', key=add_key, image_data=mod_const.ADD_ICON, border_width=1,
                                             button_color=(text_col, bg_col))]]

        sub_cond_layout = [sg.Col([[sg.Canvas(size=(container_w, 0), background_color=bg_col)],
                                   [sg.Col([[sg.Text('{}.'.format(index + 1), pad=((0, pad_h), 0), font=font_bold,
                                                     background_color=bg_col, auto_size_text=True),
                                             sg.Combo(def_combo_values, key=col_key, pad=((0, pad_h), pad_el),
                                                      size=(int(subset_w * 0.4 / 9), 1), background_color=input_col,
                                                      font=font_main, auto_size_text=False, disabled=True,
                                                      tooltip='Column'),
                                             sg.Combo(cond_operators, key=oper_key, pad=((0, pad_h), pad_el),
                                                      size=(int(subset_w * 0.2 / 9), 1), font=font_bold,
                                                      background_color=input_col, auto_size_text=False, disabled=True,
                                                      tooltip='Operator'),
                                             sg.Input('', key=value_key, pad=((0, pad_el), pad_el),
                                                      size=(int(subset_w * 0.4 / 9), 1), background_color=input_col,
                                                      font=font_main, disabled=True, tooltip='Column value')]],
                                           background_color=bg_col, justification='l', element_justification='l',
                                           expand_x=True),
                                    sg.Col(subset_bttn_layout, pad=(pad_h, 0), justification='r',
                                           element_justification='r', background_color=bg_col)]],
                                  key=subset_key, background_color=bg_col, vertical_alignment='t', justification='l',
                                  element_justification='l', pad=(0, int(pad_el / 2)), visible=visible)
                           ]
        subset_layout.append(sub_cond_layout)

    # Modify layout
    modify_keys = ['-MODIFY_{}-'.format(i) for i in range(10)]
    modify_layout = [[sg.Canvas(size=(container_w, 0), background_color=bg_col)]]
    for index, modify_key in enumerate(modify_keys):
        oper_key = '-MODIFY_OPER_{}-'.format(index)
        value_key = '-MODIFY_VALUE_{}-'.format(index)
        col_key = '-MODIFY_COL_{}-'.format(index)
        add_key = '-MODIFY_ADD_{}-'.format(index)
        delete_key = '-MODIFY_DELETE_{}-'.format(index)

        if index == 0:  # no delete key
            visible = True
            modify_bttn_layout = [[sg.Button('', key=add_key, image_data=mod_const.ADD_ICON, border_width=1,
                                             button_color=(text_col, bg_col))]]
        elif index == 9:  # no add key
            visible = False
            modify_bttn_layout = [[sg.Button('', key=delete_key, image_data=mod_const.MINUS_ICON, pad=(0, 0),
                                             border_width=1, button_color=(text_col, bg_col))]]
        else:
            visible = False
            modify_bttn_layout = [[sg.Button('', key=delete_key, image_data=mod_const.MINUS_ICON, pad=((0, pad_el), 0),
                                             border_width=1, button_color=(text_col, bg_col)),
                                   sg.Button('', key=add_key, image_data=mod_const.ADD_ICON, border_width=1,
                                             button_color=(text_col, bg_col))]]

        mod_cond_layout = [sg.Col([[sg.Canvas(size=(container_w, 0), background_color=bg_col)],
                                   [sg.Col([[sg.Text('{}.'.format(index + 1), pad=((0, pad_h), 0), font=font_bold,
                                                     background_color=bg_col, auto_size_text=True),
                                             sg.Combo(def_combo_values, key=col_key, pad=((0, pad_h), pad_el),
                                                      size=(int(subset_w * 0.4 / 9), 1), background_color=input_col,
                                                      font=font_main, auto_size_text=False, disabled=True,
                                                      tooltip='Column'),
                                             sg.Combo(math_operators, key=oper_key, pad=((0, pad_h), pad_el),
                                                      size=(int(subset_w * 0.2 / 9), 1), font=font_bold,
                                                      background_color=input_col, auto_size_text=False, disabled=True,
                                                      tooltip='Operator'),
                                             sg.Input('', key=value_key, pad=((0, pad_el), pad_el),
                                                      size=(int(subset_w * 0.4 / 9), 1), background_color=input_col,
                                                      font=font_main, disabled=True, tooltip='Column value')]],
                                           background_color=bg_col, justification='l', element_justification='l',
                                           expand_x=True),
                                    sg.Col(modify_bttn_layout, pad=(pad_h, 0), justification='r',
                                           element_justification='r', background_color=bg_col)]],
                                  key=modify_key, background_color=bg_col, vertical_alignment='t', justification='l',
                                  element_justification='l', pad=(0, int(pad_el / 2)), visible=visible)
                           ]
        modify_layout.append(mod_cond_layout)

    # Panel layout
    p1 = [[sg.Col([[sg.Text('File:', size=(5, 1), pad=((0, pad_el), 0), background_color=bg_col),
                    sg.Input('', key='-FILE-', size=(60, 1), pad=(pad_el, 0), background_color=input_col),
                    sg.FileBrowse('Browse ...', pad=((pad_el, pad_frame), 0))]],
                  pad=(pad_frame, (pad_frame, pad_v)), justification='l', background_color=bg_col)],
          [sg.Frame('File format', [
              [sg.Canvas(size=(frame_w, 0), background_color=bg_col)],
              [sg.Col([[sg.Canvas(size=(int(frame_w * 0.15), 0), background_color=bg_col)]],
                      pad=(0, pad_v), background_color=bg_col, expand_x=True, expand_y=True),
               sg.Col([[sg.Canvas(size=(int(frame_w * 0.15), 0), background_color=bg_col)],
                       [sg.Text('Format:', auto_size_text=True, pad=(pad_el, pad_el), background_color=bg_col),
                        sg.Combo(file_types, key='-FORMAT-', default_value='xls', size=(12, 1),
                                 pad=(pad_el, pad_el), background_color=input_col, tooltip='Format of the input file')],
                       [sg.Text('Encoding:', auto_size_text=True, pad=(pad_el, 0), background_color=bg_col),
                        sg.Combo(encodings, key='-ENCODE-', default_value='Default', size=(12, 1), pad=(pad_el, pad_el),
                                 background_color=input_col)]],
                      pad=((pad_h, 0), pad_v), background_color=bg_col, element_justification='r', expand_x=True),
               sg.Col([[sg.Canvas(size=(int(frame_w * 0.15), 0), background_color=bg_col)]],
                      pad=(0, pad_v), background_color=bg_col, expand_x=True, expand_y=True),
               sg.Col([[sg.Canvas(size=(int(frame_w * 0.15), 0), background_color=bg_col)],
                       [sg.Text('Newline Separator:', auto_size_text=True, pad=(pad_el, pad_el),
                                background_color=bg_col),
                        sg.Input('\\n', key='-NSEP-', size=(8, 1), pad=(pad_el, pad_el), disabled=True,
                                 background_color=input_col,
                                 tooltip='Character used in the CSV file to distinguish between rows')],
                       [sg.Text('Field Separator:', auto_size_text=True, pad=(pad_el, pad_el), background_color=bg_col),
                        sg.Input('\\t', key='-FSEP-', size=(8, 1), pad=(pad_el, pad_el), disabled=True,
                                 background_color=input_col,
                                 tooltip='Character used in the CSV file to distinguish between columns')]],
                      pad=((0, pad_h), pad_v), background_color=bg_col, element_justification='r', expand_x=True),
               sg.Col([[sg.Canvas(size=(int(frame_w * 0.15), 0), background_color=bg_col)]], pad=(0, pad_v),
                      background_color=bg_col, expand_x=True, expand_y=True)]
          ], pad=(pad_frame, pad_v), border_width=bwidth, background_color=bg_col, title_color=select_col,
                    relief='groove')],
          [sg.Frame('Formatting options', [
              [sg.Canvas(size=(frame_w, 0), background_color=bg_col)],
              [sg.Checkbox('Recognize dates', key='-DATES-', pad=(pad_h, (pad_v, pad_el)), default=True, font=font_main,
                           background_color=bg_col,
                           tooltip='Attempt to parse the values of columns containing dates.')],
              [sg.Checkbox('Recognize integers', key='-INTS-', pad=(pad_h, pad_el), default=True, font=font_main,
                           background_color=bg_col,
                           tooltip='Attempt to infer whether data type of a column is an integer or float. '
                                   'Excel files store all numeric values as decimals')],
              [sg.Col([[sg.Canvas(size=(int(frame_w * 0.25), 0), background_color=bg_col)],
                       [sg.Text('Skip n rows at top:', auto_size_text=True, pad=(0, pad_el), font=font_main,
                                background_color=bg_col, tooltip='Do not import the first n rows')],
                       [sg.Text('Skip n rows at bottom:', auto_size_text=True, pad=(0, pad_el), background_color=bg_col,
                                font=font_main, tooltip='Do not import the last n rows')],
                       [sg.Text('Header row (0 indexed):', auto_size_text=True, pad=(0, pad_el),
                                background_color=bg_col, font=font_main,
                                tooltip='Row number, starting at 0, containing the column names (applied '
                                        'after filtering by skipped rows).')],
                       [sg.Text('Thousands separator:', auto_size_text=True, pad=(0, pad_el), background_color=bg_col,
                                font=font_main,
                                tooltip='Thousands character used for parsing string columns into a numeric form')],
                       [sg.Text('Date format:', auto_size_text=True, pad=(0, pad_el), background_color=bg_col,
                                font=font_main, tooltip='Date format used by columns containing date values')],
                       [sg.Text('Date offset:', auto_size_text=True, pad=(0, pad_el), background_color=bg_col,
                                font=font_main, tooltip='Dates are offset by the given number of years')]],
                      pad=((pad_h, 0), (0, pad_v)), background_color=bg_col),
               sg.Col([[sg.Canvas(size=(int(frame_w * 0.5), 0), background_color=bg_col)],
                       [sg.Input('0', key='-TSKIP-', size=(format_param_w, 1), pad=(0, pad_el), font=font_main,
                                 background_color=input_col)],
                       [sg.Input('0', key='-BSKIP-', size=(format_param_w, 1), pad=(0, pad_el), font=font_main,
                                 background_color=input_col)],
                       [sg.Input('0', key='-HROW-', size=(format_param_w, 1), pad=(0, pad_el), font=font_main,
                                 background_color=input_col)],
                       [sg.Input(',', key='-TSEP-', size=(format_param_w, 1), pad=(0, pad_el), font=font_main,
                                 background_color=input_col)],
                       [sg.Input('YYYY-MM-DD', key='-DATE_FORMAT-', size=(format_param_w, 1), pad=(0, pad_el),
                                 font=font_main, background_color=input_col)],
                       [sg.Input('0', key='-DATE_OFFSET-', size=(format_param_w, 1), pad=(0, pad_el), font=font_main,
                                 background_color=input_col)]],
                      pad=((0, pad_h), (0, pad_v)), background_color=bg_col, expand_x=True)]
          ],
                    pad=(pad_frame, (pad_v, pad_frame)), border_width=bwidth, background_color=bg_col,
                    title_color=select_col, relief='groove')]]
    p2 = [[sg.Col([[sg.Text('Record Type:', pad=((0, pad_el), 0), background_color=bg_col),
                    sg.Combo(record_types, key='-RECORDTYPE-', size=(28, 1), pad=(0, 0),
                             enable_events=True, background_color=input_col)]],
                  pad=(pad_frame, (pad_frame, pad_v)), justification='l', background_color=bg_col)],
          [sg.Frame('Required Columns', [
              [sg.Canvas(size=(frame_w, 0), background_color=bg_col)],
              [sg.Col([
                  [sg.Col([[sg.Listbox(values=[], key='-REQLIST-', size=(26, 8), font=font_main, bind_return_key=True,
                                       background_color=bg_col, select_mode='extended',
                                       tooltip='Double-click on a column name to add the column to the table')]],
                          background_color=bg_col, justification='l', element_justification='l', expand_x=True),
                   sg.Col([[create_table_layout([[]], header_req, '-REQCOL-', bind=True, pad=(0, 0), nrow=4,
                                                width=width * 0.65,
                                                tooltip='Click on a row to edit the row fields. Use the delete or '
                                                        'backspace keys to remove a row from the table')]],
                          background_color=bg_col, justification='r', element_justification='r')]],
                  pad=(pad_v, pad_v), background_color=bg_col, expand_x=True)]],
                    pad=(pad_frame, pad_v), border_width=bwidth, background_color=bg_col, title_color=select_col,
                    relief='groove', tooltip='Set static values for required import columns.')],
          [sg.Frame('Column Map', [
              [sg.Canvas(size=(frame_w, 0), background_color=bg_col)],
              [sg.Col([
                  [sg.Col([[sg.Listbox(values=[], key='-MAPLIST-', size=(26, 8), font=font_main, bind_return_key=True,
                                       background_color=bg_col, select_mode='extended',
                                       tooltip='Double-click on a column name to add the column to the table')]],
                          background_color=bg_col, justification='l', element_justification='l', expand_x=True),
                   sg.Col([[create_table_layout([[]], header_map, '-MAPCOL-', bind=True, pad=(0, 0), nrow=4,
                                                width=width * 0.65,
                                                tooltip='Click on a row to edit the row fields. Use the delete or '
                                                        'backspace keys to remove a row from the table')]],
                          background_color=bg_col, justification='r', element_justification='r')]],
                  pad=(pad_v, pad_v), background_color=bg_col, expand_x=True)]],
                    pad=(pad_frame, pad_v), border_width=bwidth, background_color=bg_col, title_color=select_col,
                    relief='groove', tooltip='Map imported file column names to database table column names')],
          [sg.Frame('Subset Rows', [
              [sg.Canvas(size=(frame_w, 0), background_color=bg_col)],
              [sg.Col(subset_layout, pad=(pad_v, pad_v), key='-SUBSET-',
                      background_color=bg_col, expand_x=True, expand_y=True,
                      vertical_alignment='t', scrollable=True, vertical_scroll_only=True, justification='l',
                      element_justification='l')]],
                    pad=(pad_frame, pad_v), background_color=bg_col, border_width=bwidth,
                    title_color=select_col, relief='groove', element_justification='l', vertical_alignment='t',
                    tooltip='Use the subset rules to subset table rows based on the values of the imported columns')],
          [sg.Frame('Transform Values', [
              [sg.Canvas(size=(int(width * 0.85), 0), background_color=bg_col)],
              [sg.Col(modify_layout, pad=(pad_v, pad_v), key='-MODIFY-',
                      background_color=bg_col, expand_x=True, expand_y=True,
                      vertical_alignment='t', scrollable=True, vertical_scroll_only=True, justification='l',
                      element_justification='l')]],
                    pad=(pad_frame, (pad_v, pad_frame)), background_color=bg_col, border_width=bwidth,
                    title_color=select_col, relief='groove', element_justification='l', vertical_alignment='t',
                    tooltip='Use the modify rules to modify the values of an imported column. Only date and numeric '
                            'columns support this operation.')]
          ]
    p3 = [[sg.Frame('Import Statistics', [
        [sg.Canvas(size=(frame_w, 0), background_color=bg_col)],
        [sg.Col([
            [sg.Text('Record type:', size=(28, 1), pad=(0, pad_el), background_color=bg_col,
                     font=font_main),
             sg.Text('0', key='-TABLENAME-', size=(12, 1), pad=(0, pad_el), font=font_main,
                     background_color=bg_col)],
            [sg.Text('Number of data columns:', size=(28, 1), pad=(0, pad_el), background_color=bg_col,
                     font=font_main),
             sg.Text('0', key='-NCOL-', size=(12, 1), pad=(0, pad_el), font=font_main,
                     background_color=bg_col)],
            [sg.Text('Number of import rows:', size=(28, 1), pad=(0, pad_el), background_color=bg_col,
                     font=font_main),
             sg.Text('0', key='-NROW-', size=(12, 1), pad=(0, pad_el), font=font_main, background_color=bg_col)
             ]
        ], pad=(pad_v, pad_v), background_color=bg_col, vertical_alignment='t', expand_x=True, expand_y=True)]],
                    pad=(pad_frame, (pad_frame, pad_v)), border_width=bwidth, background_color=bg_col,
                    title_color=select_col, relief='groove')],
          [sg.Frame('Table Preview', [
              [sg.Canvas(size=(frame_w, 0), background_color=bg_col)],
              [sg.Col([
                  [create_table_layout([[]], ['{}'.format(i) for i in range(1)], '-PREVIEW-', pad=(0, 0), nrow=15,
                                       width=width * 0.94, tooltip='Preview of the first 10 and last 10 records that '
                                                                   'will be imported into the database table')]],
                  pad=(pad_v, pad_v), background_color=bg_col, expand_x=True, expand_y=True,
                  element_justification='c', vertical_alignment='c')]],
                    pad=(pad_frame, (pad_v, pad_frame)), border_width=bwidth, background_color=bg_col,
                    title_color=select_col, relief='groove')]]

    panels = [sg.Col(p1, key='-P1-', background_color=bg_col, vertical_alignment='c', visible=True, expand_y=True,
                     expand_x=True),
              sg.Col(p2, key='-P2-', background_color=bg_col, vertical_alignment='c', visible=False, expand_y=True,
                     expand_x=True),
              sg.Col(p3, key='-P3-', background_color=bg_col, vertical_alignment='c', visible=False, expand_y=True,
                     expand_x=True)]

    panel_layout = [[sg.Col([[sg.Canvas(size=(0, height * 0.9), background_color=bg_col)]], background_color=bg_col),
                     sg.Col([[sg.Pane(panels, key='-PANELS-', orientation='horizontal', show_handle=False,
                                      border_width=0, relief='flat')]], pad=(0, pad_v), expand_x=True)]]

    #bttn_layout = [[sg.Button('', key='-BACK-', image_data=mod_const.LEFT_ICON, image_size=mod_const.BTTN_SIZE,
    #                          pad=(pad_el, 0), disabled=True,
    #                          tooltip='Return to previous panel ({})'.format(back_shortcut)),
    #                sg.Button('', key='-NEXT-', image_data=mod_const.RIGHT_ICON, image_size=mod_const.BTTN_SIZE,
    #                          pad=(pad_el, 0), disabled=False,
    #                          tooltip='Move to next panel ({})'.format(next_shortcut)),
    #                sg.Button('', bind_return_key=True, image_data=mod_const.SAVE_ICON, image_size=mod_const.BTTN_SIZE,
    #                          key='-IMPORT-', pad=(pad_el, 0), disabled=True,
    #                          tooltip='Import file contents to the selected database table ({})'.format(save_shortcut)),
    #                sg.Button('', key='-CANCEL-', image_data=mod_const.CANCEL_ICON, image_size=mod_const.BTTN_SIZE,
    #                          pad=(pad_el, 0), disabled=False,
    #                          tooltip='Cancel importing records to the database ({})'.format(cancel_shortcut))]]

    bttn_layout = [[button_layout('-CANCEL-', icon=mod_const.BTTN_CANCEL_ICON, pad=(pad_el, 0), disabled=False,
                                  tooltip='Cancel importing records to the database ({})'.format(cancel_shortcut)),
                    button_layout('-BACK-', icon=mod_const.BTTN_LEFT_ICON, pad=(pad_el, 0), disabled=True,
                                  tooltip='Return to previous panel ({})'.format(back_shortcut)),
                    button_layout('-NEXT-', icon=mod_const.BTTN_RIGHT_ICON, pad=(pad_el, 0), disabled=False,
                                  tooltip='Move to next panel ({})'.format(next_shortcut)),
                    button_layout('-IMPORT-', icon=mod_const.BTTN_SAVE_ICON, disabled=True,
                                  tooltip='Save records to the selected database table ({})'.format(save_shortcut))]]

    sidebar_layout = [
        [sg.Col([[sg.Canvas(size=(0, height * 0.9), background_color=frame_col)]], background_color=frame_col),
         sg.Col([[sg.Text('• ', pad=((pad_frame, pad_el), (pad_frame, pad_el)), font=font_large,
                          background_color=frame_col),
                  sg.Text('File Options', key='-PN1-', pad=((pad_el, pad_frame), (pad_frame, pad_el)),
                          font=font_main, text_color=select_col, background_color=frame_col)],
                 [sg.Text('• ', pad=((pad_frame, pad_el), pad_el), font=font_large, background_color=frame_col),
                  sg.Text('Import Options', key='-PN2-', pad=((pad_el, pad_frame), pad_el), font=font_main,
                          background_color=frame_col)],
                 [sg.Text('• ', pad=((pad_frame, pad_el), pad_el), font=font_large, background_color=frame_col),
                  sg.Text('Data Preview', key='-PN3-', pad=((pad_el, pad_frame), pad_el), font=font_main,
                          background_color=frame_col)]],
                background_color=frame_col, element_justification='l', vertical_alignment='t', expand_y=True)]]

    layout = [[sg.Col([[sg.Text('Import to Database', pad=(pad_frame, (pad_frame, pad_v)),
                                font=font_h, background_color=header_col)]],
                      pad=(0, 0), justification='l', background_color=header_col, expand_x=True, expand_y=True)],
              [sg.Frame('', sidebar_layout, border_width=bwidth, title_color=text_col, relief='solid',
                        background_color=frame_col),
               sg.Frame('', panel_layout, border_width=bwidth, title_color=text_col, relief='solid',
                        background_color=bg_col)],
              [sg.Col(bttn_layout, justification='r', pad=(pad_frame, (pad_v, pad_frame)))]]

    return layout

# Panel layouts
def home_screen(size):
    """
    Create layout for the home screen.
    """
    bg_col = mod_const.FRAME_COLOR
    width, height = size

    layout = sg.Col([[sg.Canvas(key='-HOME_WIDTH-', size=(width, 0), background_color=bg_col)],
                     [sg.Canvas(key='-HOME_HEIGHT-', size=(0, height), background_color=bg_col),
                      sg.Image(filename=settings.logo, background_color=bg_col, key='-HOME_IMAGE-',
                               size=(width, height))]],
                    key='-HOME-', element_justification='c', vertical_alignment='t', background_color=bg_col,
                    expand_y=True, expand_x=True, visible=False)

    return layout


import numpy as np

def rebatch(X_train, X_test, Y_train, Y_test, batchN, pardon = None):

    X_train, Y_train = single_rebatcher(X_train, Y_train, batchN, pardon)
    X_test, Y_test = single_rebatcher(X_test, Y_test, batchN, pardon)

    return X_train, X_test, Y_train, Y_test

def single_rebatcher(X, Y, batchN, pardon = 0.25):
    cnt = 0
    buf = ''
    X_buf = []
    Y_buf = []

    #--check if we will use the clientId for divider (divider 0)
    if(batchN == 0):
        from reporter import Reporter
        report = Reporter()
        report.new_report('Rebatcher report')
        report.report('using full sequence (clientId)')
        return X,Y, report

    if pardon == 0 or pardon == None:
        pardon_up = 1
        pardon_down = 0
    else:
        pardon_up = (1 - pardon)
        pardon_down = pardon

    for i,seq in enumerate(X):
        A = seq.split()
        numTrans = len(A)

        batchInA = numTrans//batchN

        stop = 0
        for j in range(batchInA):
            start = j*batchN
            stop = (j+1) * batchN

            buf = A[start:stop]

            X_buf.append(' '.join(buf))
            Y_buf.append(Y[i])

        x_remaining = A[stop:]
        if (len(x_remaining) <= pardon_down * batchN) and (batchInA != 0):
            X_buf[-1] = X_buf[-1] + ' ' + ' '.join(x_remaining)
        elif len(x_remaining) >= pardon_up * batchN:
            X_buf.append(' '.join(x_remaining))
            Y_buf.append(Y[i])

    X_buf = np.asarray(X_buf)
    Y_buf = np.asarray(Y_buf)

    old_total=0
    for old,seq in enumerate(X):
        old_total += len(seq.split()) + 1

    new_total=0
    for new,seq in enumerate(X_buf):
        new_total += len(seq.split()) + 1

    from reporter import Reporter
    report = Reporter()
    report.new_report('Rebatcher report')
    report.report('old sample --total transitions: ,' +  str(old_total) + '-- total sequences: ,' + str(old))
    report.report('new sample --total transitions: ,' +  str(new_total) + '-- total sequences: ,' + str(new))
    return X_buf, Y_buf, report

def getBatchStatistics(X, Y):
    pass

if __name__ == "__main__":
    print('running test sequence')
    test_x = ['1 2 3 4 5 6 7 8 9 0 1','10 11 12 13 14','20 21 21 22 23 24']
    test_y = [0,1,2]
    print(test_x, test_y)
    print('-'*30)
    print(single_rebatcher(test_x, test_y, 4))


import json
import tabfile

# using files from http://compling.hss.ntu.edu.sg/omw/summx.html

def callback(output, parts):
	if len(parts) != 3: return
	synset, word = parts[0].replace('-', ''), parts[2]
	if word in output: output[word].append(synset)
	else: output[word] = [synset]

def conv(lang, path):
	output = {}
	tabfile.parse(path, callback, output)

	json_file = open('synsets.json', 'w')
	json.dump(output, json_file)
	json_file.close()

conv('fra', 'wikt.tab')


import pandas as pd
import numpy as np
import numpy.random
import pandas as pd
from astropy.convolution import convolve
import matplotlib.pyplot as plt
from astropy.convolution.kernels import Gaussian2DKernel
import scipy.ndimage as spnd
from matplotlib.colors import LogNorm

ldv_x = []
ldv_y = []
ldv_z = []
ldv = pd.read_csv('./differenced_ldv.csv')
for index, row in ldv.iterrows():
    ldv_x.append(row['x_bucket'])
    ldv_y.append(row['y_bucket'])
    ldv_z.append(row['difference_PM2.5'])

heatmap_ldv, xedges_ldv, yedges_ldv = np.histogram2d(ldv_x, ldv_y, bins=500, weights=[w*100+40 for w in ldv_z])
extent_ldv = [yedges_ldv[0], yedges_ldv[-1], xedges_ldv[0], xedges_ldv[-1]]

im = plt.imshow(convolve(heatmap_ldv, Gaussian2DKernel(stddev=2)), extent=extent_ldv, cmap='inferno', vmin=0, vmax=100)

plt.colorbar()

plt.show()

bus_x = []
bus_y = []
bus_z = []
bus = pd.read_csv('./differenced_bus.csv')
for index, row in bus.iterrows():
    bus_x.append(row['x_bucket'])
    bus_y.append(row['y_bucket'])
    bus_z.append(row['difference_PM2.5'])
heatmap_bus, xedges_bus, yedges_bus = np.histogram2d(bus_x, bus_y, bins=500, weights=[w*100+40 for w in bus_z])
extent_bus = [yedges_bus[0], yedges_bus[-1], xedges_bus[0], xedges_bus[-1]]

taxi_x = []
taxi_y = []
taxi_z = []
taxi = pd.read_csv('./differenced_taxi.csv')
for index, row in taxi.iterrows():
    taxi_x.append(row['x_bucket'])
    taxi_y.append(row['y_bucket'])
    taxi_z.append(row['difference_PM2.5'])
heatmap_taxi, xedges_taxi, yedges_taxi = np.histogram2d(taxi_x, taxi_y, bins=500, weights=[w*100+40 for w in taxi_z])
extent_taxi = [yedges_taxi[0], yedges_taxi[-1], xedges_taxi[0], xedges_taxi[-1]]

heatmaps=[heatmap_taxi, heatmap_taxi, heatmap_bus, heatmap_ldv]

im = plt.imshow(convolve(heatmap_taxi, Gaussian2DKernel(stddev=2)), extent=extent_ldv, cmap='inferno', vmin=0, vmax=100)

plt.colorbar()

plt.show()

im = plt.imshow(convolve(heatmap_bus, Gaussian2DKernel(stddev=2)), extent=extent_ldv, cmap='inferno', vmin=0, vmax=100)

plt.colorbar()

plt.show()

'''fig, ax = plt.subplots(2, 1)

pcm = ax[0].pcolor(x, y, z,
                   norm=colors.LogNorm(vmin=min(z), vmax=max(z)),
                   cmap='Greys')
fig.colorbar(pcm, ax=ax[0], extend='max')

pcm = ax[1].pcolor(x, y, z, cmap='Greys')
fig.colorbar(pcm, ax=ax[1], extend='max')
fig.show()'''

'''from astropy.convolution.kernels import Gaussian2DKernel
plt.pcolor(convolve(heatmap, Gaussian2DKernel(stddev=2)), cmap='inferno')
plt.colorbar()

plt.show()'''


from utils import NMS, load_image, draw_boxes
import torch
import os
import numpy as np
import cv2
from Yolov4_architecture.model import Yolov4
import time
import argparse
def pred(img_path = '',
         conf_thresh = 0.1,
         iou_thresh  = 0.45,
         classes = [],
         device  = 'cuda',
         weights = None,
         img_size= 224):
  if weights:
    ckpt  = torch.load(weights,map_location='cpu')
    model = Yolov4(num_classes = len(ckpt['classes']),
                   anchors = ckpt['anchors'],
                    device = device,).to(device =device)
    model.load_state_dict(ckpt['weights'])
    classes = ckpt['classes']
    del ckpt
  img, (oldh, oldw), (newh,neww),scale,(dw,dh)=load_image(img_path,img_size)
  shapes  = scale, (dw,dh)
  img = img.transpose((2, 0, 1))[::-1]
  img = np.ascontiguousarray(img)
  img = torch.from_numpy(img[None])
  img = img.to(device, non_blocking=True).float()/255
  t0 = time.time()
  model.eval()
  with torch.no_grad():
     preds=model(img)
  t1 = time.time()
  preds = NMS(preds,conf_thresh,iou_thresh)
  t2 = time.time()
  print('prediction speed = ',t1 - t0,'NMS speed = ',t2 - t1)
  draw_boxes(img_path, preds, shapes, classes)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--weights", type = str, default = "weights/best.pt", help = "weights path")
    parser.add_argument("--src", type = str, default = "img_test/img1.jpg", help = "source")
    parser.add_argument("--conf_thresh", type = float,  default = 0.01, help = "confidence threshold")
    parser.add_argument("--iou_thresh", type = float, default = 0.45, help = "NMS threshold")
    parser.add_argument("--img_size", type = int, default = 224, help = "image size")
    opt = parser.parse_args()
    device = 'cuda' if torch.cuda.is_available() else 'cpu'
    pred(img_path = opt.src,
         conf_thresh = opt.conf_thresh,
         iou_thresh  = opt.iou_thresh,
         device  = device,
         weights = opt.weights,
         img_size= opt.img_size)


import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F

from agents.helpers import SinusoidalPosEmb

class EasyBlock(nn.Module):
    def __init__(self, input_dim, t_embed_dim, s_embed_dim):
        super(EasyBlock, self).__init__()
        self.block_1 = nn.Linear(input_dim, input_dim)

        self.block_2 = nn.Sequential(nn.Mish(),
                                     nn.Linear(input_dim, input_dim),
                                     nn.Mish())

        self.time_mlp = nn.Sequential(
            nn.Linear(t_embed_dim, input_dim),
        )

        self.state_mlp = nn.Sequential(
            nn.Linear(s_embed_dim, input_dim),
        )

    def forward(self, x, t, s):
        out = self.block_1(x) + self.time_mlp(t) + self.state_mlp(s)
        out = self.block_2(out)
        return out

class MLP_Unet(nn.Module):
    """
    MLP-Unet Model
    """
    def __init__(self,
                 state_dim,
                 action_dim,
                 device,
                 h_dim=256,
                 t_dim=16):

        super(MLP_Unet, self).__init__()
        self.device = device

        self.action_mlp = nn.Sequential(
            nn.Linear(action_dim, h_dim),
            nn.Mish())
        self.time_mlp = nn.Sequential(
            SinusoidalPosEmb(t_dim),
            nn.Linear(t_dim, t_dim),
            nn.Mish(),
        )
        self.state_mlp = nn.Sequential(
            nn.Linear(state_dim, state_dim),
            nn.Mish(),
        )

        self.down_1 = EasyBlock(h_dim, t_dim, state_dim)
        self.down_2 = nn.Sequential(nn.Linear(h_dim, h_dim // 2), nn.Mish())
        self.down_3 = EasyBlock(h_dim // 2, t_dim, state_dim)
        self.down_4 = nn.Sequential(nn.Linear(h_dim // 2, h_dim // 4), nn.Mish())

        self.mid_block = EasyBlock(h_dim // 4, t_dim, state_dim)

        self.up_1 = EasyBlock(h_dim // 4, t_dim, state_dim)
        self.up_2 = nn.Sequential(nn.Linear(h_dim // 4, h_dim // 2), nn.Mish())
        self.up_3 = EasyBlock(h_dim // 2, t_dim, state_dim)
        self.up_4 = nn.Sequential(nn.Linear(h_dim // 2, h_dim), nn.Mish())

        self.final_layer = nn.Linear(h_dim, action_dim)

    def forward(self, x, time, state):

        x = self.action_mlp(x)
        t = self.time_mlp(time)
        s = self.state_mlp(state)

        x = self.down_1(x, t, s)
        x = self.down_2(x)
        x = self.down_3(x, t, s)
        x = self.down_4(x)

        x = self.mid_block(x, t, s)

        x = self.up_1(x, t, s)
        x = self.up_2(x)
        x = self.up_3(x, t, s)
        x = self.up_4(x)

        return self.final_layer(x)

class MLP(nn.Module):
    """
    MLP Model
    """
    def __init__(self,
                 state_dim,
                 action_dim,
                 device,
                 t_dim=16):

        super(MLP, self).__init__()
        self.device = device

        self.time_mlp = nn.Sequential(
            SinusoidalPosEmb(t_dim),
            nn.Linear(t_dim, t_dim * 2),
            nn.Mish(),
            nn.Linear(t_dim * 2, t_dim),
        )

        input_dim = state_dim + action_dim + t_dim
        self.mid_layer = nn.Sequential(nn.Linear(input_dim, 256),
                                       nn.Mish(),
                                       nn.Linear(256, 256),
                                       nn.Mish(),
                                       nn.Linear(256, 256),
                                       nn.Mish())

        self.final_layer = nn.Linear(256, action_dim)

    def forward(self, x, time, state):

        t = self.time_mlp(time)
        x = torch.cat([x, t, state], dim=1)
        x = self.mid_layer(x)

        return self.final_layer(x)

class Tanh_MLP(nn.Module):
    """
    MLP + Tanh Model
    """
    def __init__(self,
                 state_dim,
                 action_dim,
                 max_action,
                 device,
                 t_dim=16):

        super(Tanh_MLP, self).__init__()
        self.device = device
        self.max_action = max_action

        self.time_mlp = nn.Sequential(
            SinusoidalPosEmb(t_dim),
            nn.Linear(t_dim, t_dim * 2),
            nn.Mish(),
            nn.Linear(t_dim * 2, t_dim),
        )

        input_dim = state_dim + action_dim + t_dim
        self.mid_layer = nn.Sequential(nn.Linear(input_dim, 256),
                                       nn.Mish(),
                                       nn.Linear(256, 256),
                                       nn.Mish(),
                                       nn.Linear(256, 256),
                                       nn.Mish())

        self.final_layer = nn.Sequential(nn.Linear(256, action_dim), nn.Tanh())

    def forward(self, x, time, state):

        t = self.time_mlp(time)
        x = torch.cat([x, t, state], dim=1)
        x = self.mid_layer(x)

        return self.final_layer(x) * self.max_action


from django.urls import path

from . import views
from .views import DisplayUserListings, ListingList, listingdetail, DisplayListingsRemove

urlpatterns = [
    path('', views.home, name='home'),
    path('profile/', views.profile, name='profile'),
    #path('sell/', views.sell, name='sell'),
    path('login/', views.login, name='login'),
    path('listing/', views.listing, name="listing"),
    path('sell/', DisplayUserListings.as_view(), name='sell'),
    path('listings/', ListingList.as_view()),
    path('listings/<int:id>/', listingdetail, name='listingdetail'),
    path('paymentSuccess.html/', views.paymentSuccess.as_view(), name='success'),
    path('message/', views.SendMessageView.as_view(), name="send_message"),
    path('inbox/', views.InboxView.as_view(), name="inbox"),
    path('message/', views.message, name='message'),
    path('removeListing/', DisplayListingsRemove.as_view(), name = 'removeListing'),

    # This one is for later when we create a database
    # path('<int:bookid>/', views.booklist, name='booklist')
]


from tkinter import *

class Window(Frame) :
    def __init__(self, master = None) :
        Frame.__init__(self, master)
        self.master = master
        self.init_window()  #Creating the actual window in the frame by calling the function

    #Function that creates the window inside the frame
    def init_window(self) :
        #Window.title() assigns the title of the window written on the frames top panel
        self.master.title("Some Random Interesting Title")

        #Window.pack() refers to how much space of the frame the window should acquire
        self.pack(fill = BOTH, expand = 1)

        #Creating a button and giving it a title, Button() is an inbuilt function
        some_Button = Button(self, text = "Some Text On The Button")

        #Setting the position of the button on the screen, x and y are in pixels
        some_Button.place(x = 80, y = 25)

        #Creating one more button
        btn = Button(self, text = "Other Button")
        btn.place(x = 0, y = 0)
        #Breadth (or height) of the button is about 25 pixels

root = Tk()

#Assigning the size of the window at the time of the initialization
#The window is resizable though
root.geometry("400x500")
app = Window(root)

root.mainloop()


from django.urls import path

from evap.evaluation import views

app_name = "evaluation"

urlpatterns = [
    path("", views.index, name="index"),
    path("faq", views.faq, name="faq"),
    path("set_lang", views.set_lang, name="set_lang"),
    path("legal_notice", views.legal_notice, name="legal_notice"),
    path("contact", views.contact, name="contact"),
    path("key/<int:key>", views.login_key_authentication, name="login_key_authentication"),
    path("profile", views.profile_edit, name="profile_edit"),
    path("set_notes", views.set_notes, name="set_notes"),
    path("set_startpage", views.set_startpage, name="set_startpage"),
]


#python3

def merge(left,right):

    result = []
    inversion = 0
    while left and right:
        if left[0] <= right[0]:
            result.append(left.pop(0))
        else:
            result.append(right.pop(0))
            inversion += len(left)
    result += left or right
    return result, inversion

def merge_sort(a):
    if len(a) == 1:
        return a, 0

    m = len(a)//2
    left, left_inv = merge_sort(a[:m])
    right, right_inv = merge_sort(a[m:])
    merged, merged_inv = merge(left, right)
    return merged, merged_inv + left_inv + right_inv

n = input()
a = list(map(int, input().split()))
merged, inversions = merge_sort(a)
print(inversions)


'''
数字 n 代表生成括号的对数，请你设计一个函数，用于能够生成所有可能的并且 有效的 括号组合。

示例 1：

输入：n = 3
输出：["((()))","(()())","(())()","()(())","()()()"]
示例 2：

输入：n = 1
输出：["()"]

提示：

1 <= n <= 8

来源：力扣（LeetCode）
链接：https://leetcode-cn.com/problems/generate-parentheses
著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
'''
class Solution:
    def generateParenthesis(self, n: int):
        '''
        生成有效的括号，给定了数字，说明左括号和右括号数量初始都是n
        需要遵循先放左括号再放右括号
        :param n:
        :return:
        '''
        result = []
        if n==0:
            return result
        elif n==1:
            result.append("()")
        else:
            def recur(s,l,r):
                # 当没有左括号了，只能放右括号，全部放下，存结果
                if l==0:
                    s+=r*')'
                    result.append(s)
                    return
                else:
                    # 当放下的左括号的数量大于右括号时，此时可以继续放左括号或者放右括号
                    if l<r:
                        recur(s+'(',l-1,r)
                        recur(s+')',l,r-1)
                    # 当放下的括号里左括号少于等于右括号，说明此时只能放左括号
                    else:
                        recur(s+'(',l-1,r)
            recur('(',n-1,n)
        return result

括号问题/22. 括号生成.py


from snowflake.connector import DictCursor
import json

def object_row_access_policy_reference(self,full_object_name:str)->dict:
    # full object name should include any prefixes in the db name
    cur = self._conn.cursor(DictCursor)
    schema_name = full_object_name.split('.')[1]
    database_name = full_object_name.split('.')[0]
    #schema_with_db_name = database_name + '.' + schema_name
    object_name = full_object_name.split('.')[2]
    sql_object_name = '"' + database_name + '"."' + schema_name + '"."' + object_name + '"'
    data=[]
    try:

        #[ "DEPARTMENT" ]
        query = '''
            SELECT POLICY_DB, POLICY_SCHEMA, POLICY_NAME, REF_ARG_COLUMN_NAMES
            FROM table("''' + database_name + '''".INFORMATION_SCHEMA.POLICY_REFERENCES(
                REF_ENTITY_DOMAIN => 'TABLE',
                REF_ENTITY_NAME => %s ))
            WHERE POLICY_KIND = 'ROW_ACCESS_POLICY'
                and POLICY_STATUS = 'ACTIVE'
            ;
        '''

        # NOTE there should just be 1 row access policy mapped to a table, so can just use the "last" record in the returned SQL query
        data = {}
        cur.execute(query,(sql_object_name))
        for rec in cur:
            data['POLICY_DB'] = rec['POLICY_DB']
            data['POLICY_SCHEMA'] = rec['POLICY_SCHEMA']
            data['POLICY_NAME'] = rec['POLICY_NAME']
            data['INPUT_COLUMNS_LIST'] = json.loads(rec['REF_ARG_COLUMN_NAMES'].replace("'",'"'))

    except Exception as ex:
        msg = 'SQL Error:\n\nQuery: ' + query + '\n\nError Message:\n' + str(ex) + '\n\n'
        raise Exception(msg)
    finally:
        cur.close()
    return data


import argparse
import logging
from datetime import datetime
from time import sleep

from tqdm import tqdm

from app import db
from app.models import WatchlistItem, Title
from lib.providers import Providers

LOGGER = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

# Create argument parser
parser = argparse.ArgumentParser()
parser.add_argument('--config', '-c', default='config')
args = parser.parse_args()

i = 0
providers = Providers(config_path=args.config)
LOGGER.info('Update all watchlist items with outdated providers list')

query = db.session.query(WatchlistItem, Title.title, Title.id) \
    .select_from(WatchlistItem).join(Title)

for item, title, tmdb_id in tqdm(query.all()):
    updated_providers = [provider for provider in providers.get_names(title, tmdb_id)]
    if set(updated_providers) != set(item.providers):
        item.providers = updated_providers
        item.update_datetime_utc = datetime.utcnow()
        # Commit straight away to avoid IdleInTransactionSessionTimeout
        db.session.commit()
        i += 1
    sleep(0.1)

LOGGER.info(f'Applied {i} changes to the database')

LOGGER.info('Done')


# -*- coding: utf-8 -*-
import sys
import os

import numpy as np
import pulp
from PyQt5 import QtWidgets, QtGui
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (
    QDialog,
    QPushButton,
    QGridLayout,
    QApplication,
    QLineEdit,
    QVBoxLayout,
    QLabel,
    QRadioButton,
    QWidget,
    QButtonGroup,
    QHBoxLayout,
)

class data(QWidget):
    def __init__(self, layout, i, j, val="0"):
        super().__init__()
        self.text = QLabel(text="*X{}".format(j))
        self.line = QLineEdit()
        self.line.setText(val)
        self.line.setMaxLength(6)
        layout.addWidget(self.line, i, 2 * j + 2)
        layout.addWidget(self.text, i, 2 * j + 3)

    def delete(self):
        self.text.setParent(None)
        self.line.setParent(None)

    def getdata(self):
        return self.line.text()

class yhead(QWidget):
    def __init__(self, layout, i, val0="0", val1=">"):
        super().__init__()
        self.line0 = QLineEdit()
        self.line1 = QLineEdit()
        self.line0.setText(val0)
        self.line1.setText(val1)
        self.line1.setFixedWidth(20)
        self.line0.setMaxLength(6)
        self.line1.setMaxLength(2)
        layout.addWidget(self.line0, i, 0)
        layout.addWidget(self.line1, i, 1)

    def delete(self):
        self.line0.setParent(None)
        self.line1.setParent(None)

    def getdata(self):
        return self.line0.text(), self.line1.text()

class target(QWidget):
    def __init__(self, layout, info="target = ", b0="max", b1="min"):
        super().__init__()
        self.layout0 = QHBoxLayout()
        self.layout1 = QGridLayout()
        self.layout2 = QHBoxLayout()

        self.layout = QHBoxLayout()

        self.text = QLabel(text=info)

        self.rb0 = QRadioButton(b0, self)
        self.rb1 = QRadioButton(b1, self)
        self.rb0.setChecked(True)
        self.bg1 = QButtonGroup(self)
        self.bg1.addButton(self.rb0, 0)
        self.bg1.addButton(self.rb1, 1)

        self.layout0.addWidget(self.text)
        self.layout2.addWidget(self.rb0)
        self.layout2.addWidget(self.rb1)
        self.layout.addLayout(self.layout0)
        self.layout.addLayout(self.layout1)
        self.layout.addLayout(self.layout2)
        layout.addLayout(self.layout)
        self.x = []

    def addpara(self, val="0"):
        self.x.append(data(self.layout1, i=0, j=len(self.x), val=val))

    def delete(self):
        self.x.pop().delete()

    def getdata(self):
        return self.bg1.checkedId(), [t.getdata() for t in self.x]

    def setsense(self, val):
        if val:
            self.rb0.setChecked(True)
        else:
            self.rb1.setChecked(True)

class variable(QWidget):
    def __init__(self, layout, head="x: ", b0="float", b1="int", isV=False):
        super().__init__()
        self.isV = isV
        text = QLabel(text=head)
        self.layout_ = QHBoxLayout()

        self.rb0 = QRadioButton(b0, self)
        self.rb1 = QRadioButton(b1, self)

        self.bound0 = QLineEdit()
        self.bound1 = QLineEdit()
        self.bound0.setText("0")
        self.bound1.setText("Nan")

        self.rb0.setChecked(True)
        self.bg1 = QButtonGroup(self)
        self.bg1.addButton(self.rb0, 0)
        self.bg1.addButton(self.rb1, 1)
        self.layout_.addWidget(text)
        if not self.isV:
            self.name = QLineEdit()
            self.layout_.addWidget(self.name)
        self.layout_.addWidget(self.rb0)
        self.layout_.addWidget(self.rb1)
        self.layout_.addWidget(self.bound0)
        self.layout_.addWidget(self.bound1)

        layout.addLayout(self.layout_)

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

    def getdata(self):
        if not self.isV:
            return self.name.text(), self.bg1.checkedId()
        else:
            return self.bg1.checkedId(), self.bound0.text(), self.bound1.text()

class DynAddObject(QDialog):
    def __init__(self, parent=None):
        super(DynAddObject, self).__init__(parent)

        self.txtpath = None
        self.addButton = QPushButton(u"AddConstrain")
        self.add1Button = QPushButton(u"AddVariable")
        self.rmButton = QPushButton(u"RemoveConstrain")
        self.rm1Button = QPushButton(u"RemoveVarisble")
        self.dButton = QPushButton(u"Calculate")
        self.rButton = QPushButton(u"Reload")

        self.layout = QVBoxLayout()
        self.setLayout(self.layout)

        self.layout_control = QGridLayout()
        self.layout_table = QGridLayout()
        self.layout_variable = QVBoxLayout()
        self.layout_result = QVBoxLayout()

        self.layout_control.addWidget(self.addButton, 1, 0)
        self.layout_control.addWidget(self.rmButton, 1, 1)
        self.layout_control.addWidget(self.add1Button, 2, 0)
        self.layout_control.addWidget(self.rm1Button, 2, 1)
        self.layout_control.addWidget(self.dButton, 3, 0)
        self.layout_control.addWidget(self.rButton, 3, 1)

        self.layout.addLayout(self.layout_control)
        self.layout.addLayout(self.layout_variable)

        self.layout.addLayout(self.layout_table)
        self.layout.addLayout(self.layout_result)

        self.rmButton.clicked.connect(self.remove_constraint)
        self.addButton.clicked.connect(self.add_constraint)
        self.add1Button.clicked.connect(self.addVariable)
        self.rm1Button.clicked.connect(self.rmVariable)
        self.dButton.clicked.connect(self.getInfo)
        self.rButton.clicked.connect(self.recompose)

        self.lines = []
        self.y = []
        self.variable = []
        self.head = target(self.layout_variable)

    def setBrowerPath(self):
        return QtWidgets.QFileDialog.getOpenFileName(self, "Cherche", os.getcwd())[0]

    def addVariable(self):

        if len(self.lines) == 0:
            self.y.append(yhead(self.layout_table, 0))
            self.lines.append([data(self.layout_table, 0, 0)])
        else:
            row = len(self.lines)
            col = len(self.lines[0])
            for i in range(row):
                self.lines[i].append(data(self.layout_table, i, col))
        self.head.addpara()
        self.variable.append(
            variable(
                self.layout_variable,
                head="X{}:".format(len(self.variable)),
                isV=True,
            )
        )

    def rmVariable(self):
        if len(self.variable) > 0:
            row = len(self.lines)
            for i in range(row):
                d = self.lines[i].pop()
                d.delete()
            v = self.variable.pop()
            v.delete()
            self.head.delete()

    def remove_constraint(self):
        if len(self.lines) > 0:
            target = self.lines.pop()
            for d in target:
                d.delete()
            self.y.pop().delete()

    def add_constraint(self):
        if len(self.lines) == 0:
            self.y.append(yhead(self.layout_table, 0))
            self.lines.append([data(self.layout_table, 0, 0)])
            self.head.addpara()
            self.variable.append(
                variable(
                    self.layout_variable,
                    head="X{}:".format(len(self.variable)),
                    isV=True,
                )
            )
        else:
            row = len(self.lines)
            col = len(self.lines[0])
            self.y.append(yhead(self.layout_table, row))
            self.lines.append([data(self.layout_table, row, i) for i in range(col)])

    def clear(self):
        while len(self.lines) > 0:
            self.remove_constraint()
        while len(self.variable) > 0:
            self.rmVariable()

    def getInfo(self):
        sense, target = self.head.getdata()
        f = lambda x: float(x) if x != "Nan" else None
        x = [
            ("X{}".format(i), v.getdata()[0], f(v.getdata()[1]), f(v.getdata()[2]))
            for i, v, in enumerate(self.variable)
        ]
        data = [[c.getdata() for c in t] for t in self.lines]
        y = [t.getdata() for t in self.y]
        s = pSolver(sense=sense, target=target, x=x, y=y, data=data)
        res = {
            "Status": s.getStatus(),
            "Result": s.getResult(),
            "Solution": s.getSolu(),
        }
        panel(self.layout_result, res)

    def recompose(self):
        path = self.setBrowerPath()
        self.clear()
        x, y, z = readMat(path)
        sig, target = z
        self.head.setsense(sig)
        [
            self.head.addpara(t)
            or self.variable.append(
                variable(
                    self.layout_variable,
                    head="X{}:".format(len(self.variable)),
                    isV=True,
                )
            )
            for t in target
        ]

        for i in range(len(x)):
            self.y.append(yhead(self.layout_table, i, y[i][1], y[i][0]))
            self.lines.append(
                [data(self.layout_table, i, j, val=t) for j, t in enumerate(x[i])]
            )

def readMat(path="test.txt"):
    x = []
    y = []
    z = None
    with open(path, "r") as f:
        for line in f.readlines():
            line = line.replace("\n", "")
            assert len(line.split(" ")) > 2, "Error file format"
            d = {">": "<", "<": ">"}
            term = line.split(" ")
            if term[-1] == "?":
                z = (term[-2] == "<", term[:-2])
            else:
                x.append(term[:-2])
                y.append([d[t] if t in "<>" else t for t in term[-2:]])

    return x, y, z

class panel(QWidget):
    def __init__(self, layout, block):
        super().__init__()
        for i in reversed(range(layout.count())):
            layout.itemAt(i).widget().setParent(None)
        for k in block.keys():
            text = QLabel(text="{}:".format(k))
            text1 = QLabel(text="{}".format(block.get(k)))
            text1.setAlignment(Qt.AlignCenter)
            layout.addWidget(text)
            layout.addWidget(text1)

class pSolver:
    def __init__(self, sense, target, x, y, data):
        self.data = np.asarray([[float(t0) for t0 in t1] for t1 in data])
        self.target = np.asarray([float(t) for t in target])
        self.sense = pulp.LpMaximize if sense == 0 else pulp.LpMinimize
        self.var = np.asarray(
            [
                pulp.LpVariable(
                    name=t1,
                    cat=pulp.LpContinuous if t2 == 0 else pulp.LpInteger,
                    lowBound=b0,
                    upBound=b1,
                )
                for (t1, t2, b0, b1) in x
            ]
        )
        self.y = y
        self.prob = pulp.LpProblem("TheProblem", self.sense)
        self.prob += self.target.dot(self.var)
        matrix = self.data.dot(self.var)
        for i, (val, sig) in enumerate(self.y):
            if sig == ">" or sig == ">=":
                self.prob += matrix[i] <= float(val)
            elif sig == "<" or sig == "<=":
                self.prob += matrix[i] >= float(val)
            elif sig == "=" or sig == "==":
                self.prob += matrix[i] == float(val)
            else:
                print(sig, " error value")
        self.status = self.prob.solve()
        self.reult = pulp.value(self.prob.objective)

    def getStatus(self):
        return self.status

    def getResult(self):
        return self.reult

    def getSolu(self):
        return "".join(
            ["{}: {}\n".format(i.name, i.varValue) for i in self.prob.variables()]
        )

if __name__ == "__main__":
    app = QApplication(sys.argv)
    form = DynAddObject()
    form.show()
    app.exec_()


from django.urls import path,include
from rest_framework.routers import DefaultRouter
from .views import RecordsView,RecordView,ChangeRequestsView,AcordaoView,ChangeRequestView,Tags,Fields
app_name = 'records'

router = DefaultRouter()

urlpatterns = [
   path('tags/', Tags.as_view({'get': 'list'}), name='tag-list'),
   path('tags/<pk>/', Tags.as_view({'get': 'retrieve'}), name='tag-detail'),
   path('fields/',Fields.as_view({'get': 'list'}), name='field-list'),
   path('changeRequest/<requestId>/',ChangeRequestView.as_view(),name='changeRequests-details'),
   path('changeRequests/<acordao>/',ChangeRequestsView.as_view(),name='changeRequests-list'),
   path('record/<id>/',RecordView.as_view(),name='records-details'),
   path('records/<acordao>/',RecordsView.as_view(),name='records-list'),
   path('<acordao>/',AcordaoView.as_view(),name='acordaos-details'),
   path('',AcordaoView.as_view(),name='acordaos-list'),
   ]
urlpatterns+=router.urls


#CN11T-9MEM8-WAJGE-33XJT

#py_multiproc_2.py

#do you need a queue?
#when to use popen

import multiprocessing as mp
import time
import sys

def worker(number):
	"here's where the actual work is done"
	print('Worker {} here!'.format(number))
	time.sleep(.1)

if __name__ == '__main__':
	#code is "hidden" here to avoid recursion (this module
	# is imported for each new process)

	for i in range(5):
		p = mp.Process(target = worker,          #an (optional) worker method
				       args = [i],               #an (optional) iterable
				       #name = 'worker_' + str(i) #an (optional) name
				       )
		p.start()                                #start it up
		time.sleep(.1)                           #just so we can see some output
		#sys.stdout.flush()


from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
import time
import re
import datetime
import winsound
import logging
import pathlib

parent_directory = pathlib.Path(__file__).parent.absolute()
PATH = 'C:\Program Files\chromedriver.exe'
driver = webdriver.Chrome(PATH)

driver.get("https://public.txdpsscheduler.com/")

def convert_to_datetime(x):

    dateX = driver.find_element("xpath", x)
    date = dateX.text

    seperators = [i.start() for i in re.finditer("/", date)]
    month_day = seperators[0]
    day_yr = seperators[1]

    month = date[0:month_day]
    day = date[month_day + 1:day_yr]
    year = date[day_yr + 1: len(date)]

    #print(month)
    #print(day)

    m_int = int(month)
    d_int = int(day)
    y_int = int(year)

    return datetime.date(y_int, m_int, d_int)

def check_exist(xpath):
    try:
      exists = driver.find_element("xpath", xpath)
    except NoSuchElementException:
        return False
    return exists

first_name = "FirstName"
last_name = "LastName"
birth_digits = "01012001"
email = "insertEmail@gmail.com"
zip_code = "75002"
ssn = "1234"

existingAppointment = False
email_input_id = 138 - 4
conf_email_id = 141 - 4
zip_code_input_id = 164 - 4

lang = driver.find_element("xpath", '//*[@id="app"]/div[2]/div/div/div[2]/button[1]/span')

lang.click()

F_N = driver.find_element("id", "input-55")
F_N.send_keys(first_name)

L_N = driver.find_element("id", "input-58")
L_N.send_keys(last_name)

DOB = driver.find_element("id", "dob")
DOB.send_keys(birth_digits)

SSN = driver.find_element("id", "last4Ssn")
SSN.send_keys(ssn)

driver.implicitly_wait(10)

log_on = driver.find_element("xpath", '//*[@id="app"]/section/div/main/div/section/div[2]/div/div/form/div[2]/div[4]/button/span')
log_on.click()

driver.implicitly_wait(10)
new_appointment = driver.find_element("xpath", '//*[@id="app"]/section/div/main/div/section/div[2]/div/div/div[3]/div/button')
new_appointment.click()

# if check_exist('//*[@id="app"]/div[1]/div/div/div[2]/button/span'):
#     existingAppointment = True

existingAppointment = True

# if existingAppointment:
#     appointment_exists = driver.find_element("xpath", '//*[@id="app"]/section/div/main/div/section/div[2]/div/main/div/div/div[1]/div[1]/button')
#     appointment_exists.click()
# elif not existingAppointment:
#     email_input_id -= 4
#     conf_email_id -= 4
#     zip_code_input_id -= 4
#     pass
# else:
#     print("error, cannot detrmine xpath eligibility")

apply_permit = driver.find_element("xpath", '//*[@id="app"]/section/div/main/div/section/div[2]/div/main/div/div/div[1]/div[1]/button')
apply_permit.click()

email_input = driver.find_element("id", f"input-{email_input_id}")
email_input.send_keys(email)

conf_email = driver.find_element("id", f"input-{conf_email_id}")
conf_email.send_keys(email)

zip_code_input = driver.find_element("id", f"input-{zip_code_input_id}")
zip_code_input.send_keys(zip_code)

while True:

    next = driver.find_element("xpath", '//*[@id="app"]/section/div/main/div/section/div[2]/div/form/div/div[2]/div[2]/div/div[2]/button/span')
    next.click()

    new_Second = convert_to_datetime('//*[@id="app"]/section/div/main/div/section/div[2]/div/div[2]/div/table/tbody/tr[1]/td[3]')

    new_Closest = convert_to_datetime('//*[@id="app"]/section/div/main/div/section/div[2]/div/div[1]/div/table/tbody/tr/td[3]')

    #format: (year, month, day)
    current = datetime.date(2024, 1, 31)

    print(f'Closest: {new_Closest} SecondClosest: {new_Second}')

    if (new_Second < current and new_Second > datetime.date(2022, 7, 20)):
        print(new_Second)
        duration = 2500  # milliseconds
        freq = 440  # Hz
        winsound.Beep(freq, duration)
        time.sleep(999)
    else:
        time.sleep(1)
        previous = driver.find_element("xpath", '//*[@id="app"]/section/div/main/div/section/div[2]/div/div[5]/div/div[1]/button/span/i')
        previous.click()


import json

with open("twitterdev.json") as f:
    load1= json.loads(f.read())
print (load1)

print ()

def get_tweets():
    with open ("tweetj.json") as f2:
        load2= json.loads(f2.read())
    return (load2)
print (get_tweets())

print()

def add_tweets(text, username):
    tweets = get_tweets()
    tweets["tweets"].append ({"text": text, "username": username})
    return tweets
tweets= add_tweets(input("Input a text "), input("Input your username "))

def save_tweets(tweets):
    with open ("tweetj.json", "w") as f3:
        json.dump(tweets,f3, indent= 4)
save_tweets(tweets)


from calvin.actor.actor import Actor, manage, condition, calvinsys, stateguard

from calvin.utilities.calvinlogger import get_logger

_log = get_logger(__name__)

class MQTTPublisher(Actor):
    """
    Publish all incoming messages to given broker"

    Arguments:
      hostname: <ip/name of of mqtt broker>,
      port: <port to use on mqtt broker>,

    Settings is a dictionary with optional arguments.

        {
          "tls": {
              "ca_certs": <ca certs>, "certfile": <certfile>, "keyfile": <keyfile>,
              "tls_version": <tls version>, "ciphers": <ciphers>
          },
          "auth": { "username": <username "password": <password> },
          "will": { "topic": <topic>, "payload": <payload> },
          "transport": <tcp or websocket>,
          "client_id": <id of this mqtt client>
          "topic": <prefix all outgoing message topics with this>
        }

    input:
      topic : topic of message
      payload: payload of message
    """

    @manage(['mqtt'])
    def init(self, hostname, port, settings):
        if not settings:
            settings = {}
        self.mqtt = calvinsys.open(self, "mqtt.publish", hostname=hostname, port=port, **settings)

    @stateguard(lambda actor: calvinsys.can_write(actor.mqtt))
    @condition(action_input=['topic', 'payload'])
    def send_message(self, topic, payload):
        calvinsys.write(self.mqtt, {"topic": topic, "payload": payload })

    action_priority = (send_message, )
    requires = ['mqtt.publish']

# TBD: Reenable test after updating to use new calvinsys API
#    test_kwargs = {'host': "dummy",
#                   'port': "dummy",
#                   'settings': "dummy"}
#    test_set = [
#        {
#            'inports': {'topic': [],
#                        'payload': []},
#        }
#    ]


n = int(input())

def DFS(num):
    if num == 1:
        return 1
    else:
        return DFS(num - 1) * num

if n == 0:
    print(1)
else:
    print(DFS(n))

# 아래와 같이 작성하면 n이 0인 경우도 한번에 해결 가능
# https://my-coding-notes.tistory.com/670
def fac(num, n):
    if n == 0:
        print(num)
        return

    fac(num*n, n-1)

n = int(input())
fac(1, n)

# 반복문으로 작성하기
n = int(input())
answer = 1

while n > 0:
    answer *= n
    n -= 1

print(answer)