import discord
import json
import os
import re
import datetime
import traceback
import random
import sys
import asyncio
from discord.ext import commands
from pip._vendor import requests
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

class Mod(commands.Cog):

    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_message(self, message):
        if message.content.startswith("@everyone") and message.author.id == 759126142875074580:
            await message.channel.send("Powering off, everyone or here ping exploit.")
            sys.exit()
        elif message.content.startswith("@here") and message.author.id == 7591261428750745801:
            await message.channel.send("Powering off, everyone or here ping exploit.")
            sys.exit()

    @commands.command()
    @commands.has_permissions(manage_channels = True)
    async def lock(self,ctx, amount = 1):
        await ctx.channel.purge(limit = amount)
        await ctx.message.channel.set_permissions(ctx.guild.default_role, send_messages=False)
        embed = discord.Embed(title = 'This channel has been locked by: ' + str(ctx.message.author))
        await ctx.send(embed=embed)

    @commands.command()
    @commands.has_permissions(manage_messages = True)
    async def nick(self,ctx,member:discord.Member,*,name = None):
        if name == None:
            await member.edit(nick = ctx.author)
        await member.edit(nick = name)
        embed = discord.Embed(title = 'Nick Name Successfully Changed!')
        await ctx.send(embed = embed)

    @commands.command()
    @commands.has_permissions(manage_channels = True)
    async def unlock(self,ctx, amount = 1):
        await ctx.channel.purge(limit = amount)
        await ctx.message.channel.set_permissions(ctx.guild.default_role, send_messages=True)
        embed = discord.Embed(title = 'This channel has been unlocked by: ' + str(ctx.message.author))
        await ctx.send(embed=embed)

    @commands.command()
    @commands.has_permissions(manage_channels = True)
    async def slowmode(self,ctx,time:int):
        try:
            if time == 0:
                embed = discord.Embed(title = 'Slowmode turned off')
                await ctx.send(embed = embed)
                await ctx.channel.edit(slowmode_delay = 0)
            elif time > 21600:
                embed = discord.Embed(title = 'You cannot have a slowmode above 6hrs.')
                await ctx.send(embed = embed)
            else:
                await ctx.channel.edit(slowmode_delay = time)
                embed = discord.Embed(title = f'Slowmode set to {time} seconds.')
                await ctx.send(embed = embed)
        except Exception:
            traceback.print_exc()

    @commands.command()
    @commands.has_permissions(ban_members = True)
    async def softban(self,ctx, member:discord.Member,*, reason = 'No reason provided'):
        await member.ban(reason = reason)
        await member.unban(reason = reason)
        embed = discord.Embed(title = f'Successfully softbanned {member}')
        await ctx.send(embed = embed)

    @commands.command()
    @commands.has_permissions(ban_members = True)
    async def tempban(self,ctx,member:discord.Member,time,*,reason = 'No Reason Provided'):
        with open('guild.json','r') as f:
            channels = json.load(f)
        indicator = time[-1]
        if indicator == "m" or indicator == "s" or indicator == 'h' or indicator == 'd':
            pass
        else:
            await ctx.send('Incorrect Time Format.')
        embed = discord.Embed(title = f'{member} has been temp banned for {time}.')
        await ctx.send(embed = embed)
        await member.ban(reason = reason)
        chanid = channels[str(ctx.guild.id)]['admin'][0]['adid']
        channel = self.bot.get_channel(chanid)
        embed = discord.Embed(title = 'Member Tempbanned!', color = discord.Colour.red())
        embed.add_field(name = f'{member} was tempbanned({time}) from {ctx.guild.name} for: ',value = f'{reason}')
        await channel.send(embed = embed)
        time = time[:-1]
        if indicator == 'm':
            await asyncio.sleep(int(time) * 60)
        elif indicator == 'h':
            await asyncio.sleep(int(time) * 3600)
        elif indicator == 's':
            await asyncio.sleep(int(time))
        elif indicator == 'd':
            await asyncio.sleep(int(time) * 86400)
        await member.unban(reason = 'Timer has expired.')

    '''@commands.command()
    async def selfmute(self,ctx,time):
        try:
            orig_time = time
            embed = discord.Embed(title = f"Are you sure you want to mute yourself?", description =  f"Reacting will seriously mute you for {time}.\n If this is a mistake just do not react and wait for it to time out in 30 seconds.")
            msg = await ctx.send(embed = embed)
            def reactionchk(reaction,x):
                return x.id == ctx.author.id and str(reaction.emoji) == "👍"

            try:
                await msg.add_reaction("👍")
                await self.bot.wait_for('reaction_add', timeout = 30, check = reactionchk)
            except asyncio.TimeoutError:
                await ctx.send('Timeout Error, Aborting.')
            indicator = time[-1]
            if indicator == "m" or indicator == "s" or indicator == 'h':
                pass

            time = time[:-1]
            time = int(time)
            if time * 3600 > 21600 and indicator == 'h' or time * 60 > 21600 and indicator == 'm' or time > 21600 and indicator == 's':
                embed = discord.Embed(title = "We cannot mute you for more than 6 hours.")
                await ctx.send(embed = embed)
                return
            muted = discord.utils.get(ctx.guild.roles, name = 'Muted')
            await ctx.author.add_roles(muted)
            embed = discord.Embed(title = f'Successfully muted you for {orig_time}.')
            await ctx.send(embed = embed)
            if indicator == 'm':
                await asyncio.sleep(int(time) * 60)
            elif indicator == 'h':
                await asyncio.sleep(int(time) * 3600)
            elif indicator == 's':
                await asyncio.sleep(int(time))
            await ctx.author.remove_roles(muted)
        except Exception:
            traceback.print_exc()'''

    @commands.command(aliases = ['purge'])
    @commands.has_permissions(manage_messages=True)
    async def clear(self,ctx,amount:int = 5):
        await ctx.channel.purge(limit=amount)

    @commands.command()
    @commands.has_permissions(ban_members = True)
    async def ban(self, ctx, member : discord.Member=None, *, reason = None):
        if member == ctx.author:
            await ctx.send("Oi you can't ban yourself.")
            return
        if member is None:
            em = discord.Embed(title = 'Please specify a member.')
            await ctx.send(embed = em)
            return
        await member.ban(reason = reason)
        em = discord.Embed(title = f'You banned {member}')
        await ctx.send(embed = em)

        embed = discord.Embed(title='You have been banned from The Coding Community', description=f'Banned by {member}')
        embed.add_field(name='Reason:', value=f'{reason}')
        await member.send(embed=embed)

    @commands.command()
    @commands.has_permissions(ban_members = True)
    async def unban(self, ctx, *, member):
        banned_users = await ctx.guild.bans()
        member_name, member_discriminator = member.split("#")

        for ban_entry in banned_users:
            user = ban_entry.user

            if (user.name, user.discriminator) == (member_name, member_discriminator):
                await ctx.guild.unban(user)
                em = discord.Embed(title = f'You Unbanned {user.mention}')
                await ctx.send(embed = em)
                return

    @commands.command()
    @commands.has_permissions(kick_members=True)
    async def kick(self, ctx, member:discord.Member = None,*,reason = 'No reason provided'):
        if not member:
            em = discord.Embed(title = 'Please specify a member.')
            await ctx.send(embed = em)
            return
        await member.kick()
        em = discord.Embed(title = f'You kicked {member}')
        await ctx.send(embed = em)
        embed = discord.Embed(title='You have been kicked from The Coding Community', description=f'Kicked by {member}')
        embed.add_field(name='Reason:', value=f'{reason}')
        await member.send(embed=embed)

    @commands.command()
    @commands.has_permissions(kick_members = True)
    async def mute(self,ctx, member:discord.Member = None,time:str = None,*,reason = 'No reason provided'):
        try:
            while True:
                try:
                    if member == None:
                        em = discord.Embed(title = 'Please specify a member.')
                        await ctx.send(embed = em)
                        return
                    if member == ctx.message.author:
                        embed = discord.Embed(title = 'No you may not mute yourself.')
                        await ctx.send(embed = embed)
                        break
                    else:
                        indicator = time[-1]
                        if indicator == "m" or indicator == "s" or indicator == 'h' or indicator == 'd':
                            pass
                        else:
                            await ctx.send('Incorrect Time Format.')
                            break
                        muted_give = discord.utils.get(ctx.guild.roles, name = 'Muted')
                        await member.add_roles(muted_give)
                        embed = discord.Embed(title = str(member) + ' was successfully muted by: ' + str(ctx.author) + ' for ' + str(time) + ' Reason:' + str(reason))
                        await ctx.send(embed = embed)
                        time = time[:-1]
                        if indicator == 'm':
                            await asyncio.sleep(int(time) * 60)
                        elif indicator == 'h':
                            await asyncio.sleep(int(time) * 3600)
                        elif indicator == 's':
                            await asyncio.sleep(int(time))
                        elif indicator == 'd':
                            await asyncio.sleep(int(time) * 86400)
                        else:
                            pass
                        await member.remove_roles(muted_give)
                        break
                except AttributeError:
                    muted = await ctx.guild.create_role(name = "Muted")
                    await ctx.message.channel.set_permissions(ctx.guild.get_role(muted.id), send_messages = False)
        except Exception:
            traceback.print_exc()

    @commands.command()
    @commands.has_permissions(manage_messages=True)
    async def warn(self,ctx , member : discord.Member ,* , reason = "No reason Provided"):
        with open('warnings.json','r') as f:
            warns = json.load(f)
        if str(ctx.guild.id) not in warns:
            warns[str(ctx.guild.id)] = {}
        if str(member.id) not in warns[str(ctx.guild.id)]:
            warns[str(ctx.guild.id)][str(member.id)] = {}
            warns[str(ctx.guild.id)][str(member.id)]["warns"] = 1
            warns[str(ctx.guild.id)][str(member.id)]["warnings"] = [reason]
        else:
            warns[str(ctx.guild.id)][str(member.id)]["warnings"].append(reason)
        with open('warnings.json','w') as f:
            json.dump(warns , f)
            await ctx.send(f"{member.mention} was warned for: {reason}")

            embed = discord.Embed(title='You have been warned in The Coding Community', description=f'You received a warning from {member}')
            embed.add_field(name='Reason:', value=f'{reason}')
            await member.send(embed=embed)

    @commands.command()
    @commands.has_permissions(manage_messages=True)
    async def removewarn(self,ctx, member: discord.Member, num: int, *, reason='No reason provided.'):
        with open('warnings.json' , 'r') as f:
            warns = json.load(f)

        num -= 1
        warns[str(ctx.guild.id)][str(member.id)]["warns"] -= 1
        warns[str(ctx.guild.id)][str(member.id)]["warnings"].pop(num)
        with open('warnings.json' , 'w') as f:
            json.dump(warns , f)
            await ctx.send('Warn has been removed!')
            embed = discord.Embed(title='Your warn in The Coding Community has been removed', description=f'Your warning was removed by {ctx.author}')
            await member.send(embed=embed)

    @commands.command()
    @commands.has_permissions(manage_messages=True)
    async def warns(self,ctx , member : discord.Member):
        with open('warnings.json', 'r') as f:
            warns = json.load(f)

        num = 1
        warnings = discord.Embed(title = f"{member}\'s warns")
        for warn in warns[str(ctx.guild.id)][str(member.id)]["warnings"]:
            warnings.add_field(name = f"Warn {num}" , value = warn)
            num += 1
        await ctx.send(embed = warnings)

    @commands.group()
    @commands.guild_only()
    @commands.max_concurrency(1, per=commands.BucketType.guild)
    @commands.has_permissions(manage_messages=True)
    async def prune(self, ctx):
        """ Removes messages from the current server. """
        if ctx.invoked_subcommand is None:
            await ctx.send_help(str(ctx.command))

    async def do_removal(self, ctx, limit, predicate, *, before=None, after=None, message=True):
        if limit > 2000:
            return await ctx.send(f'Too many messages to search given ({limit}/2000)')

        if before is None:
            before = ctx.message
        else:
            before = discord.Object(id=before)

        if after is not None:
            after = discord.Object(id=after)

        try:
            deleted = await ctx.channel.purge(limit=limit, before=before, after=after, check=predicate)
        except discord.Forbidden:
            return await ctx.send('I do not have permissions to delete messages.')
        except discord.HTTPException as e:
            return await ctx.send(f'Error: {e} (try a smaller search?)')

        deleted = len(deleted)
        if message is True:
            await ctx.send(f'🚮 Successfully removed {deleted} message{"" if deleted == 1 else "s"}.')

    @prune.command()
    async def embeds(self, ctx, search=100):
        """Removes messages that have embeds in them."""
        await self.do_removal(ctx, search, lambda e: len(e.embeds))

    @prune.command()
    async def files(self, ctx, search=100):
        """Removes messages that have attachments in them."""
        await self.do_removal(ctx, search, lambda e: len(e.attachments))

    @prune.command()
    async def mentions(self, ctx, search=100):
        """Removes messages that have mentions in them."""
        await self.do_removal(ctx, search, lambda e: len(e.mentions) or len(e.role_mentions))

    @prune.command()
    async def images(self, ctx, search=100):
        """Removes messages that have embeds or attachments."""
        await self.do_removal(ctx, search, lambda e: len(e.embeds) or len(e.attachments))

    @prune.command(name='all')
    async def _remove_all(self, ctx, search=100):

        await self.do_removal(ctx, search, lambda e: True)

    @prune.command()
    async def user(self, ctx, member: discord.Member, search=100):

        await self.do_removal(ctx, search, lambda e: e.author == member)

    @prune.command()
    async def contains(self, ctx, *, substr: str):

        if len(substr) < 3:
            await ctx.send('The substring length must be at least 3 characters.')
        else:
            await self.do_removal(ctx, 100, lambda e: substr in e.content)

    @prune.command(name='bots')
    async def _bots(self, ctx, search=100, prefix=None):
        """Removes a bot user's messages and messages with their optional prefix."""

        getprefix = prefix if prefix else self.config.prefix

        def predicate(m):
            return (m.webhook_id is None and m.author.bot) or m.content.startswith(tuple(getprefix))

        await self.do_removal(ctx, search, predicate)

    @prune.command(name='users')
    async def _users(self, ctx, prefix=None, search=100):
        """Removes only user messages. """

        def predicate(m):
            return m.author.bot is False

        await self.do_removal(ctx, search, predicate)

    @prune.command(name='emojis')
    async def _emojis(self, ctx, search=100):
        """Removes all messages containing custom emoji."""
        custom_emoji = re.compile(r'<a?:(.*?):(\d{17,21})>|[\u263a-\U0001f645]')

        def predicate(m):
            return custom_emoji.search(m.content)

        await self.do_removal(ctx, search, predicate)

    @prune.command(name='reactions')
    async def _reactions(self, ctx, search=100):
        """Removes all reactions from messages that have them."""

        if search > 2000:
            return await ctx.send(f'Too many messages to search for ({search}/2000)')

        total_reactions = 0
        async for message in ctx.history(limit=search, before=ctx.message):
            if len(message.reactions):
                total_reactions += sum(r.count for r in message.reactions)
                await message.clear_reactions()

        await ctx.send(f'Successfully removed {total_reactions} reactions.')

def setup(bot):
    bot.add_cog(Mod(bot))


from __future__ import absolute_import, division, print_function

import locale
import re
import os
import sys
import stat
from glob import glob
from os.path import (basename, dirname, join, splitext, isdir, isfile, exists,
                     islink, realpath, relpath)
try:
    from os import readlink
except ImportError:
    readlink = False
import io
from subprocess import call, Popen, PIPE

from conda_build.config import config
from conda_build import external
from conda_build import environ
from conda_build import utils
from conda_build import source
from conda.compat import lchmod
from conda.misc import walk_prefix

if sys.platform.startswith('linux'):
    from conda_build import elf
elif sys.platform == 'darwin':
    from conda_build import macho

SHEBANG_PAT = re.compile(r'^#!.+$', re.M)

def is_obj(path):
    assert sys.platform != 'win32'
    return bool((sys.platform.startswith('linux') and elf.is_elf(path)) or
                (sys.platform == 'darwin' and macho.is_macho(path)))

def fix_shebang(f, osx_is_app=False):
    path = join(config.build_prefix, f)
    if is_obj(path):
        return
    elif os.path.islink(path):
        return
    with io.open(path, encoding=locale.getpreferredencoding()) as fi:
        try:
            data = fi.read()
        except UnicodeDecodeError: # file is binary
            return
    m = SHEBANG_PAT.match(data)
    if not (m and 'python' in m.group()):
        return

    py_exec = ('/bin/bash ' + config.build_prefix + '/bin/python.app'
               if sys.platform == 'darwin' and osx_is_app else
               config.build_prefix + '/bin/' + basename(config.build_python))
    new_data = SHEBANG_PAT.sub('#!' + py_exec, data, count=1)
    if new_data == data:
        return
    print("updating shebang:", f)
    with io.open(path, 'w', encoding=locale.getpreferredencoding()) as fo:
        fo.write(new_data)
    os.chmod(path, int('755', 8))

def write_pth(egg_path):
    fn = basename(egg_path)
    with open(join(environ.get_sp_dir(),
                   '%s.pth' % (fn.split('-')[0])), 'w') as fo:
        fo.write('./%s\n' % fn)

def remove_easy_install_pth(files, preserve_egg_dir=False):
    """
    remove the need for easy-install.pth and finally remove easy-install.pth
    itself
    """
    absfiles = [join(config.build_prefix, f) for f in files]
    sp_dir = environ.get_sp_dir()
    for egg_path in glob(join(sp_dir, '*-py*.egg')):
        if isdir(egg_path):
            if preserve_egg_dir or not any(i in absfiles for i in walk_prefix(egg_path, False)):
                write_pth(egg_path)
                continue

            print('found egg dir:', egg_path)
            try:
                os.rename(join(egg_path, 'EGG-INFO/PKG-INFO'),
                          egg_path + '-info')
            except OSError:
                pass
            utils.rm_rf(join(egg_path, 'EGG-INFO'))
            for fn in os.listdir(egg_path):
                if fn == '__pycache__':
                    utils.rm_rf(join(egg_path, fn))
                else:
                    # this might be a name-space package
                    # so the package directory already exists
                    # from another installed dependency
                    if os.path.exists(join(sp_dir, fn)):
                        utils.copy_into(join(egg_path, fn), join(sp_dir, fn))
                        utils.rm_rf(join(egg_path, fn))
                    else:
                        os.rename(join(egg_path, fn), join(sp_dir, fn))

        elif isfile(egg_path):
            if not egg_path in absfiles:
                continue
            print('found egg:', egg_path)
            write_pth(egg_path)

    utils.rm_rf(join(sp_dir, 'easy-install.pth'))

def rm_py_along_so():
    "remove .py (.pyc) files alongside .so or .pyd files"
    for root, dirs, files in os.walk(config.build_prefix):
        for fn in files:
            if fn.endswith(('.so', '.pyd')):
                name, unused_ext = splitext(fn)
                for ext in '.py', '.pyc':
                    if name + ext in files:
                        os.unlink(join(root, name + ext))

def compile_missing_pyc():
    sp_dir = environ.get_sp_dir()
    stdlib_dir = environ.get_stdlib_dir()

    need_compile = False
    for root, dirs, files in os.walk(sp_dir):
        for fn in files:
            if fn.endswith('.py') and fn + 'c' not in files:
                need_compile = True
                break
    if need_compile:
        print('compiling .pyc files...')
        utils._check_call([config.build_python, '-Wi',
                           join(stdlib_dir, 'compileall.py'),
                           '-q', '-x', 'port_v3', sp_dir])

def post_process(files, preserve_egg_dir=False):
    remove_easy_install_pth(files, preserve_egg_dir=preserve_egg_dir)
    rm_py_along_so()
    if not config.PY3K:
        compile_missing_pyc()

def osx_ch_link(path, link):
    assert path.startswith(config.build_prefix + '/')
    reldir = utils.relative(path[len(config.build_prefix) + 1:])

    prefix_lib = config.build_prefix + '/lib'
    if link.startswith(prefix_lib):
        return '@loader_path/%s/%s' % (reldir, link[len(prefix_lib) + 1:])

    if link.startswith(('lib', '@executable_path/')):
        return '@loader_path/%s/%s' % (reldir, basename(link))

    if link == '/usr/local/lib/libgcc_s.1.dylib':
        return '/usr/lib/libgcc_s.1.dylib'

def mk_relative_osx(path):
    assert sys.platform == 'darwin' and is_obj(path)
    s = macho.install_name_change(path, osx_ch_link)

    if macho.is_dylib(path):
        names = macho.otool(path)
        if names:
            args = ['install_name_tool', '-id', basename(names[0]), path]
            print(' '.join(args))
            p = Popen(args, stderr=PIPE)
            stdout, stderr = p.communicate()
            stderr = stderr.decode('utf-8')
            if "Mach-O dynamic shared library stub file" in stderr:
                print("Skipping Mach-O dynamic shared library stub file %s\n" % path)
                return
            else:
                print(stderr, file=sys.stderr)
                if p.returncode:
                    raise RuntimeError("install_name_tool failed with exit status %d"
                % p.returncode)

    if s:
        # Skip for stub files, which have to use binary_has_prefix_files to be
        # made relocatable.
        assert_relative_osx(path)

def mk_relative_linux(f, rpaths=('lib',)):
    path = join(config.build_prefix, f)
    rpath = ':'.join('$ORIGIN/' + utils.relative(f, d) for d in rpaths)
    patchelf = external.find_executable('patchelf')
    print('patchelf: file: %s\n    setting rpath to: %s' % (path, rpath))
    call([patchelf, '--set-rpath', rpath, path])

def assert_relative_osx(path):
    for name in macho.otool(path):
        assert not name.startswith(config.build_prefix), path

def mk_relative(m, f):
    assert sys.platform != 'win32'
    path = join(config.build_prefix, f)
    if not is_obj(path):
        return

    if sys.platform.startswith('linux'):
        mk_relative_linux(f, rpaths=m.get_value('build/rpaths', ['lib']))
    elif sys.platform == 'darwin':
        mk_relative_osx(path)

def fix_permissions(files):
    for root, dirs, unused_files in os.walk(config.build_prefix):
        for dn in dirs:
            lchmod(join(root, dn), int('755', 8))

    for f in files:
        path = join(config.build_prefix, f)
        st = os.lstat(path)
        lchmod(path, stat.S_IMODE(st.st_mode) | stat.S_IWUSR) # chmod u+w

def post_build(m, files):
    print('number of files:', len(files))
    fix_permissions(files)

    if sys.platform == 'win32':
        return

    binary_relocation = bool(m.get_value('build/binary_relocation', True))
    if not binary_relocation:
        print("Skipping binary relocation logic")
    osx_is_app = bool(m.get_value('build/osx_is_app', False))

    for f in files:
        if f.startswith('bin/'):
            fix_shebang(f, osx_is_app=osx_is_app)
        if binary_relocation:
            mk_relative(m, f)

    check_symlinks(files)

def check_symlinks(files):
    if readlink is False:
        return  # Not on Unix system
    msgs = []
    for f in files:
        path = join(config.build_prefix, f)
        if islink(path):
            link_path = readlink(path)
            real_link_path = realpath(path)
            if real_link_path.startswith(config.build_prefix):
                # If the path is in the build prefix, this is fine, but
                # the link needs to be relative
                if not link_path.startswith('.'):
                    # Don't change the link structure if it is already a
                    # relative link. It's possible that ..'s later in the path
                    # can result in a broken link still, but we'll assume that
                    # such crazy things don't happen.
                    print("Making absolute symlink %s -> %s relative" % (f, link_path))
                    os.unlink(path)
                    os.symlink(relpath(real_link_path, dirname(path)), path)
            else:
                # Symlinks to absolute paths on the system (like /usr) are fine.
                if real_link_path.startswith(config.croot):
                    msgs.append("%s is a symlink to a path that may not "
                        "exist after the build is completed (%s)" % (f, link_path))

    if msgs:
        for msg in msgs:
            print("Error: %s" % msg, file=sys.stderr)
        sys.exit(1)

def get_build_metadata(m):
    if exists(join(source.WORK_DIR, '__conda_version__.txt')):
        with open(join(source.WORK_DIR, '__conda_version__.txt')) as f:
            version = f.read().strip()
            print("Setting version from __conda_version__.txt: %s" % version)
            m.meta['package']['version'] = version
    if exists(join(source.WORK_DIR, '__conda_buildnum__.txt')):
        with open(join(source.WORK_DIR, '__conda_buildnum__.txt')) as f:
            build_number = f.read().strip()
            print("Setting build number from __conda_buildnum__.txt: %s" %
                  build_number)
            m.meta['build']['number'] = build_number
    if exists(join(source.WORK_DIR, '__conda_buildstr__.txt')):
        with open(join(source.WORK_DIR, '__conda_buildstr__.txt')) as f:
            buildstr = f.read().strip()
            print("Setting version from __conda_buildstr__.txt: %s" % buildstr)
            m.meta['build']['string'] = buildstr


# -*- coding: utf-8 -*-
from dateutil.parser import *
from datetime import *

import logging
_logger = logging.getLogger(__name__)

# Odoo version 15.0

# Odoo 12.0 -> Odoo 13.0
uom_model = "uom.uom"
cl_vat_sep_million = "."

#message types
order_message_type = "notification"
product_message_type = "notification"

#price from pricelist
def get_price_from_pl( pricelist, product, quantity ):
    pl = pricelist
    return_val = {}
    return_val = pl.price_get( product.id, quantity)
    return return_val

#Autocommit
def Autocommit( self, act=False ):
    self._cr.autocommit(act)
    return False

def UpdateProductType( product ):
    if not product:
        return
    for prod in product:
        if (prod and prod.detailed_type not in ['product']):
            failed = False
            try:
                prod.write( { 'detailed_type': 'product' } )
            except Exception as e:
                _logger.info("Set detailed_type almacenable ('product') not possible:")
                _logger.error(e, exc_info=True)
                failed = True
                pass;
            try:
                prod.write( { 'type': 'product' } )
            except Exception as e:
                _logger.info("Set type almacenable ('product') not possible:")
                _logger.error(e, exc_info=True)
                failed = True
                pass;

            query = """UPDATE product_template SET type='product', detailed_type='product' WHERE id=%i""" % (prod.id)
            cr = prod._cr
            respquery = cr.execute(query)

def ProductType():
    return {
        "type": "product",
        "detailed_type": "product"
    }

# Odoo 12.0 -> Odoo 13.0
prod_att_line = "product.template.attribute.line"

# account
acc_inv_model  = "account.move"

#stock inventory to quant: 14.0 -> 15.0
stock_inv_model = "stock.quant"

# default_create_variant
default_no_create_variant = "no_variant"
default_create_variant = "always"

#'unique(product_tmpl_id,meli_imagen_id)'
unique_meli_imagen_id_fields = 'unique(product_tmpl_id,product_variant_id,meli_imagen_id)'

def get_ref_view( self, module_name, view_name ):

    refview = self.env['ir.model.data'].check_object_reference( module_name, view_name )

    return refview

#TODO: get_company_selected, user with allowed companies
def get_company_selected( self, context=None, company=None, company_id=None, user=None, user_id=None ):
    context = context or self.env.context
    company = company or self.env.user.company_id
    #_logger.info("context:"+str(context)+" company:"+str(company))
    company_id = company_id or (context and 'allowed_company_ids' in context and context['allowed_company_ids'] and context['allowed_company_ids'][0]) or company.id
    company = self.env['res.company'].browse(company_id) or company
    return company

#variant mage ids
def variant_image_ids(self):
    if "product_variant_image_ids" in self._fields:
        return self.product_variant_image_ids
    return None

#template image ids
def template_image_ids(self):
    if "product_template_image_ids" in self._fields:
        return self.product_template_image_ids
    return None

#att value ids
def att_value_ids(self):
    return self.product_template_attribute_value_ids

#att line ids
def att_line_ids(self):
    return self.attribute_line_ids

def get_image_full(self):
    return ("variant_image" in self._fields and self.variant_image) or self.image_1920

def set_image_full(self, image):
    self.image_1920 = image
    return True

def get_first_image_to_publish(self):
    company = self.env.user.company_id
    product = self
    first_image_to_publish = None

    if (company.mercadolibre_do_not_use_first_image):
        image_ids = variant_image_ids(product)
        if (len(image_ids)):
            #Use first image of variant image ids: product.image
            first_image_to_publish = get_image_full(image_ids[0])
    else:
        first_image_to_publish = get_image_full(product)

    return first_image_to_publish

def prepare_attribute( product_template_id, attribute_id, attribute_value_id ):
    att_vals = { 'attribute_id': attribute_id,
                 'value_ids': [(4,attribute_value_id)],
                 'product_tmpl_id': product_template_id
               }
    return att_vals

def stock_picking_set_quantities( picking ):
    for spick in picking:
        for pop in spick.move_line_ids:
            #_logger.info(pop)
            if (pop.qty_done==0.0 and pop.product_qty>=0.0):
                pop.qty_done = pop.product_qty

def stock_inventory_action_done( self, product, stock, config ):
    return_id = False
    uomobj = self.env[uom_model]
    whid = self.env['stock.location'].search([('usage','=','internal')]).id
    product_uom_id = uomobj.search([('name','=','Unidad(es)')])
    if (product_uom_id.id==False):
        product_uom_id = 1
    else:
        product_uom_id = product_uom_id.id

    stock_inventory_fields = get_inventory_fields( product, whid, quantity=_stock )

    _logger.info("stock_inventory_fields:")
    _logger.info(stock_inventory_fields)
    StockInventory = self.env[stock_inv_model].create(stock_inventory_fields)
    if (StockInventory):
        return_id = self.with_context(inventory_mode=True)._apply_inventory()
    return return_id

def ml_datetime(datestr):
    try:
        #return parse(datestr).isoformat().replace("T"," ")
        datestr = str(datestr)
        return parse(datestr).astimezone(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')
    except:
        #_logger.error(type(datestr))
        #_logger.error(datestr)
        return None

def ml_tax_excluded(self, config=None ):
    #11.0
    #tax_excluded = self.env.user.has_group('sale.group_show_price_subtotal')
    #12.0 and 13.0
    tax_excluded = self.env.user.has_group('account.group_show_line_subtotals_tax_excluded')

    company = (config and "company_id" in config._fields and config.company_id) or self.env.user.company_id
    config = config or company
    if (config and config.mercadolibre_tax_included not in ['auto']):
        tax_excluded = (config.mercadolibre_tax_included in ['tax_excluded'])
    return tax_excluded

def ml_product_price_conversion( self, product_related_obj, price, config=None):
    company_id = ("company_id" in config._fields and config.company_id) or config
    product_template = product_related_obj.product_tmpl_id
    ml_price_converted = float(price)
    tax_excluded = ml_tax_excluded( self, config=config )
    #tax_excluded = True
    #_logger.info("Taxes:"+str(product_template.taxes_id))
    if ( tax_excluded and product_template.taxes_id ):
        txfixed = 0
        txpercent = 0
        #_logger.info("Adjust taxes")
        for txid in product_template.taxes_id:
            if (txid.company_id!=company_id):
                continue;
            if (txid.type_tax_use=="sale" and not txid.price_include):
                if (txid.amount_type=="percent"):
                    txpercent = txpercent + txid.amount
                if (txid.amount_type=="fixed"):
                    txfixed = txfixed + txid.amount
                #_logger.info(txid.amount)
        if (txfixed>0 or txpercent>0):
            #_logger.info("Tx Total:"+str(txtotal)+" to Price:"+str(ml_price_converted))
            ml_price_converted = txfixed + ml_price_converted / (1.0 + txpercent*0.01)
            #_logger.info("Price adjusted with taxes:"+str(ml_price_converted))

    ml_price_converted = round(ml_price_converted,2)
    return ml_price_converted

def get_inventory_fields( product, warehouse, quantity=0 ):
    return {
            #"product_ids": [(4,product.id)],
            "product_id": product.id,
            #"filter": "product",
            "location_id": warehouse,
            "inventory_quantity": quantity
            #"name": "INV: "+ product.name
            }

def get_delivery_line(sorder):
    delivery_line = None
    try:
        carrier_product_id = sorder.carrier_id.product_id.id
        for line in sorder.order_line:
            if(line.product_id.id == carrier_product_id):
                delivery_line = line
                return delivery_line

        delivery_lines = self.env['sale.order.line'].search([('order_id', 'in', sorder.ids), ('is_delivery', '=', True)])
        if delivery_lines:
            delivery_line = delivery_lines[0]
            return delivery_line

    except:
        _logger.info("Error get delivery line failed")
        return delivery_line

def set_delivery_line( sorder, delivery_price, delivery_message ):
    #check version
    delivery_line = get_delivery_line(sorder)
    if not delivery_line:
        sorder.set_delivery_line(sorder.carrier_id, delivery_price)
        delivery_line = get_delivery_line(sorder)
    try:
        recompute_delivery_price = False

        if (delivery_line and abs(delivery_line.price_unit - float(delivery_price)) > 1.1 ):
            recompute_delivery_price = True
            sorder.set_delivery_line(sorder.carrier_id, delivery_price)

        sorder.write({
        	'recompute_delivery_price': recompute_delivery_price,
        	'delivery_message': delivery_message,
        })
    except:
            _logger.info("Error set_delivery_line failed (order invoiced)")

    return delivery_line

def remove_delivery_line( sorder, delivery_price=0):
    sorder._remove_delivery_line()
    return


from translator.translator import TextTranslator
from merger.general.general_operations import GeneralOperations
from urllib.request import urlopen
from common.errors import ConnectError
from common.decorator_for_output_errors import decorator_for_output_errors

class AddFileInRussian(GeneralOperations):

    def __init__(self):
        self.translator = TextTranslator()

    @decorator_for_output_errors()
    def __update_progressbar(self, progressbar, start_progressbar, step_progressbar):
        if progressbar is not None:
            progressbar.UpdateBar(start_progressbar + step_progressbar)
            start_progressbar += step_progressbar
            return start_progressbar
        return 0

    @decorator_for_output_errors()
    def execute_operation(self, path_general_file, add_path, progressbar=None):
        '''Дополнить на русском языке'''

        general_dict_string = self.file_in_dict(path_general_file)
        additional_dict_string = self.file_in_dict(add_path)

        general_list_string = list(general_dict_string.keys())
        additional_list_string = list(additional_dict_string.keys())

        common_string = set(general_list_string) & set(additional_list_string)
        additional_file = self.file_for_write(add_path)
        additional_file.write('l_russian:\n')

        start_progressbar = 0
        step_progressbar = 100/len(general_list_string)

        for line in general_list_string:
            if 'l_english' in line or 'l_russian' in line:
                continue
            elif '\n' in line:
                continue
            elif line == ' \n':
                continue
            elif line == '  \n':
                continue
            elif line not in common_string:
                eng = general_dict_string[line].replace(':0 "', '').replace('"', '')
                ru = ':0 "' + self.translator.transleate_text(eng) + '"'
                additional_file.write(line + ru+'\n')
                start_progressbar = self.__update_progressbar(progressbar, start_progressbar, step_progressbar)
                if 'desc' in line:
                    additional_file.write('\n')
                del general_dict_string[line]

        other_string = list(general_dict_string.keys())
        for line in other_string:
            if 'l_english' in line or 'l_russian' in line:
                continue
            elif line == '\n':
                additional_file.write('\n')
            elif line == '  \n':
                additional_file.write('\n')
            elif ':' in additional_dict_string[line]:
                additional_file.write(line + additional_dict_string[line])
                start_progressbar = self.__update_progressbar(progressbar, start_progressbar, step_progressbar)
                if 'desc' in line:
                    additional_file.write('\n')
            else:
                additional_file.write(line)
        additional_file.close()
        print('Операция завершена')
        self.encod_utf8_bom(add_path)

    @decorator_for_output_errors()
    def __check_connection(self):
        for timeout in [1, 5, 10, 15]:
            try:
                response = urlopen('http://google.com', timeout=timeout)
            except:
                raise ConnectError


from typing import Callable

import pytest
from httpx import AsyncClient, Headers
from logrich.logger_ import log  # noqa

from src.auth.conftest import Routs
from src.auth.tests.ads.conftest import insert_fake_ads, insert_fake_images

skip = False
# skip = True
reason = "Temporary off!"
pytestmark = pytest.mark.django_db(transaction=True, reset_sequences=True)

@pytest.mark.skipif(skip, reason=reason)
@pytest.mark.asyncio
async def test_list_ads_with_paginate(
    client: AsyncClient, routes: Routs, user_active_auth_headers: Headers, add_test_ad: Callable
) -> None:
    """Тест списка объявлений с пагинацией"""
    AMOUNT_ADS = 27
    SIZE = 5
    PAGE = 1

    await insert_fake_ads(amount_ads=AMOUNT_ADS)
    await insert_fake_images(amount_ads=AMOUNT_ADS)

    params = {"page": PAGE, "size": SIZE}

    resp = await client.get(routes.read_ads, params=params)
    log.debug(resp)
    data = resp.json()
    log.debug("список объявлений с пагинацией..", o=data)
    assert resp.status_code == 200
    assert data.get("total") == AMOUNT_ADS + 1
    # assert len(data) == 2
    # return
    assert len(data.get("items")) == SIZE
    assert data.get("page") == PAGE
    assert data.get("size") == SIZE


import argparse
import os
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline, FeatureUnion
from sklearn.metrics import f1_score, make_scorer
from pk_classifier.bootstrap import read_in_distributional, simple_tokenizer, TextSelector
import xgboost as xgb
import pandas as pd
import joblib

HYPERPARAMETER_GRID = {
    'encoder__bow__vect__min_df': 2 ** np.arange(1, 10, 1),
    'clf__max_depth': 2 ** np.arange(1, 7, 1),
    'clf__colsample_bytree': [1 / 3, 2 / 3, 3 / 3],
}

def cross_validate_pk(training_embeddings: str, training_optimal_bow: str, training_labels: str, output_dir: str):
    all_features, all_labs = read_in_distributional(path_preproc=training_embeddings, path_labels=training_labels,
                                                    is_specter=False, path_optimal_bow=training_optimal_bow)
    all_labs = all_labs['label']
    rd_seed = 10042006

    # =====================================================================================================
    #               Define pipeline
    # ======================================================================================================
    hyp_grid = HYPERPARAMETER_GRID
    balancing_factor = all_labs.value_counts()["Not Relevant"] / all_labs.value_counts()["Relevant"]
    encoder = CountVectorizer(tokenizer=simple_tokenizer, ngram_range=(1, 1), lowercase=False, preprocessor=None)
    normalizer = TfidfTransformer(norm="l1", use_idf=False)
    decoder = xgb.XGBClassifier(random_state=rd_seed,
                                n_estimators=148,  # Median value of the optimal n_estimators across 200 bootstrapping
                                # iterations when early stopping was applied
                                objective='binary:logistic',
                                learning_rate=0.1,
                                scale_pos_weight=balancing_factor, nthread=-1, n_jobs=-1, )

    EncDecPip = Pipeline([
        ('encoder', FeatureUnion(transformer_list=[
            ('bow', Pipeline([
                ('selector', TextSelector('BoW_Ready', emb=False)),
                ('vect', encoder),
                ('norm', normalizer)
            ])
             ),
            ('abs', Pipeline([
                ('selector', TextSelector('embedding', emb=True))
            ]))
        ])),
        ('clf', decoder)
    ])

    f1_scorer = make_scorer(f1_score, pos_label="Relevant")
    grid_obj = GridSearchCV(EncDecPip, hyp_grid, scoring=f1_scorer, cv=5, n_jobs=-1, verbose=51)
    # Train
    model_trained = grid_obj.fit(all_features, all_labs)
    best_param = model_trained.best_params_
    best_param['Mean F1-score'] = model_trained.best_score_
    best_param['Time'] = model_trained.refit_time_
    print("Optimal parameter combination ", best_param)
    results_df = pd.DataFrame.from_dict(best_param, orient='index')
    # save your model and results
    results_df.to_pickle(os.path.join(output_dir, "cv_results.pkl"))
    joblib.dump(model_trained, os.path.join(output_dir, "cv_optimal_pipeline.pkl"))

def run(training_embeddings: str, training_optimal_bow: str, training_labels: str, output_dir: str):
    if not os.path.isdir(output_dir):
        os.makedirs(output_dir, exist_ok=True)
    cross_validate_pk(training_embeddings=training_embeddings, training_optimal_bow=training_optimal_bow,
                      training_labels=training_labels, output_dir=output_dir)

def main():
    parser = argparse.ArgumentParser()

    parser.add_argument("--training-embeddings",
                        type=str,
                        help="Parquet file with the embeddings of the training data.",
                        default="../data/encoded/biobert/training_biobert_avg.parquet")

    parser.add_argument("--training-optimal-bow",
                        type=str,
                        help="Path to the parquet file with the optimal BoW features of the training set.",
                        default="../data/encoded/ngrams/training_unigrams.parquet")

    parser.add_argument("--training-labels",
                        type=str,
                        help="Path to the CSV file containing the labels of the training data.",
                        default="../data/labels/training_labels.csv")

    parser.add_argument("--output-dir",
                        type=str,
                        help="Directory to save the CV results and output files.",
                        default="../data/results/final-pipeline")

    args = parser.parse_args()
    run(training_embeddings=args.training_embeddings, training_optimal_bow=args.training_optimal_bow,
        training_labels=args.training_labels, output_dir=args.output_dir)

if __name__ == '__main__':
    main()


import logging

from flask import Blueprint, jsonify
from blueprint_api.dao.postsDAO import PostDAO

logging.basicConfig(level=logging.INFO, filename="api.log", filemode="w",
                    format="%(asctime)s %(levelname)s %(message)s")

postsDAO = PostDAO()

api_blueprint = Blueprint("api_blueprint",
                          __name__)

@api_blueprint.route("/api/posts")
def api_posts():
    posts = postsDAO.get_posts_all()
    logging.info(f"api/posts")
    return jsonify(posts)

@api_blueprint.route("/api/posts/<int:post_id>")
def api_post(post_id):
    post = postsDAO.get_post_by_pk(post_id)
    logging.info(f"api/posts/{post_id}")
    return jsonify(post)


from . import views
from django.urls import path, include

app_name = 'Signin'
urlpatterns = [
    path('', views.index, name = 'index'),
    path('login/', views.login, name='login'),
    path('gotoprofile/', views.gotoprofile, name = 'gotoprofile'),
    path('logoff/', views.logoff, name = 'logoff'),
    path('addCourse/<int:course_id>', views.addCourse, name='addCourse'),
    path('deleteCourse/<int:course_id>', views.deleteCourse, name = 'deleteCourse'),
    path('areatable/', views.areatable, name = 'areatable'),
    path('jobtable', views.jobtable, name = 'jobtable'),
    # path('search_course', views.search_course, name = 'search_course'),
    #path('profile/', views.profile, name='profile'),
    # path('changepassword/', views.changepassword, name = 'changepassword'),
    # path('updatepassword/', views.updatepassword, name = 'updatepassword'),

]


"""Regression test."""
import numpy as np
import json
import gw_eccentricity
from gw_eccentricity import load_data
from gw_eccentricity import measure_eccentricity

# locally it passs without problem but on github action, we need to set this tolerance
atol = 1e-9

def test_regression():
    """Regression test using all methods."""
    # List of all available methods
    available_methods = gw_eccentricity.get_available_methods()
    for method in available_methods:
        # Load regression data
        regression_data_file = f"test/regression_data/{method}_regression_data.json"
        # Load the regression data
        fl = open(regression_data_file, "r")
        regression_data = json.load(fl)
        fl.close()
        # waveform kwargs
        lal_kwargs = regression_data["waveform_kwargs"]
        # load waveform data
        dataDict = load_data.load_waveform(**lal_kwargs)
        extra_kwargs = regression_data["extra_kwargs"]

        # Try evaluating at times where regression data are saved
        regression_data_at_tref = regression_data["tref"]
        tref_in = regression_data_at_tref["time"]
        gwecc_dict = measure_eccentricity(
            tref_in=tref_in,
            method=method,
            dataDict=dataDict,
            extra_kwargs=extra_kwargs)
        tref_out = gwecc_dict["tref_out"]
        ecc_ref = gwecc_dict["eccentricity"]
        meanano_ref = gwecc_dict["mean_anomaly"]
        # Compare the measured data with the saved data
        np.testing.assert_allclose(
            ecc_ref, regression_data_at_tref["eccentricity"],
            atol=atol,
            err_msg="measured and saved eccentricity at saved times do not match.")
        np.testing.assert_allclose(
            meanano_ref, regression_data_at_tref["mean_anomaly"],
            atol=atol,
            err_msg="measured and saved mean anomaly at saved times do not match.")

        # Try evaluating at frequencies where regression data are saved
        regression_data_at_fref = regression_data["fref"]
        fref_in = regression_data_at_fref["frequency"]
        gwecc_dict = measure_eccentricity(
            fref_in=fref_in,
            method=method,
            dataDict=dataDict,
            extra_kwargs=extra_kwargs)
        fref_out = gwecc_dict["fref_out"]
        ecc_ref = gwecc_dict["eccentricity"]
        meanano_ref = gwecc_dict["mean_anomaly"]
        # Compare the measured data with the saved data
        np.testing.assert_allclose(
            ecc_ref, regression_data_at_fref["eccentricity"],
            atol=atol,
            err_msg="measured and saved eccentricity at saved frequencies do not match.")
        np.testing.assert_allclose(
            meanano_ref, regression_data_at_fref["mean_anomaly"],
            atol=atol,
            err_msg="measured and saved mean anomaly at saved frequencies do not match.")


# License
# 'image: fullScreen.png'. This cover has been designed using images from Flaticon.com
# 'image: icon.png, favicon.ico'. This cover has been designed using images from logo.com

import sys,os
from PyQt5.QtWidgets import QApplication, QWidget,QPushButton, QLabel, QVBoxLayout,QHBoxLayout
from PyQt5.QtGui import QPixmap, QIcon
from PyQt5.QtCore import Qt

# 고객용 서브윈도우
class SubWindow(QWidget):

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

        # ★ debug path ★
        # self.exePath = os.path.dirname(os.path.abspath(__file__))
        # self.tmpPath = os.path.dirname(os.path.abspath(__file__))

        # ★ build path ★
        self.exePath = os.path.dirname(os.path.abspath(sys.executable))
        try: self.tmpPath = sys._MEIPASS
        except Exception: self.tmpPath = os.path.abspath(".")

        # 창 기본세팅
        self.setWindowTitle('SubWindow')
        self.setWindowIcon(QIcon(self.tmpPath+"\img\icon.png"))
        self.setStyleSheet("background-color: black;")
        self.show()
        self.vbox=QVBoxLayout()

    # 작업윈도우에서 이미지 출력이끝나면 호출되는메서드
    def displayInfo(self,files):
        # 이전이미지는 제거 작업(메모리관리)
        # vbox의 자식 개체수만큼
        while self.vbox.count():
            # 자식개체와 해당 개체의 레이아웃 저장
            childWidget = self.vbox.takeAt(0)
            childLayout = childWidget.layout()
            if childLayout:
                # 자식개체의 레이아웃(hbox)의 자식 개체수만큼
                while childLayout.count():
                    childWidget2=childLayout.takeAt(0)
                    childLayout2=childWidget2.widget()
                    # hbox의 자식 개체(이미지) 의 상속관계를 해제후 destory)
                    if childLayout2:
                        childLayout2.setParent(None)
                        childLayout2.deleteLater()
                # vbox의 자식개체(hbox) 의 상속관계를 해제후 destory
                childLayout.setParent(None)
                childLayout.deleteLater()

        # 수평박스
        hbox=[QHBoxLayout(),QHBoxLayout()]

        # 제공받은 이미지 갯수만큼
        for f in files:
            c=f.replace('/','\\')
            pixmap = QPixmap(c)
            lbl_img = QLabel(self)
            # 해상도 가로 기준으로 이미지 리사이즈
            lbl_img.setPixmap(pixmap.scaledToWidth(int(self.size().width()/2)))
            # 센터정렬
            lbl_img.setAlignment(Qt.AlignCenter)
            # 이미지갯수 절반보다 작으면 위에 많으면 밑에
            if files.index(f)<(len(files)/2):
                hbox[0].addWidget(lbl_img)
            else:
                hbox[1].addWidget(lbl_img)

        # vbox 에 hbox 두개를 순서대로 추가후 레이아웃을 vbox로 설정
        self.vbox.addLayout(hbox[0])
        self.vbox.addLayout(hbox[1])
        self.setLayout(self.vbox)

# 작업자용 메인윈도우
class MainWindow(QWidget):
    def __init__(self):
        super().__init__()

        # ★ debug path ★
        # self.exePath = os.path.dirname(os.path.abspath(__file__))
        # self.tmpPath = os.path.dirname(os.path.abspath(__file__))

        # ★ build path ★
        self.exePath = os.path.dirname(os.path.abspath(sys.executable))
        try: self.tmpPath = sys._MEIPASS
        except Exception: self.tmpPath = os.path.abspath(".")

        # 윈도우 아이콘 설정
        self.setWindowIcon(QIcon(self.tmpPath+"\img\icon.png"))

        # 서브윈도우 생성
        self.subWindow = SubWindow()
        self.setAcceptDrops(True)

        # 작업자뷰 상단에 위치하는 조작용 버튼 레이아웃
        startInfoBox = QVBoxLayout()
        fullBtn = QPushButton()
        fullBtn.setIcon(QIcon(self.tmpPath+"\img//fullScreen.png"))
        self.setStyleSheet("QPushButton{background-color: rgb(151, 151, 141);border-radius: 20px;}QPushButton:hover{background-color: rgb(121, 121, 111);}")
        fullBtn.setIconSize(fullBtn.size())
        fullBtn.clicked.connect(self.fullScreen)
        startInfoBox.addWidget(fullBtn)

        # 멤버로 쓸수있게끔 vbox 생성
        # SubWindow 선언, dropevent 활성화
        self.vbox=QVBoxLayout()
        self.vbox.addLayout(startInfoBox)
        self.setLayout(self.vbox)
        self.move(self.subWindow.pos().x()+100,self.subWindow.pos().y()+100)

        # 창제목 및 기본 사이즈
        self.setWindowTitle('SplitViewer')

    # 작업자 뷰 조작용
    def closeEvent(self, QCloseEvent):
        self.subWindow.close()
    def fullScreen(self):
        self.subWindow.showFullScreen()

    # drag&drop 이벤트
    def dragEnterEvent(self, event):
        if event.mimeData().hasUrls(): event.accept()
        else: event.ignore()
    def dropEvent(self, event):
        self.setStyleSheet("QPushButton{border-radius: 0px;}")
        # 이전이미지는 제거 작업(메모리관리)
        while self.vbox.count():
            # 자식개체와 해당 개체의 레이아웃 저장
            childWidget = self.vbox.takeAt(0)
            childLayout = childWidget.layout()
            if childLayout:
                # 자식개체의 레이아웃(hbox)의 자식 개체수만큼
                while childLayout.count():
                    childWidget2=childLayout.takeAt(0)
                    childLayout2=childWidget2.widget()
                    # hbox의 자식 개체(이미지) 의 상속관계를 해제후 destory)
                    if childLayout2:
                        childLayout2.setParent(None)
                        childLayout2.deleteLater()
                # vbox의 자식개체(hbox) 의 상속관계를 해제후 destory
                childLayout.setParent(None)
                childLayout.deleteLater()

        # 수평박스
        hbox=[QHBoxLayout(),QHBoxLayout()]
        files = [u.toLocalFile() for u in event.mimeData().urls()]
        for f in files:
            c=f.replace('/','\\')
            # 이미지 생성
            pixmap = QPixmap(c)

            # 해상도 가로 기준으로 이미지 리사이즈 fitToScreenWidth
            pixmap= pixmap.scaledToWidth(int(self.size().width()/2))
            # 해상도 세로 기준으로 이미지 리사이즈 fitToScreenWidth
            #pixmap= pixmap.scaledToHeight(int(self.size().width()/2))

            # 아이콘형태로
            icon = QIcon()
            icon.addPixmap(pixmap)

            # 버튼
            btn = QPushButton()
            btn.setIcon(icon)
            btn.setIconSize(pixmap.size())
            btn.setObjectName(c)
            btn.clicked.connect(self.printImage)

            # 이미지갯수 절반보다 작으면 위에 많으면 밑에
            if files.index(f)<(len(files)/2):
                hbox[0].addWidget(btn)
            else:
                hbox[1].addWidget(btn)

        # vbox 에 hbox 두개를 순서대로 추가후 레이아웃을 vbox로 설정
        self.vbox.addLayout(hbox[0])
        self.vbox.addLayout(hbox[1])
        self.setLayout(self.vbox)

        # 드래그앤드랍으로 사용자에게 제공받은 파일들을 고객윈도우에 똑같이 제공
        self.subWindow.displayInfo(files)

    # 이미지 클릭시 호출될 메서드
    def printImage(self):
        # 클릭한 버튼개체를 저장
        btn = self.sender()
        # 버튼의 이름을 저장
        filename=btn.objectName()
        # 버튼의이름(파일명)을 기반으로 프린트
        os.startfile(filename,"print")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = MainWindow()
    main.show()
    sys.exit(app.exec_())


from django.contrib import admin
from django.urls import path, include
from django.conf.urls import url
from LiveData.views import (LiveDataDetailAPIView,
                            LiveDataListAPIView,
                            LiveDataUpdateAPIView,
                            LiveDataDeleteAPIView)

app_name = 'LiveData'
urlpatterns = [
    url(r'edit/(?P<pk>\d+)$', LiveDataUpdateAPIView.as_view(), name='update'),
    url(r'detail/(?P<pk>\d+)$', LiveDataDetailAPIView.as_view(), name='detail'),
    url(r'delete/(?P<pk>\d+)$', LiveDataDeleteAPIView.as_view(), name='delete'),
    url(r'list/$', LiveDataListAPIView.as_view(), name='list'),
]


"""Support for Lektrico charging station switches."""
from __future__ import annotations

from dataclasses import dataclass
from typing import Any

import lektricowifi

from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_FRIENDLY_NAME
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity

from . import LektricoDeviceDataUpdateCoordinator
from .const import DOMAIN

@dataclass
class LektricoSwitchEntityDescription(SwitchEntityDescription):
    """A class that describes the Lektrico switch entities."""

    @classmethod
    def get_is_on(cls, data: Any) -> int | None:
        """Return None."""
        return None

    @classmethod
    async def turn_on(cls, device: lektricowifi.Device, data: Any) -> bool | None:
        """Return None."""
        return None

    @classmethod
    async def turn_off(cls, device: lektricowifi.Device, data: Any) -> bool | None:
        """Return None."""
        return None

@dataclass
class RequireAuthSwitchEntityDescription(LektricoSwitchEntityDescription):
    """A class that describes the Lektrico RequireAuth Switch entity."""

    @classmethod
    def get_is_on(cls, data: Any) -> bool:
        """Get the RequireAuth."""
        return bool(data.require_auth)

    @classmethod
    async def turn_on(cls, device: lektricowifi.Device, data: Any) -> bool:
        """Turn on the RequireAuth switch."""
        return bool(await device.set_auth(False))

    @classmethod
    async def turn_off(cls, device: lektricowifi.Device, data: Any) -> bool:
        """Turn off the RequireAuth switch."""
        return bool(await device.set_auth(True))

@dataclass
class LockSwitchEntityDescription(LektricoSwitchEntityDescription):
    """A class that describes the Lektrico Lock / Unlock Switch entity."""

    @classmethod
    def get_is_on(cls, data: Any) -> bool:
        """Check if the reported state is LOCKED."""
        return str(data.charger_state) == "LOCKED"

    @classmethod
    async def turn_on(cls, device: lektricowifi.Device, data: Any) -> bool:
        """Lock the charger."""
        return bool(await device.set_charger_locked(True))

    @classmethod
    async def turn_off(cls, device: lektricowifi.Device, data: Any) -> bool:
        """Unlock the charger."""
        return bool(await device.set_charger_locked(False))

SENSORS: tuple[LektricoSwitchEntityDescription, ...] = (
    RequireAuthSwitchEntityDescription(
        key="authentication",
        name="Authentication",
    ),
    LockSwitchEntityDescription(
        key="locked",
        name="Lock",
    ),
)

async def async_setup_entry(
    hass: HomeAssistant,
    entry: ConfigEntry,
    async_add_entities: AddEntitiesCallback,
) -> None:
    """Set up Lektrico charger based on a config entry."""
    coordinator: LektricoDeviceDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]

    async_add_entities(
        LektricoSwitch(
            description,
            coordinator,
            entry.data[CONF_FRIENDLY_NAME],
        )
        for description in SENSORS
    )

class LektricoSwitch(CoordinatorEntity, SwitchEntity):
    """The entity class for Lektrico charging stations switches."""

    entity_description: LektricoSwitchEntityDescription
    _attr_has_entity_name = True

    def __init__(
        self,
        description: LektricoSwitchEntityDescription,
        coordinator: LektricoDeviceDataUpdateCoordinator,
        friendly_name: str,
    ) -> None:
        """Initialize Lektrico charger."""
        super().__init__(coordinator)
        self.entity_description = description

        self._attr_unique_id = f"{coordinator.serial_number}_{description.key}"
        self._attr_device_info = DeviceInfo(
            identifiers={(DOMAIN, str(coordinator.serial_number))},
            model=f"{coordinator.device_type.upper()} {coordinator.serial_number} rev.{coordinator.board_revision}",
            name=friendly_name,
            manufacturer="Lektrico",
            sw_version=coordinator.data.fw_version,
        )

    @property
    def is_on(self) -> bool:
        """If the switch is currently on or off."""
        return bool(self.entity_description.get_is_on(self.coordinator.data))

    async def async_turn_on(self, **kwargs: Any) -> None:
        """Turn the switch on."""
        await self.entity_description.turn_on(
            self.coordinator.device, self.coordinator.data
        )
        # Refresh the coordinator because a switch changed a value.
        await self.coordinator.async_refresh()

    async def async_turn_off(self, **kwargs: Any) -> None:
        """Turn the switch off."""
        await self.entity_description.turn_off(
            self.coordinator.device, self.coordinator.data
        )
        # Refresh the coordinator because a switch changed a value.
        await self.coordinator.async_refresh()


#Thresholding:- It's a process of binarising the image. That is comparing the each pixel with a threshold value and if pixel < threshold then that pixel is considered
#as 0, if it is > then it will be considered either as 1 or 255.

import cv2 as cv
import numpy as np

img = cv.imread('images\lady.jpg')

cv.imshow('Lady', img)

gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

cv.imshow('LadyGray', gray)

# Two types of thresholding.

# Method:- 1 Simple Thresholding

threshold, thresh = cv.threshold(gray, 150, 255, cv.THRESH_BINARY)

print(threshold)

cv.imshow('Thresholded Image', thresh)

#Inverse Threshold

threshold, thresh_inv = cv.threshold(gray, 150, 255, cv.THRESH_BINARY_INV)

print(threshold)

cv.imshow('Inverse Thresholded Image', thresh_inv)

#In the simple threshold technique, the threshold value is user defined, hence this type of threshold may work for some cases and may not work for some other cases.

# Hence, in the adaptive threshold technique the algorithm it self finds the appropriate threshold value.

# Method:- 2 Adaptive Thresholding.

adaptive_threshold = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 11, 3)

#Here 11 is the kernal size to find  the mean, so it is 11x11, and the 3 is just an integer which will be subtracted from the mean. In place of MEAN we can also use GUASSIAN.

cv.imshow('Adaptive Threshold Image', adaptive_threshold)

cv.waitKey(0)


import numpy as np
import VkInline as vki
import FeiRaysInline as fri
from PIL import Image

width = 640
height = 480

film = fri.Film(width, height)

kernel = vki.Computer(['film'],
'''
void main()
{
    int x = int(gl_GlobalInvocationID.x);
    int y = int(gl_GlobalInvocationID.y);
    if (x >= film.width || y>=film.height) return;

    float u = (float(x)+0.5)/float(film.width);
    float v = (float(y)+0.5)/float(film.height);

    Spectrum color;
    from_rgb(color, vec3(u, v, 0.0));
    incr_pixel(film, x, y, color);
}
''')

blockSize = (8,8)
gridSize = (int((width+7)/8), int((height+7)/8))
kernel.launch(gridSize, blockSize, [film])
film.inc_times_exposure()

img_out = film.download_srgb()
Image.fromarray(img_out, 'RGBA').save('output.png')


import scrapy
import pandas as pd
from scrapy import Request
import re

class GlassdoorTextSpider(scrapy.Spider):
    name = 'glassdoor_text'

    def start_requests(self):
        # for item in pd.read_csv(f"data_{self.topic}/glassdoor_raw.csv", converters={"link": lambda x: str(x)}):

        for index, row in pd.read_csv(f"data_{self.cat}/glassdoor/glassdoor_raw.csv").iterrows():
            yield Request(
                url=row['link'],
                dont_filter=True,
                callback=self.parse_text,
                cb_kwargs=dict(link=row['link'], job_id=row['job_id']))

    def parse_text(self, response, link, job_id):
        text = self.cleanhtml("".join(response.css(
            "#JobDescriptionContainer").css(".desc").getall()))
        yield {"text": text, "job_id": job_id, "link": link}

    def cleanhtml(self, raw_html):
        cleanr = re.compile('<.*?>')
        cleantext = re.sub(cleanr, '', raw_html)
        cleantext = cleantext.replace("\n", "")
        cleantext = cleantext.replace("\t", "")
        cleantext = cleantext.replace("\r", "")
        return cleantext.strip()


import torch

from typing import List
from pandas import DataFrame
from collections import Counter

from constants import (
    LSTM_SEQUENCE_LENGTH,
    NUMBER_OF_POKEMON,
)

class PokemonDataset(torch.utils.data.Dataset):
    def __init__(self, dataset: DataFrame):
        self.words = self.load_words(dataset)
        self.vocabulary = self.get_vocabulary()
        self.vocabulary_size = len(self.vocabulary)

        self.index_to_word = {index: word for index, word in enumerate(self.vocabulary)}
        self.word_to_index = {word: index for index, word in enumerate(self.vocabulary)}

        self.words_indexes = [self.word_to_index[w] for w in self.words]

    def load_words(self, dataset: DataFrame) -> List[str]:
        text = ''

        for i in range(NUMBER_OF_POKEMON):
            # Add the color
            text = text + ' ' + dataset.iloc[[i]]['color'].str.cat(sep=' ')

            # Add the classification (Removing the String "Pokémon")
            text = text + ' ' + dataset.iloc[[i]]['classification'].str.cat(sep=' ')[:-8]

            # Add the type
            text = text + ' ' + dataset.iloc[[i]]['type_1'].str.cat(sep=' ')

            # Add the flavor text
            text = text + ' ' + dataset.iloc[[i]]['flavor_text'].str.cat(sep=' ')

        return text.split(' ')

    def get_vocabulary(self) -> List[str]:
        word_counts = Counter(self.words)
        return sorted(word_counts, key=word_counts.get, reverse=True)

    def __len__(self):
        return len(self.words_indexes) - LSTM_SEQUENCE_LENGTH

    def __getitem__(self, index):
        return (
            torch.tensor(self.words_indexes[index:index+LSTM_SEQUENCE_LENGTH]),
            torch.tensor(self.words_indexes[index+1:index+LSTM_SEQUENCE_LENGTH+1]),
        )


from fastapi import APIRouter, Depends, Request
from models.prediction import TemperaturePrediction
from models.payload import TemperaturePredictionPayload
from enum import Enum

from core.auth import get_current_user
router = APIRouter()

#set model types available to user
class ModelType(str,Enum):
    RF='random_forest'
    SVR='support_vector'
    LGBM='lightgbm'

#run predction at endpoint from the FastAPI app object
@router.post("/model_deploy/{model_type}",
             response_model= TemperaturePrediction)
async def predict(request: Request,model_type: ModelType,
                  payload: TemperaturePredictionPayload,
             current_user=Depends(get_current_user)) -> TemperaturePrediction:

    if model_type==ModelType.RF:
        model = request.app.state.model_rf
    elif model_type==ModelType.SVR:
        model = request.app.state.model_svr
    else:
        model = request.app.state.model_lgbm
    prediction: TemperaturePrediction = model.predict(payload)
    return prediction


"""myresume URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include
from django.contrib.auth import views
from myapp import views

urlpatterns = [
    url(r'^$',views.index,name='index'),
    url(r'^admin/', admin.site.urls),
    # url(r'^myapp/',include('myapp.urls')),
    url(r'^about/',views.about,name='about'),
    url(r'^profile_picture/',views.profile_picture,name='profile_picture'),
    url(r'^education/',views.education,name='education'),
    url(r'^technical_skills/',views.technical_skills,name='technical_skills'),
    url(r'^research/',views.research,name='research'),
    url(r'^strengths/',views.strengths,name='strengths'),
    url(r'^certifications_workshops/',views.certifications_workshops,name='certifications_workshops'),
    url(r'^project_experience/',views.project_experience,name='project_experience'),
    url(r'^achievements/',views.achievements,name='achievements'),
    url(r'^extracurricular_activities/',views.extracurricular_activities,name='extracurricular_activities'),
    url(r'^hobbies/',views.hobbies,name='hobbies'),
    url(r'^personal_details/',views.personal_details,name='personal_details'),

]


import os, config, time, requests, sys, json, logging, torch, utils
import numpy as np
from PIL import Image
import pandas as pd
import argparse
#from utils import LoadDataset
from requests.exceptions import HTTPError, ConnectTimeout
from glob import glob
#from load_dataset import load_test_caltech_256
from torchvision.utils import save_image

def load_dataset(args, dataset_path, savePath_idx):
	return load_test_caltech_256(config.input_dim, dataset_path, args.split_ratio, savePath_idx, config.model_id_dict[args.model_name])

def main(args):
	#Number of side branches that exists in the early-exit DNNs
	#nr_branches_model_list = np.arange(config.nr_min_branches, config.nr_max_branches+1)

	p_tar_list = [0.8, 0.81, 0.82, 0.83, 0.84, 0.85]
	dataset_path = config.dataset_path_dict["caltech256"]

	logPath = os.path.join(config.DIR_NAME, "logTest_%s.log"%(args.model_name))

	logging.basicConfig(level=logging.DEBUG, filename=logPath, filemode="a+", format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')

	#This line defines the number of side branches processed at the edge
	nr_branch_edge = np.arange(3, config.n_branches+1)

	logging.debug("Sending Configuration")

	utils.sendModelConf(config.urlConfModelEdge, config.n_branches, args.dataset_name, args.model_name, args.location)
	#utils.sendModelConf(config.urlConfModelCloud, config.n_branches, args.dataset_name, args.model_name, args.location)

	logging.debug("Finish Configuration")

	#test_loader = load_dataset(args, dataset_path, save_indices_path)
	#inferenceTimeExperiment(test_loader, p_tar_list, nr_branch_edge, logPath)

if (__name__ == "__main__"):
	# Input Arguments. Hyperparameters configuration
	parser = argparse.ArgumentParser(description="Evaluating early-exits DNNs perfomance in terms of missed deadline probability.")

	parser.add_argument('--dataset_name', type=str, default=config.dataset_name,
		choices=["caltech256"], help='Dataset name (default: Caltech-256)')

	parser.add_argument('--model_name', type=str, default=config.model_name,
		choices=["mobilenet", "resnet18", "resnet152", "vgg16"], help='DNN model name (default: MobileNet)')

	parser.add_argument('--split_ratio', type=float, default=config.split_ratio, help='Split Ratio')

	parser.add_argument('--location', type=str, choices=["ohio", "sp"], help='Location of Cloud Server')

	args = parser.parse_args()

	main(args)


from django.apps import apps
from django.core.management.base import BaseCommand, CommandParser
from impossible_travel.models import Alert, Config, Login, TaskSettings, User

class Command(BaseCommand):
    help = "Clear data on the models"

    def add_arguments(self, parser: CommandParser) -> None:
        parser.add_argument("--model", nargs="?", type=str, help="Model to clear")
        return super().add_arguments(parser)

    def handle(self, *args, **options):
        if options["model"]:
            if options["model"] in ["Config", "config"]:
                choice = input(self.stdout.write("Are you sure you want to delete the Configurations model? [y/N]"))
                if choice in ["y", "Y"]:
                    Config.objects.all().delete()
                    self.stdout.write(self.style.SUCCESS("Config model is correctly emptied"))
                else:
                    self.stdout.write("Config model isn't emptied")
            else:
                try:
                    Model = apps.get_model("impossible_travel", options["model"].capitalize())
                    Model.objects.all().delete()
                    self.stdout.write(self.style.SUCCESS(f"{Model} model is correctly emptied"))
                except LookupError:
                    self.stdout.write(self.style.ERROR(f"{options['model']} model doesn't exist"))
        else:
            Alert.objects.all().delete()
            Login.objects.all().delete()
            User.objects.all().delete()
            TaskSettings.objects.all().delete()
            self.stdout.write(self.style.SUCCESS("All the models have been emptied, expect the Config model"))


#!/usr/bin/env python
#  test3_kinesis_data_put.py

# https://docs.aws.amazon.com/streams/latest/dev/get-started-exercise.html

import json
import boto3
import random
import datetime

kinesis = boto3.client('kinesis')

def getReferrer():
    data = {}
    now = datetime.datetime.now()
    str_now = now.isoformat()
    data['EVENT_TIME'] = str_now
    data['TICKER'] = random.choice(['AAPL', 'AMZN', 'MSFT', 'INTC', 'TBV'])
    price = random.random() * 100
    data['PRICE'] = round(price, 2)
    return data

while True:
    data = json.dumps(getReferrer())
    print(data)
    kinesis.put_record(
        StreamName="ExampleInputStream",
        Data=data,
        PartitionKey="partitionkey")


import logging

from rtctools.simulation.csv_mixin import CSVMixin
from rtctools.simulation.simulation_problem import SimulationProblem
from rtctools.util import run_simulation_problem

logger = logging.getLogger("rtctools")

class Example(CSVMixin, SimulationProblem):
    """
    A basic example for introducing users to RTC-Tools 2 Simulation
    """

    def initialize(self):
        self.set_var('P_control', 0.0)
        super().initialize()

    # Min and Max flow rate that the storage is capable of releasing
    min_release, max_release = 0.0, 8.0  # m^3/s

    # Here is an example of overriding the update() method to show how control
    # can be build into the python script
    def update(self, dt):

        # Get the time step
        if dt < 0:
            dt = self.get_time_step()

        # Get relevant model variables
        volume = self.get_var('storage.V')
        target = self.get_var('storage_V_target')

        # Calucate error in storage.V
        error = target - volume

        # Calculate the desired control
        control = -error / dt

        # Get the closest feasible setting.
        bounded_control = min(max(control, self.min_release), self.max_release)

        # Set the control variable as the control for the next step of the simulation
        self.set_var('P_control', bounded_control)

        # Call the super class so that everything else continues as normal
        super().update(dt)

# Run
run_simulation_problem(Example, log_level=logging.DEBUG)


import os
import jinja2
import webapp2

JINJA_ENVIRONMENT = jinja2.Environment(
	loader = jinja2.FileSystemLoader(os.path.dirname(__file__) + "/templates"))

class MainHandler(webapp2.RequestHandler):
	def get(self):
		template = JINJA_ENVIRONMENT.get_template('index.html')
		self.response.out.write(template)

app = webapp2.WSGIApplication([
('/', MainHandler),
], debug=True)


import datetime
import os

import xlrd  # Reading an excel file using Python

def get_json_form_xlsx_file(filename):
    # print(filename)
    directory = 'uploaded-files'
    json = []
    wb = xlrd.open_workbook(os.path.join(directory, filename))
    sheet = wb.sheet_by_index(0)
    for i in range(3, sheet.nrows):
        # print(sheet.row_values(i))
        if sheet.row_values(i)[0] != '':
            tuple_date = xlrd.xldate_as_tuple(int(sheet.row_values(i)[0]), wb.datemode)
            date = str(tuple_date[0]) + '-' + str(tuple_date[1]) + '-' + str(tuple_date[2])
            reason = ' '.join(sheet.row_values(i)[3].split())
            amount = sheet.row_values(i)[4]
            credit = ''
            debit = ''
            if amount > 0:
                credit = abs(amount)
            else:
                debit = abs(amount)
            json.append({'date': date, 'reason': reason, 'credit': credit, 'debit': debit})

    return json


# to run this project: main.py
# made by Thiago M Nóbrega

import matplotlib.pyplot as plt
from numpy import sqrt
import os

def Circle():
    """ This function was an attempt to solve the game using logic
    """
    amount = []
    x = -2
    while x <= 2:

        y = sqrt(4-(x**2))
        print("x: ", x)
        print("y: ", y)
        plt.plot(x,y,"ro")
        # x = x + 0.001
        x = x + 0.001
        amount.append(x)

    x = -2
    while x <= 2:

        y = -sqrt(4-(x**2))
        print("x: ", x)
        print("y: ", y)
        plt.plot(x,y,"ro")
        # x = x + 0.001
        x = x + 0.001
        amount.append(x)

    plt.show()
    print("points: ", len(amount))
    print("lines: ", (len(amount))/2)

    print("press 1 to go back to main menu: ")
    while True:
        try:
            x = int(input('Your choice: '))
            break
        except:
            print("Invalid option. Please try again.")

    if x == 1:
        os.system('cls||clear')
        from main import main
        main()
    else:
        print("sorry, not an option")


# 1. Imported Modules
# -------------------
import openpyxl

def ImportGameExcel(gameNumber, file_name):
    wb = openpyxl.load_workbook(file_name)
    ws = wb.active
    list1 = []
    number = None
    for row in ws.rows:
        if row[2].value == gameNumber:
            for cell in row:
                if cell.row not in list1:
                    list1.append((cell.row))
                    number = list1[0]
    if number is not None:
        start_row = number-3
        max_row1 = start_row + 13
        list2 = []
        list3 = []
        for i in range(start_row, max_row1):

            cell_obj1 = ws.cell(row = i, column = 2)
            cell_obj2 = ws.cell(row = i, column = 3)
            if cell_obj1.value == None:
                break
            list2.append(cell_obj1.value)
            list3.append(cell_obj2.value)
        res = {}
        for key in list2:
            for value in list3:
                res[key] = value
                list3.remove(value)
                break
        whiteMoves = []
        blackMoves = []
        for i in range(max_row1, ws.max_row):
            cell_obj1 = ws.cell(row = i, column = 3)
            cell_obj2 = ws.cell(row = i, column = 4)
            if cell_obj1.value == None or cell_obj2.value == None:
                break
            whiteMoves.append(cell_obj1.value)
            blackMoves.append(cell_obj2.value)
        allMoves = [None]*(len(whiteMoves)+len(blackMoves))
        allMoves[::2] = whiteMoves
        allMoves[1::2] = blackMoves
        if 'White' in allMoves:
            allMoves.remove('White')
        if 'Black' in allMoves:
            allMoves.remove('Black')
        list4 = []
        list4.append(res)
        list4.append(allMoves)
        return list4
    else:
        print('Game not found')

def ExportGameExcel(game, file_name):
    wb = openpyxl.load_workbook(file_name)
    ws = wb.active

    gameMeta = game[0]
    gameMoves = game[1]
    gameNumber = gameMeta['Round']
    gameNumbers = [row[2].value for row in ws.rows if row[2].value is not None]

    if gameNumber in gameNumbers:
        print(f"Round '{gameNumber}' already exists in the file")
    else:
        start_row = ws.max_row + 2
        for i, (key, value) in enumerate(gameMeta.items()):
            ws.cell(row=start_row + i, column=2).value = key
            ws.cell(row=start_row + i, column=3).value = value

        # Determine the row number to start writing at (one row after the last row with data)
        start_row = ws.max_row + 2
        ws.cell(row=start_row, column=2).value = 'Turn'
        ws.cell(row=start_row, column=3).value = 'white'
        ws.cell(row=start_row, column=4).value = 'Black'
        start_row = ws.max_row + 1
        # Loop through the list of values and write them to the Excel file
        for i in range(0, len(gameMoves), 2):
            ws.cell(row=start_row, column=2).value = i//2 + 1
            ws.cell(row=start_row, column=3).value = gameMoves[i]
            ws.cell(row=start_row, column=4).value = gameMoves[i+1] if i+1 < len(gameMoves) else ''
            # Increment the row number for the next iteration
            start_row += 1
        # Save the changes to the Excel file
        wb.save(file_name)


from typing import Callable

from fastapi import (
    FastAPI,
    Request,
)
from fastapi.middleware.cors import CORSMiddleware
from fastapi_jwt_auth.exceptions import AuthJWTException
from fastapi_pagination import add_pagination

from core.apps.localization.middlewares import localization_middleware
from core.common.config import config
from core.common.exception_handlers import authjwt_exception_handler

API_V1_PREFIX = '/api/v1/'

class AppFactory:
    @classmethod
    def add_middleware(
        cls,
        app: FastAPI,
        protocol: str,
        middleware: Callable[[Request, Callable], None],
    ):
        app.middleware(protocol)(middleware)

    @classmethod
    def create_app(cls) -> FastAPI:
        """Returns the FastAPI app with instantiated DB."""
        app = FastAPI(
            debug=config.DEBUG_MODE,
            title='Classroom API',
            openapi_url='/api/openapi.json',
            docs_url='/api/docs',
        )

        app.add_middleware(
            CORSMiddleware,
            allow_origins=config.ALLOWED_CORS_ORIGINS,
            allow_credentials=True,
            allow_methods=['*'],
            allow_headers=['*'],
        )
        cls._register_views(app)
        cls.add_middleware(app, 'http', localization_middleware)

        app.exception_handler(AuthJWTException)(authjwt_exception_handler)

        add_pagination(app)
        return app

    @classmethod
    def _register_views(cls, app: FastAPI):
        from core.apps.attachments.views import router as attachment_router
        from core.apps.chat.views import router as chat_router
        from core.apps.classroom.views import router as classroom_router
        from core.apps.localization.views import router as localization_router
        from core.apps.users.views import router as user_router

        app.include_router(
            localization_router,
            prefix=''.join([API_V1_PREFIX, 'localization']),
        )
        app.include_router(
            user_router,
            prefix=''.join([API_V1_PREFIX, 'auth/user']),
        )
        app.include_router(
            classroom_router,
            prefix=''.join([API_V1_PREFIX, 'classroom']),
        )
        app.include_router(
            attachment_router,
            prefix=''.join([API_V1_PREFIX, 'attachments']),
        )
        app.include_router(
            chat_router,
            prefix=''.join([API_V1_PREFIX, 'chat']),
        )


import pinecone

from api.abc import MemoryProviderSingleton
from api.utils import get_ada_embedding

from api.constants import PINECONE_API_KEY, PINECONE_API_ENVIRONMENT, PINECONE_TABLE_NAME, PINECONE_POD_TYPE, EMBED_DIM
from loguru import logger

from uuid import uuid4

class PineconeMemory(MemoryProviderSingleton):
    def __init__(self):
        pinecone_api_key = PINECONE_API_KEY
        pinecone_region = PINECONE_API_ENVIRONMENT
        pinecone.init(api_key=pinecone_api_key, environment=pinecone_region)
        dimension = EMBED_DIM
        metric = "cosine"
        pod_type = PINECONE_POD_TYPE
        table_name = PINECONE_TABLE_NAME

        try:
            pinecone.whoami()
        except Exception as e:
            logger.error("FAILED TO CONNECT TO PINECONE")
            exit(1)

        indexes = pinecone.list_indexes()
        logger.info(f"existing indexes {indexes}")
        try :
            if table_name not in indexes:
                pinecone.create_index(table_name, dimension=dimension, metric=metric, pod_type=pod_type)
        except Exception as e:
            logger.error("FAILED TO CREATE PINECONE INDEX", e)
        self.index = pinecone.Index(table_name)

    def add(self, data, user):
        vector = get_ada_embedding(data)
        id = uuid4()
        self.index.upsert([(str(id), vector, {"raw_text": data, "user": user})], namespace=None)
        _text = f"Inserting data into memory at index: {id}:\n data: {data}"
        return _text

    def get(self, data):
        return self.get_relevant(data, 1)

    def clear(self):
        self.index.delete(deleteAll=True)
        return "Obliviated"

    def get_relevant(self, data, user, num_relevant=5):
        """
        Returns all the data in the memory that is relevant to the given data.
        :param data: The data to compare to.
        :param num_relevant: The number of relevant data to return. Defaults to 5
        """
        query_embedding = get_ada_embedding(data)
        results = self.index.query(query_embedding, top_k=num_relevant, include_metadata=True, filter={"user":user})
        sorted_results = sorted(results.matches, key=lambda x: x.score)
        return [str(item['metadata']["raw_text"]) for item in sorted_results]

    def get_stats(self):
        return self.index.describe_index_stats()

memory = PineconeMemory()


import argparse
import asyncio
import datetime
import json
import logging
import re

import websockets
from pygtail import Pygtail
from websockets import WebSocketServerProtocol

INTERVAL = 1
logging.basicConfig(level=logging.INFO)

class Server:
    def __init__(self, log_file, interface, port):
        self.log_file = log_file
        self.interface = interface
        self.port = port
        self.clients = set()
        self.ON_LINE = set()

    async def register(self, ws: WebSocketServerProtocol) -> None:
        self.clients.add(ws)
        logging.info(f'{ws.remote_address} connects.')
        jobj = json.dumps(list(self.ON_LINE))
        await ws.send(str(jobj))

    async def unregister(self, ws: WebSocketServerProtocol) -> None:
        self.clients.remove(ws)
        logging.info(f'{ws.remote_address} disconnects.')

    async def send_to_clients(self, message: str) -> None:
        if self.clients:
            await asyncio.wait([client.send(message) for client in self.clients])

    async def ws_handler(self, ws: WebSocketServerProtocol, url: str) -> None:
        await self.register(ws)
        try:
            await self.distribute(ws)
        except websockets.exceptions.ConnectionClosedError:
            pass
        finally:
            await self.unregister(ws)

    async def distribute(self, ws: WebSocketServerProtocol) -> None:
        async for message in ws:
            logging.info(f'I got the message: {message}')
            await self.send_to_clients(message)

    async def start(self) -> None:
        start_server = websockets.serve(self.ws_handler, self.interface, self.port)
        self.server = await start_server

    def stop(self) -> None:
        if self.server != None:
            self.server.close()

    async def monitor_log(self) -> None:
        joinedRegEx = re.compile("^.*: (.*) joined the game$")
        leftRegEx = re.compile("^.*: (.*) left the game$")
        pygtail = Pygtail(self.log_file, paranoid=True)
        while True:
            try:
                for line in pygtail:
                    x = joinedRegEx.search(line)
                    if x != None:
                        self.ON_LINE.add(x.group(1))
                    x = leftRegEx.search(line)
                    if x != None:
                        self.ON_LINE.discard(x.group(1))
                    jobj = json.dumps(list(self.ON_LINE))
                    now = datetime.datetime.now() + datetime.timedelta(hours=5)
                    print(str(jobj) + "  " + now.strftime('%H:%M:%S on %A, %B the %dth, %Y'))
                    await self.send_to_clients(str(jobj))
                await asyncio.sleep(INTERVAL)
            except OSError:
                await asyncio.sleep(INTERVAL)

ap = argparse.ArgumentParser()
ap.add_argument("-l", "--log", required=True, help="path to the log file")
ap.add_argument("-i", "--interface", default="0.0.0.0", help="network interface")
ap.add_argument("-p", "--port", default=4000, help="port to use for websocket")
args = ap.parse_args()

log_file = args.log
interface = args.interface
port = args.port
try:
    server = Server(log_file, interface, port)
    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.gather(server.start(), server.monitor_log()))
    loop.run_forever()
except KeyboardInterrupt:
    server.stop()


import random
import sys
import pygame
import numpy
from snake import Snake
from foodspawner import FoodSpawner
from fileio import FileIO

baseFramerate = 500
size = 500
fIO = FileIO()

def gameover(quitGame=False, score = 0, framerate = 0):
	pygame.quit()
	fIO.printScore(score,framerate)
	if quitGame == True:
		sys.exit(0)
	init(baseFramerate)

def userInput(snake):
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			gameover(True)
		elif event.type == pygame.KEYDOWN:
			if event.key == pygame.K_RIGHT:
				snake.changeDirTo("R")

			if event.key == pygame.K_LEFT:
				snake.changeDirTo("L")

			if event.key == pygame.K_DOWN:
				snake.changeDirTo("D")

			if event.key == pygame.K_UP:
				snake.changeDirTo("U")

def compInput(snake, foodpos):
	# Quit key event
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			gameover(True)

	moved = False

	# Avoid walls
	if snake.getDir() != "U" and snake.getDir() != "D":
		if snake.getX()+10 >= size and moved==False:
			if snake.getY() <= size/2:
				snake.changeDirTo("D")
				moved = True
			else:
				snake.changeDirTo("U")
				moved = True
		if snake.getX()-10 < 0 and moved==False:
			if snake.getY() <= size/2:
				snake.changeDirTo("D")
				moved = True
			else:
				snake.changeDirTo("U")
				moved = True
	if snake.getDir() != "L" and snake.getDir() != "R":
		if snake.getY()+10 >= size and moved==False:
			if snake.getX() <= size/2:
				snake.changeDirTo("R")
				moved = True
			else:
				snake.changeDirTo("L")
				moved = True
		if snake.getY()-10 < 0 and moved==False:
			if snake.getX() <= size/2:
				moved = True
				snake.changeDirTo("R")
			else:
				moved = True
				snake.changeDirTo("L")

	# Avoid bodyparts

	if snake.getDir() == "L" and moved==False:
		for bodyParts in snake.getBody()[1:]:
			if snake.getX()-10 == bodyParts[0] and snake.getY() == bodyParts[1] and moved==False:

				if snake.checkPos(snake.getX()-10,snake.getY()-10):
					if snake.checkPos(snake.getX(),snake.getY()+10):
						snake.changeDirTo("U")
					else:
						snake.changeDirTo("D")
				else:
					snake.changeDirTo("U")
				moved=True

	if snake.getDir() == "R" and moved==False:
		for bodyParts in snake.getBody()[1:]:
			if snake.getX()+10 == bodyParts[0] and snake.getY() == bodyParts[1]  and moved==False:
				if snake.checkPos(snake.getX()+10,snake.getY()-10):
					snake.changeDirTo("D")
				else:
					snake.changeDirTo("U")
				moved=True

	if snake.getDir() == "U" and moved==False:
		for bodyParts in snake.getBody()[1:]:
			if snake.getY()-10 == bodyParts[1] and snake.getX() == bodyParts[0]  and moved==False:
				if snake.checkPos(snake.getX()+10, snake.getY()-10):
					if snake.checkPos(snake.getX()-10,snake.getY()):
						snake.changeDirTo("R")
					else:
						snake.changeDirTo("L")
				else:
					snake.changeDirTo("R")
				moved=True
	if snake.getDir() == "D" and moved==False:
		for bodyParts in snake.getBody()[1:]:
			if snake.getY()+10 == bodyParts[1] and snake.getX() == bodyParts[0]  and moved==False:
				if snake.checkPos(snake.getX()+10, snake.getY()+10):
					snake.changeDirTo("L")
				else:
					snake.changeDirTo("R")
				moved=True

	# Look for food
	if  moved==False:
		if snake.getX() < foodpos[0] :
			snake.changeDirTo("R")
			moved = True
		elif snake.getX() > foodpos[0]:
			snake.changeDirTo("L")
			moved = True
		else:
			if snake.getY() < foodpos[1] :
				snake.changeDirTo("D")
				moved=True
			else:
				snake.changeDirTo("U")
				moved=True

def init(framerate):
	global size
	window = pygame.display.set_mode((size, size))
	pygame.display.set_caption("SNAKE")
	fps = pygame.time.Clock()

	score = 0

	snake = Snake(size)
	food = FoodSpawner(size)

	highscore = "\t Highscore: "+str(fIO.getHighScore())

	while True:
		# userInput(snake)

		foodpos = food.spawnFood()
		compInput(snake,foodpos)

		if(snake.move(foodpos) == 1):
			score += 1
			if(score%5 == 0 and score > 0):
				framerate += 1
			if(foodpos == snake.position):
    				food.setFoodOnScreen(False)

		window.fill(pygame.Color(0, 0, int(abs(numpy.sin(score)*50))))
		for pos in snake.getBody():
			pygame.draw.rect(window, pygame.Color(0, 255, 0), pygame.Rect(pos[0], pos[1], 10,10))
		pygame.draw.rect(window, pygame.Color(255, 0, 0), pygame.Rect(foodpos[0], foodpos[1], 10, 10))

		if snake.checkCollision() == 1:
			gameover(False, score, framerate)
		pygame.display.set_caption("Snake | Score:"+str(score)+highscore+"\t speed:"+str(framerate))
		pygame.display.flip()
		fps.tick(framerate)

init(baseFramerate)


import os
import pandas as pd
import numpy as np
from keras import backend as K
from keras.models import model_from_json
from keras.utils.np_utils import to_categorical
from keras.layers import Dense
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D
import tensorflow as tf
import keras.backend.tensorflow_backend as tfback
from keras.utils import plot_model
import matplotlib.pyplot as plt
# injection method to fix issue with mismatching tf and keras versions
# https://github.com/keras-team/keras/issues/13684
def _get_available_gpus():
    """Get a list of available gpu devices (formatted as strings).

    # Returns
        A list of available GPU devices.
    """
    #global _LOCAL_DEVICES
    if tfback._LOCAL_DEVICES is None:
        devices = tf.config.list_logical_devices()
        tfback._LOCAL_DEVICES = [x.name for x in devices]
    return [x for x in tfback._LOCAL_DEVICES if 'device:gpu' in x.lower()]

tfback._get_available_gpus = _get_available_gpus

K.set_image_data_format('channels_first')

print('training starting...')
print()

df = pd.read_csv(os.path.join('ml','training_data.csv'), index_col=False)
# last col is labels
col_len = len(df.columns)-1
# print(col_len)
labels = df[[str(col_len)]]
labels = np.array(labels)
unique = np.unique(labels)
# get how many unique symbols we are processing
num_classes = len(unique)
# remove label col
df.drop(df.columns[[col_len]],axis=1,inplace=True)
# number of symbols we are processing
cat=to_categorical(labels,num_classes=num_classes)

df_len = len(df)

arr = []
for i in range(df_len):
    arr.append(np.array(df[i:i+1]).reshape(1,28,28))

# create model
model = Sequential()
# 30 convolution filters, kernel size of 5x5
# input shape has a depth of 1, width and height of 28
# relu activation ignores negative values
model.add(Conv2D(30, (5, 5), input_shape=(1 , 28, 28), activation='relu'))
# half the input, summarize features
model.add(MaxPooling2D(pool_size=(2, 2)))
# 15 output filters, smaller kernel size
model.add(Conv2D(15, (3, 3), activation='relu'))
# half the input again
model.add(MaxPooling2D(pool_size=(2, 2)))
# drop 20 percent of inputs to help prevent overfitting
model.add(Dropout(0.2))
# flatten the input for the dense layer
model.add(Flatten())
# dense layer with an output of 128
model.add(Dense(128, activation='relu'))
# dense layer with an output of 50
model.add(Dense(50, activation='relu'))
# final dense layer with an output of the number of classes we have
model.add(Dense(num_classes, activation='softmax'))

model.summary()

# Compile model
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

# Fit model
history = model.fit(np.array(arr), cat, epochs=10, batch_size=200, shuffle=True, verbose=1)

#plot model
#print(history.history)
loss = history.history['loss']
accuracy = history.history['accuracy']
plt.plot(loss)
plt.plot(accuracy)
plt.legend(['loss', 'accuracy'])
plt.show()

plot_model(model, to_file='model.png', show_shapes=True, dpi=400)

model_json = model.to_json()
with open("model.json", "w") as json_file:
    json_file.write(model_json)

# serialize weights to HDF5
model.save_weights("model.h5")

print()
print('training finished...')